1. compliance
prorm
  • prorm documentation
  • Known test gaps
  • Architecture
  • Core concepts
  • Database types & coverage
  • Getting started
  • Going further
  • compliance
    • Compliance
    • The security toolkit: `prorm audit`
    • Checklists by regulation
    • Declaring personal data
    • Evidence bundles
    • Evidence
    • Frameworks: `@Security`
    • Jurisdictions
    • Platform policies
    • Protecting data
    • The regulation dataset
    • Residency and cross-border transfers
    • Retention & integrity
    • Status
    • Subject rights
  • decorators
    • prorm with decorators
    • Models with decorators
    • Querying a decorated model
    • Relations with decorators
  • diagrams
    • Diagram generators
    • Chen diagram
    • Class diagram
    • Dependency diagram
    • ER diagram
    • Flow diagram
    • From your models to a diagram
    • Gantt diagram
    • Index diagram
    • Migration diagram
    • Model diagram
    • Package diagram
    • Crow’s-foot diagram
    • Schema documentation
    • Sequence diagram
    • State diagram
    • Tree diagram
  • dialects
    • SQL dialects
    • AlloyDB Dialect
    • AlloyDB Omni Dialect
    • Amazon Athena Dialect
    • Aurora DSQL Dialect
    • Amazon Aurora MySQL Dialect
    • Amazon Aurora PostgreSQL Dialect
    • Azure Database for MySQL Dialect
    • Azure Database for PostgreSQL Dialect
    • Azure SQL Database Dialect
    • Azure SQL Managed Instance Dialect
    • Google BigQuery Dialect
    • Citus Dialect
    • ClickHouse dialect
    • Cloud Authentication (`cloud-auth`)
    • Cloud SQL for SQL Server Dialect
    • Cloud SQL for MySQL Dialect
    • Cloud SQL for PostgreSQL Dialect
    • CockroachDB Dialect
    • Azure Cosmos DB for PostgreSQL Dialect
    • CrateDB Dialect
    • Cloudflare D1 Dialect
    • Databricks dialect
    • IBM Db2 Dialect
    • Dolt Dialect
    • Apache Doris Dialect
    • Druid Dialect
    • DuckDB Dialect
    • Exasol dialect
    • Microsoft Fabric Data Warehouse Dialect
    • Firebird Dialect
    • Greenplum Dialect
    • SAP HANA Dialect
    • MySQL HeatWave Dialect
    • Azure Data Explorer (Kusto) Dialect — T-SQL
    • MariaDB Dialect
    • Materialize Dialect
    • MonetDB Dialect
    • MotherDuck Dialect
    • Microsoft SQL Server Dialect
    • MySQL Dialect
    • Neon Dialect
    • OceanBase Dialect
    • openGauss Dialect
    • Oracle Dialect
    • Oracle Autonomous Database Dialect
    • ParadeDB Dialect
    • PolarDB Dialect
    • PostgreSQL Dialect
    • Presto Dialect
    • QuestDB Dialect
    • Aurora RDS Data API Dialect (`rdsdata`)
    • Amazon RDS for Db2 Dialect
    • Amazon RDS for MariaDB Dialect
    • Amazon RDS for SQL Server Dialect
    • Amazon RDS for MySQL Dialect
    • Amazon RDS for Oracle Dialect
    • Amazon RDS for PostgreSQL Dialect
    • Amazon Redshift
    • Amazon Redshift Data API Dialect
    • RisingWave Dialect
    • rqlite Dialect
    • SingleStore Dialect
    • Snowflake Dialect
    • Google Cloud Spanner Dialect
    • Spanner (PostgreSQL interface) Dialect
    • SQLite Dialect
    • StarRocks Dialect
    • Supabase Dialect
    • Azure Synapse Analytics (dedicated SQL pool)
    • Teradata Dialect
    • TiDB Dialect
    • TimescaleDB Dialect
    • Trino Dialect
    • Turso / libSQL Dialect
    • Vertica dialect
    • Vitess Dialect
    • Yellowbrick Dialect
    • YugabyteDB Dialect
  • guides
    • Access rules and behaviour profiles
    • ArangoDB (AQL)
    • Associations
    • Audit levels and escalation
    • Audit logging
    • In the browser
    • Bulk operations
    • Caching
    • Capabilities, tiers and team roles
    • CLI
    • Cloudflare
    • Compliance & data protection
    • Connection Pooling & Performance
    • Security in the console
    • Couchbase: structured N1QL queries
    • Data types
    • Decorators
    • Eager loading
    • Enums and constants
    • Error handling & error types
    • Extensions
    • External fields
    • Foreign data wrappers
    • Graph databases
    • Hooks & lifecycle events
    • Indexes & constraints
    • InfluxDB: structured Flux pipelines
    • klock-errors
    • klock — the `.klock` file
    • Local databases (`prorm db up`)
    • Structured log search — Splunk, Graylog, Papertrail, Sumo Logic
    • Logging
    • Grafana Loki: structured LogQL queries
    • MCP server
    • Migrate — the data transfer subsystem
    • Migrations & Schema Sync
    • Models from an existing database
    • Defining models
    • Multiple databases
    • OrientDB, Neptune and TigerGraph
    • Passwords
    • Importing a Prisma schema
    • Structured PromQL and MetricsQL
    • Query firewall
    • QueryInterface
    • Query operators reference
    • Query optimization
    • Composing find options with `pipe()` and `Q`
    • Query safety: the fail-closed WHERE guard
    • Querying
    • Raw Queries & Query Building
    • Read replicas
    • Schema diffing & migration generation
    • Views, triggers & other schema objects
    • Scopes & default scopes
    • Seeders
    • SPARQL / RDF triplestores
    • SQL constants
    • SQL features
    • SQL function builders
    • SQLite advanced features
    • StoreKey — a prod-orm database as the storage
    • Streaming results
    • Terraform
    • Transactions & Isolation Levels
    • Type mapping: legacy and modern
    • TypeScript types
    • Database users, roles & privileges
    • Validation & constraints
    • Virtual & Computed Fields
    • Writing docs
  • javascript
    • prorm in JavaScript
    • Models in JavaScript
    • Querying in JavaScript
    • Relations in JavaScript
  • runbooks
    • Operational runbooks
    • Connection failures
    • Credential rotation
    • Failover
    • Incident checklist
    • Deploying klock v2
    • Migration rollback
  • running-databases
    • Running databases in Docker
    • Running prorm under Bun in Docker
    • Running Cassandra in Docker with prorm
    • Running ClickHouse in Docker with prorm
    • Running CockroachDB in Docker with prorm
    • Running prorm under Deno in Docker
    • Running Elasticsearch in Docker with prorm
    • Running MariaDB in Docker with prorm
    • Running MongoDB in Docker with prorm
  • prorm control plane
    • Introduction
    • Authentication
    • Errors
    • Getting started
      • Service
        • Is it up
        • This description
    • Account
      • Sign-up and verification
        • Create an account
        • Exchange credentials for a token
        • Verify with the emailed code
        • Verify by clicking the emailed link
        • Name the parent or guardian
        • What a consent link is about
        • Give consent for a child's account
        • Ask the parent or guardian again
        • Send a new code and link
      • Family
        • Everyone this account is responsible for
        • One child, in detail
        • Turn a limit on or off
      • Profile
        • Who am I
        • Change the account
        • Every address on the account
        • Add an address
        • Confirm an address with the code mailed to it
        • Mail a fresh code to an unconfirmed address
        • Make an address primary
        • Remove an address
        • What this caller may do
    • Security
      • Sessions
        • Everywhere this account is signed in
        • Sign out everywhere else
        • Sign one out
        • A token for the CLI on a named machine
        • A token for the customer console, from the staff one
        • Park a sign-in for the CLI to collect
        • The CLI collecting its sign-in
        • The team's members' live sessions
        • Sign a member's session out
        • Sign an account out everywhere
        • Everywhere the account is signed in
        • Sign an account's session out
      • Single sign-on
        • Begin a single sign-on
        • The provider's return
        • Link the signed-in account to a team's provider
        • Which team an address signs in to
        • The team's single sign-on, as a member sees it
        • Set the team's OpenID Connect provider up, or change it
        • Remove the provider
        • The team's domain claims and the DNS record each needs
        • Prove a claimed domain
      • MFA and passwords
        • Start enrolling a second factor
        • Prove the app has it
        • Remove the second factor
        • Ask for a reset link
        • Set a new password with the emailed token
      • Klock
        • Open a device-bound klock session
        • Check in, for the next grant
        • Step up the session asking
        • Rotate the device key
        • Freeze a session
        • Unfreeze a session
        • A guest grant
        • The revocation feed
        • The published keyset
        • What this control plane supports
      • Devices
        • Your devices, or a team's
        • Approve a new device's pairing code
        • One device
        • Rename a device
        • Revoke a device
        • Suspend a device
        • Reinstate a suspended device
        • Wipe a device
        • Ask a device to rotate its key
        • The team's members' devices
        • Revoke a member's device
        • An account's devices
        • Revoke an account's device
        • Wipe an account's device
        • The device fleet
      • Access rules and behaviour
        • The access rules that bear on you
        • Add an access rule
        • This request, as the rules see it
        • One access rule
        • Remove an access rule
        • The behaviour profiles that bear on you
        • Add or change a behaviour profile
        • The profile presets
        • Your behaviour findings
        • Acknowledge a finding
        • One behaviour profile
        • Remove a behaviour profile
        • The team's access rules
        • Add a team access rule
        • Remove a team access rule
        • The team's behaviour profiles
        • Add or change a team behaviour profile
        • Remove a team behaviour profile
        • What the team's profiles caught
        • Acknowledge a team finding
      • Recovery and lockdown
        • Ask for a recovery link
        • Recover access with the emailed code
        • Is the account locked down
        • Lock the account down
        • Release a lockdown
        • Lock a member down
        • Release a member's lockdown
      • MCP tokens
        • Make a delegated token for one MCP client
        • The account's delegated tokens
        • Revoke a delegated token
        • What a delegated token may do now
        • Run one MCP tool with a delegated token
        • Run a device-signed MCP tool call relayed by the MCP Worker
      • Kerberos
        • Give the team its own Kerberos realm
        • The team's realm
        • Remove the team's realm
    • Logging and monitoring
      • Audit log
        • What has been done to the account
        • What has happened to this account
        • The account's audit trail
      • Operations
        • Everything that has been asked of this database
        • One, with its steps
        • Stop it
        • Put a failed one back in the queue
        • Every operation, across all accounts
      • Metrics and events
        • Every measurement, for a graph
        • Who did what to it
    • Billing
      • Plans and pricing
        • What the plans allow
        • The rate card
        • What one database would cost
        • What this account is paying for, itemised
      • Subscriptions and invoices
        • What this month's invoice will say
        • What this account is on
        • What it has been charged
        • Start a Stripe Checkout session
        • Open the customer portal
        • Stripe's events
        • Buy more connection pools
      • Team billing
        • The team's billing account
        • What the team has been charged
        • What this month's invoice will say
        • The team's cards
        • Add a card, through a Stripe-hosted setup session
        • Make a card the team's default
        • Remove a card
        • Start the team paying
        • Open the Stripe portal on the team's customer
        • Change the team's plan
        • Who receives the team's bills
        • How the team pays for transfers
    • Support
      • Support chat
        • My conversations
        • Start a conversation
        • Every support conversation, open first
        • A ticket for the socket
        • One conversation, with who is in it and who is connected
        • Rename a group; open or close a support conversation
        • The lines, oldest first
        • Say something
        • Add somebody
        • Mark read
    • Administration
      • Users
        • Every account
        • One account, with everything hanging off it
        • Grant or revoke admin
        • Verify an account by hand
        • Lock or unlock sign-in
        • Allow or hold provisioning
        • Send the verification mail again
        • Set the plan by hand
      • Platform
        • Every database and store, across all accounts
        • The counts worth putting on a dashboard
      • Staff and permissions
        • What kind of admin the caller is, and which scopes they hold
        • The admin presets
        • Every admin, and the scopes each resolves to
        • Make an account an admin of a kind
        • Change an admin's kind, or a custom admin's scopes
        • Revoke admin
      • Team administration
        • Every team, with its owner and size
        • One team in full — members with their accounts, and projects
        • Hand the team to another member
        • Put an account in the team, active at once
        • Change a member's role
        • Remove a member
      • Assumed identities
        • Assume an identity — act as a customer account
        • The identities the caller holds open
        • End an assumed identity
      • Support inbox
        • The platform's addresses
        • Add a platform address
        • One address, with its counts
        • Change an address's label, routing, or whether it accepts mail
        • Remove an address that holds no mail
        • Make, adopt or repair the address's routing rule
        • Every admin's personal address, made where missing
        • File a raw message, as if it had arrived
        • The inbox
        • One message, whole
        • Mark a message
        • Hand a message to an admin, or take it back
        • Leave an internal note
        • Reply, from the address the message came to
        • What is waiting
    • Databases
      • Databases
        • Data stores
          • Every data store on the account
          • Provision a data store
          • Change a data store that is already running
          • One data store
          • Deprovision it
          • Report what it is using
          • How to reach a data store
        • Connections and credentials
          • The api keys on a database
          • Issue a key
          • Revoke a key
          • The engine users we created
          • Create a user inside the database
          • Give a user a new password
          • Drop a user
          • How the database is reached
          • Set how it is reached
          • Revoke every api key on it
          • How to connect to it
          • The ssh keys that open its bastion
          • Add a key, or have one made
          • The private half of a generated key, once
          • Revoke an ssh key
        • Schema and objects
          • The SQL objects we put in it
          • Create one, and apply it
          • What is in the database, as the engine reports it
          • One table
          • What it would run, without running it
          • Redefine an object in place
          • Drop it
          • The extensions installed in it
        • Migrations
          • A plan compiled to statements, recording nothing
          • The migrations recorded for it
          • Record one
          • Apply everything recorded and not yet run
          • Apply everything pending, oldest version first
        • Lifecycle
          • Grow or shrink it
          • Stop it accepting connections
          • Start it again
          • Move it to another region
        • Backups and replicas
          • Take a backup
          • The backups it has
          • Restore one into it
          • What has been restored into it, and from where
          • Its read copies
          • Add one
        • Policies
          • The catalog
          • One policy
          • What this database is held to
          • Switch a policy on, or change its knobs
          • Switch it off
          • Mark the policies reviewed
          • Evaluate the periodic policies now
          • Who is behind a credential
        • Passwordless
          • The database's passwordless sessions
          • Issue a passwordless session (v1)
          • Revoke a passwordless session
          • Bind a session to a device key
          • Issue a v2 session for a host to bind
          • Redeem an enrolment ticket on the host
          • Check a passwordless credential
          • Run one described query under a passwordless credential
        • Database roles
          • The database's roles
          • Define a role
          • One role
          • Change what a role permits
          • Delete a role, and revoke every key granted it
          • Grant a role, which mints a key
          • Who holds a role
          • The api keys bound to a role
        • Pools
          • A database's connection pools, and how busy each is
          • Open another pool
          • Rename a pool or change its size
          • Close a pool
        • Data plane
          • Run a query against a database
          • Several statements, in order, over one connection
          • Is this database answering
          • What the proxy itself is holding
        • Transfers
          • The strategies this account's tier may use
          • Price a transfer without creating it
          • The account's transfer jobs, newest first
          • Create a transfer job
          • One job, and whether its certificate holds
          • Cancel an unfinished job
          • Start a created job, confirming its price
          • Report a job's status (the runner, or the owner's side of a local run)
        • Every database on the account
        • Provision a database
        • Change a database that is already running
        • One database
        • Deprovision it
        • Read or write it
        • Report what it is using
        • The engines this API will provision
        • Where a managed database can be put
    • Teams
      • Teams
        • Members
          • Who is on it
          • Invite somebody
          • Accept an invitation
          • Change somebody's role
          • Remove somebody
        • Projects
          • The projects a team runs
          • Start one
          • Rename a project, or move its environment
          • Delete a project
          • One project, and what is in it
          • Put a database or store in it
          • What is in a project
          • Take one out
        • The teams this account is on
        • Start one
        • The twelve roles, and what each may do
        • Rename a team
        • Close a team
        • One team
        • Hand the team to somebody else
        • Leave a team
    • Schemas
      • Error
      • ValidationErrors
      • Token
      • PolicyCategory
      • PolicySeverity
      • PolicyAction
      • PolicyTrigger
      • PolicyParam
      • Policy
      • PolicyCatalog
      • PolicyAssignment
      • PolicyOutcome
      • PolicyFiring
      • CredentialTrace
      • Relation
      • Restrictions
      • ChildSummary
      • SignupRequest
      • SigninRequest
      • UpdateMeRequest
      • User
      • Address
      • GeoPoint
      • D1Region
      • Usage
      • UsageReport
      • Resource
      • Database
      • DataStore
      • NewDatabase
      • NewDataStore
      • QueryRequest
      • DatabasePrivilege
      • ApiKey
      • DbUser
      • Access
      • AccessRequest
      • DatabaseObject
      • NewDatabaseObject
      • NewMigration
      • SchemaOperation
      • Migration
      • Operation
      • Session
      • AdminPowers
      • Admin
      • AuditEntry
      • TeamRole
      • Conversation
      • ChatMessage
      • TeamSso
      • Team
      • TeamMember
      • SshKey
      • ConnectionInfo
      • InboxAddress
      • InboxMailbox
      • InboxMessageSummary
      • InboxMessage
      • InboxNote
      • Page
      • Quote
      • Plan
      • ApiError
      • CapabilityRefusal
      • KlockErrorCode
      • PageWindow
      • SessionView
      • KlockStepUpRequest
      • KlockOpenRequest
      • KlockOpenedSession
      • UpdateMeResult
      • CapabilitiesView
      • SessionLimits
      • Device
      • DeviceListed
      • DeviceTeamRef
      • DeviceCommand
      • DeviceAuditLine
      • DeviceActionRequest
      • StaffActionRequest
      • ManagedSession
      • SessionRevoked
      • AccessRule
      • AccessRuleRequest
      • BehaviourProfile
      • BehaviourProfileRequest
      • BehaviourProfileSaved
      • BehaviourFinding
      • BehaviourFindingAck
      • StepUpProof
      • Removed
      • MemberLockdownRequest
      • McpClient
      • McpDelegatedView
      • McpToolCall
      • McpForwardRequest
      • PasswordlessScope
      • RoleScope
      • PasswordlessSession
      • PasswordlessTlsMaterial
      • PasswordlessKerberosMaterial
      • ServiceDeviceKeys
      • ServiceSession
      • DatabaseRole
      • TransferEndpoint
      • TransferJobRequest
      • TransferQuote
      • TransferStrategy
      • TransferJob
      • TransferJobAccess
      • Pool
      • PoolAllowance
      • BillingSubscription
      • Invoice
      • BillingContact
      • PaymentMethod
      • UpcomingCharges
      • TeamBilling
      • TeamKerberosRealm
      • TeamSsoDomain
      • TeamSsoResponse
      • StoreConnection
      • BatchFailure
      • ProxyStatus
  1. compliance

Protecting data

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.
NeedControlEnforced by
know which columns are sensitiveClassification and discoverymetadata
unreadable at restField encryptionhooks, in the application
hidden from some readersMaskingan afterFind hook
replace with a reversible tokenPseudonymisationhooks + a mapping store
a tenant sees only its rowsRow-level securitya beforeFind hook — prefer the database's own
only over TLSTLS enforcementa startup check
never run that statementQuery firewallregex over prorm.query
not that oftenRate limitingin-memory counters

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');
PatternOutput
ssn***-**-1234
card-last4**** **** **** 4242
card-first6first six kept
emaila***@example.com
phonelast digits kept
fullentirely masked
customyour 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.
Next: Retention & integrity.
Modified at 2026-10-04 00:40:16
Previous
Platform policies
Next
The regulation dataset
Built with