Crypto Prisma
    Preparing search index...

    Crypto Prisma

    crypto-prisma logo

    @sebastienrousseau/crypto-prisma

    Transparent field-level encryption extension for Prisma Client, powered by XChaCha20-Poly1305.

    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-prisma
    # or
    npm install @sebastienrousseau/crypto-prisma
    # or
    yarn add @sebastienrousseau/crypto-prisma

    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 { PrismaClient } from "@prisma/client";
    import { createEncryptionMiddleware } from "@sebastienrousseau/crypto-prisma";

    const prisma = new PrismaClient();

    prisma.$use(
    createEncryptionMiddleware({
    key: process.env.FIELD_ENCRYPTION_KEY!, // 64-char hex (256-bit)
    encryptedFields: [
    { model: "User", fields: ["email", "phone"] },
    { model: "Patient", fields: ["ssn", "diagnosis"] },
    ],
    }),
    );

    // Usage is completely transparent:
    const user = await prisma.user.create({
    data: { name: "Alice", email: "alice@example.com", phone: "+1-555-0100" },
    });
    // email and phone are encrypted in the database
    // but returned as plaintext to your application
    console.log(user.email); // "alice@example.com"

    Or use the Client Extension (Prisma 4.16+):

    import { PrismaClient } from "@prisma/client";
    import { createFieldEncryptionExtension } from "@sebastienrousseau/crypto-prisma";

    const prisma = new PrismaClient().$extends(
    createFieldEncryptionExtension({
    key: process.env.FIELD_ENCRYPTION_KEY!,
    encryptedFields: [{ model: "User", fields: ["email", "phone"] }],
    }),
    );

    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 (this package) 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 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-prisma provides transparent field-level encryption for Prisma ORM. It intercepts write operations (create, update, upsert, createMany) to encrypt configured fields with XChaCha20-Poly1305 before they reach the database, and decrypts them transparently on read. A deterministic HMAC-SHA-256 mode enables exact-match queries on encrypted columns. Both the classic $use() middleware and the modern $extends() Client Extension API are supported.

    Back to Top


    Feature Detail
    Encrypt on write create, createMany, update, updateMany, and upsert fields are encrypted with XChaCha20-Poly1305 (secretbox) before reaching the database. Each write uses a fresh random 24-byte nonce.
    Decrypt on read findUnique, findFirst, findMany (and the OrThrow variants) results are decrypted transparently, as are the records returned by create, update, and upsert.
    Bound ciphertexts Every value is sealed with associated data crypto-prisma/v2:<Model>.<field>, so a ciphertext copied into another field or model fails to decrypt.
    Fails closed A stored value that is tampered with, moved, or not a ciphertext throws a FieldDecryptionError; it is never returned as if it were decrypted data.
    Searchable fields Deterministic HMAC-SHA-256 mode for exact-match WHERE queries on encrypted columns.
    Two integration styles Classic $use() middleware and the modern $extends() Client Extension API.
    Zero native deps Built on @sebastienrousseau/crypto-lib which uses the audited @noble/* family.

    Back to Top


    Option Type Required Default Description
    key string Yes -- 64-character hex string (256-bit key)
    encryptedFields FieldConfig[] Yes -- Models and their fields to encrypt
    algorithm string No "xchacha20-poly1305" Accepted for forward compatibility; only XChaCha20-Poly1305 is implemented
    deterministicFields string[] No [] Fields stored as an HMAC-SHA-256 blind index for exact-match search (reads return the MAC)
    allowPlaintextFallback boolean No false Return values that are not ciphertexts as-is instead of throwing; for plaintext migrations only
    acceptLegacyCiphertext boolean No false Read ciphertexts written before the v2: format, only while re-writing them
    blindIndexKeyDerivation "legacy" | "hkdf" No "legacy" "hkdf" computes the blind index with a derived subkey; existing index values must be recomputed

    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-prisma/enc/v2), not under key itself.
    • Associated data. Each value is bound to crypto-prisma/v2:<Model>.<field>, using the model name as written in encryptedFields. The primary key is not bound, because it is usually generated by the database and unknown when a row is created, so two rows of the same model can still have the same field's value swapped.
    • Fail closed. A value that does not decrypt throws FieldDecryptionError (exported; it carries model and field and never the stored value). 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 model or field. Re-write them by reading each row and updating the field with the value read, then remove acceptLegacyCiphertext.
    • Blind index. deterministicFields keep using key for HMAC-SHA-256 by default, so existing index values keep matching. blindIndexKeyDerivation: "hkdf" uses a separate subkey (info crypto-prisma/bidx/v1) instead; switching an existing database requires recomputing every stored index value. The blind index is not bound to a model, so equal values in two deterministic fields produce the same MAC.

    Back to Top


    For fields you need to query by exact match, use deterministic encryption via HMAC-SHA-256:

    prisma.$use(
    createEncryptionMiddleware({
    key: process.env.FIELD_ENCRYPTION_KEY!,
    encryptedFields: [{ model: "User", fields: ["email", "phone"] }],
    deterministicFields: ["email"], // email is searchable
    }),
    );

    // This works because email is hashed deterministically:
    const user = await prisma.user.findFirst({
    where: { email: "alice@example.com" },
    });

    Trade-off: Deterministic fields reveal when two rows have the same value for that field. Use this only for fields where exact-match search is essential.

    Reads return the MAC. A deterministic field holds a one-way HMAC-SHA-256 digest, not a ciphertext, so reads return that hex MAC rather than the original plaintext. Store the plaintext in a separate encrypted field if the application also needs to read it back.

    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
    Middleware middleware.ts Basic middleware setup and transparent encrypt/decrypt
    Extension extension.ts Client Extension approach (Prisma 4.16+)
    Searchable searchable.ts Deterministic HMAC encryption for exact-match search
    Migration migration.ts Migrate existing plaintext data to encrypted storage

    Back to Top

    Back to Top


    pnpm --filter @sebastienrousseau/crypto-prisma run build
    pnpm --filter @sebastienrousseau/crypto-prisma run test
    pnpm --filter @sebastienrousseau/crypto-prisma run lint
    pnpm --filter @sebastienrousseau/crypto-prisma 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