decryption 0.5.1 → 0.6.0

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 +3 -66
  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,118 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.installHook = exports.isHookInstalled = exports.runGuard = exports.checkPaths = void 0;
4
- const core_1 = require("@decryption/core");
5
- const fs_1 = require("fs");
6
- const path_1 = require("path");
7
- const errors_1 = require("../utils/errors");
8
- const git_1 = require("./git");
9
- const layout_1 = require("./layout");
10
- const snippets_1 = require("./snippets");
11
- /**
12
- * The pre-commit guard: looks at what a commit would record and refuses three things.
13
- *
14
- * 1. A file inside a section's plaintext folder.
15
- * 2. A `*.dcrypt` file that is not encrypted: a plain file given the name by mistake.
16
- * 3. A file the ignore rules cover, which can only be staged by forcing it past them.
17
- *
18
- * It reads the index, not the working tree: what matters is what would be committed.
19
- */
20
- const ENCRYPTED_SUFFIX = '.dcrypt';
21
- const LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/';
22
- const HEAD_LENGTH = 64;
23
- const startsWith = (head, prefix) => head.subarray(0, prefix.length).equals(Buffer.from(prefix));
24
- const isEnvelope = (head) => startsWith(head, core_1.MAGIC) || startsWith(head, core_1.ARMOR_PREFIX) || startsWith(head, core_1.FILE_ARMOR_PREFIX);
25
- const fileHead = (path) => {
26
- if (!(0, fs_1.existsSync)(path))
27
- return undefined;
28
- const head = Buffer.alloc(HEAD_LENGTH);
29
- const descriptor = (0, fs_1.openSync)(path, 'r');
30
- try {
31
- return head.subarray(0, (0, fs_1.readSync)(descriptor, head, 0, HEAD_LENGTH, 0));
32
- }
33
- finally {
34
- (0, fs_1.closeSync)(descriptor);
35
- }
36
- };
37
- /**
38
- * True when what would be committed at `path` is ciphertext. With Git LFS the index holds a
39
- * pointer, so the file the pointer stands for is checked instead, when it is here to check.
40
- */
41
- const isEncrypted = async (root, path) => {
42
- const head = await (0, git_1.indexedHead)(root, path, HEAD_LENGTH);
43
- if (!startsWith(head, LFS_POINTER_PREFIX))
44
- return isEnvelope(head);
45
- const local = fileHead((0, path_1.join)(root, path));
46
- return local === undefined || startsWith(local, LFS_POINTER_PREFIX) || isEnvelope(local);
47
- };
48
- /** Names of every section the repository knows: bundles on disk, staged, or tracked. */
49
- const sectionNames = (workspace, paths) => {
50
- const fromGit = [...paths, ...(0, git_1.trackedPaths)(workspace.root)]
51
- .filter((path) => path.endsWith(layout_1.BUNDLE_SUFFIX))
52
- .map((path) => path.slice(0, -layout_1.BUNDLE_SUFFIX.length));
53
- const onDisk = (0, layout_1.discoverSections)(workspace).map((section) => section.name);
54
- return [...new Set([...fromGit, ...onDisk])];
55
- };
56
- /** Checks the given paths (relative to the workspace root) as they stand in the index. */
57
- const checkPaths = async (workspace, paths) => {
58
- const sections = sectionNames(workspace, paths);
59
- const ignored = new Set((0, git_1.ignoredPaths)(workspace.root, paths));
60
- const violations = [];
61
- for (const path of paths) {
62
- const section = sections.find((name) => path.startsWith(`${name}/`));
63
- if (section) {
64
- violations.push({
65
- path,
66
- rule: 'plaintext',
67
- message: `plaintext of the encrypted section "${section}"; commit ${section}${layout_1.BUNDLE_SUFFIX} instead`,
68
- });
69
- }
70
- else if (path.endsWith(ENCRYPTED_SUFFIX) && !(await isEncrypted(workspace.root, path))) {
71
- violations.push({
72
- path,
73
- rule: 'not encrypted',
74
- message: `named ${ENCRYPTED_SUFFIX} but its content is not a dcrypt envelope`,
75
- });
76
- }
77
- else if (ignored.has(path)) {
78
- violations.push({
79
- path,
80
- rule: 'ignored',
81
- message: 'covered by .gitignore, so it was added by force; it is not on the allow-list',
82
- });
83
- }
84
- }
85
- return violations;
86
- };
87
- exports.checkPaths = checkPaths;
88
- /** Runs the guard over what is staged, or over everything tracked. */
89
- const runGuard = async (workspace, scope) => {
90
- const paths = scope === 'staged' ? (0, git_1.stagedPaths)(workspace.root) : (0, git_1.trackedPaths)(workspace.root);
91
- return { scope, checked: paths.length, violations: await (0, exports.checkPaths)(workspace, paths) };
92
- };
93
- exports.runGuard = runGuard;
94
- const hookPath = (workspace) => (0, path_1.join)((0, git_1.hooksDirectory)(workspace.root), 'pre-commit');
95
- /** True when this repository's pre-commit hook is the one `dcrypt guard install` writes. */
96
- const isHookInstalled = (workspace) => {
97
- const path = hookPath(workspace);
98
- return (0, fs_1.existsSync)(path) && (0, fs_1.readFileSync)(path, 'utf8').includes(snippets_1.HOOK_MARKER);
99
- };
100
- exports.isHookInstalled = isHookInstalled;
101
- /**
102
- * Installs the pre-commit hook. A hook that is already there and is not ours is left alone
103
- * unless `force` is set.
104
- */
105
- const installHook = (workspace, force = false) => {
106
- if ((0, git_1.repositoryRoot)(workspace.root) !== (0, fs_1.realpathSync)(workspace.root)) {
107
- throw new errors_1.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`);
108
- }
109
- const path = hookPath(workspace);
110
- if ((0, fs_1.existsSync)(path) && !(0, exports.isHookInstalled)(workspace) && !force) {
111
- throw new errors_1.CliError(`${path} already exists and was not written by dcrypt; add "dcrypt guard --staged" to it, or pass --force to replace it`);
112
- }
113
- (0, fs_1.mkdirSync)((0, git_1.hooksDirectory)(workspace.root), { recursive: true });
114
- (0, fs_1.writeFileSync)(path, snippets_1.SNIPPETS.hook.text);
115
- (0, fs_1.chmodSync)(path, 0o755);
116
- return path;
117
- };
118
- exports.installHook = installHook;
@@ -1,47 +0,0 @@
1
- import { ParsedArgs } from 'minimist';
2
- /**
3
- * Where things are in a workspace.
4
- *
5
- * ```text
6
- * <root>/
7
- * recipients.txt who can decrypt (public keys; committed)
8
- * finance.tar.dcrypt a section, encrypted (committed)
9
- * finance/ the same section, decrypted (never committed)
10
- * .dcrypt/state.json what this machine last encrypted or decrypted (never committed)
11
- * ```
12
- *
13
- * A section is a folder and the bundle beside it; the bundle's name is the folder's name plus
14
- * `.tar.dcrypt`. Sections may sit in sub-folders, but not inside one another.
15
- */
16
- export declare const BUNDLE_SUFFIX = ".tar.dcrypt";
17
- export declare const RECIPIENTS_FILE = "recipients.txt";
18
- export declare const STATE_DIRECTORY = ".dcrypt";
19
- /** Marks the previous plaintext of a section while a new one is being swapped in. */
20
- export declare const REPLACED_MARKER = ".dcrypt-old-";
21
- /** True for the temporary and set-aside folders a decryption works in. */
22
- export declare const isLeftoverName: (name: string) => boolean;
23
- export interface Workspace {
24
- root: string;
25
- recipientsFile: string;
26
- }
27
- export interface Section {
28
- /** Path of the section relative to the workspace root, `/`-separated. */
29
- name: string;
30
- /** The plaintext folder. */
31
- directory: string;
32
- /** The encrypted bundle. */
33
- bundle: string;
34
- }
35
- /**
36
- * The workspace a command applies to: `--workspace <dir>`, otherwise the nearest folder upwards
37
- * that has a `recipients.txt`, otherwise the current folder.
38
- */
39
- export declare const findWorkspace: (argv: ParsedArgs) => Workspace;
40
- /**
41
- * The section a user named. The folder and the bundle are both accepted (`finance`, `finance/`,
42
- * `finance.tar.dcrypt`), relative to the current folder when that is inside the workspace and to
43
- * the workspace root otherwise.
44
- */
45
- export declare const resolveSection: (workspace: Workspace, name: string) => Section;
46
- /** Every section that has a bundle, found by walking the workspace. Sorted by name. */
47
- export declare const discoverSections: (workspace: Workspace) => Section[];
@@ -1,113 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.discoverSections = exports.resolveSection = exports.findWorkspace = exports.isLeftoverName = exports.REPLACED_MARKER = exports.STATE_DIRECTORY = exports.RECIPIENTS_FILE = exports.BUNDLE_SUFFIX = void 0;
4
- const fs_1 = require("fs");
5
- const path_1 = require("path");
6
- const errors_1 = require("../utils/errors");
7
- const temp_1 = require("../utils/temp");
8
- /**
9
- * Where things are in a workspace.
10
- *
11
- * ```text
12
- * <root>/
13
- * recipients.txt who can decrypt (public keys; committed)
14
- * finance.tar.dcrypt a section, encrypted (committed)
15
- * finance/ the same section, decrypted (never committed)
16
- * .dcrypt/state.json what this machine last encrypted or decrypted (never committed)
17
- * ```
18
- *
19
- * A section is a folder and the bundle beside it; the bundle's name is the folder's name plus
20
- * `.tar.dcrypt`. Sections may sit in sub-folders, but not inside one another.
21
- */
22
- exports.BUNDLE_SUFFIX = '.tar.dcrypt';
23
- exports.RECIPIENTS_FILE = 'recipients.txt';
24
- exports.STATE_DIRECTORY = '.dcrypt';
25
- /** Marks the previous plaintext of a section while a new one is being swapped in. */
26
- exports.REPLACED_MARKER = '.dcrypt-old-';
27
- /** True for the temporary and set-aside folders a decryption works in. */
28
- const isLeftoverName = (name) => (0, temp_1.isTempName)(name) || name.includes(exports.REPLACED_MARKER);
29
- exports.isLeftoverName = isLeftoverName;
30
- /** Folders that are never searched for bundles. */
31
- const SKIPPED_DIRECTORIES = new Set(['.git', 'node_modules', exports.STATE_DIRECTORY]);
32
- const isDirectory = (path) => {
33
- try {
34
- return (0, fs_1.statSync)(path).isDirectory();
35
- }
36
- catch {
37
- return false;
38
- }
39
- };
40
- const isInside = (parent, child) => {
41
- const path = (0, path_1.relative)(parent, child);
42
- return path === '' || (!path.startsWith('..') && !(0, path_1.isAbsolute)(path));
43
- };
44
- /** The nearest folder, from `start` upwards, that has a recipients file. */
45
- const findRoot = (start) => {
46
- for (let directory = start;; directory = (0, path_1.dirname)(directory)) {
47
- if ((0, fs_1.existsSync)((0, path_1.join)(directory, exports.RECIPIENTS_FILE)))
48
- return directory;
49
- if ((0, path_1.dirname)(directory) === directory)
50
- return undefined;
51
- }
52
- };
53
- /**
54
- * The workspace a command applies to: `--workspace <dir>`, otherwise the nearest folder upwards
55
- * that has a `recipients.txt`, otherwise the current folder.
56
- */
57
- const findWorkspace = (argv) => {
58
- const given = argv.workspace;
59
- if (given !== undefined && (typeof given !== 'string' || !isDirectory(given))) {
60
- throw new errors_1.CliError(`--workspace ${String(given)} is not a folder`, errors_1.EXIT.notFound);
61
- }
62
- const root = given ? (0, path_1.resolve)(given) : (findRoot(process.cwd()) ?? process.cwd());
63
- return { root, recipientsFile: (0, path_1.join)(root, exports.RECIPIENTS_FILE) };
64
- };
65
- exports.findWorkspace = findWorkspace;
66
- const sectionAt = ({ root }, directory) => ({
67
- name: (0, path_1.relative)(root, directory).split(path_1.sep).join('/'),
68
- directory,
69
- bundle: directory + exports.BUNDLE_SUFFIX,
70
- });
71
- /**
72
- * The section a user named. The folder and the bundle are both accepted (`finance`, `finance/`,
73
- * `finance.tar.dcrypt`), relative to the current folder when that is inside the workspace and to
74
- * the workspace root otherwise.
75
- */
76
- const resolveSection = (workspace, name) => {
77
- const base = isInside(workspace.root, process.cwd()) ? process.cwd() : workspace.root;
78
- const target = (0, path_1.resolve)(base, name.endsWith(exports.BUNDLE_SUFFIX) ? name.slice(0, -exports.BUNDLE_SUFFIX.length) : name);
79
- if (target === workspace.root || !isInside(workspace.root, target)) {
80
- throw new errors_1.CliError(`"${name}" is not a folder inside the workspace ${workspace.root}`);
81
- }
82
- const section = sectionAt(workspace, target);
83
- if (section.name.split('/').some((part) => SKIPPED_DIRECTORIES.has(part) || (0, temp_1.isTempName)(part))) {
84
- throw new errors_1.CliError(`"${name}" cannot be a section`);
85
- }
86
- return section;
87
- };
88
- exports.resolveSection = resolveSection;
89
- /** Every section that has a bundle, found by walking the workspace. Sorted by name. */
90
- const discoverSections = (workspace) => {
91
- const sections = [];
92
- const walk = (directory) => {
93
- const entries = (0, fs_1.readdirSync)(directory, { withFileTypes: true });
94
- const bundles = entries
95
- .filter((entry) => entry.isFile() && entry.name.endsWith(exports.BUNDLE_SUFFIX))
96
- .map((entry) => (0, path_1.join)(directory, entry.name.slice(0, -exports.BUNDLE_SUFFIX.length)))
97
- .filter((target) => (0, path_1.basename)(target).length > 0);
98
- sections.push(...bundles.map((target) => sectionAt(workspace, target)));
99
- // A section's plaintext is not searched: sections do not nest.
100
- const plaintext = new Set(bundles);
101
- for (const entry of entries) {
102
- const path = (0, path_1.join)(directory, entry.name);
103
- if (!entry.isDirectory() || SKIPPED_DIRECTORIES.has(entry.name))
104
- continue;
105
- if (plaintext.has(path) || (0, exports.isLeftoverName)(entry.name))
106
- continue;
107
- walk(path);
108
- }
109
- };
110
- walk(workspace.root);
111
- return sections.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
112
- };
113
- exports.discoverSections = discoverSections;
@@ -1,52 +0,0 @@
1
- import { ByteStream } from '../utils/bytes';
2
- /**
3
- * What a section contains: every file's path, size and SHA-256.
4
- *
5
- * The manifest is the first entry of a section's archive, inside the encryption. It is what makes
6
- * "nothing changed" cheap to establish (two sections are the same exactly when their manifests
7
- * are), and it is what an extraction is checked against before any plaintext is replaced.
8
- */
9
- export declare const MANIFEST_PATH = ".dcrypt-manifest.json";
10
- export declare const MANIFEST_VERSION = 1;
11
- export interface ManifestFile {
12
- /** Path inside the section: `/`-separated, NFC-normalized, never absolute. */
13
- path: string;
14
- size: number;
15
- /** Lowercase hex. */
16
- sha256: string;
17
- executable: boolean;
18
- }
19
- export interface Manifest {
20
- version: typeof MANIFEST_VERSION;
21
- /** Sorted by the bytes of `path`. */
22
- files: ManifestFile[];
23
- }
24
- /** A manifest entry together with where its file is on this machine. */
25
- export interface SectionFile extends ManifestFile {
26
- source: string;
27
- }
28
- /** A section's plaintext as it is on disk right now. */
29
- export interface Snapshot {
30
- manifest: Manifest;
31
- /** SHA-256 of the canonical manifest: one value that identifies the whole content. */
32
- digest: string;
33
- files: SectionFile[];
34
- }
35
- /**
36
- * Throws unless `path` names a file strictly inside the directory it will be extracted into.
37
- * Applied to every path that comes out of a bundle, before anything is written.
38
- */
39
- export declare const assertSafePath: (path: string) => void;
40
- /** The one byte sequence a manifest is written as: fixed key order, sorted files. */
41
- export declare const serializeManifest: (manifest: Manifest) => Buffer;
42
- export declare const digestOf: (manifest: Manifest) => string;
43
- /**
44
- * Parses a manifest read from a bundle. Strict about every field it reads; a field it does not
45
- * know is dropped, so that nothing outside the format can reach the digest.
46
- */
47
- export declare const parseManifest: (bytes: Uint8Array) => Manifest;
48
- /** SHA-256 of a byte stream, as lowercase hex. */
49
- export declare const hashBytes: (bytes: ByteStream) => Promise<string>;
50
- export declare const hashFile: (path: string) => Promise<string>;
51
- /** Reads a section's plaintext: finds its files and hashes each one. */
52
- export declare const snapshotSection: (directory: string) => Promise<Snapshot>;
@@ -1,157 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.snapshotSection = exports.hashFile = exports.hashBytes = exports.parseManifest = exports.digestOf = exports.serializeManifest = exports.assertSafePath = exports.MANIFEST_VERSION = exports.MANIFEST_PATH = void 0;
4
- const crypto_1 = require("crypto");
5
- const fs_1 = require("fs");
6
- const promises_1 = require("fs/promises");
7
- const path_1 = require("path");
8
- const bytes_1 = require("../utils/bytes");
9
- const errors_1 = require("../utils/errors");
10
- /**
11
- * What a section contains: every file's path, size and SHA-256.
12
- *
13
- * The manifest is the first entry of a section's archive, inside the encryption. It is what makes
14
- * "nothing changed" cheap to establish (two sections are the same exactly when their manifests
15
- * are), and it is what an extraction is checked against before any plaintext is replaced.
16
- */
17
- exports.MANIFEST_PATH = '.dcrypt-manifest.json';
18
- exports.MANIFEST_VERSION = 1;
19
- /** Finder metadata, rewritten whenever a folder is opened: never part of a section. */
20
- const IGNORED_NAMES = new Set(['.DS_Store']);
21
- const OWNER_EXECUTE = 0o100;
22
- const invalid = (message) => new errors_1.CliError(`the manifest is invalid: ${message}`, errors_1.EXIT.corrupt);
23
- /**
24
- * Throws unless `path` names a file strictly inside the directory it will be extracted into.
25
- * Applied to every path that comes out of a bundle, before anything is written.
26
- */
27
- const assertSafePath = (path) => {
28
- const reason = path.length === 0
29
- ? 'it is empty'
30
- : /[\0\\]/.test(path)
31
- ? 'it contains a NUL or a backslash'
32
- : path.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')
33
- ? 'it is absolute or has an empty, "." or ".." segment'
34
- : path === exports.MANIFEST_PATH
35
- ? 'that name is reserved'
36
- : path !== path.normalize('NFC')
37
- ? 'it is not NFC-normalized'
38
- : undefined;
39
- if (reason)
40
- throw invalid(`path ${JSON.stringify(path)} is not acceptable (${reason})`);
41
- };
42
- exports.assertSafePath = assertSafePath;
43
- const byPath = (a, b) => Buffer.compare(Buffer.from(a.path, 'utf8'), Buffer.from(b.path, 'utf8'));
44
- /** The one byte sequence a manifest is written as: fixed key order, sorted files. */
45
- const serializeManifest = (manifest) => {
46
- const files = manifest.files.map(({ path, size, sha256, executable }) => ({
47
- path,
48
- size,
49
- sha256,
50
- executable,
51
- }));
52
- return Buffer.from(JSON.stringify({ version: manifest.version, files }, null, 2) + '\n', 'utf8');
53
- };
54
- exports.serializeManifest = serializeManifest;
55
- const digestOf = (manifest) => (0, crypto_1.createHash)('sha256').update((0, exports.serializeManifest)(manifest)).digest('hex');
56
- exports.digestOf = digestOf;
57
- const isManifestFile = (value) => {
58
- const file = value;
59
- return (typeof file === 'object' &&
60
- file !== null &&
61
- typeof file.path === 'string' &&
62
- Number.isSafeInteger(file.size) &&
63
- file.size >= 0 &&
64
- typeof file.sha256 === 'string' &&
65
- /^[0-9a-f]{64}$/.test(file.sha256) &&
66
- typeof file.executable === 'boolean');
67
- };
68
- /**
69
- * Parses a manifest read from a bundle. Strict about every field it reads; a field it does not
70
- * know is dropped, so that nothing outside the format can reach the digest.
71
- */
72
- const parseManifest = (bytes) => {
73
- let parsed;
74
- try {
75
- parsed = JSON.parse(Buffer.from(bytes).toString('utf8'));
76
- }
77
- catch {
78
- throw invalid('it is not JSON');
79
- }
80
- if (parsed?.version !== exports.MANIFEST_VERSION) {
81
- throw invalid(`version ${JSON.stringify(parsed?.version)} is not supported`);
82
- }
83
- if (!Array.isArray(parsed.files) || !parsed.files.every(isManifestFile)) {
84
- throw invalid('the file list is malformed');
85
- }
86
- const files = parsed.files.map(({ path, size, sha256, executable }) => ({
87
- path,
88
- size,
89
- sha256,
90
- executable,
91
- }));
92
- files.forEach((file, index) => {
93
- (0, exports.assertSafePath)(file.path);
94
- // Strictly ascending order also rules out duplicates.
95
- if (index > 0 && byPath(files[index - 1], file) >= 0)
96
- throw invalid('the files are not sorted');
97
- });
98
- return { version: exports.MANIFEST_VERSION, files };
99
- };
100
- exports.parseManifest = parseManifest;
101
- const readBytes = (path) => (0, fs_1.createReadStream)(path, { highWaterMark: bytes_1.IO_CHUNK_SIZE });
102
- /** SHA-256 of a byte stream, as lowercase hex. */
103
- const hashBytes = async (bytes) => {
104
- const hash = (0, crypto_1.createHash)('sha256');
105
- for await (const piece of bytes)
106
- hash.update(piece);
107
- return hash.digest('hex');
108
- };
109
- exports.hashBytes = hashBytes;
110
- const hashFile = (path) => (0, exports.hashBytes)(readBytes(path));
111
- exports.hashFile = hashFile;
112
- /** Every regular file under `directory`. Anything that is not a file or a folder is refused. */
113
- const findFiles = async (directory, prefix = '') => {
114
- const found = [];
115
- for (const name of await (0, promises_1.readdir)(directory)) {
116
- if (IGNORED_NAMES.has(name))
117
- continue;
118
- const source = (0, path_1.join)(directory, name);
119
- // The name on disk is used to read the file; the manifest records its normalized form, so
120
- // that the same section has the same digest on file systems that store names differently.
121
- const path = prefix + name.normalize('NFC');
122
- const stats = await (0, promises_1.lstat)(source);
123
- if (stats.isDirectory()) {
124
- found.push(...(await findFiles(source, `${path}/`)));
125
- }
126
- else if (stats.isFile()) {
127
- found.push({ path, source, size: stats.size, executable: (stats.mode & OWNER_EXECUTE) !== 0 });
128
- }
129
- else {
130
- throw new errors_1.CliError(`${source} is a link or a special file; a section holds regular files only (empty folders are not kept)`);
131
- }
132
- }
133
- return found;
134
- };
135
- /** Reads a section's plaintext: finds its files and hashes each one. */
136
- const snapshotSection = async (directory) => {
137
- const found = (await findFiles(directory)).sort(byPath);
138
- const files = [];
139
- for (const file of found) {
140
- try {
141
- (0, exports.assertSafePath)(file.path);
142
- }
143
- catch {
144
- throw new errors_1.CliError(`${file.source} cannot be stored: its name is reserved, or contains a backslash or a NUL`);
145
- }
146
- if (files.length && files[files.length - 1].path === file.path) {
147
- throw new errors_1.CliError(`${file.source} has the same name as another file once normalized`);
148
- }
149
- files.push({ ...file, sha256: await (0, exports.hashFile)(file.source) });
150
- }
151
- const manifest = {
152
- version: exports.MANIFEST_VERSION,
153
- files: files.map(({ path, size, sha256, executable }) => ({ path, size, sha256, executable })),
154
- };
155
- return { manifest, digest: (0, exports.digestOf)(manifest), files };
156
- };
157
- exports.snapshotSection = snapshotSection;
@@ -1,16 +0,0 @@
1
- import { RecipientEntry } from '../utils/recipients';
2
- import { Workspace } from './layout';
3
- /** The fingerprint a bundle's header lists for this `dcrypt1…` recipient. */
4
- export declare const fingerprintOf: (recipient: string) => string;
5
- /** This machine's fingerprint, when it has an identity. Public: no passphrase is involved. */
6
- export declare const ownFingerprint: () => string | undefined;
7
- /** Everyone the workspace's sections are encrypted to. */
8
- export declare const readWorkspaceRecipients: (workspace: Workspace) => RecipientEntry[];
9
- /**
10
- * A recovery recipient is a key that lives on no working machine: kept offline, for the day
11
- * every laptop is gone. It is recognised by the word "recovery" in its label.
12
- */
13
- export declare const isRecovery: (entry: RecipientEntry) => boolean;
14
- export declare const NO_RECOVERY_WARNING: string;
15
- /** What is worth saying about a set of recipients before encrypting to them. */
16
- export declare const recipientWarnings: (entries: RecipientEntry[]) => string[];
@@ -1,45 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.recipientWarnings = exports.NO_RECOVERY_WARNING = exports.isRecovery = exports.readWorkspaceRecipients = exports.ownFingerprint = exports.fingerprintOf = void 0;
4
- const keys_1 = require("@decryption/keys");
5
- const fs_1 = require("fs");
6
- const errors_1 = require("../utils/errors");
7
- const recipients_1 = require("../utils/recipients");
8
- const stash_1 = require("../utils/stash");
9
- /** The fingerprint a bundle's header lists for this `dcrypt1…` recipient. */
10
- const fingerprintOf = (recipient) => (0, keys_1.fingerprint)((0, keys_1.recipientFromString)(recipient));
11
- exports.fingerprintOf = fingerprintOf;
12
- /** This machine's fingerprint, when it has an identity. Public: no passphrase is involved. */
13
- const ownFingerprint = () => (0, stash_1.hasIdentity)() ? (0, exports.fingerprintOf)((0, stash_1.readStoredIdentity)().recipient) : undefined;
14
- exports.ownFingerprint = ownFingerprint;
15
- /** Everyone the workspace's sections are encrypted to. */
16
- const readWorkspaceRecipients = (workspace) => {
17
- if (!(0, fs_1.existsSync)(workspace.recipientsFile)) {
18
- throw new errors_1.CliError(`no recipients.txt in ${workspace.root}; create one with a "dcrypt1…" public key per line ("dcrypt keys show" prints yours)`, errors_1.EXIT.notFound);
19
- }
20
- const entries = (0, recipients_1.readRecipientsFile)(workspace.recipientsFile);
21
- if (!entries.length)
22
- throw new errors_1.CliError(`${workspace.recipientsFile} lists no recipients`);
23
- return entries;
24
- };
25
- exports.readWorkspaceRecipients = readWorkspaceRecipients;
26
- /**
27
- * A recovery recipient is a key that lives on no working machine: kept offline, for the day
28
- * every laptop is gone. It is recognised by the word "recovery" in its label.
29
- */
30
- const isRecovery = (entry) => /\brecovery\b/i.test(entry.label);
31
- exports.isRecovery = isRecovery;
32
- exports.NO_RECOVERY_WARNING = 'no recovery recipient: if every machine key is lost, nothing can decrypt these sections. ' +
33
- 'Add a key that is kept offline to recipients.txt, with "recovery" in its label.';
34
- /** What is worth saying about a set of recipients before encrypting to them. */
35
- const recipientWarnings = (entries) => {
36
- const warnings = [];
37
- if (!entries.some(exports.isRecovery))
38
- warnings.push(exports.NO_RECOVERY_WARNING);
39
- const mine = (0, exports.ownFingerprint)();
40
- if (mine && !entries.some((entry) => (0, exports.fingerprintOf)(entry.recipient) === mine)) {
41
- warnings.push(`this machine's identity (${mine}) is not in recipients.txt: it cannot decrypt what it encrypts.`);
42
- }
43
- return warnings;
44
- };
45
- exports.recipientWarnings = recipientWarnings;
@@ -1,29 +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 declare const HOOK_MARKER = "# dcrypt-guard";
6
- export declare const SNIPPETS: {
7
- readonly gitignore: {
8
- readonly file: ".gitignore";
9
- readonly text: "# Allow-list: ignore everything, then name what may be committed.\n# A new file is private until a line here says otherwise.\n/*\n!/.gitignore\n!/.gitattributes\n!/README.md\n!/recipients.txt\n!/*.tar.dcrypt\n\n# For bundles in a sub-folder, open the folder, close its contents, allow its bundles:\n# !/clients/\n# /clients/*\n# !/clients/*.tar.dcrypt\n";
10
- };
11
- readonly gitattributes: {
12
- readonly file: ".gitattributes";
13
- readonly text: "# Bundles are large and change completely on every encryption: keep them in Git LFS.\n*.tar.dcrypt filter=lfs diff=lfs merge=lfs -text\n";
14
- };
15
- readonly hook: {
16
- readonly file: ".git/hooks/pre-commit";
17
- readonly text: "#!/bin/sh\n# dcrypt-guard: installed by \"dcrypt guard install\"\n# Refuses a commit that would record plaintext from an encrypted section.\nif ! command -v dcrypt >/dev/null 2>&1; then\n echo \"pre-commit: dcrypt is not installed, so this commit cannot be checked.\" >&2\n echo \"pre-commit: install it with: npm i -g @decryption/cli\" >&2\n exit 1\nfi\nexec dcrypt guard --staged\n";
18
- };
19
- readonly ci: {
20
- readonly file: "a CI workflow";
21
- readonly text: "# A step for CI: fails the build if plaintext was ever committed.\n- name: dcrypt guard\n run: npx --yes @decryption/cli guard --all\n";
22
- };
23
- readonly recipients: {
24
- readonly file: "recipients.txt";
25
- readonly text: "# Who can decrypt the sections in this folder. One public key per line, then a label.\n# Public keys are safe to commit. \"dcrypt keys show\" prints yours.\n#\n# Keep one key that lives on no working machine, with \"recovery\" in its label:\n# it is what opens the sections on the day every laptop is gone.\n#\n# dcrypt1… ada (laptop)\n# dcrypt1… ada (desktop)\n# dcrypt1… recovery (printed, in the safe)\n";
26
- };
27
- };
28
- export type SnippetName = keyof typeof SNIPPETS;
29
- export declare const isSnippetName: (name: string) => name is SnippetName;
@@ -1,58 +0,0 @@
1
- "use strict";
2
- /**
3
- * Files a workspace's repository needs, ready to paste. `dcrypt guard snippet <name>` prints one.
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isSnippetName = exports.SNIPPETS = exports.HOOK_MARKER = void 0;
7
- /** Marks a pre-commit hook as ours, so that installing again replaces it and nothing else. */
8
- exports.HOOK_MARKER = '# dcrypt-guard';
9
- const gitignore = `# Allow-list: ignore everything, then name what may be committed.
10
- # A new file is private until a line here says otherwise.
11
- /*
12
- !/.gitignore
13
- !/.gitattributes
14
- !/README.md
15
- !/recipients.txt
16
- !/*.tar.dcrypt
17
-
18
- # For bundles in a sub-folder, open the folder, close its contents, allow its bundles:
19
- # !/clients/
20
- # /clients/*
21
- # !/clients/*.tar.dcrypt
22
- `;
23
- const gitattributes = `# Bundles are large and change completely on every encryption: keep them in Git LFS.
24
- *.tar.dcrypt filter=lfs diff=lfs merge=lfs -text
25
- `;
26
- const hook = `#!/bin/sh
27
- ${exports.HOOK_MARKER}: installed by "dcrypt guard install"
28
- # Refuses a commit that would record plaintext from an encrypted section.
29
- if ! command -v dcrypt >/dev/null 2>&1; then
30
- echo "pre-commit: dcrypt is not installed, so this commit cannot be checked." >&2
31
- echo "pre-commit: install it with: npm i -g @decryption/cli" >&2
32
- exit 1
33
- fi
34
- exec dcrypt guard --staged
35
- `;
36
- const ci = `# A step for CI: fails the build if plaintext was ever committed.
37
- - name: dcrypt guard
38
- run: npx --yes @decryption/cli guard --all
39
- `;
40
- const recipients = `# Who can decrypt the sections in this folder. One public key per line, then a label.
41
- # Public keys are safe to commit. "dcrypt keys show" prints yours.
42
- #
43
- # Keep one key that lives on no working machine, with "recovery" in its label:
44
- # it is what opens the sections on the day every laptop is gone.
45
- #
46
- # dcrypt1… ada (laptop)
47
- # dcrypt1… ada (desktop)
48
- # dcrypt1… recovery (printed, in the safe)
49
- `;
50
- exports.SNIPPETS = {
51
- gitignore: { file: '.gitignore', text: gitignore },
52
- gitattributes: { file: '.gitattributes', text: gitattributes },
53
- hook: { file: '.git/hooks/pre-commit', text: hook },
54
- ci: { file: 'a CI workflow', text: ci },
55
- recipients: { file: 'recipients.txt', text: recipients },
56
- };
57
- const isSnippetName = (name) => Object.hasOwn(exports.SNIPPETS, name);
58
- exports.isSnippetName = isSnippetName;
@@ -1,13 +0,0 @@
1
- import { Workspace } from './layout';
2
- export interface SectionRecord {
3
- /** Digest of the manifest the plaintext and the bundle agreed on. */
4
- digest: string;
5
- /** SHA-256 of the bundle file at that moment. */
6
- bundle: string;
7
- }
8
- export type State = Record<string, SectionRecord>;
9
- export declare const statePath: (workspace: Workspace) => string;
10
- /** Reads the state. A missing or unreadable file is an empty one: every section is then unknown. */
11
- export declare const readState: (workspace: Workspace) => State;
12
- /** Records that `name`'s plaintext and bundle agree, replacing what was known about it. */
13
- export declare const recordSection: (workspace: Workspace, name: string, record: SectionRecord) => Promise<void>;