Encrypted Fields
The problem
Section titled “The problem”Events are immutable. The library never updates or deletes them, and that is what makes the event log a reliable history. Some data does not fit that model:
- personal data that has to be erased when the person asks for it;
- secrets the app has to read back later, such as API tokens or OAuth refresh tokens, which should not sit in plaintext in the database and its backups;
- data of a tenant that leaves;
- data that may only be kept for a fixed retention period.
Encrypted fields solve this without touching the event log. You mark a field as encrypted, and the library stores only ciphertext in the event. To make the data unreadable, you destroy its key. The events stay as they are, but the field can never be decrypted again, including in future replays. This is called crypto-shredding.
How it works
Section titled “How it works”import { createAggregateRoot } from '@requence/event-sourcing'
export const customer = createAggregateRoot('customer') .withInitialState({ registered: false }) .withEvents(({ z, encrypted }) => ({ CustomerRegistered: z.object({ name: encrypted(z.string(), { keyId: ({ streamId }) => `user:${streamId}` }), email: encrypted(z.email(), { keyId: ({ streamId }) => `user:${streamId}` }), country: z.string(), }), })) .withEventHandlers((state) => ({ onCustomerRegistered() { state.registered = true }, })) .withCommands((state, event) => ({ register(data: { name: string; email: string; country: string }) { if (state.registered) { throw new Error('Customer is already registered') } return event('CustomerRegistered', data) }, }))- Every encrypted field has a key ID, returned by its
keyIdresolver. Here, all personal fields of a customer share the key IDuser:<streamId>. - Each key ID gets its own random 256-bit data key, created the first time a value is encrypted under it. Values are encrypted with AES-256-GCM. The key ID is bound to the ciphertext, so a value cannot be moved to another key ID unnoticed.
- Data keys are never stored in plaintext. They are encrypted (“wrapped”) with a master key that only your app knows, and stored in a key store next to your events (envelope encryption). The master key never reaches the database.
eventStore.destroyKey(keyId)deletes the wrapped data key. From then on, every field encrypted under that key ID reads asnull.
Unencrypted fields, such as country above, stay readable, so the event history, statistics and replays keep working after a key was destroyed.
The event store needs the encryption option as soon as an aggregate root declares an encrypted field. Without it, the store refuses to initialize and never appends plaintext:
import { createEventStore, memoryKeyStore } from '@requence/event-sourcing/memory'import { customer } from './customer'
const eventStore = createEventStore({ aggregateRoots: [customer], encryption: { masterKeys: process.env.MASTER_KEYS, keyStore: memoryKeyStore(), },})Each driver ships a persistent key store: drizzleKeyStore and surrealKeyStore. Generate a master key with:
openssl rand -base64 32Choosing key IDs
Section titled “Choosing key IDs”The key ID decides what disappears together. Destroying a key ID makes every field encrypted under it unreadable, across all events and all aggregate roots. Pick it by asking: what has to become unreadable at the same time?
| Use case | Key ID | Destroyed when |
|---|---|---|
| Personal data, erasable on request | user:<id> | The person asks for erasure. |
| Secrets the app reads back (API tokens, OAuth refresh tokens) | tenant:<id> or integration:<id> | The tenant leaves or the integration is removed. |
| Tenant offboarding | tenant:<id> | The tenant’s contract ends. |
| Retention periods | retention:<companyId>:<year> | The retention period for that year ends. |
The resolver receives the stream and the validated payload, so a key ID can depend on the event’s content:
.withEvents(({ z, encrypted }) => ({ InvoiceIssued: z.object({ companyId: z.string(), fiscalYear: z.int(), customerName: encrypted(z.string(), { keyId: ({ payload }) => `retention:${payload.companyId}:${payload.fiscalYear}`, }), }),}))A field has exactly one key ID. If data is subject to two rules, for example erasure on request and a retention period, decide which one governs it.
After destroyKey(), a new event with the same key ID gets a fresh data key. Old values stay unreadable, new ones are readable again.
Alternative: keep the data out of events
Section titled “Alternative: keep the data out of events”Encryption is not the only option. You can keep confidential data in an ordinary, mutable table and only put its ID into events. Deleting the row deletes the data.
| Prefer a mutable table when… | Prefer encrypted fields when… |
|---|---|
| the data changes often or has to be searched, sorted or filtered; | the data is part of what happened and belongs into the event; |
| single values have to be corrected or deleted; | projections, process managers or listeners need it, also in replays; |
| the data is large (files, documents). | you want one mechanism for erasure, offboarding and retention. |
Both can be combined: keep searchable data in a table, and encrypted fields for data that belongs to the history.
What handlers see
Section titled “What handlers see”| Where | Type of an encrypted field | Value |
|---|---|---|
Commands (event('…', payload)) | T | Plaintext. Encrypted before the event is stored. |
Aggregate event handlers, snapshots, loadStream filters | EncryptedValue | The stored ciphertext, never plaintext. |
| Projections, process managers, event listeners | T | null | Plaintext, or null once the key was destroyed. |
eventStore.decryptEvent(event) | T | null | Same as above, for raw events, e.g. exports. |
Aggregates never see plaintext. Their state and snapshots therefore hold no confidential data, and they fold the same state before and after a key is destroyed.
- Always handle
null. Every encrypted field can turn intonullin a later replay. Read models need nullable columns for them. - Never base aggregate decisions on encrypted fields. Aggregates only see ciphertext. If a rule depends on a value, for example “email must be unique”, check it in a read model before calling the command, or keep a separate, unencrypted fact (
emailVerified: boolean) in the event. - Process managers and listeners must skip side effects when a value is
null. A replay or refresh after an erasure must not send an email tonull, and must not fail on it either. - Don’t log decrypted payloads. Logs, error trackers and analytics tools receive plaintext if you pass them events from handlers.
destroyKey()does not change your read models. It only drops projection snapshots of projections that handle an encrypted field. Remove the data from your read models yourself, for example with an erasure event that your projections handle, or by replaying them.
Learn more
Section titled “Learn more”- Personal Data and Erasure: a complete GDPR example.
encrypted()reference: supported positions, versioned events and types.encryptionoption: master keys, key stores and multiple instances.