@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): voidParameters:
| 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): PropertyDecoratorOptions:
| 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): PropertyDecoratorOptions 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
- Key Management: Store your encryption key securely (environment variables, secrets manager, etc.)
- Key Rotation: This library does not currently support automatic key rotation. Rotating keys requires decrypting and re-encrypting all data.
- Column Type: Encrypted values are longer than original values. Always use
textcolumn type (handled automatically by decorators). - 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
