> ## Documentation Index
> Fetch the complete documentation index at: https://docs.phala.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cloud JS SDK

> JavaScript/TypeScript SDK for Phala Cloud API — manage CVMs, deployments, and resources programmatically.

The `@phala/cloud` SDK provides a type-safe JavaScript/TypeScript client for the Phala Cloud API. It includes built-in API versioning, Zod schema validation, and comprehensive error handling.

## Installation

```bash theme={"system"}
npm install @phala/cloud
```

```bash theme={"system"}
pnpm add @phala/cloud
```

```bash theme={"system"}
yarn add @phala/cloud
```

## Quick Start

```typescript theme={"system"}
import { createClient } from "@phala/cloud";

const client = createClient({ apiKey: "phak_your_api_key" });

// Get current user info
const user = await client.getCurrentUser();
console.log(user.user.username);

// List all CVMs
const cvms = await client.getCvmList();
console.log(cvms.items);
```

## Client Creation

### `createClient(config?)`

Creates a full-featured client with all action methods.

```typescript theme={"system"}
import { createClient } from "@phala/cloud";

// Minimal — reads API key from PHALA_CLOUD_API_KEY env var
const client = createClient();
```

```typescript theme={"system"}
// Explicit configuration
const client = createClient({
  apiKey: "phak_your_api_key",
  baseURL: "https://cloud-api.phala.com/api/v1",
  version: "2026-01-21",
  timeout: 30000,
});
```

### Configuration Options

| Option            | Type                     | Default                              | Description                                                               |
| ----------------- | ------------------------ | ------------------------------------ | ------------------------------------------------------------------------- |
| `apiKey`          | `string`                 | `PHALA_CLOUD_API_KEY` env var        | API key for authentication                                                |
| `baseURL`         | `string`                 | `https://cloud-api.phala.com/api/v1` | API base URL (or `PHALA_CLOUD_API_PREFIX` env var)                        |
| `version`         | `ApiVersion`             | `"2026-01-21"`                       | [API version](/phala-cloud/references/cloud-js-sdk/api-versioning) to use |
| `timeout`         | `number`                 | `30000`                              | Request timeout in milliseconds                                           |
| `useCookieAuth`   | `boolean`                | `false`                              | Use cookie-based auth instead of API key                                  |
| `headers`         | `Record<string, string>` | —                                    | Additional request headers                                                |
| `onResponseError` | `function`               | —                                    | Custom response error handler                                             |

### Tree-Shaking with `createBaseClient`

For smaller bundles, use `createBaseClient` with individual action imports:

```typescript theme={"system"}
import { createBaseClient, getCurrentUser, getCvmList } from "@phala/cloud";

const client = createBaseClient({ apiKey: "phak_your_api_key" });

// Call actions as standalone functions
const user = await getCurrentUser(client);
const cvms = await getCvmList(client);
```

### Extending the Base Client

`createClient` already includes all built-in actions as methods. The `.extend()` method on `createBaseClient` is useful when you want to selectively include actions (for tree-shaking) or add your own custom actions:

```typescript theme={"system"}
import { createBaseClient, getCurrentUser, getCvmList } from "@phala/cloud";

const client = createBaseClient({ apiKey: "phak_your_api_key" }).extend({
  getCurrentUser,
  getCvmList,
});

// Only the actions you included are available as methods
const user = await client.getCurrentUser();
```

## Available Actions

Actions marked with **V** return different response types depending on the client's [API version](/phala-cloud/references/cloud-js-sdk/api-versioning).

### Authentication & User

| Method                   | Description                                   |
| ------------------------ | --------------------------------------------- |
| `getCurrentUser()` **V** | Get current user, workspace, and credits info |

### CVM Query

| Method                           | Description                         |
| -------------------------------- | ----------------------------------- |
| `getCvmList(request?)` **V**     | List all CVMs (paginated)           |
| `getCvmInfo(request)` **V**      | Get single CVM details              |
| `getCvmStats(request)`           | Get CVM system stats                |
| `getCvmNetwork(request)`         | Get CVM network info                |
| `getCvmState(request)`           | Get CVM current state               |
| `getCvmDockerCompose(request)`   | Get Docker Compose config           |
| `getCvmComposeFile(request)`     | Get compose file content            |
| `getCvmContainersStats(request)` | Get container stats                 |
| `getCvmAttestation(request)`     | Get TEE attestation                 |
| `getCvmPreLaunchScript(request)` | Get pre-launch script               |
| `getCvmStatusBatch(request)`     | Get status of multiple CVMs         |
| `getCvmUserConfig(request)`      | Get user-level CVM config           |
| `checkCvmIsAllowed(request)`     | Check on-chain deployment allowance |

