# Export a backup

Choose which vaults to back up and which configured recipients can recover their key material. Each vault has one backup encryption-key assignment. Use the special scope `offchain` for exchange and API keys.

Store the ZIP in durable, immutable storage and keep the corresponding private recovery keys separately, outside the vault.

## Check your permissions

Read `GET /v1/whoami` and inspect:

| Field | What it controls |
|---|---|
| `access_keys_backup_for_vaults` | Scopes whose encrypted keys you can export |
| `configure_vault_backup_encryption_keys_for_vaults` | Scopes whose backup recipient assignment you can change |

The corresponding Administrative Policy types are `access_keys_backup` and `configure_vault_backup_encryption_keys`. Both accept `Any` or an `Only` list of vault IDs, including `offchain`. Export permission does not grant permission to change recipients. Export requires authorization for every selected scope.

## Find a backup encryption-key entry

Your infrastructure administrator supplies the available entries. The API lets you read those entries and assign them to vaults; it does not generate private recovery keys.

```bash
curl --fail-with-body --silent --show-error \
  "$CV_BASE/v1/vault-backup-encryption-keys?limit=100" \
  -H "Authorization: ApiKey $API_KEY_UUID"
```

Each entry has `id`, `display_name`, `public_keys`, and `linked_vault_count`. Each public key identifies a `party_id` and an `encryption_scheme`:

| Scheme | Public-key encoding |
|---|---|
| `hpke` | Raw X25519 public key, hex-encoded |
| `rsa_oaep_sha256_chacha20_poly1305` | RSA public key in PEM SubjectPublicKeyInfo format |

Use `GET /v1/vault-backup-encryption-keys/{id}` to inspect an entry. Use `GET /v1/vault-backup-encryption-keys/{id}/vaults` to list assigned vaults, including `offchain` when assigned. Both list endpoints accept `display_name_like`, `limit`, and `cursor`; pass back `next_cursor` unchanged until it is absent or null.

## Assign an entry to a vault

Read the assignment with `GET /v1/vaults/{vault_id}/backup-encryption-keys`. Submit this body to `PUT /v1/vaults/{vault_id}/backup-encryption-keys`:

```json
{
  "backup_encryption_keys_id": "treasury-recovery"
}
```

Use an entry ID returned by the catalog. For exchange keys, substitute `offchain` for the vault ID. After defining `CV_BASE` and `buildAuthHeaders` from the [Machine User authentication example](/develop/authentication/machine-users), sign and submit the exact body:

```js
async function assignBackupKeys(vaultId, entryId) {
  const path = `/v1/vaults/${encodeURIComponent(vaultId)}/backup-encryption-keys`;
  const body = Buffer.from(JSON.stringify({ backup_encryption_keys_id: entryId }));
  const response = await fetch(`${CV_BASE}${path}`, {
    method: 'PUT',
    headers: {
      ...buildAuthHeaders({ method: 'PUT', path, query: '', body }),
      'Content-Type': 'application/json',
    },
    body,
  });
  if (!response.ok) throw new Error(await response.text());
  if (response.status === 202) {
    const { request_id } = await response.json();
    console.log('Poll this request until completed:', request_id);
  }
}

assignBackupKeys('treasury', 'treasury-recovery').catch(console.error);
```

Assignment changes follow Administrative Policy and may require approval. A `202` response is not a completed assignment. Follow the [request lifecycle](/develop/signing/request-lifecycle), then read the assignment again. The approval operation kind is `put_vault_backup_encryption_keys`.

To clear an assignment, send `{"backup_encryption_keys_id": null}`. This leaves the vault unconfigured: exports that include it fail until an available entry is assigned. A new assignment controls future exports; retain the private keys needed to recover older archives.

## Select the scopes to export

Use the comma-separated `vault_ids` query parameter:

```text
GET /v1/keys-backup?vault_ids=treasury,settlement
```

Every selected scope must have an available assignment, and all selected scopes must use the same backup encryption-key entry. Split exports by entry when vaults have different recipients. Use `GET /v1/vaults?backup_encryption_keys_id=treasury-recovery` to find matching vaults; check `offchain` separately through its assignment endpoint.

Omitting `vault_ids` requests all vaults and `offchain`. It does not restrict the export to your permitted vaults. Prefer an explicit list for scheduled jobs so a newly created or unconfigured vault does not unexpectedly block the job.

## Download the archive

The export is a signed `GET`: include the API key, nonce, timestamp, and assertion. The signature covers the exact query string as well as the path. A successful response is `application/zip`, containing `backup.json`, and produces a `keys_backup_created` audit event.

After defining `CV_BASE` and `buildAuthHeaders` from the [authentication example](/develop/authentication/machine-users), run this Node.js example. It streams the response to a new file and waits for the stream to finish:

```js
const { createWriteStream } = require('node:fs');
const { Readable } = require('node:stream');
const { pipeline } = require('node:stream/promises');

async function exportBackup(vaultIds, outputPath) {
  const path = '/v1/keys-backup';
  const query = new URLSearchParams({ vault_ids: vaultIds.join(',') }).toString();
  const response = await fetch(`${CV_BASE}${path}?${query}`, {
    headers: buildAuthHeaders({ method: 'GET', path, query, body: Buffer.alloc(0) }),
  });
  if (!response.ok) {
    throw new Error(`Export failed (${response.status}): ${await response.text()}`);
  }
  if (!response.headers.get('content-type')?.includes('application/zip')) {
    throw new Error('Expected a ZIP archive');
  }
  await pipeline(Readable.fromWeb(response.body), createWriteStream(outputPath, { flags: 'wx' }));
}

exportBackup(['treasury', 'settlement'], 'backup.zip').catch(error => {
  console.error(error.message);
  process.exitCode = 1;
});
```

## Verify backup format 3

Open `backup.json` from the ZIP and check its `version` before parsing. Format `3` includes:

| Field | Verification |
|---|---|
| `backup_encryption_keys_id` | Matches the intended recipient entry |
| `parties` | Lists the expected party IDs and their encryption keys and schemes |
| `exported_scopes` | Matches the vault IDs and optional `offchain` scope you selected |
| `vaults`, `vault_count` | Includes the selected vault records, root-key shares, and wallet metadata |
| `keys`, `key_count` | Accounts for exported offchain keys when selected |
| `exported_at`, `exported_by`, `checksum` | Records the export metadata |
| `error_logs` | Must be inspected for missing or failed material |

Encrypted shares are associated with recipient party IDs. Keep private recovery keys separate from both the archive and the running deployment.

:::warning\[An HTTP 200 is not proof of a complete backup]
An archive can contain partial results and entries in `error_logs`. Verify expected scopes, keys, wallets, and recipient shares before marking the backup successful. Investigate errors and export again after resolving them.
:::

## Audit and retention

Backup audit metadata records `backup_encryption_keys_id` and `exported_scopes`. Assignment events record the previous and new entry IDs. See [Export the audit log](/develop/audit-export).

Keep immutable copies in separate locations and retain the private recovery keys required by every archive you keep. See [Backup & disaster recovery](/deploy/operations/backup-dr) for deployment and storage guidance.
