decryption 0.5.1 → 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.
Files changed (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -325
  3. package/index.js +8 -64
  4. package/package.json +8 -24
  5. package/commands/account.d.ts +0 -4
  6. package/commands/account.js +0 -470
  7. package/commands/cosmology.d.ts +0 -4
  8. package/commands/cosmology.js +0 -97
  9. package/commands/doctor.d.ts +0 -3
  10. package/commands/doctor.js +0 -42
  11. package/commands/encrypt.d.ts +0 -12
  12. package/commands/encrypt.js +0 -251
  13. package/commands/guard.d.ts +0 -3
  14. package/commands/guard.js +0 -92
  15. package/commands/keychain.d.ts +0 -4
  16. package/commands/keychain.js +0 -92
  17. package/commands/keys.d.ts +0 -4
  18. package/commands/keys.js +0 -74
  19. package/commands/passkey.d.ts +0 -4
  20. package/commands/passkey.js +0 -135
  21. package/commands/salt.d.ts +0 -4
  22. package/commands/salt.js +0 -113
  23. package/commands/secrets.d.ts +0 -4
  24. package/commands/secrets.js +0 -214
  25. package/commands/shamir.d.ts +0 -4
  26. package/commands/shamir.js +0 -62
  27. package/commands/vault.d.ts +0 -7
  28. package/commands/vault.js +0 -382
  29. package/commands/wallet.d.ts +0 -5
  30. package/commands/wallet.js +0 -129
  31. package/commands/workspace.d.ts +0 -8
  32. package/commands/workspace.js +0 -289
  33. package/commands.d.ts +0 -8
  34. package/commands.js +0 -126
  35. package/esm/commands/account.js +0 -466
  36. package/esm/commands/cosmology.js +0 -93
  37. package/esm/commands/doctor.js +0 -38
  38. package/esm/commands/encrypt.js +0 -245
  39. package/esm/commands/guard.js +0 -88
  40. package/esm/commands/keychain.js +0 -88
  41. package/esm/commands/keys.js +0 -70
  42. package/esm/commands/passkey.js +0 -131
  43. package/esm/commands/salt.js +0 -109
  44. package/esm/commands/secrets.js +0 -210
  45. package/esm/commands/shamir.js +0 -58
  46. package/esm/commands/vault.js +0 -376
  47. package/esm/commands/wallet.js +0 -125
  48. package/esm/commands/workspace.js +0 -283
  49. package/esm/commands.js +0 -120
  50. package/esm/index.js +0 -50
  51. package/esm/utils/bytes.js +0 -286
  52. package/esm/utils/dispatch.js +0 -52
  53. package/esm/utils/env.js +0 -44
  54. package/esm/utils/errors.js +0 -44
  55. package/esm/utils/header.js +0 -14
  56. package/esm/utils/io.js +0 -49
  57. package/esm/utils/passphrase.js +0 -49
  58. package/esm/utils/recipients.js +0 -74
  59. package/esm/utils/stash.js +0 -61
  60. package/esm/utils/temp.js +0 -51
  61. package/esm/utils/text.js +0 -2
  62. package/esm/workspace/bundle.js +0 -239
  63. package/esm/workspace/doctor.js +0 -104
  64. package/esm/workspace/git.js +0 -72
  65. package/esm/workspace/guard.js +0 -111
  66. package/esm/workspace/layout.js +0 -106
  67. package/esm/workspace/manifest.js +0 -147
  68. package/esm/workspace/recipients.js +0 -37
  69. package/esm/workspace/snippets.js +0 -54
  70. package/esm/workspace/state.js +0 -46
  71. package/esm/workspace/status.js +0 -93
  72. package/esm/workspace/tar.js +0 -235
  73. package/index.d.ts +0 -12
  74. package/utils/bytes.d.ts +0 -86
  75. package/utils/bytes.js +0 -301
  76. package/utils/dispatch.d.ts +0 -24
  77. package/utils/dispatch.js +0 -58
  78. package/utils/env.d.ts +0 -26
  79. package/utils/env.js +0 -49
  80. package/utils/errors.d.ts +0 -25
  81. package/utils/errors.js +0 -50
  82. package/utils/header.d.ts +0 -4
  83. package/utils/header.js +0 -18
  84. package/utils/io.d.ts +0 -10
  85. package/utils/io.js +0 -57
  86. package/utils/passphrase.d.ts +0 -15
  87. package/utils/passphrase.js +0 -53
  88. package/utils/recipients.d.ts +0 -28
  89. package/utils/recipients.js +0 -80
  90. package/utils/stash.d.ts +0 -40
  91. package/utils/stash.js +0 -76
  92. package/utils/temp.d.ts +0 -10
  93. package/utils/temp.js +0 -59
  94. package/utils/text.d.ts +0 -2
  95. package/utils/text.js +0 -6
  96. package/workspace/bundle.d.ts +0 -50
  97. package/workspace/bundle.js +0 -248
  98. package/workspace/doctor.d.ts +0 -8
  99. package/workspace/doctor.js +0 -108
  100. package/workspace/git.d.ts +0 -21
  101. package/workspace/git.js +0 -83
  102. package/workspace/guard.d.ts +0 -23
  103. package/workspace/guard.js +0 -118
  104. package/workspace/layout.d.ts +0 -47
  105. package/workspace/layout.js +0 -113
  106. package/workspace/manifest.d.ts +0 -52
  107. package/workspace/manifest.js +0 -157
  108. package/workspace/recipients.d.ts +0 -16
  109. package/workspace/recipients.js +0 -45
  110. package/workspace/snippets.d.ts +0 -29
  111. package/workspace/snippets.js +0 -58
  112. package/workspace/state.d.ts +0 -13
  113. package/workspace/state.js +0 -52
  114. package/workspace/status.d.ts +0 -54
  115. package/workspace/status.js +0 -99
  116. package/workspace/tar.d.ts +0 -29
  117. package/workspace/tar.js +0 -240
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.recordSection = exports.readState = exports.statePath = void 0;
4
- const fs_1 = require("fs");
5
- const promises_1 = require("fs/promises");
6
- const path_1 = require("path");
7
- const bytes_1 = require("../utils/bytes");
8
- const layout_1 = require("./layout");
9
- /**
10
- * What this machine last encrypted or decrypted, per section.
11
- *
12
- * Comparing a section against its bundle would otherwise need the bundle decrypted, and so a
13
- * passphrase. Remembering the two hashes that were in agreement the last time lets `status` and
14
- * an unchanged `encrypt-section` answer without one. The file is local, holds only hashes, and is
15
- * never committed; losing it loses nothing but that shortcut.
16
- */
17
- const STATE_VERSION = 1;
18
- const statePath = (workspace) => (0, path_1.join)(workspace.root, layout_1.STATE_DIRECTORY, 'state.json');
19
- exports.statePath = statePath;
20
- const isRecord = (value) => {
21
- const record = value;
22
- return (typeof record === 'object' &&
23
- record !== null &&
24
- typeof record.digest === 'string' &&
25
- typeof record.bundle === 'string');
26
- };
27
- /** Reads the state. A missing or unreadable file is an empty one: every section is then unknown. */
28
- const readState = (workspace) => {
29
- const path = (0, exports.statePath)(workspace);
30
- if (!(0, fs_1.existsSync)(path))
31
- return {};
32
- try {
33
- const parsed = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
34
- if (parsed?.version !== STATE_VERSION || typeof parsed.sections !== 'object')
35
- return {};
36
- return Object.fromEntries(Object.entries(parsed.sections ?? {}).filter(([, value]) => isRecord(value)));
37
- }
38
- catch {
39
- return {};
40
- }
41
- };
42
- exports.readState = readState;
43
- /** Records that `name`'s plaintext and bundle agree, replacing what was known about it. */
44
- const recordSection = async (workspace, name, record) => {
45
- const sections = { ...(0, exports.readState)(workspace), [name]: record };
46
- const sorted = Object.fromEntries(Object.entries(sections).sort(([a], [b]) => (a < b ? -1 : 1)));
47
- const path = (0, exports.statePath)(workspace);
48
- await (0, promises_1.mkdir)((0, path_1.join)(workspace.root, layout_1.STATE_DIRECTORY), { recursive: true });
49
- const text = JSON.stringify({ version: STATE_VERSION, sections: sorted }, null, 2) + '\n';
50
- await (0, bytes_1.writeFileAtomically)(path, [Buffer.from(text, 'utf8')]);
51
- };
52
- exports.recordSection = recordSection;
@@ -1,54 +0,0 @@
1
- import { BundleInfo } from './bundle';
2
- import { Section } from './layout';
3
- import { Snapshot } from './manifest';
4
- import { SectionRecord } from './state';
5
- /** Where a section's plaintext and its bundle stand relative to each other. */
6
- export type SectionState =
7
- /** Plaintext and bundle are the pair this machine last wrote or read. */
8
- 'in sync'
9
- /** The plaintext was edited and has not been encrypted again. */
10
- | 'plaintext changed'
11
- /** The bundle is newer than the plaintext: someone else encrypted it. */
12
- | 'bundle changed'
13
- /** Both changed since they last agreed. */
14
- | 'conflict'
15
- /** There is a bundle and no plaintext. */
16
- | 'not decrypted'
17
- /** There is plaintext and no bundle. */
18
- | 'not encrypted'
19
- /** Both exist, and this machine has no record of them agreeing. */
20
- | 'unknown'
21
- /** The bundle is a Git LFS pointer. */
22
- | 'not downloaded'
23
- /** The bundle is not a file dcrypt can read: its header is damaged, cut short or unsupported. */
24
- | 'bundle unreadable'
25
- /** The folder cannot be recorded: it holds a link, or a name a bundle cannot store. */
26
- | 'plaintext unreadable'
27
- /** Neither exists. */
28
- | 'missing';
29
- export interface SectionReport {
30
- section: Section;
31
- state: SectionState;
32
- snapshot?: Snapshot;
33
- bundle?: BundleInfo;
34
- /** Why it could not be read, in the two states that say it could not. */
35
- problem?: string;
36
- /** Fingerprints in `recipients.txt` that the bundle is not encrypted to. */
37
- missingRecipients: string[];
38
- /** Fingerprints the bundle is encrypted to that are not in `recipients.txt`. */
39
- extraRecipients: string[];
40
- }
41
- /**
42
- * Compares a section's plaintext, its bundle and what this machine remembers of them. Needs no
43
- * key: the plaintext is hashed, the bundle is hashed, and its header names its recipients.
44
- *
45
- * `recipients` is the fingerprints in `recipients.txt`, when there is one to compare against.
46
- *
47
- * It does not throw for a section it cannot read: that is a state of that section, with the
48
- * reason in `problem`, so that one bad section never hides the state of the others.
49
- */
50
- export declare const inspectSection: (section: Section, record?: SectionRecord, recipients?: string[]) => Promise<SectionReport>;
51
- /** True when the bundle is not encrypted to exactly the people in `recipients.txt`. */
52
- export declare const recipientsDiffer: (report: SectionReport) => boolean;
53
- /** One line on what a report means and what to do about it. Empty when there is nothing to do. */
54
- export declare const adviceFor: (report: SectionReport) => string;
@@ -1,99 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.adviceFor = exports.recipientsDiffer = exports.inspectSection = void 0;
4
- const fs_1 = require("fs");
5
- const errors_1 = require("../utils/errors");
6
- const text_1 = require("../utils/text");
7
- const bundle_1 = require("./bundle");
8
- const manifest_1 = require("./manifest");
9
- const exists = (path, kind) => {
10
- try {
11
- return (0, fs_1.statSync)(path)[kind]();
12
- }
13
- catch {
14
- return false;
15
- }
16
- };
17
- const stateOf = (snapshot, bundle, record) => {
18
- if (!bundle)
19
- return snapshot ? 'not encrypted' : 'missing';
20
- if (!snapshot)
21
- return 'not decrypted';
22
- if (!record)
23
- return 'unknown';
24
- const plaintextSame = snapshot.digest === record.digest;
25
- const bundleSame = bundle.sha256 === record.bundle;
26
- if (plaintextSame)
27
- return bundleSame ? 'in sync' : 'bundle changed';
28
- return bundleSame ? 'plaintext changed' : 'conflict';
29
- };
30
- /**
31
- * Compares a section's plaintext, its bundle and what this machine remembers of them. Needs no
32
- * key: the plaintext is hashed, the bundle is hashed, and its header names its recipients.
33
- *
34
- * `recipients` is the fingerprints in `recipients.txt`, when there is one to compare against.
35
- *
36
- * It does not throw for a section it cannot read: that is a state of that section, with the
37
- * reason in `problem`, so that one bad section never hides the state of the others.
38
- */
39
- const inspectSection = async (section, record, recipients) => {
40
- const unread = { section, missingRecipients: [], extraRecipients: [] };
41
- let snapshot;
42
- try {
43
- if (exists(section.directory, 'isDirectory'))
44
- snapshot = await (0, manifest_1.snapshotSection)(section.directory);
45
- }
46
- catch (error) {
47
- return { ...unread, state: 'plaintext unreadable', problem: (0, errors_1.messageFor)(error) };
48
- }
49
- const report = { ...unread, snapshot };
50
- if (!exists(section.bundle, 'isFile'))
51
- return { ...report, state: stateOf(snapshot, undefined, record) };
52
- let bundle;
53
- try {
54
- bundle = await (0, bundle_1.inspectBundle)(section.bundle);
55
- }
56
- catch (error) {
57
- if (error instanceof bundle_1.LfsPointerError)
58
- return { ...report, state: 'not downloaded' };
59
- return { ...report, state: 'bundle unreadable', problem: (0, errors_1.messageFor)(error) };
60
- }
61
- return {
62
- ...report,
63
- bundle,
64
- state: stateOf(snapshot, bundle, record),
65
- missingRecipients: (recipients ?? []).filter((id) => !bundle.recipients.includes(id)),
66
- extraRecipients: recipients ? bundle.recipients.filter((id) => !recipients.includes(id)) : [],
67
- };
68
- };
69
- exports.inspectSection = inspectSection;
70
- /** True when the bundle is not encrypted to exactly the people in `recipients.txt`. */
71
- const recipientsDiffer = (report) => report.missingRecipients.length + report.extraRecipients.length > 0;
72
- exports.recipientsDiffer = recipientsDiffer;
73
- const ADVICE = {
74
- 'in sync': '',
75
- 'plaintext changed': 'run `dcrypt encrypt-section` to encrypt the changes',
76
- 'bundle changed': 'run `dcrypt decrypt-workspace` to update the plaintext',
77
- conflict: 'the plaintext and the bundle have both changed since they last agreed',
78
- 'not decrypted': 'run `dcrypt decrypt-workspace`',
79
- 'not encrypted': 'run `dcrypt encrypt-section`',
80
- unknown: 'this machine has no record of it; run `dcrypt decrypt-workspace` to compare',
81
- 'not downloaded': 'the bundle is a Git LFS pointer; run `git lfs pull`',
82
- 'bundle unreadable': 'restore the bundle from git, or replace it with `dcrypt encrypt-section --force`',
83
- 'plaintext unreadable': '',
84
- missing: 'there is no such folder and no such bundle',
85
- };
86
- /** What to say when the bundle is not encrypted to exactly the people in `recipients.txt`. */
87
- const recipientAdvice = ({ missingRecipients, extraRecipients }) => {
88
- const differences = [];
89
- if (missingRecipients.length) {
90
- differences.push(`${(0, text_1.count)(missingRecipients.length, 'recipient')} in recipients.txt cannot open it yet`);
91
- }
92
- if (extraRecipients.length) {
93
- differences.push(`it is still encrypted to ${(0, text_1.count)(extraRecipients.length, 'key')} no longer in recipients.txt`);
94
- }
95
- return differences.length ? `${differences.join(', and ')}; encrypt it again` : '';
96
- };
97
- /** One line on what a report means and what to do about it. Empty when there is nothing to do. */
98
- const adviceFor = (report) => [report.problem, ADVICE[report.state], recipientAdvice(report)].filter(Boolean).join('; ');
99
- exports.adviceFor = adviceFor;
@@ -1,29 +0,0 @@
1
- import { ByteStream } from '../utils/bytes';
2
- /** The largest file an 11-digit octal size field can describe: one byte under 8 GiB. */
3
- export declare const MAX_TAR_FILE_SIZE = 8589934591;
4
- /** A file to archive. `content` must yield exactly `size` bytes. */
5
- export interface TarFile {
6
- /** Path inside the archive, `/`-separated. */
7
- path: string;
8
- size: number;
9
- executable: boolean;
10
- content: ByteStream;
11
- }
12
- /** A file read back from an archive. `content` is only valid until the next entry is requested. */
13
- export interface TarEntry {
14
- path: string;
15
- size: number;
16
- executable: boolean;
17
- content: AsyncIterable<Uint8Array>;
18
- }
19
- /** Writes `files` as a tar archive, in the order given. */
20
- export declare function writeTar(files: Iterable<TarFile> | AsyncIterable<TarFile>): AsyncGenerator<Uint8Array>;
21
- /**
22
- * Reads a tar archive one file at a time. An entry's `content` has to be consumed before the
23
- * next entry is requested; whatever is left of it then is skipped.
24
- *
25
- * The generator only finishes once `source` itself has ended. When the source is a decryptor,
26
- * that is what makes it check its final chunk: an archive that completes normally came from a
27
- * ciphertext that was complete.
28
- */
29
- export declare function readTar(source: ByteStream): AsyncGenerator<TarEntry>;
package/workspace/tar.js DELETED
@@ -1,240 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_TAR_FILE_SIZE = void 0;
4
- exports.writeTar = writeTar;
5
- exports.readTar = readTar;
6
- const bytes_1 = require("../utils/bytes");
7
- const errors_1 = require("../utils/errors");
8
- /**
9
- * A deterministic subset of POSIX tar (ustar, plus a pax `path` record where a name does not fit).
10
- *
11
- * The same files always produce the same bytes: entries are written in the order given, and
12
- * every field that describes the machine rather than the content is fixed. There is no owner, no
13
- * group, no timestamp, and the mode is one of two values. Only regular files are stored.
14
- *
15
- * The output is ordinary tar. `dcrypt decrypt --in section.tar.dcrypt --out section.tar` followed
16
- * by `tar -xf` recovers a section without any of the code in this folder.
17
- */
18
- const BLOCK_SIZE = 512;
19
- const NAME_LENGTH = 100;
20
- const MAX_PAX_LENGTH = 64 * 1024;
21
- /** The largest file an 11-digit octal size field can describe: one byte under 8 GiB. */
22
- exports.MAX_TAR_FILE_SIZE = 0o77777777777;
23
- const TYPE_FILE = '0';
24
- const TYPE_PAX = 'x';
25
- const MODE_FILE = 0o644;
26
- const MODE_EXECUTABLE = 0o755;
27
- const OWNER_EXECUTE = 0o100;
28
- /** Offset and length of each header field this format reads or writes. */
29
- const FIELD = {
30
- name: [0, NAME_LENGTH],
31
- mode: [100, 8],
32
- uid: [108, 8],
33
- gid: [116, 8],
34
- size: [124, 12],
35
- mtime: [136, 12],
36
- checksum: [148, 8],
37
- type: [156, 1],
38
- magic: [257, 6],
39
- version: [263, 2],
40
- prefix: [345, 155],
41
- };
42
- const corrupt = (message) => new errors_1.CliError(`the archive is corrupt: ${message}`, errors_1.EXIT.corrupt);
43
- const paddingFor = (length) => (BLOCK_SIZE - (length % BLOCK_SIZE)) % BLOCK_SIZE;
44
- /** Sum of the header's bytes, with the checksum field itself counted as spaces. */
45
- const checksumOf = (block) => {
46
- const [start, length] = FIELD.checksum;
47
- let sum = 0;
48
- for (let i = 0; i < BLOCK_SIZE; i++) {
49
- sum += i >= start && i < start + length ? 0x20 : block[i];
50
- }
51
- return sum;
52
- };
53
- const octal = (value, [, length]) => value.toString(8).padStart(length - 1, '0') + '\0';
54
- const headerBlock = (name, size, mode, type) => {
55
- const block = Buffer.alloc(BLOCK_SIZE);
56
- const put = (field, value) => void block.write(value, field[0], 'latin1');
57
- put(FIELD.name, name);
58
- put(FIELD.mode, octal(mode, FIELD.mode));
59
- put(FIELD.uid, octal(0, FIELD.uid));
60
- put(FIELD.gid, octal(0, FIELD.gid));
61
- put(FIELD.size, octal(size, FIELD.size));
62
- put(FIELD.mtime, octal(0, FIELD.mtime));
63
- put(FIELD.type, type);
64
- put(FIELD.magic, 'ustar\0');
65
- put(FIELD.version, '00');
66
- put(FIELD.checksum, checksumOf(block).toString(8).padStart(6, '0') + '\0 ');
67
- return block;
68
- };
69
- /** True when `path` can be stored in the 100-byte name field as it is. */
70
- const fitsNameField = (path) => /^[\x20-\x7e]{1,100}$/.test(path);
71
- /** A pax record is `<length> <key>=<value>\n`, where the length counts its own digits. */
72
- const paxRecord = (key, value) => {
73
- const body = Buffer.from(` ${key}=${value}\n`, 'utf8');
74
- let length = body.length;
75
- while (String(length).length + body.length !== length) {
76
- length = String(length).length + body.length;
77
- }
78
- return Buffer.concat([Buffer.from(String(length), 'latin1'), body]);
79
- };
80
- /** The header blocks that introduce one file: a pax header first when the path needs one. */
81
- const entryHeader = ({ path, size, executable }) => {
82
- const mode = executable ? MODE_EXECUTABLE : MODE_FILE;
83
- if (fitsNameField(path))
84
- return headerBlock(path, size, mode, TYPE_FILE);
85
- const record = paxRecord('path', path);
86
- // What a reader without pax support would see: the tail of the path, in printable ASCII.
87
- const fallback = path.replace(/[^\x20-\x7e]/g, '_').slice(-NAME_LENGTH);
88
- return Buffer.concat([
89
- headerBlock('PaxHeader', record.length, MODE_FILE, TYPE_PAX),
90
- record,
91
- Buffer.alloc(paddingFor(record.length)),
92
- headerBlock(fallback, size, mode, TYPE_FILE),
93
- ]);
94
- };
95
- /** Writes `files` as a tar archive, in the order given. */
96
- async function* writeTar(files) {
97
- for await (const file of files) {
98
- if (!Number.isSafeInteger(file.size) || file.size < 0 || file.size > exports.MAX_TAR_FILE_SIZE) {
99
- throw new errors_1.CliError(`${file.path} is too large to archive (the limit is 8 GiB per file)`);
100
- }
101
- yield entryHeader(file);
102
- let written = 0;
103
- for await (const piece of file.content) {
104
- written += piece.length;
105
- if (written > file.size)
106
- break;
107
- yield piece;
108
- }
109
- if (written !== file.size) {
110
- throw new errors_1.CliError(`${file.path} changed size while it was being archived; run the command again`);
111
- }
112
- if (paddingFor(file.size))
113
- yield Buffer.alloc(paddingFor(file.size));
114
- }
115
- yield Buffer.alloc(2 * BLOCK_SIZE);
116
- }
117
- const takeBlock = async (reader) => {
118
- const held = await reader.fill(BLOCK_SIZE);
119
- if (held.length < BLOCK_SIZE)
120
- throw corrupt('it ends in the middle of a block');
121
- const block = held.subarray(0, BLOCK_SIZE);
122
- reader.skip(BLOCK_SIZE);
123
- return block;
124
- };
125
- /** Streams the next `count.remaining` bytes, keeping the count current as they are handed out. */
126
- async function* takeBytes(reader, count) {
127
- while (count.remaining > 0) {
128
- const held = await reader.fill(1);
129
- if (!held.length)
130
- throw corrupt('it ends in the middle of a file');
131
- const piece = held.subarray(0, Math.min(held.length, count.remaining));
132
- reader.skip(piece.length);
133
- count.remaining -= piece.length;
134
- yield piece;
135
- }
136
- }
137
- const skipBytes = async (reader, length) => {
138
- for await (const piece of takeBytes(reader, { remaining: length }))
139
- void piece;
140
- };
141
- const textOf = (block, [offset, length]) => {
142
- const end = block.indexOf(0, offset);
143
- const stop = end === -1 || end > offset + length ? offset + length : end;
144
- return block.toString('utf8', offset, stop);
145
- };
146
- const numberOf = (block, field, name) => {
147
- const digits = textOf(block, field).trim();
148
- if (!/^[0-7]*$/.test(digits))
149
- throw corrupt(`a header has an unreadable ${name}`);
150
- return parseInt(digits || '0', 8);
151
- };
152
- const parseHeader = (block) => {
153
- if (textOf(block, FIELD.magic) !== 'ustar')
154
- throw corrupt('a header is not in ustar format');
155
- if (numberOf(block, FIELD.checksum, 'checksum') !== checksumOf(block)) {
156
- throw corrupt('a header fails its checksum');
157
- }
158
- const name = textOf(block, FIELD.name);
159
- const prefix = textOf(block, FIELD.prefix);
160
- return {
161
- path: prefix ? `${prefix}/${name}` : name,
162
- size: numberOf(block, FIELD.size, 'size'),
163
- mode: numberOf(block, FIELD.mode, 'mode'),
164
- // Archives older than ustar mark a regular file with a NUL instead of "0".
165
- type: textOf(block, FIELD.type) || TYPE_FILE,
166
- };
167
- };
168
- /** Reads the one pax record this format writes. Anything else is refused, not skipped. */
169
- const paxPath = (data) => {
170
- let path;
171
- for (let offset = 0; offset < data.length;) {
172
- const space = data.indexOf(0x20, offset);
173
- const length = space === -1 ? NaN : Number(data.toString('latin1', offset, space));
174
- const end = offset + length;
175
- if (!Number.isInteger(length) || end <= space + 1 || end > data.length || data[end - 1] !== 0x0a) {
176
- throw corrupt('an extended header is malformed');
177
- }
178
- const record = data.toString('utf8', space + 1, end - 1);
179
- const equals = record.indexOf('=');
180
- if (record.slice(0, Math.max(equals, 0)) !== 'path') {
181
- throw corrupt('an extended header carries something other than a path');
182
- }
183
- path = record.slice(equals + 1);
184
- offset = end;
185
- }
186
- if (path === undefined)
187
- throw corrupt('an extended header is empty');
188
- return path;
189
- };
190
- const readPaxPath = async (reader, size) => {
191
- if (size > MAX_PAX_LENGTH)
192
- throw corrupt('an extended header is implausibly large');
193
- const pieces = [];
194
- for await (const piece of takeBytes(reader, { remaining: size }))
195
- pieces.push(piece);
196
- await skipBytes(reader, paddingFor(size));
197
- return paxPath(Buffer.concat(pieces));
198
- };
199
- /**
200
- * Reads a tar archive one file at a time. An entry's `content` has to be consumed before the
201
- * next entry is requested; whatever is left of it then is skipped.
202
- *
203
- * The generator only finishes once `source` itself has ended. When the source is a decryptor,
204
- * that is what makes it check its final chunk: an archive that completes normally came from a
205
- * ciphertext that was complete.
206
- */
207
- async function* readTar(source) {
208
- const reader = new bytes_1.ByteReader(source);
209
- let path;
210
- for (;;) {
211
- const block = await takeBlock(reader);
212
- if (block.every((byte) => byte === 0))
213
- break;
214
- const header = parseHeader(block);
215
- if (header.type === TYPE_PAX) {
216
- path = await readPaxPath(reader, header.size);
217
- continue;
218
- }
219
- if (header.type !== TYPE_FILE) {
220
- throw corrupt(`"${header.path}" is not a regular file (links and devices are not accepted)`);
221
- }
222
- const count = { remaining: header.size };
223
- yield {
224
- path: path ?? header.path,
225
- size: header.size,
226
- executable: (header.mode & OWNER_EXECUTE) !== 0,
227
- content: takeBytes(reader, count),
228
- };
229
- path = undefined;
230
- await skipBytes(reader, count.remaining + paddingFor(header.size));
231
- }
232
- if (path !== undefined)
233
- throw corrupt('an extended header is not followed by a file');
234
- // The end marker is two empty blocks; nothing but padding may follow it.
235
- do {
236
- if (reader.buffered.some((byte) => byte !== 0))
237
- throw corrupt('data follows the end marker');
238
- reader.skip(reader.buffered.length);
239
- } while (await reader.more());
240
- }