phala 1.0.25 → 1.0.26
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/index.js +29 -29
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
@@ -1,5 +1,5 @@
|
|
1
1
|
#!/usr/bin/env node
|
2
|
-
import{$ as Ke,L as ue,M as xe,N as Q,O as L,P as Fe,R as Me,S as Te,T as Ve,U as Ue,V as Ne,W as Re,Y as ee,Z as Le,_ as Oe,a as e,aa as ze,b as le,ba as O,c as R,d as B,e as pe,f as P,g as y,h as M,i as T,j as V,k as de,l as Ie,m as Pe,n as Ae}from"./chunk-UU6UDBBR.js";import{Command as
|
2
|
+
import{$ as Ke,L as ue,M as xe,N as Q,O as L,P as Fe,R as Me,S as Te,T as Ve,U as Ue,V as Ne,W as Re,Y as ee,Z as Le,_ as Oe,a as e,aa as ze,b as le,ba as O,c as R,d as B,e as pe,f as P,g as y,h as M,i as T,j as V,k as de,l as Ie,m as Pe,n as Ae}from"./chunk-UU6UDBBR.js";import{Command as wo}from"commander";import Be from"chalk";var Ge=Be.hex("#cdfa50"),je=Ge(`
|
3
3
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E0\u28E4\u28E4\u28E4\u28C0\u2840\u2800\u2880\u28C0\u28E4\u28E4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
4
4
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28F4\u287F\u281B\u2809\u2801\u2800\u2808\u2809\u281B\u283F\u281B\u2809\u2809\u2809\u2809\u2819\u2837\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
5
5
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u28E7\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
@@ -21,7 +21,7 @@ import{$ as Ke,L as ue,M as xe,N as Q,O as L,P as Fe,R as Me,S as Te,T as Ve,U a
|
|
21
21
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u281B\u283F\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u281F\u280B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28FE\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
22
22
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u283B\u28B6\u28E6\u28E4\u28C4\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E4\u28F4\u28F6\u283F\u281B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
23
23
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u281B\u283B\u283F\u283F\u283F\u283F\u28BF\u28FF\u28FF\u28FF\u283F\u283F\u283F\u283F\u281F\u281B\u281B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
24
|
-
`),
|
24
|
+
`),So=Ge(`
|
25
25
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E0\u28E4\u28E4\u28E4\u28C0\u2840\u2800\u2880\u28C0\u28E4\u28E4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
26
26
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28F4\u287F\u281B\u2809\u2801\u2800\u2808\u2809\u281B\u283F\u281B\u2809\u2809\u2809\u2809\u2819\u2837\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
27
27
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u28E7\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
@@ -43,30 +43,30 @@ import{$ as Ke,L as ue,M as xe,N as Q,O as L,P as Fe,R as Me,S as Te,T as Ve,U a
|
|
43
43
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u281B\u283F\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u281F\u280B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28FE\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
44
44
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u283B\u28B6\u28E6\u28E4\u28C4\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E4\u28F4\u28F6\u283F\u281B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
45
45
|
\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u281B\u283B\u283F\u283F\u283F\u283F\u28BF\u28FF\u28FF\u28FF\u283F\u283F\u283F\u283F\u281F\u281B\u281B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
|
46
|
-
`),
|
46
|
+
`),bo=Be.cyan("PHALA TEE CLOUD CLI");import{Command as rt}from"commander";import{Command as Yr}from"commander";import Jr from"prompts";var He=new Yr().name("login").description("Set the API key for authentication").argument("[api-key]","Phala Cloud API key to set").action(async o=>{try{let t;if(!o)o=(await Jr({type:"password",name:"apiKey",message:"Enter your API key:",validate:async i=>{if(i.length===0)return"API key cannot be empty";try{if(await le(i),t=await ue(i),!t.username)throw await B(),new Error("Invalid API key")}catch{throw new Error("Invalid API key")}return!0}})).apiKey;else if(await le(o),t=await ue(o),!t.username)throw await B(),new Error("Invalid API key");e.success(`Welcome ${t.username}! API key validated and saved successfully`),e.break(),e.info(`Open in Web UI at ${y}/dashboard/`)}catch(t){e.error(`Failed to set API key: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Zr}from"commander";var qe=new Zr().name("logout").description("Remove the stored API key").action(async()=>{try{await B(),e.success("API key removed successfully")}catch(o){e.error(`Failed to remove API key: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{createClient as Xr}from"@phala/cloud";import{Command as Qr}from"commander";import{safeGetCurrentUser as et}from"@phala/cloud";var We=new Qr().name("status").description("Check authentication status").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(async o=>{try{let t=o.debug||process.env.DEBUG?.toLowerCase()==="true",r=R();if(!r){console.log('Not authenticated. Please set an API key with "phala auth login"');return}t&&e.debug(`Using API key: ${r.substring(0,5)}...`);try{let i=Xr({apiKey:r}),n=await et(i);if(!n.success){e.error("Failed to get user information"),n.error&&e.error(`Error: ${n.error.message}`);return}let a=n.data,s=process.env.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.network/api/v1";if(o.json){console.log(JSON.stringify({apiUrl:s,username:a.username,team_name:a.team_name},null,2));return}console.log(`Integrated API: ${s}`),console.log(`Logged in as: ${a.username}`),console.log(`Current Workspace: ${a.team_name}`)}catch(i){console.error("Authentication failed. Your API key may be invalid or expired."),console.log('Please set a new API key with "phala auth login"'),t&&e.debug(`Error details: ${i instanceof Error?i.message:String(i)}`)}}catch(t){e.error(`Failed to check authentication status: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});var Ye=new rt().name("auth").description("Authenticate with Phala Cloud").addCommand(He).addCommand(qe).addCommand(We);import{Command as vt}from"commander";import{Command as dt}from"commander";import{execa as st}from"execa";import x from"node:fs";import H from"node:path";import at from"handlebars";import{exec as ct,spawn as mt}from"node:child_process";import{promisify as lt}from"node:util";import er from"node:os";import tt from"inquirer";import fe from"node:fs";import ge from"node:path";function U(o,t=process.cwd()){let r=ge.resolve(t,o);if(!fe.existsSync(r))throw new Error(`File not found at ${r}`);return!0}async function D(o,t,r="file",i=process.cwd()){return(await tt.prompt([{type:"input",name:r,message:o,default:t,validate:a=>{let s=ge.resolve(i,a);return fe.existsSync(s)?!0:`File not found at ${s}`}}]))[r]}function K(o,t){for(let r of o){let i=ge.join(process.cwd(),r);if(fe.existsSync(i))return t?e.info(t.replace("{path}",i)):e.info(`File detected: ${i}`),r}}import*as h from"node:fs";import*as b from"node:path";import*as I from"node:os";import{execSync as A,spawn as ot}from"node:child_process";import*as he from"node:net";var k={version:"0.5.3",baseUrl:"https://github.com/Dstack-TEE/dstack/releases/download/v0.5.3",installDir:b.join(I.homedir(),".phala-cloud","simulator"),defaultLogPath:b.join(I.homedir(),".phala-cloud","logs","dstack-simulator.log"),platforms:{darwin:{filename:"dstack-simulator-0.5.3-aarch64-apple-darwin.tgz",extractedFolder:"0.5.3",socketPath:b.join(I.homedir(),".phala-cloud","simulator","0.5.3","dstack.sock")},linux:{filename:"dstack-simulator-0.5.3-x86_64-linux-musl.tgz",extractedFolder:"0.5.3",socketPath:b.join(I.homedir(),".phala-cloud","simulator","0.5.3","dstack.sock")},win32:{filename:"dstack-simulator-0.5.3-x86_64-pc-windows-msvc.tgz",extractedFolder:"dstack-simulator-0.5.3-x86_64-pc-windows-msvc",socketPath:"127.0.0.1:8090"}}};function Je(){try{if(!h.existsSync(k.installDir))return!1;let o=I.platform();if(!k.platforms[o])throw new Error(`Unsupported platform: ${o}`);let t=b.join(k.installDir,k.platforms[o].extractedFolder);if(!h.existsSync(t))return!1;let i=b.join(t,o==="win32"?"dstack-simulator.exe":"dstack-simulator");return h.existsSync(i)}catch(o){return e.error("Error checking if simulator is installed:",o),!1}}function G(){let o=I.platform();if(!k.platforms[o])throw new Error(`Unsupported platform: ${o}. Only darwin, linux, and win32 are supported.`);return o}async function Ze(o){let t=r=>{e.info(r),o&&o(r)};try{let r=G(),i=k.platforms[r];if(r==="win32"){try{A("tar --version",{stdio:"ignore"})}catch{throw new Error("Windows 10 build 17063 or later is required (includes tar command). Please update your Windows version.")}throw new Error("Windows platform is currently not supported. Support will be added in a future release.")}h.existsSync(k.installDir)||(e.info(`Creating installation directory at ${k.installDir}`),h.mkdirSync(k.installDir,{recursive:!0})),process.chdir(k.installDir);let n=`${k.baseUrl}/${i.filename}`;e.info(`Downloading simulator from ${n}`),A(`wget ${n}`,{stdio:"inherit"});let a=b.join(k.installDir,i.extractedFolder);h.existsSync(a)||h.mkdirSync(a,{recursive:!0}),e.info(`Extracting ${i.filename} to ${a}`);let s=`tar -xvf "${i.filename}" -C "${a}" --strip-components=1`;e.debug(`Running: ${s}`);try{A(s,{stdio:"inherit"}),h.unlinkSync(i.filename)}catch(m){throw e.error(`Failed to extract ${i.filename}:`,m),new Error("Failed to extract simulator archive. Make sure you have sufficient permissions and disk space.")}e.success("Simulator installation completed successfully")}catch(r){throw e.error("Error installing simulator:",r),new Error(`Failed to install simulator: ${r}`)}}var ye=()=>b.join(I.tmpdir(),"dstack-simulator.pid");function it(o){return Buffer.byteLength(o,"utf8")>104}function re(){try{let o=ye();if(h.existsSync(o)){let t=parseInt(h.readFileSync(o,"utf-8").trim(),10);try{return process.kill(t,0),t}catch{h.unlinkSync(o)}}return null}catch(o){return e.warn("Error checking simulator PID:",o),null}}function nt(o,t){try{let r=ye();t&&e.info(`Saving simulator PID ${o} to: ${r}`),h.writeFileSync(r,o.toString(),"utf-8")}catch(r){e.warn("Failed to save simulator PID:",r)}}async function Xe(o={}){try{let t=G(),r=k.platforms[t],i=b.join(k.installDir,r.extractedFolder),n=re();if(n)throw new Error(`Simulator is already running with PID: ${n}`);if(t!=="win32"&&it(r.socketPath))throw new Error(`Socket path is too long (${r.socketPath.length} chars, max 104): ${r.socketPath}`);if(t!=="win32"&&h.existsSync(r.socketPath)){e.warn(`Removing existing socket file: ${r.socketPath}`);try{h.unlinkSync(r.socketPath)}catch(c){e.warn(`Failed to remove existing socket file: ${c}`)}}process.chdir(i);let a=t==="win32"?"dstack-simulator.exe":"./dstack-simulator";o.verbose&&t!=="win32"&&e.info(`Using socket path: ${r.socketPath}`);let s={background:o.background??!0,logToFile:o.logToFile??!0,logFilePath:o.logFilePath??k.defaultLogPath};if(s.logToFile){let c=b.dirname(s.logFilePath);h.existsSync(c)||h.mkdirSync(c,{recursive:!0}),o.verbose&&e.info(`Simulator logs will be written to: ${s.logFilePath}`)}o.verbose&&e.info(`Starting simulator with: ${a}`);let m=s.logToFile?["ignore",h.openSync(s.logFilePath,"a"),h.openSync(s.logFilePath,"a")]:"inherit",l=ot(a,[],{stdio:m,shell:t==="win32",detached:s.background});if(s.logToFile&&Array.isArray(m)&&(typeof m[1]=="number"&&h.closeSync(m[1]),typeof m[2]=="number"&&h.closeSync(m[2])),s.logToFile){let p=`
|
47
47
|
=== Simulator started at ${new Date().toISOString()} ===
|
48
48
|
Command: ${a}
|
49
49
|
|
50
|
-
`;h.appendFileSync(s.logFilePath,
|
51
|
-
`);
|
52
|
-
Operation completed. Full log available at: ${l}`),a()):s(new Error(`Process exited with code ${
|
53
|
-
`).filter(
|
54
|
-
`).filter(a=>a&&!a.includes("<none>")).filter(a=>a.includes(`${i}/`)).map(a=>({imageName:a}))}catch(
|
50
|
+
`;h.appendFileSync(s.logFilePath,p)}return l.pid&&nt(l.pid,o.verbose),s.background&&(l.unref(),o.verbose&&e.success("Simulator is running in the background")),await ve(),l}catch(t){throw e.error("Error running simulator:",t),new Error(`Failed to run simulator: ${t}`)}}async function j(){try{let o=G(),t=k.platforms[o];if(o==="darwin"||o==="linux"){let r=t.socketPath;return h.existsSync(r)?new Promise(i=>{let n=he.createConnection({path:r}).on("connect",()=>{n.end(),i(!0)}).on("error",()=>{i(!1)});setTimeout(()=>{n.end(),i(!1)},1e3)}):!1}if(o==="win32"){let r="127.0.0.1";return new Promise(n=>{let a=he.createConnection({host:r,port:8090}).on("connect",()=>{a.end(),n(!0)}).on("error",()=>{n(!1)});setTimeout(()=>{a.end(),n(!1)},1e3)})}return!1}catch(o){return e.error("Error checking if simulator is running:",o),!1}}async function Qe(){try{let o=re();if(!await j()&&!o)return e.info("Simulator is not running"),!0;let r=G(),i=!1;if(r==="win32")try{o?(e.info(`Stopping simulator process (PID: ${o})...`),process.kill(o,"SIGTERM")):A("taskkill /F /IM dstack-simulator.exe",{stdio:"ignore"}),i=!0}catch(a){if(a.code!=="ESRCH")return e.error("Failed to stop simulator:",a),!1;i=!0}else try{o?(e.info(`Stopping simulator process (PID: ${o})...`),process.kill(o,"SIGTERM")):A("pkill -f dstack-simulator",{stdio:"ignore"}),i=!0}catch(a){if(a.code!=="ESRCH")return e.error("Failed to stop simulator:",a),!1;i=!0}let n=ye();if(h.existsSync(n))try{h.unlinkSync(n)}catch(a){e.warn("Failed to remove PID file:",a)}return await N(),i&&e.success("Simulator stopped successfully"),i}catch(o){return e.error("Error stopping simulator:",o),!1}}function te(){let o=G(),t=k.platforms[o];return o==="win32"?"http://127.0.0.1:8090":`${t.socketPath||"/tmp/dstack.sock"}`}async function ve(o){try{let t=te(),r=o||t;await A(`export DSTACK_SIMULATOR_ENDPOINT=${r}`);let i=r.replace(/dstack\.sock$/,"tappd.sock");return await A(`export TAPPD_SIMULATOR_ENDPOINT=${i}`),e.success("Setting environment for current process..."),e.success(` DSTACK_SIMULATOR_ENDPOINT=${r}`),e.success(` TAPPD_SIMULATOR_ENDPOINT=${i}`),r}catch(t){throw e.error("Error setting simulator endpoint environment variable:",t),new Error(`Failed to set simulator endpoint: ${t}`)}}async function N(){try{return await A("unset DSTACK_SIMULATOR_ENDPOINT"),await A("unset TAPPD_SIMULATOR_ENDPOINT"),e.debug("Deleted simulator endpoint environment variables from current process"),!0}catch(o){return e.warn("Error while unsetting simulator endpoint environment variables:",o),!1}}var q=lt(ct),rr=".phala-cloud/logs",pt=".phala-cloud/compose",tr=10,E=class{username;image;registry;constructor(t,r,i){this.image=t,this.username=r||"",this.registry=i||""}ensureLogsDir(){let t=H.resolve(rr);x.existsSync(t)||x.mkdirSync(t,{recursive:!0})}getLogFilePath(t,r){let i=new Date().toISOString().replace(/[:.]/g,"-");return H.resolve(rr,`${r||this.image}-${t}-${i}.log`)}getSystemArchitecture(){let t=er.arch();switch(t){case"arm":case"arm64":return"arm64";case"x64":return"amd64";default:return t}}spawnProcess(t,r,i,n){return new Promise((a,s)=>{let m=mt(t,r);this.ensureLogsDir();let l=this.getLogFilePath(i,n),c=x.createWriteStream(l,{flags:"a"}),p=[],f=(u,g=!1)=>{let v=u.toString().split(`
|
51
|
+
`);c.write(u);for(let d of v)if(d.trim()){p.push(d),p.length>tr&&p.shift(),console.clear(),console.log(`Latest ${tr} lines (full log at ${l}):`),console.log("-".repeat(50));for(let w of p)g?console.error(w):console.log(w)}};m.stdout.on("data",u=>f(u)),m.stderr.on("data",u=>f(u,!0)),m.on("close",u=>{c.end(),u===0?(console.log(`
|
52
|
+
Operation completed. Full log available at: ${l}`),a()):s(new Error(`Process exited with code ${u}. Check log file: ${l}`))}),m.on("error",u=>{c.end(),s(u)})})}setCredentials(t,r){this.username=t,r&&(this.registry=r)}async buildImage(t,r){try{let i=this.getSystemArchitecture(),n=`${this.username}/${this.image}:${r}`,a=e.startSpinner(`Building Docker image ${this.username}/${this.image}:${r}`);U(t);let s=["build","-t",n,"-f",t];return i==="arm64"&&(console.log("Detected arm64 architecture, using --platform linux/amd64"),s.push("--platform","linux/amd64")),s.push("."),await this.spawnProcess("docker",s,"build",this.image),a.stop(!0,`Docker image ${n} built successfully`),!0}catch(i){return e.error(`Failed to build Docker image: ${i instanceof Error?i.message:String(i)}`),!1}}async pushImage(t){try{let r=e.startSpinner(`Pushing Docker image ${t} to Docker Hub`);if(!await P())throw r.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let n=t;return console.log(`Pushing image ${n} to Docker Hub...`),await this.spawnProcess("docker",["push",n],"push",t.replace(/.*\/+([\w-]+):.*$/g,"$1")),r.stop(!0,`Docker image ${n} pushed successfully`),!0}catch(r){return e.error(`Failed to push Docker image: ${r instanceof Error?r.message:String(r)}`),!1}}async login(t,r,i){try{let n=e.startSpinner(`Logging in to Docker Hub as ${t}`);if(await this.checkLogin())return n.stop(!0,"Already logged in to Docker Hub"),this.setCredentials(t,i),!0;if(!r)throw n.stop(!1),new Error("Password is required for Docker login");try{await st("docker",["login",...i?[i]:[],"-u",t,"--password-stdin"],{input:r,timeout:1e4})}catch(s){throw s.timedOut?(n.stop(!1),new Error("Docker login timed out. Please check your credentials and try again.")):s}return n.stop(!0,"Logged in to Docker Hub successfully"),this.setCredentials(t,i),!0}catch(n){return e.error(`Failed to login to Docker Hub: ${n instanceof Error?n.message:String(n)}`),!1}}async checkLogin(){try{let t=er.homedir(),r=H.join(t,".docker","config.json");if(!x.existsSync(r))return!1;let i=JSON.parse(x.readFileSync(r,"utf-8"));return!!(i?.auths&&Object.keys(i.auths).length>0)}catch(t){return e.debug(`Docker login check failed: ${t instanceof Error?t.message:String(t)}`),!1}}async buildComposeFile(t,r,i){if(!this.username)throw new Error("Docker Hub username is required for building compose file");let n=i==="eliza"?Ie:Pe,a=Ae.parse({template:n}),s=H.resolve(pt);x.existsSync(s)||(e.info(`Creating directory: ${s}`),x.mkdirSync(s,{recursive:!0}));let m=[];r&&(m=x.readFileSync(r,"utf-8").split(`
|
53
|
+
`).filter(g=>g&&!g.startsWith("#")).map(g=>{let v=g.indexOf("#");return v>0&&(g=g.substring(0,v).trim()),g.trim()}).filter(g=>g.includes("=")).map(g=>{let[v,d]=g.split("=",2),w=v.trim();return(d?d.trim():"")===""?null:`${w}=${w}`}).filter(Boolean));let l=t,p=at.compile(a.template,{noEscape:!0})({imageName:l,envVars:m.map(u=>u.replace(/=.*/,`=\${${u.split("=")[0]}}`))}),f=H.join(s,`${t.replace(/.*\/+([\w-]+):.*$/g,"$1")}-tee-compose.yaml`);return x.writeFileSync(f,p),e.success(`Backup of docker compose file created at: ${f}`),f}async runComposeLocally(t,r){try{let i=e.startSpinner(`Running Docker Compose file at ${t}`);U(t);let n=["-f",t,"up","-d"];return r&&(U(r),n.splice(2,0,"--env-file",r)),await q(`docker compose ${n.join(" ")}`),i.stop(!0,"Docker Compose file running successfully"),!0}catch(i){return e.error(`Failed to run Docker Compose file: ${i instanceof Error?i.message:String(i)}`),!1}}async runSimulator(t,r){try{e.info(`Running TEE simulator with image ${t}`),e.info("Pulling latest simulator image..."),await q(`docker pull ${t}`),e.info("Starting simulator in background...");let{stdout:i}=await q(`docker run -d --name tee-simulator --rm -p ${r}:${r} ${t}`),n=i.trim();return e.success(`TEE simulator running successfully. Container ID: ${n}`),e.break(),e.break(),e.info("Useful commands:"),e.info(`- View logs: docker logs -f ${n}`),e.info(`- Stop simulator: docker stop ${n}`),ve(`http://localhost:${r}`),!0}catch(i){return e.error(`Failed to run TEE simulator: ${i instanceof Error?i.message:String(i)}`),!1}}async stopSimulator(){try{let t=e.startSpinner("Stopping TEE simulator...");return await q("docker stop tee-simulator"),await N(),t.stop(!0,"TEE simulator stopped successfully"),!0}catch(t){return e.error(`Failed to stop TEE simulator: ${t instanceof Error?t.message:String(t)}`),!1}}static async listLocalImages(){try{let{stdout:t}=await q('docker images --format "{{.Repository}}:{{.Tag}}"'),i=(await P())?.username;return t.split(`
|
54
|
+
`).filter(a=>a&&!a.includes("<none>")).filter(a=>a.includes(`${i}/`)).map(a=>({imageName:a}))}catch(t){return e.error(`Failed to list local Docker images: ${t instanceof Error?t.message:String(t)}`),[]}}};import or from"prompts";var ir=new dt().name("login").description("Login to Docker Hub").option("-u, --username <username>","Docker Hub username").option("-p, --password <password>","Docker Hub password").option("-r, --registry <registry>","Docker registry URL").action(async o=>{try{let t=o.username,r=o.password,i=o.registry;if(!t){e.info("First we need your Docker Hub username to check if you are already logged in.");let m=await or({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:l=>l.length>0?!0:"Username cannot be empty"});m.username||(e.error("Username is required"),process.exit(1)),t=m.username}let n=new E("",t,i);if(await n.login(t)){e.success(`${t} is logged in to Docker Hub`),await pe({username:t,registry:i||null});return}if(!r){let m=await or({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:l=>l.length>0?!0:"Password cannot be empty"});m.password||(e.error("Password is required"),process.exit(1)),r=m.password}await n.login(t,r,i)||(e.error("Failed to login to Docker Hub"),process.exit(1)),await pe({username:t,registry:i||null}),e.success("Logged in to Docker Hub successfully")}catch(t){e.error(`Failed to login to Docker Hub: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as ut}from"commander";import nr from"node:path";import sr from"inquirer";import ft from"node:fs";var ar=new ut().name("build").description("Build a Docker image").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").option("-f, --file <file>","Path to Dockerfile","Dockerfile").action(async o=>{try{let t=await P();if(t||(e.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!o.image){let s=await sr.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:m=>m.trim()?!0:"Image name is required"}]);o.image=s.image}if(!o.tag){let s=await sr.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:m=>m.trim()?!0:"Tag is required"}]);o.tag=s.tag}let r=nr.resolve(process.cwd(),o.file);ft.existsSync(r)||(e.info(`Default Dockerfile not found at ${r}`),o.file=await D("Enter the path to your Dockerfile:","Dockerfile","file"));let i=nr.resolve(process.cwd(),o.file);await new E(o.image,t.username,t.registry).buildImage(i,o.tag)||(e.error("Failed to build Docker image"),process.exit(1)),e.success(`Docker image ${t.username}/${o.image}:${o.tag} built successfully`)}catch(t){e.error(`Failed to build Docker image: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as gt}from"commander";import ht from"inquirer";var cr=new gt().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Full image name (e.g. username/image:tag)").action(async o=>{try{let t=await P();t||(e.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let r=o.image;if(!r){let a=await E.listLocalImages();if(a.length===0&&(e.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!r){let s=Array.from(new Set(a.map(l=>l.imageName))),{selectedImage:m}=await ht.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:s}]);r=m}}await new E("",t.username,t.registry).pushImage(r)||(e.error("Failed to push Docker image"),process.exit(1)),e.success(`Docker image ${r} pushed successfully`)}catch(t){e.error(`Failed to push Docker image: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as yt}from"commander";import W from"inquirer";import Y from"node:fs";import oe from"node:path";var mr=new yt().name("generate").description("Generate a Docker Compose file").option("-i, --image <imageName>","Docker image name to use in the compose file (e.g. phala/phala-cloud)").option("-e, --env-file <envFile>","Path to environment variables file").option("-o, --output <output>","Output path for generated docker-compose.yml").option("--template <template>","Template to use for the generated docker-compose.yml").action(async o=>{try{let t=await P();(!t||!t.username)&&(e.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let r=o.image;if(!r){let m=await E.listLocalImages();if(m.length===0&&(e.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!r){let l=Array.from(new Set(m.map(p=>p.imageName))),{selectedImage:c}=await W.prompt([{type:"list",name:"selectedImage",message:"Select an image to use in the compose file:",choices:l}]);r=c}}let i=o.envFile;if(i)try{U(i)}catch{e.error(`File not found: ${i}`),process.exit(1)}else{let m=oe.join(process.cwd(),".env");if(Y.existsSync(m)){let{useDefault:c}=await W.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);c&&(i=m)}if(!i){let{envPath:c}=await W.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:p=>{try{return U(p),!0}catch{return`File not found: ${p}`}}}]);i=c}}let n=o.output;if(!n&&(n=oe.join(process.cwd(),"docker-compose.yml"),Y.existsSync(n))){let{confirmOverwrite:m}=await W.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${n} already exists. Overwrite?`,default:!1}]);if(!m){let{customPath:l}=await W.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:oe.join(process.cwd(),"docker-generated-compose.yml")}]);n=l}}let a=new E("",t.username,t.registry);i?e.info(`Generating Docker Compose file for ${r} using env file: ${i}`):e.info(`Generating Docker Compose file for ${r} without env file`);let s=await a.buildComposeFile(r,i,o.template);if(s!==n){let m=oe.dirname(n);Y.existsSync(m)||(e.info(`Creating directory: ${m}`),Y.mkdirSync(m,{recursive:!0})),Y.copyFileSync(s,n)}e.success(`Docker Compose file generated successfully: ${n}`)}catch(t){e.error(`Failed to generate Docker Compose file: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});var lr=new vt().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(ir).addCommand(ar).addCommand(cr).addCommand(mr);import{Command as kt}from"commander";import{Command as Ct}from"commander";var pr=new Ct().name("start").description("Start the TEE simulator").option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-v, --verbose","Enable verbose output",!1).action(async o=>{try{if(Je()||await Ze(),await j()){e.success("TEE simulator is already running");return}let r=await Xe({verbose:o.verbose});e.success("TEE simulator started successfully")}catch(t){e.error(`Failed to start TEE simulator: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as wt}from"commander";var dr=new wt().name("stop").description("Stop the TEE simulator").action(async()=>{try{await Qe()||(e.error("Failed to stop TEE simulator"),process.exit(1)),e.success("TEE simulator stopped successfully")}catch(o){e.error(`Failed to stop TEE simulator: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});var Ce=new kt().name("simulator").description("TEE simulator commands").addCommand(pr).addCommand(dr);Ce.action(async()=>{try{let o=await j(),t=re();if(o&&t){let r=te(),i=te(),n=i.replace(/dstack\.sock$/,"tappd.sock");console.log(`\u2713 TEE simulator is running (PID: ${t})`),console.log(`
|
55
55
|
Set these environment variables to use the simulator:`),console.log(` export DSTACK_SIMULATOR_ENDPOINT=${i}`),console.log(` export TAPPD_SIMULATOR_ENDPOINT=${n}`)}else console.log("TEE simulator is not running"),console.log(`
|
56
|
-
To start the simulator, run:`),console.log(" phala simulator start")}catch(o){console.error("Error checking simulator status:",o)}});import{Command as
|
57
|
-
${y}/dashboard/cvms/app_${i.app_id}`)}catch(
|
58
|
-
${y}/dashboard/cvms/app_${i.app_id}`)}catch(
|
59
|
-
${y}/dashboard/cvms/app_${i.app_id}`)}catch(
|
60
|
-
`)){if(!n.trim()||n.trim().startsWith("#"))continue;let a=-1,s=!1,
|
61
|
-
`))):
|
62
|
-
phala cvms get app_${
|
63
|
-
${y}/dashboard/cvms/app_${
|
64
|
-
`;if(e.keyValueTable({vCPUs:i.vcpu!==n?`${F.red(i.vcpu)} -> ${F.green(n)}`:i.vcpu,Memory:i.memory!==a?`${F.red(i.memory)} MB -> ${F.green(a)} MB`:i.memory,"Disk Size":i.disk_size!==s?`${F.red(i.disk_size)} GB -> ${F.green(s)} GB`:i.disk_size,"Allow Restart":
|
65
|
-
${y}/dashboard/cvms/app_${
|
66
|
-
Available KMS Instances:`),
|
67
|
-
`).filter(
|
68
|
-
phala cvms get ${n.app_id}`)}catch(
|
69
|
-
Available KMS Instances:`),
|
56
|
+
To start the simulator, run:`),console.log(" phala simulator start")}catch(o){console.error("Error checking simulator status:",o)}});import{Command as Kt}from"commander";import{Command as _t}from"commander";import we from"chalk";var ur=new _t().name("list").alias("ls").description("List all CVMs").option("-j, --json","Output in JSON format").action(async o=>{try{let t=e.startSpinner("Fetching CVMs"),r=await xe();if(t.stop(!0),!r||r.length===0){e.info("No CVMs found");return}if(o.json){console.log(JSON.stringify(r,null,2));return}for(let i of r)e.keyValueTable({Name:i.name,"App ID":`app_${i.hosted.app_id}`,"CVM ID":i.hosted.id.replace(/-/g,""),Region:i.node.region_identifier,Status:i.status==="running"?we.green(i.status):i.status==="stopped"?we.red(i.status):we.yellow(i.status),"Node Info URL":i.hosted.app_url,"App URL":`${y}/dashboard/cvms/${i.hosted.id.replace(/-/g,"")}`}),e.break();e.success(`Found ${r.length} CVMs`),e.break(),e.info(`Go to ${y}/dashboard/ to view your CVMs`)}catch(t){e.error(`Failed to list CVMs: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as St}from"commander";import ke from"chalk";async function S(o){if(!o){let t=await ee();return t||void 0}return await Q(o)}var fr=new St().name("get").description("Get details of a CVM").argument("[app-id]","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async(o,t)=>{try{let r=await S(o),i=e.startSpinner(`Fetching CVM with App ID app_${r}`),n=await L(r);if(i.stop(!0),e.break(),n||(e.error(`CVM with App ID app_${r} not found`),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}e.keyValueTable({Name:n.name,"App ID":`app_${n.app_id}`,Status:n.status==="running"?ke.green(n.status):n.status==="stopped"?ke.red(n.status):ke.yellow(n.status),vCPU:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"Dstack Image":n.base_image,"App URL":`${y}/dashboard/cvms/app_${n.app_id}`})}catch(r){e.error(`Failed to get CVM details: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as bt}from"commander";var gr=new bt().name("start").description("Start a stopped CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async o=>{try{let t=await S(o),r=e.startSpinner(`Starting CVM with App ID app_${t}`),i=await Te(t);r.stop(!0),e.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`};e.keyValueTable(n,{borderStyle:"rounded"}),e.break(),e.success(`Your CVM is being started. You can check the dashboard for more details:
|
57
|
+
${y}/dashboard/cvms/app_${i.app_id}`)}catch(t){e.error(`Failed to start CVM: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Et}from"commander";var hr=new Et().name("stop").description("Stop a running CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async o=>{try{let t=await S(o),r=e.startSpinner(`Stopping CVM with App ID app_${t}`),i=await Ve(t);r.stop(!0),e.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`};e.keyValueTable(n,{borderStyle:"rounded"}),e.break(),e.success(`Your CVM is being stopped. You can check the dashboard for more details:
|
58
|
+
${y}/dashboard/cvms/app_${i.app_id}`)}catch(t){e.error(`Failed to stop CVM: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as $t}from"commander";var yr=new $t().name("restart").description("Restart a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async o=>{try{let t=await S(o),r=e.startSpinner(`Restarting CVM with App ID app_${t}`),i=await Ue(t);r.stop(!0),e.break();let n={"CVM ID":i.id,Name:i.name,Status:i.status,"App ID":`app_${i.app_id}`,"App URL":i.app_url?i.app_url:`${y}/dashboard/cvms/app_${i.app_id}`};e.keyValueTable(n,{borderStyle:"rounded"}),e.break(),e.success(`Your CVM is being restarted. You can check the dashboard for more details:
|
59
|
+
${y}/dashboard/cvms/app_${i.app_id}`)}catch(t){e.error(`Failed to restart CVM: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Dt}from"commander";import ie from"chalk";var vr=new Dt().name("attestation").description("Get attestation information for a CVM").argument("[app-id]","CVM app ID (will prompt for selection if not provided)").option("-j, --json","Output in JSON format").action(async(o,t)=>{try{let r;if(o)r=await Q(o);else{e.info("No CVM specified, fetching available CVMs...");let n=await ee();if(!n)return;r=n}let i=e.startSpinner(`Fetching attestation information for CVM app_${r}...`);try{let n=await Le(r);if(i.stop(!0),!n||Object.keys(n).length===0){e.info("No attestation information found");return}if(t?.json){e.info(JSON.stringify(n,null,2));return}e.success("Attestation Summary:");let a={Status:n.is_online?ie.green("Online"):ie.red("Offline"),"Public Access":n.is_public?ie.green("Enabled"):ie.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};if(e.keyValueTable(a,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((s,m)=>{e.break(),e.success(`Certificate #${m+1} (${s.position_in_chain===0?"End Entity":"CA"}):`);let l={Subject:`${s.subject.common_name||"Unknown"}${s.subject.organization?` (${s.subject.organization})`:""}`,Issuer:`${s.issuer.common_name||"Unknown"}${s.issuer.organization?` (${s.issuer.organization})`:""}`,"Serial Number":s.serial_number,Validity:`${new Date(s.not_before).toLocaleString()} to ${new Date(s.not_after).toLocaleString()}`,Fingerprint:s.fingerprint,"Signature Algorithm":s.signature_algorithm,"Is CA":s.is_ca?"Yes":"No","Position in Chain":s.position_in_chain};e.keyValueTable(l,{borderStyle:"rounded"})}),n.tcb_info){e.break(),e.success("Trusted Computing Base (TCB) Information:");let s={Mrtd:n.tcb_info.mrtd,"Rootfs Hash":n.tcb_info.rootfs_hash,Rtmr0:n.tcb_info.rtmr0,Rtmr1:n.tcb_info.rtmr1,Rtmr2:n.tcb_info.rtmr2,Rtmr3:n.tcb_info.rtmr3,"Event Log Entries":`${n.tcb_info.event_log.length} entries`};if(e.keyValueTable(s,{borderStyle:"rounded"}),n.tcb_info.event_log&&n.tcb_info.event_log.length>0){e.break(),e.success("Event Log (Showing entries to reproduce RTMR3):");let m=5,l=n.tcb_info.event_log.filter(c=>c.event!==null&&c.event!=="").map(c=>({Event:c.event,IMR:c.imr.toString(),"Event Type":c.event_type.toString(),Payload:c.event_payload}));e.table(l,[{key:"Event",header:"Event",minWidth:8},{key:"IMR",header:"IMR",minWidth:3},{key:"Event Type",header:"Type",minWidth:8},{key:"Payload",header:"Payload",minWidth:25}]),n.tcb_info.event_log.length>m&&e.info("To see all full attestation data, use --json"),e.break(),e.success("To reproduce RTMR3, use the tool at https://rtmr3-calculator.vercel.app/")}}}catch(n){throw i.stop(!1),n}}catch(r){e.error(`Failed to get attestation information: ${r instanceof Error?r.message:String(r)}`)}});import{Command as It}from"commander";import{encryptEnvVars as Pt}from"@phala/dstack-sdk/encrypt-env-vars";import wr from"node:fs";import At from"node:path";import kr from"inquirer";import*as Cr from"node:fs";var J=(o,t)=>{let r={};if(o){for(let i of o)if(i.includes("=")){let[n,...a]=i.split("="),s=a.join("=");n&&(r[n]=s)}}if(t){let i=Cr.readFileSync(t,"utf8");for(let n of i.split(`
|
60
|
+
`)){if(!n.trim()||n.trim().startsWith("#"))continue;let a=-1,s=!1,m="";for(let d=0;d<n.length;d++)if((n[d]==='"'||n[d]==="'"||n[d]==="`")&&(d===0||n[d-1]!=="\\"))s&&n[d]===m?(s=!1,m=""):s||(s=!0,m=n[d]);else if(n[d]==="="&&!s){a=d;break}else if(n[d]==="#"&&!s)break;if(a===-1){n.trim().startsWith("#");continue}let l=n.substring(0,a).trim(),c=n.substring(a+1),p=!1,f="",u=-1;for(let d=0;d<c.length;d++)if((c[d]==='"'||c[d]==="'"||c[d]==="`")&&(d===0||c[d-1]!=="\\"))p&&c[d]===f?(p=!1,f=""):p||(p=!0,f=c[d]);else if(c[d]==="#"&&!p&&d>0&&c[d-1]===" "){u=d-1;break}else if(c[d]==="#"&&!p&&d===0){u=d;break}u!==-1&&(c=c.substring(0,u)),c===void 0&&(c="");let g=c.charAt(0),v=c.charAt(c.length-1);g==='"'&&v==='"'||g==="'"&&v==="'"||g==="`"&&v==="`"?(c=c.substring(1,c.length-1),g==='"'&&(c=c.replace(/\\\\n/g,`
|
61
|
+
`))):c=c.trim(),l&&(r[l]=c)}}return Object.entries(r).map(([i,n])=>({key:i,value:n}))};var _r=new It().name("create").description("Create a new CVM").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file").option("--vcpu <vcpu>",`Number of vCPUs, default is ${M}`).option("--memory <memory>",`Memory in MB, default is ${T}`).option("--disk-size <diskSize>",`Disk size in GB, default is ${V}`).option("--teepod-id <teepodId>","TEEPod ID to use. If not provided, it will be selected from the list of available TEEPods.").option("--image <image>","Version of dstack image to use. If not provided, it will be selected from the list of available images for the selected TEEPod.").option("-e, --env-file <envFile>","Path to environment file").option("--skip-env","Skip environment variable prompt",!1).option("--debug","Enable debug mode",!1).action(async o=>{try{if(!o.name){let{name:_}=await kr.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:$=>$.trim()?$.trim().length>20?"CVM name must be less than 20 characters":$.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test($)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}]);o.name=_}if(!o.compose){let $=K(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");o.compose=await D("Enter the path to your Docker Compose file:",$,"file")}let t=At.resolve(o.compose);wr.existsSync(t)||(e.error(`Docker Compose file not found: ${t}`),process.exit(1));let r=wr.readFileSync(t,"utf8");await N(),process.env.DSTACK_DOCKER_USERNAME&&process.env.DSTACK_DOCKER_PASSWORD?e.info("\u{1F510} Using private DockerHub registry credentials..."):process.env.DSTACK_AWS_ACCESS_KEY_ID&&process.env.DSTACK_AWS_SECRET_ACCESS_KEY&&process.env.DSTACK_AWS_REGION&&process.env.DSTACK_AWS_ECR_REGISTRY?e.info(`\u{1F510} Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`):e.info("\u{1F510} Using public DockerHub registry...");let i=[];if(o.envFile)try{i=J([],o.envFile)}catch(_){e.error(`Failed to read environment file: ${_ instanceof Error?_.message:String(_)}`),process.exit(1)}else if(!o.skipEnv){let{shouldSkip:_}=await kr.prompt([{type:"confirm",name:"shouldSkip",message:"Do you want to skip environment variable prompt?",default:!0}]);if(_)e.info("Skipping environment variable prompt");else{let $=await D("Enter the path to your environment file:",".env","file");i=J([],$)}}let n=Number(o.vcpu)||M,a=Number(o.memory)||T,s=Number(o.diskSize)||V;(Number.isNaN(n)||n<=0)&&(e.error(`Invalid number of vCPUs: ${n}`),process.exit(1)),(Number.isNaN(a)||a<=0)&&(e.error(`Invalid memory: ${a}`),process.exit(1)),(Number.isNaN(s)||s<=0)&&(e.error(`Invalid disk size: ${s}`),process.exit(1));let m=e.startSpinner("Fetching available TEEPods"),l=await O();m.stop(!0),l.nodes.length===0&&(e.error("No TEEPods available. Please try again later."),process.exit(1));let c;o.teepodId?(c=l.nodes.find(_=>_.teepod_id===Number(o.teepodId)),c||(e.error("Failed to find selected TEEPod"),process.exit(1))):(c=l.nodes[0],c||(e.error("Failed to find default TEEPod"),process.exit(1)));let p;o.image?(p=c.images?.find(_=>_.name===o.image),p||(e.error(`Failed to find selected image: ${o.image}`),process.exit(1))):(p=c.images?.find(_=>_.name===de),p||(e.error(`Failed to find default image ${de}`),process.exit(1)));let f={teepod_id:c.teepod_id,name:o.name,image:p.name,vcpu:n,memory:a,disk_size:s,compose_manifest:{docker_compose_file:r,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:o.name,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},u=e.startSpinner("Getting public key from CVM"),g=await Fe(f);u.stop(!0),g||(e.error("Failed to get public key from CVM"),process.exit(1));let v=e.startSpinner("Encrypting environment variables"),d=await Pt(i,g.app_env_encrypt_pubkey);v.stop(!0),o.debug&&(e.debug("Public key:",g.app_env_encrypt_pubkey),e.debug("Encrypted environment variables:",d),e.debug("Environment variables:",JSON.stringify(i)));let w=e.startSpinner("Creating CVM"),C=await Me({...f,encrypted_env:d,app_env_encrypt_pubkey:g.app_env_encrypt_pubkey,app_id_salt:g.app_id_salt});w.stop(!0),C||(e.error("Failed to create CVM"),process.exit(1)),e.success("CVM created successfully"),e.break();let se={"CVM ID":C.id,Name:C.name,Status:C.status,"App ID":`app_${C.app_id}`,"App URL":C.app_url?C.app_url:`${y}/dashboard/cvms/app_${C.app_id}`};e.keyValueTable(se,{borderStyle:"rounded"}),e.info(""),e.success(`Your CVM is being created. You can check its status with:
|
62
|
+
phala cvms get app_${C.app_id}`)}catch(t){e.error(`Failed to create CVM: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as xt}from"commander";import Ft from"inquirer";var Sr=new xt().name("delete").description("Delete a CVM").argument("[app-id]","App ID of the CVM to delete (if not provided, a selection prompt will appear)").option("-f, --force","Skip confirmation prompt",!1).action(async(o,t)=>{try{let r=await S(o);if(!t.force){let{confirm:a}=await Ft.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID app_${r}? This action cannot be undone.`,default:!1}]);if(!a){e.info("Deletion cancelled");return}}let i=e.startSpinner(`Deleting CVM app_${r}`),n=await Re(r);i.stop(!0),n||(e.error(`Failed to delete CVM app_${r}`),process.exit(1)),e.success(`CVM app_${r} deleted successfully`)}catch(r){e.error(`Failed to delete CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as Mt}from"commander";import Tt from"node:fs";import{encryptEnvVars as Vt}from"@phala/dstack-sdk/encrypt-env-vars";var br=new Mt().name("upgrade").description("Upgrade a CVM to a new version").argument("[app-id]","CVM app ID to upgrade (will prompt for selection if not provided)").option("-c, --compose <compose>","Path to new Docker Compose file").option("-e, --env-file <envFile>","Path to environment file").option("--debug","Enable debug mode",!1).action(async(o,t)=>{try{let r=await S(o),i=e.startSpinner(`Fetching current configuration for CVM app_${r}`),n=await L(r);if(i.stop(!0),n||(e.error(`CVM with App ID app_${r} not found`),process.exit(1)),!t.compose){let f=K(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");t.compose=await D("Enter the path to your Docker Compose file:",f,"file")}let a="";if(t.compose)try{a=Tt.readFileSync(t.compose,"utf8")}catch(p){e.error(`Failed to read Docker Compose file: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}await N(),process.env.DSTACK_DOCKER_USERNAME&&process.env.DSTACK_DOCKER_PASSWORD?e.info("\u{1F510} Using private DockerHub registry credentials..."):process.env.DSTACK_AWS_ACCESS_KEY_ID&&process.env.DSTACK_AWS_SECRET_ACCESS_KEY&&process.env.DSTACK_AWS_REGION&&process.env.DSTACK_AWS_ECR_REGISTRY?e.info(`\u{1F510} Using private AWS ECR registry: ${process.env.DSTACK_AWS_ECR_REGISTRY}`):e.info("\u{1F510} Using public DockerHub registry...");let s="";if(t.envFile){let p=[];if(t.envFile)try{p=J([],t.envFile),s=await Vt(p,n.encrypted_env_pubkey)}catch(f){e.error(`Failed to read environment file: ${f instanceof Error?f.message:String(f)}`),process.exit(1)}}let m={compose_manifest:{docker_compose_file:a,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${r}`},encrypted_env:s,allow_restart:!0},l=e.startSpinner(`Upgrading CVM app_${r}`),c=await Ne(r,m);c||(l.stop(!1),e.error("Failed to upgrade CVM"),process.exit(1)),l.stop(!0),c.detail&&e.info(`Details: ${c.detail}`),e.break(),e.success(`Your CVM is being upgraded. You can check the dashboard for more details:
|
63
|
+
${y}/dashboard/cvms/app_${r}`)}catch(r){e.error(`Failed to upgrade CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as Ut}from"commander";import Z from"inquirer";import F from"chalk";var Er=new Ut().name("resize").description("Resize resources for a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").option("-v, --vcpu <vcpu>","Number of virtual CPUs").option("-m, --memory <memory>","Memory size in MB").option("-d, --disk-size <diskSize>","Disk size in GB").option("-r, --allow-restart <allowRestart>","Allow restart of the CVM if needed for resizing").option("-y, --yes","Automatically confirm the resize operation").action(async(o,t)=>{try{let r=await S(o),i=await L(r),n=t.vcpu,a=t.memory,s=t.diskSize,m=t.allowRestart;n||(n=(await Z.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:u=>{let g=parseInt(u);return isNaN(g)||g<0?"Please enter a valid non-negative number":!0},default:i.vcpu,filter:u=>parseInt(u)}])).vcpu),a||(a=(await Z.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:u=>{let g=parseInt(u);return isNaN(g)||g<0?"Please enter a valid non-negative number":!0},default:i.memory,filter:u=>parseInt(u)}])).memory),s||(s=(await Z.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:u=>{let g=parseInt(u);return isNaN(g)||g<0?"Please enter a valid non-negative number":!0},default:i.disk_size,filter:u=>parseInt(u)}])).diskSize),m||(m=(await Z.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let l=`Are you sure you want to resize CVM app_${r} with the following changes:
|
64
|
+
`;if(e.keyValueTable({vCPUs:i.vcpu!==n?`${F.red(i.vcpu)} -> ${F.green(n)}`:i.vcpu,Memory:i.memory!==a?`${F.red(i.memory)} MB -> ${F.green(a)} MB`:i.memory,"Disk Size":i.disk_size!==s?`${F.red(i.disk_size)} GB -> ${F.green(s)} GB`:i.disk_size,"Allow Restart":m?F.green("Yes"):F.red("No")}),!t.yes){let{confirm:f}=await Z.prompt([{type:"confirm",name:"confirm",message:l,default:!1}]);if(!f){e.info("Resize operation cancelled");return}}let c=e.startSpinner(`Resizing CVM with App ID app_${r}`);await ze(r,n,a,s,m?1:0),c.stop(!0),e.break(),e.success(`Your CVM is being resized. You can check the dashboard for more details:
|
65
|
+
${y}/dashboard/cvms/app_${r}`)}catch(r){e.error(`Failed to resize CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as Nt}from"commander";var $r=new Nt().name("list-nodes").description("List all available worker nodes.").action(async()=>{try{let{nodes:o,kms_list:t}=await O();if(o.length===0){e.info("No available nodes found.");return}e.info("Available Nodes:"),o.forEach(r=>{e.info("----------------------------------------"),e.info(` ID: ${r.teepod_id}`),e.info(` Name: ${r.name}`),e.info(` Region: ${r.region_identifier}`),e.info(` FMSPC: ${r.fmspc||"N/A"}`),e.info(` Device ID: ${r.device_id||"N/A"}`),e.info(` Support Onchain KMS: ${r.support_onchain_kms}`),e.info(" Images:"),r.images&&r.images.length>0?r.images.forEach(i=>{e.info(` - ${i.name}`),e.info(` Hash: ${i.os_image_hash||"N/A"}`)}):e.info(" N/A")}),t&&t.length>0&&(e.info(`
|
66
|
+
Available KMS Instances:`),t.forEach(r=>{e.info("----------------------------------------"),e.info(` ID: ${r.id}`),e.info(` URL: ${r.url}`),e.info(` Version: ${r.version}`),e.info(` Chain ID: ${r.chain_id}`),e.info(` Contract Address: ${r.kms_contract_address}`),e.info(` Gateway App ID: ${r.gateway_app_id}`)}))}catch(o){e.error(`Failed to list available nodes: ${o instanceof Error?o.message:String(o)}`)}});import{Command as Rt}from"commander";import{encryptEnvVars as Lt}from"@phala/dstack-sdk/encrypt-env-vars";import Dr from"node:fs";import Ot from"node:path";var Ir=new Rt().name("replicate").description("Create a replica of an existing CVM").argument("<cvm-id>","UUID of the CVM to replicate").option("--teepod-id <teepodId>","TEEPod ID to use for the replica").option("-e, --env-file <envFile>","Path to environment file").action(async(o,t)=>{try{let r;if(o=o.replace(/-/g,""),t.envFile){let s=Ot.resolve(process.cwd(),t.envFile);if(!Dr.existsSync(s))throw new Error(`Environment file not found: ${s}`);let l=Dr.readFileSync(s,"utf-8").split(`
|
67
|
+
`).filter(f=>f.trim()!==""&&!f.trim().startsWith("#")).map(f=>{let[u,...g]=f.split("=");return{key:u.trim(),value:g.join("=").trim()}}),c=await Oe(o);e.info("Encrypting environment variables..."),r=await Lt(l,c.env_pubkey)}let i={};t.teepodId&&(i.teepod_id=parseInt(t.teepodId,10)),r&&(i.encrypted_env=r);let n=await Ke(o,i);e.success(`Successfully created replica of CVM UUID: ${o} with App ID: ${n.app_id}`);let a={"CVM UUID":n.vm_uuid.replace(/-/g,""),"App ID":n.app_id,Name:n.name,Status:n.status,TEEPod:`${n.teepod.name} (ID: ${n.teepod_id})`,vCPUs:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"App URL":n.app_url||`${process.env.CLOUD_URL||"https://cloud.phala.network"}/dashboard/cvms/${n.vm_uuid.replace(/-/g,"")}`};e.keyValueTable(a,{borderStyle:"rounded"}),e.success(`Your CVM replica is being created. You can check its status with:
|
68
|
+
phala cvms get ${n.app_id}`)}catch(r){e.error("Failed to create CVM replica:",r instanceof Error?r.message:r),process.exit(1)}});var Pr=new Kt().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(vr).addCommand(_r).addCommand(Sr).addCommand(fr).addCommand(ur).addCommand(gr).addCommand(hr).addCommand(Er).addCommand(yr).addCommand(br).addCommand($r).addCommand(Ir);import{Command as Ar}from"commander";async function _e(){try{let{nodes:o,kms_list:t}=await O();if(o.length===0){e.info("No available nodes found.");return}e.info("Available Nodes:"),o.forEach(r=>{e.info("----------------------------------------"),e.info(` ID: ${r.teepod_id}`),e.info(` Name: ${r.name}`),e.info(` Region: ${r.region_identifier}`),e.info(` FMSPC: ${r.fmspc||"N/A"}`),e.info(` Device ID: ${r.device_id||"N/A"}`),e.info(` Support Onchain KMS: ${r.support_onchain_kms}`),e.info(" Images:"),r.images&&r.images.length>0?r.images.forEach(i=>{e.info(` - ${i.name}`),e.info(` Hash: ${i.os_image_hash||"N/A"}`)}):e.info(" N/A")}),t&&t.length>0&&(e.info(`
|
69
|
+
Available KMS Instances:`),t.forEach(r=>{e.info("----------------------------------------"),e.info(` Slug: ${r.slug}`),e.info(` URL: ${r.url}`),e.info(` Version: ${r.version}`),r.chain_id&&(e.info(` Chain ID: ${r.chain_id}`),e.info(` Contract Address: ${r.kms_contract_address}`),e.info(` Gateway App ID: ${r.gateway_app_id}`))}))}catch(o){throw e.error(`Failed to list available nodes: ${o instanceof Error?o.message:String(o)}`),o}}var xr=new Ar().name("nodes").description("List and manage TEE nodes").action(_e).addCommand(new Ar("list").description("List all available worker nodes").alias("ls").action(_e));import{createClient as zt}from"@phala/cloud";import{Command as Bt}from"commander";import{safeGetCurrentUser as Gt}from"@phala/cloud";async function jt(o={}){try{let t=o.debug||process.env.DEBUG?.toLowerCase()==="true",r=o.apiKey||R();if(!r){e.warn('Not authenticated. Please set an API key with "phala auth login"');return}t&&e.debug(`Using API key: ${r.substring(0,5)}...`);try{let i=zt({apiKey:r}),n=await Gt(i);if(!n.success){e.error("Failed to get user information"),n.error&&e.error(`Error: ${n.error.message}`);return}let a=n.data,s=process.env.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.network/api/v1";if(o.json){console.log(JSON.stringify({apiUrl:s,username:a.username,team_name:a.team_name},null,2));return}console.log(`Integrated API: ${s}`),console.log(`Logged in as: ${a.username}`),console.log(`Current Workspace: ${a.team_name}`)}catch(i){console.error("Authentication failed. Your API key may be invalid or expired."),console.log('Please set a new API key with "phala auth login"'),t&&e.debug(`Error details: ${i instanceof Error?i.message:String(i)}`)}}catch(t){e.error(`Failed to check authentication status: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}}var Fr=new Bt().name("status").description("Check Phala Cloud status and authentication").option("--api-key <apiKey>","API key for authentication").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(jt);import{Command as Yt,Option as Jt}from"commander";import $e from"dedent";import be from"fs-extra";import z from"inquirer";import Zt from"path";import{createClient as ne,encryptEnvVars as Ee,parseEnvVars as Xt,safeAddComposeHash as Qt,safeCommitCvmComposeFileUpdate as eo,safeCommitCvmProvision as zr,safeDeployAppAuth as ro,safeGetAppEnvEncryptPubKey as to,safeGetAvailableNodes as oo,safeGetCvmComposeFile as io,safeGetCvmInfo as no,safeGetKmsList as so,safeProvisionCvm as ao,safeProvisionCvmComposeFileUpdate as co}from"@phala/cloud";function Mr(o,t="B"){if(!o||typeof o!="string")throw new Error("Invalid input: must be a non-empty string");let r=o.trim().match(/^(\d+(?:\.\d+)?)\s*([KkMmGgTt][Bb]?)?$/);if(!r)throw new Error(`Invalid format: ${o}. Expected format: <number>[unit] (e.g., 2G, 500MB, 1T)`);let i=parseFloat(r[1]),n=(r[2]||t).toUpperCase().replace("B",""),a={K:1024,M:1024*1024,G:1024*1024*1024,T:1024*1024*1024*1024,"":1};if(!(n in a))throw new Error(`Unsupported unit: ${n}. Supported units: B, K/KB, M/MB, G/GB, T/TB`);return Math.round(i*a[n])}function Tr(o){let t=Mr(o,"MB"),r=Math.round(t/(1024*1024));if(r%1024!==0)throw new Error(`Memory must be a multiple of 1GB (1024MB). Got: ${r}MB`);return r}function Vr(o){let t=Mr(o,"GB"),r=Math.round(t/(1024*1024*1024));if(r%1!==0)throw new Error(`Disk size must be a multiple of 1GB. Got: ${r}GB`);let i=250;if(r>i)throw new Error(`Maximum disk size is ${i}GB. Got: ${r}GB`);return r}import X from"fs-extra";import Ur from"node:path";import Ht from"node:os";import{join as Nr}from"path";var qt=Ur.join(Ht.homedir(),".phala-cloud"),Ra=Ur.join(qt,"config.json");function Se(){return Nr(process.cwd(),".phala","config")}function Rr(){let o=Se(),t=Nr(process.cwd(),".phala");X.ensureDirSync(t),X.pathExistsSync(o)||X.writeJsonSync(o,{},{spaces:2})}function Lr(){return Rr(),X.readJsonSync(Se())}function Wt(o){Rr(),X.writeJsonSync(Se(),o,{spaces:2})}function Or(o){let t=Lr();t.cvmUuid=o,Wt(t)}function Kr(){return process.env.PHALA_CLOUD_CVM_UUID?process.env.PHALA_CLOUD_CVM_UUID:Lr().cvmUuid}async function mo({apiKey:o,interactive:t}){if(!o&&!process.env.PHALA_CLOUD_API_KEY)if(t){let{apiKey:r}=await z.prompt([{type:"password",name:"apiKey",message:"Enter your API key:",validate:i=>i.trim()?!0:"API key is required"}]);return ne({apiKey:r})}else{let r=R();if(!r)throw new Error("API key is required. Please provide it via --api-key or PHALA_CLOUD_API_KEY environment variable");return ne({apiKey:r})}else if(o)return ne({apiKey:o});return ne()}async function lo({dockerComposePath:o,interactive:t}){if(!o)if(t){let i=K(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");o=await D("Enter the path to your Docker Compose file:",i,"file")}else throw new Error($e(`
|
70
70
|
Docker Compose file is required.
|
71
71
|
|
72
72
|
Usage examples:
|
@@ -81,13 +81,13 @@ Available KMS Instances:`),r.forEach(t=>{e.info("-------------------------------
|
|
81
81
|
--private-key <key> Private key for deployment
|
82
82
|
|
83
83
|
Run with --interactive for guided setup
|
84
|
-
`));if(!be.existsSync(o))throw new Error(`Docker compose file not found: ${o}`);return be.readFileSync(o,"utf8")}function
|
84
|
+
`));if(!be.existsSync(o))throw new Error(`Docker compose file not found: ${o}`);return be.readFileSync(o,"utf8")}function po({uuid:o}={}){return o||Kr()}var uo=async(o,t)=>{let r=o.privateKey||process.env.PRIVATE_KEY;if(o.kmsId&&t&&!o.privateKey)if(o.interactive)r=(await z.prompt([{type:"password",name:"privateKey",message:"Enter your private key:",validate:n=>n.trim()?!0:"Private key is required"}])).privateKey;else throw new Error("When using on-chain KMS, either --private-key (or PRIVATE_KEY env) must be provided");return r},fo=async o=>{let t=o.name;if(!o.name){let r=Zt.basename(process.cwd()).toLowerCase().replace(/[^a-z0-9_-]/g,"-");r.length<3&&(r=r+"-cvm");let i=r.slice(0,20);o.interactive?t=(await z.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",default:i,validate:a=>a.trim()?a.trim().length>20?"CVM name must be less than 20 characters":a.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test(a)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}])).name:t=i}return t},go=async o=>{let t=[],r=o.envFile;if(o.interactive&&(!o.envFile||r===!0)&&(r=await D("Enter the path to your environment file:",".env","file")),r&&r!==!0)try{let i=be.readFileSync(r,{encoding:"utf8"});t=Xt(i)}catch(i){throw new Error(`Error reading environment file ${r}:`,i)}return t},ho=async o=>{let t=M;if(o.vcpu)try{t=Number(o.vcpu)}catch{throw new Error(`Invalid vCPU format '${o.vcpu}'. Using default: ${M}`)}let r=T;if(o.memory)try{r=Tr(o.memory)}catch{throw new Error(`Invalid memory format '${o.memory}'. Using default: ${T}MB`)}let i=V;if(o.diskSize)try{i=Vr(o.diskSize)}catch{throw new Error(`Invalid disk size format '${o.diskSize}'. Using default: ${V}GB`)}return{vcpu:t,memoryMB:r,diskSizeGB:i}},yo=async(o,t)=>{let r=await oo(t);if(!r.success)throw"isRequestError"in r.error?new Error(`HTTP ${r.error.status}: ${r.error.message}`):new Error(`Validation error: ${r.error.issues}`);let i=r.data,n=null,a=null,s=o.privateKey;if(o.nodeId){if(n=i.nodes.find(l=>l.teepod_id===Number(o.nodeId)),!n)throw new Error(`Node ${o.nodeId} not found, available nodes: ${i.nodes.map(l=>l.teepod_id).join(", ")}`)}else if(o.interactive){let{node:l}=await z.prompt([{type:"list",name:"node",message:"Select a Node to use:",choices:i.nodes.map(c=>({name:`${c.name} (Region: ${c.region_identifier})`,value:c}))}]);n=l}else n=i.nodes[0];if(!n)throw new Error(`No available nodes found, available nodes: ${i.nodes.map(l=>l.teepod_id).join(", ")}`);if(n.support_onchain_kms){let l=await so(t);if(!l.success)throw"isRequestError"in l.error?new Error(`HTTP ${l.error.status}: ${l.error.message}`):new Error(`Validation error: ${l.error.issues}`);let c=l.data;if(o.kmsId)a=c.items.find(p=>p.slug===o.kmsId||p.id===o.kmsId);else if(o.interactive){let{kmsChoice:p}=await z.prompt([{type:"list",name:"kmsChoice",message:"Select a KMS to use:",choices:c.items.map(f=>({name:f.chain_id?`${f.slug} (Chain ID: ${f.chain_id})`:`${f.slug} (No chain required)`,value:f}))}]);a=p}else throw new Error(`Node ${n.name} requires a KMS ID for Contract Owned CVM, available kms: ${c.items.map(p=>p.slug).join(", ")}`);if(a)s=await uo({...o,kmsId:a.id},a.chain_id);else throw new Error(`KMS ${o.kmsId} not found, available kms: ${c.items.map(p=>p.slug).join(", ")}`)}let m=n.images[0];if(o.image){if(m=n.images.find(l=>l.name===o.image),!m)throw new Error(`Image ${o.image} not found in the node ${n.name}, available images: ${n.images.map(l=>l.name).join(", ")}.`)}else if(o.interactive){let{imageChoice:l}=await z.prompt([{type:"list",name:"imageChoice",message:"Select an image to use:",choices:n.images.map(c=>({name:`${c.name}`,value:c}))}]);m=l}if(!m)throw new Error(`No available OS images found in the node ${n.name}, available images: ${n.images.map(l=>l.name).join(", ")}.`);return{target:n,kms:a,image:m,privateKey:s}},vo=async(o,t,r,i)=>{let n=await fo(o),{vcpu:a,memoryMB:s,diskSizeGB:m}=await ho(o),{target:l,kms:c,image:p,privateKey:f}=await yo(o,i),u={name:n,compose_file:{docker_compose_file:t,allowed_envs:r.map(C=>C.key)},vcpu:a,memory:s,disk_size:m,node_id:l.teepod_id,image:p.name,kms_id:c?.slug};console.log(`Deploying CVM ${n}...`);let g=await ao(i,u);if(!g.success)throw new Error("Failed to provision CVM:",g.error);let v=g.data,d;if(v.app_env_encrypt_pubkey&&v.app_id||!c?.chain_id){let C=await Ee(r,v.app_env_encrypt_pubkey);d=await zr(i,{app_id:v.app_id,encrypted_env:C,compose_hash:v.compose_hash,kms_id:c?.slug})}else{let C=c.slug,se=c.kms_contract_address,_=c.chain,$=v.compose_hash,Gr=l.device_id,jr=o.rpcUrl,ae=await ro({chain:_,rpcUrl:jr,kmsContractAddress:se,privateKey:f,deviceId:Gr,composeHash:$});if(!ae.success){let Wr=ae?.error?.message;throw new Error(`Deployment contract failed: ${Wr}`)}let ce=ae.data,De=ce.appId,me=await to(i,{app_id:De,kms:C});if(!me.success)throw new Error(`Failed to get app env encrypt pubkey: ${me.error.message}`);let Hr=me.data,qr=await Ee(r,Hr.public_key);d=await zr(i,{app_id:De,encrypted_env:qr,compose_hash:v.compose_hash,kms_id:C,contract_address:ce.appAuthAddress,deployer_address:ce.deployer})}if(!d.success)throw"isRequestError"in d.error?new Error(`HTTP ${d.error.status}: ${d.error.message}`):new Error(`Validation error: ${d.error.issues}`);let w=d.data;if(Or(w.vm_uuid),o?.json!==!1)console.log(JSON.stringify({success:!0,vm_uuid:w.vm_uuid,name:w.name,app_id:w.app_id,dashboard_url:`${y}/dashboard/cvms/${w.vm_uuid}`},null,2));else{let C=$e`
|
85
85
|
CVM created successfully!
|
86
86
|
|
87
|
-
CVM ID: ${
|
88
|
-
Name: ${
|
89
|
-
App ID: ${
|
90
|
-
Dashboard URL: ${y}/dashboard/cvms/${
|
91
|
-
`;console.log(
|
92
|
-
Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("v1.0.15").addCommand(Fr).addCommand(
|
87
|
+
CVM ID: ${w.vm_uuid}
|
88
|
+
Name: ${w.name}
|
89
|
+
App ID: ${w.app_id}
|
90
|
+
Dashboard URL: ${y}/dashboard/cvms/${w.vm_uuid}
|
91
|
+
`;console.log(C)}},Co=async(o,t,r,i)=>{let[n,a]=await Promise.all([no(i,{uuid:o.uuid}),io(i,{uuid:o.uuid})]);if(!n.success)throw new Error(`Failed to get cvm info: ${n.error.message}`);if(!a.success)throw new Error(`Failed to get cvm compose file: ${a.error.message}`);let s=n.data,m=a.data;m.docker_compose_file=t,m.allowed_envs=r.map(u=>u.key),console.log(`Preparing update for CVM ${o.uuid}...`);let l=await co(i,{uuid:o.uuid,app_compose:m});if(!l.success)throw new Error(`Failed to provision cvm compose file: ${l.error.message}`);let c=l.data,p;if(s.kms_info?.chain_id){if(!o.privateKey)throw new Error("Private key is required for contract DstackApp");let u=await Qt({chain:s.kms_info?.chain,rpcUrl:o.rpcUrl,appId:s.app_id,composeHash:c.compose_hash,privateKey:o.privateKey});if(!u.success){let g=u?.error?.message;throw new Error(`Failed to add compose hash: ${g}`)}}else r.length>0&&(p=await Ee(r,s.encrypted_env_pubkey));let f=await eo(i,{id:o.uuid,compose_hash:c.compose_hash,encrypted_env:p,env_keys:r.map(u=>u.key)});if(!f.success)throw new Error(`Failed to commit CVM compose file update: ${f.error.message}`);o?.json!==!1?console.log(JSON.stringify({success:!0,vm_uuid:o.uuid,name:s.name,app_id:s.app_id,dashboard_url:`${y}/dashboard/cvms/${o.uuid}`},null,2)):console.log("CVM compose file updated successfully!")},Br=new Yt().command("deploy [compose]").description("Create a new CVM with on-chain KMS in one step.").option("--json","Output in JSON format",!1).option("--no-json","Disable JSON output format").option("--debug","Enable debug logging",!1).option("--api-key <apiKey>","API key for authentication").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file (default: docker-compose.yml in current directory)").option("--vcpu <vcpu>",`Number of vCPUs, default is ${M}`).option("--memory <memory>",`Memory with optional unit (e.g., 2G, 1024MB), default is ${T}MB`).option("--disk-size <diskSize>",`Disk size with optional unit (e.g., 50G, 100GB), default is ${V}GB`).option("--image <image>","Version of dstack image to use").option("--node-id <nodeId>","Node ID to use").option("-e, --env-file <envFile>","Prompt for environment variables and save to file (optional)").option("-i, --interactive","Enable interactive mode for required parameters",!1).option("--kms-id <kmsId>","KMS ID to use.").option("--uuid <uuid>","UUID of the CVM to upgrade").addOption(new Jt("--custom-app-id <customAppId>","Custom App ID to use.").hideHelp()).option("--pre-launch-script <preLaunchScript>","Path to pre-launch script").option("--private-key <privateKey>","Private key for signing transactions.").option("--rpc-url <rpcUrl>","RPC URL for the blockchain.").action(async(o,t)=>{try{let r=o||t.compose,i=await mo({apiKey:t.apiKey,interactive:t.interactive}),n=await lo({dockerComposePath:r,interactive:t.interactive}),a=po({uuid:t.uuid}),s=await go(t);!!a?await Co({...t,uuid:a},n,s,i):await vo({...t,uuid:a},n,s,i)}catch(r){t.json!==!1?console.error(JSON.stringify({success:!1,error:r.message,stack:t.debug&&r instanceof Error?r.stack:void 0},null,2)):console.error($e`${r.message}`),process.exit(1)}});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function ko(){new wo().name("phala").alias("pha").description(`${je}
|
92
|
+
Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("v1.0.15").addCommand(Fr).addCommand(Ye).addCommand(Pr).addCommand(lr).addCommand(Ce).addCommand(xr).addCommand(Br).parse(process.argv)}ko().catch(o=>{e.error("An error occurred:",o),process.exit(1)});
|
93
93
|
//# sourceMappingURL=index.js.map
|