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,283 @@
1
+ import { relative } from 'path';
2
+ import { takeFirst, wantsHelp } from '../utils/dispatch';
3
+ import { CliError, EXIT, exitCodeFor, messageFor } from '../utils/errors';
4
+ import { emit } from '../utils/io';
5
+ import { resolvePassphrase } from '../utils/passphrase';
6
+ import { loadIdentity, readStoredIdentity } from '../utils/stash';
7
+ import { discardTemp } from '../utils/temp';
8
+ import { count } from '../utils/text';
9
+ import { encryptSection, extractSection, installExtraction, recoverSection } from '../workspace/bundle';
10
+ import { discoverSections, findWorkspace, resolveSection } from '../workspace/layout';
11
+ import { fingerprintOf, readWorkspaceRecipients, recipientWarnings } from '../workspace/recipients';
12
+ import { readState, recordSection } from '../workspace/state';
13
+ import { adviceFor, inspectSection, recipientsDiffer } from '../workspace/status';
14
+ const WORKSPACE_OPTIONS = ` --workspace <dir> The workspace root (default: the nearest folder upwards with a
15
+ recipients.txt, otherwise the current folder)
16
+ --json Machine-readable output
17
+ --help, -h Show this help message`;
18
+ export const encryptSectionUsage = `
19
+ Encrypt Section Command:
20
+
21
+ dcrypt encrypt-section <name> [OPTIONS]
22
+
23
+ Encrypt the folder <name> into <name>.tar.dcrypt, for everyone in recipients.txt.
24
+ One section at a time, and only when you ask.
25
+
26
+ The bundle is a single encrypted file: the names, sizes and number of the files
27
+ inside it are not visible, only its total size. No passphrase is needed, because
28
+ encrypting uses only public keys. Nothing is rewritten when nothing changed, and
29
+ the bundle is replaced only once the new one is complete.
30
+
31
+ Options:
32
+ --force Replace a bundle that changed since this machine last read it
33
+ ${WORKSPACE_OPTIONS}
34
+
35
+ Examples:
36
+ dcrypt encrypt-section finance
37
+ dcrypt encrypt-section clients/northwind
38
+ `;
39
+ export const decryptWorkspaceUsage = `
40
+ Decrypt Workspace Command:
41
+
42
+ dcrypt decrypt-workspace [name…] [OPTIONS]
43
+
44
+ Decrypt every section of the workspace (or only the ones named) with your
45
+ identity. You are asked for its passphrase once, and not at all when every
46
+ section is already up to date.
47
+
48
+ Each bundle is decrypted into a new folder and checked, file by file, against
49
+ the manifest inside it. Only then does it replace the plaintext. A wrong
50
+ passphrase, a damaged or truncated bundle, or an interrupt changes nothing.
51
+ Plaintext you have edited and not yet encrypted is never replaced without --force.
52
+
53
+ Options:
54
+ --force Replace plaintext that has changes the bundle does not have
55
+ --passphrase-file <p> Read the identity passphrase from a file
56
+ --passphrase-stdin Read the identity passphrase from stdin
57
+ ${WORKSPACE_OPTIONS}
58
+
59
+ Examples:
60
+ dcrypt decrypt-workspace
61
+ dcrypt decrypt-workspace finance
62
+ `;
63
+ export const statusUsage = `
64
+ Status Command:
65
+
66
+ dcrypt status [OPTIONS]
67
+
68
+ Show where each section stands: in sync, plaintext changed and not yet
69
+ encrypted, bundle changed and not yet decrypted, and whether a recipient in
70
+ recipients.txt is missing from a bundle. Needs no passphrase.
71
+
72
+ Options:
73
+ ${WORKSPACE_OPTIONS}
74
+ `;
75
+ const warn = (message) => void process.stderr.write(`warning: ${message}\n`);
76
+ /** Finishes whatever a killed run left half-done, and says so when plaintext was put back. */
77
+ const recover = (section) => {
78
+ if (recoverSection(section))
79
+ warn(`restored ${section.name} after an interrupted run`);
80
+ };
81
+ const STALE_BUNDLE = {
82
+ 'bundle changed': 'its bundle has changed since this machine last decrypted it',
83
+ conflict: 'its bundle has changed since this machine last decrypted it',
84
+ unknown: 'this machine has never decrypted its bundle, so it may hold changes you do not have',
85
+ 'not downloaded': 'its bundle is a Git LFS pointer (run `git lfs pull` first)',
86
+ 'bundle unreadable': 'its bundle cannot be read (restore it from git first)',
87
+ };
88
+ export const encryptSectionCommand = async (argv) => {
89
+ if (wantsHelp(argv, encryptSectionUsage))
90
+ return;
91
+ const { first: name, newArgv } = takeFirst(argv);
92
+ if (!name || newArgv._.length) {
93
+ throw new CliError('name one section: dcrypt encrypt-section <name>');
94
+ }
95
+ const workspace = findWorkspace(newArgv);
96
+ const section = resolveSection(workspace, name);
97
+ const recipients = readWorkspaceRecipients(workspace);
98
+ recover(section);
99
+ const report = await inspectSection(section, readState(workspace)[section.name], recipients.map((entry) => fingerprintOf(entry.recipient)));
100
+ const { snapshot } = report;
101
+ if (report.state === 'plaintext unreadable')
102
+ throw new CliError(adviceFor(report));
103
+ if (!snapshot)
104
+ throw new CliError(`there is no folder ${section.directory} to encrypt`, EXIT.notFound);
105
+ if (!snapshot.files.length)
106
+ throw new CliError(`${section.directory} has no files to encrypt`);
107
+ const bundle = relative(workspace.root, section.bundle);
108
+ const summary = { section: section.name, bundle, files: snapshot.files.length, recipients: recipients.length };
109
+ if (report.state === 'in sync' && !recipientsDiffer(report)) {
110
+ emit(newArgv, { ...summary, changed: false }, () => `${section.name}: unchanged, ${bundle} is up to date`);
111
+ return;
112
+ }
113
+ const stale = STALE_BUNDLE[report.state];
114
+ if (stale && !newArgv.force) {
115
+ throw new CliError(`${section.name} was not encrypted: ${stale}. Run \`dcrypt decrypt-workspace\`, or pass --force to replace the bundle with what is on this machine.`);
116
+ }
117
+ const sha256 = await encryptSection(section, snapshot, recipients.map((entry) => entry.recipient));
118
+ await recordSection(workspace, section.name, { digest: snapshot.digest, bundle: sha256 });
119
+ recipientWarnings(recipients).forEach(warn);
120
+ emit(newArgv, { ...summary, changed: true }, () => `${section.name}: encrypted ${count(summary.files, 'file')} to ${count(summary.recipients, 'recipient')} → ${bundle}`);
121
+ };
122
+ /** One outcome per section. The first failure decides the command's exit code. */
123
+ class Outcomes {
124
+ bySection = new Map();
125
+ exitCode = 0;
126
+ record(section, result, detail = '') {
127
+ this.bySection.set(section.name, { section: section.name, result, detail });
128
+ }
129
+ fail(section, detail, code = EXIT.usage) {
130
+ this.exitCode ||= code;
131
+ this.record(section, 'failed', detail);
132
+ }
133
+ inOrder(sections) {
134
+ return sections.map((section) => this.bySection.get(section.name));
135
+ }
136
+ }
137
+ const FORCE_HINT = 'pass --force to take the bundle, or `dcrypt encrypt-section --force` to keep what is here';
138
+ /**
139
+ * Settles, without a key, every section that can be settled that way. Returns what a section
140
+ * still needs when it needs its bundle decrypted, and undefined when it is done.
141
+ */
142
+ const settle = (report, force, outcomes) => {
143
+ const { section } = report;
144
+ const replace = { report, compareOnly: false };
145
+ switch (report.state) {
146
+ case 'in sync':
147
+ return void outcomes.record(section, 'unchanged', 'in sync');
148
+ case 'not decrypted':
149
+ case 'bundle changed':
150
+ return replace;
151
+ case 'plaintext changed':
152
+ return force ? replace : void outcomes.record(section, 'kept', 'it has changes that are not encrypted yet');
153
+ case 'unknown':
154
+ return force ? replace : { report, compareOnly: true };
155
+ case 'conflict':
156
+ return force
157
+ ? replace
158
+ : void outcomes.fail(section, `the plaintext and the bundle have both changed; ${FORCE_HINT}`);
159
+ case 'bundle unreadable':
160
+ return void outcomes.fail(section, adviceFor(report), EXIT.corrupt);
161
+ case 'plaintext unreadable':
162
+ return void outcomes.fail(section, adviceFor(report));
163
+ default:
164
+ return void outcomes.fail(section, adviceFor(report), EXIT.notFound);
165
+ }
166
+ };
167
+ /** Keeps the sections this machine's identity can open. Public information: no passphrase yet. */
168
+ const openableBy = (mine, pending, outcomes) => pending.filter(({ report }) => {
169
+ const isRecipient = Boolean(report.bundle?.recipients.includes(mine));
170
+ if (!isRecipient) {
171
+ outcomes.fail(report.section, `this machine's identity (${mine}) is not one of its recipients`, EXIT.permission);
172
+ }
173
+ return isRecipient;
174
+ });
175
+ /** Decrypts one section. Never throws: a failure is that section's outcome, not the command's. */
176
+ const decryptSection = async (workspace, { report: { section, snapshot }, compareOnly }, identity, outcomes) => {
177
+ try {
178
+ const extraction = await extractSection(section, identity);
179
+ const same = snapshot?.digest === extraction.digest;
180
+ if (compareOnly && !same) {
181
+ discardTemp(extraction.directory);
182
+ outcomes.fail(section, `it differs from its bundle, and this machine has no record of which is newer; ${FORCE_HINT}`);
183
+ return;
184
+ }
185
+ // Plaintext that already is what the bundle holds is left alone: there is nothing to swap.
186
+ if (same)
187
+ discardTemp(extraction.directory);
188
+ else
189
+ await installExtraction(section, extraction);
190
+ await recordSection(workspace, section.name, { digest: extraction.digest, bundle: extraction.bundle });
191
+ if (same)
192
+ outcomes.record(section, 'unchanged', 'already matches its bundle');
193
+ else
194
+ outcomes.record(section, snapshot ? 'updated' : 'decrypted', count(extraction.manifest.files.length, 'file'));
195
+ }
196
+ catch (error) {
197
+ outcomes.fail(section, messageFor(error), exitCodeFor(error));
198
+ }
199
+ };
200
+ export const decryptWorkspaceCommand = async (argv, prompter) => {
201
+ if (wantsHelp(argv, decryptWorkspaceUsage))
202
+ return;
203
+ const workspace = findWorkspace(argv);
204
+ const sections = argv._.length
205
+ ? argv._.map((name) => resolveSection(workspace, String(name)))
206
+ : discoverSections(workspace);
207
+ if (!sections.length) {
208
+ emit(argv, { workspace: workspace.root, sections: [] }, () => `no sections in ${workspace.root}`);
209
+ return;
210
+ }
211
+ const state = readState(workspace);
212
+ const outcomes = new Outcomes();
213
+ const pending = [];
214
+ for (const section of sections) {
215
+ recover(section);
216
+ const report = await inspectSection(section, state[section.name]);
217
+ const next = settle(report, Boolean(argv.force), outcomes);
218
+ if (next)
219
+ pending.push(next);
220
+ }
221
+ const openable = pending.length
222
+ ? openableBy(fingerprintOf(readStoredIdentity().recipient), pending, outcomes)
223
+ : [];
224
+ if (openable.length) {
225
+ // The one prompt. A wrong passphrase fails here, before any bundle is opened.
226
+ const identity = loadIdentity(await resolvePassphrase(argv, prompter, { message: 'Identity passphrase' }));
227
+ try {
228
+ for (const item of openable)
229
+ await decryptSection(workspace, item, identity, outcomes);
230
+ }
231
+ finally {
232
+ identity.privateKey.fill(0);
233
+ }
234
+ }
235
+ const results = outcomes.inOrder(sections);
236
+ const width = Math.max(...results.map((outcome) => outcome.section.length));
237
+ emit(argv, { workspace: workspace.root, sections: results }, () => results
238
+ .map(({ section, result, detail }) => `${section.padEnd(width)} ${result}${detail ? ` (${detail})` : ''}`)
239
+ .join('\n'));
240
+ const failures = results.filter((outcome) => outcome.result === 'failed').length;
241
+ if (failures) {
242
+ throw new CliError(`${count(failures, 'section')} could not be decrypted; ${failures === 1 ? 'its' : 'their'} plaintext was not changed`, outcomes.exitCode);
243
+ }
244
+ };
245
+ export const statusCommand = async (argv) => {
246
+ if (wantsHelp(argv, statusUsage))
247
+ return;
248
+ const workspace = findWorkspace(argv);
249
+ const state = readState(workspace);
250
+ const recipients = readRecipientFingerprints(workspace);
251
+ const reports = [];
252
+ for (const section of discoverSections(workspace)) {
253
+ reports.push(await inspectSection(section, state[section.name], recipients));
254
+ }
255
+ const sections = reports.map((report) => ({
256
+ section: report.section.name,
257
+ state: report.state,
258
+ files: report.snapshot?.files.length,
259
+ missingRecipients: report.missingRecipients,
260
+ extraRecipients: report.extraRecipients,
261
+ advice: adviceFor(report),
262
+ }));
263
+ const width = Math.max(0, ...sections.map(({ section }) => section.length));
264
+ emit(argv, { workspace: workspace.root, sections }, () => sections.length
265
+ ? sections
266
+ .map(({ section, state: current, advice }) => `${section.padEnd(width)} ${current}${advice ? ` — ${advice}` : ''}`)
267
+ .join('\n')
268
+ : `no sections in ${workspace.root}`);
269
+ };
270
+ /**
271
+ * Fingerprints from recipients.txt, or undefined when there is none to compare against. One that
272
+ * is there and cannot be used is worth a warning, and no reason to say nothing about the sections.
273
+ */
274
+ const readRecipientFingerprints = (workspace) => {
275
+ try {
276
+ return readWorkspaceRecipients(workspace).map((entry) => fingerprintOf(entry.recipient));
277
+ }
278
+ catch (error) {
279
+ if (exitCodeFor(error) !== EXIT.notFound)
280
+ warn(messageFor(error));
281
+ return undefined;
282
+ }
283
+ };
@@ -0,0 +1,120 @@
1
+ import { getPackageJson } from 'inquirerer';
2
+ import { accountCommand } from './commands/account';
3
+ import { cosmologyCommand } from './commands/cosmology';
4
+ import { doctorCommand } from './commands/doctor';
5
+ import { decryptCommand, encryptCommand } from './commands/encrypt';
6
+ import { guardCommand } from './commands/guard';
7
+ import { keychainCommand } from './commands/keychain';
8
+ import { keysCommand } from './commands/keys';
9
+ import { passkeyCommand } from './commands/passkey';
10
+ import { saltCommand } from './commands/salt';
11
+ import { secretsCommand } from './commands/secrets';
12
+ import { shamirCommand } from './commands/shamir';
13
+ import { vaultCommand } from './commands/vault';
14
+ import { walletCommand } from './commands/wallet';
15
+ import { decryptWorkspaceCommand, encryptSectionCommand, statusCommand } from './commands/workspace';
16
+ import { takeFirst } from './utils/dispatch';
17
+ import { envUsage } from './utils/env';
18
+ import { exitCodeFor, messageFor } from './utils/errors';
19
+ export const usageText = `
20
+ dcrypt — local-first encryption, wallets and team secrets
21
+
22
+ Usage:
23
+ dcrypt <command> [subcommand] [OPTIONS]
24
+
25
+ Commands:
26
+ encrypt Encrypt data with a passphrase, or to X25519 recipients
27
+ decrypt Decrypt data with a passphrase, or with your identity
28
+ encrypt-section Encrypt one folder of a workspace into a single bundle
29
+ decrypt-workspace Decrypt a workspace's bundles, with one passphrase prompt
30
+ status Show which sections are in sync, changed or not decrypted
31
+ doctor Check this machine and workspace; warn on a missing recovery key
32
+ guard Keep plaintext out of git: pre-commit check, hook and snippets
33
+ wallet Create BIP39 wallets and derive addresses (offline)
34
+ keys Manage your X25519 identity
35
+ secrets Team secrets files (.env generation, recipients, rekeying)
36
+ vault The local encrypted vault, shared with the desktop app
37
+ account Constructive accounts and API keys, stored in the vault
38
+ passkey Passkeys held in the vault; dcrypt signs for the site
39
+ keychain Store named secrets locally, always encrypted
40
+ shamir Split and recombine a secret into authenticated shares
41
+ salt Two-layer encryption: data under a salt, salt under your passphrase
42
+ cosmology Read and upgrade data written by the cosmology CLI
43
+
44
+ Global options:
45
+ --json Machine-readable output where supported
46
+ --in <file> / --out Read input from, and write output to, files ("-" is stdin)
47
+ --passphrase-file <p> Read the passphrase from a file
48
+ --passphrase-stdin Read the passphrase from stdin
49
+ --version, -v Print the version
50
+ --help, -h Show this help; "dcrypt <command> --help" for a command
51
+
52
+ Only "dcrypt account" reaches the network, and only the endpoint you name.
53
+ Passphrases and passwords are never accepted in argv.
54
+ ${envUsage}
55
+ Exit codes:
56
+ 1 usage 2 wrong passphrase 3 corrupt input 4 not found 5 not a recipient
57
+ `;
58
+ export const createCommandMap = () => ({
59
+ encrypt: encryptCommand,
60
+ decrypt: decryptCommand,
61
+ 'encrypt-section': encryptSectionCommand,
62
+ 'decrypt-workspace': decryptWorkspaceCommand,
63
+ status: statusCommand,
64
+ doctor: doctorCommand,
65
+ guard: guardCommand,
66
+ wallet: walletCommand,
67
+ keys: keysCommand,
68
+ secrets: secretsCommand,
69
+ vault: vaultCommand,
70
+ account: accountCommand,
71
+ passkey: passkeyCommand,
72
+ keychain: keychainCommand,
73
+ shamir: shamirCommand,
74
+ salt: saltCommand,
75
+ cosmology: cosmologyCommand,
76
+ });
77
+ /** Runs one command and maps thrown errors onto exit codes; used by the bin and by tests. */
78
+ export const dispatch = async (argv, prompter) => {
79
+ const commandMap = createCommandMap();
80
+ let { first: command, newArgv } = takeFirst(argv);
81
+ if (command === 'help' || (!command && (argv.help || argv.h))) {
82
+ process.stdout.write(usageText);
83
+ return 0;
84
+ }
85
+ if (!command) {
86
+ const answer = await prompter.prompt(newArgv, [
87
+ {
88
+ type: 'autocomplete',
89
+ name: 'command',
90
+ message: 'What do you want to do?',
91
+ options: Object.keys(commandMap),
92
+ },
93
+ ]);
94
+ command = answer.command;
95
+ }
96
+ const handler = commandMap[command];
97
+ if (!handler) {
98
+ process.stdout.write(usageText);
99
+ process.stderr.write(`Error: unknown command: ${command}\n`);
100
+ return 1;
101
+ }
102
+ try {
103
+ await handler(newArgv, prompter);
104
+ return 0;
105
+ }
106
+ catch (error) {
107
+ process.stderr.write(`Error: ${messageFor(error)}\n`);
108
+ return exitCodeFor(error);
109
+ }
110
+ };
111
+ export const commands = async (argv, prompter, _options) => {
112
+ if (argv.version || argv.v) {
113
+ process.stdout.write(`${getPackageJson(__dirname).version}\n`);
114
+ return;
115
+ }
116
+ const code = await dispatch(argv, prompter);
117
+ prompter.close();
118
+ if (code !== 0)
119
+ process.exit(code);
120
+ };
package/esm/index.js ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ import { CLI, getPackageJson } from 'inquirerer';
3
+ import { commands } from './commands';
4
+ export * from './commands';
5
+ export * from './utils/bytes';
6
+ export * from './utils/dispatch';
7
+ export * from './utils/errors';
8
+ export * from './utils/io';
9
+ export * from './utils/passphrase';
10
+ export * from './utils/recipients';
11
+ export * from './utils/stash';
12
+ export * from './utils/temp';
13
+ export const options = {
14
+ minimistOpts: {
15
+ alias: { v: 'version', h: 'help' },
16
+ // everything after `--` belongs to `dcrypt secrets run`
17
+ '--': true,
18
+ string: [
19
+ 'in',
20
+ 'out',
21
+ 'passphrase-file',
22
+ 'salt-file',
23
+ 'aad',
24
+ 'vault',
25
+ 'file',
26
+ 'format',
27
+ 'kdf',
28
+ 'recipient',
29
+ 'recipients-file',
30
+ 'workspace',
31
+ ],
32
+ // declared so that a flag never takes the positional after it as its value:
33
+ // `dcrypt encrypt --binary "some text"`, `dcrypt decrypt-workspace --force finance`
34
+ boolean: ['binary', 'force', 'json', 'staged', 'all'],
35
+ },
36
+ };
37
+ if (require.main === module) {
38
+ const app = new CLI(commands, {
39
+ ...options,
40
+ // The prompter attaches a line reader to stdin as soon as it is constructed. When stdin is a
41
+ // pipe or a file it is data (or nothing), never a keyboard: a reader there would take bytes
42
+ // away from `--in -`, and a prompt would read the data as its answer.
43
+ noTty: !process.stdin.isTTY,
44
+ version: `dcrypt@${getPackageJson(__dirname).version}`,
45
+ });
46
+ app.run().catch((error) => {
47
+ process.stderr.write(`Unexpected error: ${String(error)}\n`);
48
+ process.exit(1);
49
+ });
50
+ }