Runtime

Redaction

Strip, mask or hash sensitive fields in API responses, logs and audit events with redact(), redactResponses() and redactingTransport() from @axiljs/runtime.

6 min readUpdated DocumentationEdit this page
On this page10

@axiljs/runtime redacts data based on the tRedact and tSensitive metadata recorded by @axiljs/decorator, plus optional name-based rules for plain objects. One set of annotations on an entity protects API responses, log lines and audit events.

TypeScript
TS
1import { tRedact, tSensitive } from '@axiljs/decorator'
2import { redact } from '@axiljs/runtime'
3
4class User {
5  id = 'u_1'
6  @tRedact({ strategy: 'remove' }) passwordHash = 'scrypt$...'
7  @tRedact({ strategy: 'mask', visibleChars: 4 }) card = '4242424242424242'
8  @tRedact({ strategy: 'hash' }) ssn = '123-45-6789'
9  @tSensitive('PII') email = 'ann@example.com'
10}
11
12redact(new User())
13// {
14//   id: 'u_1',
15//   card: '************4242',
16//   ssn: 'sha256:01a54629efb95228',   (first 16 hex chars of the SHA-256)
17//   email: '***'
18// }                                   passwordHash is gone

tRedact strategies

@tRedact(options?) on a property means "this value is always redacted", in responses, logs and audit events.

StrategyResultNotes
'mask' (default)'***', or '*' repeated plus the last visibleChars charactersNon-string values always become '***'
'hash''sha256:' followed by the first 16 hex characters of the SHA-256 of String(value)Same input, same output: useful for correlating records without exposing the value
'remove'The key is omitted from the output

null and undefined values are kept as they are for mask and hash.

visibleChars

Only applies to mask on strings:

visibleCharsInputOutput
unset or 0'4242424242424242''***'
4'4242424242424242''************4242'
4'abc''***' (whole value masked)

The whole value is never revealed: when visibleChars is greater than or equal to the length, every character is masked. Note that a partial mask keeps the original length.

Warning

hash is an unsalted, truncated SHA-256. It hides the value from casual reading, but low-entropy values (national ID numbers, phone numbers, short codes) can be recovered by hashing every possible input. Use remove or mask for those when correlation is not needed.

tSensitive: logs yes, responses no

@tSensitive(classification) marks a field as sensitive data ('PII', 'PHI', 'PCI', 'SECRET' or 'INTERNAL'). It is treated differently from tRedact:

WheretRedact fieldstSensitive fields
redact() (default)redacted with their strategymasked as '***'
redactingTransport() (logs, default)redactedmasked as '***'
tAudit args / resultredactedmasked as '***'
redactResponses() (default)redactedkept

The idea: a user's own email belongs in the response to GET /me, but not in every log line and audit record. The classification does not change the masking; all tSensitive fields are masked the same way.

A field with both tRedact and tSensitive follows its tRedact rule everywhere.

redact(value, options?)

Returns a redacted plain copy of value. The input is never mutated.

OptionTypeDefaultDescription
includeSensitivebooleantrueMask tSensitive fields as well as tRedact ones
fieldsRecord<string, RedactRule>noneRules by field name, for objects without metadata
maxDepthnumber10Stop descending past this depth

RedactRule is either a strategy name ('mask', 'hash', 'remove') or a full { strategy, visibleChars } object.

How values are walked:

  • Class instances become plain objects with their own enumerable properties. Metadata is looked up on the instance's prototype, so redact() must receive the class instance, not a spread copy.
  • Arrays are mapped element by element; Maps are converted to plain objects.
  • Date, Buffer and typed arrays are returned as they are.
  • Circular references are replaced with '[Circular]'.
  • A field with a rule is replaced as a whole; its contents are not walked.
  • Beyond maxDepth, values are returned unredacted.

Rule precedence for one key

  1. tRedact metadata on the object's class.
  2. tSensitive metadata (masked), unless includeSensitive: false.
  3. A fields rule for that key name.

Rules for plain objects

Request bodies, headers and third-party payloads carry no decorator metadata. Use fields; the rule applies to that key name at any depth:

TypeScript
TS
1redact(
2  { user: { name: 'Ann', password: 'hunter2' }, headers: { authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9' } },
3  { fields: { password: 'remove', authorization: { strategy: 'mask', visibleChars: 4 } } }
4)
5// { user: { name: 'Ann' }, headers: { authorization: '***********************NiJ9' } }

Tip

Keep entities as class instances all the way to the response (return new User(row), not { ...row }). That is what lets redactResponses() find the metadata.

redactResponses(options?): API responses

Middleware that redacts every JSON body the response sends: res.json() and the envelope helpers (res.success(), res.created(), res.paginated() and the rest).

TypeScript
TS
1import { Application } from '@axiljs/core'
2import { redactResponses } from '@axiljs/runtime'
3
4const app = new Application()
5app.use(redactResponses())
6
7app.get('/users/:id', async (req, res) => {
8  res.success(await users.find(req.params.id))   // passwordHash removed, card masked, email kept
9})

It takes the same options as redact(), but defaults to includeSensitive: false, so tSensitive fields reach the client and tRedact fields never do. To strip sensitive fields from a public endpoint too, pass includeSensitive: true:

TypeScript
TS
app.get('/public/profiles/:id', redactResponses({ includeSensitive: true }), async (req, res) => {
  res.success(await profiles.find(req.params.id))   // email is '***' here
})

Tip

On hot paths, attach redactResponses() as route middleware only where entities leave the API, rather than globally. Health probes and static responses then skip the extra copy. The high-scale-api template does this for its /api/users routes.

redactingTransport(inner, options?): logs

Wraps any log transport (anything with write(entry)) so each entry is redacted before it is written. Combine it with @axiljs/observability's Logger:

TypeScript
TS
1import { ConsoleTransport, Logger } from '@axiljs/observability'
2import { redactingTransport } from '@axiljs/runtime'
3
4const logger = new Logger({
5  name: 'api',
6  transports: [
7    redactingTransport(new ConsoleTransport('json'), {
8      fields: { authorization: 'mask', password: 'remove', token: 'remove' }
9    })
10  ]
11})
12
13logger.info('login', { user, headers: req.headers })
14// user's tRedact fields redacted, tSensitive fields masked,
15// headers.authorization masked, any password / token key removed

The options are the same as redact(), with includeSensitive defaulting to true, so tSensitive fields are masked in logs. Context fields passed to logger.info(message, context) are spread onto the log entry, so fields rules match them by name.

Note

When you pass transports, the Logger's format option does not reach your transport. Choose the format on the transport itself: new ConsoleTransport('json') or new ConsoleTransport('pretty').

Audit events

tAudit passes method arguments (includeRequest) and results (includeResponse) through redact() with its defaults before emitting audit.log. There is nothing to configure: annotate the entity once and the audit trail follows. See Interceptors.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY