# Node.js

_Encrypt data server-side, invoke Functions, Enclaves and proxy requests through Relay._

> Encrypting/Decrypting data with our backend SDKs may expose you to greater
>   compliance burden because your server needs to handle plaintext data. Instead,
>   we recommend using [Relay](/relay) or our [Client-Side SDKs](/sdks) to encrypt
>   data.

## Getting started

### Install the SDK

First, let's install the Evervault SDK using your package manager of choice.

### Initialize the SDK

Now, let's initialize the SDK using our app's ID and our app's API key. If you don't have an API key yet, you can get one by creating an App in the [Evervault Dashboard](https://app.evervault.com).

```javascript
const Evervault = require("@evervault/sdk");
const evervault = new Evervault("<APP_ID>", "<API_KEY>");
```

## Relay proxies

SDKs that support using proxies can be configured to use Relay, use the `createRelayHttpsAgent()` function to return a pre-configured `HTTPSProxyAgent`. The Agent will use the HTTP CONNECT protocol to establish a connection to Relay. Below is how you would configure Relay with the Stripe Node.js SDK.

```javascript
const httpsAgent = evervault.createRelayHttpsAgent();

const stripe = Stripe("sk_test_...", {
  maxNetworkRetries: 1,
  httpAgent: httpsAgent,
  timeout: 1000,
  host: "api.example.com",
  port: 123,
  telemetry: true,
});
```

The `HTTPSProxyAgent` can also be used with popular HTTP clients like [axios](https://github.com/axios/axios). Its important to note that the URL of the request is not the Relay URL but the URL of the target.

```javascript
// Send a singular request with encrypted data to a third-party API
const httpsAgent = evervault.createRelayHttpsAgent();
const payload = { sensitiveField: "sensitive value" };
const response = await axios.post("https://example.com", payload, {
  httpsAgent,
  headers: {
    "Content-Type": "application/json",
  },
});
```

## Reference

### Evervault

You have to pass your app's ID and API key to initialize the SDK. You can also pass an `options` object with additional configuration settings.

```javascript
const Evervault = require("@evervault/sdk");
const evervault = new Evervault("<APP_ID>", "<API_KEY>");
```

**Parameters**

- `appId` `String` _(required)_ — Your Evervault App's ID.
- `apiKey` `String` _(required)_ — Your Evervault app's API key.
- `options` `Object` — An optional configuration object.
  - `options.httpAgent` `http.Agent` — A custom Node.js [HTTP Agent](https://nodejs.org/api/http.html#class-httpagent) used for all outbound HTTP SDK requests. This can be used for local development or testing if you need to mock responses from Evervault, but don't use it in production systems.
  - `options.httpsAgent` `https.Agent` — A custom Node.js [HTTPS Agent](https://nodejs.org/api/https.html#class-httpsagent) used for all outbound HTTPS SDK requests. Use this when you need granular control over networking behavior, such as connection pooling, keep-alive settings, or routing requests through an HTTP proxy. When omitted, the SDK uses the default global agent.

#### Using a custom agent

You can pass a custom agent to control connection behavior for all requests made by the SDK. This is useful for scenarios such as connection pooling with `keepAlive`, or routing SDK traffic through a corporate proxy.

```javascript
const https = require("https");
const Evervault = require("@evervault/sdk");

// Keep connections alive to reduce latency on subsequent requests
const agent = new https.Agent({ keepAlive: true });

const evervault = new Evervault("<APP_ID>", "<API_KEY>", { httpsAgent: agent });
```

To route SDK requests through an HTTP proxy, use a proxy agent library such as [https-proxy-agent](https://www.npmjs.com/package/https-proxy-agent).

```javascript
const { HttpsProxyAgent } = require("https-proxy-agent");
const Evervault = require("@evervault/sdk");

const agent = new HttpsProxyAgent("https://proxy.example.com:8080");

const evervault = new Evervault("<APP_ID>", "<API_KEY>", { httpsAgent: agent });
```

### encrypt()

Encrypts data using [Evervault Encryption](/developers/evervault-encryption).

To encrypt strings using the Node.js SDK, simply pass a String or an Object into the evervault.encrypt() function. To encrypt a file, pass a `Buffer`.

The encrypted data can be stored in your database or file storage as normal. Evervault Strings can be used across all of our products. Evervault File Encryption is currently in Beta, and files can only be decrypted with [Relay](/relay).

```javascript
const Evervault = require("@evervault/sdk");
const evervault = new Evervault("<APP_ID>", "<API_KEY>");

// encrypt a string
const encrypted = await evervault.encrypt("Hello, world!");

// encrypt a file
const fileContents = fs.readFileSync("<input-file>");
const encryptedFile = await evervault.encrypt(fileContents);
fs.writeFileSync("<output-file>", encryptedFile);
```

**Parameters**

- `data` `String | Boolean | Number | Object | Buffer` _(required)_ — The data to encrypt.

### decrypt()

Decrypts data previously encrypted with the `encrypt()` function or through [Relay](/relay). An API key with the `decrypt` permission must be used to perform this operation.

```javascript
const Evervault = require("@evervault/sdk");
const evervault = new Evervault("<APP_ID>", "<API_KEY>");

const encrypted = await evervault.encrypt("Hello, world!");
const decrypted = await evervault.decrypt(encrypted);
console.log(decrypted);
// Hello, world!
```

**Parameters**

- `data` `String | Object | Buffer` _(required)_ — The data to decrypt.

> **PCI Compliance**
>
> Decrypting data with our backend SDKs is not available if you are part of the PCI or HIPAA compliance use cases. Instead you can:
>
> - Use [Relay](/relay) to decrypt data before it reaches third-party services.
> - Use [Functions](/functions) or [Enclaves](/enclaves) to process encrypted data.

### createClientSideDecryptToken()

Client Side Decrypt Tokens are versatile and short-lived tokens that frontend applications can utilise to decrypt data previously encrypted through Evervault. Client Side Decrypt Tokens are restricted to specific payloads.

By default, a Client Side Decrypt Token will live for 5 minutes into the future. The maximum time to live of the token is 10 minutes into the future.

```javascript
const encryptedData = await evervault.encrypt("foo");
const now = new Date();
const timeInFiveMinutes = now.setMinutes(now.getMinutes() + 5);

const token = await evervault.createClientSideDecryptToken(
  encryptedData,
  timeInFiveMinutes
);
```

**Parameters**

- `payload` `String | Object | Buffer` _(required)_ — The payload containing the encrypted data that the token will be used to decrypt.
- `timeToLive` `Number` — The time the token will expire. Defaults to 5 minutes in the future.

### run()

Lets you invoke an Evervault [Function](/functions) with a given payload.

```javascript
const Evervault = require("@evervault/sdk");
const evervault = new Evervault("<APP_ID>", "<API_KEY>");

const result = await evervault.functions.run("hello-function", {
  name: "Claude Shannon",
  ssn: "ev:encrypted_string",
});
```

**Parameters**

- `functionName` `String` _(required)_ — The name of the function to invoke.
- `data` `Object` _(required)_ — The payload to pass to the function.

Successful Function runs will return an object containing a Function Run ID and the result from your Function in the following format:

```json
{
  "id": "func_run_09413338da56",
  "status": "success",
  "result": {
    "message": "Hello from a Function! It seems you have 14 letters in your name",
    "name": "ev:RFVC:TTLHY04oVJlBuvPx:A7MeNriTKFES0Djl9uKaPvHCAn9PjSfOHu7tswXFCHF9:jwYKE13o3iQlr6Dn/DRk80XpNOGb:$"
  }
}
```

### createRunToken()

Creates a single use, time bound token (5 minutes) for invoking an Evervault [Function](/functions) with a given payload. Run Tokens can be used to invoke an Evervault Function client-side without providing a sensitive API Key.

```javascript
const Evervault = require("@evervault/sdk");
const evervault = new Evervault("<APP_ID>", "<API_KEY>");

const runToken = await evervault.createRunToken("hello-function", {
  name: "Claude Shannon",
  ssn: "ev:encrypted_string",
});
```

**Parameters**

- `functionName` `String` _(required)_ — The name of the function to invoke.
- `data` `Object` — The data you want to send to the function. If not provided, a run token will be created, and the payload will not be validated when the function is executed.

When you create a Run Token, the SDK will return a JSON object containing your token.

```json
{
  "token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsInZlciI6IjAuMCJ9.eyJhcHBVdWlkIjoiYXBwX2RmZGE3MmUwMTZiMCIsImZ1bmN0aW9uTmFtZSI6ImhlbGxvLWZ1bmN0aW9uIiwicnVuSWQiOiI0YjI4ZjMzZS1lNzY2LTQyNjgtYjZmNi01MmM2ZDNlZjBkM2MiLCJleHAiOjE3NjcyMjU2MDB9.gCiFw7UJ8gjZfeXNEaqX4H1Y9HBX9avjioZ4yDU8PTtmGT4QTzVOhnDV46v_yyXLxpO1BgzoBRpYbLciiW1_QXSLmx6cCuJy4vHUZwssHT13vB7AXIl_88Ab5R7w9vpOQIDoCjhPVWJsolwUiiGh_5yE4wGv6WPTIfSv249_hpJLMz3AAffXUckiLPxFporY73KXtTANQH_zniivB91KdBnyGhle7gTs1EXWLqpdMIrqOz9cmoXU31DGd-AgeMzM082s_XtdCFq7FNLLtg6Nx8Mx8Bjl0cKV41R-jbTpHSXxutLX-PSDmWn5wSqDhlQoEWdTLsoS6xp7qhZ2urYyYg"
}
```

Run Tokens can then be used to authenticate Function runs from the client-side.

```javascript
fetch("https://api.evervault.com/functions/[function-name]/runs", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `RunToken [run-token]`,
  },
  body: JSON.stringify({
    payload: {
      ssn: "encrypted_string",
    },
  }),
});
```

### enableOutboundRelay()

> We recommend using the `createRelayHttpsAgent()` function instead of this
>   function if the SDK you are using supports proxy agents.

Automatically configures your application to proxy requests through Relay when making requests to domains you have configured Relays for inside of the Evervault Dashboard. See [Relay](/relay) to learn more.

```javascript
await evervault.enableOutboundRelay();
```

**Parameters**

- `options.decryptionDomains` `String[]` — Requests sent to any of the domains listed will be proxied through Relay. This will override the configuration created in the Evervault dashboard.
- `options.debugRequests` `Boolean` — Output request domains and whether they were sent through Relay.

### createRelayHttpsAgent()

The HTTPSProxyAgent allows for more granular control over what requests gets sent through Relay. This can be passed to any client that supports the [Node.js Agent](https://nodejs.org/api/http.html#class-httpagent) as a parameter.

```javascript
const axios = require("axios");
const httpsAgent = evervault.createRelayHttpsAgent();
const payload = { sensitiveField: "sensitive value" };
const response = await axios.post("https://example.com", payload, {
  httpsAgent,
  headers: {
    "Content-Type": "application/json",
  },
});
```

### createEnclaveHttpsAgent()

Returns a HTTPS Agent which can be used to attest all TLS connections to your Evervault Enclave. See Enclave's [TLS Attestation](/enclaves#attestation) to learn more.

```javascript
const AttestationBindings = require("@evervault/attestation-bindings");

const enclaveHttpsAgent = await evervault.createEnclaveHttpsAgent(
  {},
  AttestationBindings
);

const response = await axios.post(
  "https://my-enclave.my-app.enclave.evervault.com",
  encrypted,
  {
    httpsAgent: enclaveHttpsAgent,
  }
);
```

**Parameters**

- `enclaveAttestationData` `Object` — A mapping of Enclave names to their PCRs or Callbacks which resolve to PCRs. This is optional. When included, the connection will only be attested when the PCRs match exactly. The provided data can be either a single Object, or an Array of Objects to allow roll-over between different sets of PCRs. If not provided, the attestation doc and its signature will be validated but the PCRs will be ignored.
  - `enclaveAttestationData.[enclaveName].pcr0` `String` — The PCR0 to use when attesting the given Enclave. Defaults to undefined.
  - `enclaveAttestationData.[enclaveName].pcr1` `String` — The PCR1 to use when attesting the given Enclave. Defaults to undefined.
  - `enclaveAttestationData.[enclaveName].pcr2` `String` — The PCR2 to use when attesting the given Enclave. Defaults to undefined.
  - `enclaveAttestationData.[enclaveName].pcr8` `String` — The PCR8 to use when attesting the given Enclave. Defaults to undefined.
- `evervaultAttestationBindings` — The Evervault Attestation Bindings distributed as `@evervault/attestation-bindings` on npm. For testing, you can provide a mock object with a single async attestEnclave function.

#### Using static PCRs

The most simple way to set up your Evervault client to attest Enclaves is to provide hardcoded PCRs. This approach is not recommended for production deployments, as your clients will fall out of sync from the Enclave during deployments.

```javascript
const AttestationBindings = require("@evervault/attestation-bindings");
const enclaveHttpsAgent = await evervault.createEnclaveHttpsAgent({
  "my-enclave": {
    pcr0: "...",
    pcr1: "...",
    pcr2: "...",
    pcr8: "...",
  },
  AttestationBindings,
});
```

#### Using the Evervault API as a PCR Provider

The Evervault API exposes an endpoint to retrieve the PCRs for all active deployments of an Enclave. This can be used to keep your Client in sync with your Enclave across deployments.

```javascript
const AttestationBindings = require("@evervault/attestation-bindings");
const axios = require("axios");

async function resolveEnclavePCRsFromEvervaultAPI() {
  const { data: responseBody } = await axios.get(
    "https://api.evervault.com/enclaves/my-enclave/attestation",
    {
      headers: {
        "x-evervault-app-id": "app_1234", // replace with your app uuid
      },
    }
  );
  /**
   * The API Responds with the enclave attestation under the top level data key:
   * { "data": [{ "pcr0": "...",  ... }] }
   */
  return responseBody.data;
}

const enclaveHttpsAgent = await evervault.createEnclaveHttpsAgent(
  {
    "my-enclave": resolveEnclavePCRsFromEvervaultAPI,
  },
  AttestationBindings
);
```

