Repository navigation
Expand file tree
/
Copy pathguard-bytes.js
More file actions
596 lines (547 loc) · 26.3 KB
/
Copy pathguard-bytes.js
File metadata and controls
596 lines (547 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) blamejs contributors
"use strict";
// @internal
var async = require("./guard-async");
var identifier = require("./guard-identifier");
var time = require("./guard-time");
var intrinsic = require("./guard-intrinsic");
var constants = require("./constants");
var _NAMED_SCAN_MAX_ELEMENTS = constants.LIMITS.NAMED_SCAN_MAX_ELEMENTS;
var util = intrinsic.assign(intrinsic.create(null), { types: intrinsic.types });
var _isArray = intrinsic.isArray;
var _bufferFrom = intrinsic.bufferFrom;
var _abSlice = intrinsic.arrayBufferSlice;
var _isView = intrinsic.isView;
var _isBuffer = intrinsic.isBuffer;
var _bufferCompare = intrinsic.compare;
var _asyncIterator = intrinsic.asyncIterator;
var _NO_ARGS = intrinsic.freeze([]);
var _create = intrinsic.create;
var _getPrototypeOf = intrinsic.getPrototypeOf;
var _getOwnPropertyDescriptor = intrinsic.getOwnPropertyDescriptor;
var _defineProperty = intrinsic.defineProperty;
var _objectKeys = intrinsic.keys;
var _isExtensible = intrinsic.isExtensible;
var _ownKeys = intrinsic.ownKeys;
var _stringify = intrinsic.stringify;
var _forEach = intrinsic.forEach;
var _map = intrinsic.map;
var _filter = intrinsic.filter;
var _charCodeAt = intrinsic.uncurry(String.prototype.charCodeAt);
var _setForEach = intrinsic.uncurry(Set.prototype.forEach);
var _mapForEach = intrinsic.uncurry(Map.prototype.forEach);
var _String = intrinsic.String;
var _Date = intrinsic.Date;
var _apply = intrinsic.apply;
var _ArrayBuffer = intrinsic.ArrayBuffer;
var _Uint8Array = intrinsic.Uint8Array;
var _DataView = intrinsic.DataView;
var _ObjectProto = intrinsic.ObjectProto;
var _setAdd = intrinsic.setAdd;
var _setHas = intrinsic.setHas;
var _mapSet = intrinsic.mapSet;
var _taSet = intrinsic.typedArraySet;
var _Set = intrinsic.Set;
var _Map = intrinsic.Map;
var guardList = require("./guard-list");
var _append = guardList.append;
function _ownArrayIndices(v, n) {
var keys = _ownKeys(v);
var out = [];
for (var j = 0; j < keys.length; j++) {
var k = keys[j];
if (typeof k !== "string") continue;
var ix = k >>> 0;
if (_String(ix) === k && ix !== 0xFFFFFFFF && ix < n) _append(out, k);
}
return out;
}
// @enforced-by behavioral -- a narrowed restatement of a list has no rename-proof code shape;
function isByteSource(x) {
return _isBuffer(x) || _isView(x) || _isArrayBuffer(x);
}
// @enforced-by behavioral -- a lazy stream wrapper has no rename-proof code shape; the RED vectors (a
function asyncStreamOf(x) {
if (isByteSource(x) || x == null || (typeof x !== "object" && typeof x !== "function")) return null;
var acquire = x[_asyncIterator];
if (typeof acquire !== "function") return null;
var stream = intrinsic.create(null);
stream[_asyncIterator] = function () { return _apply(acquire, x, _NO_ARGS); };
return stream;
}
/** @internal A streaming door's own refusal for a fault the WebCrypto layer raised while reading a
* chunk. Anything else is rethrown as it stands.
*
* @enforced-by behavioral -- the rule is which faults are translated and which are rethrown, which no
* code shape distinguishes from any other error-code test; the vectors driving a chunk that is not a byte
* source and an unrelated throw through a streaming door are the guard */
function translateStreamError(e, E, code) {
if (e && e.code === "webcrypto/data") throw E(code, "a streamed content chunk is not a byte source", e);
if (e && e.code === "webcrypto/syntax") throw E(code, "the streamed content is not a valid async iterable of byte chunks", e);
throw e;
}
function _isArrayBuffer(v) {
return util.types.isArrayBuffer(v);
}
var _TYPED_ARRAY_PROTO = _getPrototypeOf(Uint8Array.prototype);
var _uncurriedGetter = intrinsic.getter;
var _taBuffer = _uncurriedGetter(_TYPED_ARRAY_PROTO, "buffer", "%TypedArray%.prototype");
var _taByteOffset = _uncurriedGetter(_TYPED_ARRAY_PROTO, "byteOffset", "%TypedArray%.prototype");
var _dvBuffer = _uncurriedGetter(DataView.prototype, "buffer", "DataView.prototype");
var _dvByteOffset = _uncurriedGetter(DataView.prototype, "byteOffset", "DataView.prototype");
function _storeOf(v) { return util.types.isDataView(v) ? _dvBuffer(v) : _taBuffer(v); }
function _offsetOf(v) { return util.types.isDataView(v) ? _dvByteOffset(v) : _taByteOffset(v); }
function _lengthOf(v) { return intrinsic.sizeOf(v); }
function _reView(v) {
return _bufferFrom(_storeOf(v), _offsetOf(v), _lengthOf(v));
}
function _isTypedArrayPredName(name) {
var n = name.length;
if (n < 8) return false;
if (_charCodeAt(name, 0) !== 105 || _charCodeAt(name, 1) !== 115) return false;
var tail = "Array";
for (var k = 0; k < 5; k++) { if (_charCodeAt(name, n - 5 + k) !== _charCodeAt(tail, k)) return false; }
for (var i = 2; i < n - 5; i++) {
var c = _charCodeAt(name, i);
if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122))) return false;
}
return true;
}
var _CONCRETE_KINDS = _filter(
_map(
// allow:guard-reads-runtime-live -- module-init, see above
_filter(_objectKeys(util.types), function (name) { return _isTypedArrayPredName(name); }),
// allow:guard-reads-runtime-live -- module-init, see above
function (name) { return [util.types[name], globalThis[name.slice(2)]]; }
),
function (row) {
return typeof row[0] === "function" && typeof row[1] === "function" &&
typeof row[1].BYTES_PER_ELEMENT === "number" && row[1].BYTES_PER_ELEMENT > 0;
}
);
function _concreteKindOf(v) {
for (var i = 0; i < _CONCRETE_KINDS.length; i++) {
if (_CONCRETE_KINDS[i][0](v)) return _CONCRETE_KINDS[i][1];
}
return null;
}
var _NAMED_KINDS = _filter([
["isNativeError", "Error"], ["isRegExp", "RegExp"], ["isPromise", "Promise"],
["isWeakMap", "WeakMap"], ["isWeakSet", "WeakSet"], ["isMap", "Map"], ["isSet", "Set"],
["isDate", "Date"], ["isProxy", "Proxy"]
], function (row) { return typeof util.types[row[0]] === "function"; });
function _kindName(v) {
for (var i = 0; i < _NAMED_KINDS.length; i++) {
if (util.types[_NAMED_KINDS[i][0]](v)) return _NAMED_KINDS[i][1];
}
return typeof v === "function" ? "function" : "value";
}
function _article(name) {
var c = name.length > 0 ? _charCodeAt(name, 0) : 0;
var vowel = c === 65 || c === 69 || c === 73 || c === 79 || c === 85 ||
c === 97 || c === 101 || c === 105 || c === 111 || c === 117;
return vowel ? "an" : "a";
}
// @enforced-by behavioral -- an input door reaching for this instead of `view` has no rename-proof
function outputView(input, ErrorClass, code, label) {
if (!util.types.isUint8Array(input) && !_isView(input)) {
throw _raise(ErrorClass, code, label + ": expected a Buffer / TypedArray to write into");
}
try {
return _reView(input);
} catch (e) {
throw _raise(ErrorClass, code, label + ": output is not a usable byte view (detached backing buffer?)", e);
}
}
// @enforced-by behavioral -- `x.length` is the ordinary spelling wherever the value is this
function lengthOf(view) {
return _lengthOf(view);
}
/** @internal A view's bytes as an ArrayBuffer of their own, read through the captured accessors.
* `v.buffer`, `v.byteOffset` and `v.byteLength` are getters on the TypedArray and DataView prototypes,
* so a replacement of any of them decides which bytes the result holds: measured, replacing them after
* the slicing helper had been captured turned a valid 64-byte Ed25519 signature into 64 zero bytes on
* its way out of `pki.webcrypto.subtle.sign`. This is the form for a value crossing into a WebCrypto
* return, where the API's type is an ArrayBuffer rather than a view.
*
* @enforced-by guard-shape-reinlined
* @guard-shape \(\s*([A-Za-z_$][\w$]*)\.buffer\s*,\s*\1\.byteOffset
*/
function toArrayBuffer(input) {
var offset = _offsetOf(input);
return _abSlice(_storeOf(input), offset, offset + _lengthOf(input));
}
function _refuseShared(v, ErrorClass, code, label) {
if (util.types.isSharedArrayBuffer(v) ||
(_isView(v) && util.types.isSharedArrayBuffer(_storeOf(v)))) {
throw _raise(ErrorClass, code, label + ": shared memory cannot be used here, because another " +
"thread can rewrite it after it has been checked; pass a Buffer or a Uint8Array over " +
"memory this process owns");
}
}
var _ErrorProto = Error.prototype;
function _isErrorClass(E) {
if (typeof E !== "function") return false;
var seen = new _Set();
for (var p = E.prototype; p !== null && typeof p === "object"; p = _getPrototypeOf(p)) {
if (p === _ErrorProto) return true;
if (_setHas(seen, p)) return false;
_setAdd(seen, p);
}
return false;
}
function _raise(E, code, message, cause) {
return _isErrorClass(E) ? new E(code, message, cause) : E(code, message, cause);
}
// @enforced-by guard-shape-reinlined
// @guard-shape (?:Buffer\.from|new\s+[A-Za-z_$][\w$]*Array)\(\s*(?:new\s+[A-Za-z_$][\w$]*Array\(\s*)?([A-Za-z_$][\w$]*)\.buffer\s*,\s*\1\.byteOffset
function view(input, ErrorClass, code, label) {
_refuseShared(input, ErrorClass, code, label);
if (util.types.isUint8Array(input)) {
try {
return _reView(input);
} catch (e) {
throw _raise(ErrorClass, code, label + ": input is not a usable byte view (detached backing buffer?)", e);
}
}
throw _raise(ErrorClass, code, label + ": expected a Buffer / Uint8Array");
}
// @enforced-by guard-shape-reinlined (the re-view shape is declared on view above)
function source(input, ErrorClass, code, label) {
_refuseShared(input, ErrorClass, code, label);
var isAb = _isArrayBuffer(input);
if (isAb || _isView(input)) {
try {
return isAb ? _bufferFrom(input) : _reView(input);
} catch (e) {
throw _raise(ErrorClass, code, label + ": input is not a usable byte source (detached backing buffer?)", e);
}
}
throw _raise(ErrorClass, code, label + ": expected a BufferSource (ArrayBuffer / TypedArray / Buffer)");
}
/** @internal Into a store of its own, not through `Buffer.from`. A small `Buffer.from` takes its result
* out of the 64 KiB allocation pool, so a caller whose own input came from that pool holds a view of
* the whole store and the copy lands inside it at another offset. MEASURED through a shipped verb: a
* caller's transport, which runs after the key is copied and before the signature is checked, found
* the copy in the pool it shared, wrote an attacker's SPKI over it, and the forged tree head was
* accepted. Every consumer of this door relies on the copy being out of the caller's reach, which is
* the whole reason the copy is taken. The deep copy below has always allocated its own store; this is
* the same allocation. */
function _ownedCopy(src) {
var len = _lengthOf(src);
var owned = new _ArrayBuffer(len);
_taSet(new _Uint8Array(owned), src);
return _bufferFrom(owned, 0, len);
}
// @enforced-by behavioral -- a copy has no rename-proof code shape to detect (any
function snapshot(input, ErrorClass, code, label) {
return _ownedCopy(view(input, ErrorClass, code, label));
}
// @enforced-by behavioral -- a copy has no rename-proof shape to detect; the guard
function snapshotSource(input, ErrorClass, code, label) {
return _ownedCopy(source(input, ErrorClass, code, label));
}
// @enforced-by behavioral -- a copy has no rename-proof code shape to detect (any `Buffer.from(x)`
/** @internal `maxNodes` bounds the WORK, which the depth cap does not. A value that shares a subobject
* with itself is a graph rather than a tree, and this copy visits every reference independently: with
* `v = [v, v]` repeated n times, the depth is n and the work is 2 to the n. MEASURED through two shipped
* doors, a DAG placed in a member beside the ones a verb validates, `pki.jose.thumbprint` took 748 ms at
* 16 levels, 2.9 seconds at 18 and 5.9 at 19, doubling every level up to a depth cap of 64, and
* `pki.tuf.keyId` the same (CWE-770). The counter is shared across the whole walk, so the cost follows
* the budget rather than the shape of the input. The figure is far above any real caller value: an
* options bag or a JWK is tens of nodes, and a certificate chain passed as an anchor list is thousands. */
function snapshotDeep(value, ErrorClass, code, label, opts) {
var o = opts || _create(null);
var cap = o.maxDepth == null ? 64 : o.maxDepth;
var maxNodes = o.maxNodes == null ? constants.LIMITS.DEEP_COPY_MAX_NODES : o.maxNodes;
return _deep(value, ErrorClass, code, label, cap, 0, o.collect || null, { n: 0, max: maxNodes });
}
function _surface(names) {
var t = _create(null);
_forEach(names, function (n) { t[n] = 1; });
t[Symbol.toStringTag] = 1;
return t;
}
var _CRYPTO_KEY_SURFACE = _surface(["type", "extractable", "algorithm", "usages",
"asymmetricKeyType", "asymmetricKeyDetails", "_handle"]);
var _ERROR_SURFACE = _surface(["message", "stack", "name", "cause"]);
var _REGEXP_SURFACE = _surface(["lastIndex", "source", "flags", "global", "ignoreCase", "multiline",
"sticky", "unicode", "unicodeSets", "hasIndices", "dotAll"]);
var _THENABLE_SURFACE = _surface(["then", "catch", "finally"]);
function _opaqueSurface(v, ErrorClass, code, label) {
var proto = _getPrototypeOf(v);
if (proto === _ObjectProto || proto === null) return null;
if (util.types.isWeakMap(v) || util.types.isWeakSet(v)) return _create(null);
if (util.types.isNativeError(v)) return _ERROR_SURFACE;
if (util.types.isRegExp(v)) return _REGEXP_SURFACE;
if (util.types.isKeyObject(v)) return _CRYPTO_KEY_SURFACE;
var keyLike;
try {
keyLike = require("./webcrypto").isCryptoKeyLike(v); // allow:inline-require -- circular load: webcrypto requires this module
} catch (e) {
throw _raise(ErrorClass, code, label + ": reading the key surface threw", e);
}
if (keyLike) return _CRYPTO_KEY_SURFACE;
var then;
try { then = v.then; }
catch (e) { throw _raise(ErrorClass, code, label + ": reading \"then\" threw", e); }
if (typeof then === "function") return _THENABLE_SURFACE;
return null;
}
function _canChangeAfterTheCheck(v, name) {
var visited = new _Set();
for (var o = v; o && !_setHas(visited, o); o = _getPrototypeOf(o)) {
_setAdd(visited, o);
var d = _getOwnPropertyDescriptor(o, name);
if (!d) continue;
if (d.get || d.set || d.writable || d.configurable) return true;
return o !== v && _isExtensible(v);
}
return false;
}
var _SETTLED_DEPTH = 4;
function _settledValueIsFixed(value, ErrorClass, code, label, depth) {
if (value === null || (typeof value !== "object" && typeof value !== "function")) return true;
if (depth >= _SETTLED_DEPTH) return false;
if (util.types.isProxy(value)) return false;
var surface = _opaqueSurface(value, ErrorClass, code, label);
if (!surface) return false;
return _opaqueFieldOutsideSurface(value, surface, ErrorClass, code, label, depth + 1) === null;
}
function _opaqueFieldOutsideSurface(v, surface, ErrorClass, code, label, depth) {
var keys = _namesToCopy(v, ErrorClass, code, label);
for (var i = 0; i < keys.length; i++) {
if (surface[keys[i]]) continue;
if (typeof keys[i] === "symbol") continue;
if (!_canChangeAfterTheCheck(v, keys[i]) &&
_settledValueIsFixed(v[keys[i]], ErrorClass, code, label, depth || 0)) continue;
return keys[i];
}
return null;
}
function _copyBytesSameKind(v, ErrorClass, code, label, collect) {
var src = source(v, ErrorClass, code, label);
var srcLen = _lengthOf(src);
var owned = new _ArrayBuffer(srcLen);
_taSet(new _Uint8Array(owned), src);
if (collect) _append(collect, _bufferFrom(owned, 0, srcLen));
if (_isBuffer(v)) return _bufferFrom(owned, 0, srcLen);
if (_isArrayBuffer(v)) return owned;
if (util.types.isDataView(v)) return new _DataView(owned);
var Ctor = _concreteKindOf(v);
if (!Ctor) {
throw _raise(ErrorClass, code, label + ": a " +
(util.types.isTypedArray(v) ? "typed array of a kind this runtime added" : "byte view") +
" cannot be copied while keeping its kind; pass a Buffer or a Uint8Array");
}
return new Ctor(owned, 0, srcLen / Ctor.BYTES_PER_ELEMENT);
}
function _protoChainIsCyclic(v) {
var visited = new _Set();
for (var o = v; o; o = _getPrototypeOf(o)) {
if (_setHas(visited, o)) return true;
_setAdd(visited, o);
}
return false;
}
function _protoChainHasProxy(v) {
var visited = new _Set();
for (var o = v; o && !_setHas(visited, o); o = _getPrototypeOf(o)) {
_setAdd(visited, o);
if (util.types.isProxy(o)) return true;
}
return false;
}
function _plainCopy(copy) { return copy; }
function _deep(v, ErrorClass, code, label, cap, depth, collect, work) {
if (depth > cap) throw _raise(ErrorClass, code, label + " is nested too deeply to copy");
/** @internal One unit per value visited, charged against the shared counter before the value is read.
* The depth cap above bounds how far down the walk goes and says nothing about how WIDE the walk is
* when references are shared, which is what the counter answers. */
if (work !== undefined) {
work.n += 1;
if (work.n > work.max) {
throw _raise(ErrorClass, code, label + " expands to more than " + work.max +
" values when copied: a value that holds the same subobject in more than one place is copied " +
"once per place, so a few dozen fields can expand without bound");
}
}
if (v == null || typeof v !== "object") return v;
_refuseShared(v, ErrorClass, code, label);
if (_protoChainHasProxy(v)) {
throw _raise(ErrorClass, code, label + ": a Proxy cannot be copied faithfully, because the " +
"keys it reports need not be the ones it answers; pass a plain object");
}
if (_protoChainIsCyclic(v)) {
throw _raise(ErrorClass, code, label + ": its prototype chain is a cycle, so it cannot be " +
"read or copied; pass a plain object");
}
if (_isBuffer(v) || _isView(v) || _isArrayBuffer(v)) {
var bytesCopy = _copyBytesSameKind(v, ErrorClass, code, label, collect);
if (bytesCopy.byteLength <= _NAMED_SCAN_MAX_ELEMENTS) {
_copyNamed(v, bytesCopy, ErrorClass, code, label, cap, depth, collect, work);
}
return bytesCopy;
}
if (require("./guard-parsed").isRecordedAsProduced(v)) return v; // allow:inline-require -- circular load: guard-parsed requires this module
if (util.types.isDate(v)) {
var dateCopy = new _Date(time.instantOf(v));
_copyNamed(v, dateCopy, ErrorClass, code, label, cap, depth, collect, work, _DATE_BEHAVIOR);
return _plainCopy(dateCopy);
}
if (_isArray(v)) {
var arr = [];
var indexE = function (c, m) { return _raise(ErrorClass, c, m); };
/** @internal The count is narrowed where it is taken and the copy's own length is set from it, not
* from a second read of the source. Read again at the end, a nested getter that shrank the source
* while the walk ran TRUNCATED the finished copy: both elements had been collected and the copy
* then reported one. The snapshot is of the array as it was counted. */
var vCount = guardList.count(v, "snapshotDeep");
var indices = _ownArrayIndices(v, vCount);
if (identifier.readableIndices(v, indexE, code, label).length !== indices.length) {
throw _raise(ErrorClass, code, label + " has an in-range index supplied by its prototype rather than the array itself; a list resolved through the prototype chain is refused");
}
if (depth === 0) identifier.refuseAccessorFields(v, indices, indexE, code, label);
_forEach(indices, function (k) {
var element;
try { element = v[k]; }
catch (e) { throw _raise(ErrorClass, code, label + ": reading element " + k + " threw", e); }
/** @internal The copy's slot is DEFINED, not stored at. The indices walked here are the ones
* the source holds of its own, so they can skip: a store at an index this copy has no own
* property at walks the prototype chain for a setter, which would take the copied element at
* the toolkit's own door for caller byte structures. */
_defineProperty(arr, k, { value: _deep(element, ErrorClass, code, label, cap, depth + 1, collect, work), writable: true, enumerable: true, configurable: true });
});
arr.length = vCount;
_copyNamed(v, arr, ErrorClass, code, label, cap, depth, collect, work);
return _plainCopy(arr);
}
var surface = _opaqueSurface(v, ErrorClass, code, label);
if (surface) {
var carried = _opaqueFieldOutsideSurface(v, surface, ErrorClass, code, label);
if (carried === null) return v;
throw _raise(ErrorClass, code, label + ": " + _article(_kindName(v)) + " " + _kindName(v) +
" carrying its own field " + _stringify(_String(carried)) + " cannot be used here -- its " +
"state cannot be copied, so that field would stay changeable after it was checked; pass the " +
"fields as a plain object");
}
if (util.types.isMap(v)) {
return _plainCopy(_copyEntries(v, new _Map(), ErrorClass, code, label, cap, depth, collect, work));
}
if (util.types.isSet(v)) {
return _plainCopy(_copyEntries(v, new _Set(), ErrorClass, code, label, cap, depth, collect, work));
}
var out = _create(_getPrototypeOf(v) === null ? null : _ObjectProto);
_copyNamed(v, out, ErrorClass, code, label, cap, depth, collect, work);
return out;
}
function _namesToCopy(src, ErrorClass, code, label, atArgument) {
var E = function (c, m) { return _raise(ErrorClass, c, m); };
var names = identifier.readableNames(src, E, code, label);
if (atArgument) identifier.refuseAccessorFields(src, names, E, code, label);
return names;
}
function _copyEntries(src, dst, ErrorClass, code, label, cap, depth, collect, work) {
var walk = util.types.isSet(src) ? _setForEach : _mapForEach;
walk(src, function (value, key) {
var copiedValue = _deep(value, ErrorClass, code, label, cap, depth + 1, collect, work);
if (util.types.isSet(dst)) _setAdd(dst, copiedValue);
else _mapSet(dst, _deep(key, ErrorClass, code, label, cap, depth + 1, collect, work), copiedValue);
});
_copyNamed(src, dst, ErrorClass, code, label, cap, depth, collect, work);
return dst;
}
var _DATE_BEHAVIOR = (function () {
var t = _create(null);
_forEach(_ownKeys(Date.prototype), function (n) { t[n] = 1; });
return t;
})();
function _copyNamed(src, dst, ErrorClass, code, label, cap, depth, collect, work, behavior) {
var keys = _namesToCopy(src, ErrorClass, code, label, depth === 0);
/** @internal Every PROPERTY is charged, not only every value `_deep` recurses into. A function is
* carried across by reference rather than copied, so it took no charge, and the counter then
* under-counted the real work by the property count: MEASURED through `pki.jose.thumbprint`, a graph
* whose shared leaf carried 1000 function properties cost 17.7 seconds against 384 ms for the same
* graph with a plain leaf, because the visits were capped and the per-visit work was not. Charging the
* key run up front is one charge for work proportional to it. */
if (work !== undefined && keys.length > 0) {
work.n += keys.length;
if (work.n > work.max) {
throw _raise(ErrorClass, code, label + " expands to more than " + work.max +
" values when copied: a value that holds the same subobject in more than one place is copied " +
"once per place, so a few dozen fields can expand without bound");
}
}
for (var k = 0; k < keys.length; k++) {
var value;
try { value = src[keys[k]]; }
catch (e) { throw _raise(ErrorClass, code, label + ": reading " + _stringify(keys[k]) + " threw", e); }
if (behavior && behavior[keys[k]] && typeof value === "function") continue;
_defineProperty(dst, keys[k], {
value: typeof value === "function" ? value
: _deep(value, ErrorClass, code, label, cap, depth + 1, collect, work),
writable: true, enumerable: _wasEnumerable(src, keys[k]), configurable: true,
});
}
}
function _wasEnumerable(v, name) {
for (var o = v; o && o !== _ObjectProto; o = _getPrototypeOf(o)) {
var d = _getOwnPropertyDescriptor(o, name);
if (d) return !!d.enumerable;
}
return false;
}
// @enforced-by behavioral -- there is no rename-proof code shape for "copied every argument". The
function fixArguments(ErrorClass, code, args) {
var copies = [];
var values = [];
function release() {
require("./guard-secret").zeroizeAll(copies, ErrorClass, code, // allow:inline-require -- circular load: guard-secret requires this module
"a copy of a caller-supplied argument");
}
try {
/** @internal The count is narrowed where it is taken, as every walk in `guard.list` is. */
var argCount = guardList.count(args, "fixArguments");
for (var i = 0; i < argCount; i++) {
_append(values, snapshotDeep(args[i][0], ErrorClass, code, args[i][1], { collect: copies }));
}
} catch (e) {
release();
throw e;
}
return { values: values, release: release };
}
// @enforced-by behavioral -- an arrangement of two calls has no rename-proof shape to detect. The
function fixedCall(ErrorClass, code, args, body) {
var handle = null;
/** @internal The release is attached on BOTH outcomes rather than through `finally`, which calls
* the receiver's own `then` and so reads the live method: a replacement there settles the chain
* with a value of its own AND skips this callback, so the fixed views stay pinned. */
var ran = async.deferred(function () {
handle = fixArguments(ErrorClass, code, args);
return _apply(body, null, handle.values);
});
return async.cleanup(ran, function () { if (handle) handle.release(); });
}
/**
* @internal The ORDER of two byte strings, through the captured operation. A DER SET OF is ordered by
* its members' encoded bytes and a byte-for-byte claim is this comparison, so whatever answers
* "before" and "equal" decides emitted bytes at one end and a verdict at the other: a replacement
* answering a fixed order sets the order of every SET this toolkit builds, and one answering zero turns
* a mismatch into a match. Offered here so a module can reach the captured operation through the guard
* surface it already takes. This is an ORDERING, not a secret comparison: a secret goes through
* `guard.crypto.constantTimeEqual`.
*
* @enforced-by guard-shape-reinlined
* @guard-shape Buffer\.compare\(
* @guard-via (?:guard\.bytes|intrinsic)\.compare\(
*/
function compare(a, b) { return _bufferCompare(a, b); }
module.exports = intrinsic.freeze({
compare: compare,
view: view, source: source, snapshot: snapshot, snapshotSource: snapshotSource,
isByteSource: isByteSource, asyncStreamOf: asyncStreamOf, translateStreamError: translateStreamError, lengthOf: lengthOf, outputView: outputView,
toArrayBuffer: toArrayBuffer,
snapshotDeep: snapshotDeep, fixArguments: fixArguments, fixedCall: fixedCall,
});