@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
package/dist/worker.js
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UnshareableConstraintError = exports.UnportableDataError = exports.UnauditedWorkerError = exports.UnregisteredClassError = exports.MissingWorkerValueError = exports.ConsumedWorkerPayloadError = exports.MalformedWorkerPayloadError = void 0;
|
|
4
|
+
exports.toWorkerPayload = toWorkerPayload;
|
|
5
|
+
exports.fromWorkerPayload = fromWorkerPayload;
|
|
6
|
+
exports.withWorkerPayload = withWorkerPayload;
|
|
7
|
+
/**
|
|
8
|
+
* Moving a value across a thread or process boundary, and getting it back.
|
|
9
|
+
*
|
|
10
|
+
* `structuredClone` turns a `SensitiveString` into a plain `{ klass, label }`
|
|
11
|
+
* with no value and no methods, and nothing throws at the boundary: the
|
|
12
|
+
* failure surfaces at the first method call, in another thread, in a stack
|
|
13
|
+
* that names neither. The usual fix is `workerData: { token: token.reveal() }`,
|
|
14
|
+
* which works, and which leaves the plaintext in a plain string for the life
|
|
15
|
+
* of the thread with no class, no deadline, and no audit record.
|
|
16
|
+
*
|
|
17
|
+
* `toWorkerPayload()` builds a payload out of the wire format, which is the
|
|
18
|
+
* shape `serialize()` already produces for a socket, so every marker-aware
|
|
19
|
+
* walk in this library redacts it, and `fromWorkerPayload()` rebuilds the
|
|
20
|
+
* instances on the far side. Building the payload is a reveal, authorized as
|
|
21
|
+
* an ordinary `expose` and audited as a `worker-handoff`. The one thing that
|
|
22
|
+
* cannot cross is a function, so the audit hook does not, and the receiving
|
|
23
|
+
* side is required to install its own.
|
|
24
|
+
*
|
|
25
|
+
* Neither function imports `node:worker_threads`. One builds a plain object
|
|
26
|
+
* and the other reads one, so the same pair works over `workerData`,
|
|
27
|
+
* `postMessage`, a `MessagePort`, a `BroadcastChannel`, and, with
|
|
28
|
+
* `transport: 'json'`, `child_process` IPC.
|
|
29
|
+
*/
|
|
30
|
+
const context_js_1 = require("./context.js");
|
|
31
|
+
const errors_js_1 = require("./errors.js");
|
|
32
|
+
const own_property_js_1 = require("./own-property.js");
|
|
33
|
+
const policy_js_1 = require("./policy.js");
|
|
34
|
+
const probe_js_1 = require("./probe.js");
|
|
35
|
+
const redact_js_1 = require("./redact.js");
|
|
36
|
+
const sensitive_string_js_1 = require("./sensitive-string.js");
|
|
37
|
+
const ttl_js_1 = require("./ttl.js");
|
|
38
|
+
/**
|
|
39
|
+
* The marker a payload carries.
|
|
40
|
+
*
|
|
41
|
+
* Distinct from `__sensitive`: the payload is a container of wire objects, not
|
|
42
|
+
* a wire object, and giving it the same marker would make `redactSerialized`
|
|
43
|
+
* render the whole container as one redaction and hide the structure from
|
|
44
|
+
* anyone debugging a handoff.
|
|
45
|
+
*/
|
|
46
|
+
const PAYLOAD_MARKER = '__sensitiveWorkerPayload';
|
|
47
|
+
/**
|
|
48
|
+
* Raised when what `fromWorkerPayload()` was handed is not a payload, or holds
|
|
49
|
+
* an entry that is not a serialized sensitive value.
|
|
50
|
+
*
|
|
51
|
+
* The message describes the shape received and never its contents.
|
|
52
|
+
*/
|
|
53
|
+
class MalformedWorkerPayloadError extends errors_js_1.SensitiveStringError {
|
|
54
|
+
name = 'MalformedWorkerPayloadError';
|
|
55
|
+
code = 'malformed-payload';
|
|
56
|
+
constructor(detail) {
|
|
57
|
+
super(`Invalid worker payload: ${detail}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
exports.MalformedWorkerPayloadError = MalformedWorkerPayloadError;
|
|
61
|
+
/**
|
|
62
|
+
* Raised when a payload is consumed a second time.
|
|
63
|
+
*
|
|
64
|
+
* The first `fromWorkerPayload()` deleted the raw values, so there is nothing
|
|
65
|
+
* left to rebuild.
|
|
66
|
+
*
|
|
67
|
+
* ⚠️ This is per copy, not per payload. Every transport clones, so a payload
|
|
68
|
+
* the sender posts to two workers arrives twice, whole, and each copy is
|
|
69
|
+
* consumable once; only the copy that was consumed, and anything it is passed
|
|
70
|
+
* on to, refuses. Consumption shortens how long *one thread* holds plaintext.
|
|
71
|
+
* It is not a use-once token, and nothing here makes it one: build a payload
|
|
72
|
+
* per destination, and remember the sender's own object still holds the
|
|
73
|
+
* values until it is unreachable.
|
|
74
|
+
*/
|
|
75
|
+
class ConsumedWorkerPayloadError extends errors_js_1.SensitiveStringError {
|
|
76
|
+
name = 'ConsumedWorkerPayloadError';
|
|
77
|
+
code = 'consumed-payload';
|
|
78
|
+
constructor() {
|
|
79
|
+
super('This worker payload has already been consumed: the first fromWorkerPayload() call ' +
|
|
80
|
+
'deleted its raw values. Build a new payload for a second handoff, or pass ' +
|
|
81
|
+
'keepPayload: true if one payload must feed two consumers.');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
exports.ConsumedWorkerPayloadError = ConsumedWorkerPayloadError;
|
|
85
|
+
/**
|
|
86
|
+
* Raised when a key named in `require` is absent from the payload.
|
|
87
|
+
*/
|
|
88
|
+
class MissingWorkerValueError extends errors_js_1.SensitiveStringError {
|
|
89
|
+
key;
|
|
90
|
+
name = 'MissingWorkerValueError';
|
|
91
|
+
code = 'missing-value';
|
|
92
|
+
constructor(key) {
|
|
93
|
+
super(`Worker payload has no value under the required key '${key}'`);
|
|
94
|
+
this.key = key;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
exports.MissingWorkerValueError = MissingWorkerValueError;
|
|
98
|
+
/**
|
|
99
|
+
* Raised when a payload names a sensitivity class this thread has not
|
|
100
|
+
* registered.
|
|
101
|
+
*
|
|
102
|
+
* Policies are per isolate: a class registered with `registerPolicy()` on the
|
|
103
|
+
* main thread does not exist in a worker, and a `redact` function could not be
|
|
104
|
+
* carried in the payload even if functions cloned, since a payload that can
|
|
105
|
+
* install a policy can install one that returns its input. The worker's own
|
|
106
|
+
* bootstrap registers what it needs.
|
|
107
|
+
*/
|
|
108
|
+
class UnregisteredClassError extends errors_js_1.SensitiveStringError {
|
|
109
|
+
key;
|
|
110
|
+
klass;
|
|
111
|
+
name = 'UnregisteredClassError';
|
|
112
|
+
code = 'unregistered-class';
|
|
113
|
+
constructor(key, klass, registered) {
|
|
114
|
+
super(`Worker payload value '${key}' has sensitivity class '${klass}', which is not registered ` +
|
|
115
|
+
'on this thread. Policies are per-thread: call registerPolicy() in the receiving ' +
|
|
116
|
+
`thread's own bootstrap. Registered here: ${registered.join(', ')}.`);
|
|
117
|
+
this.key = key;
|
|
118
|
+
this.klass = klass;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
exports.UnregisteredClassError = UnregisteredClassError;
|
|
122
|
+
/**
|
|
123
|
+
* Raised when a payload built under an audited context is consumed with no
|
|
124
|
+
* audit hook on this side.
|
|
125
|
+
*
|
|
126
|
+
* A refusal rather than a warning. A warning from a worker is a line on the
|
|
127
|
+
* parent's stderr that nothing reads, and the condition it would report is a
|
|
128
|
+
* security control the sender asked for being dropped in silence.
|
|
129
|
+
*/
|
|
130
|
+
class UnauditedWorkerError extends errors_js_1.SensitiveStringError {
|
|
131
|
+
name = 'UnauditedWorkerError';
|
|
132
|
+
code = 'unaudited-worker';
|
|
133
|
+
constructor() {
|
|
134
|
+
super('Worker payload was built under an audited context, and the audit hook cannot cross a ' +
|
|
135
|
+
'thread boundary. Pass auditReveal to fromWorkerPayload(), consume it inside a ' +
|
|
136
|
+
'withRevealContext() that carries one, or pass allowUnaudited: true to accept that ' +
|
|
137
|
+
'reveals in this thread will go unrecorded.');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
exports.UnauditedWorkerError = UnauditedWorkerError;
|
|
141
|
+
/**
|
|
142
|
+
* Raised when `data` or the context's `tags` would not survive the transport.
|
|
143
|
+
*
|
|
144
|
+
* The message names the path of the offending entry and never its value. A
|
|
145
|
+
* `DataCloneError` from the runtime quotes the source text of a function it
|
|
146
|
+
* could not clone, so that message is discarded rather than wrapped.
|
|
147
|
+
*/
|
|
148
|
+
class UnportableDataError extends errors_js_1.SensitiveStringError {
|
|
149
|
+
path;
|
|
150
|
+
transport;
|
|
151
|
+
name = 'UnportableDataError';
|
|
152
|
+
code = 'unportable-data';
|
|
153
|
+
constructor(
|
|
154
|
+
/** Where in the payload the entry sits, such as `data.batch.onDone`. */
|
|
155
|
+
path, transport, detail) {
|
|
156
|
+
super(`Worker payload cannot carry ${path} over the '${transport}' transport: ${detail}`);
|
|
157
|
+
this.path = path;
|
|
158
|
+
this.transport = transport;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
exports.UnportableDataError = UnportableDataError;
|
|
162
|
+
/**
|
|
163
|
+
* Raised when a value carries a constraint no other isolate can share.
|
|
164
|
+
*
|
|
165
|
+
* Two things qualify. A reveal budget is a counter shared by reference between
|
|
166
|
+
* a value and its derivatives; a thread has no reference to share, and the wire
|
|
167
|
+
* format resets counters, so a handoff would hand every worker a fresh budget.
|
|
168
|
+
* A custom environment restriction is a function, which is not data and cannot
|
|
169
|
+
* be cloned into another isolate at all, so a handoff would leave the receiving
|
|
170
|
+
* thread enforcing the declarative half of a restriction and silently not the
|
|
171
|
+
* rest.
|
|
172
|
+
*
|
|
173
|
+
* Both refusals are the rule that a derivative carries its parent's constraint
|
|
174
|
+
* or refuses to exist, applied to a transport.
|
|
175
|
+
*/
|
|
176
|
+
class UnshareableConstraintError extends errors_js_1.SensitiveStringError {
|
|
177
|
+
key;
|
|
178
|
+
constraints;
|
|
179
|
+
name = 'UnshareableConstraintError';
|
|
180
|
+
code = 'unshareable-constraint';
|
|
181
|
+
constructor(key, constraints) {
|
|
182
|
+
const limits = constraints.filter((name) => name !== 'restrictions');
|
|
183
|
+
const carried = [];
|
|
184
|
+
if (limits.length !== 0) {
|
|
185
|
+
carried.push(`${limits.join(' and ')}, a reveal limit that another thread cannot share: a handoff ` +
|
|
186
|
+
'would give the receiving thread a fresh budget');
|
|
187
|
+
}
|
|
188
|
+
if (limits.length !== constraints.length) {
|
|
189
|
+
carried.push('a custom restriction, which is a function rather than data: a handoff would leave the ' +
|
|
190
|
+
'receiving thread enforcing only the declarative half of it');
|
|
191
|
+
}
|
|
192
|
+
super(`Worker payload value '${key}' carries ${carried.join('; and ')}. The value is refused ` +
|
|
193
|
+
'rather than the constraint silently reset.');
|
|
194
|
+
this.key = key;
|
|
195
|
+
this.constraints = constraints;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
exports.UnshareableConstraintError = UnshareableConstraintError;
|
|
199
|
+
/**
|
|
200
|
+
* Describe a value without disclosing it.
|
|
201
|
+
*
|
|
202
|
+
* Only the kind is reported, never any content: what arrives here may be a
|
|
203
|
+
* secret handed to the wrong function.
|
|
204
|
+
*/
|
|
205
|
+
function describeKind(value) {
|
|
206
|
+
if (value === null) {
|
|
207
|
+
return 'null';
|
|
208
|
+
}
|
|
209
|
+
if (Array.isArray(value)) {
|
|
210
|
+
return 'an array';
|
|
211
|
+
}
|
|
212
|
+
if (typeof value !== 'object') {
|
|
213
|
+
return `a ${typeof value}`;
|
|
214
|
+
}
|
|
215
|
+
const tag = (0, probe_js_1.probeTag)(value).slice(8, -1);
|
|
216
|
+
return tag === 'Object' ? 'an object' : `a ${tag}`;
|
|
217
|
+
}
|
|
218
|
+
function isPlainRecord(value) {
|
|
219
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
220
|
+
}
|
|
221
|
+
/** A guard rather than a bare `instanceof`, which narrows to `SensitiveString<any>`. */
|
|
222
|
+
function isInstance(value) {
|
|
223
|
+
return value instanceof sensitive_string_js_1.SensitiveString;
|
|
224
|
+
}
|
|
225
|
+
/** The audit field for a destination, from whatever the caller named it with. */
|
|
226
|
+
function describeWorker(worker) {
|
|
227
|
+
if (worker === undefined) {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
if (typeof worker === 'string') {
|
|
231
|
+
return worker;
|
|
232
|
+
}
|
|
233
|
+
if (worker instanceof URL) {
|
|
234
|
+
return worker.href;
|
|
235
|
+
}
|
|
236
|
+
throw new TypeError(`toWorkerPayload: worker must be a string or a URL, received ${describeKind(worker)}`);
|
|
237
|
+
}
|
|
238
|
+
function requireTransport(transport) {
|
|
239
|
+
if (transport === undefined) {
|
|
240
|
+
return 'clone';
|
|
241
|
+
}
|
|
242
|
+
if (transport === 'clone' || transport === 'json') {
|
|
243
|
+
return transport;
|
|
244
|
+
}
|
|
245
|
+
throw new TypeError(`toWorkerPayload: transport must be 'clone' or 'json', received ${describeKind(transport)}`);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The entries of `values`, each checked to be an instance.
|
|
249
|
+
*
|
|
250
|
+
* A non-instance is refused by name: it is the value the caller meant to
|
|
251
|
+
* protect, or non-sensitive data that belongs in `options.data`, and either way
|
|
252
|
+
* a payload that silently carried it would be the accident this module exists
|
|
253
|
+
* to prevent.
|
|
254
|
+
*/
|
|
255
|
+
function requireValues(values) {
|
|
256
|
+
if (!isPlainRecord(values)) {
|
|
257
|
+
throw new TypeError('toWorkerPayload: values must be a plain object of SensitiveString instances, received ' +
|
|
258
|
+
describeKind(values));
|
|
259
|
+
}
|
|
260
|
+
const entries = [];
|
|
261
|
+
for (const key of Object.keys(values)) {
|
|
262
|
+
const value = values[key];
|
|
263
|
+
if (!isInstance(value)) {
|
|
264
|
+
throw new TypeError(`toWorkerPayload: values.${key} is ${describeKind(value)}, not a SensitiveString. ` +
|
|
265
|
+
'Non-sensitive data belongs in options.data.');
|
|
266
|
+
}
|
|
267
|
+
entries.push([key, value]);
|
|
268
|
+
}
|
|
269
|
+
return entries;
|
|
270
|
+
}
|
|
271
|
+
/** The three fields of a context that can cross, and nothing else. */
|
|
272
|
+
function portableContext(context) {
|
|
273
|
+
const portable = {
|
|
274
|
+
name: context.name,
|
|
275
|
+
};
|
|
276
|
+
if (context.reason !== undefined) {
|
|
277
|
+
portable.reason = context.reason;
|
|
278
|
+
}
|
|
279
|
+
if (context.tags !== undefined) {
|
|
280
|
+
portable.tags = context.tags;
|
|
281
|
+
}
|
|
282
|
+
return portable;
|
|
283
|
+
}
|
|
284
|
+
function isCloneable(value) {
|
|
285
|
+
try {
|
|
286
|
+
structuredClone(value);
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The children of a container, each with the path it will be reported under.
|
|
295
|
+
*
|
|
296
|
+
* Map and Set entries are numbered rather than keyed, because a Map key is a
|
|
297
|
+
* value and could be a secret.
|
|
298
|
+
*/
|
|
299
|
+
function childrenOf(value, path) {
|
|
300
|
+
// Iteration is the collection's own code, and a Proxy in front of a built-in
|
|
301
|
+
// is free to throw from it. A refusal answers "no children", which leaves
|
|
302
|
+
// the caller reporting the container itself: this runs while building an
|
|
303
|
+
// error message, and an object that will not be read must not replace that
|
|
304
|
+
// message with an exception of its own.
|
|
305
|
+
if (Array.isArray(value)) {
|
|
306
|
+
return ((0, probe_js_1.probeBuiltin)(() => value.map((item, index) => [`${path}[${index}]`, item])) ?? []);
|
|
307
|
+
}
|
|
308
|
+
if (value instanceof Map) {
|
|
309
|
+
return ((0, probe_js_1.probeBuiltin)(() => {
|
|
310
|
+
const children = [];
|
|
311
|
+
let index = 0;
|
|
312
|
+
for (const [key, entry] of value) {
|
|
313
|
+
children.push([`${path}[entry ${index}].key`, key], [`${path}[entry ${index}].value`, entry]);
|
|
314
|
+
index++;
|
|
315
|
+
}
|
|
316
|
+
return children;
|
|
317
|
+
}) ?? []);
|
|
318
|
+
}
|
|
319
|
+
if (value instanceof Set) {
|
|
320
|
+
return ((0, probe_js_1.probeBuiltin)(() => Array.from(value, (entry, index) => [`${path}[entry ${index}]`, entry])) ?? []);
|
|
321
|
+
}
|
|
322
|
+
return ((0, probe_js_1.probeEntries)(value) ?? []).map(([key, entry]) => [`${path}.${key}`, entry]);
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* The path of the entry structured clone refuses, given a value it refuses.
|
|
326
|
+
*
|
|
327
|
+
* Descends into whichever child also refuses, and reports the node whose
|
|
328
|
+
* children all clone, which is the offending leaf: a function, a symbol, or
|
|
329
|
+
* an object the algorithm has no serialization for.
|
|
330
|
+
*/
|
|
331
|
+
function locateCloneFailure(value, path, seen) {
|
|
332
|
+
if (typeof value === 'function') {
|
|
333
|
+
return { path, detail: 'a function cannot be cloned' };
|
|
334
|
+
}
|
|
335
|
+
if (typeof value === 'symbol') {
|
|
336
|
+
return { path, detail: 'a symbol cannot be cloned' };
|
|
337
|
+
}
|
|
338
|
+
if (value !== null && typeof value === 'object' && !seen.has(value)) {
|
|
339
|
+
seen.add(value);
|
|
340
|
+
for (const [childPath, child] of childrenOf(value, path)) {
|
|
341
|
+
if (!isCloneable(child)) {
|
|
342
|
+
return locateCloneFailure(child, childPath, seen);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return { path, detail: `${describeKind(value)} cannot be cloned` };
|
|
347
|
+
}
|
|
348
|
+
function findCloneFailure(value, path) {
|
|
349
|
+
return isCloneable(value) ? undefined : locateCloneFailure(value, path, new Set());
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Built-ins JSON does not round-trip, with what each arrives as.
|
|
353
|
+
*
|
|
354
|
+
* Keyed by `Object.prototype.toString` tag, so a `Date` from another realm is
|
|
355
|
+
* still a Date.
|
|
356
|
+
*/
|
|
357
|
+
const JSON_LOSSY_TAGS = new Map([
|
|
358
|
+
['Date', 'a string'],
|
|
359
|
+
['RegExp', 'an empty object'],
|
|
360
|
+
['Map', 'an empty object'],
|
|
361
|
+
['Set', 'an empty object'],
|
|
362
|
+
['WeakMap', 'an empty object'],
|
|
363
|
+
['WeakSet', 'an empty object'],
|
|
364
|
+
['Error', 'an empty object'],
|
|
365
|
+
['Promise', 'an empty object'],
|
|
366
|
+
['ArrayBuffer', 'an empty object'],
|
|
367
|
+
['DataView', 'an empty object'],
|
|
368
|
+
]);
|
|
369
|
+
/**
|
|
370
|
+
* The first entry JSON would lose or change, compared structurally against
|
|
371
|
+
* the input rather than by a round trip alone: a round trip succeeds on a
|
|
372
|
+
* `Date` and hands back a string, which is exactly the loss a caller is least
|
|
373
|
+
* likely to notice.
|
|
374
|
+
*
|
|
375
|
+
* Two sets, not one. `onPath` holds the current path from the root and is
|
|
376
|
+
* what detects a cycle, so it has to be unwound on the way back up; `cleared`
|
|
377
|
+
* remembers every node already found lossless and is never unwound. With only
|
|
378
|
+
* the first, a node reachable by several paths is re-walked once per path,
|
|
379
|
+
* which is exponential on a shared subtree: a 24-deep diamond took 16 seconds
|
|
380
|
+
* before `cleared` existed, against under a millisecond after.
|
|
381
|
+
*/
|
|
382
|
+
function findJsonLoss(value, path, onPath, cleared) {
|
|
383
|
+
switch (typeof value) {
|
|
384
|
+
case 'undefined':
|
|
385
|
+
return { path, detail: 'an undefined value is dropped by JSON' };
|
|
386
|
+
case 'function':
|
|
387
|
+
return { path, detail: 'a function is dropped by JSON' };
|
|
388
|
+
case 'symbol':
|
|
389
|
+
return { path, detail: 'a symbol is dropped by JSON' };
|
|
390
|
+
case 'bigint':
|
|
391
|
+
return { path, detail: 'a BigInt makes JSON.stringify throw' };
|
|
392
|
+
case 'number':
|
|
393
|
+
return Number.isFinite(value)
|
|
394
|
+
? undefined
|
|
395
|
+
: { path, detail: 'a non-finite number becomes null in JSON' };
|
|
396
|
+
case 'string':
|
|
397
|
+
case 'boolean':
|
|
398
|
+
return undefined;
|
|
399
|
+
case 'object':
|
|
400
|
+
break;
|
|
401
|
+
}
|
|
402
|
+
if (value === null) {
|
|
403
|
+
return undefined;
|
|
404
|
+
}
|
|
405
|
+
if (onPath.has(value)) {
|
|
406
|
+
return { path, detail: 'a circular reference makes JSON.stringify throw' };
|
|
407
|
+
}
|
|
408
|
+
// Already walked, by another path, and found lossless. A DAG is not a cycle.
|
|
409
|
+
if (cleared.has(value)) {
|
|
410
|
+
return undefined;
|
|
411
|
+
}
|
|
412
|
+
onPath.add(value);
|
|
413
|
+
try {
|
|
414
|
+
if (Array.isArray(value)) {
|
|
415
|
+
for (const [childPath, child] of childrenOf(value, path)) {
|
|
416
|
+
const loss = findJsonLoss(child, childPath, onPath, cleared);
|
|
417
|
+
if (loss !== undefined) {
|
|
418
|
+
return loss;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
cleared.add(value);
|
|
422
|
+
return undefined;
|
|
423
|
+
}
|
|
424
|
+
if (ArrayBuffer.isView(value)) {
|
|
425
|
+
return { path, detail: 'a typed array becomes an object of indexed keys in JSON' };
|
|
426
|
+
}
|
|
427
|
+
const tag = (0, probe_js_1.probeTag)(value).slice(8, -1);
|
|
428
|
+
const arrival = JSON_LOSSY_TAGS.get(tag);
|
|
429
|
+
if (arrival !== undefined) {
|
|
430
|
+
return { path, detail: `a ${tag} arrives as ${arrival} over JSON` };
|
|
431
|
+
}
|
|
432
|
+
// A toJSON rewrites the shape on the way out and nothing rewrites it back.
|
|
433
|
+
// Whether the rewrite is a loss depends on what it returns, and the
|
|
434
|
+
// conservative answer avoids running caller code to find out.
|
|
435
|
+
if (typeof (0, probe_js_1.probeProperty)(value, 'toJSON') === 'function') {
|
|
436
|
+
return {
|
|
437
|
+
path,
|
|
438
|
+
detail: 'its toJSON() changes its shape in JSON, and the receiver gets the changed shape',
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
for (const [childPath, child] of childrenOf(value, path)) {
|
|
442
|
+
const loss = findJsonLoss(child, childPath, onPath, cleared);
|
|
443
|
+
if (loss !== undefined) {
|
|
444
|
+
return loss;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
cleared.add(value);
|
|
448
|
+
return undefined;
|
|
449
|
+
}
|
|
450
|
+
finally {
|
|
451
|
+
onPath.delete(value);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Refuse a passthrough that carries a protected value, at any depth.
|
|
456
|
+
*
|
|
457
|
+
* An instance would degrade to `{ klass, label }` in silence, and a wire
|
|
458
|
+
* object would carry the raw value somewhere `fromWorkerPayload` does not
|
|
459
|
+
* clear. `values` is the one place a protected value belongs, and it is the
|
|
460
|
+
* only place consumption reaches.
|
|
461
|
+
*/
|
|
462
|
+
function requireNoSensitiveValue(value, path, transport) {
|
|
463
|
+
if (!(0, redact_js_1.containsSensitive)(value)) {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const classes = Array.from((0, redact_js_1.sensitiveClassesIn)(value));
|
|
467
|
+
const named = classes.length === 0 ? 'in an object that could not be read' : classes.join(', ');
|
|
468
|
+
throw new UnportableDataError(path, transport, `it holds a sensitive value (${named}), which would arrive as { klass, label } with no ` +
|
|
469
|
+
'value, or would carry the raw value past consumption. Put it in values instead.');
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Refuse a value that would not survive the transport, naming where.
|
|
473
|
+
*
|
|
474
|
+
* The runtime's own `DataCloneError` is never consulted for its message, only
|
|
475
|
+
* for its occurrence: that message embeds the source text of a function it
|
|
476
|
+
* could not clone, and a function's body can hold a literal.
|
|
477
|
+
*/
|
|
478
|
+
function requirePortable(value, path, transport) {
|
|
479
|
+
const failure = transport === 'json'
|
|
480
|
+
? findJsonLoss(value, path, new Set(), new Set())
|
|
481
|
+
: findCloneFailure(value, path);
|
|
482
|
+
if (failure !== undefined) {
|
|
483
|
+
throw new UnportableDataError(failure.path, transport, failure.detail);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Build a payload that carries sensitive values across a thread or process
|
|
488
|
+
* boundary with their class, label, and deadline intact.
|
|
489
|
+
*
|
|
490
|
+
* ⚠️ RETURNS RAW VALUES, in the wire format, one per entry. Building the
|
|
491
|
+
* payload is a reveal of each value: it goes through the same gate as
|
|
492
|
+
* `reveal()`, so an expired, revoked, or policy-denied value refuses here, on
|
|
493
|
+
* the sending side, and each value produces one audit record with
|
|
494
|
+
* `operation: 'worker-handoff'`.
|
|
495
|
+
*
|
|
496
|
+
* The checks that do not need the value run first, over every entry: an
|
|
497
|
+
* unshareable constraint, a protected value in `data` or `tags`, and anything
|
|
498
|
+
* the transport would lose. Failing one of those reveals nothing and records
|
|
499
|
+
* nothing.
|
|
500
|
+
*
|
|
501
|
+
* The gate's own refusals cannot be hoisted that way, because deciding them
|
|
502
|
+
* means reading. Values are read in key order, so an expired, revoked or
|
|
503
|
+
* policy-denied value at key *n* leaves the values before it revealed and
|
|
504
|
+
* audited, with the payload discarded. That is `serialize()`'s behaviour in a
|
|
505
|
+
* loop, and it is why the audit record names the key.
|
|
506
|
+
*
|
|
507
|
+
* @param values - The instances to carry, keyed however the receiver expects.
|
|
508
|
+
* @param options - Destination, context, non-sensitive data, and transport.
|
|
509
|
+
* @throws TypeError If `values` is not a plain object of instances.
|
|
510
|
+
* @throws UnshareableConstraintError If a value carries a reveal limit or a custom environment restriction.
|
|
511
|
+
* @throws UnportableDataError If `data` holds a sensitive value, or `data` or the
|
|
512
|
+
* context's `tags` would not survive the transport.
|
|
513
|
+
* @throws ExpiredSensitiveValueError, RevokedSensitiveValueError, or whatever
|
|
514
|
+
* the class policy throws, from the gate, exactly as `reveal()` would.
|
|
515
|
+
*
|
|
516
|
+
* @example
|
|
517
|
+
* ```ts
|
|
518
|
+
* const worker = new Worker(workerFile, {
|
|
519
|
+
* workerData: toWorkerPayload({ token }, { worker: workerFile, data: { batchSize: 100 } }),
|
|
520
|
+
* });
|
|
521
|
+
* ```
|
|
522
|
+
*
|
|
523
|
+
* @remarks
|
|
524
|
+
* Pass the result as an expression, as above, rather than binding it: the
|
|
525
|
+
* sender's copy holds plaintext until it is unreachable. For a long-lived
|
|
526
|
+
* worker, `postMessage` after start keeps that window shorter than
|
|
527
|
+
* `workerData` does, because a message is garbage once its handler returns
|
|
528
|
+
* where `workerData` lives as long as the thread.
|
|
529
|
+
*
|
|
530
|
+
* The receiving thread's heap holds the plaintext once it consumes the
|
|
531
|
+
* payload. `fromWorkerPayload()` deletes the raw values from the payload
|
|
532
|
+
* object, which shortens the accident window; it does not erase a string from
|
|
533
|
+
* memory, which nothing in JavaScript can.
|
|
534
|
+
*
|
|
535
|
+
* A value that crosses leaves this side's revocation reach entirely, which is
|
|
536
|
+
* the part of the boundary most easily read backwards. Instance `revoke()` is
|
|
537
|
+
* per copy; `revokeByLabel()` and `revokeByPattern()` act on module state, and
|
|
538
|
+
* module state is per isolate; a `revocationRegistry` is a function table, so
|
|
539
|
+
* it does not clone, and the receiving side cannot bind one to a rebuilt value
|
|
540
|
+
* because `deserialize()` takes no options. What still reaches the copy is the
|
|
541
|
+
* worker's own label list, matched on the label that crossed, so a worker that
|
|
542
|
+
* must honour revocation keeps one. Revoking before the handoff is not a way
|
|
543
|
+
* round it either: the gate refuses to read a revoked value, so there is no
|
|
544
|
+
* payload. Measured in `__tests__/worker-boundary.test.ts` against a real
|
|
545
|
+
* thread.
|
|
546
|
+
*/
|
|
547
|
+
function toWorkerPayload(values, options = {}) {
|
|
548
|
+
const entries = requireValues(values);
|
|
549
|
+
const transport = requireTransport(options.transport);
|
|
550
|
+
const worker = describeWorker(options.worker);
|
|
551
|
+
const context = options.context ?? (0, context_js_1.getCurrentRevealContext)() ?? undefined;
|
|
552
|
+
const portable = context === undefined ? undefined : portableContext(context);
|
|
553
|
+
const audited = typeof context?.auditReveal === 'function';
|
|
554
|
+
// Everything that can refuse does so here, ahead of the reads below. A read
|
|
555
|
+
// is a reveal, and a refusal is not: a payload that fails validation has
|
|
556
|
+
// handed nothing out and must not be recorded as if it had.
|
|
557
|
+
for (const [key, value] of entries) {
|
|
558
|
+
const constraints = (0, sensitive_string_js_1.unshareableConstraints)(value);
|
|
559
|
+
if (constraints.length !== 0) {
|
|
560
|
+
throw new UnshareableConstraintError(key, constraints);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
// Both passthroughs get the same two checks. `tags` used to get only the
|
|
564
|
+
// portability one, which let a wire object ride across inside the context
|
|
565
|
+
// and, because consumption only clears `values`, stay in the payload after
|
|
566
|
+
// it had been consumed. A raw value has exactly one place in a payload.
|
|
567
|
+
if (options.data !== undefined) {
|
|
568
|
+
requireNoSensitiveValue(options.data, 'data', transport);
|
|
569
|
+
requirePortable(options.data, 'data', transport);
|
|
570
|
+
}
|
|
571
|
+
if (portable?.tags !== undefined) {
|
|
572
|
+
requireNoSensitiveValue(portable.tags, 'context.tags', transport);
|
|
573
|
+
requirePortable(portable.tags, 'context.tags', transport);
|
|
574
|
+
}
|
|
575
|
+
const serialized = {};
|
|
576
|
+
for (const [key, value] of entries) {
|
|
577
|
+
const details = Object.freeze({
|
|
578
|
+
operation: 'worker-handoff',
|
|
579
|
+
worker,
|
|
580
|
+
key,
|
|
581
|
+
auditHookDropped: audited,
|
|
582
|
+
});
|
|
583
|
+
(0, own_property_js_1.assignOwn)(serialized, key, (0, sensitive_string_js_1.serializeSensitiveString)(value, context, details));
|
|
584
|
+
}
|
|
585
|
+
const payload = {
|
|
586
|
+
__sensitiveWorkerPayload: 1,
|
|
587
|
+
values: serialized,
|
|
588
|
+
audited,
|
|
589
|
+
};
|
|
590
|
+
if (portable !== undefined) {
|
|
591
|
+
payload.context = portable;
|
|
592
|
+
}
|
|
593
|
+
if (options.data !== undefined) {
|
|
594
|
+
payload.data = options.data;
|
|
595
|
+
}
|
|
596
|
+
return payload;
|
|
597
|
+
}
|
|
598
|
+
function requirePayload(payload) {
|
|
599
|
+
if (!isPlainRecord(payload)) {
|
|
600
|
+
throw new MalformedWorkerPayloadError(`expected the object toWorkerPayload() returns, received ${describeKind(payload)}`);
|
|
601
|
+
}
|
|
602
|
+
if (payload[PAYLOAD_MARKER] !== 1) {
|
|
603
|
+
throw new MalformedWorkerPayloadError(`the object carries no ${PAYLOAD_MARKER} marker. Pass the object toWorkerPayload() ` +
|
|
604
|
+
'returned, not one assembled by hand.');
|
|
605
|
+
}
|
|
606
|
+
return payload;
|
|
607
|
+
}
|
|
608
|
+
function requireValueRecord(values) {
|
|
609
|
+
if (!isPlainRecord(values)) {
|
|
610
|
+
throw new MalformedWorkerPayloadError(`values must be an object, received ${describeKind(values)}`);
|
|
611
|
+
}
|
|
612
|
+
return values;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* The parts of a wire object that decide whether it can be rebuilt here.
|
|
616
|
+
*
|
|
617
|
+
* `deserialize()` checks the rest, and its own errors are wrapped so they name
|
|
618
|
+
* the key. The class check is separate because its failure has its own error
|
|
619
|
+
* and its own instruction.
|
|
620
|
+
*/
|
|
621
|
+
function requireWireObject(entry, key) {
|
|
622
|
+
if (!isPlainRecord(entry)) {
|
|
623
|
+
throw new MalformedWorkerPayloadError(`values.${key} is ${describeKind(entry)}, not a serialized sensitive value`);
|
|
624
|
+
}
|
|
625
|
+
if (entry['__sensitive'] !== true) {
|
|
626
|
+
throw new MalformedWorkerPayloadError(`values.${key} carries no __sensitive marker`);
|
|
627
|
+
}
|
|
628
|
+
if (typeof entry['value'] !== 'string') {
|
|
629
|
+
throw new MalformedWorkerPayloadError(`values.${key} has ${describeKind(entry['value'])} where its string value belongs`);
|
|
630
|
+
}
|
|
631
|
+
const klass = entry['klass'];
|
|
632
|
+
if (typeof klass !== 'string') {
|
|
633
|
+
throw new MalformedWorkerPayloadError(`values.${key} has ${describeKind(klass)} where its sensitivity class belongs`);
|
|
634
|
+
}
|
|
635
|
+
if (!(0, policy_js_1.hasPolicy)(klass)) {
|
|
636
|
+
throw new UnregisteredClassError(key, klass, (0, policy_js_1.getRegisteredClasses)());
|
|
637
|
+
}
|
|
638
|
+
return entry;
|
|
639
|
+
}
|
|
640
|
+
function requireContext(context) {
|
|
641
|
+
if (context === undefined) {
|
|
642
|
+
return undefined;
|
|
643
|
+
}
|
|
644
|
+
if (!isPlainRecord(context) || typeof context['name'] !== 'string') {
|
|
645
|
+
throw new MalformedWorkerPayloadError('context must be an object with a string name');
|
|
646
|
+
}
|
|
647
|
+
const reason = context['reason'];
|
|
648
|
+
const tags = context['tags'];
|
|
649
|
+
if (reason !== undefined && typeof reason !== 'string') {
|
|
650
|
+
throw new MalformedWorkerPayloadError('context.reason must be a string when present');
|
|
651
|
+
}
|
|
652
|
+
if (tags !== undefined && !isPlainRecord(tags)) {
|
|
653
|
+
throw new MalformedWorkerPayloadError('context.tags must be an object when present');
|
|
654
|
+
}
|
|
655
|
+
const portable = {
|
|
656
|
+
name: context['name'],
|
|
657
|
+
};
|
|
658
|
+
if (reason !== undefined) {
|
|
659
|
+
portable.reason = reason;
|
|
660
|
+
}
|
|
661
|
+
if (tags !== undefined) {
|
|
662
|
+
portable.tags = tags;
|
|
663
|
+
}
|
|
664
|
+
return portable;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Delete the raw values from the payload and mark it consumed.
|
|
668
|
+
*
|
|
669
|
+
* Deleting rather than overwriting is deliberate. A sentinel would leave a
|
|
670
|
+
* payload that still deserializes, into an instance that wraps the sentinel
|
|
671
|
+
* and looks valid. The `__sensitive` and `klass` fields stay, so a consumed
|
|
672
|
+
* payload still renders as a redaction under the marker-aware walks.
|
|
673
|
+
*
|
|
674
|
+
* `workerData` is one mutable object shared by every module in the thread, so
|
|
675
|
+
* this deletion is thread-wide *within that thread*: a later
|
|
676
|
+
* `console.log(workerData)` or a crash handler serializing it no longer reads
|
|
677
|
+
* the values. It does not reach back to the sender, whose own object was
|
|
678
|
+
* cloned on the way out, and it does not erase the string from the heap.
|
|
679
|
+
*
|
|
680
|
+
* Every write is best-effort. This is hardening applied after the instances
|
|
681
|
+
* have already been rebuilt, so a frozen payload must not turn a successful
|
|
682
|
+
* consume into a throw that leaves the caller with no values *and* the
|
|
683
|
+
* plaintext still in place, which is strictly worse than either alone.
|
|
684
|
+
* `consumed` reports whether the payload can be relied on to refuse a second
|
|
685
|
+
* call.
|
|
686
|
+
*/
|
|
687
|
+
function consume(payload, values) {
|
|
688
|
+
for (const key of Object.keys(values)) {
|
|
689
|
+
const entry = values[key];
|
|
690
|
+
if (isPlainRecord(entry)) {
|
|
691
|
+
try {
|
|
692
|
+
delete entry['value'];
|
|
693
|
+
}
|
|
694
|
+
catch {
|
|
695
|
+
// A frozen or sealed entry keeps its value. Nothing else to try: the
|
|
696
|
+
// caller froze it, and the rebuild has already succeeded.
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
try {
|
|
701
|
+
payload['consumed'] = true;
|
|
702
|
+
return payload['consumed'] === true;
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
return false;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* This side's audit hook: the one given, or the ambient one forwarded.
|
|
710
|
+
*
|
|
711
|
+
* Forwarded rather than copied, so the ambient context stays the receiver of
|
|
712
|
+
* its own method. And forwarded rather than left implicit: the returned context
|
|
713
|
+
* is meant to be installed, and installing a context without a hook would
|
|
714
|
+
* replace the ambient one that has it.
|
|
715
|
+
*/
|
|
716
|
+
function resolveAuditHook(given, ambient) {
|
|
717
|
+
if (given !== undefined) {
|
|
718
|
+
return given;
|
|
719
|
+
}
|
|
720
|
+
if (ambient?.auditReveal === undefined) {
|
|
721
|
+
return undefined;
|
|
722
|
+
}
|
|
723
|
+
return (value, details, context) => ambient.auditReveal?.(value, details, context);
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Rebuild the instances a payload carries, and take the raw values out of it.
|
|
727
|
+
*
|
|
728
|
+
* Validation runs in full before anything is rebuilt, and rebuilding runs in
|
|
729
|
+
* full before the payload is consumed, so a call that throws returns no
|
|
730
|
+
* partial result and, with one exception, leaves the payload intact for a
|
|
731
|
+
* corrected retry. The exception is a value that expired between build and
|
|
732
|
+
* consume: that cannot be fixed by retrying, so the payload is consumed before
|
|
733
|
+
* the throw rather than left holding plaintext for the life of the thread.
|
|
734
|
+
*
|
|
735
|
+
* @param payload - What arrived: `workerData`, a message, or an IPC message.
|
|
736
|
+
* @param options - This side's audit hook, and what to require.
|
|
737
|
+
* @throws MalformedWorkerPayloadError If `payload` is not what `toWorkerPayload()` returns.
|
|
738
|
+
* @throws ConsumedWorkerPayloadError If the payload was consumed already.
|
|
739
|
+
* @throws MissingWorkerValueError If a key in `require` is absent.
|
|
740
|
+
* @throws UnregisteredClassError If a value's class is not registered on this thread.
|
|
741
|
+
* @throws UnauditedWorkerError If the payload is audited and no hook is available here.
|
|
742
|
+
* @throws ExpiredSensitiveValueError If a value expired in transit, naming its key.
|
|
743
|
+
*
|
|
744
|
+
* @example
|
|
745
|
+
* ```ts
|
|
746
|
+
* const { values, context } = fromWorkerPayload<{ token: SensitiveString<'credential'> }>(
|
|
747
|
+
* workerData,
|
|
748
|
+
* { auditReveal: (value, details) => log.info('reveal', { klass: value.klass, ...details }) },
|
|
749
|
+
* );
|
|
750
|
+
* withRevealContext(context, () => callApi(values.token.reveal()));
|
|
751
|
+
* ```
|
|
752
|
+
*
|
|
753
|
+
* @remarks
|
|
754
|
+
* The type parameter is a claim about names and classes that the runtime
|
|
755
|
+
* cannot check, as with `deserialize()`. `require` is what makes the names
|
|
756
|
+
* enforceable.
|
|
757
|
+
*
|
|
758
|
+
* After this returns, the payload object holds no raw value and a second call
|
|
759
|
+
* on it throws. A heap snapshot or a debugger still sees the string, which is
|
|
760
|
+
* the same limitation the library has everywhere.
|
|
761
|
+
*/
|
|
762
|
+
function fromWorkerPayload(payload, options = {}) {
|
|
763
|
+
const container = requirePayload(payload);
|
|
764
|
+
if (container['consumed'] === true) {
|
|
765
|
+
throw new ConsumedWorkerPayloadError();
|
|
766
|
+
}
|
|
767
|
+
const values = requireValueRecord(container['values']);
|
|
768
|
+
for (const key of options.require ?? []) {
|
|
769
|
+
if (!Object.hasOwn(values, key)) {
|
|
770
|
+
throw new MissingWorkerValueError(key);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
const entries = Object.keys(values).map((key) => [
|
|
774
|
+
key,
|
|
775
|
+
requireWireObject(values[key], key),
|
|
776
|
+
]);
|
|
777
|
+
const hook = resolveAuditHook(options.auditReveal, (0, context_js_1.getCurrentRevealContext)());
|
|
778
|
+
if (container['audited'] === true && hook === undefined && options.allowUnaudited !== true) {
|
|
779
|
+
throw new UnauditedWorkerError();
|
|
780
|
+
}
|
|
781
|
+
const carried = requireContext(container['context']);
|
|
782
|
+
const rebuilt = {};
|
|
783
|
+
for (const [key, wire] of entries) {
|
|
784
|
+
let value;
|
|
785
|
+
try {
|
|
786
|
+
value = sensitive_string_js_1.SensitiveString.deserialize(wire);
|
|
787
|
+
}
|
|
788
|
+
catch (error) {
|
|
789
|
+
// `deserialize()` describes the field, never the value, so its message
|
|
790
|
+
// is safe to carry; what it lacks is the key.
|
|
791
|
+
throw new MalformedWorkerPayloadError(`values.${key}: ${error instanceof Error ? error.message : 'could not be deserialized'}`);
|
|
792
|
+
}
|
|
793
|
+
// A value with milliseconds left when the payload was built can be dead
|
|
794
|
+
// by the time a thread has started. Refused here, where the cause is
|
|
795
|
+
// visible, rather than handed back to throw from inside application code.
|
|
796
|
+
if (value.isExpired()) {
|
|
797
|
+
const deadline = value.expiresAt ?? new Date(NaN);
|
|
798
|
+
if (options.keepPayload !== true) {
|
|
799
|
+
consume(container, values);
|
|
800
|
+
}
|
|
801
|
+
throw new ttl_js_1.ExpiredSensitiveValueError(deadline, new Date(), value.label, key);
|
|
802
|
+
}
|
|
803
|
+
(0, own_property_js_1.assignOwn)(rebuilt, key, value);
|
|
804
|
+
}
|
|
805
|
+
if (options.keepPayload !== true) {
|
|
806
|
+
consume(container, values);
|
|
807
|
+
}
|
|
808
|
+
const context = { ...(carried ?? { name: 'worker' }) };
|
|
809
|
+
if (hook !== undefined) {
|
|
810
|
+
context.auditReveal = hook;
|
|
811
|
+
}
|
|
812
|
+
return { values: rebuilt, context, data: container['data'] };
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* `fromWorkerPayload()` followed by `withRevealContext()`.
|
|
816
|
+
*
|
|
817
|
+
* The two-call form has a failure mode that is invisible in review:
|
|
818
|
+
* destructure `values`, forget `context`, and every reveal in the worker runs
|
|
819
|
+
* unaudited while the code still reads as if the context were handled. This
|
|
820
|
+
* form cannot express that mistake.
|
|
821
|
+
*
|
|
822
|
+
* Returns whatever `fn` returns, a Promise included, matching
|
|
823
|
+
* `withRevealContext()`.
|
|
824
|
+
*
|
|
825
|
+
* @typeParam T - The values the payload is claimed to carry. Unverifiable at
|
|
826
|
+
* runtime, as with `deserialize()`; pass `require` to enforce the names.
|
|
827
|
+
* @typeParam R - What `fn` returns. Inferred, and `unknown` when `T` is given
|
|
828
|
+
* explicitly, for the reason under @remarks.
|
|
829
|
+
*
|
|
830
|
+
* @example Annotate the callback, and both are inferred
|
|
831
|
+
* ```ts
|
|
832
|
+
* await withWorkerPayload(
|
|
833
|
+
* workerData,
|
|
834
|
+
* { auditReveal },
|
|
835
|
+
* ({ token }: { token: SensitiveString<'credential'> }, data) =>
|
|
836
|
+
* callApi(token.reveal(), data),
|
|
837
|
+
* );
|
|
838
|
+
* ```
|
|
839
|
+
*
|
|
840
|
+
* @example Or name both, when the return type matters and the callback is long
|
|
841
|
+
* ```ts
|
|
842
|
+
* const signatures = withWorkerPayload<SignerValues, string[]>(
|
|
843
|
+
* workerData,
|
|
844
|
+
* { auditReveal, require: ['signingKey'] },
|
|
845
|
+
* ({ signingKey }, data) => sign(signingKey.reveal(), data),
|
|
846
|
+
* );
|
|
847
|
+
* ```
|
|
848
|
+
*
|
|
849
|
+
* @remarks
|
|
850
|
+
* TypeScript has no partial type argument inference: naming `T` alone fills
|
|
851
|
+
* `R` from its default rather than inferring it, so the call still compiles
|
|
852
|
+
* and its result is `unknown`. That is harmless when the result is discarded,
|
|
853
|
+
* which is the common shape in a worker, and the two examples above are the
|
|
854
|
+
* ways to keep it. `fromWorkerPayload()` takes one type parameter and has no
|
|
855
|
+
* such wart, so the two-call form is the other way out.
|
|
856
|
+
*/
|
|
857
|
+
function withWorkerPayload(payload, options, fn) {
|
|
858
|
+
const received = fromWorkerPayload(payload, options);
|
|
859
|
+
return (0, context_js_1.withRevealContext)(received.context, () => fn(received.values, received.data));
|
|
860
|
+
}
|
|
861
|
+
//# sourceMappingURL=worker.js.map
|