@nodii/pii
v0.27.0
Published
Substrate PII library for the Nodii microservice stack — deterministic tokenization, per-subject DEK envelope encryption, redaction, DSAR helpers, extensible-entity scaffolding. Spec: planning hub docKey=pii.
Readme
@nodii/pii
Substrate PII library for the Nodii microservice stack — deterministic tokenization, per-subject DEK envelope encryption, redaction, DSAR helpers, extensible-entity scaffolding.
Spec: https://planning.dev.nucleus-cloud.in/api/v1/feature-docs?serviceId=nodii-libs&docKey=pii
v0.1.0 surface
import {
initPii,
pii,
provisionTenantPii,
PII_DETOKENIZE_PERMISSIONS,
definePiiPolicyMap,
defineExtensibleEntity,
NoopKmsClient,
NoopSecretsManagerClient,
NoopPiiDbClient,
} from "@nodii/pii";
initPii({
serviceName: "billing-svc",
kmsClient,
secretsManagerClient,
region: "ap-south-1",
env: "prod",
db, // optional — required for detokenize + DSAR paths
});
// Tokenize (16 hex chars; deterministic per (value, tenantId))
const token = await pii.tokenize("[email protected]", {
tenantId: "t1",
fieldName: "email",
});
// Encrypt under a per-subject DEK envelope (AES-256-GCM)
const payload = await pii.withSubject("t1", "u1", "USER", () =>
pii.encrypt("[email protected]"),
);
// DSAR
await pii.erasePerSubject("t1", "u1", "USER");DEK cache: canonical keys, eviction, and the cross-replica window
The per-subject DEK and the per-tenant retention DEK are cached in process
(default TTL 60s, initPii({ cacheConfig: { dekTtlMs } })).
Keys are canonical. A uuid-shaped tenantId / subjectId is lower-cased
into Postgres's own uuid_out form before it reaches a cache key, so every
spelling of one id maps to ONE entry and a single eviction really removes the
DEK. Anything that is not a syntactically valid uuid — a slug, an email, a
composite key — is used byte-identically, because lower-casing those would merge
two genuinely different subjects. canonicalCacheId(value) is exported if you
need to apply the same rule to something you cache yourself.
Eviction is a supported, cache-only operation. Call it after a compensation
REVOKE — a DEK row you deleted so a retry can mint a fresh key — or any other
invalidation outside the DSAR path. It touches no DB row, makes no KMS call and
writes no audit row; erasePerSubject / erasePerTenant already evict
internally, so a DSAR erase does not need it.
import {
evictSubjectDek,
evictTenantDeks,
evictTenantRetentionDek,
dekCacheTtlMs,
} from "@nodii/pii";
// after the revoking transaction COMMITS
evictSubjectDek({ tenantId, subjectKind: "CUSTOMER", subjectId });The cross-replica window — read this before you rely on an eviction. These
caches are per process. Evicting reaches THIS process only; there is no
invalidation bus. After a revoke or an erase, any other replica that had already
acquired the DEK can keep using it until its own entry expires, bounded by
dekCacheTtlMs(). Within that window another replica can still seal new data
under a key whose row is gone.
The guard belongs to the writer, because only the writer knows whether a given seal may race a revoke. Either:
- Re-read and refuse — after the revoke commits, re-read the DEK row and refuse the write when it is gone or NULL. This is what crm's bulk provision path does, and the shape to copy; or
- Hold the subject un-writable for
dekCacheTtlMs()after the revoke.
Lowering dekTtlMs shortens the window at the cost of more KMS Decrypt calls;
it does not close it. Closing it inside the library would mean a generation /
version check against the DEK row on every cache HIT — a database round-trip per
encrypt, i.e. no cache at all — so it is deliberately not done.
Retention admin errors
acknowledgeRetentionPurge throws NoRetentionWatermark
(code: "NO_RETENTION_WATERMARK") when the (tenant, service, data_class) triple
has no D723 watermark row — no re-key job has ever run for the class, so there
is no hard-purge queue to acknowledge. Per D724 that is a 409, not a 500:
import { NoRetentionWatermark } from "@nodii/pii";
try {
await acknowledgeRetentionPurge(tenantId, dataClass);
} catch (err) {
if (err instanceof NoRetentionWatermark) {
return c.json({ code: "NO_RETENTION_WATERMARK", dataClass: err.dataClass }, 409);
}
throw err;
}Classify on the class or on err.code. The message is not a contract — string
matching it is the failure genus this error exists to end.
record_subjects on a postgres.js pool: pass query options through
Given a postgres.js sql pool, linkRecordSubjects reserves one connection
for the call. If a chunked link fails and its ROLLBACK also fails, the
session may hold an aborted or half-written transaction, so the library evicts
the connection rather than return it to the pool. It closes the socket from
the client side with the driver's own connection terminate(), which needs no
pg_signal_backend and works under SET ROLE. It reaches that connection
through the driver's onexecute query option.
That option, the connection's terminate() and its onclose slot are
postgres.js internals. @nodii/pii declares an optional peer dependency on
postgres >=3.4.4 <4. Every published version in that range (3.4.4 to 3.4.9,
the newest 3.x; no 3.5 exists) was inspected for all three, and the component
suite runs on 3.4.9 and pins the hook. The ceiling is the next major rather
than a minor line, so a service is not forced into a peer conflict by a future
3.x. Instead, a driver that stops handing the connection over is caught at
runtime: NODII_PII_EVICT_NO_HANDLE at the first statement, and multi-chunk
links are refused (below). Recheck the internals before
widening the range to 4.x.
A wrapper around the pool (tracing, instrumentation, a test double) must
pass unsafe(sql, args, options)'s third argument through to the driver.
A wrapper that drops it hides the connection, so a failed ROLLBACK could
not be cleaned up. A multi-chunk linkRecordSubjects (more than
LINK_CHUNK_ROWS rows), the one call that opens its own transaction, then
throws an error with code:
"RECORD_SUBJECTS_POOL_HIDES_CONNECTION" before writing anything (classify on the
code; the class is internal), and the
clean session is released normally. Reads, unlinks and links of at most
LINK_CHUNK_ROWS rows work as before.
Process warnings from this path:
| Code | Meaning |
|---|---|
| NODII_PII_EVICT_NO_HANDLE | Once per process, at the first statement on such a pool: the pool does not pass query options through, so multi-chunk links will be refused. |
| NODII_PII_EVICT_HELD | Last defence, unreachable through linkRecordSubjects: an eviction found no connection handle, so the reservation is held out of the pool. |
| NODII_PII_EVICT_TIMEOUT | An evicted socket did not report closed within 5 s; its slot returns only when it does. Carries the number of such evictions still unclosed in the process. |
Deferred to v0.1.x
- Real AWS SDK v3 KMS + Secrets Manager wiring (typed interfaces ship now).
- Augmented Drizzle column types (
piiText,piiNumeric,piiJsonb) + INSERT/UPDATE/SELECT middleware. - Migration generator CLI (
npx @nodii/pii migrate-gen <serviceName>). - Bulk streaming (
encryptStream). - The full DSAR doctrine integration (gather-walk through the subject tree).
See .agent-todo.md at the repo root.
