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

# Verifying enclave attestations

> Request an AWS Nitro attestation document alongside a response from the Privy API to verify its execution within the TEE

> [!NOTE]
>
> Please reach out to [sales@privy.io](mailto:sales@privy.io) to enable access to this feature.

Privy signs wallet operations inside an AWS Nitro Enclave. Setting a header on a supported request
returns a Nitro attestation document alongside the response. An app verifies that document to confirm
the operation ran inside the enclave.

> [card] [Request an attestation](#requesting-an-attestation)
>
> Set the nonce header and read the document from the response.

> [card] [Verify an attestation](#verifying-the-document)
>
> Check the certificate chain, signature, nonce, and response hash.

> [card] [Supported operations](#supported-operations)
>
> See which endpoints attest their responses today.

## Two levels of verification

Attestation supports two checks. Each one proves something different.

**Signature verification** is self-serve. An app sets a header, pulls the AWS Nitro root
certificate, and checks the document. This proves three facts:

* **Nitro hardware.** A certificate chain rooted in the AWS Nitro Enclaves root certificate signs
  the document, so it came from real Nitro hardware.
* **Response binding.** The enclave hashed the operation result into the document, so the attested
  result cannot be swapped for a different one after the fact.
* **Freshness.** The enclave echoed the caller's nonce into the document, so a previously captured
  attestation cannot be replayed for a new request.

**Code verification** also binds the response to a known Privy enclave build. It compares the
attested `PCR0` value against an image Privy supplies. This check is not self-serve. Privy
grants access to its AWS account so that an app can pull enclave builds.

> [!WARNING]
>
> Signature verification alone proves that some Nitro enclave signed the response, not that Privy's
> enclave signed it. An attacker running their own Nitro Enclave could intercept a request and
> return a substituted document that passes every signature check. Closing that gap requires
> [verifying the enclave code](#verifying-the-enclave-code), which Privy supports on request.

## Requesting an attestation

Set the `privy-enclave-attestation-nonce` header on a supported request. The nonce must be 8 to 128
characters, using alphanumeric, base64 (`+`, `/`, `=`), dash, or underscore characters. Apps should
use a fresh random nonce per request.

```bash theme={"system"}
curl --request POST https://api.privy.io/v1/wallets \
  --user "<your-privy-app-id>:<your-privy-app-secret>" \
  --header "privy-app-id: <your-privy-app-id>" \
  --header "privy-enclave-attestation-nonce: $(openssl rand -hex 16)" \
  --header "Content-Type: application/json" \
  --data '{"chain_type": "ethereum"}'
```

The enclave returns the document in the `privy-enclave-signature` response header, formatted as
`deflate:<base64>`. The value is a deflate-compressed, base64-encoded CBOR attestation document.

Requests that omit the nonce header behave exactly as before. The enclave then builds nothing.

### Error values

When the enclave cannot build a document, the `privy-enclave-signature` header carries an error code.
The request itself still succeeds, so apps that require attestation must check the header.

| Header value | Meaning |
| - | - |
| `attestation-nonce-invalid` | The nonce was present but failed the length or character rules |
| `attestation-not-supported` | The endpoint does not yet attest its response |
| `attestation-failed` | The enclave could not build the document |

## Document contents

Once decoded, the document follows the [AWS Nitro attestation
format](https://docs.aws.amazon.com/enclaves/latest/user/verify-root.html). AWS sets and
documents `module_id`, `timestamp`, `digest`, `pcrs`, `certificate`, and `cabundle`. Two of those
fields behave in ways the AWS docs do not cover:

* `module_id` changes whenever Privy replaces an enclave, so it is not a stable deployment identity.
* `public_key` is absent, because Privy does not use it for key exchange.

Privy controls the remaining two fields:

| Field | Meaning |
| - | - |
| `nonce` | The UTF-8 bytes of the nonce sent in the request. Proves the enclave built this document for this request. |
| `user_data` | JSON object binding the response and the enclave's long-lived keys. See below. |

### Verifying the enclave code

Platform configuration registers (PCRs) measure what the enclave booted. `PCR0` measures the entire
enclave image file, so it identifies the exact image that ran. It is also the value Privy's KMS
key policy is bound to. Secrets only decrypt for an image whose `PCR0` matches the approved value.
AWS documents the remaining registers under [cryptographic
attestation](https://docs.aws.amazon.com/enclaves/latest/user/set-up-attestation.html).

Comparing `PCR0` against a known-good value is what proves the enclave ran Privy's code. Privy does
not publish those values, so an app has two options:

* **Reproducible build.** Privy supplies the Docker image for an enclave release on request. Build
  the enclave image file from it, then compare the resulting `PCR0` to the attested value. The
  enclave build is deterministic, so a match shows exactly which code signed the response. Ask for an
  image at [security@privy.io](mailto:security@privy.io).
* **Pinning.** Record the `PCR0` observed across requests and alert on a change. This detects an
  image change. But it does not show what the image contains.

Nitro keys registers by integer, so `pcrs` may decode as a `Map` rather than a plain object. Read
index 0 for `PCR0` and hex-encode the bytes before comparing.

### User data

`user_data` holds a JSON object with four fields:

```json theme={"system"}
{
  "privy_enclave_response_sha256": "<hex sha256 of the attested payload>",
  "privy_client_nonce": "<the nonce sent by the caller>",
  "privy_dek_public_key_sha256": "<hex sha256 of the enclave data encryption public key>",
  "privy_integrity_signature_key_sha256": "<hex sha256 of the integrity signing key, domain separated>"
}
```

| Field | Meaning |
| - | - |
| `privy_enclave_response_sha256` | SHA-256 over the exact JSON string the enclave attested, which binds this document to one specific result. Property order matters and the string omits whitespace. Without checking it, a valid document proves only that some enclave signed something. |
| `privy_client_nonce` | The nonce from the request, echoed back. Confirms the document is fresh rather than a replay of an earlier response. It duplicates the top-level `nonce` field, and either can be checked. |
| `privy_dek_public_key_sha256` | SHA-256 of the public half of the enclave's data encryption key, which encrypts wallet key shares at rest. |
| `privy_integrity_signature_key_sha256` | SHA-256 of the key the enclave uses to sign wallet governance records such as wallets, policies, and key quorums, so the enclave detects tampering that happens outside it. Privy hashes this key with a domain separator. |

The two key hashes describe the enclave deployment rather than the request. They stay the same until
the enclave's key material changes. Recording them across requests therefore lets an app detect a
rotation or an unexpected change in key setup.

## Verifying the document

Verification has five steps:

1. Strip the `deflate:` prefix, base64-decode the remainder, and inflate it to raw CBOR bytes.
2. Decode the `COSE_Sign1` structure, which is a four element array of protected header,
   unprotected header, payload, and signature. The payload is the CBOR attestation document.
3. Validate the certificate chain. Confirm that `cabundle[0]` is the AWS Nitro Enclaves root
   certificate, that each certificate's predecessor signed it, and that the final bundle entry signed
   the leaf `certificate`. This proves AWS issued the certificate.
4. Verify the `COSE_Sign1` signature against the leaf certificate, then compare `privy_client_nonce`
   and `privy_enclave_response_sha256` in `user_data` against the nonce sent and the attested payload.
   This proves an enclave produced the response and that nothing altered it in flight.
5. Read `PCR0` from the document, then compare or pin it as described under [verifying the enclave
   code](#verifying-the-enclave-code). Skipping this step leaves the response unbound from Privy's
   enclave.

Steps 1 through 4 use standard Nitro primitives, which AWS covers in [verifying the root of
trust](https://docs.aws.amazon.com/enclaves/latest/user/verify-root.html). Two details matter here.
The `COSE_Sign1` signature is ES384 over the CBOR encoding of
`["Signature1", protectedHeader, <empty bytes>, payload]` ([RFC 8152 section
4.4](https://datatracker.ietf.org/doc/html/rfc8152#section-4.4)). The raw 96-byte value needs DER
conversion first. And `cabundle[0]` must match the AWS Nitro Enclaves root certificate (Root-G1). AWS
publishes it at `https://aws-nitro-enclaves.amazonaws.com/AWS_NitroEnclaves_Root-G1.zip`, with this
SHA-256 fingerprint:

```
64:1A:03:21:A3:E2:44:EF:E4:56:46:31:95:D6:06:31:7E:D7:CD:CC:3C:17:56:E0:98:93:F3:C6:8F:79:BB:5B
```

### Example

This example verifies an attestation returned with a wallet creation response. It requires the `cbor`
and `@scure/base` packages.

```typescript verify-attestation.ts theme={"system"}
import {base64} from '@scure/base';
import * as cbor from 'cbor';
import {createHash, createVerify, X509Certificate} from 'crypto';
import {inflateSync} from 'zlib';

const AWS_NITRO_ROOT_FINGERPRINT =
  '64:1A:03:21:A3:E2:44:EF:E4:56:46:31:95:D6:06:31:7E:D7:CD:CC:3C:17:56:E0:98:93:F3:C6:8F:79:BB:5B';

/** Converts a raw P-384 ECDSA signature (r || s) into the DER encoding Node.js expects. */
function ecdsaRawToDer(signature: Uint8Array): Buffer {
  const encodeInteger = (bytes: Uint8Array): Buffer => {
    let start = 0;
    while (start < bytes.length - 1 && bytes[start] === 0) start++;
    const trimmed = bytes.slice(start);
    const needsPadding = (trimmed[0]! & 0x80) !== 0;
    return needsPadding ? Buffer.concat([Buffer.from([0x00]), trimmed]) : Buffer.from(trimmed);
  };

  const r = encodeInteger(signature.slice(0, 48));
  const s = encodeInteger(signature.slice(48, 96));
  const body = Buffer.concat([Buffer.from([0x02, r.length]), r, Buffer.from([0x02, s.length]), s]);
  return Buffer.concat([Buffer.from([0x30, body.length]), body]);
}

export function verifyAttestation({
  attestationHeader,
  expectedNonce,
  attestedPayload
}: {
  attestationHeader: string;
  expectedNonce: string;
  attestedPayload: string;
}) {
  // 1. Decompress the header value into raw COSE bytes.
  const compressed = base64.decode(attestationHeader.replace(/^deflate:/, ''));
  const coseBytes = inflateSync(Buffer.from(compressed));

  // 2. Decode the COSE_Sign1 envelope and the attestation document it carries.
  const [protectedHeader, , payload, signature] = cbor.decodeFirstSync(coseBytes);
  const document = cbor.decodeFirstSync(payload);

  // 3. Validate the certificate chain against the AWS Nitro root.
  const bundle = document.cabundle.map(
    (cert: Uint8Array) => new X509Certificate(Buffer.from(cert))
  );
  const leaf = new X509Certificate(Buffer.from(document.certificate));
  const root = bundle[0];

  if (root.fingerprint256 !== AWS_NITRO_ROOT_FINGERPRINT) {
    throw new Error('cabundle[0] is not the AWS Nitro root certificate');
  }
  if (!root.verify(root.publicKey)) throw new Error('AWS Nitro root is not self signed');
  for (let i = bundle.length - 1; i > 0; i--) {
    if (!bundle[i].verify(bundle[i - 1].publicKey)) {
      throw new Error(`Certificate chain is invalid at cabundle[${i}]`);
    }
  }
  if (!leaf.verify(bundle[bundle.length - 1].publicKey)) {
    throw new Error('Leaf certificate is not signed by the chain');
  }

  // 4. Verify the ES384 signature over the COSE Sig_structure.
  const toBeSigned = cbor.encodeOne(['Signature1', protectedHeader, Buffer.alloc(0), payload]);
  const verifier = createVerify('SHA384');
  verifier.update(toBeSigned);
  if (!verifier.verify(leaf.publicKey, ecdsaRawToDer(signature))) {
    throw new Error('COSE signature verification failed');
  }

  // 5. Confirm the nonce and the attested payload hash.
  const userData = JSON.parse(new TextDecoder().decode(document.user_data));
  if (userData.privy_client_nonce !== expectedNonce) throw new Error('Nonce mismatch');

  const expectedHash = createHash('sha256').update(attestedPayload).digest('hex');
  if (userData.privy_enclave_response_sha256 !== expectedHash) {
    throw new Error('Attested payload hash mismatch');
  }

  return {
    pcrs: document.pcrs,
    moduleId: document.module_id,
    timestamp: document.timestamp,
    dekPublicKeyHash: userData.privy_dek_public_key_sha256,
    integritySignatureKeyHash: userData.privy_integrity_signature_key_sha256
  };
}
```

Calling it for wallet creation looks like this. Read the response with `text()` rather than `json()`,
because the hash covers the exact bytes Privy returned.

```typescript {skip-check} theme={"system"}
const nonce = crypto.randomUUID();
const response = await fetch('https://api.privy.io/v1/wallets', {
  method: 'POST',
  headers: {
    Authorization: `Basic ${basicAuth}`,
    'privy-app-id': appId,
    'privy-enclave-attestation-nonce': nonce,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({chain_type: 'ethereum'})
});

const rawBody = await response.text();
const wallet = JSON.parse(rawBody);

const result = verifyAttestation({
  attestationHeader: response.headers.get('privy-enclave-signature')!,
  expectedNonce: nonce,
  attestedPayload: rawBody
});

console.log(`Wallet ${wallet.id} was created inside enclave ${result.moduleId}`);
```

If the response carries an entity object or a `custody` field, normalize it before hashing. Rebuild
the object rather than deleting from the parsed body, so that `entity` keeps its position:

```typescript {skip-check} theme={"system"}
const {custody, ...rest} = JSON.parse(rawBody);
const attestedPayload = JSON.stringify({...rest, entity: null});
```

For most endpoints the attested payload is a minimal projection of the result rather than the full
response body. A `personal_sign` response, for example, attests
`JSON.stringify({signature: body.data.signature})`. Privy supplies the exact projection for each
operation on request.

## Supported operations

Attestation is currently available on:

* Wallet creation, wallet updates, and wallet deletion
* Key quorum creation, updates, and deletion
* Signing methods on `POST /v1/wallets/{wallet_id}/rpc` and `POST /v1/wallets/rpc`
* `POST /v1/wallets/{wallet_id}/raw_sign`

Policy creation and updates, policy rule changes, batch wallet creation, and
`POST /v1/users/{user_id}/wallets` do not attest their responses yet. Requesting attestation on those
endpoints returns `attestation-not-supported`. To attest a wallet creation, call the single wallet
creation endpoint instead.

### Methods that cannot be verified

These methods do more than sign. The enclave signs, then Privy performs work outside the enclave such
as nonce management, gas sponsorship, or broadcasting:

* `eth_sendTransaction`
* `signAndSendTransaction`
* `tron_sendTransaction`
* `wallet_sendCalls`
* `eth_sign7702Authorization`

The enclave does attest the signing step. But the response body returns the result of the wider
operation, not the signed artifact. An app cannot rebuild the attested payload, so the hash check
cannot pass.

> [!TIP]
>
> To attest a transaction, sign it with `eth_signTransaction`, `signTransaction` for Solana, or
> `tron_signTransaction`, verify the attestation, then broadcast the signed transaction separately.

## Limitations

* The attestation travels in a response header, so an app must read the header and the body from the
  same response. Privy's server SDKs do not expose the header, so verification requires a raw HTTP
  client.
* The enclave builds each attestation on demand and keeps no copy. Apps that need an audit trail
  should store the header value alongside the response they verified.
* Attestation failures never fail the underlying request. Apps that treat attestation as mandatory
  must enforce that themselves.

Questions about attestation, or about verifying a specific document, can go to
[security@privy.io](mailto:security@privy.io).
