Crypto TypeORM
    Preparing search index...

    Crypto TypeORM

    crypto-typeorm logo

    @sebastienrousseau/crypto-typeorm

    TypeORM column-level encryption with a single decorator, powered by crypto-lib.

    Build Coverage Registry Docs OpenSSF Scorecard License: Apache-2.0 OR MIT Node.js 22 or newer


    Getting started

    • Install — installation via pnpm, npm, or yarn
    • Requirements — runtime floor and environment prerequisites
    • Quick Start — minimal working usage sample

    The Crypto Service ecosystem

    Package reference

    Operational


    pnpm add @sebastienrousseau/crypto-typeorm
    # or
    npm install @sebastienrousseau/crypto-typeorm
    # or
    yarn add @sebastienrousseau/crypto-typeorm

    Back to Top


    • Node.js: ^22.0.0 or >=24.0.0 (active and maintenance LTS releases)
    • Package Manager: pnpm >=9 (recommended) or npm >=10
    • TypeScript: >=5.0 (when compiling with TypeScript)

    Back to Top


    import { Entity, PrimaryGeneratedColumn } from "typeorm";
    import { EncryptedColumn } from "@sebastienrousseau/crypto-typeorm";

    @Entity()
    class User {
    @PrimaryGeneratedColumn()
    id!: number;

    @EncryptedColumn({
    encrypt: { key: process.env.COLUMN_ENCRYPTION_KEY! },
    })
    ssn!: string;
    }

    That is it. The ssn column is stored as an XChaCha20-Poly1305 sealed box (Base64) and decrypted transparently on every read.

    Back to Top


    Crypto Service provides a complete cryptography stack across 14 specialized packages:

    Package Role Description
    @sebastienrousseau/crypto-api API docs Postman collection types and a Postman-to-Markdown converter; the server's API contract is its OpenAPI document.
    @sebastienrousseau/crypto-benchmarks Benchmarks Benchmarks comparing classical and post-quantum cryptography: ops/sec, latency and throughput.
    @sebastienrousseau/crypto-cbom CBOM Cryptographic Bill of Materials generator and auditor (CycloneDX 1.6, SPDX 3.0).
    @sebastienrousseau/crypto-cli Terminal CLI Command-line interface: hashing, key generation, encryption, signing, HPKE, Argon2id and CBOM scans, with an interactive menu.
    @sebastienrousseau/crypto-edge Edge Runtime Edge-runtime cryptographic operations using the Web Crypto API, optimized for Cloudflare Workers, Vercel Edge, and Deno.
    @sebastienrousseau/crypto-kms Cloud KMS Unified KMS interface: AWS KMS, Google Cloud KMS, Vault Transit and local providers; Azure is a stub.
    @sebastienrousseau/crypto-lib Core Library Core library: post-quantum ML-KEM, ML-DSA and SLH-DSA, plus classical, modern and OpenPGP cryptography for TypeScript.
    @sebastienrousseau/crypto-lsp IDE Analysis Language server that flags weak and quantum-vulnerable cryptography in the editor, with quick fixes.
    @sebastienrousseau/crypto-mcp AI Agents Model Context Protocol server exposing cryptography tools to AI assistants and agents.
    @sebastienrousseau/crypto-middleware Middleware Cryptographic middleware for Express and Fastify: decrypt requests, encrypt responses, verify HMAC signatures and JWTs.
    @sebastienrousseau/crypto-prisma ORM Adapter Transparent field-level encryption extension for Prisma Client, powered by XChaCha20-Poly1305.
    @sebastienrousseau/crypto-react React Hooks React hooks and context provider for client-side cryptographic operations with zero boilerplate.
    @sebastienrousseau/crypto-sdk Client SDK A zero-dependency, typed HTTP client for the Crypto Service REST API, with full post-quantum support.
    @sebastienrousseau/crypto-server HTTP API A hardened Fastify REST API for cryptographic operations, with rate limiting, OpenAPI schemas, and post-quantum endpoints.
    @sebastienrousseau/crypto-testing Test Support Deterministic keys, fast mocks, and test fixtures for crypto-lib
    @sebastienrousseau/crypto-typeorm (this package) ORM Adapter TypeORM column-level encryption with a single decorator, powered by crypto-lib.
    @sebastienrousseau/crypto-vue Vue Composables Vue 3 composables for client-side cryptography
    @sebastienrousseau/crypto-wasm Acceleration Placeholder for a WebAssembly accelerator; no WebAssembly module ships yet.

    Back to Top


    crypto-typeorm provides column-level encryption for TypeORM entities. Three integration styles are available: a @EncryptedColumn decorator that combines TypeORM's @Column with automatic encryption/decryption, an EncryptionSubscriber for centralised field configuration, and an EncryptionTransformer for manual ValueTransformer usage. All styles use XChaCha20-Poly1305 via crypto-lib's secretbox, with fresh random nonces on every write.

    Back to Top


    All APIs accept an EncryptionConfig object:

    Property Type Default Description
    key string required 256-bit key as a 64-char hex string
    algorithm string "xchacha20-poly1305" Algorithm identifier
    fields Map<string, string[]> undefined Per-entity field list (used by EncryptionSubscriber)
    context string "" Column context bound into each ciphertext (Entity.property); set by @EncryptedColumn
    allowPlaintextFallback boolean false Return values that are not ciphertexts as-is instead of throwing; for plaintext migrations only
    acceptLegacyCiphertext boolean false Read ciphertexts written before the v2: format, only while re-writing them

    @EncryptedColumn reads process.env.TYPEORM_ENCRYPTION_KEY when no key is provided in decorator options.

    New values are written as v2: followed by the Base64 sealed box (24-byte nonce, ciphertext, 16-byte Poly1305 tag):

    • Encryption key. Values are sealed under a subkey derived from key with HKDF-SHA-256 (info crypto-typeorm/enc/v2), not under key itself.
    • Associated data. Each value is bound to crypto-typeorm/v2:<context>. @EncryptedColumn uses ClassName.property and EncryptionSubscriber uses EntityName.field, so a ciphertext copied into another column or entity fails to decrypt. The primary key is not bound: a ValueTransformer never sees the row, and generated keys do not exist yet at insert time, so two rows can still have the same column's value swapped. A bare EncryptionTransformer without context binds the empty context, shared with every other context-less transformer; pass context explicitly.
    • Class names. The default context comes from the class name. If a bundler renames classes, pin encrypt.context (or keep class names) so values written before and after the build still match.
    • Fail closed. A value that does not decrypt throws FieldDecryptionError (exported; it carries context and never the stored value), from EncryptionTransformer.from() and from EncryptionSubscriber.afterLoad. allowPlaintextFallback: true returns a value that is not a ciphertext at all as-is, for the duration of a plaintext migration; a v2: value that fails authentication is rejected even then.
    • Legacy values. Ciphertexts written by earlier versions (bare Base64, sealed with key and no associated data) are refused unless acceptLegacyCiphertext: true, and never written. They are not bound to a column. Rewrite them in the v2: format (as examples/migration.ts does for plaintext: read each value, write it back through the transformer), then set remove acceptLegacyCiphertext.

    Back to Top


    A property decorator that combines TypeORM's @Column with an EncryptionTransformer.

    @EncryptedColumn()                              // uses TYPEORM_ENCRYPTION_KEY env var
    @EncryptedColumn({ encrypt: { key: "..." } }) // explicit key
    @EncryptedColumn({ type: "text", nullable: true, encrypt: { key: "..." } })
    @EncryptedColumn({ encrypt: { key: "...", context: "User.ssn" } }) // pinned context

    Each value is bound to ClassName.property unless encrypt.context is given.

    Back to Top


    An EntitySubscriberInterface that encrypts/decrypts fields based on a centralised configuration.

    import { DataSource } from "typeorm";
    import { EncryptionSubscriber } from "@sebastienrousseau/crypto-typeorm";

    const ds = new DataSource({
    subscribers: [
    new EncryptionSubscriber({
    key: process.env.COLUMN_ENCRYPTION_KEY!,
    fields: new Map([
    ["User", ["ssn", "email"]],
    ["Payment", ["cardNumber"]],
    ]),
    }),
    ],
    });
    Hook Behaviour
    beforeInsert Encrypts configured fields in-place
    beforeUpdate Encrypts configured fields in-place
    afterLoad Decrypts configured fields in-place

    afterLoad throws FieldDecryptionError when a stored value is not a valid ciphertext for EntityName.field. To load rows that still hold plaintext during a gradual migration, set allowPlaintextFallback: true until every row has been rewritten.

    Back to Top


    A standard TypeORM ValueTransformer for manual use on any @Column.

    import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
    import { EncryptionTransformer } from "@sebastienrousseau/crypto-typeorm";

    const transformer = new EncryptionTransformer({
    key: process.env.COLUMN_ENCRYPTION_KEY!,
    context: "Secret.value",
    });

    @Entity()
    class Secret {
    @PrimaryGeneratedColumn()
    id!: number;

    @Column({ type: "text", transformer })
    value!: string;
    }
    Method Input Output
    to(value) plaintext or null v2: Base64 sealed box or null
    from(value) stored ciphertext or null plaintext string or null; throws FieldDecryptionError

    Back to Top


    All examples are self-contained TypeScript files in the examples/ directory. Run any example with:

    npx ts-node examples/<name>.ts
    
    Category Example Purpose
    Decorator decorator.ts Using @EncryptedColumn on entity fields
    Subscriber subscriber.ts Centralised encryption via EncryptionSubscriber
    Transformer transformer.ts Manual ValueTransformer on @Column
    Migration migration.ts Encrypting existing plaintext columns

    Back to Top

    Back to Top


    pnpm --filter @sebastienrousseau/crypto-typeorm run build
    pnpm --filter @sebastienrousseau/crypto-typeorm run test
    pnpm --filter @sebastienrousseau/crypto-typeorm run lint
    pnpm --filter @sebastienrousseau/crypto-typeorm run format

    All 18 packages in the Crypto Service workspace maintain a 100% coverage floor across statements, branches, functions, and lines.

    Back to Top


    Report vulnerabilities privately via GitHub Security Advisories or according to SECURITY.md. Never report security issues publicly.

    Cryptographic operations use the @noble/* libraries, Node.js crypto and OpenPGP.js. @noble/post-quantum has not been independently audited and does not guarantee constant-time execution, and no module in this suite is FIPS 140-3 validated. Key zeroization is limited: JavaScript strings and garbage-collected buffers cannot be reliably wiped. See SECURITY.md.

    Back to Top


    Back to Top


    Versions advance strictly one step at a time on the 0.0.x line (v0.0.1 → v0.0.2 → v0.0.3 ... → v0.0.999 → v0.1.0). Work for every release iteration begins on a dedicated feat/v<version> branch.

    All 18 packages in the workspace move in lockstep. Public API signatures, cipher output formats, and serialization schemas are strictly versioned. Breaking changes to serialized formats or algorithm defaults are considered major breaking changes. Minimum toolchain upgrades (e.g. Node.js LTS floor) are governed by POLICIES.md.

    Back to Top


    Dual-licensed under Apache 2.0 or MIT, at your option.

    Copyright (c) 2022-2026 Sebastien Rousseau and The Crypto Service Suite contributors.

    Back to Top