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
package/esm/utils/temp.js DELETED
@@ -1,51 +0,0 @@
1
- import { randomBytes } from 'crypto';
2
- import { rmSync } from 'fs';
3
- import { basename, dirname, join } from 'path';
4
- /**
5
- * Temporary files and directories that must not outlive the command.
6
- *
7
- * Output is always built next to its destination and renamed into place, so an interrupted run
8
- * leaves the destination exactly as it was. What an interrupt would leave behind is the
9
- * half-written temporary itself, which may hold plaintext; everything registered here is removed
10
- * on Ctrl-C and on termination.
11
- */
12
- const live = new Set();
13
- const remove = (path) => {
14
- try {
15
- rmSync(path, { recursive: true, force: true });
16
- }
17
- catch {
18
- // best effort: there is nothing useful to do about a temp file that will not delete
19
- }
20
- };
21
- const onSignal = (signal) => {
22
- for (const path of live)
23
- remove(path);
24
- live.clear();
25
- process.exit(signal === 'SIGINT' ? 130 : 143);
26
- };
27
- /** A sibling path of `target`, so that renaming onto `target` never crosses a filesystem. */
28
- export const tempPathFor = (target) => join(dirname(target), `.${basename(target)}.dcrypt-tmp-${randomBytes(6).toString('hex')}`);
29
- /** True for names produced by {@link tempPathFor}. */
30
- export const isTempName = (name) => /\.dcrypt-tmp-[0-9a-f]{12}$/.test(name);
31
- /** Registers `path` for removal if the process is interrupted. */
32
- export const trackTemp = (path) => {
33
- if (live.size === 0) {
34
- process.on('SIGINT', onSignal);
35
- process.on('SIGTERM', onSignal);
36
- }
37
- live.add(path);
38
- };
39
- /** Forgets `path`: call once it has been renamed into place or removed. */
40
- export const untrackTemp = (path) => {
41
- live.delete(path);
42
- if (live.size === 0) {
43
- process.removeListener('SIGINT', onSignal);
44
- process.removeListener('SIGTERM', onSignal);
45
- }
46
- };
47
- /** Removes a temporary path now and forgets it. */
48
- export const discardTemp = (path) => {
49
- remove(path);
50
- untrackTemp(path);
51
- };
package/esm/utils/text.js DELETED
@@ -1,2 +0,0 @@
1
- /** "1 file", "3 files": a number with its noun, pluralised the regular way. */
2
- export const count = (n, noun) => `${n} ${noun}${n === 1 ? '' : 's'}`;
@@ -1,239 +0,0 @@
1
- import { createIdentityFileDecryptor, createRecipientFileEncryptor, fileRecipients, } from '@decryption/keys';
2
- import { createHash, randomBytes } from 'crypto';
3
- import { createReadStream, existsSync, readdirSync, renameSync, rmSync } from 'fs';
4
- import { mkdir, open } from 'fs/promises';
5
- import { basename, dirname, join } from 'path';
6
- import { pipeline } from 'stream/promises';
7
- import { ByteReader, chainBytes, IO_CHUNK_SIZE, syncDirectory, syncFile, transformBytes, writeFileAtomically, } from '../utils/bytes';
8
- import { CliError, EXIT } from '../utils/errors';
9
- import { readFileHeader } from '../utils/header';
10
- import { discardTemp, isTempName, tempPathFor, trackTemp, untrackTemp } from '../utils/temp';
11
- import { REPLACED_MARKER } from './layout';
12
- import { digestOf, MANIFEST_PATH, parseManifest, serializeManifest, } from './manifest';
13
- import { readTar, writeTar } from './tar';
14
- /**
15
- * A bundle is a section's files as one encrypted file: a deterministic tar whose first entry is
16
- * the manifest, inside the streamed envelope `dcrypt encrypt --binary --recipient` writes.
17
- *
18
- * Everything about the section is inside the encryption: file names, sizes, how many files there
19
- * are. From outside, a bundle shows its own size and the fingerprints of its recipients.
20
- *
21
- * A bundle says nothing about who made it. Recipient keys are public, so anyone who has them can
22
- * produce a bundle that decrypts cleanly. That is why extraction trusts nothing in one: every
23
- * path is checked before a byte is written, and nothing is written outside a fresh folder.
24
- */
25
- const LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/';
26
- /** Far more than any real manifest; it is held in memory, so it has a bound. */
27
- const MAX_MANIFEST_SIZE = 256 * 1024 * 1024;
28
- /** The bundle on disk is a Git LFS pointer: the real file has not been downloaded. */
29
- export class LfsPointerError extends CliError {
30
- constructor(path) {
31
- super(`${path} is a Git LFS pointer, not the bundle itself; run \`git lfs pull\``, EXIT.notFound);
32
- this.name = 'LfsPointerError';
33
- }
34
- }
35
- const mismatch = (message) => new CliError(`the bundle does not match its manifest: ${message}`, EXIT.corrupt);
36
- const readFile = (path) => createReadStream(path, { highWaterMark: IO_CHUNK_SIZE });
37
- /** Passes bytes through unchanged, feeding each piece to `hash` on the way. */
38
- async function* hashing(source, hash) {
39
- for await (const piece of source) {
40
- hash.update(piece);
41
- yield piece;
42
- }
43
- }
44
- /** Reads what a bundle shows without a key: its hash, and who can open it. */
45
- export const inspectBundle = async (path) => {
46
- const input = readFile(path);
47
- const hash = createHash('sha256');
48
- try {
49
- const reader = new ByteReader(hashing(input, hash));
50
- const head = await reader.fill(LFS_POINTER_PREFIX.length);
51
- if (head.toString('latin1').startsWith(LFS_POINTER_PREFIX))
52
- throw new LfsPointerError(path);
53
- const header = await readFileHeader(reader);
54
- for await (const piece of reader.rest())
55
- void piece;
56
- return { sha256: hash.digest('hex'), recipients: fileRecipients(header) };
57
- }
58
- finally {
59
- input.destroy();
60
- }
61
- };
62
- /** A file's bytes, with a check at the end that they are still the ones the manifest describes. */
63
- async function* unchanged(file) {
64
- const hash = createHash('sha256');
65
- yield* hashing(readFile(file.source), hash);
66
- if (hash.digest('hex') !== file.sha256) {
67
- throw new CliError(`${file.source} changed while it was being encrypted; run the command again`);
68
- }
69
- }
70
- /** The archive's entries: the manifest first, then every file in manifest order. */
71
- function* archiveEntries(snapshot) {
72
- const manifest = serializeManifest(snapshot.manifest);
73
- yield { path: MANIFEST_PATH, size: manifest.length, executable: false, content: [manifest] };
74
- for (const file of snapshot.files) {
75
- yield { path: file.path, size: file.size, executable: file.executable, content: unchanged(file) };
76
- }
77
- }
78
- /**
79
- * Encrypts a section to `recipients` and replaces its bundle atomically. Resolves to the new
80
- * bundle's SHA-256. If a file changes underneath it, the old bundle is left as it was.
81
- */
82
- export const encryptSection = async (section, snapshot, recipients) => {
83
- const { header, stream } = createRecipientFileEncryptor(recipients);
84
- const hash = createHash('sha256');
85
- try {
86
- const archive = transformBytes(writeTar(archiveEntries(snapshot)), stream);
87
- await writeFileAtomically(section.bundle, hashing(chainBytes([header], archive), hash));
88
- }
89
- finally {
90
- stream.destroy();
91
- }
92
- return hash.digest('hex');
93
- };
94
- const readManifest = async (entry) => {
95
- if (entry.path !== MANIFEST_PATH)
96
- throw mismatch('it does not begin with one');
97
- if (entry.size > MAX_MANIFEST_SIZE)
98
- throw mismatch('the manifest is implausibly large');
99
- const pieces = [];
100
- for await (const piece of entry.content)
101
- pieces.push(piece);
102
- return parseManifest(Buffer.concat(pieces));
103
- };
104
- /** Writes one archive entry to its place under `directory`, and checks it against the manifest. */
105
- const writeEntry = async (directory, entry, expected) => {
106
- const target = join(directory, ...expected.path.split('/'));
107
- const hash = createHash('sha256');
108
- const handle = await mkdir(dirname(target), { recursive: true, mode: 0o700 })
109
- // "wx" refuses a name that is already there: two paths the file system considers the same.
110
- .then(() => open(target, 'wx', expected.executable ? 0o700 : 0o600))
111
- .catch((error) => {
112
- throw new CliError(`cannot create "${expected.path}" (${error.code ?? 'error'}); two paths in the bundle may be the same on this file system`, EXIT.corrupt);
113
- });
114
- await pipeline(hashing(entry.content, hash), handle.createWriteStream());
115
- if (hash.digest('hex') !== expected.sha256) {
116
- throw mismatch(`"${expected.path}" does not have the content it lists`);
117
- }
118
- };
119
- /**
120
- * Writes an archive's files under `directory`, accepting exactly what the manifest lists, in the
121
- * order it lists it. Paths come from the manifest, which {@link parseManifest} has vetted.
122
- */
123
- const extractArchive = async (entries, directory) => {
124
- let manifest;
125
- let index = 0;
126
- for await (const entry of entries) {
127
- if (!manifest) {
128
- manifest = await readManifest(entry);
129
- continue;
130
- }
131
- const expected = manifest.files[index++];
132
- const listed = expected !== undefined &&
133
- entry.path === expected.path &&
134
- entry.size === expected.size &&
135
- entry.executable === expected.executable;
136
- if (!listed)
137
- throw mismatch(`"${entry.path}" is not the file it lists next`);
138
- await writeEntry(directory, entry, expected);
139
- }
140
- if (!manifest)
141
- throw mismatch('it is empty');
142
- if (index !== manifest.files.length)
143
- throw mismatch('files it lists are missing');
144
- return manifest;
145
- };
146
- /**
147
- * Forces an extracted folder to disk: every file, then every folder, before it may replace
148
- * anything. One pass at the end, not a sync as each file is closed: that waits for the device
149
- * once per file, milliseconds each, where this pass costs next to nothing after its first sync.
150
- */
151
- const syncExtraction = async (directory, manifest) => {
152
- const folders = new Set([directory]);
153
- for (const { path } of manifest.files) {
154
- const target = join(directory, ...path.split('/'));
155
- await syncFile(target);
156
- for (let folder = dirname(target); !folders.has(folder); folder = dirname(folder))
157
- folders.add(folder);
158
- }
159
- for (const folder of folders)
160
- await syncDirectory(folder);
161
- };
162
- /**
163
- * Decrypts a bundle into a new folder beside the section's own, which is not touched.
164
- *
165
- * It resolves only once every chunk has authenticated, the ciphertext is known to be complete,
166
- * and every file matches the manifest. On any failure the new folder is removed and the error is
167
- * rethrown: there is no partial result.
168
- */
169
- export const extractSection = async (section, identity) => {
170
- const directory = tempPathFor(section.directory);
171
- await mkdir(directory, { mode: 0o700 });
172
- trackTemp(directory);
173
- const input = readFile(section.bundle);
174
- const hash = createHash('sha256');
175
- let decryptor;
176
- try {
177
- const reader = new ByteReader(hashing(input, hash));
178
- decryptor = createIdentityFileDecryptor(await readFileHeader(reader), identity);
179
- const archive = readTar(transformBytes(reader.rest(), decryptor));
180
- const manifest = await extractArchive(archive, directory);
181
- await syncExtraction(directory, manifest);
182
- return { directory, manifest, digest: digestOf(manifest), bundle: hash.digest('hex') };
183
- }
184
- catch (error) {
185
- discardTemp(directory);
186
- throw error;
187
- }
188
- finally {
189
- decryptor?.destroy();
190
- input.destroy();
191
- }
192
- };
193
- const setAsidePathFor = (directory) => join(dirname(directory), `.${basename(directory)}${REPLACED_MARKER}${randomBytes(6).toString('hex')}`);
194
- /**
195
- * Makes an extracted folder the section's plaintext, replacing what was there.
196
- *
197
- * The two renames run back to back without returning to the event loop, so Ctrl-C cannot land
198
- * between them. If the machine dies there instead, the previous plaintext is still on disk under
199
- * its set-aside name, and {@link recoverSection} puts it back.
200
- */
201
- export const installExtraction = async (section, extraction) => {
202
- const setAside = existsSync(section.directory) ? setAsidePathFor(section.directory) : undefined;
203
- if (setAside)
204
- renameSync(section.directory, setAside);
205
- try {
206
- renameSync(extraction.directory, section.directory);
207
- }
208
- catch (error) {
209
- if (setAside)
210
- renameSync(setAside, section.directory);
211
- discardTemp(extraction.directory);
212
- throw error;
213
- }
214
- untrackTemp(extraction.directory);
215
- // The swap is on disk before the old plaintext goes, and before anyone records it as done.
216
- await syncDirectory(dirname(section.directory));
217
- if (setAside)
218
- rmSync(setAside, { recursive: true, force: true });
219
- };
220
- /**
221
- * Cleans up after a run that was killed: restores a section's plaintext if it had been set aside
222
- * and nothing took its place, and removes half-written leftovers. Returns true if it restored.
223
- */
224
- export const recoverSection = (section) => {
225
- const parent = dirname(section.directory);
226
- if (!existsSync(parent))
227
- return false;
228
- const own = (name, target) => name.startsWith(`.${basename(target)}.dcrypt-`);
229
- const names = readdirSync(parent);
230
- const setAside = names.filter((name) => own(name, section.directory) && name.includes(REPLACED_MARKER));
231
- const temporary = names.filter((name) => isTempName(name) && (own(name, section.directory) || own(name, section.bundle)));
232
- const restored = !existsSync(section.directory) && setAside.length > 0;
233
- if (restored)
234
- renameSync(join(parent, setAside.shift()), section.directory);
235
- for (const name of [...setAside, ...temporary]) {
236
- rmSync(join(parent, name), { recursive: true, force: true });
237
- }
238
- return restored;
239
- };
@@ -1,104 +0,0 @@
1
- import { existsSync } from 'fs';
2
- import { messageFor } from '../utils/errors';
3
- import { readRecipientsFile } from '../utils/recipients';
4
- import { count } from '../utils/text';
5
- import { attributeOf, ignoredPaths, isRepository } from './git';
6
- import { isHookInstalled, runGuard } from './guard';
7
- import { BUNDLE_SUFFIX, discoverSections, STATE_DIRECTORY } from './layout';
8
- import { fingerprintOf, isRecovery, NO_RECOVERY_WARNING, ownFingerprint } from './recipients';
9
- import { readState } from './state';
10
- import { adviceFor, inspectSection } from './status';
11
- /**
12
- * `dcrypt doctor`: everything that should be true of a machine and a workspace before either is
13
- * trusted with a section. It reads; it changes nothing, and it never asks for a passphrase.
14
- */
15
- const MINIMUM_NODE_MAJOR = 20;
16
- const check = (name, level, message) => ({ name, level, message });
17
- const nodeCheck = () => {
18
- const version = process.versions.node;
19
- return Number(version.split('.')[0]) >= MINIMUM_NODE_MAJOR
20
- ? check('node', 'ok', `Node.js ${version}`)
21
- : check('node', 'fail', `Node.js ${version} is too old; ${MINIMUM_NODE_MAJOR} or newer is needed`);
22
- };
23
- const identityCheck = (mine) => mine
24
- ? check('identity', 'ok', `this machine's identity is ${mine}`)
25
- : check('identity', 'fail', 'no identity on this machine; run `dcrypt keys generate`');
26
- const readRecipients = (workspace) => {
27
- if (!existsSync(workspace.recipientsFile)) {
28
- return check('recipients', 'fail', `no recipients.txt in ${workspace.root}`);
29
- }
30
- try {
31
- return readRecipientsFile(workspace.recipientsFile);
32
- }
33
- catch (error) {
34
- return check('recipients', 'fail', messageFor(error));
35
- }
36
- };
37
- const recipientChecks = (entries, mine) => {
38
- if (!entries.length)
39
- return [check('recipients', 'fail', 'recipients.txt lists no recipients')];
40
- const checks = [check('recipients', 'ok', `recipients.txt lists ${count(entries.length, 'recipient')}`)];
41
- checks.push(entries.some(isRecovery)
42
- ? check('recovery', 'ok', 'there is a recovery recipient')
43
- : check('recovery', 'warn', NO_RECOVERY_WARNING));
44
- if (entries.length === 1) {
45
- checks.push(check('recipients', 'warn', 'there is only one recipient: one lost key loses everything'));
46
- }
47
- if (mine && !entries.some((entry) => fingerprintOf(entry.recipient) === mine)) {
48
- checks.push(check('recipients', 'warn', `this machine's identity (${mine}) is not in recipients.txt`));
49
- }
50
- return checks;
51
- };
52
- const sectionChecks = async (workspace, sections, recipients) => {
53
- if (!sections.length)
54
- return [check('sections', 'ok', 'no sections are encrypted yet')];
55
- const state = readState(workspace);
56
- const checks = [];
57
- for (const section of sections) {
58
- const report = await inspectSection(section, state[section.name], recipients);
59
- const advice = adviceFor(report);
60
- const level = report.problem ? 'fail' : advice ? 'warn' : 'ok';
61
- checks.push(check(`section ${section.name}`, level, advice ? `${report.state}: ${advice}` : report.state));
62
- }
63
- return checks;
64
- };
65
- const isIgnored = (workspace, path) => ignoredPaths(workspace.root, [path]).length > 0;
66
- const repositoryChecks = async (workspace, sections) => {
67
- if (!isRepository(workspace.root)) {
68
- return [check('git', 'warn', 'not a git repository: nothing here checks what gets committed')];
69
- }
70
- const checks = [
71
- isHookInstalled(workspace)
72
- ? check('guard', 'ok', 'the pre-commit guard is installed')
73
- : check('guard', 'warn', 'no pre-commit guard; run `dcrypt guard install`'),
74
- ];
75
- const exposed = sections.filter((section) => !isIgnored(workspace, `${section.name}/file`));
76
- checks.push(exposed.length
77
- ? check('gitignore', 'fail', `git does not ignore the plaintext of: ${exposed.map((section) => section.name).join(', ')} (see \`dcrypt guard snippet gitignore\`)`)
78
- : check('gitignore', 'ok', 'git ignores the plaintext of every section'));
79
- if (!isIgnored(workspace, `${STATE_DIRECTORY}/state.json`)) {
80
- checks.push(check('gitignore', 'warn', `git does not ignore ${STATE_DIRECTORY}/`));
81
- }
82
- const outsideLfs = sections.filter((section) => attributeOf(workspace.root, 'filter', section.name + BUNDLE_SUFFIX) !== 'lfs');
83
- if (outsideLfs.length) {
84
- checks.push(check('lfs', 'warn', 'bundles are not stored with Git LFS (see `dcrypt guard snippet gitattributes`)'));
85
- }
86
- const { violations } = await runGuard(workspace, 'all');
87
- checks.push(violations.length
88
- ? check('tracked files', 'fail', `${count(violations.length, 'tracked file')} should not be in the repository; run \`dcrypt guard --all\``)
89
- : check('tracked files', 'ok', 'nothing tracked is plaintext'));
90
- return checks;
91
- };
92
- export const runDoctor = async (workspace) => {
93
- const mine = ownFingerprint();
94
- const recipients = readRecipients(workspace);
95
- const entries = Array.isArray(recipients) ? recipients : undefined;
96
- const sections = discoverSections(workspace);
97
- return [
98
- nodeCheck(),
99
- identityCheck(mine),
100
- ...(entries ? recipientChecks(entries, mine) : [recipients]),
101
- ...(await sectionChecks(workspace, sections, entries?.map((entry) => fingerprintOf(entry.recipient)))),
102
- ...(await repositoryChecks(workspace, sections)),
103
- ];
104
- };
@@ -1,72 +0,0 @@
1
- import { spawn, spawnSync } from 'child_process';
2
- import { realpathSync } from 'fs';
3
- import { resolve } from 'path';
4
- import { ByteReader } from '../utils/bytes';
5
- import { CliError } from '../utils/errors';
6
- /**
7
- * The few questions the guard and `doctor` ask of git, each answered by git itself. Nothing here
8
- * changes a repository. Paths are relative to `root`, which is the workspace root.
9
- */
10
- const MAX_OUTPUT = 256 * 1024 * 1024;
11
- const git = (root, args, input) => {
12
- const result = spawnSync('git', args, { cwd: root, input, encoding: 'utf8', maxBuffer: MAX_OUTPUT });
13
- if (result.error)
14
- throw new CliError(`cannot run git: ${result.error.message}`);
15
- return { status: result.status ?? 1, stdout: result.stdout };
16
- };
17
- const gitOrThrow = (root, args) => {
18
- const { status, stdout } = git(root, args);
19
- if (status !== 0)
20
- throw new CliError(`git ${args[0]} failed in ${root}`);
21
- return stdout;
22
- };
23
- const nulSeparated = (output) => output.split('\0').filter(Boolean);
24
- export const isRepository = (root) => git(root, ['rev-parse', '--is-inside-work-tree']).stdout.trim() === 'true';
25
- /** The top of the working tree `root` is in. */
26
- export const repositoryRoot = (root) => realpathSync(gitOrThrow(root, ['rev-parse', '--show-toplevel']).trim());
27
- /** Where this repository's hooks live, honouring `core.hooksPath`. */
28
- export const hooksDirectory = (root) => resolve(root, gitOrThrow(root, ['rev-parse', '--git-path', 'hooks']).trim());
29
- /** Files added or changed in the index: what the next commit would record. */
30
- export const stagedPaths = (root) => nulSeparated(gitOrThrow(root, ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '--relative', '-z']));
31
- /** Every file in the index. */
32
- export const trackedPaths = (root) => nulSeparated(gitOrThrow(root, ['ls-files', '-z']));
33
- /**
34
- * The subset of `paths` the ignore rules match. `--no-index` asks about the rules alone, so a
35
- * file that was force-added, and is therefore tracked, is still reported.
36
- */
37
- export const ignoredPaths = (root, paths) => {
38
- if (!paths.length)
39
- return [];
40
- const { status, stdout } = git(root, ['check-ignore', '--no-index', '-z', '--stdin'], paths.join('\0'));
41
- // 0: some are ignored. 1: none are. Anything else is git failing.
42
- if (status > 1)
43
- throw new CliError(`git check-ignore failed in ${root}`);
44
- return nulSeparated(stdout);
45
- };
46
- /** The value of a gitattribute for a path: "lfs", "unspecified", … */
47
- export const attributeOf = (root, attribute, path) => gitOrThrow(root, ['check-attr', attribute, '--', path]).trim().split(': ').pop() ?? '';
48
- /**
49
- * The first bytes of a file as it is in the index: what a commit would record, which is not
50
- * always what is in the working tree. Only the head is read, however large the blob.
51
- */
52
- export const indexedHead = async (root, path, length) => {
53
- const child = spawn('git', ['cat-file', 'blob', `:./${path}`], {
54
- cwd: root,
55
- stdio: ['ignore', 'pipe', 'ignore'],
56
- });
57
- const exited = new Promise((resolve) => {
58
- child.on('error', () => resolve(null));
59
- child.on('close', resolve);
60
- });
61
- try {
62
- const head = Buffer.from((await new ByteReader(child.stdout).fill(length)).subarray(0, length));
63
- // Nothing read is an empty file only if git says so: a git that failed must not pass for one.
64
- if (!head.length && (await exited) !== 0)
65
- throw new CliError(`cannot read ${path} from the git index`);
66
- return head;
67
- }
68
- finally {
69
- child.stdout.destroy();
70
- child.kill();
71
- }
72
- };
@@ -1,111 +0,0 @@
1
- import { ARMOR_PREFIX, FILE_ARMOR_PREFIX, MAGIC } from '@decryption/core';
2
- import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, writeFileSync, } from 'fs';
3
- import { join } from 'path';
4
- import { CliError } from '../utils/errors';
5
- import { hooksDirectory, ignoredPaths, indexedHead, repositoryRoot, stagedPaths, trackedPaths } from './git';
6
- import { BUNDLE_SUFFIX, discoverSections } from './layout';
7
- import { HOOK_MARKER, SNIPPETS } from './snippets';
8
- /**
9
- * The pre-commit guard: looks at what a commit would record and refuses three things.
10
- *
11
- * 1. A file inside a section's plaintext folder.
12
- * 2. A `*.dcrypt` file that is not encrypted: a plain file given the name by mistake.
13
- * 3. A file the ignore rules cover, which can only be staged by forcing it past them.
14
- *
15
- * It reads the index, not the working tree: what matters is what would be committed.
16
- */
17
- const ENCRYPTED_SUFFIX = '.dcrypt';
18
- const LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/';
19
- const HEAD_LENGTH = 64;
20
- const startsWith = (head, prefix) => head.subarray(0, prefix.length).equals(Buffer.from(prefix));
21
- const isEnvelope = (head) => startsWith(head, MAGIC) || startsWith(head, ARMOR_PREFIX) || startsWith(head, FILE_ARMOR_PREFIX);
22
- const fileHead = (path) => {
23
- if (!existsSync(path))
24
- return undefined;
25
- const head = Buffer.alloc(HEAD_LENGTH);
26
- const descriptor = openSync(path, 'r');
27
- try {
28
- return head.subarray(0, readSync(descriptor, head, 0, HEAD_LENGTH, 0));
29
- }
30
- finally {
31
- closeSync(descriptor);
32
- }
33
- };
34
- /**
35
- * True when what would be committed at `path` is ciphertext. With Git LFS the index holds a
36
- * pointer, so the file the pointer stands for is checked instead, when it is here to check.
37
- */
38
- const isEncrypted = async (root, path) => {
39
- const head = await indexedHead(root, path, HEAD_LENGTH);
40
- if (!startsWith(head, LFS_POINTER_PREFIX))
41
- return isEnvelope(head);
42
- const local = fileHead(join(root, path));
43
- return local === undefined || startsWith(local, LFS_POINTER_PREFIX) || isEnvelope(local);
44
- };
45
- /** Names of every section the repository knows: bundles on disk, staged, or tracked. */
46
- const sectionNames = (workspace, paths) => {
47
- const fromGit = [...paths, ...trackedPaths(workspace.root)]
48
- .filter((path) => path.endsWith(BUNDLE_SUFFIX))
49
- .map((path) => path.slice(0, -BUNDLE_SUFFIX.length));
50
- const onDisk = discoverSections(workspace).map((section) => section.name);
51
- return [...new Set([...fromGit, ...onDisk])];
52
- };
53
- /** Checks the given paths (relative to the workspace root) as they stand in the index. */
54
- export const checkPaths = async (workspace, paths) => {
55
- const sections = sectionNames(workspace, paths);
56
- const ignored = new Set(ignoredPaths(workspace.root, paths));
57
- const violations = [];
58
- for (const path of paths) {
59
- const section = sections.find((name) => path.startsWith(`${name}/`));
60
- if (section) {
61
- violations.push({
62
- path,
63
- rule: 'plaintext',
64
- message: `plaintext of the encrypted section "${section}"; commit ${section}${BUNDLE_SUFFIX} instead`,
65
- });
66
- }
67
- else if (path.endsWith(ENCRYPTED_SUFFIX) && !(await isEncrypted(workspace.root, path))) {
68
- violations.push({
69
- path,
70
- rule: 'not encrypted',
71
- message: `named ${ENCRYPTED_SUFFIX} but its content is not a dcrypt envelope`,
72
- });
73
- }
74
- else if (ignored.has(path)) {
75
- violations.push({
76
- path,
77
- rule: 'ignored',
78
- message: 'covered by .gitignore, so it was added by force; it is not on the allow-list',
79
- });
80
- }
81
- }
82
- return violations;
83
- };
84
- /** Runs the guard over what is staged, or over everything tracked. */
85
- export const runGuard = async (workspace, scope) => {
86
- const paths = scope === 'staged' ? stagedPaths(workspace.root) : trackedPaths(workspace.root);
87
- return { scope, checked: paths.length, violations: await checkPaths(workspace, paths) };
88
- };
89
- const hookPath = (workspace) => join(hooksDirectory(workspace.root), 'pre-commit');
90
- /** True when this repository's pre-commit hook is the one `dcrypt guard install` writes. */
91
- export const isHookInstalled = (workspace) => {
92
- const path = hookPath(workspace);
93
- return existsSync(path) && readFileSync(path, 'utf8').includes(HOOK_MARKER);
94
- };
95
- /**
96
- * Installs the pre-commit hook. A hook that is already there and is not ours is left alone
97
- * unless `force` is set.
98
- */
99
- export const installHook = (workspace, force = false) => {
100
- if (repositoryRoot(workspace.root) !== realpathSync(workspace.root)) {
101
- throw new CliError(`the workspace ${workspace.root} is not the top of its git repository; the hook runs from the top, so call "dcrypt guard --staged --workspace <dir>" from your own pre-commit hook instead`);
102
- }
103
- const path = hookPath(workspace);
104
- if (existsSync(path) && !isHookInstalled(workspace) && !force) {
105
- throw new CliError(`${path} already exists and was not written by dcrypt; add "dcrypt guard --staged" to it, or pass --force to replace it`);
106
- }
107
- mkdirSync(hooksDirectory(workspace.root), { recursive: true });
108
- writeFileSync(path, SNIPPETS.hook.text);
109
- chmodSync(path, 0o755);
110
- return path;
111
- };