@platform-sec/sensitive-string-core 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bson.d.ts +28 -0
- package/dist/bson.d.ts.map +1 -0
- package/dist/bson.js +37 -0
- package/dist/bson.js.map +1 -0
- package/dist/classification.d.ts +69 -0
- package/dist/classification.d.ts.map +1 -0
- package/dist/classification.js +104 -0
- package/dist/classification.js.map +1 -0
- package/dist/compare.d.ts +36 -0
- package/dist/compare.d.ts.map +1 -0
- package/dist/compare.js +123 -0
- package/dist/compare.js.map +1 -0
- package/dist/context.d.ts +78 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +110 -0
- package/dist/context.js.map +1 -0
- package/dist/derive.d.ts +110 -0
- package/dist/derive.d.ts.map +1 -0
- package/dist/derive.js +153 -0
- package/dist/derive.js.map +1 -0
- package/dist/destination.d.ts +120 -0
- package/dist/destination.d.ts.map +1 -0
- package/dist/destination.js +352 -0
- package/dist/destination.js.map +1 -0
- package/dist/deterministic.d.ts +145 -0
- package/dist/deterministic.d.ts.map +1 -0
- package/dist/deterministic.js +352 -0
- package/dist/deterministic.js.map +1 -0
- package/dist/dev-mode.d.ts +177 -0
- package/dist/dev-mode.d.ts.map +1 -0
- package/dist/dev-mode.js +503 -0
- package/dist/dev-mode.js.map +1 -0
- package/dist/environment.d.ts +181 -0
- package/dist/environment.d.ts.map +1 -0
- package/dist/environment.js +558 -0
- package/dist/environment.js.map +1 -0
- package/dist/errors.d.ts +23 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +21 -0
- package/dist/errors.js.map +1 -0
- package/dist/global-state.d.ts +8 -0
- package/dist/global-state.d.ts.map +1 -0
- package/dist/global-state.js +22 -0
- package/dist/global-state.js.map +1 -0
- package/dist/hash.d.ts +74 -0
- package/dist/hash.d.ts.map +1 -0
- package/dist/hash.js +253 -0
- package/dist/hash.js.map +1 -0
- package/dist/hygiene.d.ts +242 -0
- package/dist/hygiene.d.ts.map +1 -0
- package/dist/hygiene.js +257 -0
- package/dist/hygiene.js.map +1 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +233 -0
- package/dist/index.js.map +1 -0
- package/dist/mask.d.ts +51 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +461 -0
- package/dist/mask.js.map +1 -0
- package/dist/own-property.d.ts +20 -0
- package/dist/own-property.d.ts.map +1 -0
- package/dist/own-property.js +34 -0
- package/dist/own-property.js.map +1 -0
- package/dist/patterns.d.ts +12 -0
- package/dist/patterns.d.ts.map +1 -0
- package/dist/patterns.js +19 -0
- package/dist/patterns.js.map +1 -0
- package/dist/policy.d.ts +51 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +181 -0
- package/dist/policy.js.map +1 -0
- package/dist/probe.d.ts +141 -0
- package/dist/probe.d.ts.map +1 -0
- package/dist/probe.js +213 -0
- package/dist/probe.js.map +1 -0
- package/dist/redact-copy.d.ts +61 -0
- package/dist/redact-copy.d.ts.map +1 -0
- package/dist/redact-copy.js +217 -0
- package/dist/redact-copy.js.map +1 -0
- package/dist/redact.d.ts +141 -0
- package/dist/redact.d.ts.map +1 -0
- package/dist/redact.js +514 -0
- package/dist/redact.js.map +1 -0
- package/dist/redaction-marker.d.ts +48 -0
- package/dist/redaction-marker.d.ts.map +1 -0
- package/dist/redaction-marker.js +138 -0
- package/dist/redaction-marker.js.map +1 -0
- package/dist/redaction-observer.d.ts +108 -0
- package/dist/redaction-observer.d.ts.map +1 -0
- package/dist/redaction-observer.js +103 -0
- package/dist/redaction-observer.js.map +1 -0
- package/dist/redaction-scope.d.ts +21 -0
- package/dist/redaction-scope.d.ts.map +1 -0
- package/dist/redaction-scope.js +44 -0
- package/dist/redaction-scope.js.map +1 -0
- package/dist/reference.d.ts +101 -0
- package/dist/reference.d.ts.map +1 -0
- package/dist/reference.js +123 -0
- package/dist/reference.js.map +1 -0
- package/dist/regexp.d.ts +25 -0
- package/dist/regexp.d.ts.map +1 -0
- package/dist/regexp.js +61 -0
- package/dist/regexp.js.map +1 -0
- package/dist/release.d.ts +88 -0
- package/dist/release.d.ts.map +1 -0
- package/dist/release.js +108 -0
- package/dist/release.js.map +1 -0
- package/dist/reveal-budget.d.ts +148 -0
- package/dist/reveal-budget.d.ts.map +1 -0
- package/dist/reveal-budget.js +314 -0
- package/dist/reveal-budget.js.map +1 -0
- package/dist/revocation.d.ts +168 -0
- package/dist/revocation.d.ts.map +1 -0
- package/dist/revocation.js +541 -0
- package/dist/revocation.js.map +1 -0
- package/dist/sealing.d.ts +283 -0
- package/dist/sealing.d.ts.map +1 -0
- package/dist/sealing.js +523 -0
- package/dist/sealing.js.map +1 -0
- package/dist/sensitive-string.d.ts +919 -0
- package/dist/sensitive-string.d.ts.map +1 -0
- package/dist/sensitive-string.js +2260 -0
- package/dist/sensitive-string.js.map +1 -0
- package/dist/serialized.d.ts +33 -0
- package/dist/serialized.d.ts.map +1 -0
- package/dist/serialized.js +65 -0
- package/dist/serialized.js.map +1 -0
- package/dist/template.d.ts +69 -0
- package/dist/template.d.ts.map +1 -0
- package/dist/template.js +158 -0
- package/dist/template.js.map +1 -0
- package/dist/ttl.d.ts +104 -0
- package/dist/ttl.d.ts.map +1 -0
- package/dist/ttl.js +330 -0
- package/dist/ttl.js.map +1 -0
- package/dist/types.d.ts +859 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +13 -0
- package/dist/types.js.map +1 -0
- package/dist/winston.d.ts +114 -0
- package/dist/winston.d.ts.map +1 -0
- package/dist/winston.js +170 -0
- package/dist/winston.js.map +1 -0
- package/dist/worker.d.ts +398 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +861 -0
- package/dist/worker.js.map +1 -0
- package/dist/wrap.d.ts +287 -0
- package/dist/wrap.d.ts.map +1 -0
- package/dist/wrap.js +553 -0
- package/dist/wrap.js.map +1 -0
- package/package.json +10 -10
|
@@ -0,0 +1,2260 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var _a;
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.SensitiveString = exports.renderStructureRedaction = exports.unshareableConstraints = exports.serializeSensitiveString = exports.deriveSensitiveString = void 0;
|
|
5
|
+
const compare_js_1 = require("./compare.js");
|
|
6
|
+
const policy_js_1 = require("./policy.js");
|
|
7
|
+
const context_js_1 = require("./context.js");
|
|
8
|
+
const redaction_scope_js_1 = require("./redaction-scope.js");
|
|
9
|
+
const bson_js_1 = require("./bson.js");
|
|
10
|
+
const mask_js_1 = require("./mask.js");
|
|
11
|
+
const hash_js_1 = require("./hash.js");
|
|
12
|
+
const dev_mode_js_1 = require("./dev-mode.js");
|
|
13
|
+
const ttl_js_1 = require("./ttl.js");
|
|
14
|
+
const reveal_budget_js_1 = require("./reveal-budget.js");
|
|
15
|
+
const revocation_js_1 = require("./revocation.js");
|
|
16
|
+
const environment_js_1 = require("./environment.js");
|
|
17
|
+
const destination_js_1 = require("./destination.js");
|
|
18
|
+
const release_js_1 = require("./release.js");
|
|
19
|
+
const regexp_js_1 = require("./regexp.js");
|
|
20
|
+
const sealing_js_1 = require("./sealing.js");
|
|
21
|
+
const hygiene_js_1 = require("./hygiene.js");
|
|
22
|
+
const redaction_observer_js_1 = require("./redaction-observer.js");
|
|
23
|
+
/**
|
|
24
|
+
* Node.js custom inspect symbol for util.inspect() and console.log().
|
|
25
|
+
*/
|
|
26
|
+
const NODE_INSPECT_SYMBOL = Symbol.for('nodejs.util.inspect.custom');
|
|
27
|
+
/**
|
|
28
|
+
* Name the kind of value the constructor refused, and nothing of its content:
|
|
29
|
+
* the message may be logged, and an object or array can hold the secret that
|
|
30
|
+
* was meant to be protected.
|
|
31
|
+
*/
|
|
32
|
+
function describeNonString(value) {
|
|
33
|
+
if (value === null || value === undefined) {
|
|
34
|
+
return String(value);
|
|
35
|
+
}
|
|
36
|
+
if (value instanceof SensitiveString) {
|
|
37
|
+
return 'a SensitiveString';
|
|
38
|
+
}
|
|
39
|
+
if (Array.isArray(value)) {
|
|
40
|
+
return 'an array';
|
|
41
|
+
}
|
|
42
|
+
const type = typeof value;
|
|
43
|
+
return type === 'object' ? 'an object' : `a ${type}`;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The audit record every operation but `mask()` reports. Shared and frozen: it
|
|
47
|
+
* is handed to caller-supplied audit hooks.
|
|
48
|
+
*/
|
|
49
|
+
const REVEAL_AUDIT_DETAILS = Object.freeze({ operation: 'reveal' });
|
|
50
|
+
/**
|
|
51
|
+
* Two inputs a policy's `redact` is asked about, to learn whether its output
|
|
52
|
+
* depends on what it is given.
|
|
53
|
+
*
|
|
54
|
+
* Obvious non-secrets, and never anything a caller supplied: they exist to be
|
|
55
|
+
* discarded. `registerPolicy` already runs a caller's redactor over canaries of
|
|
56
|
+
* its own at registration, so probing one is not a new kind of thing to do.
|
|
57
|
+
*/
|
|
58
|
+
const REDACTION_PROBE_A = 'sensitive-string-probe-a';
|
|
59
|
+
const REDACTION_PROBE_B = 'sensitive-string-probe-b';
|
|
60
|
+
/**
|
|
61
|
+
* Whether a policy's rendering depends on the value it is handed.
|
|
62
|
+
*
|
|
63
|
+
* The default policies and almost every custom one emit a constant marker and
|
|
64
|
+
* ignore the argument. Deterministic redaction does not: its whole purpose is a
|
|
65
|
+
* tag derived from the value, so two values must render differently.
|
|
66
|
+
*
|
|
67
|
+
* Only `fromBuffer` asks, and only because the answer decides whether it has to
|
|
68
|
+
* decode the plaintext to render it. A redactor that answers `true` for an
|
|
69
|
+
* unrelated reason, one that is random rather than value-derived, costs that
|
|
70
|
+
* decode and nothing else.
|
|
71
|
+
*/
|
|
72
|
+
function redactionReadsValue(policy) {
|
|
73
|
+
try {
|
|
74
|
+
return policy.redact(REDACTION_PROBE_A) !== policy.redact(REDACTION_PROBE_B);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
// A broken redactor renders as the class marker anyway, through the
|
|
78
|
+
// fallback in `#sealFromBytes`. Nothing here needs the plaintext.
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* How a caller uses the raw value determines authorization and auditing.
|
|
84
|
+
* Safe reads only feed redaction or intentionally public metadata. Comparisons
|
|
85
|
+
* are authorized but are not reveals. Exposing reads are authorized and audited.
|
|
86
|
+
*/
|
|
87
|
+
/**
|
|
88
|
+
* Refuse a policy hook's answer unless it is the one the gate can act on.
|
|
89
|
+
*
|
|
90
|
+
* `checkRevealAllowed` denies by throwing, so its only meaningful return is
|
|
91
|
+
* `undefined`. TypeScript accepts an `async` function where a `void`-returning
|
|
92
|
+
* one is expected, and an `async` hook that throws after its first `await`
|
|
93
|
+
* throws into a Promise nobody reads, after the gate has already handed the
|
|
94
|
+
* raw value back: the hook fails open, silently, on exactly the reads it was
|
|
95
|
+
* written to refuse. The declared type is `undefined`, which rejects the
|
|
96
|
+
* `async` form at compile time; this is the same rule at runtime, for a hook
|
|
97
|
+
* written in JavaScript or cast past the type. A Promise cannot deny a read
|
|
98
|
+
* that has already returned, so returning one is treated as a denial, and so
|
|
99
|
+
* is any other value: a hook that returns `false` meant to deny.
|
|
100
|
+
*/
|
|
101
|
+
function refuseHookReturn(returned, klass) {
|
|
102
|
+
if (returned === undefined) {
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const why = isThenable(returned)
|
|
106
|
+
? 'a Promise. The hook must be synchronous: a Promise cannot deny a read that has already returned'
|
|
107
|
+
: `${returned === null ? 'null' : `a ${typeof returned}`}. The hook denies by throwing and must return undefined`;
|
|
108
|
+
throw new TypeError(`checkRevealAllowed for sensitivity class '${klass}' returned ${why}`);
|
|
109
|
+
}
|
|
110
|
+
function isThenable(value) {
|
|
111
|
+
return ((typeof value === 'object' || typeof value === 'function') &&
|
|
112
|
+
value !== null &&
|
|
113
|
+
typeof value.then === 'function');
|
|
114
|
+
}
|
|
115
|
+
function isConstrained(state) {
|
|
116
|
+
return state.budget !== undefined;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The shared empty array every unconstrained value points at, so a value that
|
|
120
|
+
* configures no limits allocates nothing for the ones it does not have.
|
|
121
|
+
*/
|
|
122
|
+
const NO_BUDGETS = Object.freeze([]);
|
|
123
|
+
/** The same, for a derivative between construction and adopting its sources. */
|
|
124
|
+
const NO_STATES = Object.freeze([]);
|
|
125
|
+
/**
|
|
126
|
+
* The subset of these states that limits reveals.
|
|
127
|
+
*
|
|
128
|
+
* A filtered view of `#states` rather than a second source of truth: the state
|
|
129
|
+
* objects are the same ones, so the two cannot disagree about a count. It
|
|
130
|
+
* exists so the gate can dismiss the overwhelmingly common unconstrained case
|
|
131
|
+
* with a length check instead of a walk.
|
|
132
|
+
*/
|
|
133
|
+
function constrainedStates(states) {
|
|
134
|
+
let constrained;
|
|
135
|
+
for (const state of states) {
|
|
136
|
+
if (isConstrained(state)) {
|
|
137
|
+
(constrained ??= []).push(state);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return constrained ?? NO_BUDGETS;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Every restriction set these states carry, flattened.
|
|
144
|
+
*
|
|
145
|
+
* The same shape as the constrained view above and for the same reason: the
|
|
146
|
+
* gate dismisses the overwhelmingly common unrestricted case with a length
|
|
147
|
+
* check instead of walking states that restrict nothing.
|
|
148
|
+
*/
|
|
149
|
+
function restrictedStates(states) {
|
|
150
|
+
let restrictions;
|
|
151
|
+
for (const state of states) {
|
|
152
|
+
if (state.restrictions !== undefined) {
|
|
153
|
+
(restrictions ??= []).push(...state.restrictions);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return restrictions ?? environment_js_1.NO_RESTRICTIONS;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Every destination binding these states carry, flattened, on the same shape
|
|
160
|
+
* and for the same reason as the restricted view above.
|
|
161
|
+
*/
|
|
162
|
+
function boundStates(states) {
|
|
163
|
+
let destinations;
|
|
164
|
+
for (const state of states) {
|
|
165
|
+
if (state.destinations !== undefined) {
|
|
166
|
+
(destinations ??= []).push(...state.destinations);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return destinations ?? destination_js_1.NO_DESTINATIONS;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Passed in place of options by `#derived`, which supplies the state of the
|
|
173
|
+
* values the derivative came from instead of planning its own.
|
|
174
|
+
*
|
|
175
|
+
* Without it a derived value would be planned as a fresh one, and a class whose
|
|
176
|
+
* policy sets `requireExpiration` would refuse to produce a substring of a value
|
|
177
|
+
* that does have a deadline. The symbol is module-private and unreachable from
|
|
178
|
+
* a caller, so the only way onto this path is from inside the class.
|
|
179
|
+
*/
|
|
180
|
+
const DERIVED_CONSTRUCTION = Symbol('SensitiveString.derived');
|
|
181
|
+
/**
|
|
182
|
+
* Secure wrapper for sensitive string data.
|
|
183
|
+
*
|
|
184
|
+
* Features:
|
|
185
|
+
* - Runtime encapsulation via ES2022 #private fields.
|
|
186
|
+
* - Automatic redaction in `toString()`, `toJSON()`, and `util.inspect()`.
|
|
187
|
+
* - Constant-time comparison for credentials.
|
|
188
|
+
* - Audit hooks on access via `reveal()`.
|
|
189
|
+
*
|
|
190
|
+
* @typeParam C - Sensitivity class ('sensitive' | 'credential').
|
|
191
|
+
*
|
|
192
|
+
* @example
|
|
193
|
+
* ```ts
|
|
194
|
+
* const apiKey = new SensitiveString(process.env.API_KEY!, 'credential', 'api_key');
|
|
195
|
+
* console.log(apiKey); // SensitiveString<credential:api_key> { [REDACTED:credential] }
|
|
196
|
+
*
|
|
197
|
+
* // Explicit access with audit context
|
|
198
|
+
* const raw = apiKey.reveal({ name: 'api-call', reason: 'authenticating' });
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
/**
|
|
202
|
+
* ISO 8601 renderings of deadlines, memoized.
|
|
203
|
+
*
|
|
204
|
+
* `serialize()` formatted one on every call, which cost more than the rest of
|
|
205
|
+
* the method put together. A deadline is a plain number that already travels
|
|
206
|
+
* on the wire in this form, so nothing secret is held here. Keyed by the
|
|
207
|
+
* deadline itself, so a renewal misses and re-renders on its own.
|
|
208
|
+
*/
|
|
209
|
+
const isoDeadlines = new Map();
|
|
210
|
+
function isoDeadline(deadline) {
|
|
211
|
+
let iso = isoDeadlines.get(deadline);
|
|
212
|
+
if (iso === undefined) {
|
|
213
|
+
iso = new Date(deadline).toISOString();
|
|
214
|
+
// A service with many distinct deadlines must not grow this without bound.
|
|
215
|
+
if (isoDeadlines.size >= 256) {
|
|
216
|
+
isoDeadlines.clear();
|
|
217
|
+
}
|
|
218
|
+
isoDeadlines.set(deadline, iso);
|
|
219
|
+
}
|
|
220
|
+
return iso;
|
|
221
|
+
}
|
|
222
|
+
class SensitiveString {
|
|
223
|
+
/**
|
|
224
|
+
* The raw value, when this instance is not sealed. Using ES2022 #private for
|
|
225
|
+
* true runtime encapsulation: this field is inaccessible outside the class,
|
|
226
|
+
* even via reflection or type coercion.
|
|
227
|
+
*
|
|
228
|
+
* `undefined` exactly when {@link SensitiveString.#box} is set. The two are
|
|
229
|
+
* never both present, and the one that is present is chosen once at
|
|
230
|
+
* construction and never changes afterwards.
|
|
231
|
+
*/
|
|
232
|
+
#value;
|
|
233
|
+
/**
|
|
234
|
+
* The value as AES-256-GCM ciphertext, when this instance is sealed.
|
|
235
|
+
*
|
|
236
|
+
* `generation || iv || ciphertext || tag`, one `Buffer`, 32 bytes of
|
|
237
|
+
* overhead. Its bytes are external to the V8 heap, so a heap snapshot does
|
|
238
|
+
* not record them, and it can be zeroed, which a string can never be.
|
|
239
|
+
*
|
|
240
|
+
* Everything that reads it goes through `#open()`, which is reachable only
|
|
241
|
+
* from inside the gate.
|
|
242
|
+
*/
|
|
243
|
+
#box;
|
|
244
|
+
/**
|
|
245
|
+
* The value's length in UTF-16 code units, captured at construction, for a
|
|
246
|
+
* sealed instance only.
|
|
247
|
+
*
|
|
248
|
+
* `length` is a `'safe'` read: it needs no authorization, and answering it by
|
|
249
|
+
* decrypting would put a plaintext string in the heap for a question that is
|
|
250
|
+
* documented as not sensitive. Meaningless while `#box` is `undefined`, where
|
|
251
|
+
* the string answers for itself.
|
|
252
|
+
*/
|
|
253
|
+
#sealedLength = 0;
|
|
254
|
+
/**
|
|
255
|
+
* State inherited from the values this instance was derived from. Multiple
|
|
256
|
+
* sources are retained for concat so future constraints and counters remain
|
|
257
|
+
* shared without dropping either parent.
|
|
258
|
+
*/
|
|
259
|
+
#states = NO_STATES;
|
|
260
|
+
/**
|
|
261
|
+
* The states above that limit reveals, assigned only through `#adopt` so it
|
|
262
|
+
* cannot drift from `#states`. Empty for a value with no limits, which is
|
|
263
|
+
* how the gate skips the whole feature in one comparison.
|
|
264
|
+
*/
|
|
265
|
+
#constrained = NO_BUDGETS;
|
|
266
|
+
/**
|
|
267
|
+
* The restrictions of every state above, flattened, so the gate answers with
|
|
268
|
+
* a length check on a value that has none.
|
|
269
|
+
*/
|
|
270
|
+
#restrictions = environment_js_1.NO_RESTRICTIONS;
|
|
271
|
+
/**
|
|
272
|
+
* The destination bindings of every state above, flattened, so the gate
|
|
273
|
+
* answers with a length check on a value that has none.
|
|
274
|
+
*/
|
|
275
|
+
#destinations = destination_js_1.NO_DESTINATIONS;
|
|
276
|
+
/**
|
|
277
|
+
* This instance's own state, or undefined when it was derived from other
|
|
278
|
+
* values. Only an owner may renew: a derivative shares its sources' state by
|
|
279
|
+
* reference, so renewing through one would silently extend the lifetime of
|
|
280
|
+
* the value it came from, and of every other derivative of it.
|
|
281
|
+
*/
|
|
282
|
+
#own;
|
|
283
|
+
/**
|
|
284
|
+
* This instance's own clear, epoch milliseconds, or `undefined`.
|
|
285
|
+
*
|
|
286
|
+
* Set on any instance, owner or derivative. The shared `clearedAt` beside it
|
|
287
|
+
* says a value this one was built from was destroyed; this one says this
|
|
288
|
+
* instance dropped its own copy of the plaintext, which is a separate fact
|
|
289
|
+
* with a separate consequence: only the second releases anything.
|
|
290
|
+
*/
|
|
291
|
+
#ownClearedAt;
|
|
292
|
+
/**
|
|
293
|
+
* The redacted rendering, taken by `clear()` from the live value immediately
|
|
294
|
+
* before it is dropped, or `undefined` on a value that still has one.
|
|
295
|
+
*
|
|
296
|
+
* Retaining it discloses nothing the design had not already accepted: it is
|
|
297
|
+
* the string the policy exists to emit in place of the value, so a copy of it
|
|
298
|
+
* is what a log line would have held anyway.
|
|
299
|
+
*/
|
|
300
|
+
#redaction;
|
|
301
|
+
/**
|
|
302
|
+
* The sensitivity classification for this value.
|
|
303
|
+
*/
|
|
304
|
+
klass;
|
|
305
|
+
/**
|
|
306
|
+
* Optional label for audit/compliance categorization.
|
|
307
|
+
* Examples: 'api_key', 'email', 'ssn', 'session_token'
|
|
308
|
+
*/
|
|
309
|
+
label;
|
|
310
|
+
/**
|
|
311
|
+
* Create a new SensitiveString.
|
|
312
|
+
*
|
|
313
|
+
* @param value - The raw string value to protect
|
|
314
|
+
* @param klass - The sensitivity classification ('credential' or 'sensitive')
|
|
315
|
+
* @param label - Optional label for audit/compliance (e.g., 'api_key', 'email')
|
|
316
|
+
* @param options - Shared options for access constraints and feature behavior
|
|
317
|
+
* @throws Error If both `ttl` and `expiresAt` are given, if only one half of the rate limit is given, if a restriction set expresses no restriction, or if the class policy requires an expiration and neither is.
|
|
318
|
+
* @throws TypeError If `value` is not a string, or an option has the wrong type.
|
|
319
|
+
* @throws RangeError If `ttl` is negative, `expiresAt` is an invalid Date, a reveal limit is out of range, or a restriction list is empty or holds a pattern that is neither a literal name nor a prefix.
|
|
320
|
+
*/
|
|
321
|
+
constructor(value, klass, label, options) {
|
|
322
|
+
// Anything but a string would still redact, and then fail far from here:
|
|
323
|
+
// a number breaks `equals()` inside Buffer.from, and an instance wrapped
|
|
324
|
+
// again reveals the inner instance instead of its value. Refusing at
|
|
325
|
+
// construction keeps a wrong value from surviving long enough to be trusted.
|
|
326
|
+
if (typeof value !== 'string') {
|
|
327
|
+
throw new TypeError(`SensitiveString expects a string value; received ${describeNonString(value)}`);
|
|
328
|
+
}
|
|
329
|
+
this.#value = value;
|
|
330
|
+
this.klass = klass;
|
|
331
|
+
this.label = label;
|
|
332
|
+
// Before the derived early return, so a substring of a value is tracked in
|
|
333
|
+
// its own right. The guard is one property read when development mode is
|
|
334
|
+
// off, which is what production pays for the feature.
|
|
335
|
+
if (dev_mode_js_1.devMode.config.enabled) {
|
|
336
|
+
(0, dev_mode_js_1.recordCreation)(this);
|
|
337
|
+
}
|
|
338
|
+
// Before the derived early return, and for the reason tracking exists: a
|
|
339
|
+
// derivative of 13 characters or more pins its origin's whole backing
|
|
340
|
+
// store, so it is the value a bulk clear most needs to reach, and it is
|
|
341
|
+
// usually a local whose holder a caller cannot name. Registering after the
|
|
342
|
+
// return would track origins only.
|
|
343
|
+
//
|
|
344
|
+
// Freezing goes here too, after the last own-property write and before
|
|
345
|
+
// both returns, so an owner and a derivative are frozen alike. Every
|
|
346
|
+
// assignment below this point is to a `#private` field, which `Object.freeze`
|
|
347
|
+
// does not touch.
|
|
348
|
+
if (hygiene_js_1.hygiene.config.trackInstances) {
|
|
349
|
+
(0, hygiene_js_1.trackInstance)(this);
|
|
350
|
+
}
|
|
351
|
+
if (hygiene_js_1.hygiene.config.freezeInstances) {
|
|
352
|
+
Object.freeze(this);
|
|
353
|
+
}
|
|
354
|
+
if (options === DERIVED_CONSTRUCTION) {
|
|
355
|
+
// #derived assigns the sources' state objects immediately after this
|
|
356
|
+
// returns. Planning state here would be discarded, and a policy that
|
|
357
|
+
// requires an expiration would reject a derivative that has one.
|
|
358
|
+
this.#own = undefined;
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const state = {
|
|
362
|
+
options: options ?? {},
|
|
363
|
+
expiry: (0, ttl_js_1.planExpiry)(options, klass, (0, policy_js_1.getPolicy)(klass)),
|
|
364
|
+
reveals: 0,
|
|
365
|
+
budget: (0, reveal_budget_js_1.planRevealBudget)(options),
|
|
366
|
+
revocation: (0, revocation_js_1.planRevocation)(options, label),
|
|
367
|
+
restrictions: (0, environment_js_1.planRestrictions)(options),
|
|
368
|
+
destinations: (0, destination_js_1.planDestinations)(options),
|
|
369
|
+
release: (0, release_js_1.planRelease)(options),
|
|
370
|
+
clearedAt: undefined,
|
|
371
|
+
};
|
|
372
|
+
this.#own = state;
|
|
373
|
+
this.#adopt([state]);
|
|
374
|
+
// Last in the constructor, so a value that fails to seal fails after every
|
|
375
|
+
// other check has passed rather than in place of one. `#derived` does its
|
|
376
|
+
// own sealing after the early return above, because a derivative takes its
|
|
377
|
+
// storage from its sources rather than from the process default.
|
|
378
|
+
if (options?.sealed ?? sealing_js_1.sealing.config.sealByDefault) {
|
|
379
|
+
this.#seal(value, options?.sealed === true && sealing_js_1.sealing.config.strict);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Move this instance's value from a string into a box, and drop the string.
|
|
384
|
+
*
|
|
385
|
+
* Called once, from the constructor or from `#derived`, and never again: an
|
|
386
|
+
* instance is sealed or it is not, decided before any caller can observe it.
|
|
387
|
+
*
|
|
388
|
+
* `required` decides only what happens when sealing is unavailable. Each call
|
|
389
|
+
* site works it out for itself, because the two have different reasons: the
|
|
390
|
+
* constructor asks whether the caller named `sealed: true` and whether
|
|
391
|
+
* `strict` is on, and `#derived` always requires it, because a derivative
|
|
392
|
+
* that fell back to a plaintext string is the R2 bypass the propagation
|
|
393
|
+
* exists to close. `strict` is a preference about a caller's request; it has
|
|
394
|
+
* no say over a rule.
|
|
395
|
+
*/
|
|
396
|
+
#seal(value, required) {
|
|
397
|
+
const bytes = Buffer.from(value, 'utf8');
|
|
398
|
+
try {
|
|
399
|
+
this.#sealFromBytes(bytes, value.length, value);
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
if (error instanceof sealing_js_1.SealingUnavailableError && !required) {
|
|
403
|
+
// The value stays a string. Not silent: `isSealed` reports false, which
|
|
404
|
+
// is the same answer it gives in a process that never configured
|
|
405
|
+
// sealing, and `strict` defaults to true precisely so a caller who
|
|
406
|
+
// asked by name is refused instead.
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
finally {
|
|
412
|
+
bytes.fill(0);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Seal from bytes that already exist, which is the path `fromBuffer` needs.
|
|
417
|
+
*
|
|
418
|
+
* The caller owns `bytes` and zeroes them; this reads them and nothing else.
|
|
419
|
+
*
|
|
420
|
+
* `rendered` is what the class policy is asked to redact. It is the live
|
|
421
|
+
* value on the constructor path. On the `fromBuffer` path there is no live
|
|
422
|
+
* value, so it is the empty string when the policy's rendering does not
|
|
423
|
+
* depend on its argument and the decoded plaintext when it does; `fromBuffer`
|
|
424
|
+
* decides which, because only it knows what that decision costs.
|
|
425
|
+
*/
|
|
426
|
+
#sealFromBytes(bytes, codeUnits, rendered) {
|
|
427
|
+
// The rendering is captured rather than computed later, and this is the one
|
|
428
|
+
// place in the library where a rendering outlives the value it came from.
|
|
429
|
+
// Deterministic redaction reads the raw value, so a policy that HMACs it
|
|
430
|
+
// would otherwise force a decrypt on every log line, and computing the tag
|
|
431
|
+
// after the value was sealed would be worse still.
|
|
432
|
+
//
|
|
433
|
+
// The seal goes first, and before anything is written. `sealBytes` can refuse, and
|
|
434
|
+
// `#seal` may then fall back to leaving this a plaintext value; an instance
|
|
435
|
+
// that took that path has to be indistinguishable from one that never asked
|
|
436
|
+
// to be sealed, which it would not be if it were already carrying a frozen
|
|
437
|
+
// rendering.
|
|
438
|
+
const box = (0, sealing_js_1.sealBytes)(bytes, (0, sealing_js_1.additionalData)(this.klass, this.label), this.label);
|
|
439
|
+
// A custom redact that throws must not undo the seal, for the reason
|
|
440
|
+
// `clear()` gives for the same fallback: refusing to protect a secret
|
|
441
|
+
// because its renderer is broken is the wrong way to fail.
|
|
442
|
+
try {
|
|
443
|
+
this.#redaction ??= this.policy.redact(rendered);
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
this.#redaction = `[REDACTED:${this.klass}]`;
|
|
447
|
+
}
|
|
448
|
+
this.#box = box;
|
|
449
|
+
this.#sealedLength = codeUnits;
|
|
450
|
+
this.#value = undefined;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Decrypt this instance's box into bytes the caller owns and may zero.
|
|
454
|
+
*
|
|
455
|
+
* Private, and called only from the two gated readers, which is what
|
|
456
|
+
* `INV-SEAL-003` rests on: there is no path to a decryption that has not
|
|
457
|
+
* already run the expiry, revocation, restriction, budget, policy and audit
|
|
458
|
+
* steps.
|
|
459
|
+
*/
|
|
460
|
+
#open() {
|
|
461
|
+
return (0, sealing_js_1.openBox)(this.#box, (0, sealing_js_1.additionalData)(this.klass, this.label), this.label);
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Take on a set of shared states.
|
|
465
|
+
*
|
|
466
|
+
* The only assignment to `#states`, so the constrained view is never left
|
|
467
|
+
* behind by a derivation that forgot it. A derivation that dropped the view
|
|
468
|
+
* would hand back an unlimited copy of a value that was meant to be spent.
|
|
469
|
+
*/
|
|
470
|
+
#adopt(states, constrained, restricted, bound) {
|
|
471
|
+
this.#states = states;
|
|
472
|
+
this.#constrained = constrained ?? constrainedStates(states);
|
|
473
|
+
this.#restrictions = restricted ?? restrictedStates(states);
|
|
474
|
+
this.#destinations = bound ?? boundStates(states);
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Get the policy for this instance's sensitivity class.
|
|
478
|
+
*/
|
|
479
|
+
get policy() {
|
|
480
|
+
return (0, policy_js_1.getPolicy)(this.klass);
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* The earliest deadline among the values this one was built from, or
|
|
484
|
+
* undefined when none of them expires.
|
|
485
|
+
*
|
|
486
|
+
* Private on purpose: `serialize()` puts this on the wire, so it must not read
|
|
487
|
+
* an `expiresAt` getter that a subclass could override.
|
|
488
|
+
*/
|
|
489
|
+
#earliestDeadline() {
|
|
490
|
+
let earliest;
|
|
491
|
+
for (const state of this.#states) {
|
|
492
|
+
const { deadline } = state.expiry;
|
|
493
|
+
if (deadline !== undefined && (earliest === undefined || deadline < earliest)) {
|
|
494
|
+
earliest = deadline;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return earliest;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* The earliest deadline this value has passed, or undefined while it is live.
|
|
501
|
+
*
|
|
502
|
+
* Private on purpose: the gate must not route its decision through the public
|
|
503
|
+
* `isExpired()`, which a subclass could override to lift it.
|
|
504
|
+
*/
|
|
505
|
+
#expiredDeadline(notify) {
|
|
506
|
+
// Read at most once, and only when a state can actually expire. An
|
|
507
|
+
// unconditional read cost more than the rest of the gate put together on a
|
|
508
|
+
// value with no deadline, which is most of them.
|
|
509
|
+
let now = -1;
|
|
510
|
+
let earliest;
|
|
511
|
+
// Every source state is checked rather than only the first match, so a
|
|
512
|
+
// derivative of two expiring values fires both onExpire callbacks.
|
|
513
|
+
for (const state of this.#states) {
|
|
514
|
+
if (state.expiry.deadline === undefined) {
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (now < 0) {
|
|
518
|
+
now = Date.now();
|
|
519
|
+
}
|
|
520
|
+
const deadline = (0, ttl_js_1.expiredDeadline)(state.expiry, now, notify);
|
|
521
|
+
if (deadline !== undefined && (earliest === undefined || deadline < earliest)) {
|
|
522
|
+
earliest = deadline;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return earliest;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* The earliest clear affecting this value: its own, or one that destroyed a
|
|
529
|
+
* value it was derived from.
|
|
530
|
+
*
|
|
531
|
+
* Mirrors `#earliestDeadline`, and private for the same reason: the gate must
|
|
532
|
+
* not route its decision through a public `isCleared` that a subclass could
|
|
533
|
+
* override. Reporting the earliest rather than the most recent means an error
|
|
534
|
+
* says when the value stopped being usable rather than when the last clear in
|
|
535
|
+
* its lineage happened to run.
|
|
536
|
+
*/
|
|
537
|
+
#clearedFlag() {
|
|
538
|
+
let earliest = this.#ownClearedAt;
|
|
539
|
+
for (const state of this.#states) {
|
|
540
|
+
const { clearedAt } = state;
|
|
541
|
+
if (clearedAt !== undefined && (earliest === undefined || clearedAt < earliest)) {
|
|
542
|
+
earliest = clearedAt;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return earliest;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Refuse an operation that needs a value this process has destroyed.
|
|
549
|
+
*
|
|
550
|
+
* Written once because three callers need it: the gate, and the two `'safe'`
|
|
551
|
+
* readers that are exempt from the gate and have nothing to fall back on.
|
|
552
|
+
*/
|
|
553
|
+
#refuseIfCleared() {
|
|
554
|
+
const cleared = this.#clearedFlag();
|
|
555
|
+
if (cleared !== undefined) {
|
|
556
|
+
throw new hygiene_js_1.ClearedSensitiveValueError(new Date(cleared), new Date(), this.label);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* The sole accessor for #value.
|
|
561
|
+
*
|
|
562
|
+
* Feature-level checks such as expiry, revocation, and environment
|
|
563
|
+
* restrictions belong here so no operation can bypass them. Redaction and
|
|
564
|
+
* documented metadata reads stay available even when access is denied.
|
|
565
|
+
*/
|
|
566
|
+
#readRawValue(access, ctx, details = REVEAL_AUDIT_DETAILS) {
|
|
567
|
+
if (access === 'safe') {
|
|
568
|
+
if (this.#box !== undefined) {
|
|
569
|
+
// A safe read is one that needs no authorization, and a sealed value
|
|
570
|
+
// has none to give: decrypting for a log line would put a plaintext
|
|
571
|
+
// string in the heap on every logged object, which is the thing sealing
|
|
572
|
+
// exists to avoid. Every safe caller in this class answers a sealed
|
|
573
|
+
// value from `#redaction` or `#sealedLength` instead, so reaching here
|
|
574
|
+
// is a bug in this file rather than a caller error, and throwing is
|
|
575
|
+
// what turns "somebody added a fourth safe reader" into a test failure
|
|
576
|
+
// instead of a silent per-call decrypt.
|
|
577
|
+
throw new Error('internal: a safe read reached a sealed value');
|
|
578
|
+
}
|
|
579
|
+
return this.#value;
|
|
580
|
+
}
|
|
581
|
+
const effectiveCtx = this.#gate(access, ctx, details);
|
|
582
|
+
const value = this.#box === undefined ? this.#value : this.#open().toString('utf8');
|
|
583
|
+
if (access === 'expose' && dev_mode_js_1.devMode.config.enabled) {
|
|
584
|
+
(0, dev_mode_js_1.recordReveal)(this, this.klass, this.label, value, effectiveCtx, details);
|
|
585
|
+
}
|
|
586
|
+
return value;
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* The raw value as UTF-8 bytes, through the same gate and in the same order.
|
|
590
|
+
*
|
|
591
|
+
* The buffer belongs to the caller, which is the point: a sealed value
|
|
592
|
+
* decrypts into it and an unsealed one encodes into it, so either way the
|
|
593
|
+
* caller may zero it when it is done. That is what makes `equals()` and
|
|
594
|
+
* `revealBytes()` leave nothing recoverable in process memory where a
|
|
595
|
+
* string-returning read leaves one copy per call.
|
|
596
|
+
*
|
|
597
|
+
* Not implemented in terms of `#readRawValue`, and it must never be: a byte
|
|
598
|
+
* read that produced a string on its way to a buffer would leave exactly the
|
|
599
|
+
* copy it exists to avoid.
|
|
600
|
+
*/
|
|
601
|
+
#readRawBytes(access, ctx, details = REVEAL_AUDIT_DETAILS) {
|
|
602
|
+
const effectiveCtx = this.#gate(access, ctx, details);
|
|
603
|
+
const bytes = this.#box === undefined ? Buffer.from(this.#value, 'utf8') : this.#open();
|
|
604
|
+
if (access === 'expose' && dev_mode_js_1.devMode.config.enabled) {
|
|
605
|
+
// A thunk, so the only reader of it, development mode's opt-in partial
|
|
606
|
+
// rendering, is also the only thing that can turn these bytes into a
|
|
607
|
+
// string.
|
|
608
|
+
(0, dev_mode_js_1.recordReveal)(this, this.klass, this.label, () => bytes.toString('utf8'), effectiveCtx, details);
|
|
609
|
+
}
|
|
610
|
+
return bytes;
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Every check a read of the raw value has to pass, in the order it has to
|
|
614
|
+
* pass them, ending with the audit record and the charge.
|
|
615
|
+
*
|
|
616
|
+
* Split out so the string reader and the byte reader run one implementation
|
|
617
|
+
* rather than two that could drift. What is left to each of them afterwards
|
|
618
|
+
* is only how the value is materialized.
|
|
619
|
+
*
|
|
620
|
+
* @returns The context the operation ran under, for the caller's own record.
|
|
621
|
+
*/
|
|
622
|
+
#gate(access, ctx, details) {
|
|
623
|
+
// A walk that is running a toJSON() on the object's behalf gets no raw
|
|
624
|
+
// value: whatever the toJSON() returned would be logged as it is. Refused
|
|
625
|
+
// before the deadline check, the policy and the audit hook, because a log
|
|
626
|
+
// line asking is not an access and must fire none of them.
|
|
627
|
+
if (access === 'expose' && (0, redaction_scope_js_1.isInsideRedaction)()) {
|
|
628
|
+
throw new redaction_scope_js_1.RevealDuringRedactionError(this.klass, this.label);
|
|
629
|
+
}
|
|
630
|
+
// First of the lifecycle checks, ahead of revocation as well as expiry.
|
|
631
|
+
// Two reasons, and neither is that a destruction outranks a revocation.
|
|
632
|
+
// It is the only one of the three that reads a plain field: it cannot
|
|
633
|
+
// fail, cannot allocate, and cannot call out of the process, where the
|
|
634
|
+
// revocation check may consult an external registry. Asking a registry
|
|
635
|
+
// about a value this process has already destroyed would let a registry
|
|
636
|
+
// outage decide which refusal a destroyed value reports. And a lapse
|
|
637
|
+
// invites a fresh fetch and a retry where a destruction says this code
|
|
638
|
+
// holds a reference past its own teardown, which is the more useful thing
|
|
639
|
+
// to be told when both are true.
|
|
640
|
+
this.#refuseIfCleared();
|
|
641
|
+
// Ahead of the deadline, because when both refuse, the revocation is the
|
|
642
|
+
// one worth reporting: expiry invites a renewal and a retry, and a revoked
|
|
643
|
+
// value must never look renewable. It is also the check that can consult
|
|
644
|
+
// something outside the process, so a caller sees the reason that came from
|
|
645
|
+
// there rather than a lapsed clock.
|
|
646
|
+
const revoked = (0, revocation_js_1.revocationInForce)(this.#states);
|
|
647
|
+
if (revoked !== undefined) {
|
|
648
|
+
throw new revocation_js_1.RevokedSensitiveValueError(revoked.reason, new Date(revoked.at), this.label, revoked.scope, revoked.cause);
|
|
649
|
+
}
|
|
650
|
+
// Before authorization and before the audit hook: a denied read is not a
|
|
651
|
+
// reveal, and must not be logged as one.
|
|
652
|
+
const expired = this.#expiredDeadline(true);
|
|
653
|
+
if (expired !== undefined) {
|
|
654
|
+
throw new ttl_js_1.ExpiredSensitiveValueError(new Date(expired), new Date(), this.label);
|
|
655
|
+
}
|
|
656
|
+
// After the deadline and before the budget, which is the order the
|
|
657
|
+
// restriction was specified in, and before the policy hook and the audit
|
|
658
|
+
// hook for the reason the two above are: a refused read is not a reveal.
|
|
659
|
+
// A comparison is checked too. Rule R2 names `equals()` as a read for the
|
|
660
|
+
// purposes of expiry, revocation and restrictions alike: a value that may
|
|
661
|
+
// not be read in this region must not still be able to answer whether a
|
|
662
|
+
// guess matches it here.
|
|
663
|
+
if (this.#restrictions.length !== 0) {
|
|
664
|
+
(0, environment_js_1.checkEnvironmentRestrictions)(this.#restrictions, this.label);
|
|
665
|
+
}
|
|
666
|
+
const effectiveCtx = ctx ?? (0, context_js_1.getCurrentRevealContext)();
|
|
667
|
+
// Beside the environment restrictions, because it is the other "where"
|
|
668
|
+
// check: that one asks where the process is, this one asks where the
|
|
669
|
+
// plaintext is about to go, and the answer is the context's own `sink`
|
|
670
|
+
// and `host` tags. Before the budget and the hooks for the reason the
|
|
671
|
+
// checks above are: a refused read is not a reveal. A comparison is not
|
|
672
|
+
// checked, because `equals()` sends the value nowhere; every other access
|
|
673
|
+
// hands plaintext out of the library, and a bound value hands it out only
|
|
674
|
+
// toward a stated destination, hashing and a worker handoff included.
|
|
675
|
+
if (access === 'expose' && this.#destinations.length !== 0) {
|
|
676
|
+
(0, destination_js_1.checkDestinations)(this.#destinations, effectiveCtx, this.label);
|
|
677
|
+
}
|
|
678
|
+
// After the destination, because it is the destination's own second
|
|
679
|
+
// question: not where the bytes may go, but whether the recipient has
|
|
680
|
+
// been checked yet. Exposing reads only, for the reason the destination
|
|
681
|
+
// check is: a comparison sends the value nowhere. A walk over `#states`
|
|
682
|
+
// rather than a flattened view, since a value that waits on nothing is
|
|
683
|
+
// the common case and the walk is one field read per state.
|
|
684
|
+
if (access === 'expose') {
|
|
685
|
+
const unreleased = (0, release_js_1.releaseInForce)(this.#states);
|
|
686
|
+
if (unreleased !== undefined) {
|
|
687
|
+
throw new release_js_1.UnreleasedSensitiveValueError(unreleased.status === 'pending' ? 'pending' : 'refused', this.label, unreleased.detail, unreleased.cause);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
// The same rule one step later, and the same reason the budget is decided
|
|
691
|
+
// here but charged below: a refusal is not a reveal, and neither is a read
|
|
692
|
+
// an audit hook stopped. A comparison is not charged and so is not refused
|
|
693
|
+
// by a spent budget either; it reads the value without disclosing it, and
|
|
694
|
+
// it is the operation the library wants used in place of a reveal.
|
|
695
|
+
if (access === 'expose' && this.#constrained.length !== 0) {
|
|
696
|
+
(0, reveal_budget_js_1.checkRevealBudget)(this.#constrained, this.label);
|
|
697
|
+
}
|
|
698
|
+
// `access` is 'compare' or 'expose' by this function's signature: a `'safe'`
|
|
699
|
+
// read never reaches here, so a policy is never asked to authorize a read
|
|
700
|
+
// that only feeds redaction.
|
|
701
|
+
refuseHookReturn(this.policy.checkRevealAllowed?.(effectiveCtx, this, access), this.klass);
|
|
702
|
+
if (access === 'expose') {
|
|
703
|
+
effectiveCtx?.auditReveal?.(this, details, effectiveCtx);
|
|
704
|
+
// After the audit hook, which is free to throw and stop the reveal: what
|
|
705
|
+
// is counted, charged, and recorded is what actually reached the caller.
|
|
706
|
+
// The two callers record what they materialized, after this returns and
|
|
707
|
+
// after the decryption a sealed value still has to do.
|
|
708
|
+
(0, reveal_budget_js_1.chargeReveal)(this.#states);
|
|
709
|
+
}
|
|
710
|
+
return effectiveCtx;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Construct a derived instance while retaining every source state object.
|
|
714
|
+
*/
|
|
715
|
+
static #derived(value, klass, label, sources) {
|
|
716
|
+
const derived = new _a(value, klass, label, DERIVED_CONSTRUCTION);
|
|
717
|
+
// Rule R2's tighten-only principle applied to a storage decision, and the
|
|
718
|
+
// bypass it exists to close is exact: without this, `secret.map(v => v)` on
|
|
719
|
+
// a sealed value would hand back a well-formed instance holding the same
|
|
720
|
+
// value as a plaintext string. Any source sealed seals the result, which is
|
|
721
|
+
// also the pairwise rule for `concat()` and the template literals.
|
|
722
|
+
//
|
|
723
|
+
// It costs what it says: a `substring()` of a sealed value opens the box,
|
|
724
|
+
// slices the string, and seals the slice, so a plaintext string for both
|
|
725
|
+
// exists while it runs. Sealing does not make derivation cheap; it makes
|
|
726
|
+
// the result of derivation stored the same way as its source.
|
|
727
|
+
//
|
|
728
|
+
// Placed here, in the one construction-side point every deriving method
|
|
729
|
+
// routes through, so a method added later cannot forget it.
|
|
730
|
+
if (sources.some((source) => source.#box !== undefined)) {
|
|
731
|
+
// Required, not merely requested: `strict` is off in some processes, and
|
|
732
|
+
// a derivative that quietly became a plaintext instance of a sealed
|
|
733
|
+
// value's contents is exactly the bypass this block exists to close.
|
|
734
|
+
derived.#seal(value, true);
|
|
735
|
+
}
|
|
736
|
+
const only = sources.length === 1 ? sources[0] : undefined;
|
|
737
|
+
// One source is the common case, and its state arrays are already exactly
|
|
738
|
+
// what the derivative needs. `#states` is assigned once and never mutated,
|
|
739
|
+
// and the state objects are shared between derivatives by design.
|
|
740
|
+
if (only !== undefined) {
|
|
741
|
+
derived.#adopt(only.#states, only.#constrained, only.#restrictions, only.#destinations);
|
|
742
|
+
return derived;
|
|
743
|
+
}
|
|
744
|
+
// A Set, so a value derived from two values that already share a state
|
|
745
|
+
// charges that state once per read rather than twice.
|
|
746
|
+
const states = new Set();
|
|
747
|
+
for (const source of sources) {
|
|
748
|
+
for (const state of source.#states) {
|
|
749
|
+
states.add(state);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
derived.#adopt(Array.from(states));
|
|
753
|
+
return derived;
|
|
754
|
+
}
|
|
755
|
+
static {
|
|
756
|
+
// The private access is deferred to call time on purpose. A CommonJS emit
|
|
757
|
+
// rewrites the class name inside the class body to a temporary that is only
|
|
758
|
+
// assigned once the class definition completes, so reading `#derived` here
|
|
759
|
+
// would fail the brand check.
|
|
760
|
+
exports.deriveSensitiveString = (value, klass, label, sources) => _a.#derived(value, klass, label, sources);
|
|
761
|
+
exports.serializeSensitiveString = (value, ctx, details) => value.#serialize(ctx, details);
|
|
762
|
+
exports.renderStructureRedaction = (value) => {
|
|
763
|
+
try {
|
|
764
|
+
return value.#render('structure');
|
|
765
|
+
}
|
|
766
|
+
catch {
|
|
767
|
+
return undefined;
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
exports.unshareableConstraints = (value) => {
|
|
771
|
+
const names = [...(0, reveal_budget_js_1.unshareableBudgetOptions)(value.#constrained)];
|
|
772
|
+
if ((0, environment_js_1.carriesCustomRestriction)(value.#restrictions)) {
|
|
773
|
+
names.push('restrictions');
|
|
774
|
+
}
|
|
775
|
+
return names;
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Apply an audited transformation and retain this instance's shared state.
|
|
780
|
+
*/
|
|
781
|
+
#transform(transform, ctx) {
|
|
782
|
+
const value = this.#readRawValue('expose', ctx);
|
|
783
|
+
return _a.#derived(transform(value), this.klass, this.label, [this]);
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Read the raw value for a partial query after enforcing the class policy.
|
|
787
|
+
*/
|
|
788
|
+
#readPartialQueryValue(ctx) {
|
|
789
|
+
const policy = this.policy;
|
|
790
|
+
const allowPartialQueries = policy.allowPartialQueries ?? this.klass === 'sensitive';
|
|
791
|
+
if (!allowPartialQueries) {
|
|
792
|
+
throw new Error(`Partial queries are not allowed for sensitivity class '${this.klass}'`);
|
|
793
|
+
}
|
|
794
|
+
return this.#readRawValue('expose', ctx);
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* The redaction, rendered, and reported to the observers as one rendering on
|
|
798
|
+
* the named surface.
|
|
799
|
+
*
|
|
800
|
+
* The one place a marker is produced for a caller, so `toString()`,
|
|
801
|
+
* `toJSON()`, the inspect hook and the structure walkers all count the same
|
|
802
|
+
* way and none of them can be observed differently from the others.
|
|
803
|
+
*/
|
|
804
|
+
#render(surface) {
|
|
805
|
+
// An instance that destroyed its own value renders the snapshot `clear()`
|
|
806
|
+
// took from it. One that only inherited a clear still holds its own copy
|
|
807
|
+
// and redacts that live, which is why the `'safe'` path stays exempt from
|
|
808
|
+
// the cleared check: logging a sensitive value must never throw, and an
|
|
809
|
+
// error handler doing `logger.error({ err, token })` on a cleared token
|
|
810
|
+
// would otherwise lose the diagnostic it was writing.
|
|
811
|
+
const rendering = this.#redaction ?? this.policy.redact(this.#readRawValue('safe'));
|
|
812
|
+
// After the rendering rather than before, so a policy whose `redact`
|
|
813
|
+
// throws reports nothing: nothing was written. One length read is the
|
|
814
|
+
// whole of what an unobserved process pays here, and the observers get
|
|
815
|
+
// the class, the label and the surface, never `rendering`, which under a
|
|
816
|
+
// deterministic policy is a pseudonym of the value.
|
|
817
|
+
if (redaction_observer_js_1.redactionObservers.observers.length !== 0) {
|
|
818
|
+
(0, redaction_observer_js_1.notifyRedaction)(this.klass, this.label, surface);
|
|
819
|
+
}
|
|
820
|
+
return rendering;
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Returns the redacted form of this value.
|
|
824
|
+
* Safe for logging and display.
|
|
825
|
+
*/
|
|
826
|
+
toString() {
|
|
827
|
+
return this.#render('toString');
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Returns the redacted form for JSON serialization.
|
|
831
|
+
* Automatically called by JSON.stringify().
|
|
832
|
+
*/
|
|
833
|
+
toJSON() {
|
|
834
|
+
return this.#render('toJSON');
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Refuses BSON serialization.
|
|
838
|
+
*
|
|
839
|
+
* Called by the BSON encoder under every MongoDB write and every filter, on
|
|
840
|
+
* the ODM and the raw driver alike. It throws rather than redacting because
|
|
841
|
+
* BSON is a persistence and matching format: see {@link SensitiveBsonError}
|
|
842
|
+
* for why the two serializers differ, and why the silent outcome this
|
|
843
|
+
* replaces is worse than a leak.
|
|
844
|
+
*
|
|
845
|
+
* Nothing but a BSON encoder calls this, so it costs nothing on any other
|
|
846
|
+
* path.
|
|
847
|
+
*/
|
|
848
|
+
toBSON() {
|
|
849
|
+
throw new bson_js_1.SensitiveBsonError(this.klass, this.label);
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Custom inspect for Node.js util.inspect() and console.log().
|
|
853
|
+
* Displays the class, optional label, redacted value, and expiry state.
|
|
854
|
+
*
|
|
855
|
+
* The redacted form stays exactly what the class policy produces: expiry is
|
|
856
|
+
* reported next to it rather than in place of it, so a custom redaction is
|
|
857
|
+
* never replaced by a lifecycle marker. Inspecting is not an access, so this
|
|
858
|
+
* does not fire `onExpire`, and it neither calls out to an external
|
|
859
|
+
* revocation registry nor latches what it finds: a log line must not make a
|
|
860
|
+
* network call, and a value that was only printed has not been used.
|
|
861
|
+
*/
|
|
862
|
+
[NODE_INSPECT_SYMBOL]() {
|
|
863
|
+
const klassLabel = this.label ? `${this.klass}:${this.label}` : this.klass;
|
|
864
|
+
// In the order the gate would refuse them, so a value that is both cleared
|
|
865
|
+
// and expired reads as the error it would raise followed by the one it
|
|
866
|
+
// would not.
|
|
867
|
+
const cleared = this.#clearedFlag() !== undefined ? ' CLEARED' : '';
|
|
868
|
+
const revoked = (0, revocation_js_1.observedRevocation)(this.#states) !== undefined ? ' REVOKED' : '';
|
|
869
|
+
const expired = this.#expiredDeadline(false) !== undefined ? ' EXPIRED' : '';
|
|
870
|
+
const exhausted = (0, reveal_budget_js_1.isBudgetExhausted)(this.#constrained) ? ' EXHAUSTED' : '';
|
|
871
|
+
return (`SensitiveString<${klassLabel}> ` +
|
|
872
|
+
`{ ${this.#render('inspect')}${cleared}${revoked}${expired}${exhausted} }`);
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Returns the raw (unredacted) value.
|
|
876
|
+
*
|
|
877
|
+
* Triggers audit logging if a RevealContext is active.
|
|
878
|
+
*
|
|
879
|
+
* @param ctx - Optional explicit reveal context.
|
|
880
|
+
* @throws If policy checking fails.
|
|
881
|
+
* @throws ExpiredSensitiveValueError If the value has expired.
|
|
882
|
+
* @throws RevokedSensitiveValueError If the value has been revoked, or a registry it consults cannot be reached.
|
|
883
|
+
* @throws RevealLimitExceededError If `maxReveals` has been reached.
|
|
884
|
+
* @throws RevealRateLimitError If `maxRevealsPerWindow` has been reached within the window.
|
|
885
|
+
*/
|
|
886
|
+
reveal(ctx) {
|
|
887
|
+
return this.#readRawValue('expose', ctx);
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Returns the raw (unredacted) value as UTF-8 bytes, in a buffer the caller
|
|
891
|
+
* owns and should zero.
|
|
892
|
+
*
|
|
893
|
+
* A reveal in every sense the gate cares about: same checks, same order, same
|
|
894
|
+
* audit record, and it counts against a reveal budget exactly as
|
|
895
|
+
* {@link reveal} does. What differs is only the representation, and that
|
|
896
|
+
* difference is the whole reason it exists.
|
|
897
|
+
*
|
|
898
|
+
* A string-returning reveal leaves one copy of the plaintext in process
|
|
899
|
+
* memory that garbage collection does not remove, and the copies accumulate:
|
|
900
|
+
* a thousand `reveal()` calls on a sealed value leave about a thousand. This
|
|
901
|
+
* returns bytes the caller can overwrite, so a thousand calls can leave none.
|
|
902
|
+
*
|
|
903
|
+
* Works on an unsealed value too, which encodes rather than decrypts, so a
|
|
904
|
+
* caller need not know how the value is stored to use the careful path.
|
|
905
|
+
*
|
|
906
|
+
* @param ctx - Optional explicit reveal context.
|
|
907
|
+
* @throws ClearedSensitiveValueError If the value, or one it was derived from, has been cleared.
|
|
908
|
+
* @throws ExpiredSensitiveValueError If the value has expired.
|
|
909
|
+
* @throws RevokedSensitiveValueError If the value has been revoked, or a registry it consults cannot be reached.
|
|
910
|
+
* @throws RevealLimitExceededError If `maxReveals` has been reached.
|
|
911
|
+
* @throws SealingKeyDestroyedError If `destroySealingKey()` has run since this value was sealed.
|
|
912
|
+
* @throws SealedValueIntegrityError If the stored box, its class or its label was modified.
|
|
913
|
+
*
|
|
914
|
+
* @example
|
|
915
|
+
* ```ts
|
|
916
|
+
* const bytes = token.revealBytes(ctx);
|
|
917
|
+
* try {
|
|
918
|
+
* socket.write(bytes);
|
|
919
|
+
* } finally {
|
|
920
|
+
* bytes.fill(0);
|
|
921
|
+
* }
|
|
922
|
+
* ```
|
|
923
|
+
*/
|
|
924
|
+
revealBytes(ctx) {
|
|
925
|
+
return this.#readRawBytes('expose', ctx);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Whether this value is held as ciphertext rather than as a string.
|
|
929
|
+
*
|
|
930
|
+
* Decided once, at construction, from the `sealed` option or the process
|
|
931
|
+
* default, and never afterwards. A derivative reports `true` when any value
|
|
932
|
+
* it was built from does.
|
|
933
|
+
*
|
|
934
|
+
* `false` in a process that never configured sealing, and `false` on a value
|
|
935
|
+
* whose `sealed: true` fell back because sealing was unavailable and `strict`
|
|
936
|
+
* was off. There is no state in which this reports `true` for a value holding
|
|
937
|
+
* a plaintext string.
|
|
938
|
+
*/
|
|
939
|
+
get isSealed() {
|
|
940
|
+
return this.#box !== undefined;
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* What development mode recorded about this value, or `undefined`.
|
|
944
|
+
*
|
|
945
|
+
* `undefined` unless development mode is on and was on when this value was
|
|
946
|
+
* constructed, so a production build reads `undefined` here rather than
|
|
947
|
+
* failing on a missing property. The record holds no part of the raw value:
|
|
948
|
+
* when the value was made, where it was made, how often it has been exposed
|
|
949
|
+
* and from where.
|
|
950
|
+
*
|
|
951
|
+
* @see setDevMode
|
|
952
|
+
*/
|
|
953
|
+
get __devInfo() {
|
|
954
|
+
return (0, dev_mode_js_1.readDevInfo)(this);
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Returns a partially masked rendering of the value, for display.
|
|
958
|
+
*
|
|
959
|
+
* This is a partial reveal: it runs the same authorization and audit hooks as
|
|
960
|
+
* `reveal()`, and the audit record says `operation: 'mask'` so a log can tell
|
|
961
|
+
* the two apart. The result is a plain string and is not protected; it is
|
|
962
|
+
* meant for a support screen, a confirmation prompt, or a log line, not for
|
|
963
|
+
* further processing.
|
|
964
|
+
*
|
|
965
|
+
* The rendering must hide at least `minMasked` characters, which defaults to
|
|
966
|
+
* 4 for `sensitive` and 8 for `credential` and may only be raised. Positional
|
|
967
|
+
* masking clamps what it shows to satisfy the floor; a strategy that cannot
|
|
968
|
+
* reach it, including one applied to a value of the wrong shape, falls back
|
|
969
|
+
* to the class's full redaction. Counts are code points, and the length of
|
|
970
|
+
* the value is disclosed by construction.
|
|
971
|
+
*
|
|
972
|
+
* @param options - Positional bounds or a format strategy. Defaults to hiding everything.
|
|
973
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
974
|
+
* @throws Error If the class policy sets `allowMask: false`, as `credential` does by default.
|
|
975
|
+
* @throws TypeError If an option has the wrong type or names an unknown strategy.
|
|
976
|
+
* @throws RangeError If a count is not a whole number, or `minMasked` is below the class floor.
|
|
977
|
+
*
|
|
978
|
+
* @example
|
|
979
|
+
* ```ts
|
|
980
|
+
* const key = new SensitiveString('sk_live_abc123xyz9', 'sensitive', 'api_key');
|
|
981
|
+
* key.mask({ showFirst: 2, showLast: 4 }); // 'sk************xyz9'
|
|
982
|
+
*
|
|
983
|
+
* const email = new SensitiveString('jane@example.com', 'sensitive', 'email');
|
|
984
|
+
* email.mask({ strategy: 'email' }); // 'j***@e******.com'
|
|
985
|
+
* ```
|
|
986
|
+
*/
|
|
987
|
+
mask(options = {}, ctx) {
|
|
988
|
+
const policy = this.policy;
|
|
989
|
+
if (!(policy.allowMask ?? this.klass === 'sensitive')) {
|
|
990
|
+
const label = this.label !== undefined ? ` (${this.label})` : '';
|
|
991
|
+
throw new Error(`Masking is not allowed for sensitivity class '${this.klass}'${label}`);
|
|
992
|
+
}
|
|
993
|
+
// Options are validated before the value is read, so a rejected call leaves
|
|
994
|
+
// no audit record for a mask that was never rendered.
|
|
995
|
+
const plan = (0, mask_js_1.planMask)(options, this.klass);
|
|
996
|
+
const value = this.#readRawValue('expose', ctx, (0, mask_js_1.maskAuditDetails)(plan));
|
|
997
|
+
return (0, mask_js_1.applyMask)(value, plan, (raw) => policy.redact(raw));
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Refuse a digest when the class policy forbids one.
|
|
1001
|
+
*
|
|
1002
|
+
* `advisory.allowHash` has been declared since the beginning and read by
|
|
1003
|
+
* nothing. This is what reads it. `undefined` allows, which is the opposite
|
|
1004
|
+
* of how `allowSendToExternal` is read and is deliberate: hashing is the
|
|
1005
|
+
* operation this library wants used in place of holding a value, so the flag
|
|
1006
|
+
* exists to forbid it for a class where even a digest is too much, not to
|
|
1007
|
+
* require permission for the safe path.
|
|
1008
|
+
*/
|
|
1009
|
+
#requireHashingAllowed(operation) {
|
|
1010
|
+
if (this.policy.advisory?.allowHash === false) {
|
|
1011
|
+
const label = this.label !== undefined ? ` (${this.label})` : '';
|
|
1012
|
+
throw new Error(`SensitiveString.${operation}: hashing is not allowed for sensitivity class ` +
|
|
1013
|
+
`'${this.klass}'${label}; its policy sets advisory.allowHash: false`);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* A one-way digest of the value, as a protected value.
|
|
1018
|
+
*
|
|
1019
|
+
* For a lookup key, a deduplication key, or a correlation token: something
|
|
1020
|
+
* derived from the value that can be stored or compared without storing the
|
|
1021
|
+
* value. It is an exposure like any other, so it runs the class policy, fires
|
|
1022
|
+
* the audit hook with `operation: 'hash'`, counts against a reveal budget,
|
|
1023
|
+
* and refuses on an expired or revoked value.
|
|
1024
|
+
*
|
|
1025
|
+
* ⚠️ This is not password hashing. The digest is fast to compute, which is
|
|
1026
|
+
* the one property a stored password must not have: a wordlist runs through
|
|
1027
|
+
* SHA-256 at billions of guesses a second, and a salt does not slow that down
|
|
1028
|
+
* for the attacker who has the salt, which is everyone holding the record.
|
|
1029
|
+
* Use `hashForStorage` from `@platform-sec/sensitive-string-kdf`.
|
|
1030
|
+
*
|
|
1031
|
+
* The result is always `credential`, whatever the source class was, because a
|
|
1032
|
+
* digest of a value an attacker can guess is a copy of that value behind a
|
|
1033
|
+
* lookup table, and one that correlates the same subject across every system
|
|
1034
|
+
* that stores it. It carries the deadline, the reveal budget and the
|
|
1035
|
+
* revocation of the value it came from, for the same reason.
|
|
1036
|
+
*
|
|
1037
|
+
* @param algorithm - One of sha256, sha384, sha512, sha3-256, sha3-512.
|
|
1038
|
+
* @param options - Salt and digest encoding.
|
|
1039
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1040
|
+
* @throws Error If the class policy sets `advisory.allowHash: false`, or the algorithm is broken or unavailable in this Node build.
|
|
1041
|
+
* @throws TypeError If the algorithm, encoding, salt or options object has the wrong type.
|
|
1042
|
+
* @throws RangeError If the salt is empty.
|
|
1043
|
+
*
|
|
1044
|
+
* @example
|
|
1045
|
+
* ```ts
|
|
1046
|
+
* const token = new SensitiveString(raw, 'credential', 'session_token');
|
|
1047
|
+
* const lookupKey = token.hash('sha256'); // SensitiveString<'credential'>
|
|
1048
|
+
* await db.sessions.findUnique({ where: { tokenHash: lookupKey.reveal() } });
|
|
1049
|
+
* ```
|
|
1050
|
+
*/
|
|
1051
|
+
hash(algorithm, options = {}, ctx) {
|
|
1052
|
+
this.#requireHashingAllowed('hash');
|
|
1053
|
+
// Options are validated before the value is read, so a rejected call leaves
|
|
1054
|
+
// no audit record and charges nothing for a digest that was never taken.
|
|
1055
|
+
const plan = (0, hash_js_1.planHash)('hash', algorithm, options);
|
|
1056
|
+
const value = this.#readRawValue('expose', ctx, (0, hash_js_1.hashAuditDetails)(plan));
|
|
1057
|
+
return _a.#derived((0, hash_js_1.applyHash)(value, plan), 'credential', (0, hash_js_1.hashLabel)(this.label, 'hash'), [this]);
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* A keyed one-way digest of the value, as a protected value.
|
|
1061
|
+
*
|
|
1062
|
+
* The version of `hash()` to reach for when the value is something an
|
|
1063
|
+
* attacker can enumerate: an email address, a phone number, a card number, a
|
|
1064
|
+
* six-digit code. A salt stops precomputation and nothing else, because the
|
|
1065
|
+
* salt sits beside the digest in the same record; a key that the attacker
|
|
1066
|
+
* does not have is what makes the digest unanswerable, and it is also what
|
|
1067
|
+
* stops the same subject being correlated across two systems that both
|
|
1068
|
+
* store one.
|
|
1069
|
+
*
|
|
1070
|
+
* The key may itself be protected, and then it is read through its own gate:
|
|
1071
|
+
* its policy, its audit hook, its budget and its revocation all apply, and
|
|
1072
|
+
* the result carries the constraints of the value and the key both. Using a
|
|
1073
|
+
* value as a key reads it.
|
|
1074
|
+
*
|
|
1075
|
+
* @param algorithm - One of sha256, sha384, sha512, sha3-256, sha3-512.
|
|
1076
|
+
* @param key - At least 16 bytes. 32 bytes from `randomBytes` or a secrets manager is the recommendation.
|
|
1077
|
+
* @param options - Digest encoding.
|
|
1078
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1079
|
+
* @throws Error If the class policy sets `advisory.allowHash: false`, or the algorithm is broken or unavailable in this Node build.
|
|
1080
|
+
* @throws TypeError If the algorithm, encoding, key or options object has the wrong type, or a salt is supplied.
|
|
1081
|
+
* @throws RangeError If the key is shorter than 16 bytes.
|
|
1082
|
+
*
|
|
1083
|
+
* @example
|
|
1084
|
+
* ```ts
|
|
1085
|
+
* const email = new SensitiveString('jane@example.com', 'sensitive', 'email');
|
|
1086
|
+
* const pseudonym = email.hmac('sha256', process.env.CORRELATION_KEY!);
|
|
1087
|
+
* ```
|
|
1088
|
+
*/
|
|
1089
|
+
hmac(algorithm, key, options = {}, ctx) {
|
|
1090
|
+
this.#requireHashingAllowed('hmac');
|
|
1091
|
+
const plan = (0, hash_js_1.planHash)('hmac', algorithm, options);
|
|
1092
|
+
const details = (0, hash_js_1.hmacAuditDetails)(plan, key instanceof _a);
|
|
1093
|
+
// The key is read and measured before the value is, which is the one place
|
|
1094
|
+
// this class puts an argument ahead of its receiver. A key below the floor
|
|
1095
|
+
// is a call that will not produce a digest, and refusing it after the
|
|
1096
|
+
// receiver had been read would charge an exposure for nothing.
|
|
1097
|
+
const keyBytes = (0, hash_js_1.requireHmacKey)(key instanceof _a ? key.#readRawValue('expose', ctx, details) : key);
|
|
1098
|
+
const value = this.#readRawValue('expose', ctx, details);
|
|
1099
|
+
const sources = key instanceof _a ? [this, key] : [this];
|
|
1100
|
+
return _a.#derived((0, hash_js_1.applyHmac)(value, keyBytes, plan), 'credential', (0, hash_js_1.hashLabel)(this.label, 'hmac'), sources);
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* The deadline after which this value can no longer be read, if it has one.
|
|
1104
|
+
*
|
|
1105
|
+
* A derived value carries the deadlines of every value it came from, and this
|
|
1106
|
+
* reports the earliest of them: a substring of an expired OTP is expired, and
|
|
1107
|
+
* a concatenation is only usable while both of its operands are.
|
|
1108
|
+
*
|
|
1109
|
+
* Returns a copy, so the deadline cannot be moved through it.
|
|
1110
|
+
*/
|
|
1111
|
+
get expiresAt() {
|
|
1112
|
+
const earliest = this.#earliestDeadline();
|
|
1113
|
+
return earliest === undefined ? undefined : new Date(earliest);
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Whether the deadline has passed. A value is not usable at its own deadline.
|
|
1117
|
+
*
|
|
1118
|
+
* The first detection fires the `onExpire` callback of every expired source.
|
|
1119
|
+
*/
|
|
1120
|
+
isExpired() {
|
|
1121
|
+
return this.#expiredDeadline(true) !== undefined;
|
|
1122
|
+
}
|
|
1123
|
+
/**
|
|
1124
|
+
* Milliseconds until the deadline, `-1` once it has passed, or `undefined`
|
|
1125
|
+
* when this value does not expire.
|
|
1126
|
+
*/
|
|
1127
|
+
ttlRemaining() {
|
|
1128
|
+
const earliest = this.#earliestDeadline();
|
|
1129
|
+
if (earliest === undefined) {
|
|
1130
|
+
return undefined;
|
|
1131
|
+
}
|
|
1132
|
+
const remaining = earliest - Date.now();
|
|
1133
|
+
return remaining <= 0 ? -1 : remaining;
|
|
1134
|
+
}
|
|
1135
|
+
/**
|
|
1136
|
+
* Whether `renew()` would be accepted right now.
|
|
1137
|
+
*
|
|
1138
|
+
* Renewal needs a deadline to extend, permission from the class policy and
|
|
1139
|
+
* the construction options, an unexhausted renewal budget, and ownership of
|
|
1140
|
+
* the deadline: a derived value cannot renew one it shares.
|
|
1141
|
+
*/
|
|
1142
|
+
isRenewable() {
|
|
1143
|
+
const own = this.#own;
|
|
1144
|
+
if (own === undefined || own.expiry.deadline === undefined || !own.expiry.allowRenewal) {
|
|
1145
|
+
return false;
|
|
1146
|
+
}
|
|
1147
|
+
const { maxRenewals, renewalCount } = own.expiry;
|
|
1148
|
+
return maxRenewals === undefined || renewalCount < maxRenewals;
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* How many times this value has extended the deadline it owns.
|
|
1152
|
+
*
|
|
1153
|
+
* A derived value owns no deadline and reports `0`, however often the value
|
|
1154
|
+
* it came from has been renewed.
|
|
1155
|
+
*/
|
|
1156
|
+
get renewalCount() {
|
|
1157
|
+
return this.#own?.expiry.renewalCount ?? 0;
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Extend the deadline, when the class policy and the construction options
|
|
1161
|
+
* allow it.
|
|
1162
|
+
*
|
|
1163
|
+
* An expired value extends from now rather than from its lapsed deadline, so
|
|
1164
|
+
* a sliding session that missed a heartbeat is granted the full duration.
|
|
1165
|
+
* Reviving a value this way is why `allowRenewal` defaults to `false` for
|
|
1166
|
+
* `credential` and why a policy may forbid it outright.
|
|
1167
|
+
*
|
|
1168
|
+
* The extension is audited before it takes effect, so an audit sink that
|
|
1169
|
+
* throws stops it, and a refused renewal leaves no record of one that never
|
|
1170
|
+
* happened. Renewing is not a read: it does not disclose the value, and it
|
|
1171
|
+
* works on an expired one. It does not work on a revoked one, or on one this
|
|
1172
|
+
* environment may not read, because neither of those is a lapsed deadline:
|
|
1173
|
+
* both say the value must not be used here, and extending its life is using
|
|
1174
|
+
* it.
|
|
1175
|
+
*
|
|
1176
|
+
* @param additionalTtl - Milliseconds to add. Must be positive.
|
|
1177
|
+
* @param options - `maxExtension` clamps the resulting deadline.
|
|
1178
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1179
|
+
* @throws ClearedSensitiveValueError If the value, or one it was derived from, has been cleared.
|
|
1180
|
+
* @throws RenewalNotAllowedError If renewal is refused, or a cap leaves no room to extend.
|
|
1181
|
+
* @throws RangeError If `additionalTtl` is not a positive, finite number.
|
|
1182
|
+
* @throws RevokedSensitiveValueError If the value has been revoked.
|
|
1183
|
+
* @throws EnvironmentRestrictedError If this environment may not read the value.
|
|
1184
|
+
*
|
|
1185
|
+
* @example
|
|
1186
|
+
* ```ts
|
|
1187
|
+
* const session = new SensitiveString(token, 'sensitive', 'session', { ttl: 15 * 60_000 });
|
|
1188
|
+
* session.renew(15 * 60_000, { maxExtension: absoluteSessionDeadline });
|
|
1189
|
+
* ```
|
|
1190
|
+
*/
|
|
1191
|
+
renew(additionalTtl, options = {}, ctx) {
|
|
1192
|
+
// Renewal reads nothing, so it does not route through the gate, and
|
|
1193
|
+
// without this a value that no longer exists would still have its deadline
|
|
1194
|
+
// moved. Ahead of the ownership check as well, and ahead of everything
|
|
1195
|
+
// else here for the same reason the gate puts it first: whatever else is
|
|
1196
|
+
// true of a destroyed value, extending its life is not a thing to report
|
|
1197
|
+
// success for.
|
|
1198
|
+
this.#refuseIfCleared();
|
|
1199
|
+
const own = this.#own;
|
|
1200
|
+
if (own === undefined) {
|
|
1201
|
+
throw new ttl_js_1.RenewalNotAllowedError('derived', this.label);
|
|
1202
|
+
}
|
|
1203
|
+
// Renewal does not read the value, so it does not go through the gate, and
|
|
1204
|
+
// without this a revoked value could still have its deadline extended. It
|
|
1205
|
+
// would stay unreadable, but a lifecycle control that keeps working on a
|
|
1206
|
+
// revoked value is one somebody will eventually mistake for the value
|
|
1207
|
+
// working.
|
|
1208
|
+
const revoked = (0, revocation_js_1.revocationInForce)(this.#states);
|
|
1209
|
+
if (revoked !== undefined) {
|
|
1210
|
+
throw new revocation_js_1.RevokedSensitiveValueError(revoked.reason, new Date(revoked.at), this.label, revoked.scope, revoked.cause);
|
|
1211
|
+
}
|
|
1212
|
+
// The same reason, one restriction along: renewal does not read the value,
|
|
1213
|
+
// so nothing else here consults the environment, and without this a process
|
|
1214
|
+
// the value forbids could keep extending its life. Reading it is the thing
|
|
1215
|
+
// the restriction denies, and a lifecycle control that keeps working where
|
|
1216
|
+
// the value does not is one somebody will mistake for the value working.
|
|
1217
|
+
if (this.#restrictions.length !== 0) {
|
|
1218
|
+
(0, environment_js_1.checkEnvironmentRestrictions)(this.#restrictions, this.label);
|
|
1219
|
+
}
|
|
1220
|
+
const { expiry } = own;
|
|
1221
|
+
const plan = (0, ttl_js_1.planRenewal)(expiry, additionalTtl, options, this.label);
|
|
1222
|
+
const effectiveCtx = ctx ?? (0, context_js_1.getCurrentRevealContext)();
|
|
1223
|
+
// Renewal reads no value, so it does not go through the gate, but it is
|
|
1224
|
+
// still an operation a policy may refuse.
|
|
1225
|
+
refuseHookReturn(this.policy.checkRevealAllowed?.(effectiveCtx, this, 'renew'), this.klass);
|
|
1226
|
+
effectiveCtx?.auditReveal?.(this, (0, ttl_js_1.renewAuditDetails)(expiry, plan), effectiveCtx);
|
|
1227
|
+
expiry.deadline = plan.next;
|
|
1228
|
+
expiry.renewalCount++;
|
|
1229
|
+
// The new deadline is a new expiration, so its own notification is due.
|
|
1230
|
+
expiry.notified = false;
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* The revocation in force on this value, or `undefined`. Shared by the three
|
|
1234
|
+
* public accessors below; the gate calls the same module function directly,
|
|
1235
|
+
* so that its decision never routes through anything a subclass could
|
|
1236
|
+
* override.
|
|
1237
|
+
*
|
|
1238
|
+
* Latches what it finds, so a value that has once been refused stays refused
|
|
1239
|
+
* even if the entry behind it is pruned, and consults an external registry,
|
|
1240
|
+
* so each accessor is a live question rather than a cached answer.
|
|
1241
|
+
*/
|
|
1242
|
+
#revocation() {
|
|
1243
|
+
return (0, revocation_js_1.revocationInForce)(this.#states);
|
|
1244
|
+
}
|
|
1245
|
+
/**
|
|
1246
|
+
* Stop this value from being read, permanently.
|
|
1247
|
+
*
|
|
1248
|
+
* There is no way back. Nothing lifts a revocation: not a policy, not a new
|
|
1249
|
+
* options object, not a round trip through the wire format.
|
|
1250
|
+
*
|
|
1251
|
+
* Revocation runs along derivation edges in both directions. Every value this
|
|
1252
|
+
* one was derived from is revoked too, and so is everything else derived from
|
|
1253
|
+
* those, because a derivative is made of its sources' material: a leaked
|
|
1254
|
+
* substring is a leaked secret. Refusing to revoke through the handle a
|
|
1255
|
+
* caller happens to be holding would fail open in exactly the incident this
|
|
1256
|
+
* exists for, which is why this is the one piece of shared state a derived
|
|
1257
|
+
* value may write, where `renew()` refuses.
|
|
1258
|
+
*
|
|
1259
|
+
* Nothing may refuse a revocation, so no policy hook is consulted and the
|
|
1260
|
+
* audit record is reported after the fact, with anything the sink throws
|
|
1261
|
+
* swallowed. `renew()` audits first for the opposite reason.
|
|
1262
|
+
*
|
|
1263
|
+
* Revoking an already-revoked value changes nothing and reports nothing: the
|
|
1264
|
+
* first reason and timestamp stand, because a revocation is a fact that
|
|
1265
|
+
* already happened.
|
|
1266
|
+
*
|
|
1267
|
+
* @param reason - Why, for the error message and the audit record. Developer
|
|
1268
|
+
* text: it must not carry any part of the protected value.
|
|
1269
|
+
* @param ctx - Optional reveal context for auditing.
|
|
1270
|
+
* @throws TypeError If `reason` is not a string.
|
|
1271
|
+
*
|
|
1272
|
+
* @example
|
|
1273
|
+
* ```ts
|
|
1274
|
+
* apiKey.revoke('Rotated 2026-08-01');
|
|
1275
|
+
* apiKey.reveal(); // throws RevokedSensitiveValueError
|
|
1276
|
+
* ```
|
|
1277
|
+
*/
|
|
1278
|
+
revoke(reason, ctx) {
|
|
1279
|
+
const why = (0, revocation_js_1.requireReason)(reason, 'SensitiveString.revoke');
|
|
1280
|
+
const record = (0, revocation_js_1.revokeStates)(this.#states, why);
|
|
1281
|
+
if (record === undefined) {
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
const effectiveCtx = ctx ?? (0, context_js_1.getCurrentRevealContext)();
|
|
1285
|
+
try {
|
|
1286
|
+
effectiveCtx?.auditReveal?.(this, (0, revocation_js_1.revokeAuditDetails)(record), effectiveCtx);
|
|
1287
|
+
}
|
|
1288
|
+
catch {
|
|
1289
|
+
// The value is already revoked. A sink that fails must not make it look
|
|
1290
|
+
// as though the revocation did.
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* Whether this value has been revoked, by any of the four sources: its own
|
|
1295
|
+
* `revoke()`, the process-global label and pattern lists, or the registry it
|
|
1296
|
+
* was constructed with.
|
|
1297
|
+
*
|
|
1298
|
+
* `true` as well when a registry it was given cannot be reached, because a
|
|
1299
|
+
* value whose revocation cannot be checked is not one to hand out.
|
|
1300
|
+
*/
|
|
1301
|
+
get isRevoked() {
|
|
1302
|
+
return this.#revocation() !== undefined;
|
|
1303
|
+
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Why this value was revoked, or `undefined` when it was not.
|
|
1306
|
+
*
|
|
1307
|
+
* The reason recorded by whichever source refused first. For a value revoked
|
|
1308
|
+
* through several of them, that is the one observed earliest rather than the
|
|
1309
|
+
* one highest in any precedence order: a latched revocation is a fact that
|
|
1310
|
+
* already happened.
|
|
1311
|
+
*/
|
|
1312
|
+
get revocationReason() {
|
|
1313
|
+
return this.#revocation()?.reason;
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* When this value was revoked, or `undefined` when it was not.
|
|
1317
|
+
*
|
|
1318
|
+
* For a label or pattern revocation this is when the list was written, not
|
|
1319
|
+
* when this value first noticed.
|
|
1320
|
+
*/
|
|
1321
|
+
get revokedAt() {
|
|
1322
|
+
const record = this.#revocation();
|
|
1323
|
+
return record === undefined ? undefined : new Date(record.at);
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Destroy this instance's copy of the plaintext, permanently.
|
|
1327
|
+
*
|
|
1328
|
+
* What it does is narrow, and the first paragraph of the documentation is the
|
|
1329
|
+
* right place to say so: it drops **the library's** reference to the string
|
|
1330
|
+
* and refuses every later read. It is not zeroing. JavaScript cannot
|
|
1331
|
+
* overwrite the backing store of a string it holds a reference to, and
|
|
1332
|
+
* whether the library's was the last reference is a property of the calling
|
|
1333
|
+
* code rather than of this method.
|
|
1334
|
+
*
|
|
1335
|
+
* ```ts
|
|
1336
|
+
* // Works: the library's copy is the only copy.
|
|
1337
|
+
* const password = new SensitiveString(await kms.decrypt(blob), 'credential', 'db_password');
|
|
1338
|
+
* await connect(password.reveal(ctx));
|
|
1339
|
+
* password.clear();
|
|
1340
|
+
*
|
|
1341
|
+
* // Does nothing while the handler still holds req.body: req.body.token and
|
|
1342
|
+
* // the instance's value are the same string object.
|
|
1343
|
+
* const token = new SensitiveString(req.body.token, 'credential');
|
|
1344
|
+
* token.clear();
|
|
1345
|
+
* ```
|
|
1346
|
+
*
|
|
1347
|
+
* The second shape is not fixable from inside the library, and no boundary
|
|
1348
|
+
* integration fixes it either: a body has to be parsed into strings before
|
|
1349
|
+
* any field can be classified. The fix belongs to the caller, which is to
|
|
1350
|
+
* drop or delete the source property once the value is wrapped.
|
|
1351
|
+
*
|
|
1352
|
+
* Derivatives are refused, not released. Clearing an owner refuses every
|
|
1353
|
+
* value derived from it, because they share the state object this writes;
|
|
1354
|
+
* clearing a derivative refuses only that derivative, because it has no
|
|
1355
|
+
* shared state of its own to write. The traffic also runs the other way: a
|
|
1356
|
+
* derivative of 13 characters or more is a V8 `SlicedString` pinning its
|
|
1357
|
+
* origin's entire backing store, and a `concat()` result pins both operands,
|
|
1358
|
+
* so an origin's `clear()` releases nothing at all until the derivatives are
|
|
1359
|
+
* cleared too. Clear them, or turn on `trackInstances` and let
|
|
1360
|
+
* `clearAllSensitiveValues()` find the ones you no longer hold.
|
|
1361
|
+
*
|
|
1362
|
+
* Redaction keeps working: `toString()`, `toJSON()` and `inspect()` render
|
|
1363
|
+
* the rendering this snapshotted from the live value, so logging a cleared
|
|
1364
|
+
* value never throws. `length` and `isEmpty()` refuse instead of answering
|
|
1365
|
+
* `0` and `true`, which would be wrong rather than degraded.
|
|
1366
|
+
*
|
|
1367
|
+
* No policy is consulted. Clearing reduces exposure, so there is no
|
|
1368
|
+
* confidentiality outcome a denial would protect, and the same caller could
|
|
1369
|
+
* drop the reference by letting it go out of scope. It is audited, after the
|
|
1370
|
+
* fact, with anything the sink throws swallowed.
|
|
1371
|
+
*
|
|
1372
|
+
* Irreversible, and idempotent per instance: a second call on the same
|
|
1373
|
+
* instance changes nothing and reports nothing. A derivative whose origin was
|
|
1374
|
+
* cleared has still not dropped its own copy, so `clear()` on it is not a
|
|
1375
|
+
* no-op.
|
|
1376
|
+
*
|
|
1377
|
+
* @param ctx - Optional reveal context for auditing. The ambient context is used when this is omitted.
|
|
1378
|
+
*
|
|
1379
|
+
* @example
|
|
1380
|
+
* ```ts
|
|
1381
|
+
* token.clear();
|
|
1382
|
+
* token.isCleared; // true
|
|
1383
|
+
* token.toString(); // '[REDACTED:credential]', unchanged
|
|
1384
|
+
* token.reveal(); // throws ClearedSensitiveValueError
|
|
1385
|
+
* ```
|
|
1386
|
+
*/
|
|
1387
|
+
clear(ctx) {
|
|
1388
|
+
// Guarded on this instance's own clear, never on the inherited flag. A
|
|
1389
|
+
// derivative whose origin was cleared is already refused for every read,
|
|
1390
|
+
// and still holds its own copy of the plaintext and its own pin on the
|
|
1391
|
+
// origin's, so it still has work to do here. Guarding on #clearedFlag()
|
|
1392
|
+
// would return early for every derivative a bulk clear reaches after its
|
|
1393
|
+
// origin, which is precisely the set that function exists to reach.
|
|
1394
|
+
if (this.#ownClearedAt !== undefined) {
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
const now = Date.now();
|
|
1398
|
+
const own = this.#own;
|
|
1399
|
+
// Taken from the live value, immediately before it is dropped, so
|
|
1400
|
+
// toString() keeps answering afterwards. The 'safe' path is exempt from the
|
|
1401
|
+
// cleared check, so this works on an instance that inherited a clear too.
|
|
1402
|
+
//
|
|
1403
|
+
// A custom redact that throws must not leave the value uncleared: refusing
|
|
1404
|
+
// to destroy a secret because its renderer is broken is the wrong way to
|
|
1405
|
+
// fail. The fallback is the marker the class would have emitted anyway.
|
|
1406
|
+
// A sealed value captured its rendering at construction and has no live
|
|
1407
|
+
// value to take one from now, so it keeps the one it has. The `'safe'` read
|
|
1408
|
+
// below would throw on it.
|
|
1409
|
+
if (this.#redaction === undefined) {
|
|
1410
|
+
try {
|
|
1411
|
+
this.#redaction = this.policy.redact(this.#readRawValue('safe'));
|
|
1412
|
+
}
|
|
1413
|
+
catch {
|
|
1414
|
+
this.#redaction = `[REDACTED:${this.klass}]`;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
this.#ownClearedAt = now;
|
|
1418
|
+
if (own !== undefined) {
|
|
1419
|
+
// Only an owner writes shared state. A derivative shares its sources'
|
|
1420
|
+
// state by reference, so writing it would destroy the value it came from.
|
|
1421
|
+
own.clearedAt = now;
|
|
1422
|
+
}
|
|
1423
|
+
// For an unsealed value this drops the library's reference and nothing
|
|
1424
|
+
// more: JavaScript cannot overwrite a string's backing store, so the
|
|
1425
|
+
// plaintext survives in process memory until the collector reclaims the
|
|
1426
|
+
// page and something else reuses it.
|
|
1427
|
+
//
|
|
1428
|
+
// For a sealed one the box is zeroed first, which is the difference sealing
|
|
1429
|
+
// makes to this method. The bytes are actually overwritten, so a dump taken
|
|
1430
|
+
// afterwards holds neither the value nor anything that could become it,
|
|
1431
|
+
// which is what turns `clear()` from best-effort into an erase.
|
|
1432
|
+
this.#box?.fill(0);
|
|
1433
|
+
this.#box = undefined;
|
|
1434
|
+
this.#value = '';
|
|
1435
|
+
const effectiveCtx = ctx ?? (0, context_js_1.getCurrentRevealContext)();
|
|
1436
|
+
try {
|
|
1437
|
+
// After the state change, which is the inverse of renew()'s order and the
|
|
1438
|
+
// same as revoke()'s. renew() audits first so a sink that throws stops the
|
|
1439
|
+
// extension; a clear is not something a sink may veto, and a sink that
|
|
1440
|
+
// fails must not make it look as though the destruction did not happen.
|
|
1441
|
+
effectiveCtx?.auditReveal?.(this, { operation: 'clear', propagated: own !== undefined }, effectiveCtx);
|
|
1442
|
+
}
|
|
1443
|
+
catch {
|
|
1444
|
+
// See above. The value is already gone.
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* Whether this value has been destroyed, by its own `clear()` or by one on a
|
|
1449
|
+
* value it was derived from.
|
|
1450
|
+
*/
|
|
1451
|
+
get isCleared() {
|
|
1452
|
+
return this.#clearedFlag() !== undefined;
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* When this value was destroyed, or `undefined` when it was not.
|
|
1456
|
+
*
|
|
1457
|
+
* The earliest clear affecting it, so a derivative cleared after its origin
|
|
1458
|
+
* reports the origin's time: that is when it stopped being usable.
|
|
1459
|
+
*/
|
|
1460
|
+
get clearedAt() {
|
|
1461
|
+
const cleared = this.#clearedFlag();
|
|
1462
|
+
return cleared === undefined ? undefined : new Date(cleared);
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* How many times this value has been exposed.
|
|
1466
|
+
*
|
|
1467
|
+
* Counted for every value, whether or not it limits reveals. An exposure is
|
|
1468
|
+
* what an audit hook sees: `reveal()`, `mask()`, `hash()`, `hmac()`,
|
|
1469
|
+
* `serialize()`, `map()`, and the string, regex, and template operations, one
|
|
1470
|
+
* per call. An `hmac()` with a protected key counts once against the value
|
|
1471
|
+
* and once against the key. `equals()` is
|
|
1472
|
+
* not, because a comparison reads the value without disclosing it, and
|
|
1473
|
+
* neither is redaction. A read the gate refused, or one an audit hook stopped
|
|
1474
|
+
* by throwing, is not counted: a denied reveal is not a reveal.
|
|
1475
|
+
*
|
|
1476
|
+
* A derived value reports the highest count among the values it was built
|
|
1477
|
+
* from, which is the one nearest a limit.
|
|
1478
|
+
*/
|
|
1479
|
+
get revealCount() {
|
|
1480
|
+
let highest = 0;
|
|
1481
|
+
for (const state of this.#states) {
|
|
1482
|
+
if (state.reveals > highest) {
|
|
1483
|
+
highest = state.reveals;
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
return highest;
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* Exposures still allowed before `maxReveals` is reached, or `undefined` when
|
|
1490
|
+
* this value sets no lifetime limit.
|
|
1491
|
+
*
|
|
1492
|
+
* A derived value reports the smallest remaining budget among the values it
|
|
1493
|
+
* was built from, which is the one that will refuse first.
|
|
1494
|
+
*/
|
|
1495
|
+
get revealsRemaining() {
|
|
1496
|
+
return (0, reveal_budget_js_1.revealsRemaining)(this.#constrained);
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Whether the lifetime limit has been reached, so no further exposure is
|
|
1500
|
+
* possible. Permanent: nothing resets a reveal count.
|
|
1501
|
+
*
|
|
1502
|
+
* A rate limit does not make a value exhausted, because waiting clears it.
|
|
1503
|
+
*/
|
|
1504
|
+
isExhausted() {
|
|
1505
|
+
return (0, reveal_budget_js_1.isBudgetExhausted)(this.#constrained);
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Compare this value with another string or SensitiveString.
|
|
1509
|
+
*
|
|
1510
|
+
* Uses constant-time comparison when either operand's class requires it, as
|
|
1511
|
+
* 'credential' does, to prevent timing attacks. The receiver alone used to
|
|
1512
|
+
* decide, so `input.equals(storedCredential)` compared with `===` while
|
|
1513
|
+
* `storedCredential.equals(input)` did not, and which side of the call a
|
|
1514
|
+
* credential lands on is not a decision anyone makes on purpose.
|
|
1515
|
+
*
|
|
1516
|
+
* @param other - The value to compare against
|
|
1517
|
+
* @param ctx - Optional reveal context for policy checks
|
|
1518
|
+
* @returns true if values are equal
|
|
1519
|
+
*
|
|
1520
|
+
* @remarks
|
|
1521
|
+
* The constant-time path hides the stored value's contents, and hides its
|
|
1522
|
+
* length to the granularity of a SHA-256 block: a comparand of the wrong
|
|
1523
|
+
* length costs what a comparand of the right length costs, and a stored
|
|
1524
|
+
* value of 8 bytes costs what one of 55 costs. See `compare.ts` for why that
|
|
1525
|
+
* needs more than `timingSafeEqual` alone, and for what it still leaves.
|
|
1526
|
+
*/
|
|
1527
|
+
equals(other, ctx) {
|
|
1528
|
+
if (this.#box !== undefined || (other instanceof _a && other.#box !== undefined)) {
|
|
1529
|
+
return this.#equalsBytes(other, ctx);
|
|
1530
|
+
}
|
|
1531
|
+
const value = this.#readRawValue('compare', ctx);
|
|
1532
|
+
const rawOther = other instanceof _a ? other.#readRawValue('compare', ctx) : other;
|
|
1533
|
+
const constantTime = this.policy.requireConstantTimeEquals === true ||
|
|
1534
|
+
(other instanceof _a && other.policy.requireConstantTimeEquals === true);
|
|
1535
|
+
if (constantTime) {
|
|
1536
|
+
return (0, compare_js_1.constantTimeEquals)(value, rawOther);
|
|
1537
|
+
}
|
|
1538
|
+
return value === rawOther;
|
|
1539
|
+
}
|
|
1540
|
+
/**
|
|
1541
|
+
* Compare without either side becoming a plaintext string.
|
|
1542
|
+
*
|
|
1543
|
+
* The reason this path exists rather than reusing the string one: a thousand
|
|
1544
|
+
* comparisons of a sealed credential leave nothing recoverable in process
|
|
1545
|
+
* memory, where a thousand `reveal()` calls leave about a thousand copies.
|
|
1546
|
+
* For a login endpoint, which is the archetypal `credential` workload, that
|
|
1547
|
+
* makes sealing an improvement rather than a trade.
|
|
1548
|
+
*
|
|
1549
|
+
* The comparison is constant time whether or not either policy asks for it.
|
|
1550
|
+
* Once both operands are buffers the alternative is `Buffer.equals`, a length
|
|
1551
|
+
* check followed by a `memcmp`, which is the variable-time shape `compare.ts`
|
|
1552
|
+
* exists to avoid; and a caller who opted into sealing has already accepted
|
|
1553
|
+
* microsecond-scale costs, so the branch on the policy buys nothing worth its
|
|
1554
|
+
* asymmetry. The unsealed path above is untouched, so nothing changes for a
|
|
1555
|
+
* caller who did not opt in.
|
|
1556
|
+
*/
|
|
1557
|
+
#equalsBytes(other, ctx) {
|
|
1558
|
+
const mine = this.#readRawBytes('compare', ctx);
|
|
1559
|
+
let theirs;
|
|
1560
|
+
try {
|
|
1561
|
+
if (other instanceof _a) {
|
|
1562
|
+
theirs = other.#readRawBytes('compare', ctx);
|
|
1563
|
+
}
|
|
1564
|
+
else if (typeof other === 'string') {
|
|
1565
|
+
theirs = Buffer.from(other, 'utf8');
|
|
1566
|
+
}
|
|
1567
|
+
else {
|
|
1568
|
+
// The declared signature allows a string or an instance, and this path
|
|
1569
|
+
// refuses anything else rather than guessing. Leaving it to
|
|
1570
|
+
// `Buffer.from` would be worse than it looks: `Buffer.from([])` is a
|
|
1571
|
+
// valid empty buffer, so an array comparand would silently become bytes
|
|
1572
|
+
// and compare, where the constant-time string path raises because
|
|
1573
|
+
// `createHmac` refuses it. A comparison that answers at all for a
|
|
1574
|
+
// comparand nobody meant to pass is the wrong outcome for this method.
|
|
1575
|
+
throw new TypeError(`SensitiveString.equals expects a string or a SensitiveString; ` +
|
|
1576
|
+
`received ${describeNonString(other)}`);
|
|
1577
|
+
}
|
|
1578
|
+
return (0, compare_js_1.constantTimeEqualsBytes)(mine, theirs);
|
|
1579
|
+
}
|
|
1580
|
+
finally {
|
|
1581
|
+
// Both operands are this method's own: `#readRawBytes` hands back a
|
|
1582
|
+
// buffer the caller owns, and the string branch encodes into a fresh one.
|
|
1583
|
+
// Zeroing them is what makes row twelve of the design's measurement true,
|
|
1584
|
+
// and the `finally` is so a throwing comparand does not skip it.
|
|
1585
|
+
mine.fill(0);
|
|
1586
|
+
theirs?.fill(0);
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Concatenate with another string or SensitiveString.
|
|
1591
|
+
*
|
|
1592
|
+
* Inherits the most restrictive sensitivity class.
|
|
1593
|
+
* Labels are combined with '/' separator.
|
|
1594
|
+
*
|
|
1595
|
+
* @param other - The value to append.
|
|
1596
|
+
* @param ctx - Audit context for raw-value access.
|
|
1597
|
+
*/
|
|
1598
|
+
concat(other, ctx) {
|
|
1599
|
+
const value = this.#readRawValue('expose', ctx);
|
|
1600
|
+
const rawOther = other instanceof _a ? other.#readRawValue('expose', ctx) : other;
|
|
1601
|
+
const otherClass = other instanceof _a ? other.klass : 'sensitive';
|
|
1602
|
+
const otherLabel = other instanceof _a ? other.label : undefined;
|
|
1603
|
+
const combinedClass = this.policy.combineClasses
|
|
1604
|
+
? this.policy.combineClasses(this.klass, otherClass)
|
|
1605
|
+
: (0, policy_js_1.defaultCombineClasses)(this.klass, otherClass);
|
|
1606
|
+
// Combine labels if both exist
|
|
1607
|
+
const combinedLabel = this.label && otherLabel ? `${this.label}/${otherLabel}` : (this.label ?? otherLabel);
|
|
1608
|
+
const sources = other instanceof _a ? [this, other] : [this];
|
|
1609
|
+
return _a.#derived(value + rawOther, combinedClass, combinedLabel, sources);
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* Get the length of the raw value.
|
|
1613
|
+
* Note: Length is generally not considered sensitive for most use cases.
|
|
1614
|
+
*
|
|
1615
|
+
* @throws ClearedSensitiveValueError If the value, or one it was derived from, has been cleared. `0` would be a wrong answer, not a degraded one.
|
|
1616
|
+
*/
|
|
1617
|
+
get length() {
|
|
1618
|
+
// The `'safe'` path is exempt from the cleared check so redaction survives
|
|
1619
|
+
// one, and this reader has nothing to fall back on: after a clear it would
|
|
1620
|
+
// answer `0` from the empty string. That is a wrong answer rather than a
|
|
1621
|
+
// degraded one, and a caller branching on `if (!token.length)` would read a
|
|
1622
|
+
// destroyed credential as an absent one.
|
|
1623
|
+
this.#refuseIfCleared();
|
|
1624
|
+
return this.#rawLength();
|
|
1625
|
+
}
|
|
1626
|
+
/**
|
|
1627
|
+
* The length in UTF-16 code units, without deciding whether the caller may
|
|
1628
|
+
* have it.
|
|
1629
|
+
*
|
|
1630
|
+
* A sealed value answers from the count captured at construction. Decoding
|
|
1631
|
+
* the box to measure it would put a plaintext string in the heap for a
|
|
1632
|
+
* question this library documents as not sensitive, which is the trade
|
|
1633
|
+
* sealing exists to refuse.
|
|
1634
|
+
*
|
|
1635
|
+
* Private, so `isEmpty()` does not route its answer through a public `length`
|
|
1636
|
+
* a subclass could override, for the reason `#clearedFlag` is private.
|
|
1637
|
+
*/
|
|
1638
|
+
#rawLength() {
|
|
1639
|
+
return this.#box !== undefined ? this.#sealedLength : this.#readRawValue('safe').length;
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* Check if the raw value is empty.
|
|
1643
|
+
*
|
|
1644
|
+
* @throws ClearedSensitiveValueError If the value, or one it was derived from, has been cleared. `true` would be a wrong answer, not a degraded one.
|
|
1645
|
+
*/
|
|
1646
|
+
isEmpty() {
|
|
1647
|
+
this.#refuseIfCleared();
|
|
1648
|
+
return this.#rawLength() === 0;
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Create a substring, preserving sensitivity class and label.
|
|
1652
|
+
*
|
|
1653
|
+
* @param start - Start index.
|
|
1654
|
+
* @param end - Optional end index.
|
|
1655
|
+
* @param ctx - Audit context.
|
|
1656
|
+
* @throws If policy checking fails (e.g., context required but not provided).
|
|
1657
|
+
*/
|
|
1658
|
+
substring(start, end, ctx) {
|
|
1659
|
+
return this.#transform((value) => value.substring(start, end), ctx);
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1662
|
+
* Remove whitespace from both ends, preserving sensitivity and label.
|
|
1663
|
+
*
|
|
1664
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1665
|
+
*/
|
|
1666
|
+
trim(ctx) {
|
|
1667
|
+
return this.#transform((value) => value.trim(), ctx);
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Remove leading whitespace, preserving sensitivity and label.
|
|
1671
|
+
*
|
|
1672
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1673
|
+
*/
|
|
1674
|
+
trimStart(ctx) {
|
|
1675
|
+
return this.#transform((value) => value.trimStart(), ctx);
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* Remove trailing whitespace, preserving sensitivity and label.
|
|
1679
|
+
*
|
|
1680
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1681
|
+
*/
|
|
1682
|
+
trimEnd(ctx) {
|
|
1683
|
+
return this.#transform((value) => value.trimEnd(), ctx);
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Convert the value to lowercase, preserving sensitivity and label.
|
|
1687
|
+
*
|
|
1688
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1689
|
+
*/
|
|
1690
|
+
toLowerCase(ctx) {
|
|
1691
|
+
return this.#transform((value) => value.toLowerCase(), ctx);
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Convert the value to uppercase, preserving sensitivity and label.
|
|
1695
|
+
*
|
|
1696
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1697
|
+
*/
|
|
1698
|
+
toUpperCase(ctx) {
|
|
1699
|
+
return this.#transform((value) => value.toUpperCase(), ctx);
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Pad the start of the value to a target length.
|
|
1703
|
+
*
|
|
1704
|
+
* @param targetLength - Desired result length.
|
|
1705
|
+
* @param padString - String used for padding.
|
|
1706
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1707
|
+
*/
|
|
1708
|
+
padStart(targetLength, padString, ctx) {
|
|
1709
|
+
return this.#transform((value) => value.padStart(targetLength, padString), ctx);
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Pad the end of the value to a target length.
|
|
1713
|
+
*
|
|
1714
|
+
* @param targetLength - Desired result length.
|
|
1715
|
+
* @param padString - String used for padding.
|
|
1716
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1717
|
+
*/
|
|
1718
|
+
padEnd(targetLength, padString, ctx) {
|
|
1719
|
+
return this.#transform((value) => value.padEnd(targetLength, padString), ctx);
|
|
1720
|
+
}
|
|
1721
|
+
/**
|
|
1722
|
+
* Extract a section of the value, preserving sensitivity and label.
|
|
1723
|
+
*
|
|
1724
|
+
* @param start - Zero-based start index. Negative indices count from the end.
|
|
1725
|
+
* @param end - Optional exclusive end index.
|
|
1726
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1727
|
+
*/
|
|
1728
|
+
slice(start, end, ctx) {
|
|
1729
|
+
return this.#transform((value) => value.slice(start, end), ctx);
|
|
1730
|
+
}
|
|
1731
|
+
/**
|
|
1732
|
+
* Test whether the value begins with a string.
|
|
1733
|
+
*
|
|
1734
|
+
* Partial queries are disabled for credentials by default because their
|
|
1735
|
+
* results can be used as a character-by-character oracle.
|
|
1736
|
+
*
|
|
1737
|
+
* @param searchString - Prefix to find.
|
|
1738
|
+
* @param position - Position at which to begin searching.
|
|
1739
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1740
|
+
*/
|
|
1741
|
+
startsWith(searchString, position, ctx) {
|
|
1742
|
+
return this.#readPartialQueryValue(ctx).startsWith(searchString, position);
|
|
1743
|
+
}
|
|
1744
|
+
/**
|
|
1745
|
+
* Test whether the value ends with a string.
|
|
1746
|
+
*
|
|
1747
|
+
* @param searchString - Suffix to find.
|
|
1748
|
+
* @param endPosition - End position to use for the search.
|
|
1749
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1750
|
+
*/
|
|
1751
|
+
endsWith(searchString, endPosition, ctx) {
|
|
1752
|
+
return this.#readPartialQueryValue(ctx).endsWith(searchString, endPosition);
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Test whether the value contains a string.
|
|
1756
|
+
*
|
|
1757
|
+
* @param searchString - String to find.
|
|
1758
|
+
* @param position - Position at which to begin searching.
|
|
1759
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1760
|
+
*/
|
|
1761
|
+
includes(searchString, position, ctx) {
|
|
1762
|
+
return this.#readPartialQueryValue(ctx).includes(searchString, position);
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Find the first index of a string in the value.
|
|
1766
|
+
*
|
|
1767
|
+
* @param searchString - String to find.
|
|
1768
|
+
* @param position - Position at which to begin searching.
|
|
1769
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1770
|
+
*/
|
|
1771
|
+
indexOf(searchString, position, ctx) {
|
|
1772
|
+
return this.#readPartialQueryValue(ctx).indexOf(searchString, position);
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* Find the last index of a string in the value.
|
|
1776
|
+
*
|
|
1777
|
+
* @param searchString - String to find.
|
|
1778
|
+
* @param position - Position at which to begin searching backward.
|
|
1779
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1780
|
+
*/
|
|
1781
|
+
lastIndexOf(searchString, position, ctx) {
|
|
1782
|
+
return this.#readPartialQueryValue(ctx).lastIndexOf(searchString, position);
|
|
1783
|
+
}
|
|
1784
|
+
/**
|
|
1785
|
+
* Test whether a regular expression matches the value.
|
|
1786
|
+
*
|
|
1787
|
+
* Regex tests are partial queries and are disabled for credentials by default
|
|
1788
|
+
* because caller-controlled patterns can form a powerful content oracle.
|
|
1789
|
+
*
|
|
1790
|
+
* @param pattern - Regular expression to test.
|
|
1791
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1792
|
+
*/
|
|
1793
|
+
test(pattern, ctx) {
|
|
1794
|
+
const regex = (0, regexp_js_1.snapshotRegExp)(pattern, 'SensitiveString.test');
|
|
1795
|
+
return regex.test(this.#readPartialQueryValue(ctx));
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Find the index of the first regular-expression match.
|
|
1799
|
+
*
|
|
1800
|
+
* This is a partial query and is disabled for credentials by default.
|
|
1801
|
+
*
|
|
1802
|
+
* @param pattern - Regular expression to search for.
|
|
1803
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1804
|
+
*/
|
|
1805
|
+
search(pattern, ctx) {
|
|
1806
|
+
const regex = (0, regexp_js_1.snapshotRegExp)(pattern, 'SensitiveString.search');
|
|
1807
|
+
return this.#readPartialQueryValue(ctx).search(regex);
|
|
1808
|
+
}
|
|
1809
|
+
/**
|
|
1810
|
+
* Return regular-expression matches as protected values.
|
|
1811
|
+
*
|
|
1812
|
+
* Native match metadata such as `input` is intentionally omitted because it
|
|
1813
|
+
* contains the complete raw value. Unmatched optional captures are omitted.
|
|
1814
|
+
*
|
|
1815
|
+
* @param pattern - Regular expression to match.
|
|
1816
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1817
|
+
*/
|
|
1818
|
+
match(pattern, ctx) {
|
|
1819
|
+
const regex = (0, regexp_js_1.snapshotRegExp)(pattern, 'SensitiveString.match');
|
|
1820
|
+
const matches = this.#readRawValue('expose', ctx).match(regex);
|
|
1821
|
+
if (matches === null) {
|
|
1822
|
+
return null;
|
|
1823
|
+
}
|
|
1824
|
+
return matches
|
|
1825
|
+
.filter((match) => match !== undefined)
|
|
1826
|
+
.map((match) => _a.#derived(match, this.klass, this.label, [this]));
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
1829
|
+
* Return named regular-expression groups as protected values.
|
|
1830
|
+
*
|
|
1831
|
+
* A successful match without named groups returns an empty, null-prototype
|
|
1832
|
+
* object. Named groups that did not participate in the match are omitted.
|
|
1833
|
+
*
|
|
1834
|
+
* @param pattern - Regular expression containing optional named groups.
|
|
1835
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1836
|
+
*/
|
|
1837
|
+
matchGroups(pattern, ctx) {
|
|
1838
|
+
const regex = (0, regexp_js_1.snapshotRegExp)(pattern, 'SensitiveString.matchGroups');
|
|
1839
|
+
const match = regex.exec(this.#readRawValue('expose', ctx));
|
|
1840
|
+
if (match === null) {
|
|
1841
|
+
return null;
|
|
1842
|
+
}
|
|
1843
|
+
const groups = Object.create(null);
|
|
1844
|
+
for (const [group, value] of Object.entries(match.groups ?? {})) {
|
|
1845
|
+
if (value === undefined) {
|
|
1846
|
+
continue;
|
|
1847
|
+
}
|
|
1848
|
+
const label = this.label !== undefined ? `${this.label}:${group}` : group;
|
|
1849
|
+
Object.defineProperty(groups, group, {
|
|
1850
|
+
value: _a.#derived(value, this.klass, label, [this]),
|
|
1851
|
+
enumerable: true,
|
|
1852
|
+
configurable: true,
|
|
1853
|
+
writable: true,
|
|
1854
|
+
});
|
|
1855
|
+
}
|
|
1856
|
+
return groups;
|
|
1857
|
+
}
|
|
1858
|
+
/**
|
|
1859
|
+
* Return every regular-expression match as an iterator of protected arrays.
|
|
1860
|
+
*
|
|
1861
|
+
* The pattern must have the global (`g`) flag, matching native String.matchAll
|
|
1862
|
+
* requirements. Match metadata containing the complete input is omitted.
|
|
1863
|
+
*
|
|
1864
|
+
* @param pattern - Global regular expression to match.
|
|
1865
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1866
|
+
*/
|
|
1867
|
+
matchAll(pattern, ctx) {
|
|
1868
|
+
const regex = (0, regexp_js_1.snapshotRegExp)(pattern, 'SensitiveString.matchAll');
|
|
1869
|
+
if (!regex.global) {
|
|
1870
|
+
throw new TypeError('SensitiveString.matchAll requires a global regular expression');
|
|
1871
|
+
}
|
|
1872
|
+
const matches = this.#readRawValue('expose', ctx).matchAll(regex);
|
|
1873
|
+
const protect = (match) => match
|
|
1874
|
+
.filter((part) => part !== undefined)
|
|
1875
|
+
.map((part) => _a.#derived(part, this.klass, this.label, [this]));
|
|
1876
|
+
return (function* protectedMatches() {
|
|
1877
|
+
for (const match of matches) {
|
|
1878
|
+
yield protect(match);
|
|
1879
|
+
}
|
|
1880
|
+
})();
|
|
1881
|
+
}
|
|
1882
|
+
/**
|
|
1883
|
+
* Split the value into protected parts.
|
|
1884
|
+
*
|
|
1885
|
+
* @param separator - String or regular expression used to divide the value.
|
|
1886
|
+
* @param limit - Maximum number of results.
|
|
1887
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1888
|
+
*/
|
|
1889
|
+
split(separator, limit, ctx) {
|
|
1890
|
+
const safeSeparator = typeof separator === 'string'
|
|
1891
|
+
? separator
|
|
1892
|
+
: (0, regexp_js_1.snapshotRegExp)(separator, 'SensitiveString.split');
|
|
1893
|
+
const value = this.#readRawValue('expose', ctx);
|
|
1894
|
+
return value
|
|
1895
|
+
.split(safeSeparator, limit)
|
|
1896
|
+
.map((part) => _a.#derived(part, this.klass, this.label, [this]));
|
|
1897
|
+
}
|
|
1898
|
+
/**
|
|
1899
|
+
* Replace the first matching string or the matches selected by a regular expression.
|
|
1900
|
+
*
|
|
1901
|
+
* Replacement callbacks are intentionally unsupported because they receive raw
|
|
1902
|
+
* matched content.
|
|
1903
|
+
*
|
|
1904
|
+
* @param searchValue - String or regular expression to replace.
|
|
1905
|
+
* @param replaceValue - String replacement pattern.
|
|
1906
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1907
|
+
*/
|
|
1908
|
+
replace(searchValue, replaceValue, ctx) {
|
|
1909
|
+
if (typeof replaceValue !== 'string') {
|
|
1910
|
+
throw new TypeError('SensitiveString replacement value must be a string');
|
|
1911
|
+
}
|
|
1912
|
+
const safeSearchValue = typeof searchValue === 'string'
|
|
1913
|
+
? searchValue
|
|
1914
|
+
: (0, regexp_js_1.snapshotRegExp)(searchValue, 'SensitiveString.replace');
|
|
1915
|
+
return this.#transform((value) => value.replace(safeSearchValue, replaceValue), ctx);
|
|
1916
|
+
}
|
|
1917
|
+
/**
|
|
1918
|
+
* Replace every matching string or regular-expression match.
|
|
1919
|
+
*
|
|
1920
|
+
* Replacement callbacks are intentionally unsupported because they receive raw
|
|
1921
|
+
* matched content.
|
|
1922
|
+
*
|
|
1923
|
+
* @param searchValue - String or global regular expression to replace.
|
|
1924
|
+
* @param replaceValue - String replacement pattern.
|
|
1925
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1926
|
+
*/
|
|
1927
|
+
replaceAll(searchValue, replaceValue, ctx) {
|
|
1928
|
+
if (typeof replaceValue !== 'string') {
|
|
1929
|
+
throw new TypeError('SensitiveString replacement value must be a string');
|
|
1930
|
+
}
|
|
1931
|
+
const safeSearchValue = typeof searchValue === 'string'
|
|
1932
|
+
? searchValue
|
|
1933
|
+
: (0, regexp_js_1.snapshotRegExp)(searchValue, 'SensitiveString.replaceAll');
|
|
1934
|
+
if (safeSearchValue instanceof RegExp && !safeSearchValue.global) {
|
|
1935
|
+
throw new TypeError('SensitiveString.replaceAll requires a global regular expression');
|
|
1936
|
+
}
|
|
1937
|
+
return this.#transform((value) => value.replaceAll(safeSearchValue, replaceValue), ctx);
|
|
1938
|
+
}
|
|
1939
|
+
/**
|
|
1940
|
+
* Return the character at an index as a protected value.
|
|
1941
|
+
*
|
|
1942
|
+
* An out-of-range index returns a protected empty string, matching String.charAt().
|
|
1943
|
+
*
|
|
1944
|
+
* @param index - Zero-based character index.
|
|
1945
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1946
|
+
*/
|
|
1947
|
+
charAt(index, ctx) {
|
|
1948
|
+
return this.#transform((value) => value.charAt(index), ctx);
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* Return the character at an index as a protected value.
|
|
1952
|
+
*
|
|
1953
|
+
* @param index - Character index. Negative indices count from the end.
|
|
1954
|
+
* @param ctx - Optional reveal context for authorization and auditing.
|
|
1955
|
+
*/
|
|
1956
|
+
at(index, ctx) {
|
|
1957
|
+
const value = this.#readRawValue('expose', ctx).at(index);
|
|
1958
|
+
return value === undefined
|
|
1959
|
+
? undefined
|
|
1960
|
+
: _a.#derived(value, this.klass, this.label, [this]);
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* Serialize for secure service boundary transmission.
|
|
1964
|
+
*
|
|
1965
|
+
* ⚠️ RETURNS RAW VALUE - DO NOT LOG ⚠️
|
|
1966
|
+
*
|
|
1967
|
+
* Intended for mTLS/encrypted transmission only.
|
|
1968
|
+
*
|
|
1969
|
+
* A deadline travels with the value, so a token with five minutes left still
|
|
1970
|
+
* has five minutes left on the other side. The receiver enforces it against
|
|
1971
|
+
* its own clock: a receiver whose clock runs ahead of the sender's rejects the
|
|
1972
|
+
* value early, which is the direction to fail in. Renewal permission and
|
|
1973
|
+
* renewal counts do not travel, so a payload cannot grant the right to extend
|
|
1974
|
+
* a credential's lifetime.
|
|
1975
|
+
*
|
|
1976
|
+
* A revoked value is not transmittable: reading it to build the payload goes
|
|
1977
|
+
* through the same gate as any other read, so this throws rather than
|
|
1978
|
+
* emitting the wire format's `revoked` flag. That flag is for the receiving
|
|
1979
|
+
* side, and `deserialize()` honours it.
|
|
1980
|
+
*
|
|
1981
|
+
* Environment restrictions travel too, so a value that may only be read in
|
|
1982
|
+
* the EU is still restricted to the EU on the other side. A restriction that
|
|
1983
|
+
* is a function does not travel and cannot: such a value refuses to
|
|
1984
|
+
* serialize rather than arriving with half of its restriction enforced.
|
|
1985
|
+
*
|
|
1986
|
+
* Destination bindings travel as well, and serializing is itself a reveal
|
|
1987
|
+
* toward wherever the payload is going: a bound value serializes only under
|
|
1988
|
+
* a context whose tags name a sink or host the binding allows.
|
|
1989
|
+
*
|
|
1990
|
+
* @param ctx - Optional context for audit/permission checks
|
|
1991
|
+
* @throws ExpiredSensitiveValueError If the value has expired.
|
|
1992
|
+
* @throws RevokedSensitiveValueError If the value has been revoked.
|
|
1993
|
+
* @throws EnvironmentRestrictedError If this environment may not read the value.
|
|
1994
|
+
* @throws DestinationRestrictedError If the context names no destination the value allows.
|
|
1995
|
+
* @throws UnserializableRestrictionError If the value carries a custom restriction.
|
|
1996
|
+
*/
|
|
1997
|
+
serialize(ctx) {
|
|
1998
|
+
return this.#serialize(ctx, REVEAL_AUDIT_DETAILS);
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* The wire form, read under the given audit record.
|
|
2002
|
+
*
|
|
2003
|
+
* `serialize()` reports a reveal; a handoff to another thread reports itself
|
|
2004
|
+
* as one, through `serializeSensitiveString`. Same gate, same access kind.
|
|
2005
|
+
*/
|
|
2006
|
+
#serialize(ctx, details) {
|
|
2007
|
+
// Before the read, so a value that cannot cross intact is refused without
|
|
2008
|
+
// being revealed or audited. A function has no wire form: emitting the
|
|
2009
|
+
// declarative half and dropping this would hand the receiver a value it
|
|
2010
|
+
// believes it has fully checked.
|
|
2011
|
+
if ((0, environment_js_1.carriesCustomRestriction)(this.#restrictions)) {
|
|
2012
|
+
throw new environment_js_1.UnserializableRestrictionError(this.label);
|
|
2013
|
+
}
|
|
2014
|
+
const value = this.#readRawValue('expose', ctx, details);
|
|
2015
|
+
const deadline = this.#earliestDeadline();
|
|
2016
|
+
const serialized = {
|
|
2017
|
+
__sensitive: true,
|
|
2018
|
+
klass: this.klass,
|
|
2019
|
+
value,
|
|
2020
|
+
};
|
|
2021
|
+
if (this.label !== undefined) {
|
|
2022
|
+
serialized.label = this.label;
|
|
2023
|
+
}
|
|
2024
|
+
if (deadline !== undefined) {
|
|
2025
|
+
serialized.expiresAt = isoDeadline(deadline);
|
|
2026
|
+
}
|
|
2027
|
+
if (this.#restrictions.length !== 0) {
|
|
2028
|
+
serialized.restrictions = (0, environment_js_1.serializeRestrictions)(this.#restrictions);
|
|
2029
|
+
}
|
|
2030
|
+
if (this.#destinations.length !== 0) {
|
|
2031
|
+
serialized.destinations = (0, destination_js_1.serializeDestinations)(this.#destinations);
|
|
2032
|
+
}
|
|
2033
|
+
return serialized;
|
|
2034
|
+
}
|
|
2035
|
+
/**
|
|
2036
|
+
* Reconstruct a SensitiveString from a serialized form.
|
|
2037
|
+
*
|
|
2038
|
+
* @param serialized - The serialized form (potentially untrusted data from external source).
|
|
2039
|
+
* @throws If the serialized form is invalid or missing required fields.
|
|
2040
|
+
* @throws If the klass is not a registered sensitivity class.
|
|
2041
|
+
*/
|
|
2042
|
+
static deserialize(serialized) {
|
|
2043
|
+
// Type guard for runtime validation of untrusted data
|
|
2044
|
+
if (typeof serialized !== 'object' ||
|
|
2045
|
+
serialized === null ||
|
|
2046
|
+
!('__sensitive' in serialized) ||
|
|
2047
|
+
serialized.__sensitive !== true) {
|
|
2048
|
+
throw new Error('Invalid SerializedSensitiveString: missing __sensitive marker');
|
|
2049
|
+
}
|
|
2050
|
+
if (!('value' in serialized) || typeof serialized.value !== 'string') {
|
|
2051
|
+
throw new Error('Invalid SerializedSensitiveString: value must be a string');
|
|
2052
|
+
}
|
|
2053
|
+
if (!('klass' in serialized) || typeof serialized.klass !== 'string') {
|
|
2054
|
+
throw new Error('Invalid SerializedSensitiveString: klass must be a string');
|
|
2055
|
+
}
|
|
2056
|
+
// Validate that klass is a registered sensitivity class
|
|
2057
|
+
if (!(0, policy_js_1.hasPolicy)(serialized.klass)) {
|
|
2058
|
+
throw new Error(`Invalid SerializedSensitiveString: unknown sensitivity class '${serialized.klass}'`);
|
|
2059
|
+
}
|
|
2060
|
+
if ('label' in serialized &&
|
|
2061
|
+
serialized.label !== undefined &&
|
|
2062
|
+
typeof serialized.label !== 'string') {
|
|
2063
|
+
throw new Error('Invalid SerializedSensitiveString: label must be a string or undefined');
|
|
2064
|
+
}
|
|
2065
|
+
const label = 'label' in serialized && typeof serialized.label === 'string' ? serialized.label : undefined;
|
|
2066
|
+
const value = new _a(serialized.value, serialized.klass, label, _a.#deserializeOptions(serialized));
|
|
2067
|
+
const revoked = _a.#deserializeRevocation(serialized);
|
|
2068
|
+
if (revoked !== undefined) {
|
|
2069
|
+
(0, revocation_js_1.revokeStates)(value.#states, revoked, 'wire');
|
|
2070
|
+
}
|
|
2071
|
+
return value;
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* The reason a payload carries for a value it marks revoked, or `undefined`.
|
|
2075
|
+
*
|
|
2076
|
+
* `serialize()` never writes these fields, because the gate refuses to read a
|
|
2077
|
+
* revoked value at all. They exist so a payload assembled elsewhere can tell
|
|
2078
|
+
* the receiver not to use what it is sending, and they can only tighten:
|
|
2079
|
+
* there is no spelling of "not revoked" here, which is why `revoked: false`
|
|
2080
|
+
* is rejected rather than honoured. A reason without the flag is rejected
|
|
2081
|
+
* too, since it reads as a revocation that would silently not happen.
|
|
2082
|
+
*/
|
|
2083
|
+
static #deserializeRevocation(serialized) {
|
|
2084
|
+
const flag = 'revoked' in serialized ? serialized.revoked : undefined;
|
|
2085
|
+
const reason = 'revocationReason' in serialized ? serialized.revocationReason : undefined;
|
|
2086
|
+
if (flag !== undefined && flag !== true) {
|
|
2087
|
+
throw new Error('Invalid SerializedSensitiveString: revoked must be true or absent; ' +
|
|
2088
|
+
'there is no way to mark a value as not revoked');
|
|
2089
|
+
}
|
|
2090
|
+
if (reason !== undefined && typeof reason !== 'string') {
|
|
2091
|
+
throw new Error('Invalid SerializedSensitiveString: revocationReason must be a string');
|
|
2092
|
+
}
|
|
2093
|
+
if (flag === undefined) {
|
|
2094
|
+
if (reason !== undefined) {
|
|
2095
|
+
throw new Error('Invalid SerializedSensitiveString: revocationReason without revoked: true');
|
|
2096
|
+
}
|
|
2097
|
+
return undefined;
|
|
2098
|
+
}
|
|
2099
|
+
return reason ?? 'revoked by the sender';
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Rebuild the construction options carried by a serialized form.
|
|
2103
|
+
*
|
|
2104
|
+
* The deadline, the environment restrictions and the destination bindings
|
|
2105
|
+
* cross, and nothing else. All three only ever narrow what the receiver may
|
|
2106
|
+
* do. Renewal permission and renewal counts are decided locally, by the
|
|
2107
|
+
* receiving process's policy: taking them from a payload would let a sender
|
|
2108
|
+
* declare a credential renewable.
|
|
2109
|
+
*/
|
|
2110
|
+
static #deserializeOptions(serialized) {
|
|
2111
|
+
const options = {};
|
|
2112
|
+
const restrictions = (0, environment_js_1.deserializeRestrictions)(serialized);
|
|
2113
|
+
const destinations = (0, destination_js_1.deserializeDestinations)(serialized);
|
|
2114
|
+
if (restrictions !== undefined) {
|
|
2115
|
+
options.restrictions = restrictions;
|
|
2116
|
+
}
|
|
2117
|
+
if (destinations !== undefined) {
|
|
2118
|
+
options.destinations = destinations;
|
|
2119
|
+
}
|
|
2120
|
+
if ('expiresAt' in serialized && serialized.expiresAt !== undefined) {
|
|
2121
|
+
if (typeof serialized.expiresAt !== 'string') {
|
|
2122
|
+
throw new Error('Invalid SerializedSensitiveString: expiresAt must be an ISO 8601 string');
|
|
2123
|
+
}
|
|
2124
|
+
const expiresAt = new Date(serialized.expiresAt);
|
|
2125
|
+
if (Number.isNaN(expiresAt.getTime())) {
|
|
2126
|
+
throw new Error(`Invalid SerializedSensitiveString: expiresAt '${serialized.expiresAt}' is not a valid date`);
|
|
2127
|
+
}
|
|
2128
|
+
options.expiresAt = expiresAt;
|
|
2129
|
+
}
|
|
2130
|
+
return Object.keys(options).length === 0 ? undefined : options;
|
|
2131
|
+
}
|
|
2132
|
+
/**
|
|
2133
|
+
* Create a SensitiveString if the input is truthy, otherwise return null.
|
|
2134
|
+
* Useful for optional fields.
|
|
2135
|
+
*/
|
|
2136
|
+
/**
|
|
2137
|
+
* Create a sealed SensitiveString from bytes, without the value ever becoming
|
|
2138
|
+
* a JavaScript string.
|
|
2139
|
+
*
|
|
2140
|
+
* The reason to reach for this over the ordinary constructor: a string passed
|
|
2141
|
+
* to the constructor survives in process memory after the instance drops it,
|
|
2142
|
+
* permanently as far as a core dump is concerned, because JavaScript cannot
|
|
2143
|
+
* overwrite a string's backing store. A value that arrives as bytes, from a
|
|
2144
|
+
* KMS client or a secrets manager, need never become one.
|
|
2145
|
+
*
|
|
2146
|
+
* **`bytes` is zeroed before this returns.** A caller that needs to keep them
|
|
2147
|
+
* must copy first. That is the point of the method rather than a side effect
|
|
2148
|
+
* of it: leaving the caller's buffer intact would move the exposure rather
|
|
2149
|
+
* than remove it.
|
|
2150
|
+
*
|
|
2151
|
+
* Seals unconditionally, so it refuses `{ sealed: false }` rather than
|
|
2152
|
+
* accepting an option that contradicts its only purpose. Every other option
|
|
2153
|
+
* behaves as it does on the constructor.
|
|
2154
|
+
*
|
|
2155
|
+
* One exception to the promise, and it is the policy's doing rather than this
|
|
2156
|
+
* method's. A sealed value's redacted rendering is captured at construction,
|
|
2157
|
+
* and there is no live value here to capture it from. When the class policy's
|
|
2158
|
+
* rendering ignores its argument, which every default one does, that costs
|
|
2159
|
+
* nothing. When the policy reads the value, which is exactly what
|
|
2160
|
+
* deterministic redaction is for, the bytes are decoded once so the tag is the
|
|
2161
|
+
* tag of this value rather than the shared tag of the empty string, and that
|
|
2162
|
+
* one plaintext string is then in process memory for good. A process that
|
|
2163
|
+
* wants both `fromBuffer`'s guarantee and a value-derived rendering cannot
|
|
2164
|
+
* have both, and this resolves it in favour of a rendering that is not
|
|
2165
|
+
* silently wrong.
|
|
2166
|
+
*
|
|
2167
|
+
* @param bytes - The value as UTF-8 bytes. Zeroed before this returns.
|
|
2168
|
+
* @param klass - The sensitivity classification.
|
|
2169
|
+
* @param label - Optional label for audit and compliance.
|
|
2170
|
+
* @param options - Shared options, as on the constructor.
|
|
2171
|
+
* @throws TypeError If `bytes` is not a Buffer, if it is not valid UTF-8, or if `options.sealed` is false.
|
|
2172
|
+
* @throws SealingUnavailableError If this process cannot seal.
|
|
2173
|
+
*
|
|
2174
|
+
* @example
|
|
2175
|
+
* ```ts
|
|
2176
|
+
* const bytes = await kms.decryptToBuffer(blob); // a Buffer, never a string
|
|
2177
|
+
* const password = SensitiveString.fromBuffer(bytes, 'credential', 'db_password');
|
|
2178
|
+
* // `bytes` is now zeroed.
|
|
2179
|
+
* ```
|
|
2180
|
+
*/
|
|
2181
|
+
static fromBuffer(bytes, klass, label, options) {
|
|
2182
|
+
if (!Buffer.isBuffer(bytes)) {
|
|
2183
|
+
throw new TypeError(`SensitiveString.fromBuffer expects a Buffer; received ${describeNonString(bytes)}`);
|
|
2184
|
+
}
|
|
2185
|
+
if (options?.sealed === false) {
|
|
2186
|
+
throw new TypeError('SensitiveString.fromBuffer always seals; pass the value to the constructor ' +
|
|
2187
|
+
'instead of asking for { sealed: false }');
|
|
2188
|
+
}
|
|
2189
|
+
// Before construction, so a rejected buffer leaves no instance behind, and
|
|
2190
|
+
// a walk rather than a decode: `new TextDecoder('utf-8', { fatal: true })`
|
|
2191
|
+
// would validate by producing exactly the plaintext string this method
|
|
2192
|
+
// exists to avoid. Invalid sequences have to be refused rather than
|
|
2193
|
+
// replaced, because U+FFFD substitution changes both the value a later
|
|
2194
|
+
// reveal returns and the length reported for it.
|
|
2195
|
+
const codeUnits = (0, sealing_js_1.utf8CodeUnits)(bytes);
|
|
2196
|
+
// A sealed value's redacted rendering is captured at construction, and there
|
|
2197
|
+
// is no live value here to capture it from. A policy whose rendering ignores
|
|
2198
|
+
// its argument, which every default one does, is happy with the empty
|
|
2199
|
+
// string. One that reads the value, which is what deterministic redaction
|
|
2200
|
+
// is, would otherwise give every value built this way the single shared
|
|
2201
|
+
// correlation tag of `redact('')`, which is worse than no tag at all.
|
|
2202
|
+
//
|
|
2203
|
+
// So the plaintext is decoded only for a policy that reads it, and that
|
|
2204
|
+
// process pays one permanent plaintext copy in process memory for the
|
|
2205
|
+
// rendering it asked for. Documented above, and it is the one case where
|
|
2206
|
+
// this method cannot keep its whole promise.
|
|
2207
|
+
const rendered = redactionReadsValue((0, policy_js_1.getPolicy)(klass)) ? bytes.toString('utf8') : '';
|
|
2208
|
+
try {
|
|
2209
|
+
// Constructed empty and sealed afterwards from the caller's bytes. The
|
|
2210
|
+
// constructor takes a string, so passing the value through it is the one
|
|
2211
|
+
// thing this method may not do; `sealed: false` here keeps it from
|
|
2212
|
+
// sealing the empty string on the way past.
|
|
2213
|
+
const instance = new _a('', klass, label, { ...options, sealed: false });
|
|
2214
|
+
instance.#sealFromBytes(bytes, codeUnits, rendered);
|
|
2215
|
+
return instance;
|
|
2216
|
+
}
|
|
2217
|
+
finally {
|
|
2218
|
+
bytes.fill(0);
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
static fromOptional(value, klass, label, options) {
|
|
2222
|
+
if (value == null || value === '') {
|
|
2223
|
+
return null;
|
|
2224
|
+
}
|
|
2225
|
+
return new _a(value, klass, label, options);
|
|
2226
|
+
}
|
|
2227
|
+
/**
|
|
2228
|
+
* Map over the raw value, producing a new SensitiveString.
|
|
2229
|
+
* The transformation function receives the raw value.
|
|
2230
|
+
*
|
|
2231
|
+
* @param fn - Transformation function
|
|
2232
|
+
* @param ctx - Reveal context for audit
|
|
2233
|
+
* @returns A new SensitiveString with the transformed value, preserving class and label
|
|
2234
|
+
* @throws If policy checking fails (e.g., context required but not provided).
|
|
2235
|
+
*/
|
|
2236
|
+
map(fn, ctx) {
|
|
2237
|
+
const value = this.#readRawValue('expose', ctx);
|
|
2238
|
+
return _a.#derived(fn(value), this.klass, this.label, [this]);
|
|
2239
|
+
}
|
|
2240
|
+
/**
|
|
2241
|
+
* Reclassify this value with a different sensitivity class and/or label.
|
|
2242
|
+
* Creates a new SensitiveString with the same value but different class/label.
|
|
2243
|
+
*
|
|
2244
|
+
* @param newKlass - The new sensitivity class
|
|
2245
|
+
* @param newLabel - Optional new label (if undefined, preserves existing label)
|
|
2246
|
+
* @param ctx - Reveal context for audit
|
|
2247
|
+
* @returns A new SensitiveString with the new class
|
|
2248
|
+
* @throws If policy checking fails (e.g., context required but not provided).
|
|
2249
|
+
*
|
|
2250
|
+
* @remarks
|
|
2251
|
+
* Use with caution - this bypasses the automatic class escalation logic.
|
|
2252
|
+
*/
|
|
2253
|
+
reclassify(newKlass, newLabel, ctx) {
|
|
2254
|
+
const value = this.#readRawValue('expose', ctx);
|
|
2255
|
+
return _a.#derived(value, newKlass, newLabel ?? this.label, [this]);
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
exports.SensitiveString = SensitiveString;
|
|
2259
|
+
_a = SensitiveString;
|
|
2260
|
+
//# sourceMappingURL=sensitive-string.js.map
|