@misconfig/cli 1.1.0 → 1.3.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.
@@ -0,0 +1,41 @@
1
+ // Turns file bytes into text. Editors and PowerShell save agent files as
2
+ // UTF-8, with or without a byte order mark, or as UTF-16. A file with many
3
+ // zero bytes in it is binary: decodeText returns null and it isn't read. A
4
+ // few stray zero bytes don't make a file binary, so they can't hide one from
5
+ // the checks while an agent still reads it as text.
6
+
7
+ const utf8 = (bytes) => new TextDecoder("utf-8").decode(bytes);
8
+ const utf16le = (bytes) => new TextDecoder("utf-16le").decode(bytes);
9
+ const utf16be = (bytes) => {
10
+ const swapped = new Uint8Array(bytes.length - (bytes.length % 2));
11
+ for (let i = 0; i < swapped.length; i += 2) {
12
+ swapped[i] = bytes[i + 1];
13
+ swapped[i + 1] = bytes[i];
14
+ }
15
+ return utf16le(swapped);
16
+ };
17
+
18
+ export function decodeText(input) {
19
+ const b = input instanceof Uint8Array ? input : new Uint8Array(input);
20
+ if (b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf) return utf8(b.subarray(3));
21
+ if (b[0] === 0xff && b[1] === 0xfe) return utf16le(b.subarray(2));
22
+ if (b[0] === 0xfe && b[1] === 0xff) return utf16be(b.subarray(2));
23
+ // Without a byte order mark, UTF-16 text in a Latin script has a zero in
24
+ // every other byte.
25
+ const sample = b.subarray(0, 4096);
26
+ let even = 0;
27
+ let odd = 0;
28
+ for (let i = 0; i < sample.length; i++) if (sample[i] === 0) i % 2 ? odd++ : even++;
29
+ if (!even && !odd) return utf8(b);
30
+ const pairs = sample.length / 2;
31
+ if (!even && odd > pairs * 0.9) return utf16le(b);
32
+ if (!odd && even > pairs * 0.9) return utf16be(b);
33
+ // Stray zero bytes in otherwise clean UTF-8 text. Real binary files have
34
+ // other control bytes too, or bytes that aren't UTF-8.
35
+ for (const x of sample) if ((x > 0 && x < 9) || (x > 13 && x < 32 && x !== 27)) return null;
36
+ try {
37
+ return new TextDecoder("utf-8", { fatal: true }).decode(b);
38
+ } catch {
39
+ return null;
40
+ }
41
+ }