### CVM Lifecycle

| Method                        | Description                     |
| ----------------------------- | ------------------------------- |
| `provisionCvm(request)`       | Create a new CVM                |
| `commitCvmProvision(request)` | Commit a CVM provision          |
| `startCvm(request)`           | Start a CVM                     |
| `stopCvm(request)`            | Stop a CVM                      |
| `shutdownCvm(request)`        | Shutdown a CVM                  |
| `restartCvm(request)`         | Restart a CVM                   |
| `deleteCvm(request)`          | Delete a CVM                    |
| `replicateCvm(request)`       | Create a copy of a CVM          |
| `watchCvmState(request)`      | Watch CVM state changes via SSE |

### CVM Configuration

| Method                                   | Description                          |
| ---------------------------------------- | ------------------------------------ |
| `updateCvmEnvs(request)`                 | Update environment variables         |
| `updateDockerCompose(request)`           | Update Docker Compose config         |
| `updatePreLaunchScript(request)`         | Update pre-launch script             |
| `updateCvmResources(request)`            | Update resource allocation           |
| `updateCvmVisibility(request)`           | Update visibility settings           |
| `updateOsImage(request)`                 | Update OS image                      |
| `getAvailableOsImages(request?)`         | List available OS images             |
| `provisionCvmComposeFileUpdate(request)` | Provision a compose file update      |
| `commitCvmComposeFileUpdate(request)`    | Commit a compose file update         |
| `patchCvm(request)`                      | Unified partial CVM update           |
| `confirmCvmPatch(request)`               | Confirm on-chain KMS patch (Phase 2) |
| `commitCvmUpdate(request)`               | Commit update with token (multisig)  |
| `refreshCvmInstanceId(request)`          | Refresh a CVM instance ID            |
| `refreshCvmInstanceIds(request)`         | Batch refresh CVM instance IDs       |

### Apps

| Method                           | Description                               |
| -------------------------------- | ----------------------------------------- |
| `getAppList(request?)` **V**     | List apps                                 |
| `getAppInfo(request)` **V**      | Get app details                           |
| `getAppCvms(request)` **V**      | List CVMs for an app                      |
| `getAppRevisions(request)`       | List app revision history                 |
| `getAppRevisionDetail(request)`  | Get app revision details                  |
| `getAppFilterOptions()`          | Get available filter options for app list |
| `getAppAttestation(request)`     | Get app TEE attestation                   |
| `getAppDeviceAllowlist(request)` | Get app device allowlist status           |
| `checkAppIsAllowed(request)`     | Check on-chain app allowance              |
| `checkAppCvmsIsAllowed(request)` | Batch check app CVMs allowance            |

### Workspace

| Method                        | Description                   |
| ----------------------------- | ----------------------------- |
| `listWorkspaces(request?)`    | List workspaces               |
| `getWorkspace(request)`       | Get workspace details         |
| `getWorkspaceNodes(request)`  | Get workspace nodes           |
| `getWorkspaceQuotas(request)` | Get workspace resource quotas |

### Nodes, Instance Types & OS Images

| Method                             | Description                       |
| ---------------------------------- | --------------------------------- |
| `getAvailableNodes()`              | List available TEE nodes          |
| `listAllInstanceTypeFamilies()`    | List all instance type families   |
| `listFamilyInstanceTypes(request)` | List instance types in a family   |
| `getOsImages(request?)`            | List public OS images (paginated) |

### KMS (Key Management)

| Method                            | Description                   |
| --------------------------------- | ----------------------------- |
| `getKmsInfo(request)`             | Get KMS info                  |
| `getKmsList(request?)`            | List KMS instances            |
| `getKmsOnChainDetail(request)`    | Get on-chain KMS details      |
| `getAppEnvEncryptPubKey(request)` | Get env encryption public key |
| `nextAppIds(request?)`            | Get next available app IDs    |

### SSH Keys

