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
package/utils/bytes.js ADDED
@@ -0,0 +1,301 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.writeText = exports.writePlaintext = exports.writeBytes = exports.assertNotTerminal = exports.writeFileAtomically = exports.syncDirectory = exports.syncFile = exports.ByteReader = exports.assertStdinFree = exports.openInput = exports.IO_CHUNK_SIZE = void 0;
4
+ exports.transformBytes = transformBytes;
5
+ exports.chainBytes = chainBytes;
6
+ const fs_1 = require("fs");
7
+ const promises_1 = require("fs/promises");
8
+ const path_1 = require("path");
9
+ const stream_1 = require("stream");
10
+ const promises_2 = require("stream/promises");
11
+ const errors_1 = require("./errors");
12
+ const temp_1 = require("./temp");
13
+ /**
14
+ * Byte-level input and output for commands that must not hold a whole file in memory.
15
+ *
16
+ * Everything here is a stream of byte pieces with backpressure: input is a Node `Readable`,
17
+ * transforms are async generators, and output goes through `stream.pipeline`. File output is
18
+ * written to a temporary sibling and renamed over the destination only once every byte has been
19
+ * written and synced. That is what keeps a wrong passphrase, a truncated download or an
20
+ * interrupt from replacing a good file with a partial one.
21
+ */
22
+ exports.IO_CHUNK_SIZE = 64 * 1024;
23
+ const memoryInput = (bytes, stdin = false) => ({
24
+ stdin,
25
+ stream: stream_1.Readable.from([bytes]),
26
+ close() { },
27
+ });
28
+ const fileInput = async (path) => {
29
+ const unreadable = () => new errors_1.CliError(`cannot read ${path}`, errors_1.EXIT.notFound);
30
+ const handle = await (0, promises_1.open)(path, 'r').catch(() => {
31
+ throw unreadable();
32
+ });
33
+ if ((await handle.stat()).isDirectory()) {
34
+ await handle.close();
35
+ throw unreadable();
36
+ }
37
+ // The stream owns the handle from here on: it is closed when the stream ends or is destroyed.
38
+ const stream = handle.createReadStream({ highWaterMark: exports.IO_CHUNK_SIZE });
39
+ return { stdin: false, stream, close: () => void stream.destroy() };
40
+ };
41
+ /**
42
+ * stdin as a byte stream.
43
+ *
44
+ * Nothing else may read stdin while it carries the input, which is why the entry point keeps the
45
+ * prompter off a stdin that is not a terminal. A terminal is shared with the prompter, so what
46
+ * is typed there is read in one blocking pass, before control returns to the event loop.
47
+ */
48
+ const stdinInput = () => {
49
+ if (!process.stdin.isTTY) {
50
+ return { stdin: true, stream: process.stdin, close: () => void process.stdin.pause() };
51
+ }
52
+ try {
53
+ return memoryInput((0, fs_1.readFileSync)(0), true);
54
+ }
55
+ catch {
56
+ throw new errors_1.CliError('failed to read stdin');
57
+ }
58
+ };
59
+ /**
60
+ * Opens the command's input as bytes: `--in <file>`, `-` (stdin), the inline value, then piped
61
+ * stdin — the same order as `readInput`.
62
+ */
63
+ const openInput = async (argv, inline) => {
64
+ if (typeof argv.in === 'string' && argv.in.length) {
65
+ return argv.in === '-' ? stdinInput() : fileInput(argv.in);
66
+ }
67
+ if (inline === '-' || argv.stdin)
68
+ return stdinInput();
69
+ if (inline !== undefined && inline !== '')
70
+ return memoryInput(Buffer.from(String(inline), 'utf8'));
71
+ if (!process.stdin.isTTY)
72
+ return stdinInput();
73
+ throw new errors_1.CliError('no input: pass a value, --in <file>, or pipe on stdin');
74
+ };
75
+ exports.openInput = openInput;
76
+ /** stdin can carry the data or the passphrase, never both. */
77
+ const assertStdinFree = (argv, input) => {
78
+ if (input.stdin && (argv['passphrase-stdin'] || argv.passphraseStdin)) {
79
+ throw new errors_1.CliError('stdin cannot carry both the input and the passphrase; use --in <file> or --passphrase-file <path>');
80
+ }
81
+ };
82
+ exports.assertStdinFree = assertStdinFree;
83
+ const NO_BYTES = Buffer.alloc(0);
84
+ const asBuffer = (bytes) => Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length);
85
+ /**
86
+ * Reads the front of a byte stream, then hands on whatever was not consumed.
87
+ *
88
+ * A command has to look at the first bytes of its input to know what it was given, and a header
89
+ * has no fixed length. This buffers only as much as it is asked for; {@link ByteReader.rest}
90
+ * streams the remainder untouched.
91
+ */
92
+ class ByteReader {
93
+ pieces;
94
+ held = NO_BYTES;
95
+ constructor(source) {
96
+ this.pieces =
97
+ Symbol.asyncIterator in source ? source[Symbol.asyncIterator]() : source[Symbol.iterator]();
98
+ }
99
+ /** What has been read from the stream and not yet consumed. */
100
+ get buffered() {
101
+ return this.held;
102
+ }
103
+ /** Buffers one more piece. Resolves to false once the stream has ended. */
104
+ async more() {
105
+ const next = await this.pieces.next();
106
+ if (next.done)
107
+ return false;
108
+ this.held = this.held.length ? Buffer.concat([this.held, next.value]) : asBuffer(next.value);
109
+ return true;
110
+ }
111
+ /** Buffers until at least `length` bytes are held, or the stream ends, and returns them. */
112
+ async fill(length) {
113
+ while (this.held.length < length && (await this.more()))
114
+ ;
115
+ return this.held;
116
+ }
117
+ /** Drops `length` bytes from the front of the buffer. */
118
+ skip(length) {
119
+ this.held = this.held.subarray(length);
120
+ }
121
+ /** Reads everything that is left into memory. For inputs that are small by construction. */
122
+ async all() {
123
+ while (await this.more())
124
+ ;
125
+ const everything = this.held;
126
+ this.held = NO_BYTES;
127
+ return everything;
128
+ }
129
+ /** Everything that is left, as a stream: the buffered bytes, then the rest of the source. */
130
+ async *rest() {
131
+ if (this.held.length) {
132
+ const head = this.held;
133
+ this.held = NO_BYTES;
134
+ yield head;
135
+ }
136
+ for (let next = await this.pieces.next(); !next.done; next = await this.pieces.next()) {
137
+ yield next.value;
138
+ }
139
+ }
140
+ }
141
+ exports.ByteReader = ByteReader;
142
+ /** Runs `source` through `transform`, one piece at a time. */
143
+ async function* transformBytes(source, transform) {
144
+ for await (const piece of source) {
145
+ const output = transform.update(piece);
146
+ if (output.length)
147
+ yield output;
148
+ }
149
+ yield transform.finish();
150
+ }
151
+ /** Node streams speak Buffer: a bare Uint8Array reads as a list of numbers to anything that inspects a chunk. */
152
+ async function* asBuffers(source) {
153
+ for await (const piece of source)
154
+ yield asBuffer(piece);
155
+ }
156
+ /** Joins byte streams end to end. */
157
+ async function* chainBytes(...sources) {
158
+ for (const source of sources)
159
+ yield* source;
160
+ }
161
+ const statOrUndefined = (path) => {
162
+ try {
163
+ return (0, fs_1.statSync)(path);
164
+ }
165
+ catch {
166
+ return undefined;
167
+ }
168
+ };
169
+ const sync = async (path, flags) => {
170
+ const handle = await (0, promises_1.open)(path, flags);
171
+ try {
172
+ await handle.sync();
173
+ }
174
+ finally {
175
+ await handle.close();
176
+ }
177
+ };
178
+ /** Forces a file that has already been written to disk. */
179
+ const syncFile = (path) => sync(path, 'r+');
180
+ exports.syncFile = syncFile;
181
+ /** Best effort: makes a rename durable. Not every platform can fsync a directory. */
182
+ const syncDirectory = async (path) => {
183
+ try {
184
+ await sync(path, 'r');
185
+ }
186
+ catch {
187
+ // ignored on purpose
188
+ }
189
+ };
190
+ exports.syncDirectory = syncDirectory;
191
+ /**
192
+ * Writes `path` atomically. The bytes go to a temporary file in the same directory, created
193
+ * owner-only; once all of them are written and synced it is renamed over `path`. If `bytes`
194
+ * fails part-way, or the process is interrupted, `path` is left exactly as it was.
195
+ */
196
+ const writeFileAtomically = async (path, bytes) => {
197
+ const existing = statOrUndefined(path);
198
+ if (existing?.isDirectory())
199
+ throw new errors_1.CliError(`cannot write ${path}: it is a directory`);
200
+ if (existing && !existing.isFile()) {
201
+ // A pipe, device or other special file: there is nothing to rename over, so write straight in.
202
+ await (0, promises_2.pipeline)(bytes, (0, fs_1.createWriteStream)(path));
203
+ return;
204
+ }
205
+ // Write through a symlink, as a plain overwrite would, instead of replacing the link.
206
+ const target = existing ? (0, fs_1.realpathSync)(path) : (0, path_1.resolve)(path);
207
+ const temp = (0, temp_1.tempPathFor)(target);
208
+ const handle = await (0, promises_1.open)(temp, 'wx', 0o600).catch(() => {
209
+ throw new errors_1.CliError(`cannot write ${path}`);
210
+ });
211
+ (0, temp_1.trackTemp)(temp);
212
+ try {
213
+ // The stream owns the handle: `flush` syncs the file to disk before the handle is closed, and
214
+ // pipeline() only resolves after that, so the rename never exposes bytes that are not there.
215
+ await (0, promises_2.pipeline)(bytes, handle.createWriteStream({ flush: true }));
216
+ await (0, promises_1.rename)(temp, target);
217
+ }
218
+ catch (error) {
219
+ (0, temp_1.discardTemp)(temp);
220
+ throw error;
221
+ }
222
+ (0, temp_1.untrackTemp)(temp);
223
+ await (0, exports.syncDirectory)((0, path_1.dirname)(target));
224
+ };
225
+ exports.writeFileAtomically = writeFileAtomically;
226
+ const outputFile = (argv) => typeof argv.out === 'string' && argv.out.length && argv.out !== '-' ? argv.out : undefined;
227
+ /** Fails, before any prompt, when binary output would land on a terminal. */
228
+ const assertNotTerminal = (argv, options) => {
229
+ if (options.binary && outputFile(argv) === undefined && process.stdout.isTTY) {
230
+ throw new errors_1.CliError('refusing to write binary ciphertext to a terminal; use --out <file> or redirect stdout');
231
+ }
232
+ };
233
+ exports.assertNotTerminal = assertNotTerminal;
234
+ /** How many bytes at the end of `bytes` begin a UTF-8 character without finishing it. */
235
+ const unfinished = (bytes) => {
236
+ for (let back = 1; back <= Math.min(3, bytes.length); back++) {
237
+ const byte = bytes[bytes.length - back];
238
+ if ((byte & 0xc0) === 0x80)
239
+ continue; // a continuation byte: its lead byte is further back
240
+ const length = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;
241
+ return length > back ? back : 0;
242
+ }
243
+ return 0;
244
+ };
245
+ const isText = (bytes) => {
246
+ if (bytes.includes(0))
247
+ return false;
248
+ try {
249
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
250
+ return true;
251
+ }
252
+ catch {
253
+ return false;
254
+ }
255
+ };
256
+ /**
257
+ * Passes text through, and stops at what a terminal should not be sent: a NUL byte, or bytes that
258
+ * are not UTF-8. Only whole characters are passed on: the start of one that is split between two
259
+ * pieces waits for the rest of it, and is never written if the rest does not come.
260
+ */
261
+ async function* textOnly(bytes) {
262
+ const refusal = () => new errors_1.CliError('refusing to write binary data to a terminal; use --out <file> or redirect stdout');
263
+ let pending = new Uint8Array(0);
264
+ for await (const piece of bytes) {
265
+ const joined = pending.length ? Buffer.concat([pending, piece]) : piece;
266
+ const end = joined.length - unfinished(joined);
267
+ const whole = joined.subarray(0, end);
268
+ if (!isText(whole))
269
+ throw refusal();
270
+ pending = joined.slice(end);
271
+ if (whole.length)
272
+ yield whole;
273
+ }
274
+ if (pending.length)
275
+ throw refusal();
276
+ }
277
+ /** Writes `bytes` to `--out <file>` when given (atomically), otherwise to stdout. */
278
+ const writeBytes = async (argv, bytes, options = {}) => {
279
+ const path = outputFile(argv);
280
+ if (path !== undefined) {
281
+ await (0, exports.writeFileAtomically)(path, bytes);
282
+ return;
283
+ }
284
+ (0, exports.assertNotTerminal)(argv, options);
285
+ // stdout belongs to the process: it is written to, never ended.
286
+ await (0, promises_2.pipeline)(asBuffers(process.stdout.isTTY ? textOnly(bytes) : bytes), process.stdout, { end: false });
287
+ };
288
+ exports.writeBytes = writeBytes;
289
+ const NEWLINE = Buffer.from('\n');
290
+ /**
291
+ * Writes decrypted bytes exactly as they were encrypted. Only on a terminal is text that does not
292
+ * end its last line given a newline, so that the prompt does not follow it on the same line.
293
+ */
294
+ const writePlaintext = (argv, plaintext) => {
295
+ const shown = outputFile(argv) === undefined && process.stdout.isTTY;
296
+ return (0, exports.writeBytes)(argv, shown && plaintext.at(-1) !== NEWLINE[0] ? [plaintext, NEWLINE] : [plaintext]);
297
+ };
298
+ exports.writePlaintext = writePlaintext;
299
+ /** Writes text the way {@link writeBytes} writes bytes, ending it with a newline. */
300
+ const writeText = (argv, text) => (0, exports.writeBytes)(argv, [Buffer.from(text.endsWith('\n') ? text : `${text}\n`, 'utf8')]);
301
+ exports.writeText = writeText;
@@ -0,0 +1,24 @@
1
+ import { Inquirerer } from 'inquirerer';
2
+ import { ParsedArgs } from 'minimist';
3
+ export type Handler = (argv: ParsedArgs, prompter: Inquirerer) => Promise<void> | void;
4
+ /**
5
+ * `extractFirst` with the argv type preserved — upstream narrows the rest of argv to
6
+ * `{ _: string[] }`, which loses every flag.
7
+ */
8
+ export declare const takeFirst: (argv: ParsedArgs) => {
9
+ first?: string;
10
+ newArgv: ParsedArgs;
11
+ };
12
+ export interface SubcommandOptions {
13
+ /** Name of the parent command, used in error messages. */
14
+ name: string;
15
+ usage: string;
16
+ handlers: Record<string, Handler>;
17
+ }
18
+ /**
19
+ * Dispatches `dcrypt <group> <subcommand>`: extracts the positional subcommand, prints per-command
20
+ * help on `--help`, and prompts for the subcommand when running interactively without one.
21
+ */
22
+ export declare const runSubcommand: (argv: ParsedArgs, prompter: Inquirerer, { name, usage, handlers }: SubcommandOptions) => Promise<void>;
23
+ /** Prints `usage` and returns true when the user asked for help. */
24
+ export declare const wantsHelp: (argv: ParsedArgs, usage: string) => boolean;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wantsHelp = exports.runSubcommand = exports.takeFirst = void 0;
4
+ const inquirerer_1 = require("inquirerer");
5
+ const errors_1 = require("./errors");
6
+ /**
7
+ * `extractFirst` with the argv type preserved — upstream narrows the rest of argv to
8
+ * `{ _: string[] }`, which loses every flag.
9
+ */
10
+ const takeFirst = (argv) => (0, inquirerer_1.extractFirst)(argv);
11
+ exports.takeFirst = takeFirst;
12
+ /**
13
+ * Dispatches `dcrypt <group> <subcommand>`: extracts the positional subcommand, prints per-command
14
+ * help on `--help`, and prompts for the subcommand when running interactively without one.
15
+ */
16
+ const runSubcommand = async (argv, prompter, { name, usage, handlers }) => {
17
+ const { first, newArgv } = (0, exports.takeFirst)(argv);
18
+ let subcommand = first;
19
+ if (!subcommand && (argv.help || argv.h)) {
20
+ process.stdout.write(usage);
21
+ return;
22
+ }
23
+ if (subcommand === 'help') {
24
+ process.stdout.write(usage);
25
+ return;
26
+ }
27
+ if (!subcommand) {
28
+ const answer = await prompter.prompt(newArgv, [
29
+ {
30
+ type: 'autocomplete',
31
+ name: 'subcommand',
32
+ message: `${name} — what do you want to do?`,
33
+ options: Object.keys(handlers),
34
+ },
35
+ ]);
36
+ subcommand = answer.subcommand;
37
+ }
38
+ const handler = handlers[subcommand];
39
+ if (!handler) {
40
+ process.stdout.write(usage);
41
+ throw new errors_1.CliError(`unknown ${name} subcommand: ${subcommand}`);
42
+ }
43
+ if (newArgv.help || newArgv.h) {
44
+ process.stdout.write(usage);
45
+ return;
46
+ }
47
+ await handler(newArgv, prompter);
48
+ };
49
+ exports.runSubcommand = runSubcommand;
50
+ /** Prints `usage` and returns true when the user asked for help. */
51
+ const wantsHelp = (argv, usage) => {
52
+ if (argv.help || argv.h) {
53
+ process.stdout.write(usage);
54
+ return true;
55
+ }
56
+ return false;
57
+ };
58
+ exports.wantsHelp = wantsHelp;
package/utils/env.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Environment variable input, kept compatible with the cosmology CLI.
3
+ *
4
+ * Every name that CLI read still works — `MNEMONIC`, `SALT`, `ENCRYPTED_SALT`,
5
+ * `KEYCHAIN_ACCOUNT` — alongside `DCRYPT_`-prefixed aliases for use in
6
+ * environments where the bare names would collide.
7
+ *
8
+ * Resolution order everywhere is: explicit flag, then environment, then stdin,
9
+ * then an interactive prompt. Flags always win so a script can override an
10
+ * inherited variable, and argv still never carries a secret.
11
+ */
12
+ export declare const ENV_VARS: {
13
+ readonly mnemonic: readonly ["MNEMONIC", "DCRYPT_MNEMONIC"];
14
+ readonly salt: readonly ["SALT", "DCRYPT_SALT"];
15
+ readonly encryptedSalt: readonly ["ENCRYPTED_SALT", "DCRYPT_ENCRYPTED_SALT"];
16
+ readonly keychainAccount: readonly ["KEYCHAIN_ACCOUNT", "DCRYPT_KEYCHAIN_ACCOUNT"];
17
+ readonly passphrase: readonly ["DCRYPT_PASSPHRASE"];
18
+ readonly accountPassword: readonly ["DCRYPT_ACCOUNT_PASSWORD"];
19
+ readonly authEndpoint: readonly ["DCRYPT_AUTH_ENDPOINT"];
20
+ };
21
+ export type EnvInput = keyof typeof ENV_VARS;
22
+ /** First non-empty value among the names for `input`, or undefined. */
23
+ export declare const fromEnv: (input: EnvInput, env?: NodeJS.ProcessEnv) => string | undefined;
24
+ /** The keychain namespace, matching the cosmology CLI's `KEYCHAIN_ACCOUNT`. */
25
+ export declare const keychainAccount: (env?: NodeJS.ProcessEnv) => string;
26
+ export declare const envUsage = "\nEnvironment:\n MNEMONIC A BIP39 mnemonic, for wallet commands\n SALT The salt, for salt and cosmology commands\n ENCRYPTED_SALT The encrypted salt, for the two-layer scheme\n KEYCHAIN_ACCOUNT Keychain namespace (default: dcrypt)\n DCRYPT_PASSPHRASE The passphrase, for unattended runs\n DCRYPT_AUTH_ENDPOINT Constructive auth endpoint, for account commands\n DCRYPT_ACCOUNT_PASSWORD The account password, for unattended sign-in\n\n Each also accepts a DCRYPT_-prefixed alias (DCRYPT_MNEMONIC, DCRYPT_SALT, ...).\n Flags take precedence over the environment, which takes precedence over stdin.\n";
package/utils/env.js ADDED
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.envUsage = exports.keychainAccount = exports.fromEnv = exports.ENV_VARS = void 0;
4
+ /**
5
+ * Environment variable input, kept compatible with the cosmology CLI.
6
+ *
7
+ * Every name that CLI read still works — `MNEMONIC`, `SALT`, `ENCRYPTED_SALT`,
8
+ * `KEYCHAIN_ACCOUNT` — alongside `DCRYPT_`-prefixed aliases for use in
9
+ * environments where the bare names would collide.
10
+ *
11
+ * Resolution order everywhere is: explicit flag, then environment, then stdin,
12
+ * then an interactive prompt. Flags always win so a script can override an
13
+ * inherited variable, and argv still never carries a secret.
14
+ */
15
+ exports.ENV_VARS = {
16
+ mnemonic: ['MNEMONIC', 'DCRYPT_MNEMONIC'],
17
+ salt: ['SALT', 'DCRYPT_SALT'],
18
+ encryptedSalt: ['ENCRYPTED_SALT', 'DCRYPT_ENCRYPTED_SALT'],
19
+ keychainAccount: ['KEYCHAIN_ACCOUNT', 'DCRYPT_KEYCHAIN_ACCOUNT'],
20
+ passphrase: ['DCRYPT_PASSPHRASE'],
21
+ accountPassword: ['DCRYPT_ACCOUNT_PASSWORD'],
22
+ authEndpoint: ['DCRYPT_AUTH_ENDPOINT'],
23
+ };
24
+ /** First non-empty value among the names for `input`, or undefined. */
25
+ const fromEnv = (input, env = process.env) => {
26
+ for (const name of exports.ENV_VARS[input]) {
27
+ const value = env[name];
28
+ if (typeof value === 'string' && value.length)
29
+ return value;
30
+ }
31
+ return undefined;
32
+ };
33
+ exports.fromEnv = fromEnv;
34
+ /** The keychain namespace, matching the cosmology CLI's `KEYCHAIN_ACCOUNT`. */
35
+ const keychainAccount = (env = process.env) => (0, exports.fromEnv)('keychainAccount', env) ?? 'dcrypt';
36
+ exports.keychainAccount = keychainAccount;
37
+ exports.envUsage = `
38
+ Environment:
39
+ MNEMONIC A BIP39 mnemonic, for wallet commands
40
+ SALT The salt, for salt and cosmology commands
41
+ ENCRYPTED_SALT The encrypted salt, for the two-layer scheme
42
+ KEYCHAIN_ACCOUNT Keychain namespace (default: dcrypt)
43
+ DCRYPT_PASSPHRASE The passphrase, for unattended runs
44
+ DCRYPT_AUTH_ENDPOINT Constructive auth endpoint, for account commands
45
+ DCRYPT_ACCOUNT_PASSWORD The account password, for unattended sign-in
46
+
47
+ Each also accepts a DCRYPT_-prefixed alias (DCRYPT_MNEMONIC, DCRYPT_SALT, ...).
48
+ Flags take precedence over the environment, which takes precedence over stdin.
49
+ `;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Exit codes, so scripts can tell failure modes apart without parsing messages.
3
+ *
4
+ * | Code | Meaning |
5
+ * |------|---------|
6
+ * | 1 | Usage error — bad arguments, unknown command |
7
+ * | 2 | Wrong passphrase, or authentication failed |
8
+ * | 3 | Corrupt or unsupported input |
9
+ * | 4 | Not found — no such secret, vault, or keychain entry |
10
+ * | 5 | Permission — this identity is not a recipient |
11
+ */
12
+ export declare const EXIT: {
13
+ readonly usage: 1;
14
+ readonly auth: 2;
15
+ readonly corrupt: 3;
16
+ readonly notFound: 4;
17
+ readonly permission: 5;
18
+ };
19
+ export declare class CliError extends Error {
20
+ readonly code: number;
21
+ constructor(message: string, code?: number);
22
+ }
23
+ /** Maps library errors onto exit codes; unknown errors keep exit code 1. */
24
+ export declare const exitCodeFor: (error: unknown) => number;
25
+ export declare const messageFor: (error: unknown) => string;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.messageFor = exports.exitCodeFor = exports.CliError = exports.EXIT = void 0;
4
+ const core_1 = require("@decryption/core");
5
+ const keys_1 = require("@decryption/keys");
6
+ /**
7
+ * Exit codes, so scripts can tell failure modes apart without parsing messages.
8
+ *
9
+ * | Code | Meaning |
10
+ * |------|---------|
11
+ * | 1 | Usage error — bad arguments, unknown command |
12
+ * | 2 | Wrong passphrase, or authentication failed |
13
+ * | 3 | Corrupt or unsupported input |
14
+ * | 4 | Not found — no such secret, vault, or keychain entry |
15
+ * | 5 | Permission — this identity is not a recipient |
16
+ */
17
+ exports.EXIT = {
18
+ usage: 1,
19
+ auth: 2,
20
+ corrupt: 3,
21
+ notFound: 4,
22
+ permission: 5,
23
+ };
24
+ class CliError extends Error {
25
+ code;
26
+ constructor(message, code = exports.EXIT.usage) {
27
+ super(message);
28
+ this.name = 'CliError';
29
+ this.code = code;
30
+ }
31
+ }
32
+ exports.CliError = CliError;
33
+ /** Maps library errors onto exit codes; unknown errors keep exit code 1. */
34
+ const exitCodeFor = (error) => {
35
+ if (error instanceof CliError)
36
+ return error.code;
37
+ if (error instanceof core_1.WrongPassphraseError)
38
+ return exports.EXIT.auth;
39
+ if (error instanceof core_1.CorruptEnvelopeError || error instanceof core_1.UnsupportedEnvelopeError) {
40
+ return exports.EXIT.corrupt;
41
+ }
42
+ if (error instanceof keys_1.NotRecipientError)
43
+ return exports.EXIT.permission;
44
+ if (error instanceof core_1.InvalidParametersError)
45
+ return exports.EXIT.usage;
46
+ return exports.EXIT.usage;
47
+ };
48
+ exports.exitCodeFor = exitCodeFor;
49
+ const messageFor = (error) => error instanceof Error ? error.message : String(error);
50
+ exports.messageFor = messageFor;
@@ -0,0 +1,4 @@
1
+ import { FileHeader } from '@decryption/core';
2
+ import { ByteReader } from './bytes';
3
+ /** Reads exactly the header off the front of `reader`; the payload stays in the stream. */
4
+ export declare const readFileHeader: (reader: ByteReader) => Promise<FileHeader>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readFileHeader = void 0;
4
+ const core_1 = require("@decryption/core");
5
+ /** Reads exactly the header off the front of `reader`; the payload stays in the stream. */
6
+ const readFileHeader = async (reader) => {
7
+ for (;;) {
8
+ const header = (0, core_1.tryParseFileHeader)(reader.buffered);
9
+ if (header) {
10
+ reader.skip(header.length);
11
+ return header;
12
+ }
13
+ if (!(await reader.more())) {
14
+ throw new core_1.CorruptEnvelopeError('envelope is truncated: the header is incomplete');
15
+ }
16
+ }
17
+ };
18
+ exports.readFileHeader = readFileHeader;
package/utils/io.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { ParsedArgs } from 'minimist';
2
+ /** Reads `--in <file>`, `-` (stdin), or the given inline value, in that order. */
3
+ export declare const readInput: (argv: ParsedArgs, inline?: string) => string;
4
+ /** Writes to `--out <file>` when given, otherwise stdout. */
5
+ export declare const writeOutput: (argv: ParsedArgs, content: string) => void;
6
+ /** Emits `--json` output, or the human-readable rendering. */
7
+ export declare const emit: (argv: ParsedArgs, data: unknown, human: () => string) => void;
8
+ /** True when the command should avoid printing secrets to a terminal. */
9
+ export declare const isTty: () => boolean;
10
+ export declare const readStdin: () => string;
package/utils/io.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readStdin = exports.isTty = exports.emit = exports.writeOutput = exports.readInput = void 0;
4
+ const fs_1 = require("fs");
5
+ const errors_1 = require("./errors");
6
+ /** Reads `--in <file>`, `-` (stdin), or the given inline value, in that order. */
7
+ const readInput = (argv, inline) => {
8
+ if (typeof argv.in === 'string' && argv.in.length) {
9
+ if (argv.in === '-')
10
+ return (0, exports.readStdin)();
11
+ try {
12
+ return (0, fs_1.readFileSync)(argv.in, 'utf8');
13
+ }
14
+ catch {
15
+ throw new errors_1.CliError(`cannot read ${argv.in}`, errors_1.EXIT.notFound);
16
+ }
17
+ }
18
+ if (inline === '-' || argv.stdin)
19
+ return (0, exports.readStdin)();
20
+ if (inline !== undefined && inline !== '')
21
+ return inline;
22
+ if (!process.stdin.isTTY)
23
+ return (0, exports.readStdin)();
24
+ throw new errors_1.CliError('no input: pass a value, --in <file>, or pipe on stdin');
25
+ };
26
+ exports.readInput = readInput;
27
+ /** Writes to `--out <file>` when given, otherwise stdout. */
28
+ const writeOutput = (argv, content) => {
29
+ const text = content.endsWith('\n') ? content : `${content}\n`;
30
+ if (typeof argv.out === 'string' && argv.out.length) {
31
+ (0, fs_1.writeFileSync)(argv.out, text, { mode: 0o600 });
32
+ return;
33
+ }
34
+ process.stdout.write(text);
35
+ };
36
+ exports.writeOutput = writeOutput;
37
+ /** Emits `--json` output, or the human-readable rendering. */
38
+ const emit = (argv, data, human) => {
39
+ if (argv.json) {
40
+ (0, exports.writeOutput)(argv, JSON.stringify(data, null, 2));
41
+ return;
42
+ }
43
+ (0, exports.writeOutput)(argv, human());
44
+ };
45
+ exports.emit = emit;
46
+ /** True when the command should avoid printing secrets to a terminal. */
47
+ const isTty = () => Boolean(process.stdout.isTTY);
48
+ exports.isTty = isTty;
49
+ const readStdin = () => {
50
+ try {
51
+ return (0, fs_1.readFileSync)(0, 'utf8');
52
+ }
53
+ catch {
54
+ throw new errors_1.CliError('failed to read stdin');
55
+ }
56
+ };
57
+ exports.readStdin = readStdin;
@@ -0,0 +1,15 @@
1
+ import { Inquirerer } from 'inquirerer';
2
+ import { ParsedArgs } from 'minimist';
3
+ export interface PassphraseOptions {
4
+ /** Ask twice and compare — used when creating something new. */
5
+ confirm?: boolean;
6
+ message?: string;
7
+ }
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
+ export declare const resolvePassphrase: (argv: ParsedArgs, prompter: Inquirerer, options?: PassphraseOptions) => Promise<string>;