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

# Encryption

> Encrypt sensitive organization data with the GatoJS encryption module: AES-256-GCM envelope encryption with a data key per organization, wrapped by ENCRYPTION_MASTER_KEY.

Some data your features store should not be readable from a database dump: an integration's API token, a customer's bank details, notes only the organization may see. The `encryption` module encrypts such values before you write them and decrypts them after you read them. Each organization gets its own data key, so a value encrypted for one organization cannot be decrypted with another organization's key, and deleting an organization deletes its data key.

The module adds no page, route or Docker service. It gives your code two functions, `encryptForOrganization` and `decryptForOrganization`, and the key storage behind them. No other kit module uses it yet; it is there for your features.

## What it doesn't do

* **No key rotation.** Neither the master key nor the data keys can be rotated. See [Changing the master key](#changing-the-master-key).
* **No KMS.** The only provider is `local`: data keys are wrapped with `ENCRYPTION_MASTER_KEY` from the environment.
* **No search on encrypted values.** Every call uses a fresh random IV, so the same plaintext gives a different ciphertext each time. You cannot filter, sort or index by an encrypted column.

Skip the module for data the database must work with (filters, sorting, reports), and for passwords, which you hash instead.

## Requirements

| | `encryption` |
| - | - |
| Required kit modules | None. |
| Services (Docker, CI) | None. |
| Environment variables | `ENCRYPTION_MASTER_KEY`, required; `ENCRYPTION_PROVIDER`, optional. |
| npm dependencies | None. The crypto code is the workspace package `@gatojs/crypto` in `packages/crypto/`, copied with the module. |
| Database | `organization_data_keys` table, so a migration after adding the module. |

## Install and remove

> [tab] Existing project
>
> **1. Add the module**
>
> ```bash theme={null}
> npx gato add encryption
> ```
>
> This copies the module files and `packages/crypto/`, adds `dataKey OrganizationDataKey?` to `Organization` in the `wa:relations` region, adds the variables to `.env.example`, runs `gato generate` and `npm install`.
>
> **2. Create the migration**
>
> ```bash theme={null}
> npx prisma migrate dev --name add-encryption
> ```
>
> **3. Set the master key in .env**
>
> `gato add` does not touch `.env`. Before you start the app, set `ENCRYPTION_PROVIDER=local` (copy it from `.env.example`) and a generated `ENCRYPTION_MASTER_KEY` (see [Configure the master key](#configure-the-master-key)): with the provider set, startup validation rejects a missing key. The example key works in development only: production rejects it, and data encrypted under it cannot move to another key.

> [tab] New project
>
> ```bash theme={null}
> npx create-gato-app@latest acme-app --modules encryption
> ```
>
> `gato create` writes a random `ENCRYPTION_MASTER_KEY` to `.env` ([generated secrets](https://docs.gatojs.com/cli/create.md#generated-secrets)). The first migration creates the `organization_data_keys` table.

### Removing the module

`npx gato remove encryption` removes the module files. The `organization_data_keys` table stays until you create and apply a migration that drops it. Every value another feature encrypted becomes unreadable without the module and its keys, so decrypt or delete that data first.

## Configure the master key

| Variable | Required | Rule |
| - | - | - |
| `ENCRYPTION_PROVIDER` | No | `local`, also when blank or unset. Any other value stops the server. |
| `ENCRYPTION_MASTER_KEY` | Yes | 32 bytes: 64 hex characters, or base64 of exactly 32 bytes. Surrounding whitespace is trimmed. With `NODE_ENV=production` it must not be the `.env.example` value. |

Generate a key:

```bash theme={null}
openssl rand -hex 32
```

A 64-character hex string is read as hex first, because it is also valid base64 (of 48 bytes). A base64 key of any length other than 32 bytes is rejected with a message that shows how to generate one.

The key is checked by the module's `env.ts`, so a missing, malformed or example key stops the server at startup with a report that names `ENCRYPTION_MASTER_KEY` ([Environment variables](https://docs.gatojs.com/configuration/environment-variables.md#at-startup)).

> [!WARNING]
>
> **If the master key is lost, every encrypted value is lost.** Keep it in a secret store, back it up together with the database (the [self-hosting backup](https://docs.gatojs.com/deployment/self-hosting.md#back-up) includes it in `.env.selfhost`), and use a different key per environment.

## Use it from your code

```ts src/features/integrations/services/commands/save-integration.ts theme={null}
"use server";

import { encryptForOrganization } from "@/features/encryption/services/organization-encryption";
import { getOrgContext } from "@/shared/lib/auth/org-context";
import { assertServiceModeConfirmed } from "@/shared/lib/auth/service-mode";
import { prisma } from "@/shared/lib/prisma";

export async function saveIntegrationCommand(input: unknown, confirmation?: unknown) {
  const context = await getOrgContext();
  assertServiceModeConfirmed(context, confirmation);
  const { token } = saveIntegrationSchema.parse(input);
  const secret = await encryptForOrganization(context.organizationId, token);
  await prisma.integration.create({
    data: { organizationId: context.organizationId, secret },
  });
  // …
}
```

| Function | Behavior |
| - | - |
| `encryptForOrganization(organizationId, plaintext)` | Returns the ciphertext as a base64 string. Creates the organization's data key on first use. |
| `decryptForOrganization(organizationId, ciphertext)` | Returns the plaintext. Throws `OrganizationDataKeyMissingError` when the organization has no data key (it never creates one), and an error when the ciphertext belongs to another organization or was changed. |

Rules:

* Take `organizationId` from `getOrgContext()` or `requireModuleAccess()`, never from the request.
* The functions are services, not server actions. The command that calls them checks permissions and [service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md#service-mode).
* Store the ciphertext in a `String` column; it is base64 and longer than the plaintext.
* If your feature cannot work without encryption, list `encryption` in its manifest's `requires`.

## How it works

### Envelope format

Values are encrypted with AES-256-GCM and stored as `base64(IV (12 bytes) ‖ ciphertext ‖ auth tag (16 bytes))`. Decryption rejects a payload shorter than 28 bytes and any payload whose tag does not verify: a changed byte or the wrong key. A test decrypts a fixed vector, so the format cannot change by accident; every stored value depends on it.

### Data keys

Each organization has at most one `OrganizationDataKey` row (`organizationId` is unique). The row holds the organization's data key, wrapped (encrypted) with the master key in the same envelope format. It is created on the first `encryptForOrganization` for that organization. The key is stored before any value is encrypted, so no value is encrypted under a key that was never saved.

When several requests encrypt for a new organization at once, each generates a key and tries to store it. Only the first insert wins; the others fail on the unique `organizationId` (Prisma's `P2002`). `encryptForOrganization` catches that error, reads the stored row again and encrypts with it, so every concurrent first call ends up on the key that was stored first. You don't need to retry. If that read finds no row, the `P2002` error is thrown; any other error is thrown unchanged. The module's integration test runs 10 concurrent first encryptions for one organization.

Every query on the table filters by `organizationId`, and the [tenant-scope guard](https://docs.gatojs.com/concepts/organizations.md) rejects one that doesn't. The row is deleted with its organization (`onDelete: Cascade`), so the live database can no longer decrypt that organization's values. A database backup taken earlier still holds the wrapped data key, and the master key can unwrap it. Permanent erasure also needs those backups and any other copies of the key row to expire or be deleted.

### Startup check and probe

Startup validation checks only the format of the key. The first `encryptForOrganization` or `decryptForOrganization` in a process also runs a probe: it generates a data key, unwraps it and compares the bytes. If the probe fails, every call throws `EncryptionUnavailableError` with the reason, before touching the database.

### Changing the master key

There is no rotation. A different `ENCRYPTION_MASTER_KEY` passes the startup check and the probe, because both only test the key itself. But every stored data key was wrapped with the old key, so each `encryptForOrganization` and `decryptForOrganization` for an organization that already has a data key throws. Don't change the master key of an environment that has encrypted data.

### Moving data to another environment

A data key is stored wrapped with the master key, so the database alone is not enough. To move the data to another environment, such as a restore on a new server or a copy into staging, set the same `ENCRYPTION_MASTER_KEY` there. With another key, every stored data key fails to unwrap. The [`api-keys`](https://docs.gatojs.com/modules/api-keys) module has the same rule for `API_KEY_PEPPER`. Keep both secrets with every backup of the database.

## Testing

Your feature's integration tests can call the functions on a real database. The test setup files (`src/test/integration/setup-env.ts`, `e2e/env.ts`) set `ENCRYPTION_MASTER_KEY`. Test isolation the same way as for any organization data: encrypt for organization A, then check that decrypting with organization B's id fails.

The module's own tests cover the fixed vector, tampering, key parsing, a separate key per organization, 10 concurrent first encryptions and the cascade delete. `packages/crypto/src/` and `src/features/encryption/services/` are on the `critical` list of the [mutation gate](https://docs.gatojs.com/guides/ai-agents.md#the-mutation-gate).

## Reference

| File | Export | Purpose |
| - | - | - |
| `src/features/encryption/services/organization-encryption.ts` | `encryptForOrganization`, `decryptForOrganization`, `OrganizationDataKeyMissingError` | The API for features. |
| `src/features/encryption/services/encryption-key-provider.ts` | `encryptionKeyProvider`, `ensureEncryptionAvailable` | The provider from `ENCRYPTION_MASTER_KEY` and the one-time probe. |
| `src/features/encryption/env.ts` | `envSchema` | Validation of both variables. |
| `prisma/schema/encryption.prisma` | `OrganizationDataKey` | Table `organization_data_keys`. |
| `packages/crypto/` | `@gatojs/crypto`: `encryptContent`, `decryptContent`, `parseMasterKey`, `LocalKeyProvider`, `probeEncryptionProvider`, `EncryptionUnavailableError` | The envelope format, key parsing and the provider interface. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.