| Method                                | Description                         |
| ------------------------------------- | ----------------------------------- |
| `listSshKeys()`                       | List SSH keys                       |
| `createSshKey(request)`               | Add an SSH key                      |
| `deleteSshKey(request)`               | Remove an SSH key                   |
| `importGithubProfileSshKeys(request)` | Import SSH keys from GitHub profile |
| `syncGithubSshKeys()`                 | Sync SSH keys from GitHub           |

### On-Chain Contract Actions

These functions interact directly with the blockchain, not the Phala Cloud API. They require ETH for gas (write operations) or a public client (read operations).

| Method                               | Description                                 |
| ------------------------------------ | ------------------------------------------- |
| `deployAppAuth(request)`             | Deploy an AppAuth smart contract            |
| `addComposeHash(request)`            | Register a compose hash on-chain            |
| `addDevice(request)`                 | Add a device to the on-chain allowlist      |
| `removeDevice(request)`              | Remove a device from the on-chain allowlist |
| `setAllowAnyDevice(request)`         | Toggle the allow-any-device flag            |
| `getAllowedDevices(request)`         | Query the on-chain device allowlist         |
| `checkDeviceAllowed(request)`        | Check if a device is allowed on-chain       |
| `checkComposeHashAllowed(request)`   | Check if a compose hash is allowed on-chain |
| `checkOnChainPrerequisites(request)` | Batch check all on-chain prerequisites      |

## Safe Methods

Every action has a `safe` variant that returns a `SafeResult` instead of throwing:

```typescript theme={"system"}
const result = await client.safeGetCvmInfo({ id: "cvm-abc123" });

if (result.success) {
  console.log(result.data);
} else {
  console.error(result.error.message);
}
```

The `SafeResult` type:

```typescript theme={"system"}
type SafeResult<T, E = SafeError> =
  | { success: true; data: T; error?: never }
  | { success: false; data?: never; error: E };
```

## Custom Schema Validation

Every action accepts an optional `schema` parameter for custom response validation.

For actions **without** required request parameters, pass `schema` as the first argument:

```typescript theme={"system"}
import { z } from "zod";

const MySchema = z.object({ username: z.string() });
const user = await client.getCurrentUser({ schema: MySchema });
// user is typed as { username: string }

// Disable validation (returns unknown)
const raw = await client.getCurrentUser({ schema: false });
```

For actions **with** required request parameters, pass `schema` as the second argument:

```typescript theme={"system"}
const MyCvmSchema = z.object({ id: z.string(), name: z.string() });
const cvm = await client.getCvmInfo({ id: "cvm-abc123" }, { schema: MyCvmSchema });
```

## Event Handling

Listen for error events across all API calls:

```typescript theme={"system"}
client.on("error", (error) => {
  console.error("API Error:", error.message);
});

// Listen once
client.once("error", (error) => {
  console.error("First error:", error.message);
});

// Remove listener
client.off("error", handler);
```

## Debug Logging

Enable detailed cURL-format request/response logging:

```bash theme={"system"}
DEBUG=phala::api-client node your-script.js
```

## Environment Variables

| Variable                 | Description                |
| ------------------------ | -------------------------- |
| `PHALA_CLOUD_API_KEY`    | API key for authentication |
| `PHALA_CLOUD_API_PREFIX` | Base URL for the API       |

## Webhook Signature Verification

The SDK provides utilities for verifying webhook signatures, exported from a separate subpath to avoid bundling `node:crypto` into browser builds:

```typescript theme={"system"}
import { verifyWebhookSignature, parseWebhookEvent } from "@phala/cloud/webhook";

// Verify a single signature
const isValid = verifyWebhookSignature({
  secret: "whsec_...",
  timestamp: req.headers["x-webhook-timestamp"],
  body: rawBody,
  signature: req.headers["x-webhook-signature"],
});

// Or parse and verify in one step
const event = parseWebhookEvent({
  headers: req.headers,
  body: rawBody,
  secret: "whsec_...",
});
```

See [Webhooks](/phala-cloud/references/webhooks) for full payload format and delivery behavior.

## Related

* [API Versioning](/phala-cloud/references/cloud-js-sdk/api-versioning) — version management and migration
* [Schema Reference](/phala-cloud/references/cloud-js-sdk/schema-reference) — response schema details per version
* [Error Handling](/phala-cloud/references/cloud-js-sdk/error-handling) — error classes and safe methods
* [Webhooks](/phala-cloud/references/webhooks) — webhook events, signatures, and delivery
* [Cloud API Reference](/phala-cloud/phala-cloud-api/overview) — full REST API docs
