npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@techbulls/encrypted-typeorm

v1.0.0

Published

Transparent field encryption for TypeORM using decorators

Readme

First, the README.md:

# @techbulls/encrypted-typeorm

Transparent field encryption for TypeORM using decorators. Automatically encrypts data before saving to the database and decrypts after loading.

## Features

- 🔐 AES-256-GCM encryption (authenticated encryption)
- 🎯 Simple decorator-based API (`@Encrypted`, `@EncryptedJson`)
- 🔄 Transparent encryption/decryption
- 📦 Support for JSON objects
- 🔍 Deterministic mode for queryable encrypted fields
- 🛡️ TypeScript support

## Installation

```bash
npm install @techbulls/encrypted-typeorm
# or
pnpm add @techbulls/encrypted-typeorm
# or
yarn add @techbulls/encrypted-typeorm
```

Quick Start

1. Initialize encryption

Initialize encryption before creating your TypeORM DataSource:

import { initializeEncryption } from '@techbulls/encrypted-typeorm';

// Use a secure key from environment variables
initializeEncryption(process.env.ENCRYPTION_KEY!);

2. Use decorators in your entities

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { Encrypted, EncryptedJson } from '@techbulls/encrypted-typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  username: string;

  @Encrypted()
  ssn: string;

  @Encrypted({ nullable: true })
  creditCard: string | null;

  @EncryptedJson()
  sensitiveData: {
    apiKeys: string[];
    tokens: Record<string, string>;
  };
}

3. Use normally with TypeORM

const userRepo = dataSource.getRepository(User);

// Create - automatically encrypts
const user = userRepo.create({
  username: 'johndoe',
  ssn: '123-45-6789',
  creditCard: '4111-1111-1111-1111',
  sensitiveData: {
    apiKeys: ['key1', 'key2'],
    tokens: { github: 'ghp_xxx' },
  },
});
await userRepo.save(user);

// Read - automatically decrypts
const found = await userRepo.findOneBy({ id: user.id });
console.log(found.ssn); // '123-45-6789'

API Reference

initializeEncryption(key, options?)

Initialize the encryption module with a master key.

initializeEncryption(key: string | Buffer, options?: EncryptionConfig): void

Parameters:

| Parameter | Type | Description | | ------------------- | ------------------ | ------------------------------------------------------------------------------------- | | key | string \| Buffer | Master encryption key. If string, can be hex-encoded or will be derived using scrypt. | | options.algorithm | string | Encryption algorithm (default: 'aes-256-gcm') | | options.ivLength | number | IV length in bytes (default: 16) | | options.keyLength | number | Key length in bytes (default: 32) |

@Encrypted(options?)

Decorator for encrypted string columns.

@Encrypted(options?: EncryptedColumnOptions): PropertyDecorator

Options:

| Option | Type | Description | | --------------- | --------- | ----------------------------------------------------------- | | nullable | boolean | Allow null values | | unique | boolean | Add unique constraint | | name | string | Custom column name | | comment | string | Column comment | | deterministic | boolean | Use deterministic encryption (allows querying, less secure) |

@EncryptedJson(options?)

Decorator for encrypted JSON columns. Automatically serializes objects before encryption and parses after decryption.

@EncryptedJson(options?: EncryptedJsonColumnOptions): PropertyDecorator

Options are the same as @Encrypted.

Standalone Functions

For manual encryption/decryption:

import { encrypt, decrypt } from '@techbulls/encrypted-typeorm';

const encrypted = encrypt('sensitive data');
const decrypted = decrypt(encrypted);

Transformers

For use with TypeORM's @Column decorator directly:

import {
  EncryptedTransformer,
  EncryptedJsonTransformer,
  DeterministicEncryptedTransformer,
  createEncryptedTransformer
} from '@techbulls/encrypted-typeorm';

@Column({ type: 'text', transformer: EncryptedTransformer })
ssn: string;

@Column({ type: 'text', transformer: EncryptedJsonTransformer })
metadata: object;

// Custom transformer
@Column({ type: 'text', transformer: createEncryptedTransformer(true) })
queryableField: string;

Deterministic Encryption

By default, encryption is non-deterministic (same input produces different output each time due to random IV). This is more secure but prevents querying.

For fields you need to query with WHERE clauses, use deterministic mode:

@Entity()
export class User {
  @Encrypted({ deterministic: true })
  email: string;
}

// Now you can query
const user = await userRepo.findOneBy({ email: '[email protected]' });

⚠️ Warning: Deterministic encryption is less secure as identical values produce identical ciphertext. Use only when querying is required.

Security Considerations

  1. Key Management: Store your encryption key securely (environment variables, secrets manager, etc.)
  2. Key Rotation: This library does not currently support automatic key rotation. Rotating keys requires decrypting and re-encrypting all data.
  3. Column Type: Encrypted values are longer than original values. Always use text column type (handled automatically by decorators).
  4. Deterministic Mode: Only use when necessary for querying, as it's less secure.

Example: Full Setup

// src/config/encryption.ts
import { initializeEncryption } from '@techbulls/encrypted-typeorm';

export function setupEncryption(): void {
  const key = process.env.ENCRYPTION_KEY;
  if (!key) {
    throw new Error('ENCRYPTION_KEY environment variable is required');
  }
  initializeEncryption(key);
}

// src/entities/user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { Encrypted, EncryptedJson } from '@techbulls/encrypted-typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  username: string;

  @Encrypted({ deterministic: true })
  email: string;

  @Encrypted()
  ssn: string;

  @Encrypted({ nullable: true })
  creditCard: string | null;

  @EncryptedJson({ nullable: true })
  metadata: Record<string, unknown> | null;
}

// src/index.ts
import 'reflect-metadata';
import { DataSource } from 'typeorm';
import { setupEncryption } from './config/encryption';
import { User } from './entities/user.entity';

// Initialize encryption BEFORE DataSource
setupEncryption();

const AppDataSource = new DataSource({
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'password',
  database: 'myapp',
  entities: [User],
  synchronize: true,
});

async function main(): Promise<void> {
  await AppDataSource.initialize();
  console.log('Database connected');

  const userRepo = AppDataSource.getRepository(User);

  const user = userRepo.create({
    username: 'johndoe',
    email: '[email protected]',
    ssn: '123-45-6789',
    metadata: { theme: 'dark' },
  });

  await userRepo.save(user);
  console.log('User created:', user.id);

  const found = await userRepo.findOneBy({ email: '[email protected]' });
  console.log('Found user:', found?.username);
  console.log('SSN (decrypted):', found?.ssn);
}

main().catch(console.error);

License

MIT