decryption 0.0.0-stage → 0.5.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 (116) hide show
  1. package/README.md +348 -2
  2. package/commands/account.d.ts +4 -0
  3. package/commands/account.js +470 -0
  4. package/commands/cosmology.d.ts +4 -0
  5. package/commands/cosmology.js +97 -0
  6. package/commands/doctor.d.ts +3 -0
  7. package/commands/doctor.js +42 -0
  8. package/commands/encrypt.d.ts +12 -0
  9. package/commands/encrypt.js +251 -0
  10. package/commands/guard.d.ts +3 -0
  11. package/commands/guard.js +92 -0
  12. package/commands/keychain.d.ts +4 -0
  13. package/commands/keychain.js +92 -0
  14. package/commands/keys.d.ts +4 -0
  15. package/commands/keys.js +74 -0
  16. package/commands/passkey.d.ts +4 -0
  17. package/commands/passkey.js +135 -0
  18. package/commands/salt.d.ts +4 -0
  19. package/commands/salt.js +113 -0
  20. package/commands/secrets.d.ts +4 -0
  21. package/commands/secrets.js +214 -0
  22. package/commands/shamir.d.ts +4 -0
  23. package/commands/shamir.js +62 -0
  24. package/commands/vault.d.ts +7 -0
  25. package/commands/vault.js +382 -0
  26. package/commands/wallet.d.ts +5 -0
  27. package/commands/wallet.js +129 -0
  28. package/commands/workspace.d.ts +8 -0
  29. package/commands/workspace.js +289 -0
  30. package/commands.d.ts +8 -0
  31. package/commands.js +126 -0
  32. package/esm/commands/account.js +466 -0
  33. package/esm/commands/cosmology.js +93 -0
  34. package/esm/commands/doctor.js +38 -0
  35. package/esm/commands/encrypt.js +245 -0
  36. package/esm/commands/guard.js +88 -0
  37. package/esm/commands/keychain.js +88 -0
  38. package/esm/commands/keys.js +70 -0
  39. package/esm/commands/passkey.js +131 -0
  40. package/esm/commands/salt.js +109 -0
  41. package/esm/commands/secrets.js +210 -0
  42. package/esm/commands/shamir.js +58 -0
  43. package/esm/commands/vault.js +376 -0
  44. package/esm/commands/wallet.js +125 -0
  45. package/esm/commands/workspace.js +283 -0
  46. package/esm/commands.js +120 -0
  47. package/esm/index.js +50 -0
  48. package/esm/utils/bytes.js +286 -0
  49. package/esm/utils/dispatch.js +52 -0
  50. package/esm/utils/env.js +44 -0
  51. package/esm/utils/errors.js +44 -0
  52. package/esm/utils/header.js +14 -0
  53. package/esm/utils/io.js +49 -0
  54. package/esm/utils/passphrase.js +49 -0
  55. package/esm/utils/recipients.js +74 -0
  56. package/esm/utils/stash.js +61 -0
  57. package/esm/utils/temp.js +51 -0
  58. package/esm/utils/text.js +2 -0
  59. package/esm/workspace/bundle.js +239 -0
  60. package/esm/workspace/doctor.js +104 -0
  61. package/esm/workspace/git.js +72 -0
  62. package/esm/workspace/guard.js +111 -0
  63. package/esm/workspace/layout.js +106 -0
  64. package/esm/workspace/manifest.js +147 -0
  65. package/esm/workspace/recipients.js +37 -0
  66. package/esm/workspace/snippets.js +54 -0
  67. package/esm/workspace/state.js +46 -0
  68. package/esm/workspace/status.js +93 -0
  69. package/esm/workspace/tar.js +235 -0
  70. package/index.d.ts +12 -0
  71. package/index.js +67 -0
  72. package/package.json +53 -4
  73. package/utils/bytes.d.ts +86 -0
  74. package/utils/bytes.js +301 -0
  75. package/utils/dispatch.d.ts +24 -0
  76. package/utils/dispatch.js +58 -0
  77. package/utils/env.d.ts +26 -0
  78. package/utils/env.js +49 -0
  79. package/utils/errors.d.ts +25 -0
  80. package/utils/errors.js +50 -0
  81. package/utils/header.d.ts +4 -0
  82. package/utils/header.js +18 -0
  83. package/utils/io.d.ts +10 -0
  84. package/utils/io.js +57 -0
  85. package/utils/passphrase.d.ts +15 -0
  86. package/utils/passphrase.js +53 -0
  87. package/utils/recipients.d.ts +28 -0
  88. package/utils/recipients.js +80 -0
  89. package/utils/stash.d.ts +40 -0
  90. package/utils/stash.js +76 -0
  91. package/utils/temp.d.ts +10 -0
  92. package/utils/temp.js +59 -0
  93. package/utils/text.d.ts +2 -0
  94. package/utils/text.js +6 -0
  95. package/workspace/bundle.d.ts +50 -0
  96. package/workspace/bundle.js +248 -0
  97. package/workspace/doctor.d.ts +8 -0
  98. package/workspace/doctor.js +108 -0
  99. package/workspace/git.d.ts +21 -0
  100. package/workspace/git.js +83 -0
  101. package/workspace/guard.d.ts +23 -0
  102. package/workspace/guard.js +118 -0
  103. package/workspace/layout.d.ts +47 -0
  104. package/workspace/layout.js +113 -0
  105. package/workspace/manifest.d.ts +52 -0
  106. package/workspace/manifest.js +157 -0
  107. package/workspace/recipients.d.ts +16 -0
  108. package/workspace/recipients.js +45 -0
  109. package/workspace/snippets.d.ts +29 -0
  110. package/workspace/snippets.js +58 -0
  111. package/workspace/state.d.ts +13 -0
  112. package/workspace/state.js +52 -0
  113. package/workspace/status.d.ts +54 -0
  114. package/workspace/status.js +99 -0
  115. package/workspace/tar.d.ts +29 -0
  116. package/workspace/tar.js +240 -0
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runDoctor = void 0;
4
+ const fs_1 = require("fs");
5
+ const errors_1 = require("../utils/errors");
6
+ const recipients_1 = require("../utils/recipients");
7
+ const text_1 = require("../utils/text");
8
+ const git_1 = require("./git");
9
+ const guard_1 = require("./guard");
10
+ const layout_1 = require("./layout");
11
+ const recipients_2 = require("./recipients");
12
+ const state_1 = require("./state");
13
+ const status_1 = require("./status");
14
+ /**
15
+ * `dcrypt doctor`: everything that should be true of a machine and a workspace before either is
16
+ * trusted with a section. It reads; it changes nothing, and it never asks for a passphrase.
17
+ */
18
+ const MINIMUM_NODE_MAJOR = 20;
19
+ const check = (name, level, message) => ({ name, level, message });
20
+ const nodeCheck = () => {
21
+ const version = process.versions.node;
22
+ return Number(version.split('.')[0]) >= MINIMUM_NODE_MAJOR
23
+ ? check('node', 'ok', `Node.js ${version}`)
24
+ : check('node', 'fail', `Node.js ${version} is too old; ${MINIMUM_NODE_MAJOR} or newer is needed`);
25
+ };
26
+ const identityCheck = (mine) => mine
27
+ ? check('identity', 'ok', `this machine's identity is ${mine}`)
28
+ : check('identity', 'fail', 'no identity on this machine; run `dcrypt keys generate`');
29
+ const readRecipients = (workspace) => {
30
+ if (!(0, fs_1.existsSync)(workspace.recipientsFile)) {
31
+ return check('recipients', 'fail', `no recipients.txt in ${workspace.root}`);
32
+ }
33
+ try {
34
+ return (0, recipients_1.readRecipientsFile)(workspace.recipientsFile);
35
+ }
36
+ catch (error) {
37
+ return check('recipients', 'fail', (0, errors_1.messageFor)(error));
38
+ }
39
+ };
40
+ const recipientChecks = (entries, mine) => {
41
+ if (!entries.length)
42
+ return [check('recipients', 'fail', 'recipients.txt lists no recipients')];
43
+ const checks = [check('recipients', 'ok', `recipients.txt lists ${(0, text_1.count)(entries.length, 'recipient')}`)];
44
+ checks.push(entries.some(recipients_2.isRecovery)
45
+ ? check('recovery', 'ok', 'there is a recovery recipient')
46
+ : check('recovery', 'warn', recipients_2.NO_RECOVERY_WARNING));
47
+ if (entries.length === 1) {
48
+ checks.push(check('recipients', 'warn', 'there is only one recipient: one lost key loses everything'));
49
+ }
50
+ if (mine && !entries.some((entry) => (0, recipients_2.fingerprintOf)(entry.recipient) === mine)) {
51
+ checks.push(check('recipients', 'warn', `this machine's identity (${mine}) is not in recipients.txt`));
52
+ }
53
+ return checks;
54
+ };
55
+ const sectionChecks = async (workspace, sections, recipients) => {
56
+ if (!sections.length)
57
+ return [check('sections', 'ok', 'no sections are encrypted yet')];
58
+ const state = (0, state_1.readState)(workspace);
59
+ const checks = [];
60
+ for (const section of sections) {
61
+ const report = await (0, status_1.inspectSection)(section, state[section.name], recipients);
62
+ const advice = (0, status_1.adviceFor)(report);
63
+ const level = report.problem ? 'fail' : advice ? 'warn' : 'ok';
64
+ checks.push(check(`section ${section.name}`, level, advice ? `${report.state}: ${advice}` : report.state));
65
+ }
66
+ return checks;
67
+ };
68
+ const isIgnored = (workspace, path) => (0, git_1.ignoredPaths)(workspace.root, [path]).length > 0;
69
+ const repositoryChecks = async (workspace, sections) => {
70
+ if (!(0, git_1.isRepository)(workspace.root)) {
71
+ return [check('git', 'warn', 'not a git repository: nothing here checks what gets committed')];
72
+ }
73
+ const checks = [
74
+ (0, guard_1.isHookInstalled)(workspace)
75
+ ? check('guard', 'ok', 'the pre-commit guard is installed')
76
+ : check('guard', 'warn', 'no pre-commit guard; run `dcrypt guard install`'),
77
+ ];
78
+ const exposed = sections.filter((section) => !isIgnored(workspace, `${section.name}/file`));
79
+ checks.push(exposed.length
80
+ ? check('gitignore', 'fail', `git does not ignore the plaintext of: ${exposed.map((section) => section.name).join(', ')} (see \`dcrypt guard snippet gitignore\`)`)
81
+ : check('gitignore', 'ok', 'git ignores the plaintext of every section'));
82
+ if (!isIgnored(workspace, `${layout_1.STATE_DIRECTORY}/state.json`)) {
83
+ checks.push(check('gitignore', 'warn', `git does not ignore ${layout_1.STATE_DIRECTORY}/`));
84
+ }
85
+ const outsideLfs = sections.filter((section) => (0, git_1.attributeOf)(workspace.root, 'filter', section.name + layout_1.BUNDLE_SUFFIX) !== 'lfs');
86
+ if (outsideLfs.length) {
87
+ checks.push(check('lfs', 'warn', 'bundles are not stored with Git LFS (see `dcrypt guard snippet gitattributes`)'));
88
+ }
89
+ const { violations } = await (0, guard_1.runGuard)(workspace, 'all');
90
+ checks.push(violations.length
91
+ ? check('tracked files', 'fail', `${(0, text_1.count)(violations.length, 'tracked file')} should not be in the repository; run \`dcrypt guard --all\``)
92
+ : check('tracked files', 'ok', 'nothing tracked is plaintext'));
93
+ return checks;
94
+ };
95
+ const runDoctor = async (workspace) => {
96
+ const mine = (0, recipients_2.ownFingerprint)();
97
+ const recipients = readRecipients(workspace);
98
+ const entries = Array.isArray(recipients) ? recipients : undefined;
99
+ const sections = (0, layout_1.discoverSections)(workspace);
100
+ return [
101
+ nodeCheck(),
102
+ identityCheck(mine),
103
+ ...(entries ? recipientChecks(entries, mine) : [recipients]),
104
+ ...(await sectionChecks(workspace, sections, entries?.map((entry) => (0, recipients_2.fingerprintOf)(entry.recipient)))),
105
+ ...(await repositoryChecks(workspace, sections)),
106
+ ];
107
+ };
108
+ exports.runDoctor = runDoctor;
@@ -0,0 +1,21 @@
1
+ export declare const isRepository: (root: string) => boolean;
2
+ /** The top of the working tree `root` is in. */
3
+ export declare const repositoryRoot: (root: string) => string;
4
+ /** Where this repository's hooks live, honouring `core.hooksPath`. */
5
+ export declare const hooksDirectory: (root: string) => string;
6
+ /** Files added or changed in the index: what the next commit would record. */
7
+ export declare const stagedPaths: (root: string) => string[];
8
+ /** Every file in the index. */
9
+ export declare const trackedPaths: (root: string) => string[];
10
+ /**
11
+ * The subset of `paths` the ignore rules match. `--no-index` asks about the rules alone, so a
12
+ * file that was force-added, and is therefore tracked, is still reported.
13
+ */
14
+ export declare const ignoredPaths: (root: string, paths: string[]) => string[];
15
+ /** The value of a gitattribute for a path: "lfs", "unspecified", … */
16
+ export declare const attributeOf: (root: string, attribute: string, path: string) => string;
17
+ /**
18
+ * The first bytes of a file as it is in the index: what a commit would record, which is not
19
+ * always what is in the working tree. Only the head is read, however large the blob.
20
+ */
21
+ export declare const indexedHead: (root: string, path: string, length: number) => Promise<Buffer>;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.indexedHead = exports.attributeOf = exports.ignoredPaths = exports.trackedPaths = exports.stagedPaths = exports.hooksDirectory = exports.repositoryRoot = exports.isRepository = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const bytes_1 = require("../utils/bytes");
8
+ const errors_1 = require("../utils/errors");
9
+ /**
10
+ * The few questions the guard and `doctor` ask of git, each answered by git itself. Nothing here
11
+ * changes a repository. Paths are relative to `root`, which is the workspace root.
12
+ */
13
+ const MAX_OUTPUT = 256 * 1024 * 1024;
14
+ const git = (root, args, input) => {
15
+ const result = (0, child_process_1.spawnSync)('git', args, { cwd: root, input, encoding: 'utf8', maxBuffer: MAX_OUTPUT });
16
+ if (result.error)
17
+ throw new errors_1.CliError(`cannot run git: ${result.error.message}`);
18
+ return { status: result.status ?? 1, stdout: result.stdout };
19
+ };
20
+ const gitOrThrow = (root, args) => {
21
+ const { status, stdout } = git(root, args);
22
+ if (status !== 0)
23
+ throw new errors_1.CliError(`git ${args[0]} failed in ${root}`);
24
+ return stdout;
25
+ };
26
+ const nulSeparated = (output) => output.split('\0').filter(Boolean);
27
+ const isRepository = (root) => git(root, ['rev-parse', '--is-inside-work-tree']).stdout.trim() === 'true';
28
+ exports.isRepository = isRepository;
29
+ /** The top of the working tree `root` is in. */
30
+ const repositoryRoot = (root) => (0, fs_1.realpathSync)(gitOrThrow(root, ['rev-parse', '--show-toplevel']).trim());
31
+ exports.repositoryRoot = repositoryRoot;
32
+ /** Where this repository's hooks live, honouring `core.hooksPath`. */
33
+ const hooksDirectory = (root) => (0, path_1.resolve)(root, gitOrThrow(root, ['rev-parse', '--git-path', 'hooks']).trim());
34
+ exports.hooksDirectory = hooksDirectory;
35
+ /** Files added or changed in the index: what the next commit would record. */
36
+ const stagedPaths = (root) => nulSeparated(gitOrThrow(root, ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '--relative', '-z']));
37
+ exports.stagedPaths = stagedPaths;
38
+ /** Every file in the index. */
39
+ const trackedPaths = (root) => nulSeparated(gitOrThrow(root, ['ls-files', '-z']));
40
+ exports.trackedPaths = trackedPaths;
41
+ /**
42
+ * The subset of `paths` the ignore rules match. `--no-index` asks about the rules alone, so a
43
+ * file that was force-added, and is therefore tracked, is still reported.
44
+ */
45
+ const ignoredPaths = (root, paths) => {
46
+ if (!paths.length)
47
+ return [];
48
+ const { status, stdout } = git(root, ['check-ignore', '--no-index', '-z', '--stdin'], paths.join('\0'));
49
+ // 0: some are ignored. 1: none are. Anything else is git failing.
50
+ if (status > 1)
51
+ throw new errors_1.CliError(`git check-ignore failed in ${root}`);
52
+ return nulSeparated(stdout);
53
+ };
54
+ exports.ignoredPaths = ignoredPaths;
55
+ /** The value of a gitattribute for a path: "lfs", "unspecified", … */
56
+ const attributeOf = (root, attribute, path) => gitOrThrow(root, ['check-attr', attribute, '--', path]).trim().split(': ').pop() ?? '';
57
+ exports.attributeOf = attributeOf;
58
+ /**
59
+ * The first bytes of a file as it is in the index: what a commit would record, which is not
60
+ * always what is in the working tree. Only the head is read, however large the blob.
61
+ */
62
+ const indexedHead = async (root, path, length) => {
63
+ const child = (0, child_process_1.spawn)('git', ['cat-file', 'blob', `:./${path}`], {
64
+ cwd: root,
65
+ stdio: ['ignore', 'pipe', 'ignore'],
66
+ });
67
+ const exited = new Promise((resolve) => {
68
+ child.on('error', () => resolve(null));
69
+ child.on('close', resolve);
70
+ });
71
+ try {
72
+ const head = Buffer.from((await new bytes_1.ByteReader(child.stdout).fill(length)).subarray(0, length));
73
+ // Nothing read is an empty file only if git says so: a git that failed must not pass for one.
74
+ if (!head.length && (await exited) !== 0)
75
+ throw new errors_1.CliError(`cannot read ${path} from the git index`);
76
+ return head;
77
+ }
78
+ finally {
79
+ child.stdout.destroy();
80
+ child.kill();
81
+ }
82
+ };
83
+ exports.indexedHead = indexedHead;
@@ -0,0 +1,23 @@
1
+ import { Workspace } from './layout';
2
+ export type GuardScope = 'staged' | 'all';
3
+ export interface Violation {
4
+ path: string;
5
+ rule: 'plaintext' | 'not encrypted' | 'ignored';
6
+ message: string;
7
+ }
8
+ export interface GuardResult {
9
+ scope: GuardScope;
10
+ checked: number;
11
+ violations: Violation[];
12
+ }
13
+ /** Checks the given paths (relative to the workspace root) as they stand in the index. */
14
+ export declare const checkPaths: (workspace: Workspace, paths: string[]) => Promise<Violation[]>;
15
+ /** Runs the guard over what is staged, or over everything tracked. */
16
+ export declare const runGuard: (workspace: Workspace, scope: GuardScope) => Promise<GuardResult>;
17
+ /** True when this repository's pre-commit hook is the one `dcrypt guard install` writes. */
18
+ export declare const isHookInstalled: (workspace: Workspace) => boolean;
19
+ /**
20
+ * Installs the pre-commit hook. A hook that is already there and is not ours is left alone
21
+ * unless `force` is set.
22
+ */
23
+ export declare const installHook: (workspace: Workspace, force?: boolean) => string;
@@ -0,0 +1,118 @@
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;
@@ -0,0 +1,47 @@
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[];
@@ -0,0 +1,113 @@
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;
@@ -0,0 +1,52 @@
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>;