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,106 +0,0 @@
1
- import { existsSync, readdirSync, statSync } from 'fs';
2
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
3
- import { CliError, EXIT } from '../utils/errors';
4
- import { isTempName } from '../utils/temp';
5
- /**
6
- * Where things are in a workspace.
7
- *
8
- * ```text
9
- * <root>/
10
- * recipients.txt who can decrypt (public keys; committed)
11
- * finance.tar.dcrypt a section, encrypted (committed)
12
- * finance/ the same section, decrypted (never committed)
13
- * .dcrypt/state.json what this machine last encrypted or decrypted (never committed)
14
- * ```
15
- *
16
- * A section is a folder and the bundle beside it; the bundle's name is the folder's name plus
17
- * `.tar.dcrypt`. Sections may sit in sub-folders, but not inside one another.
18
- */
19
- export const BUNDLE_SUFFIX = '.tar.dcrypt';
20
- export const RECIPIENTS_FILE = 'recipients.txt';
21
- export const STATE_DIRECTORY = '.dcrypt';
22
- /** Marks the previous plaintext of a section while a new one is being swapped in. */
23
- export const REPLACED_MARKER = '.dcrypt-old-';
24
- /** True for the temporary and set-aside folders a decryption works in. */
25
- export const isLeftoverName = (name) => isTempName(name) || name.includes(REPLACED_MARKER);
26
- /** Folders that are never searched for bundles. */
27
- const SKIPPED_DIRECTORIES = new Set(['.git', 'node_modules', STATE_DIRECTORY]);
28
- const isDirectory = (path) => {
29
- try {
30
- return statSync(path).isDirectory();
31
- }
32
- catch {
33
- return false;
34
- }
35
- };
36
- const isInside = (parent, child) => {
37
- const path = relative(parent, child);
38
- return path === '' || (!path.startsWith('..') && !isAbsolute(path));
39
- };
40
- /** The nearest folder, from `start` upwards, that has a recipients file. */
41
- const findRoot = (start) => {
42
- for (let directory = start;; directory = dirname(directory)) {
43
- if (existsSync(join(directory, RECIPIENTS_FILE)))
44
- return directory;
45
- if (dirname(directory) === directory)
46
- return undefined;
47
- }
48
- };
49
- /**
50
- * The workspace a command applies to: `--workspace <dir>`, otherwise the nearest folder upwards
51
- * that has a `recipients.txt`, otherwise the current folder.
52
- */
53
- export const findWorkspace = (argv) => {
54
- const given = argv.workspace;
55
- if (given !== undefined && (typeof given !== 'string' || !isDirectory(given))) {
56
- throw new CliError(`--workspace ${String(given)} is not a folder`, EXIT.notFound);
57
- }
58
- const root = given ? resolve(given) : (findRoot(process.cwd()) ?? process.cwd());
59
- return { root, recipientsFile: join(root, RECIPIENTS_FILE) };
60
- };
61
- const sectionAt = ({ root }, directory) => ({
62
- name: relative(root, directory).split(sep).join('/'),
63
- directory,
64
- bundle: directory + BUNDLE_SUFFIX,
65
- });
66
- /**
67
- * The section a user named. The folder and the bundle are both accepted (`finance`, `finance/`,
68
- * `finance.tar.dcrypt`), relative to the current folder when that is inside the workspace and to
69
- * the workspace root otherwise.
70
- */
71
- export const resolveSection = (workspace, name) => {
72
- const base = isInside(workspace.root, process.cwd()) ? process.cwd() : workspace.root;
73
- const target = resolve(base, name.endsWith(BUNDLE_SUFFIX) ? name.slice(0, -BUNDLE_SUFFIX.length) : name);
74
- if (target === workspace.root || !isInside(workspace.root, target)) {
75
- throw new CliError(`"${name}" is not a folder inside the workspace ${workspace.root}`);
76
- }
77
- const section = sectionAt(workspace, target);
78
- if (section.name.split('/').some((part) => SKIPPED_DIRECTORIES.has(part) || isTempName(part))) {
79
- throw new CliError(`"${name}" cannot be a section`);
80
- }
81
- return section;
82
- };
83
- /** Every section that has a bundle, found by walking the workspace. Sorted by name. */
84
- export const discoverSections = (workspace) => {
85
- const sections = [];
86
- const walk = (directory) => {
87
- const entries = readdirSync(directory, { withFileTypes: true });
88
- const bundles = entries
89
- .filter((entry) => entry.isFile() && entry.name.endsWith(BUNDLE_SUFFIX))
90
- .map((entry) => join(directory, entry.name.slice(0, -BUNDLE_SUFFIX.length)))
91
- .filter((target) => basename(target).length > 0);
92
- sections.push(...bundles.map((target) => sectionAt(workspace, target)));
93
- // A section's plaintext is not searched: sections do not nest.
94
- const plaintext = new Set(bundles);
95
- for (const entry of entries) {
96
- const path = join(directory, entry.name);
97
- if (!entry.isDirectory() || SKIPPED_DIRECTORIES.has(entry.name))
98
- continue;
99
- if (plaintext.has(path) || isLeftoverName(entry.name))
100
- continue;
101
- walk(path);
102
- }
103
- };
104
- walk(workspace.root);
105
- return sections.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
106
- };
@@ -1,147 +0,0 @@
1
- import { createHash } from 'crypto';
2
- import { createReadStream } from 'fs';
3
- import { lstat, readdir } from 'fs/promises';
4
- import { join } from 'path';
5
- import { IO_CHUNK_SIZE } from '../utils/bytes';
6
- import { CliError, EXIT } from '../utils/errors';
7
- /**
8
- * What a section contains: every file's path, size and SHA-256.
9
- *
10
- * The manifest is the first entry of a section's archive, inside the encryption. It is what makes
11
- * "nothing changed" cheap to establish (two sections are the same exactly when their manifests
12
- * are), and it is what an extraction is checked against before any plaintext is replaced.
13
- */
14
- export const MANIFEST_PATH = '.dcrypt-manifest.json';
15
- export const MANIFEST_VERSION = 1;
16
- /** Finder metadata, rewritten whenever a folder is opened: never part of a section. */
17
- const IGNORED_NAMES = new Set(['.DS_Store']);
18
- const OWNER_EXECUTE = 0o100;
19
- const invalid = (message) => new CliError(`the manifest is invalid: ${message}`, EXIT.corrupt);
20
- /**
21
- * Throws unless `path` names a file strictly inside the directory it will be extracted into.
22
- * Applied to every path that comes out of a bundle, before anything is written.
23
- */
24
- export const assertSafePath = (path) => {
25
- const reason = path.length === 0
26
- ? 'it is empty'
27
- : /[\0\\]/.test(path)
28
- ? 'it contains a NUL or a backslash'
29
- : path.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')
30
- ? 'it is absolute or has an empty, "." or ".." segment'
31
- : path === MANIFEST_PATH
32
- ? 'that name is reserved'
33
- : path !== path.normalize('NFC')
34
- ? 'it is not NFC-normalized'
35
- : undefined;
36
- if (reason)
37
- throw invalid(`path ${JSON.stringify(path)} is not acceptable (${reason})`);
38
- };
39
- const byPath = (a, b) => Buffer.compare(Buffer.from(a.path, 'utf8'), Buffer.from(b.path, 'utf8'));
40
- /** The one byte sequence a manifest is written as: fixed key order, sorted files. */
41
- export const serializeManifest = (manifest) => {
42
- const files = manifest.files.map(({ path, size, sha256, executable }) => ({
43
- path,
44
- size,
45
- sha256,
46
- executable,
47
- }));
48
- return Buffer.from(JSON.stringify({ version: manifest.version, files }, null, 2) + '\n', 'utf8');
49
- };
50
- export const digestOf = (manifest) => createHash('sha256').update(serializeManifest(manifest)).digest('hex');
51
- const isManifestFile = (value) => {
52
- const file = value;
53
- return (typeof file === 'object' &&
54
- file !== null &&
55
- typeof file.path === 'string' &&
56
- Number.isSafeInteger(file.size) &&
57
- file.size >= 0 &&
58
- typeof file.sha256 === 'string' &&
59
- /^[0-9a-f]{64}$/.test(file.sha256) &&
60
- typeof file.executable === 'boolean');
61
- };
62
- /**
63
- * Parses a manifest read from a bundle. Strict about every field it reads; a field it does not
64
- * know is dropped, so that nothing outside the format can reach the digest.
65
- */
66
- export const parseManifest = (bytes) => {
67
- let parsed;
68
- try {
69
- parsed = JSON.parse(Buffer.from(bytes).toString('utf8'));
70
- }
71
- catch {
72
- throw invalid('it is not JSON');
73
- }
74
- if (parsed?.version !== MANIFEST_VERSION) {
75
- throw invalid(`version ${JSON.stringify(parsed?.version)} is not supported`);
76
- }
77
- if (!Array.isArray(parsed.files) || !parsed.files.every(isManifestFile)) {
78
- throw invalid('the file list is malformed');
79
- }
80
- const files = parsed.files.map(({ path, size, sha256, executable }) => ({
81
- path,
82
- size,
83
- sha256,
84
- executable,
85
- }));
86
- files.forEach((file, index) => {
87
- assertSafePath(file.path);
88
- // Strictly ascending order also rules out duplicates.
89
- if (index > 0 && byPath(files[index - 1], file) >= 0)
90
- throw invalid('the files are not sorted');
91
- });
92
- return { version: MANIFEST_VERSION, files };
93
- };
94
- const readBytes = (path) => createReadStream(path, { highWaterMark: IO_CHUNK_SIZE });
95
- /** SHA-256 of a byte stream, as lowercase hex. */
96
- export const hashBytes = async (bytes) => {
97
- const hash = createHash('sha256');
98
- for await (const piece of bytes)
99
- hash.update(piece);
100
- return hash.digest('hex');
101
- };
102
- export const hashFile = (path) => hashBytes(readBytes(path));
103
- /** Every regular file under `directory`. Anything that is not a file or a folder is refused. */
104
- const findFiles = async (directory, prefix = '') => {
105
- const found = [];
106
- for (const name of await readdir(directory)) {
107
- if (IGNORED_NAMES.has(name))
108
- continue;
109
- const source = join(directory, name);
110
- // The name on disk is used to read the file; the manifest records its normalized form, so
111
- // that the same section has the same digest on file systems that store names differently.
112
- const path = prefix + name.normalize('NFC');
113
- const stats = await lstat(source);
114
- if (stats.isDirectory()) {
115
- found.push(...(await findFiles(source, `${path}/`)));
116
- }
117
- else if (stats.isFile()) {
118
- found.push({ path, source, size: stats.size, executable: (stats.mode & OWNER_EXECUTE) !== 0 });
119
- }
120
- else {
121
- throw new CliError(`${source} is a link or a special file; a section holds regular files only (empty folders are not kept)`);
122
- }
123
- }
124
- return found;
125
- };
126
- /** Reads a section's plaintext: finds its files and hashes each one. */
127
- export const snapshotSection = async (directory) => {
128
- const found = (await findFiles(directory)).sort(byPath);
129
- const files = [];
130
- for (const file of found) {
131
- try {
132
- assertSafePath(file.path);
133
- }
134
- catch {
135
- throw new CliError(`${file.source} cannot be stored: its name is reserved, or contains a backslash or a NUL`);
136
- }
137
- if (files.length && files[files.length - 1].path === file.path) {
138
- throw new CliError(`${file.source} has the same name as another file once normalized`);
139
- }
140
- files.push({ ...file, sha256: await hashFile(file.source) });
141
- }
142
- const manifest = {
143
- version: MANIFEST_VERSION,
144
- files: files.map(({ path, size, sha256, executable }) => ({ path, size, sha256, executable })),
145
- };
146
- return { manifest, digest: digestOf(manifest), files };
147
- };
@@ -1,37 +0,0 @@
1
- import { fingerprint, recipientFromString } from '@decryption/keys';
2
- import { existsSync } from 'fs';
3
- import { CliError, EXIT } from '../utils/errors';
4
- import { readRecipientsFile } from '../utils/recipients';
5
- import { hasIdentity, readStoredIdentity } from '../utils/stash';
6
- /** The fingerprint a bundle's header lists for this `dcrypt1…` recipient. */
7
- export const fingerprintOf = (recipient) => fingerprint(recipientFromString(recipient));
8
- /** This machine's fingerprint, when it has an identity. Public: no passphrase is involved. */
9
- export const ownFingerprint = () => hasIdentity() ? fingerprintOf(readStoredIdentity().recipient) : undefined;
10
- /** Everyone the workspace's sections are encrypted to. */
11
- export const readWorkspaceRecipients = (workspace) => {
12
- if (!existsSync(workspace.recipientsFile)) {
13
- throw new CliError(`no recipients.txt in ${workspace.root}; create one with a "dcrypt1…" public key per line ("dcrypt keys show" prints yours)`, EXIT.notFound);
14
- }
15
- const entries = readRecipientsFile(workspace.recipientsFile);
16
- if (!entries.length)
17
- throw new CliError(`${workspace.recipientsFile} lists no recipients`);
18
- return entries;
19
- };
20
- /**
21
- * A recovery recipient is a key that lives on no working machine: kept offline, for the day
22
- * every laptop is gone. It is recognised by the word "recovery" in its label.
23
- */
24
- export const isRecovery = (entry) => /\brecovery\b/i.test(entry.label);
25
- export const NO_RECOVERY_WARNING = 'no recovery recipient: if every machine key is lost, nothing can decrypt these sections. ' +
26
- 'Add a key that is kept offline to recipients.txt, with "recovery" in its label.';
27
- /** What is worth saying about a set of recipients before encrypting to them. */
28
- export const recipientWarnings = (entries) => {
29
- const warnings = [];
30
- if (!entries.some(isRecovery))
31
- warnings.push(NO_RECOVERY_WARNING);
32
- const mine = ownFingerprint();
33
- if (mine && !entries.some((entry) => fingerprintOf(entry.recipient) === mine)) {
34
- warnings.push(`this machine's identity (${mine}) is not in recipients.txt: it cannot decrypt what it encrypts.`);
35
- }
36
- return warnings;
37
- };
@@ -1,54 +0,0 @@
1
- /**
2
- * Files a workspace's repository needs, ready to paste. `dcrypt guard snippet <name>` prints one.
3
- */
4
- /** Marks a pre-commit hook as ours, so that installing again replaces it and nothing else. */
5
- export const HOOK_MARKER = '# dcrypt-guard';
6
- const gitignore = `# Allow-list: ignore everything, then name what may be committed.
7
- # A new file is private until a line here says otherwise.
8
- /*
9
- !/.gitignore
10
- !/.gitattributes
11
- !/README.md
12
- !/recipients.txt
13
- !/*.tar.dcrypt
14
-
15
- # For bundles in a sub-folder, open the folder, close its contents, allow its bundles:
16
- # !/clients/
17
- # /clients/*
18
- # !/clients/*.tar.dcrypt
19
- `;
20
- const gitattributes = `# Bundles are large and change completely on every encryption: keep them in Git LFS.
21
- *.tar.dcrypt filter=lfs diff=lfs merge=lfs -text
22
- `;
23
- const hook = `#!/bin/sh
24
- ${HOOK_MARKER}: installed by "dcrypt guard install"
25
- # Refuses a commit that would record plaintext from an encrypted section.
26
- if ! command -v dcrypt >/dev/null 2>&1; then
27
- echo "pre-commit: dcrypt is not installed, so this commit cannot be checked." >&2
28
- echo "pre-commit: install it with: npm i -g @decryption/cli" >&2
29
- exit 1
30
- fi
31
- exec dcrypt guard --staged
32
- `;
33
- const ci = `# A step for CI: fails the build if plaintext was ever committed.
34
- - name: dcrypt guard
35
- run: npx --yes @decryption/cli guard --all
36
- `;
37
- const recipients = `# Who can decrypt the sections in this folder. One public key per line, then a label.
38
- # Public keys are safe to commit. "dcrypt keys show" prints yours.
39
- #
40
- # Keep one key that lives on no working machine, with "recovery" in its label:
41
- # it is what opens the sections on the day every laptop is gone.
42
- #
43
- # dcrypt1… ada (laptop)
44
- # dcrypt1… ada (desktop)
45
- # dcrypt1… recovery (printed, in the safe)
46
- `;
47
- export const SNIPPETS = {
48
- gitignore: { file: '.gitignore', text: gitignore },
49
- gitattributes: { file: '.gitattributes', text: gitattributes },
50
- hook: { file: '.git/hooks/pre-commit', text: hook },
51
- ci: { file: 'a CI workflow', text: ci },
52
- recipients: { file: 'recipients.txt', text: recipients },
53
- };
54
- export const isSnippetName = (name) => Object.hasOwn(SNIPPETS, name);
@@ -1,46 +0,0 @@
1
- import { existsSync, readFileSync } from 'fs';
2
- import { mkdir } from 'fs/promises';
3
- import { join } from 'path';
4
- import { writeFileAtomically } from '../utils/bytes';
5
- import { STATE_DIRECTORY } from './layout';
6
- /**
7
- * What this machine last encrypted or decrypted, per section.
8
- *
9
- * Comparing a section against its bundle would otherwise need the bundle decrypted, and so a
10
- * passphrase. Remembering the two hashes that were in agreement the last time lets `status` and
11
- * an unchanged `encrypt-section` answer without one. The file is local, holds only hashes, and is
12
- * never committed; losing it loses nothing but that shortcut.
13
- */
14
- const STATE_VERSION = 1;
15
- export const statePath = (workspace) => join(workspace.root, STATE_DIRECTORY, 'state.json');
16
- const isRecord = (value) => {
17
- const record = value;
18
- return (typeof record === 'object' &&
19
- record !== null &&
20
- typeof record.digest === 'string' &&
21
- typeof record.bundle === 'string');
22
- };
23
- /** Reads the state. A missing or unreadable file is an empty one: every section is then unknown. */
24
- export const readState = (workspace) => {
25
- const path = statePath(workspace);
26
- if (!existsSync(path))
27
- return {};
28
- try {
29
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
30
- if (parsed?.version !== STATE_VERSION || typeof parsed.sections !== 'object')
31
- return {};
32
- return Object.fromEntries(Object.entries(parsed.sections ?? {}).filter(([, value]) => isRecord(value)));
33
- }
34
- catch {
35
- return {};
36
- }
37
- };
38
- /** Records that `name`'s plaintext and bundle agree, replacing what was known about it. */
39
- export const recordSection = async (workspace, name, record) => {
40
- const sections = { ...readState(workspace), [name]: record };
41
- const sorted = Object.fromEntries(Object.entries(sections).sort(([a], [b]) => (a < b ? -1 : 1)));
42
- const path = statePath(workspace);
43
- await mkdir(join(workspace.root, STATE_DIRECTORY), { recursive: true });
44
- const text = JSON.stringify({ version: STATE_VERSION, sections: sorted }, null, 2) + '\n';
45
- await writeFileAtomically(path, [Buffer.from(text, 'utf8')]);
46
- };
@@ -1,93 +0,0 @@
1
- import { statSync } from 'fs';
2
- import { messageFor } from '../utils/errors';
3
- import { count } from '../utils/text';
4
- import { inspectBundle, LfsPointerError } from './bundle';
5
- import { snapshotSection } from './manifest';
6
- const exists = (path, kind) => {
7
- try {
8
- return statSync(path)[kind]();
9
- }
10
- catch {
11
- return false;
12
- }
13
- };
14
- const stateOf = (snapshot, bundle, record) => {
15
- if (!bundle)
16
- return snapshot ? 'not encrypted' : 'missing';
17
- if (!snapshot)
18
- return 'not decrypted';
19
- if (!record)
20
- return 'unknown';
21
- const plaintextSame = snapshot.digest === record.digest;
22
- const bundleSame = bundle.sha256 === record.bundle;
23
- if (plaintextSame)
24
- return bundleSame ? 'in sync' : 'bundle changed';
25
- return bundleSame ? 'plaintext changed' : 'conflict';
26
- };
27
- /**
28
- * Compares a section's plaintext, its bundle and what this machine remembers of them. Needs no
29
- * key: the plaintext is hashed, the bundle is hashed, and its header names its recipients.
30
- *
31
- * `recipients` is the fingerprints in `recipients.txt`, when there is one to compare against.
32
- *
33
- * It does not throw for a section it cannot read: that is a state of that section, with the
34
- * reason in `problem`, so that one bad section never hides the state of the others.
35
- */
36
- export const inspectSection = async (section, record, recipients) => {
37
- const unread = { section, missingRecipients: [], extraRecipients: [] };
38
- let snapshot;
39
- try {
40
- if (exists(section.directory, 'isDirectory'))
41
- snapshot = await snapshotSection(section.directory);
42
- }
43
- catch (error) {
44
- return { ...unread, state: 'plaintext unreadable', problem: messageFor(error) };
45
- }
46
- const report = { ...unread, snapshot };
47
- if (!exists(section.bundle, 'isFile'))
48
- return { ...report, state: stateOf(snapshot, undefined, record) };
49
- let bundle;
50
- try {
51
- bundle = await inspectBundle(section.bundle);
52
- }
53
- catch (error) {
54
- if (error instanceof LfsPointerError)
55
- return { ...report, state: 'not downloaded' };
56
- return { ...report, state: 'bundle unreadable', problem: messageFor(error) };
57
- }
58
- return {
59
- ...report,
60
- bundle,
61
- state: stateOf(snapshot, bundle, record),
62
- missingRecipients: (recipients ?? []).filter((id) => !bundle.recipients.includes(id)),
63
- extraRecipients: recipients ? bundle.recipients.filter((id) => !recipients.includes(id)) : [],
64
- };
65
- };
66
- /** True when the bundle is not encrypted to exactly the people in `recipients.txt`. */
67
- export const recipientsDiffer = (report) => report.missingRecipients.length + report.extraRecipients.length > 0;
68
- const ADVICE = {
69
- 'in sync': '',
70
- 'plaintext changed': 'run `dcrypt encrypt-section` to encrypt the changes',
71
- 'bundle changed': 'run `dcrypt decrypt-workspace` to update the plaintext',
72
- conflict: 'the plaintext and the bundle have both changed since they last agreed',
73
- 'not decrypted': 'run `dcrypt decrypt-workspace`',
74
- 'not encrypted': 'run `dcrypt encrypt-section`',
75
- unknown: 'this machine has no record of it; run `dcrypt decrypt-workspace` to compare',
76
- 'not downloaded': 'the bundle is a Git LFS pointer; run `git lfs pull`',
77
- 'bundle unreadable': 'restore the bundle from git, or replace it with `dcrypt encrypt-section --force`',
78
- 'plaintext unreadable': '',
79
- missing: 'there is no such folder and no such bundle',
80
- };
81
- /** What to say when the bundle is not encrypted to exactly the people in `recipients.txt`. */
82
- const recipientAdvice = ({ missingRecipients, extraRecipients }) => {
83
- const differences = [];
84
- if (missingRecipients.length) {
85
- differences.push(`${count(missingRecipients.length, 'recipient')} in recipients.txt cannot open it yet`);
86
- }
87
- if (extraRecipients.length) {
88
- differences.push(`it is still encrypted to ${count(extraRecipients.length, 'key')} no longer in recipients.txt`);
89
- }
90
- return differences.length ? `${differences.join(', and ')}; encrypt it again` : '';
91
- };
92
- /** One line on what a report means and what to do about it. Empty when there is nothing to do. */
93
- export const adviceFor = (report) => [report.problem, ADVICE[report.state], recipientAdvice(report)].filter(Boolean).join('; ');