The controls that change what is stored, what is returned, and who gets an
answer at all. Each is a narrow piece built on the ORM's hooks, and each has a
line it does not cross — the section for every control ends by saying where
that line is, because a control you overestimate is worse than one you do not
have.Classification#
Tag what a column is, so every other control — and the compliance sheet — can
ask.import { Model, Classify, FieldClassification, getPIIFields, getPHIFields, isSensitive, autoDiscover } from 'ts-prorm-orm';
// Class decorators that name a column, not property decorators.
@Classify('CONFIDENTIAL') // the model as a whole
@FieldClassification('ssn', 'PII')
@FieldClassification('diagnosis', 'PHI')
@FieldClassification('cardNumber', 'PCI')
class Patient extends Model { /* … */ }
getPIIFields(Patient); // ['ssn']
getPHIFields(Patient); // ['diagnosis']
isSensitive(Patient, 'ssn'); // true
autoDiscover(Patient); // tags by column NAME: ssn, email, dob, card…
Levels are PUBLIC | INTERNAL | CONFIDENTIAL | SECRET | TOP_SECRET;
categories are PII | PHI | PCI | FINANCIAL | HEALTH | BIOMETRIC.
inheritClassifications(child, parent) copies a parent model's tags.The line: classification is metadata. It encrypts, masks and hides
nothing on its own; it is what the sheet and your own code read.Sensitive data discovery#
The same idea, run as a scan: sixteen built-in patterns (SSN, card numbers,
IBAN, dates of birth, biometrics, …) matched against column names, each
with a recommended control.import { SensitiveDataDiscovery } from 'ts-prorm-orm';
const found = SensitiveDataDiscovery.scan(Patient);
// [{ field: 'ssn', type: 'SSN', confidence: 0.95, method: 'column_name', recommendation: 'encrypt' }, …]
SensitiveDataDiscovery.scanAll(prorm);
SensitiveDataDiscovery.generateComplianceReport(prorm); // every model, every finding, for the sheet
SensitiveDataDiscovery.autoProtect(Patient); // apply the recommendations
SensitiveDataDiscovery.registerPattern({
id: 'nhs', name: 'NHS number', type: 'NATIONAL_ID',
pattern: /\b\d{3}\s?\d{3}\s?\d{4}\b/, columnNames: [/nhs/i],
frameworks: ['GDPR'], recommendation: 'encrypt',
});
The line: names, not contents. A column called notes that happens to
hold card numbers is invisible to it. Sample-based analysis is declared in
the options and not implemented.Field encryption#
Real AES-256-GCM, through model hooks. Values are stored as
enc:v2:<keyId>:<base64(iv‖tag‖ciphertext)>; the older
enc:v1:<base64(…)> format is still read.import { Model, configureFieldEncryption, Encrypt, applyEncryptionHooks, encryptValue, decryptValue } from 'ts-prorm-orm';
configureFieldEncryption(process.env.FIELD_KEY!); // once, at startup
@Encrypt('ssn') // a class decorator naming the column; or Encrypt('ssn')(Patient) without decorators
class Patient extends Model {
declare ssn: string;
}
applyEncryptionHooks(Patient);
Writes are encrypted, reads decrypted, and a value already carrying the
prefix is not encrypted twice — so an existing plaintext column can be
migrated in place. A 64-character key is read as hex. A passphrase with a
stored salt — configureFieldEncryption(pass, { salt }), the salt made once
with FieldEncryption.generateSalt() — is stretched with scrypt. A
passphrase without a salt still works for backward compatibility, but is
hashed once with SHA-256 (fast to brute-force) and warns once; it is
registered under the key id legacy. encryptValue() / decryptValue()
are there for use outside a model.Rotation is a keyring: every key that wrote data stays in the ring, one is
active for new writes, and FieldEncryption.reencrypt(value) moves a value
onto the active key.FieldEncryption.keyring({
keys: [
{ id: '2025', key: process.env.FIELD_KEY_2025! },
{ id: '2026', passphrase: process.env.FIELD_PASS!, salt: process.env.FIELD_SALT! },
],
active: '2026',
});
Rotating a key#
Make the new key#
openssl rand -hex 32 for a raw key, or a passphrase plus
FieldEncryption.generateSalt(), stored together in your secret manager.Add it to the ring as the active key#
Keep the old key in the ring: rows it wrote still need it to decrypt. Deploy
this before anything else, so every instance can read both.Re-encrypt the existing rows#
Reading decrypts with whichever key wrote the value; writing it back
encrypts under the active one. Run it as a batch job:import { FieldEncryption, Op } from 'ts-prorm-orm';
declare const Patient: any;
FieldEncryption.keyring({
keys: [
{ id: '2025', key: process.env.FIELD_KEY_2025! },
{ id: '2026', key: process.env.FIELD_KEY_2026! },
],
active: '2026',
});
const stale = { ssn: { [Op.like]: 'enc:v2:2025:%' } };
for (;;) {
const batch = await Patient.findAll({ where: stale, attributes: ['id', 'ssn'], limit: 500 });
if (batch.length === 0) break;
for (const row of batch) {
// row.ssn is plain after afterFind; encrypt() writes enc:v2:2026:…
await Patient.update({ ssn: FieldEncryption.encrypt(row.ssn) }, { where: { id: row.id } });
}
}
The where matches the stored ciphertext, before the hook decrypts it, so
each pass picks up only the rows still under the old key.Drop the old key#
Once Patient.count({ where: stale }) is 0 for every encrypted column,
remove '2025' from the ring and redeploy.[!CAUTION]
Remove a key from the ring only after every value it wrote is re-encrypted.
A value whose key id is missing does not decrypt: decryptValue() throws
No key with id "2025" is configured, and the read that hit it fails.
The line: keys live in process memory — there is no KMS integration and
no per-tenant keys; string-typed fields only. Encrypted columns are opaque to
the database — no index, sort or LIKE. For per-tenant keys or hardware key
custody you want the engine's own column encryption or a KMS in front of this.Masking#
Redact on read, per role.import { Mask, applyMaskingHooks, mask, maskMany, maskValue } from 'ts-prorm-orm';
Mask('ssn', { pattern: 'ssn' })(Patient);
Mask('cardNumber', { pattern: 'card-last4' })(Patient);
Mask('email', { pattern: 'email' })(Patient);
applyMaskingHooks(Patient); // wires an afterFind hook
mask(instance, 'support'); // one row, on demand, for one response
maskMany(rows, 'support');
| Pattern | Output |
|---|
ssn | ***-**-1234 |
card-last4 | **** **** **** 4242 |
card-first6 | first six kept |
email | a***@example.com |
phone | last digits kept |
full | entirely masked |
custom | your customMasker(value) |
showFirst, showLast and maskChar tune the generic patterns.The line: masking is a display control. The real value is in the
database and in the query result before the hook runs. Pair it with
encryption when the value must not be readable at rest.Pseudonymisation#
Deterministic HMAC-SHA256 tokens in place of values, reversible through a
mapping you keep.import { PseudonymizationService, Pseudonymize, applyPseudonymizationHooks } from 'ts-prorm-orm';
PseudonymizationService.configure({
secretKey: process.env.PSEUDO_KEY!, // ≥ 32 bytes
store: 'database', // or 'memory'
model: TokenMap, // the mapping table, when store is 'database'
});
const token = await PseudonymizationService.tokenize('ada@example.com');
await PseudonymizationService.detokenize(token); // 'ada@example.com', or null
Pseudonymize('email')(Patient);
applyPseudonymizationHooks(Patient, 'email');
The line: reversibility depends entirely on the mapping store — the HMAC
alone cannot be reversed. Lose the mapping and you have anonymised, not
pseudonymised. The in-memory store is for tests.Row-level security#
A tenant sees its own rows.import { RowLevelSecurity } from 'ts-prorm-orm';
RowLevelSecurity.apply(Order, (ctx) => ({ where: { tenantId: ctx.tenantId } }));
// Recommended: fail closed. A query on Order with no context throws.
RowLevelSecurity.registerHooks(prorm, { requireContext: true });
await RowLevelSecurity.runInContext({ tenantId: 'acme', userId: 'u1', role: 'member' }, async () => {
await Order.findAll(); // WHERE tenantId = 'acme' merged into every query
await Order.count(); // …and count, sum/min/max/avg, exists, update,
// destroy, restore, increment/decrement
await Order.create({ total: 5 }); // tenantId stamped to 'acme'
});
// Trusted admin or batch work that genuinely needs every tenant:
await RowLevelSecurity.runWithoutRLS(() => Order.count());
app.use(RowLevelSecurity.middleware); // Express: context from the request
What is enforced: every read (findAll/findOne/findByPk, count,
findAndCountAll, sum/min/max/avg, exists, eager-loaded includes of
the protected model), every write (update, destroy, restore,
increment/decrement, instance save/update/destroy) and every insert
(create, bulkCreate, upsert stamp the tenant column and reject a row that
names another tenant; upsert and bulkUpdate refuse to address a row another
tenant owns; truncate is refused under a context). Violations throw
RowLevelSecurityError.Without requireContext a query with no context runs unfiltered (the
historical behaviour) and a one-time warning is logged. Turn it on.This is currentFilter() in src/compliance/row-level-security.ts, which
every hook and wrapped method calls first. The two refusals carry the code
RLS_CONTEXT_REQUIRED; a write that names another tenant's key throws with
RLS_VIOLATION.Not covered: raw SQL (prorm.query(), QueryInterface) is not model-aware
and is never filtered.The line: the database's own row-level security is better in every way —
it holds for every client, including the one that is not this ORM. Use
Model.createPolicy() on an
engine that supports it and reach for this only where the engine does not.
And a caveat the source documents: setContext() does not propagate through
AsyncLocalStorage the way you would expect — use runInContext() and verify
against your call pattern. initRLS() and clearContext() are no-ops.SessionIsolation / @TenantIsolation mirror the same pattern for
multi-tenant session context, plus per-tenant key registration that is
metadata only — FieldEncryption does not read it.TLS#
import { TLSEnforcer } from 'ts-prorm-orm';
TLSEnforcer.enforce(prorm, { mode: 'strict', allowLocal: true }); // 'strict' | 'warn' | 'off'
TLSEnforcer.enforce(prorm, { minVersion: 'TLSv1.3' }); // require a protocol floor
TLSEnforcer.inspect(prorm); // the findings, without throwing
await TLSEnforcer.verifyRuntime(prorm); // ask the server
TLSEnforcer.recommendedOptions('postgres'); // the dialectOptions to set
enforce() / inspect() read the configuration: dialectOptions.ssl,
MSSQL's options.encrypt, and sslmode from the URL or dialectOptions.
Encryption that does not verify the server certificate is reported as a
violation — ssl.rejectUnauthorized: false, trustServerCertificate: true,
and sslmode of disable, allow, prefer or require; verify-ca
earns a warning (it skips the host name). Use sslmode=verify-full.
Pass allowUnverified: true to downgrade the unverified cases to warnings.verifyRuntime() runs one read-only statement to ask the server whether
this session is encrypted — pg_stat_ssl on PostgreSQL, Ssl_version on
MySQL/MariaDB, sys.dm_exec_connections on SQL Server — and reports
encrypted, not-encrypted, not-applicable (file databases) or unknown.The line: the runtime probe describes one session at one moment. Set
sslmode=verify-full (or the engine's equivalent) at the connection and let
the engine refuse anything less — see Connection pooling.The query firewall#
A regex allow/block engine over raw SQL, installed by wrapping prorm.query.import { QueryFirewall, FirewallModeEnum } from 'ts-prorm-orm';
const firewall = QueryFirewall.create(prorm, {
mode: FirewallModeEnum.Blocklist, // Allowlist | Blocklist | Strict
frameworks: ['OWASP', 'CIS'], // bundles applied at creation
onBlock: (blocked) => log.warn(blocked),
});
firewall.applyFrameworkRules('PCI'); // CIS | PCI | HIPAA | SOX | NIST | OWASP, any time
firewall.block(/DROP\s+TABLE/i, 'no table drops from the app');
firewall.allow(/^SELECT/i);
firewall.checkQuery(sql); // analyse without running
firewall.getBlockedHistory();
firewall.getQueryLog(100);
Per-dialect rule sets cover PostgreSQL, MySQL, MariaDB, SQL Server, Oracle
and SQLite.The line: it sees only what goes through prorm.query, and it is
pattern matching, not a SQL parser. It is defence in depth behind
parameterised queries — which the ORM uses everywhere and which are your
actual protection against injection — never a substitute for them.Rate limiting#
import { Model, RateLimiter, RateLimit, initRateLimiter, checkRateLimit } from 'ts-prorm-orm';
initRateLimiter(prorm, {
user: { perMinute: 120, perHour: 2000 },
anonymous: { perMinute: 20, perHour: 200 },
role: { admin: { perMinute: 600, perHour: 10000 } },
action: 'block', // or 'throttle' with throttleDelay
});
const verdict = checkRateLimit(userId, ip, '/export', role); // { allowed, remaining, retryAfter }
// The decorator is typed for ModelStatic, so a plain `extends Model` class needs the call form:
class Export extends Model { /* … */ }
RateLimit({ perMinute: 10 })(Export as any);
Call initRateLimiter() before you register routes that use
checkRateLimit(). Until you do, checkRateLimit() enforces the default
budgets (user 100 a minute, anonymous 20, IP 50, endpoint 200) on an in-memory
limiter and logs one error saying the limiter was never initialised; so the
51st request in a minute from one IP gets allowed: false. initRateLimiter()
replaces that limiter, and its counts start again. Before 4.9.2 an
uninitialised checkRateLimit() allowed every request
(PRORM-SA-2026-102).The line: fixed-window, in-memory counters. Only perMinute is enforced;
perHour and perDay are tracked but not checked, and the database
persistence is scaffolded and never read. Put the real limit at the edge — a
gateway, or the platform's policies if you run
there — and treat this as a last line inside the process. Modified at 2026-10-04 00:40:16