-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhandler.ts
More file actions
1404 lines (1265 loc) · 38.3 KB
/
handler.ts
File metadata and controls
1404 lines (1265 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from "node:path";
import os from "node:os";
import type { CommandContext } from "@/src/core/types";
import { resolveAuthForContext } from "@/src/lib/client";
import { logger } from "@/src/utils/logger";
import {
CLOUD_URL,
DEFAULT_DISK_SIZE,
DEFAULT_MEMORY,
DEFAULT_VCPU,
} from "@/src/utils/constants";
import { waitForCvmReady } from "@/src/utils/cvms";
import { detectFileInCurrentDir, promptForFile } from "@/src/utils/prompts";
import { dedupeEnvVars, parseEnvInputs } from "@/src/utils/env-parsing";
import { parseDiskSizeInput, parseMemoryInput } from "@/src/utils/units";
import {
type Client,
type EnvVar,
type ErrorLink,
CvmIdSchema,
MAX_COMPOSE_PAYLOAD_BYTES,
ResourceError,
createClient,
encryptEnvVars,
formatStructuredError,
parseEnvVars,
safeAddComposeHash,
safeAddDevice,
safeCheckOnChainPrerequisites,
safeCommitCvmProvision,
safeConfirmCvmPatch,
safeDeployAppAuth,
safeGetAppEnvEncryptPubKey,
safeGetAvailableNodes,
safeGetCvmInfo,
safeGetCvmList,
safeGetCurrentUser,
safePatchCvm,
safeProvisionCvm,
safeUpdateCvmVisibility,
safeCommitCvmUpdate,
convertToHostname,
isValidHostname,
} from "@phala/cloud";
import dedent from "dedent";
import fs from "fs-extra";
import inquirer from "inquirer";
import type { DeployCommandInput } from "./command";
import type { RuntimeProjectConfig } from "@/src/utils/project-config";
type PrivacyConfig = Pick<
RuntimeProjectConfig,
"public_logs" | "public_sysinfo" | "listed"
>;
interface Options {
name?: string;
compose?: string;
instanceType?: string;
vcpu?: string;
memory?: string;
diskSize?: string;
fs?: string;
image?: string;
region?: string;
nodeId?: string;
env?: string[];
envFile?: string | boolean;
interactive?: boolean;
kms?: string;
kmsId?: string;
cvmId?: string;
uuid?: string;
customAppId?: string;
nonce?: string;
preLaunchScript?: string;
privateKey?: string;
rpcUrl?: string;
json?: boolean;
debug?: boolean;
apiToken?: string;
wait?: boolean;
sshPubkey?: string;
devOs?: boolean;
publicLogs?: boolean;
publicSysinfo?: boolean;
listed?: boolean;
prepareOnly?: boolean;
commit?: boolean;
token?: string;
composeHash?: string;
transactionHash?: string;
[key: string]: unknown;
}
/**
* Handle provision error with structured error response
*/
function handleProvisionError(
error: unknown,
options: Options,
): string | object {
// Check if it's a ResourceError with structured details
if (error instanceof ResourceError) {
if (options.json) {
return {
success: false,
error_code: error.errorCode,
message: error.message,
details: error.structuredDetails,
suggestions: error.suggestions,
links: error.links,
};
}
return formatStructuredError(error);
}
// Parse structured error from plain object (backward compatibility)
if (error && typeof error === "object" && "response" in error) {
const errorWithResponse = error as {
response?: {
data?: {
detail?: unknown;
};
};
};
const errorData = errorWithResponse.response?.data?.detail;
if (
errorData &&
typeof errorData === "object" &&
"error_code" in errorData
) {
const { error_code, message, details, suggestions, links } =
errorData as {
error_code: string;
message: string;
details?: Array<{
field?: string;
value?: unknown;
message?: string;
}>;
suggestions?: string[];
links?: Array<{ url: string; label: string }>;
};
if (options.json) {
return {
success: false,
error_code,
message,
details,
suggestions,
links,
};
}
let output = `\nError [${error_code}]: ${message}\n`;
if (details && details.length > 0) {
output += "\nDetails:\n";
for (const d of details) {
if (d.message) {
output += ` - ${d.message}\n`;
} else if (d.field && d.value !== undefined) {
output += ` - ${d.field}: ${d.value}\n`;
}
}
}
if (suggestions && suggestions.length > 0) {
output += "\nSuggestions:\n";
for (const s of suggestions) {
output += ` - ${s}\n`;
}
}
if (links && links.length > 0) {
output += "\nLearn more:\n";
for (const link of links) {
output += ` - ${link.label}: ${link.url}\n`;
}
}
return output;
}
}
// Fallback to generic error
const message =
error instanceof Error ? error.message : String(error || "Unknown error");
return options.json
? { success: false, error: message }
: `\nError: ${message}\n`;
}
// Use legacy API version until CLI types are updated for the new format
const API_VERSION = "2025-10-28" as const;
async function getApiClient({
apiToken,
interactive,
}: Readonly<Pick<Options, "apiToken" | "interactive">>): Promise<
Client<typeof API_VERSION>
> {
const resolved = resolveAuthForContext(undefined, { apiToken });
if (resolved.apiKey) {
return createClient({
apiKey: resolved.apiKey,
baseURL: resolved.baseURL,
version: API_VERSION,
});
}
if (interactive) {
const { apiToken: promptedToken } = await inquirer.prompt([
{
type: "password",
name: "apiToken",
message: "Enter your API token:",
validate: (input: string) =>
input.trim() ? true : "API token is required",
},
]);
return createClient({
apiKey: promptedToken,
baseURL: resolved.baseURL,
version: API_VERSION,
});
}
throw new Error(
"API token is required. Please run 'phala login' or set PHALA_CLOUD_API_KEY environment variable",
);
}
async function readDockerComposeFile({
dockerComposePath,
interactive,
}: {
dockerComposePath?: string;
interactive: boolean;
}): Promise<string> {
// 1. If path is not provided and we're in interactive mode, try to detect it
if (!dockerComposePath) {
if (interactive) {
const possibleFiles = ["docker-compose.yml", "docker-compose.yaml"];
const composeFileName = detectFileInCurrentDir(
possibleFiles,
"Detected docker compose file: {path}",
);
dockerComposePath = await promptForFile(
"Enter the path to your Docker Compose file:",
composeFileName,
"file",
);
} else {
throw new Error(
dedent(`
Docker Compose file is required.
Usage examples:
phala deploy -c docker-compose.yml
phala deploy --kms ethereum --private-key <your-private-key> --rpc-url <rpc-url> -c docker-compose.yml
Minimal required parameters:
-c, --compose <path> Path to docker-compose.yml
For on-chain KMS, also provide:
--kms <type> KMS type (phala, ethereum, base)
--private-key <key> Private key for deployment
--rpc-url <url> RPC URL for the blockchain
Run with --interactive for guided setup
`),
);
}
}
// 2. Validate the file exists
if (!fs.existsSync(dockerComposePath)) {
throw new Error(`Docker compose file not found: ${dockerComposePath}`);
}
// 3. Read and return the file content
return fs.readFileSync(dockerComposePath, "utf8");
}
const validatePrivateKey = async (
options: Options,
chainId: string | number | undefined,
): Promise<string | undefined> => {
// 1. Get private key from options or environment
let privateKey = options.privateKey || process.env.PRIVATE_KEY;
// 2. Handle on-chain KMS related validations
// If chainId is present, we will perform on-chain operations and require a private key.
if (chainId) {
if (!options.privateKey) {
if (options.interactive) {
const result = await inquirer.prompt([
{
type: "password",
name: "privateKey",
message: "Enter your private key:",
validate: (input: string) =>
input.trim() ? true : "Private key is required",
},
]);
privateKey = result.privateKey;
} else {
throw new Error(
"When using on-chain KMS, either --private-key (or PRIVATE_KEY env) must be provided",
);
}
}
}
return privateKey;
};
function resolveKmsSelection(options: Options): {
kmsType: "PHALA" | "ETHEREUM" | "BASE";
deprecatedKmsId?: string;
} {
if (options.kmsId) {
logger.warn("--kms-id is deprecated. Use --kms instead.");
}
const kmsInput = (options.kms ?? "phala").toLowerCase();
let kmsType: "PHALA" | "ETHEREUM" | "BASE";
switch (kmsInput) {
case "eth":
case "ethereum":
kmsType = "ETHEREUM";
break;
case "base":
kmsType = "BASE";
break;
default:
kmsType = "PHALA";
break;
}
return { kmsType, deprecatedKmsId: options.kmsId };
}
const validateName = async (options: Options): Promise<string | undefined> => {
let name = options.name;
// If name was explicitly provided via --name flag, validate it strictly
if (options.name) {
if (!isValidHostname(options.name)) {
throw new Error(
`Invalid CVM name: "${options.name}". Name must be 5-63 characters, start with letter, and contain only letters/numbers/hyphens.`,
);
}
return options.name;
}
// If no name provided, use directory name with auto-conversion
const folderName = path.basename(process.cwd());
const convertedName = convertToHostname(folderName);
if (!options.interactive) {
// Non-interactive mode: use converted directory name
name = convertedName;
} else {
// Interactive mode: prompt with converted name as default
const result = await inquirer.prompt([
{
type: "input",
name: "name",
message: "Enter a name for the CVM:",
default: convertedName,
validate: (input) => {
if (!input.trim()) return "CVM name is required";
if (!isValidHostname(input.trim())) {
return "Name must be 5-63 characters, start with letter, and contain only letters/numbers/hyphens";
}
return true;
},
},
]);
name = result.name;
}
return name;
};
const resolveEnvVars = async (
options: Options,
): Promise<EnvVar[] | undefined> => {
const envs: EnvVar[] = [];
// 1. Handle deprecated --env-file (backward compatibility)
if (options.envFile && typeof options.envFile === "string") {
logger.warn(
"--env-file is deprecated. Use -e <file> or -e KEY=VALUE instead.",
);
try {
const envContent = fs.readFileSync(options.envFile, { encoding: "utf8" });
envs.push(...parseEnvVars(envContent));
} catch (error) {
throw new Error(
`Error reading environment file ${options.envFile}: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
// 2. Handle new -e parameter (supports both files and KEY=VALUE)
if (options.env && options.env.length > 0) {
const parsed = parseEnvInputs(options.env);
// Load files first (in order)
for (const filePath of parsed.files) {
const resolvedPath = path.resolve(process.cwd(), filePath);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Environment file not found: ${filePath}`);
}
try {
const envContent = fs.readFileSync(resolvedPath, { encoding: "utf8" });
envs.push(...parseEnvVars(envContent));
} catch (error) {
throw new Error(
`Error reading environment file ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
// Add KEY=VALUE pairs (later values override earlier)
envs.push(...parsed.keyValues);
}
// 3. Interactive mode: prompt if no env inputs provided
if (
options.interactive &&
envs.length === 0 &&
!options.env &&
!options.envFile
) {
const { envPath } = await inquirer.prompt([
{
type: "input",
name: "envPath",
message:
"Enter the path to your environment file (leave empty to skip):",
default: "",
validate: (input: string) => {
if (!input || input.trim() === "") {
return true;
}
const filePath = path.resolve(process.cwd(), input);
if (!fs.existsSync(filePath)) {
return `File not found at ${filePath}`;
}
return true;
},
},
]);
if (envPath.trim()) {
const resolvedPath = path.resolve(process.cwd(), envPath.trim());
const envContent = fs.readFileSync(resolvedPath, { encoding: "utf8" });
envs.push(...parseEnvVars(envContent));
}
}
// 4. Return deduplicated envs (later values override earlier)
if (envs.length === 0) {
return undefined;
}
return dedupeEnvVars(envs);
};
/**
* Read SSH public key from file
* - --dev-os: SSH public key is required
* - --non-dev-os: SSH public key only if explicitly specified via --ssh-pubkey
* - Neither flag: Try to read public key, use if available
*/
const readSshPubkey = async (options: Options): Promise<string | undefined> => {
let sshPubkeyPath = options.sshPubkey;
// For --no-dev-os, only use SSH key if explicitly specified
if (options.devOs === false && !options.sshPubkey) {
return undefined;
}
// If not specified, search for default public keys (similar to ssh command)
if (!sshPubkeyPath) {
const homeDir = os.homedir();
const defaultPubKeys = [
path.join(homeDir, ".ssh", "id_rsa.pub"),
path.join(homeDir, ".ssh", "id_ed25519.pub"),
path.join(homeDir, ".ssh", "id_ecdsa.pub"),
path.join(homeDir, ".ssh", "id_dsa.pub"),
];
for (const key of defaultPubKeys) {
if (fs.existsSync(key)) {
sshPubkeyPath = key;
break;
}
}
// If still no key found
if (!sshPubkeyPath) {
// --dev-os requires SSH public key
if (options.devOs) {
throw new Error(
dedent(`
SSH public key is required for dev images but not found.
Searched for:
- ~/.ssh/id_rsa.pub
- ~/.ssh/id_ed25519.pub
- ~/.ssh/id_ecdsa.pub
- ~/.ssh/id_dsa.pub
Please either:
1. Create an SSH key pair: ssh-keygen -t rsa
2. Specify a different key file: --ssh-pubkey <path>
`),
);
}
// For default case (no flags), just skip if no key found
return undefined;
}
} else {
// Expand ~ to home directory
if (sshPubkeyPath.startsWith("~")) {
sshPubkeyPath = path.join(os.homedir(), sshPubkeyPath.slice(1));
}
// Verify key file exists
if (!fs.existsSync(sshPubkeyPath)) {
throw new Error(`SSH public key file not found: ${sshPubkeyPath}`);
}
}
// Read the public key file
try {
const pubkey = fs.readFileSync(sshPubkeyPath, "utf8").trim();
logger.info(`Using SSH public key from ${sshPubkeyPath}`);
return pubkey;
} catch (error) {
throw new Error(
`Failed to read SSH public key from ${sshPubkeyPath}: ${error instanceof Error ? error.message : String(error)}`,
);
}
};
const validateCpuMemoryDiskSize = async (options: Options) => {
let vcpu = DEFAULT_VCPU;
if (options.vcpu) {
try {
vcpu = Number(options.vcpu);
} catch (error) {
throw new Error(
`Invalid vCPU format '${options.vcpu}'. Using default: ${DEFAULT_VCPU}`,
);
}
}
let memoryMB = DEFAULT_MEMORY;
if (options.memory) {
try {
memoryMB = parseMemoryInput(options.memory);
} catch (error) {
throw new Error(
`Invalid memory format '${options.memory}'. Using default: ${DEFAULT_MEMORY}MB`,
);
}
}
let diskSizeGB = DEFAULT_DISK_SIZE;
if (options.diskSize) {
try {
diskSizeGB = parseDiskSizeInput(options.diskSize);
} catch (error) {
throw new Error(
`Invalid disk size format '${options.diskSize}'. Using default: ${DEFAULT_DISK_SIZE}GB`,
);
}
}
return {
vcpu,
memoryMB,
diskSizeGB,
};
};
interface PrivacySettings {
publicLogs: boolean;
publicSysinfo: boolean;
listed: boolean;
}
/**
* Resolve privacy settings with priority: CLI flags > phala.toml > CLI defaults
*/
const resolvePrivacySettings = (
options: Options,
projectConfig?: PrivacyConfig,
): PrivacySettings => {
return {
publicLogs: options.publicLogs ?? projectConfig?.public_logs ?? true,
publicSysinfo:
options.publicSysinfo ?? projectConfig?.public_sysinfo ?? true,
listed: options.listed ?? projectConfig?.listed ?? false,
};
};
/**
* Build provision payload from options
* All parameters are optional - backend will auto-match resources
* @param preResolvedKmsSelection - Optional pre-resolved KMS selection to avoid duplicate calls/warnings
*/
export const buildProvisionPayload = (
options: Options,
name: string,
dockerComposeYml: string,
envs: EnvVar[],
privacySettings: PrivacySettings,
preResolvedKmsSelection?: ReturnType<typeof resolveKmsSelection>,
preLaunchScriptContent?: string,
) => {
const composeFile: Record<string, unknown> = {
name: "", // Required by backend schema, defaults to empty string
docker_compose_file: dockerComposeYml,
allowed_envs: envs?.map((e) => e.key) || [],
public_logs: privacySettings.publicLogs,
public_sysinfo: privacySettings.publicSysinfo,
};
if (preLaunchScriptContent) {
composeFile.pre_launch_script = preLaunchScriptContent;
}
if (options.fs) {
composeFile.storage_fs = options.fs;
}
const payload: Record<string, unknown> = {
name: name,
compose_file: composeFile,
listed: privacySettings.listed,
};
const { kmsType, deprecatedKmsId } =
preResolvedKmsSelection ?? resolveKmsSelection(options);
// Only add user-specified parameters - let backend auto-match the rest
if (options.instanceType) {
payload.instance_type = options.instanceType;
}
if (options.vcpu) {
payload.vcpu = Number(options.vcpu);
}
if (options.memory) {
payload.memory = parseMemoryInput(options.memory);
}
if (options.diskSize) {
payload.disk_size = parseDiskSizeInput(options.diskSize);
}
if (options.nodeId) {
payload.teepod_id = Number(options.nodeId);
}
if (options.region) {
payload.region = options.region;
}
if (options.image) {
payload.image = options.image;
}
// Always set kms type (defaults to PHALA)
payload.kms = kmsType;
// Keep kms_id for backward compatibility if provided
if (deprecatedKmsId) {
payload.kms_id = deprecatedKmsId;
}
// Add prefer_dev flag based on --dev-os / --no-dev-os
// For on-chain KMS (ETHEREUM/BASE), default to non-dev since dev images may not be available
const isOnchainKms = kmsType === "ETHEREUM" || kmsType === "BASE";
if (options.devOs === true) {
payload.prefer_dev = true;
} else if (options.devOs === false || isOnchainKms) {
payload.prefer_dev = false;
}
// If devOs is undefined and not on-chain KMS, don't add prefer_dev (let backend auto-select)
// Add custom app_id if specified
if (options.customAppId) {
payload.app_id = options.customAppId;
// For PHALA KMS, nonce is required with custom app_id
if (kmsType === "PHALA") {
if (!options.nonce) {
throw new Error(
"--nonce is required when using --custom-app-id with PHALA KMS.",
);
}
const nonceNum = Number(options.nonce);
if (Number.isNaN(nonceNum)) {
throw new Error(
`Invalid nonce value: "${options.nonce}". Nonce must be a valid number.`,
);
}
payload.nonce = nonceNum;
}
}
// Validate nonce is not used alone
if (options.nonce && !options.customAppId) {
throw new Error("--nonce requires --custom-app-id to be specified.");
}
return payload;
};
const deployNewCvm = async (
validatedOptions: Options,
docker_compose_yml: string,
envs: EnvVar[],
client: Client<typeof API_VERSION>,
stdout: NodeJS.WriteStream,
stderr: NodeJS.WriteStream,
projectConfig?: PrivacyConfig,
preLaunchScriptContent?: string,
) => {
// Resolve KMS selection once at the start to avoid duplicate calls and warnings
const kmsSelection = resolveKmsSelection(validatedOptions);
const name = await validateName(validatedOptions);
// Read SSH public key and add to environment variables
const sshPubkey = await readSshPubkey(validatedOptions);
const envsWithSshKey = [...(envs || [])];
if (sshPubkey) {
envsWithSshKey.push({
key: "DSTACK_AUTHORIZED_KEYS",
value: sshPubkey,
});
}
// Resolve privacy settings based on options, phala.toml, and dev mode
const privacySettings = resolvePrivacySettings(
validatedOptions,
projectConfig,
);
const payload = buildProvisionPayload(
validatedOptions,
name,
docker_compose_yml,
envsWithSshKey,
privacySettings,
kmsSelection,
preLaunchScriptContent,
);
stdout.write(`Provisioning CVM ${name}...\n`);
// Provision - backend will auto-match resources
const provision_result = await safeProvisionCvm(client, payload);
if (!provision_result.success) {
const formattedError = handleProvisionError(
provision_result.error,
validatedOptions,
);
logger.error("Error in provisioning CVM:", formattedError);
throw provision_result.error;
}
// biome-ignore lint/suspicious/noExplicitAny: type inference issue with @phala/cloud library
const app = provision_result.data as any;
let commit_result;
const provisionKmsInfo = app.kms_info;
const needsOnchainKms =
!app.app_id &&
!!provisionKmsInfo?.chain_id &&
!!provisionKmsInfo?.kms_contract_address;
if (needsOnchainKms) {
if (!provisionKmsInfo?.chain_id || !provisionKmsInfo?.chain) {
throw new Error(
"KMS chain info is missing from provision response. Please retry or contact support.",
);
}
if (!provisionKmsInfo?.kms_contract_address) {
throw new Error(
"KMS contract address is missing from provision response. Please retry or contact support.",
);
}
// Validate private key for on-chain KMS
const privateKey = await validatePrivateKey(
validatedOptions,
provisionKmsInfo.chain_id,
);
// Deploy contract
const deploy_result = await safeDeployAppAuth({
chain: provisionKmsInfo.chain,
rpcUrl: validatedOptions.rpcUrl,
kmsContractAddress: provisionKmsInfo.kms_contract_address,
privateKey: privateKey as `0x${string}`,
deviceId: app.device_id,
composeHash: app.compose_hash,
});
if (!deploy_result.success) {
logger.logDetailedError(deploy_result, "Deploy App Auth");
const errorMsg =
typeof deploy_result === "object" && deploy_result !== null
? JSON.stringify(deploy_result)
: String(deploy_result);
throw new Error(`Deployment contract failed: ${errorMsg}`);
}
// biome-ignore lint/suspicious/noExplicitAny: type inference issue with @phala/cloud library
const deployed_contract = deploy_result.data as any;
// Get encryption key
const kmsRef = provisionKmsInfo.slug || provisionKmsInfo.id;
if (!kmsRef) {
throw new Error(
"KMS reference (slug or id) is missing from provision response",
);
}
const resp = await safeGetAppEnvEncryptPubKey(client, {
app_id: deployed_contract.appId,
kms: kmsRef,
});
if (!resp.success) {
logger.logDetailedError(resp.error, "Get App Env Encrypt PubKey");
throw new Error(
`Failed to get app env encrypt pubkey: ${resp.error.message}`,
);
}
// biome-ignore lint/suspicious/noExplicitAny: type inference issue with @phala/cloud library
const pubkey_signature = resp.data as any;
const encrypted_env_vars = await encryptEnvVars(
envsWithSshKey,
pubkey_signature.public_key,
);
commit_result = await safeCommitCvmProvision(client, {
app_id: deployed_contract.appId,
encrypted_env: encrypted_env_vars,
compose_hash: app.compose_hash,
kms_id: kmsRef,
contract_address: deployed_contract.appAuthAddress,
deployer_address: deployed_contract.deployer,
});
} else {
// Centralized KMS or provision already has app_id
const encrypted_env_vars =
envsWithSshKey && envsWithSshKey.length > 0
? await encryptEnvVars(envsWithSshKey, app.app_env_encrypt_pubkey)
: undefined;
commit_result = await safeCommitCvmProvision(client, {
app_id: app.app_id,
encrypted_env: encrypted_env_vars,
compose_hash: app.compose_hash,
kms_id: kmsSelection.deprecatedKmsId,
});
}
if (!commit_result.success) {
logger.logDetailedError(commit_result.error, "Commit CVM Provision");
throw new Error(
`Failed to commit CVM provision: ${commit_result.error.message}`,
);
}
// biome-ignore lint/suspicious/noExplicitAny: type inference issue with @phala/cloud library
const cvm = commit_result.data as any;
if (validatedOptions?.json !== false) {
stdout.write(
`${JSON.stringify(
{
success: true,
vm_uuid: cvm.vm_uuid,
name: cvm.name,
app_id: cvm.app_id,
dashboard_url: `${CLOUD_URL}/dashboard/cvms/${cvm.vm_uuid}`,
},
null,
2,
)}\n`,
);
} else {
const successMessage = dedent`
CVM created successfully!
CVM ID: ${cvm.vm_uuid}
Name: ${cvm.name}
App ID: ${cvm.app_id}
Dashboard URL: ${CLOUD_URL}/dashboard/cvms/${cvm.vm_uuid}
`;
stdout.write(`${successMessage}\n`);
}
};
const updateCvm = async (
validatedOptions: Options,
docker_compose_yml: string,
envs: EnvVar[] | undefined,
client: Client<typeof API_VERSION>,
stdout: NodeJS.WriteStream,
preLaunchScriptContent?: string,
) => {
const cvm_result = await safeGetCvmInfo(client, {
id: validatedOptions.uuid,
});
if (!cvm_result.success) {
logger.logDetailedError(cvm_result.error, "Get CVM Info");
throw new Error(`Failed to get cvm info: ${cvm_result.error.message}`);
}
// biome-ignore lint/suspicious/noExplicitAny: type inference issue with @phala/cloud library
const cvm = cvm_result.data as any;
// Encrypt env vars before patching (backend stores the full body in Redis for two-phase)
let encrypted_env: string | undefined;
if (envs && envs.length > 0) {
if (cvm.kms_info?.chain_id) {
// On-chain KMS: fetch encrypt pubkey from API
const kmsSlug = cvm.kms_info?.slug || cvm.kms_info?.id;
if (!kmsSlug) {
throw new Error("KMS slug or id is required for decentralized KMS");
}
const resp = await safeGetAppEnvEncryptPubKey(client, {
app_id: cvm.app_id,
kms: kmsSlug,
});
if (!resp.success) {
logger.logDetailedError(resp.error, "Get App Env Encrypt PubKey");
throw new Error(
`Failed to get app env encrypt pubkey: ${resp.error.message}`,
);
}
// biome-ignore lint/suspicious/noExplicitAny: type inference issue with @phala/cloud library
const pubkey_signature = resp.data as any;
encrypted_env = await encryptEnvVars(envs, pubkey_signature.public_key);
} else {
// Centralized KMS: use pubkey from CVM info
if (!cvm.encrypted_env_pubkey) {
throw new Error(
"CVM encrypted_env_pubkey is required for centralized KMS",
);
}
encrypted_env = await encryptEnvVars(envs, cvm.encrypted_env_pubkey);
}
}
// Build unified patch request
const patchBody: Record<string, unknown> = {
id: validatedOptions.uuid,
docker_compose_file: docker_compose_yml,
};
if (preLaunchScriptContent) {
patchBody.pre_launch_script = preLaunchScriptContent;
}
if (envs && envs.length > 0) {
patchBody.allowed_envs = envs.map((env) => env.key);
}
if (encrypted_env) {
patchBody.encrypted_env = encrypted_env;
}
if (validatedOptions.publicLogs !== undefined) {
patchBody.public_logs = validatedOptions.publicLogs;
}
if (validatedOptions.publicSysinfo !== undefined) {
patchBody.public_sysinfo = validatedOptions.publicSysinfo;
}
// Add prepareOnly flag if set
if (validatedOptions.prepareOnly) {
patchBody.prepareOnly = true;
}
logger.info(`Updating CVM ${validatedOptions.uuid}...`);
// biome-ignore lint/suspicious/noExplicitAny: dynamic patch body
const patchResult = await safePatchCvm(client, patchBody as any);
if (!patchResult.success) {
const formattedError = handleProvisionError(