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,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolvePassphrase = void 0;
4
+ const fs_1 = require("fs");
5
+ const env_1 = require("./env");
6
+ const errors_1 = require("./errors");
7
+ const io_1 = require("./io");
8
+ /**
9
+ * Resolves a passphrase without ever accepting one on the command line.
10
+ *
11
+ * Order: `--passphrase-file <path>`, `DCRYPT_PASSPHRASE`, `--passphrase-stdin`, then an
12
+ * interactive masked prompt. Passing `--passphrase` is rejected outright: argv is visible
13
+ * to every process on the machine.
14
+ */
15
+ const resolvePassphrase = async (argv, prompter, options = {}) => {
16
+ if (argv.passphrase !== undefined || argv.password !== undefined) {
17
+ throw new errors_1.CliError('refusing to read a passphrase from argv (it is visible in `ps`); use --passphrase-file <path> or --passphrase-stdin');
18
+ }
19
+ const file = argv['passphrase-file'] ?? argv.passphraseFile;
20
+ if (typeof file === 'string' && file.length) {
21
+ try {
22
+ return (0, fs_1.readFileSync)(file, 'utf8').replace(/\r?\n$/, '');
23
+ }
24
+ catch {
25
+ throw new errors_1.CliError(`cannot read passphrase file ${file}`, errors_1.EXIT.notFound);
26
+ }
27
+ }
28
+ const fromEnvironment = (0, env_1.fromEnv)('passphrase');
29
+ if (fromEnvironment !== undefined) {
30
+ return fromEnvironment.replace(/\r?\n$/, '');
31
+ }
32
+ if (argv['passphrase-stdin'] || argv.passphraseStdin) {
33
+ return (0, io_1.readStdin)().replace(/\r?\n$/, '');
34
+ }
35
+ if (!process.stdin.isTTY) {
36
+ throw new errors_1.CliError('no passphrase: stdin is not a terminal, so there is nothing to prompt on; use --passphrase-file <path>, DCRYPT_PASSPHRASE or --passphrase-stdin');
37
+ }
38
+ const message = options.message ?? 'Passphrase';
39
+ const { passphrase } = await prompter.prompt({}, [
40
+ { type: 'password', name: 'passphrase', message, required: true },
41
+ ]);
42
+ if (!passphrase)
43
+ throw new errors_1.CliError('a passphrase is required');
44
+ if (options.confirm) {
45
+ const { confirmation } = await prompter.prompt({}, [
46
+ { type: 'password', name: 'confirmation', message: 'Confirm passphrase', required: true },
47
+ ]);
48
+ if (confirmation !== passphrase)
49
+ throw new errors_1.CliError('passphrases do not match');
50
+ }
51
+ return passphrase;
52
+ };
53
+ exports.resolvePassphrase = resolvePassphrase;
@@ -0,0 +1,28 @@
1
+ import { ParsedArgs } from 'minimist';
2
+ /** One line of a recipients file. */
3
+ export interface RecipientEntry {
4
+ /** Canonical `dcrypt1…` string. */
5
+ recipient: string;
6
+ /** Everything after the key on its line; free text, may be empty. */
7
+ label: string;
8
+ /** 1-based line number, for messages. */
9
+ line: number;
10
+ }
11
+ /**
12
+ * Parses a recipients file: one `dcrypt1…` public key per line, optionally followed by a label.
13
+ * Blank lines and lines starting with `#` are ignored. Keys are public, so the file is safe to
14
+ * commit.
15
+ *
16
+ * ```text
17
+ * # who can open this
18
+ * dcrypt1qxy… ada (laptop)
19
+ * dcrypt1qab… recovery — printed, in the safe
20
+ * ```
21
+ */
22
+ export declare const parseRecipients: (text: string, origin?: string) => RecipientEntry[];
23
+ export declare const readRecipientsFile: (path: string) => RecipientEntry[];
24
+ /**
25
+ * Recipients named on the command line: every `--recipient <dcrypt1…>` and every line of every
26
+ * `--recipients-file <path>`, de-duplicated, in the order given.
27
+ */
28
+ export declare const collectRecipients: (argv: ParsedArgs) => string[];
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collectRecipients = exports.readRecipientsFile = exports.parseRecipients = void 0;
4
+ const keys_1 = require("@decryption/keys");
5
+ const fs_1 = require("fs");
6
+ const errors_1 = require("./errors");
7
+ /**
8
+ * Parses a recipients file: one `dcrypt1…` public key per line, optionally followed by a label.
9
+ * Blank lines and lines starting with `#` are ignored. Keys are public, so the file is safe to
10
+ * commit.
11
+ *
12
+ * ```text
13
+ * # who can open this
14
+ * dcrypt1qxy… ada (laptop)
15
+ * dcrypt1qab… recovery — printed, in the safe
16
+ * ```
17
+ */
18
+ const parseRecipients = (text, origin = 'recipients') => {
19
+ const entries = [];
20
+ const seen = new Set();
21
+ text.split(/\r?\n/).forEach((raw, index) => {
22
+ const line = raw.trim();
23
+ if (!line || line.startsWith('#'))
24
+ return;
25
+ const [key, ...rest] = line.split(/\s+/);
26
+ let recipient;
27
+ try {
28
+ recipient = (0, keys_1.recipientToString)((0, keys_1.recipientFromString)(key));
29
+ }
30
+ catch (error) {
31
+ throw new errors_1.CliError(`${origin}:${index + 1}: ${(0, errors_1.messageFor)(error)}`);
32
+ }
33
+ if (seen.has(recipient))
34
+ return;
35
+ seen.add(recipient);
36
+ entries.push({ recipient, label: rest.join(' '), line: index + 1 });
37
+ });
38
+ return entries;
39
+ };
40
+ exports.parseRecipients = parseRecipients;
41
+ const readRecipientsFile = (path) => {
42
+ let text;
43
+ try {
44
+ text = (0, fs_1.readFileSync)(path, 'utf8');
45
+ }
46
+ catch {
47
+ throw new errors_1.CliError(`cannot read recipients file ${path}`, errors_1.EXIT.notFound);
48
+ }
49
+ return (0, exports.parseRecipients)(text, path);
50
+ };
51
+ exports.readRecipientsFile = readRecipientsFile;
52
+ const values = (value, flag) => {
53
+ if (value === undefined)
54
+ return [];
55
+ const list = Array.isArray(value) ? value : [value];
56
+ return list.map((item) => {
57
+ if (typeof item !== 'string' || !item.length)
58
+ throw new errors_1.CliError(`${flag} needs a value`);
59
+ return item;
60
+ });
61
+ };
62
+ /**
63
+ * Recipients named on the command line: every `--recipient <dcrypt1…>` and every line of every
64
+ * `--recipients-file <path>`, de-duplicated, in the order given.
65
+ */
66
+ const collectRecipients = (argv) => {
67
+ const direct = values(argv.recipient, '--recipient').map((value) => {
68
+ try {
69
+ return (0, keys_1.recipientToString)((0, keys_1.recipientFromString)(value));
70
+ }
71
+ catch (error) {
72
+ throw new errors_1.CliError(`--recipient ${value}: ${(0, errors_1.messageFor)(error)}`);
73
+ }
74
+ });
75
+ const fromFiles = values(argv['recipients-file'] ?? argv.recipientsFile, '--recipients-file')
76
+ .flatMap((path) => (0, exports.readRecipientsFile)(path))
77
+ .map((entry) => entry.recipient);
78
+ return [...new Set([...direct, ...fromFiles])];
79
+ };
80
+ exports.collectRecipients = collectRecipients;
@@ -0,0 +1,40 @@
1
+ import { KdfParams, KdfProfile } from '@decryption/core';
2
+ import { Identity } from '@decryption/keys';
3
+ /**
4
+ * On-disk layout, shared byte-for-byte with the Electron app:
5
+ *
6
+ * ```text
7
+ * ~/.dcrypt/
8
+ * config/identity.json the user's X25519 identity, encrypted under a passphrase
9
+ * data/keychain.json named secrets, each encrypted under a passphrase
10
+ * (KEYCHAIN_ACCOUNT selects keychain-<account>.json instead)
11
+ * data/vaults/<name>.json team secrets files
12
+ * ```
13
+ *
14
+ * Nothing here is ever written in plaintext.
15
+ */
16
+ export declare const APP_NAME = "dcrypt";
17
+ export declare const dirs: () => import("appstash").AppStashResult;
18
+ export declare const identityPath: () => string;
19
+ export declare const keychainPath: () => string;
20
+ export declare const vaultPath: (name: string) => string;
21
+ export interface StoredIdentity {
22
+ version: 1;
23
+ /** Public recipient string — safe to store in the clear, and to share. */
24
+ recipient: string;
25
+ /** Armored envelope holding the private key. */
26
+ encrypted: string;
27
+ }
28
+ export interface Keychain {
29
+ version: 1;
30
+ entries: Record<string, string>;
31
+ }
32
+ export declare const hasIdentity: () => boolean;
33
+ export declare const saveIdentity: (identity: Identity, passphrase: string, kdf?: KdfProfile | KdfParams) => StoredIdentity;
34
+ export declare const readStoredIdentity: () => StoredIdentity;
35
+ export declare const loadIdentity: (passphrase: string) => Identity;
36
+ export declare const readKeychain: () => Keychain;
37
+ export declare const writeKeychain: (keychain: Keychain) => void;
38
+ export declare const readJson: <T>(path: string) => T;
39
+ /** Writes JSON with owner-only permissions and a trailing newline. */
40
+ export declare const writeJson: (path: string, value: unknown) => void;
package/utils/stash.js ADDED
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.writeJson = exports.readJson = exports.writeKeychain = exports.readKeychain = exports.loadIdentity = exports.readStoredIdentity = exports.saveIdentity = exports.hasIdentity = exports.vaultPath = exports.keychainPath = exports.identityPath = exports.dirs = exports.APP_NAME = void 0;
4
+ const core_1 = require("@decryption/core");
5
+ const keys_1 = require("@decryption/keys");
6
+ const appstash_1 = require("appstash");
7
+ const fs_1 = require("fs");
8
+ const path_1 = require("path");
9
+ const env_1 = require("./env");
10
+ const errors_1 = require("./errors");
11
+ /**
12
+ * On-disk layout, shared byte-for-byte with the Electron app:
13
+ *
14
+ * ```text
15
+ * ~/.dcrypt/
16
+ * config/identity.json the user's X25519 identity, encrypted under a passphrase
17
+ * data/keychain.json named secrets, each encrypted under a passphrase
18
+ * (KEYCHAIN_ACCOUNT selects keychain-<account>.json instead)
19
+ * data/vaults/<name>.json team secrets files
20
+ * ```
21
+ *
22
+ * Nothing here is ever written in plaintext.
23
+ */
24
+ exports.APP_NAME = 'dcrypt';
25
+ const dirs = () => (0, appstash_1.appstash)(exports.APP_NAME, { ensure: true });
26
+ exports.dirs = dirs;
27
+ const identityPath = () => (0, appstash_1.resolve)((0, exports.dirs)(), 'config', 'identity.json');
28
+ exports.identityPath = identityPath;
29
+ const keychainPath = () => {
30
+ const account = (0, env_1.keychainAccount)();
31
+ const file = account === 'dcrypt' ? 'keychain.json' : `keychain-${account}.json`;
32
+ return (0, appstash_1.resolve)((0, exports.dirs)(), 'data', file);
33
+ };
34
+ exports.keychainPath = keychainPath;
35
+ const vaultPath = (name) => (0, path_1.join)((0, appstash_1.resolve)((0, exports.dirs)(), 'data', 'vaults'), `${name}.json`);
36
+ exports.vaultPath = vaultPath;
37
+ const hasIdentity = () => (0, fs_1.existsSync)((0, exports.identityPath)());
38
+ exports.hasIdentity = hasIdentity;
39
+ const saveIdentity = (identity, passphrase, kdf = 'moderate') => {
40
+ const stored = {
41
+ version: 1,
42
+ recipient: (0, keys_1.recipientToString)(identity.publicKey),
43
+ encrypted: (0, core_1.encryptToString)((0, keys_1.identityToString)(identity), passphrase, { kdf }),
44
+ };
45
+ (0, exports.writeJson)((0, exports.identityPath)(), stored);
46
+ return stored;
47
+ };
48
+ exports.saveIdentity = saveIdentity;
49
+ const readStoredIdentity = () => {
50
+ if (!(0, exports.hasIdentity)()) {
51
+ throw new errors_1.CliError('no identity yet — run `dcrypt keys generate`', errors_1.EXIT.notFound);
52
+ }
53
+ return (0, exports.readJson)((0, exports.identityPath)());
54
+ };
55
+ exports.readStoredIdentity = readStoredIdentity;
56
+ const loadIdentity = (passphrase) => (0, keys_1.identityFromString)((0, core_1.decryptFromString)((0, exports.readStoredIdentity)().encrypted, passphrase));
57
+ exports.loadIdentity = loadIdentity;
58
+ const readKeychain = () => (0, fs_1.existsSync)((0, exports.keychainPath)()) ? (0, exports.readJson)((0, exports.keychainPath)()) : { version: 1, entries: {} };
59
+ exports.readKeychain = readKeychain;
60
+ const writeKeychain = (keychain) => (0, exports.writeJson)((0, exports.keychainPath)(), keychain);
61
+ exports.writeKeychain = writeKeychain;
62
+ const readJson = (path) => {
63
+ try {
64
+ return JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
65
+ }
66
+ catch {
67
+ throw new errors_1.CliError(`cannot read ${path}`, errors_1.EXIT.corrupt);
68
+ }
69
+ };
70
+ exports.readJson = readJson;
71
+ /** Writes JSON with owner-only permissions and a trailing newline. */
72
+ const writeJson = (path, value) => {
73
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(path), { recursive: true });
74
+ (0, fs_1.writeFileSync)(path, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
75
+ };
76
+ exports.writeJson = writeJson;
@@ -0,0 +1,10 @@
1
+ /** A sibling path of `target`, so that renaming onto `target` never crosses a filesystem. */
2
+ export declare const tempPathFor: (target: string) => string;
3
+ /** True for names produced by {@link tempPathFor}. */
4
+ export declare const isTempName: (name: string) => boolean;
5
+ /** Registers `path` for removal if the process is interrupted. */
6
+ export declare const trackTemp: (path: string) => void;
7
+ /** Forgets `path`: call once it has been renamed into place or removed. */
8
+ export declare const untrackTemp: (path: string) => void;
9
+ /** Removes a temporary path now and forgets it. */
10
+ export declare const discardTemp: (path: string) => void;
package/utils/temp.js ADDED
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.discardTemp = exports.untrackTemp = exports.trackTemp = exports.isTempName = exports.tempPathFor = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ /**
8
+ * Temporary files and directories that must not outlive the command.
9
+ *
10
+ * Output is always built next to its destination and renamed into place, so an interrupted run
11
+ * leaves the destination exactly as it was. What an interrupt would leave behind is the
12
+ * half-written temporary itself, which may hold plaintext; everything registered here is removed
13
+ * on Ctrl-C and on termination.
14
+ */
15
+ const live = new Set();
16
+ const remove = (path) => {
17
+ try {
18
+ (0, fs_1.rmSync)(path, { recursive: true, force: true });
19
+ }
20
+ catch {
21
+ // best effort: there is nothing useful to do about a temp file that will not delete
22
+ }
23
+ };
24
+ const onSignal = (signal) => {
25
+ for (const path of live)
26
+ remove(path);
27
+ live.clear();
28
+ process.exit(signal === 'SIGINT' ? 130 : 143);
29
+ };
30
+ /** A sibling path of `target`, so that renaming onto `target` never crosses a filesystem. */
31
+ const tempPathFor = (target) => (0, path_1.join)((0, path_1.dirname)(target), `.${(0, path_1.basename)(target)}.dcrypt-tmp-${(0, crypto_1.randomBytes)(6).toString('hex')}`);
32
+ exports.tempPathFor = tempPathFor;
33
+ /** True for names produced by {@link tempPathFor}. */
34
+ const isTempName = (name) => /\.dcrypt-tmp-[0-9a-f]{12}$/.test(name);
35
+ exports.isTempName = isTempName;
36
+ /** Registers `path` for removal if the process is interrupted. */
37
+ const trackTemp = (path) => {
38
+ if (live.size === 0) {
39
+ process.on('SIGINT', onSignal);
40
+ process.on('SIGTERM', onSignal);
41
+ }
42
+ live.add(path);
43
+ };
44
+ exports.trackTemp = trackTemp;
45
+ /** Forgets `path`: call once it has been renamed into place or removed. */
46
+ const untrackTemp = (path) => {
47
+ live.delete(path);
48
+ if (live.size === 0) {
49
+ process.removeListener('SIGINT', onSignal);
50
+ process.removeListener('SIGTERM', onSignal);
51
+ }
52
+ };
53
+ exports.untrackTemp = untrackTemp;
54
+ /** Removes a temporary path now and forgets it. */
55
+ const discardTemp = (path) => {
56
+ remove(path);
57
+ (0, exports.untrackTemp)(path);
58
+ };
59
+ exports.discardTemp = discardTemp;
@@ -0,0 +1,2 @@
1
+ /** "1 file", "3 files": a number with its noun, pluralised the regular way. */
2
+ export declare const count: (n: number, noun: string) => string;
package/utils/text.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.count = void 0;
4
+ /** "1 file", "3 files": a number with its noun, pluralised the regular way. */
5
+ const count = (n, noun) => `${n} ${noun}${n === 1 ? '' : 's'}`;
6
+ exports.count = count;
@@ -0,0 +1,50 @@
1
+ import { Identity } from '@decryption/keys';
2
+ import { CliError } from '../utils/errors';
3
+ import { Section } from './layout';
4
+ import { Manifest, Snapshot } from './manifest';
5
+ /** The bundle on disk is a Git LFS pointer: the real file has not been downloaded. */
6
+ export declare class LfsPointerError extends CliError {
7
+ constructor(path: string);
8
+ }
9
+ export interface BundleInfo {
10
+ /** SHA-256 of the bundle file. */
11
+ sha256: string;
12
+ /** Fingerprints of the recipients it is encrypted to. */
13
+ recipients: string[];
14
+ }
15
+ /** Reads what a bundle shows without a key: its hash, and who can open it. */
16
+ export declare const inspectBundle: (path: string) => Promise<BundleInfo>;
17
+ /**
18
+ * Encrypts a section to `recipients` and replaces its bundle atomically. Resolves to the new
19
+ * bundle's SHA-256. If a file changes underneath it, the old bundle is left as it was.
20
+ */
21
+ export declare const encryptSection: (section: Section, snapshot: Snapshot, recipients: string[]) => Promise<string>;
22
+ export interface Extraction {
23
+ /** A new folder beside the section, holding the bundle's files. Not yet the section itself. */
24
+ directory: string;
25
+ manifest: Manifest;
26
+ digest: string;
27
+ /** SHA-256 of the bundle that was read. */
28
+ bundle: string;
29
+ }
30
+ /**
31
+ * Decrypts a bundle into a new folder beside the section's own, which is not touched.
32
+ *
33
+ * It resolves only once every chunk has authenticated, the ciphertext is known to be complete,
34
+ * and every file matches the manifest. On any failure the new folder is removed and the error is
35
+ * rethrown: there is no partial result.
36
+ */
37
+ export declare const extractSection: (section: Section, identity: Identity) => Promise<Extraction>;
38
+ /**
39
+ * Makes an extracted folder the section's plaintext, replacing what was there.
40
+ *
41
+ * The two renames run back to back without returning to the event loop, so Ctrl-C cannot land
42
+ * between them. If the machine dies there instead, the previous plaintext is still on disk under
43
+ * its set-aside name, and {@link recoverSection} puts it back.
44
+ */
45
+ export declare const installExtraction: (section: Section, extraction: Extraction) => Promise<void>;
46
+ /**
47
+ * Cleans up after a run that was killed: restores a section's plaintext if it had been set aside
48
+ * and nothing took its place, and removes half-written leftovers. Returns true if it restored.
49
+ */
50
+ export declare const recoverSection: (section: Section) => boolean;
@@ -0,0 +1,248 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.recoverSection = exports.installExtraction = exports.extractSection = exports.encryptSection = exports.inspectBundle = exports.LfsPointerError = void 0;
4
+ const keys_1 = require("@decryption/keys");
5
+ const crypto_1 = require("crypto");
6
+ const fs_1 = require("fs");
7
+ const promises_1 = require("fs/promises");
8
+ const path_1 = require("path");
9
+ const promises_2 = require("stream/promises");
10
+ const bytes_1 = require("../utils/bytes");
11
+ const errors_1 = require("../utils/errors");
12
+ const header_1 = require("../utils/header");
13
+ const temp_1 = require("../utils/temp");
14
+ const layout_1 = require("./layout");
15
+ const manifest_1 = require("./manifest");
16
+ const tar_1 = require("./tar");
17
+ /**
18
+ * A bundle is a section's files as one encrypted file: a deterministic tar whose first entry is
19
+ * the manifest, inside the streamed envelope `dcrypt encrypt --binary --recipient` writes.
20
+ *
21
+ * Everything about the section is inside the encryption: file names, sizes, how many files there
22
+ * are. From outside, a bundle shows its own size and the fingerprints of its recipients.
23
+ *
24
+ * A bundle says nothing about who made it. Recipient keys are public, so anyone who has them can
25
+ * produce a bundle that decrypts cleanly. That is why extraction trusts nothing in one: every
26
+ * path is checked before a byte is written, and nothing is written outside a fresh folder.
27
+ */
28
+ const LFS_POINTER_PREFIX = 'version https://git-lfs.github.com/spec/';
29
+ /** Far more than any real manifest; it is held in memory, so it has a bound. */
30
+ const MAX_MANIFEST_SIZE = 256 * 1024 * 1024;
31
+ /** The bundle on disk is a Git LFS pointer: the real file has not been downloaded. */
32
+ class LfsPointerError extends errors_1.CliError {
33
+ constructor(path) {
34
+ super(`${path} is a Git LFS pointer, not the bundle itself; run \`git lfs pull\``, errors_1.EXIT.notFound);
35
+ this.name = 'LfsPointerError';
36
+ }
37
+ }
38
+ exports.LfsPointerError = LfsPointerError;
39
+ const mismatch = (message) => new errors_1.CliError(`the bundle does not match its manifest: ${message}`, errors_1.EXIT.corrupt);
40
+ const readFile = (path) => (0, fs_1.createReadStream)(path, { highWaterMark: bytes_1.IO_CHUNK_SIZE });
41
+ /** Passes bytes through unchanged, feeding each piece to `hash` on the way. */
42
+ async function* hashing(source, hash) {
43
+ for await (const piece of source) {
44
+ hash.update(piece);
45
+ yield piece;
46
+ }
47
+ }
48
+ /** Reads what a bundle shows without a key: its hash, and who can open it. */
49
+ const inspectBundle = async (path) => {
50
+ const input = readFile(path);
51
+ const hash = (0, crypto_1.createHash)('sha256');
52
+ try {
53
+ const reader = new bytes_1.ByteReader(hashing(input, hash));
54
+ const head = await reader.fill(LFS_POINTER_PREFIX.length);
55
+ if (head.toString('latin1').startsWith(LFS_POINTER_PREFIX))
56
+ throw new LfsPointerError(path);
57
+ const header = await (0, header_1.readFileHeader)(reader);
58
+ for await (const piece of reader.rest())
59
+ void piece;
60
+ return { sha256: hash.digest('hex'), recipients: (0, keys_1.fileRecipients)(header) };
61
+ }
62
+ finally {
63
+ input.destroy();
64
+ }
65
+ };
66
+ exports.inspectBundle = inspectBundle;
67
+ /** A file's bytes, with a check at the end that they are still the ones the manifest describes. */
68
+ async function* unchanged(file) {
69
+ const hash = (0, crypto_1.createHash)('sha256');
70
+ yield* hashing(readFile(file.source), hash);
71
+ if (hash.digest('hex') !== file.sha256) {
72
+ throw new errors_1.CliError(`${file.source} changed while it was being encrypted; run the command again`);
73
+ }
74
+ }
75
+ /** The archive's entries: the manifest first, then every file in manifest order. */
76
+ function* archiveEntries(snapshot) {
77
+ const manifest = (0, manifest_1.serializeManifest)(snapshot.manifest);
78
+ yield { path: manifest_1.MANIFEST_PATH, size: manifest.length, executable: false, content: [manifest] };
79
+ for (const file of snapshot.files) {
80
+ yield { path: file.path, size: file.size, executable: file.executable, content: unchanged(file) };
81
+ }
82
+ }
83
+ /**
84
+ * Encrypts a section to `recipients` and replaces its bundle atomically. Resolves to the new
85
+ * bundle's SHA-256. If a file changes underneath it, the old bundle is left as it was.
86
+ */
87
+ const encryptSection = async (section, snapshot, recipients) => {
88
+ const { header, stream } = (0, keys_1.createRecipientFileEncryptor)(recipients);
89
+ const hash = (0, crypto_1.createHash)('sha256');
90
+ try {
91
+ const archive = (0, bytes_1.transformBytes)((0, tar_1.writeTar)(archiveEntries(snapshot)), stream);
92
+ await (0, bytes_1.writeFileAtomically)(section.bundle, hashing((0, bytes_1.chainBytes)([header], archive), hash));
93
+ }
94
+ finally {
95
+ stream.destroy();
96
+ }
97
+ return hash.digest('hex');
98
+ };
99
+ exports.encryptSection = encryptSection;
100
+ const readManifest = async (entry) => {
101
+ if (entry.path !== manifest_1.MANIFEST_PATH)
102
+ throw mismatch('it does not begin with one');
103
+ if (entry.size > MAX_MANIFEST_SIZE)
104
+ throw mismatch('the manifest is implausibly large');
105
+ const pieces = [];
106
+ for await (const piece of entry.content)
107
+ pieces.push(piece);
108
+ return (0, manifest_1.parseManifest)(Buffer.concat(pieces));
109
+ };
110
+ /** Writes one archive entry to its place under `directory`, and checks it against the manifest. */
111
+ const writeEntry = async (directory, entry, expected) => {
112
+ const target = (0, path_1.join)(directory, ...expected.path.split('/'));
113
+ const hash = (0, crypto_1.createHash)('sha256');
114
+ const handle = await (0, promises_1.mkdir)((0, path_1.dirname)(target), { recursive: true, mode: 0o700 })
115
+ // "wx" refuses a name that is already there: two paths the file system considers the same.
116
+ .then(() => (0, promises_1.open)(target, 'wx', expected.executable ? 0o700 : 0o600))
117
+ .catch((error) => {
118
+ throw new errors_1.CliError(`cannot create "${expected.path}" (${error.code ?? 'error'}); two paths in the bundle may be the same on this file system`, errors_1.EXIT.corrupt);
119
+ });
120
+ await (0, promises_2.pipeline)(hashing(entry.content, hash), handle.createWriteStream());
121
+ if (hash.digest('hex') !== expected.sha256) {
122
+ throw mismatch(`"${expected.path}" does not have the content it lists`);
123
+ }
124
+ };
125
+ /**
126
+ * Writes an archive's files under `directory`, accepting exactly what the manifest lists, in the
127
+ * order it lists it. Paths come from the manifest, which {@link parseManifest} has vetted.
128
+ */
129
+ const extractArchive = async (entries, directory) => {
130
+ let manifest;
131
+ let index = 0;
132
+ for await (const entry of entries) {
133
+ if (!manifest) {
134
+ manifest = await readManifest(entry);
135
+ continue;
136
+ }
137
+ const expected = manifest.files[index++];
138
+ const listed = expected !== undefined &&
139
+ entry.path === expected.path &&
140
+ entry.size === expected.size &&
141
+ entry.executable === expected.executable;
142
+ if (!listed)
143
+ throw mismatch(`"${entry.path}" is not the file it lists next`);
144
+ await writeEntry(directory, entry, expected);
145
+ }
146
+ if (!manifest)
147
+ throw mismatch('it is empty');
148
+ if (index !== manifest.files.length)
149
+ throw mismatch('files it lists are missing');
150
+ return manifest;
151
+ };
152
+ /**
153
+ * Forces an extracted folder to disk: every file, then every folder, before it may replace
154
+ * anything. One pass at the end, not a sync as each file is closed: that waits for the device
155
+ * once per file, milliseconds each, where this pass costs next to nothing after its first sync.
156
+ */
157
+ const syncExtraction = async (directory, manifest) => {
158
+ const folders = new Set([directory]);
159
+ for (const { path } of manifest.files) {
160
+ const target = (0, path_1.join)(directory, ...path.split('/'));
161
+ await (0, bytes_1.syncFile)(target);
162
+ for (let folder = (0, path_1.dirname)(target); !folders.has(folder); folder = (0, path_1.dirname)(folder))
163
+ folders.add(folder);
164
+ }
165
+ for (const folder of folders)
166
+ await (0, bytes_1.syncDirectory)(folder);
167
+ };
168
+ /**
169
+ * Decrypts a bundle into a new folder beside the section's own, which is not touched.
170
+ *
171
+ * It resolves only once every chunk has authenticated, the ciphertext is known to be complete,
172
+ * and every file matches the manifest. On any failure the new folder is removed and the error is
173
+ * rethrown: there is no partial result.
174
+ */
175
+ const extractSection = async (section, identity) => {
176
+ const directory = (0, temp_1.tempPathFor)(section.directory);
177
+ await (0, promises_1.mkdir)(directory, { mode: 0o700 });
178
+ (0, temp_1.trackTemp)(directory);
179
+ const input = readFile(section.bundle);
180
+ const hash = (0, crypto_1.createHash)('sha256');
181
+ let decryptor;
182
+ try {
183
+ const reader = new bytes_1.ByteReader(hashing(input, hash));
184
+ decryptor = (0, keys_1.createIdentityFileDecryptor)(await (0, header_1.readFileHeader)(reader), identity);
185
+ const archive = (0, tar_1.readTar)((0, bytes_1.transformBytes)(reader.rest(), decryptor));
186
+ const manifest = await extractArchive(archive, directory);
187
+ await syncExtraction(directory, manifest);
188
+ return { directory, manifest, digest: (0, manifest_1.digestOf)(manifest), bundle: hash.digest('hex') };
189
+ }
190
+ catch (error) {
191
+ (0, temp_1.discardTemp)(directory);
192
+ throw error;
193
+ }
194
+ finally {
195
+ decryptor?.destroy();
196
+ input.destroy();
197
+ }
198
+ };
199
+ exports.extractSection = extractSection;
200
+ const setAsidePathFor = (directory) => (0, path_1.join)((0, path_1.dirname)(directory), `.${(0, path_1.basename)(directory)}${layout_1.REPLACED_MARKER}${(0, crypto_1.randomBytes)(6).toString('hex')}`);
201
+ /**
202
+ * Makes an extracted folder the section's plaintext, replacing what was there.
203
+ *
204
+ * The two renames run back to back without returning to the event loop, so Ctrl-C cannot land
205
+ * between them. If the machine dies there instead, the previous plaintext is still on disk under
206
+ * its set-aside name, and {@link recoverSection} puts it back.
207
+ */
208
+ const installExtraction = async (section, extraction) => {
209
+ const setAside = (0, fs_1.existsSync)(section.directory) ? setAsidePathFor(section.directory) : undefined;
210
+ if (setAside)
211
+ (0, fs_1.renameSync)(section.directory, setAside);
212
+ try {
213
+ (0, fs_1.renameSync)(extraction.directory, section.directory);
214
+ }
215
+ catch (error) {
216
+ if (setAside)
217
+ (0, fs_1.renameSync)(setAside, section.directory);
218
+ (0, temp_1.discardTemp)(extraction.directory);
219
+ throw error;
220
+ }
221
+ (0, temp_1.untrackTemp)(extraction.directory);
222
+ // The swap is on disk before the old plaintext goes, and before anyone records it as done.
223
+ await (0, bytes_1.syncDirectory)((0, path_1.dirname)(section.directory));
224
+ if (setAside)
225
+ (0, fs_1.rmSync)(setAside, { recursive: true, force: true });
226
+ };
227
+ exports.installExtraction = installExtraction;
228
+ /**
229
+ * Cleans up after a run that was killed: restores a section's plaintext if it had been set aside
230
+ * and nothing took its place, and removes half-written leftovers. Returns true if it restored.
231
+ */
232
+ const recoverSection = (section) => {
233
+ const parent = (0, path_1.dirname)(section.directory);
234
+ if (!(0, fs_1.existsSync)(parent))
235
+ return false;
236
+ const own = (name, target) => name.startsWith(`.${(0, path_1.basename)(target)}.dcrypt-`);
237
+ const names = (0, fs_1.readdirSync)(parent);
238
+ const setAside = names.filter((name) => own(name, section.directory) && name.includes(layout_1.REPLACED_MARKER));
239
+ const temporary = names.filter((name) => (0, temp_1.isTempName)(name) && (own(name, section.directory) || own(name, section.bundle)));
240
+ const restored = !(0, fs_1.existsSync)(section.directory) && setAside.length > 0;
241
+ if (restored)
242
+ (0, fs_1.renameSync)((0, path_1.join)(parent, setAside.shift()), section.directory);
243
+ for (const name of [...setAside, ...temporary]) {
244
+ (0, fs_1.rmSync)((0, path_1.join)(parent, name), { recursive: true, force: true });
245
+ }
246
+ return restored;
247
+ };
248
+ exports.recoverSection = recoverSection;
@@ -0,0 +1,8 @@
1
+ import { Workspace } from './layout';
2
+ export type CheckLevel = 'ok' | 'warn' | 'fail';
3
+ export interface Check {
4
+ name: string;
5
+ level: CheckLevel;
6
+ message: string;
7
+ }
8
+ export declare const runDoctor: (workspace: Workspace) => Promise<Check[]>;