decryption 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -325
  3. package/index.js +3 -66
  4. package/package.json +8 -24
  5. package/commands/account.d.ts +0 -4
  6. package/commands/account.js +0 -470
  7. package/commands/cosmology.d.ts +0 -4
  8. package/commands/cosmology.js +0 -97
  9. package/commands/doctor.d.ts +0 -3
  10. package/commands/doctor.js +0 -42
  11. package/commands/encrypt.d.ts +0 -12
  12. package/commands/encrypt.js +0 -251
  13. package/commands/guard.d.ts +0 -3
  14. package/commands/guard.js +0 -92
  15. package/commands/keychain.d.ts +0 -4
  16. package/commands/keychain.js +0 -92
  17. package/commands/keys.d.ts +0 -4
  18. package/commands/keys.js +0 -74
  19. package/commands/passkey.d.ts +0 -4
  20. package/commands/passkey.js +0 -135
  21. package/commands/salt.d.ts +0 -4
  22. package/commands/salt.js +0 -113
  23. package/commands/secrets.d.ts +0 -4
  24. package/commands/secrets.js +0 -214
  25. package/commands/shamir.d.ts +0 -4
  26. package/commands/shamir.js +0 -62
  27. package/commands/vault.d.ts +0 -7
  28. package/commands/vault.js +0 -382
  29. package/commands/wallet.d.ts +0 -5
  30. package/commands/wallet.js +0 -129
  31. package/commands/workspace.d.ts +0 -8
  32. package/commands/workspace.js +0 -289
  33. package/commands.d.ts +0 -8
  34. package/commands.js +0 -126
  35. package/esm/commands/account.js +0 -466
  36. package/esm/commands/cosmology.js +0 -93
  37. package/esm/commands/doctor.js +0 -38
  38. package/esm/commands/encrypt.js +0 -245
  39. package/esm/commands/guard.js +0 -88
  40. package/esm/commands/keychain.js +0 -88
  41. package/esm/commands/keys.js +0 -70
  42. package/esm/commands/passkey.js +0 -131
  43. package/esm/commands/salt.js +0 -109
  44. package/esm/commands/secrets.js +0 -210
  45. package/esm/commands/shamir.js +0 -58
  46. package/esm/commands/vault.js +0 -376
  47. package/esm/commands/wallet.js +0 -125
  48. package/esm/commands/workspace.js +0 -283
  49. package/esm/commands.js +0 -120
  50. package/esm/index.js +0 -50
  51. package/esm/utils/bytes.js +0 -286
  52. package/esm/utils/dispatch.js +0 -52
  53. package/esm/utils/env.js +0 -44
  54. package/esm/utils/errors.js +0 -44
  55. package/esm/utils/header.js +0 -14
  56. package/esm/utils/io.js +0 -49
  57. package/esm/utils/passphrase.js +0 -49
  58. package/esm/utils/recipients.js +0 -74
  59. package/esm/utils/stash.js +0 -61
  60. package/esm/utils/temp.js +0 -51
  61. package/esm/utils/text.js +0 -2
  62. package/esm/workspace/bundle.js +0 -239
  63. package/esm/workspace/doctor.js +0 -104
  64. package/esm/workspace/git.js +0 -72
  65. package/esm/workspace/guard.js +0 -111
  66. package/esm/workspace/layout.js +0 -106
  67. package/esm/workspace/manifest.js +0 -147
  68. package/esm/workspace/recipients.js +0 -37
  69. package/esm/workspace/snippets.js +0 -54
  70. package/esm/workspace/state.js +0 -46
  71. package/esm/workspace/status.js +0 -93
  72. package/esm/workspace/tar.js +0 -235
  73. package/index.d.ts +0 -12
  74. package/utils/bytes.d.ts +0 -86
  75. package/utils/bytes.js +0 -301
  76. package/utils/dispatch.d.ts +0 -24
  77. package/utils/dispatch.js +0 -58
  78. package/utils/env.d.ts +0 -26
  79. package/utils/env.js +0 -49
  80. package/utils/errors.d.ts +0 -25
  81. package/utils/errors.js +0 -50
  82. package/utils/header.d.ts +0 -4
  83. package/utils/header.js +0 -18
  84. package/utils/io.d.ts +0 -10
  85. package/utils/io.js +0 -57
  86. package/utils/passphrase.d.ts +0 -15
  87. package/utils/passphrase.js +0 -53
  88. package/utils/recipients.d.ts +0 -28
  89. package/utils/recipients.js +0 -80
  90. package/utils/stash.d.ts +0 -40
  91. package/utils/stash.js +0 -76
  92. package/utils/temp.d.ts +0 -10
  93. package/utils/temp.js +0 -59
  94. package/utils/text.d.ts +0 -2
  95. package/utils/text.js +0 -6
  96. package/workspace/bundle.d.ts +0 -50
  97. package/workspace/bundle.js +0 -248
  98. package/workspace/doctor.d.ts +0 -8
  99. package/workspace/doctor.js +0 -108
  100. package/workspace/git.d.ts +0 -21
  101. package/workspace/git.js +0 -83
  102. package/workspace/guard.d.ts +0 -23
  103. package/workspace/guard.js +0 -118
  104. package/workspace/layout.d.ts +0 -47
  105. package/workspace/layout.js +0 -113
  106. package/workspace/manifest.d.ts +0 -52
  107. package/workspace/manifest.js +0 -157
  108. package/workspace/recipients.d.ts +0 -16
  109. package/workspace/recipients.js +0 -45
  110. package/workspace/snippets.d.ts +0 -29
  111. package/workspace/snippets.js +0 -58
  112. package/workspace/state.d.ts +0 -13
  113. package/workspace/state.js +0 -52
  114. package/workspace/status.d.ts +0 -54
  115. package/workspace/status.js +0 -99
  116. package/workspace/tar.d.ts +0 -29
  117. package/workspace/tar.js +0 -240
@@ -1,245 +0,0 @@
1
- import { armor, armorFile, createFileDecryptor, createFileEncryptor, dearmor, dearmorFile, decrypt, encrypt, FILE_ARMOR_PREFIX, FILE_VERSION, generateFileKey, isPassphraseFile, KDF_PROFILES, MAGIC, unwrapWithPassphrase, wrapWithPassphrase, } from '@decryption/core';
2
- import { createRecipientFileEncryptor, fileRecipients, fingerprint, NotRecipientError, recipientFromString, sealFileTo, unwrapWithIdentity, } from '@decryption/keys';
3
- import { assertNotTerminal, assertStdinFree, ByteReader, chainBytes, openInput, transformBytes, writeBytes, writePlaintext, writeText, } from '../utils/bytes';
4
- import { takeFirst, wantsHelp } from '../utils/dispatch';
5
- import { CliError } from '../utils/errors';
6
- import { readFileHeader } from '../utils/header';
7
- import { resolvePassphrase } from '../utils/passphrase';
8
- import { collectRecipients } from '../utils/recipients';
9
- import { loadIdentity, readStoredIdentity } from '../utils/stash';
10
- export const encryptUsage = `
11
- Encrypt Command:
12
-
13
- dcrypt encrypt [text] [OPTIONS]
14
-
15
- Encrypt data with a passphrase, or to one or more X25519 recipients.
16
-
17
- With no format options the output is a small armored envelope (Argon2id +
18
- XChaCha20-Poly1305), held in memory: right for short secrets you paste around.
19
-
20
- --binary and --recipient select the file format instead: a binary envelope
21
- whose payload is encrypted in 64 KiB chunks, so files of any size are
22
- streamed rather than loaded. With --recipient no passphrase is asked for;
23
- whoever holds a matching identity ("dcrypt keys generate") can decrypt.
24
-
25
- Options:
26
- --in <file> Read the plaintext from a file ("-" for stdin)
27
- --out <file> Write the ciphertext to a file instead of stdout
28
- --binary Write the binary file format (streamed, for large files)
29
- --recipient <key> Encrypt to this dcrypt1… public key; repeat for several
30
- --recipients-file <p> Encrypt to every key in a file (one per line, # comments)
31
- --kdf <profile> interactive | moderate | sensitive (default: moderate)
32
- --aad <string> Bind the ciphertext to this associated data
33
- (armored passphrase envelopes only)
34
- --passphrase-file <p> Read the passphrase from a file
35
- --passphrase-stdin Read the passphrase from stdin
36
- --help, -h Show this help message
37
-
38
- --recipient without --binary writes the same file format as text
39
- ("dcrypt.v2.…"), buffered in memory: convenient for small values.
40
-
41
- Examples:
42
- dcrypt encrypt "attack at dawn"
43
- dcrypt encrypt --in notes.txt --out notes.dcrypt --kdf sensitive
44
- cat notes.txt | dcrypt encrypt --in -
45
- dcrypt encrypt --binary --in backup.tar --out backup.tar.dcrypt
46
- dcrypt encrypt --binary --recipient dcrypt1… --recipient dcrypt1… \\
47
- --in backup.tar --out backup.tar.dcrypt
48
- `;
49
- export const decryptUsage = `
50
- Decrypt Command:
51
-
52
- dcrypt decrypt [armored] [OPTIONS]
53
-
54
- Decrypt data produced by "dcrypt encrypt". The format is detected from the
55
- input. A file encrypted to recipients is opened with your stored identity,
56
- and the passphrase asked for is the one that protects that identity.
57
-
58
- Options:
59
- --in <file> Read the ciphertext from a file ("-" for stdin)
60
- --out <file> Write the plaintext to a file instead of stdout
61
- --aad <string> Associated data the ciphertext was bound to
62
- --passphrase-file <p> Read the passphrase from a file
63
- --passphrase-stdin Read the passphrase from stdin
64
- --help, -h Show this help message
65
-
66
- With --out the plaintext is written to a temporary file and renamed into
67
- place only after the whole input has authenticated: a wrong passphrase, a
68
- truncated or modified file, or an interrupt leaves --out untouched. On stdout,
69
- large files are streamed, so check the exit code before trusting the output.
70
-
71
- Exit codes:
72
- 2 wrong passphrase or tampered ciphertext
73
- 3 corrupt, truncated or unsupported envelope
74
- 4 no identity on this machine
75
- 5 your identity is not a recipient
76
-
77
- Examples:
78
- dcrypt decrypt --in notes.dcrypt --out notes.txt
79
- dcrypt decrypt --in backup.tar.dcrypt --out backup.tar
80
- `;
81
- const aadOf = (argv) => typeof argv.aad === 'string' ? argv.aad : undefined;
82
- export const encryptCommand = async (argv, prompter) => {
83
- if (wantsHelp(argv, encryptUsage))
84
- return;
85
- const { first, newArgv } = takeFirst(argv);
86
- const recipients = collectRecipients(newArgv);
87
- const binary = Boolean(newArgv.binary);
88
- if (binary || recipients.length) {
89
- await encryptFileFormat(newArgv, prompter, first, recipients, binary);
90
- return;
91
- }
92
- // The original format: one armored envelope, unchanged.
93
- const input = await openInput(newArgv, first);
94
- let plaintext;
95
- try {
96
- assertStdinFree(newArgv, input);
97
- plaintext = await new ByteReader(input.stream).all();
98
- }
99
- finally {
100
- input.close();
101
- }
102
- const passphrase = await resolvePassphrase(newArgv, prompter, { confirm: true });
103
- const envelope = encrypt(plaintext, passphrase, {
104
- kdf: resolveKdf(newArgv.kdf),
105
- aad: aadOf(newArgv),
106
- });
107
- await writeText(newArgv, armor(envelope));
108
- };
109
- const encryptFileFormat = async (argv, prompter, inline, recipients, binary) => {
110
- if (argv.aad !== undefined) {
111
- throw new CliError('--aad is only supported by the armored passphrase envelope; drop --aad, or drop --binary and --recipient');
112
- }
113
- assertNotTerminal(argv, { binary });
114
- const input = await openInput(argv, inline);
115
- try {
116
- if (!binary) {
117
- // Text form of the same file, for small values: buffered, because base64 is not streamed.
118
- const plaintext = await new ByteReader(input.stream).all();
119
- await writeText(argv, armorFile(sealFileTo(plaintext, recipients)));
120
- return;
121
- }
122
- if (!recipients.length)
123
- assertStdinFree(argv, input);
124
- const { header, stream } = recipients.length
125
- ? createRecipientFileEncryptor(recipients)
126
- : await passphraseFileEncryptor(argv, prompter);
127
- try {
128
- await writeBytes(argv, chainBytes([header], transformBytes(input.stream, stream)), { binary });
129
- }
130
- finally {
131
- stream.destroy();
132
- }
133
- }
134
- finally {
135
- input.close();
136
- }
137
- };
138
- const passphraseFileEncryptor = async (argv, prompter) => {
139
- const kdf = resolveKdf(argv.kdf);
140
- const passphrase = await resolvePassphrase(argv, prompter, { confirm: true });
141
- const fileKey = generateFileKey();
142
- try {
143
- return createFileEncryptor(fileKey, [wrapWithPassphrase(fileKey, passphrase, kdf)]);
144
- }
145
- finally {
146
- fileKey.fill(0);
147
- }
148
- };
149
- const startsWithMagic = (bytes) => bytes.length > MAGIC.length && MAGIC.every((byte, index) => bytes[index] === byte);
150
- export const decryptCommand = async (argv, prompter) => {
151
- if (wantsHelp(argv, decryptUsage))
152
- return;
153
- const { first, newArgv } = takeFirst(argv);
154
- const input = await openInput(newArgv, first);
155
- try {
156
- assertStdinFree(newArgv, input);
157
- const reader = new ByteReader(input.stream);
158
- const head = await reader.fill(MAGIC.length + 1);
159
- if (startsWithMagic(head)) {
160
- if (head[MAGIC.length] === FILE_VERSION) {
161
- await decryptFileFormat(newArgv, prompter, reader);
162
- return;
163
- }
164
- // A version 1 envelope that was never armored. Small by construction: read it whole.
165
- const envelope = await reader.all();
166
- const passphrase = await resolvePassphrase(newArgv, prompter);
167
- await writePlaintext(newArgv, decrypt(envelope, passphrase, { aad: aadOf(newArgv) }));
168
- return;
169
- }
170
- const text = (await reader.all()).toString('utf8').trim();
171
- if (text.startsWith(FILE_ARMOR_PREFIX)) {
172
- await decryptFileFormat(newArgv, prompter, new ByteReader([dearmorFile(text)]));
173
- return;
174
- }
175
- const passphrase = await resolvePassphrase(newArgv, prompter);
176
- await writePlaintext(newArgv, decrypt(dearmor(text), passphrase, { aad: aadOf(newArgv) }));
177
- }
178
- finally {
179
- input.close();
180
- }
181
- };
182
- /**
183
- * Recovers the file key. Nothing has been written anywhere yet when this runs, so a wrong
184
- * passphrase or a missing recipient fails before any output exists.
185
- */
186
- const unlockFileKey = async (argv, prompter, header) => {
187
- if (isPassphraseFile(header)) {
188
- return unwrapWithPassphrase(header, await resolvePassphrase(argv, prompter));
189
- }
190
- // The stored recipient is public, so "not for you" needs no passphrase to find out.
191
- const mine = fingerprint(recipientFromString(readStoredIdentity().recipient));
192
- const recipients = fileRecipients(header);
193
- if (!recipients.includes(mine)) {
194
- throw new NotRecipientError(`this identity (${mine}) is not a recipient; recipients are ${recipients.join(', ') || 'none'}`);
195
- }
196
- const identity = loadIdentity(await resolvePassphrase(argv, prompter, { message: 'Identity passphrase' }));
197
- try {
198
- return unwrapWithIdentity(header, identity);
199
- }
200
- finally {
201
- identity.privateKey.fill(0);
202
- }
203
- };
204
- const decryptFileFormat = async (argv, prompter, reader) => {
205
- if (argv.aad !== undefined) {
206
- throw new CliError('--aad does not apply here: this file format carries no associated data');
207
- }
208
- const header = await readFileHeader(reader);
209
- const fileKey = await unlockFileKey(argv, prompter, header);
210
- let decryptor;
211
- try {
212
- // Checks the header MAC: a header that was edited is rejected before any payload is read.
213
- decryptor = createFileDecryptor(header, fileKey);
214
- }
215
- finally {
216
- fileKey.fill(0);
217
- }
218
- try {
219
- await writeBytes(argv, transformBytes(reader.rest(), decryptor));
220
- }
221
- finally {
222
- decryptor.destroy();
223
- }
224
- };
225
- /**
226
- * Accepts a profile name, or explicit costs as `t=3,m=262144,p=1` for constrained hardware.
227
- * Envelopes carry their own parameters, so decryption never needs this flag.
228
- */
229
- export const resolveKdf = (value) => {
230
- if (value === undefined)
231
- return 'moderate';
232
- if (typeof value !== 'string')
233
- throw unknownKdf(value);
234
- if (value in KDF_PROFILES)
235
- return value;
236
- if (!/^[tmp]=\d+(,[tmp]=\d+)*$/.test(value))
237
- throw unknownKdf(value);
238
- const params = { ...KDF_PROFILES.moderate };
239
- for (const pair of value.split(',')) {
240
- const [name, count] = pair.split('=');
241
- params[name] = Number(count);
242
- }
243
- return params;
244
- };
245
- const unknownKdf = (value) => new CliError(`unknown --kdf value "${String(value)}"; expected ${Object.keys(KDF_PROFILES).join(', ')}, or explicit costs like t=3,m=262144,p=1`);
@@ -1,88 +0,0 @@
1
- import { takeFirst, wantsHelp } from '../utils/dispatch';
2
- import { CliError } from '../utils/errors';
3
- import { emit } from '../utils/io';
4
- import { count } from '../utils/text';
5
- import { isRepository } from '../workspace/git';
6
- import { installHook, runGuard } from '../workspace/guard';
7
- import { findWorkspace } from '../workspace/layout';
8
- import { isSnippetName, SNIPPETS } from '../workspace/snippets';
9
- export const guardUsage = `
10
- Guard Command:
11
-
12
- dcrypt guard [--staged | --all] [OPTIONS]
13
- dcrypt guard install [--force]
14
- dcrypt guard snippet [name]
15
-
16
- Refuse to let plaintext into git. The guard looks at what a commit would record
17
- and stops on:
18
-
19
- - a file inside the plaintext folder of an encrypted section;
20
- - a *.dcrypt file whose content is not encrypted;
21
- - a file .gitignore covers, added by force.
22
-
23
- "guard install" writes it as this repository's pre-commit hook. "guard snippet"
24
- prints a file to paste: ${Object.keys(SNIPPETS).join(', ')}.
25
-
26
- Options:
27
- --staged Check what is staged for the next commit (default)
28
- --all Check every tracked file (for CI)
29
- --force With install: replace a pre-commit hook dcrypt did not write
30
- --workspace <dir> The workspace root (default: the nearest folder upwards with a
31
- recipients.txt, otherwise the current folder)
32
- --json Machine-readable output
33
- --help, -h Show this help message
34
-
35
- Examples:
36
- dcrypt guard install
37
- dcrypt guard snippet gitignore > .gitignore
38
- dcrypt guard --all
39
- `;
40
- const check = async (argv) => {
41
- if (argv.staged && argv.all)
42
- throw new CliError('--staged and --all are alternatives');
43
- const workspace = findWorkspace(argv);
44
- if (!isRepository(workspace.root))
45
- throw new CliError(`${workspace.root} is not in a git repository`);
46
- const scope = argv.all ? 'all' : 'staged';
47
- const result = await runGuard(workspace, scope);
48
- const { violations } = result;
49
- const subject = count(result.checked, scope === 'all' ? 'tracked file' : 'staged file');
50
- emit(argv, { ok: violations.length === 0, ...result }, () => violations.length
51
- ? violations.map(({ path, message }) => `${path}: ${message}`).join('\n')
52
- : `dcrypt guard: ${subject} checked, nothing to stop`);
53
- if (violations.length) {
54
- throw new CliError(`${violations.length} of ${subject} must not be committed (to unstage: git restore --staged <path>)`);
55
- }
56
- };
57
- const install = (argv) => {
58
- const path = installHook(findWorkspace(argv), Boolean(argv.force));
59
- emit(argv, { installed: path }, () => `pre-commit guard installed at ${path}`);
60
- };
61
- const snippet = (argv) => {
62
- const { first: name } = takeFirst(argv);
63
- if (!name) {
64
- const width = Math.max(...Object.keys(SNIPPETS).map((key) => key.length));
65
- const lines = Object.entries(SNIPPETS).map(([key, { file }]) => `${key.padEnd(width)} ${file}`);
66
- process.stdout.write(`${lines.join('\n')}\n`);
67
- return;
68
- }
69
- if (!isSnippetName(name)) {
70
- throw new CliError(`unknown snippet "${name}"; there are: ${Object.keys(SNIPPETS).join(', ')}`);
71
- }
72
- process.stdout.write(SNIPPETS[name].text);
73
- };
74
- export const guardCommand = async (argv) => {
75
- if (wantsHelp(argv, guardUsage))
76
- return;
77
- const { first: subcommand, newArgv } = takeFirst(argv);
78
- switch (subcommand) {
79
- case undefined:
80
- return check(newArgv);
81
- case 'install':
82
- return install(newArgv);
83
- case 'snippet':
84
- return snippet(newArgv);
85
- default:
86
- throw new CliError(`unknown guard subcommand: ${subcommand}`);
87
- }
88
- };
@@ -1,88 +0,0 @@
1
- import { decryptFromString, encryptToString } from '@decryption/core';
2
- import { runSubcommand, takeFirst } from '../utils/dispatch';
3
- import { CliError, EXIT } from '../utils/errors';
4
- import { emit, readInput, writeOutput } from '../utils/io';
5
- import { resolvePassphrase } from '../utils/passphrase';
6
- import { keychainPath, readKeychain, writeKeychain } from '../utils/stash';
7
- import { resolveKdf } from './encrypt';
8
- export const keychainUsage = `
9
- Keychain Command:
10
-
11
- dcrypt keychain <subcommand> [name] [OPTIONS]
12
-
13
- Store named secrets locally, each encrypted under your passphrase. Values are
14
- always encrypted — there is no plaintext mode.
15
-
16
- Subcommands:
17
- set <name> Store a value
18
- get <name> Print a value
19
- del <name> Remove a value
20
- list List entry names (no values)
21
-
22
- Options:
23
- --in <file> Read the value from a file ("-" for stdin)
24
- --out <file> Write the value to a file instead of stdout
25
- --kdf <profile> interactive | moderate | sensitive (default: moderate)
26
- --json Machine-readable output
27
- --passphrase-file <p> Read the passphrase from a file
28
- --passphrase-stdin Read the passphrase from stdin
29
- --help, -h Show this help message
30
-
31
- Environment:
32
- KEYCHAIN_ACCOUNT Keychain namespace (default: dcrypt)
33
- DCRYPT_PASSPHRASE The passphrase, for unattended runs
34
-
35
- Examples:
36
- dcrypt keychain set github-token --in token.txt
37
- dcrypt keychain get github-token --out token.txt
38
- dcrypt keychain list
39
- `;
40
- const nameFrom = (argv) => {
41
- const { first, newArgv } = takeFirst(argv);
42
- const name = first ?? (typeof argv.name === 'string' ? argv.name : undefined);
43
- if (!name)
44
- throw new CliError('an entry name is required');
45
- return { name, newArgv };
46
- };
47
- const set = async (argv, prompter) => {
48
- const { name, newArgv } = nameFrom(argv);
49
- const { first: inline, newArgv: rest } = takeFirst(newArgv);
50
- const value = readInput(rest, inline);
51
- const passphrase = await resolvePassphrase(rest, prompter, { confirm: true });
52
- const keychain = readKeychain();
53
- keychain.entries[name] = encryptToString(value, passphrase, {
54
- aad: `dcrypt-keychain:${name}`,
55
- kdf: resolveKdf(rest.kdf),
56
- });
57
- writeKeychain(keychain);
58
- emit(rest, { name, path: keychainPath() }, () => `stored ${name} in ${keychainPath()}`);
59
- };
60
- const get = async (argv, prompter) => {
61
- const { name, newArgv } = nameFrom(argv);
62
- const entry = readKeychain().entries[name];
63
- if (!entry)
64
- throw new CliError(`no keychain entry named ${name}`, EXIT.notFound);
65
- const passphrase = await resolvePassphrase(newArgv, prompter);
66
- writeOutput(newArgv, decryptFromString(entry, passphrase, { aad: `dcrypt-keychain:${name}` }));
67
- };
68
- const del = (argv) => {
69
- const { name, newArgv } = nameFrom(argv);
70
- const keychain = readKeychain();
71
- if (!(name in keychain.entries)) {
72
- throw new CliError(`no keychain entry named ${name}`, EXIT.notFound);
73
- }
74
- delete keychain.entries[name];
75
- writeKeychain(keychain);
76
- emit(newArgv, { name, deleted: true }, () => `removed ${name}`);
77
- };
78
- const list = (argv) => {
79
- const names = Object.keys(readKeychain().entries).sort();
80
- emit(argv, { entries: names }, () => names.join('\n'));
81
- };
82
- export const keychainCommand = async (argv, prompter) => {
83
- await runSubcommand(argv, prompter, {
84
- name: 'keychain',
85
- usage: keychainUsage,
86
- handlers: { set, get, del, list },
87
- });
88
- };
@@ -1,70 +0,0 @@
1
- import { generateIdentity, identityFromSeed, recipientToString } from '@decryption/keys';
2
- import { mnemonicToSeed } from '@decryption/wallet';
3
- import { runSubcommand } from '../utils/dispatch';
4
- import { CliError } from '../utils/errors';
5
- import { emit, readInput } from '../utils/io';
6
- import { resolvePassphrase } from '../utils/passphrase';
7
- import { hasIdentity, identityPath, loadIdentity, readStoredIdentity, saveIdentity } from '../utils/stash';
8
- import { resolveKdf } from './encrypt';
9
- export const keysUsage = `
10
- Keys Command:
11
-
12
- dcrypt keys <subcommand> [OPTIONS]
13
-
14
- Manage the X25519 identity used to share team secrets. The private key is stored
15
- encrypted under a passphrase in ~/.dcrypt/config/identity.json and is never printed.
16
-
17
- Subcommands:
18
- generate Create an identity (use --from-mnemonic to derive it from BIP39 words)
19
- show Print your public recipient string
20
- verify Check that your passphrase unlocks the stored identity
21
-
22
- Options:
23
- --from-mnemonic Derive the identity from a mnemonic instead of random bytes
24
- --identity-index <n> Which identity to derive from the mnemonic (default: 0)
25
- --in <file> Read the mnemonic from a file ("-" for stdin)
26
- --force Overwrite an existing identity
27
- --kdf <profile> interactive | moderate | sensitive (default: moderate)
28
- --json Machine-readable output
29
- --passphrase-file <p> Read the passphrase from a file
30
- --passphrase-stdin Read the passphrase from stdin
31
- --help, -h Show this help message
32
-
33
- Examples:
34
- dcrypt keys generate
35
- dcrypt keys generate --from-mnemonic --in mnemonic.txt
36
- dcrypt keys show
37
- `;
38
- const generate = async (argv, prompter) => {
39
- if (hasIdentity() && !argv.force) {
40
- throw new CliError(`an identity already exists at ${identityPath()}; pass --force to replace it (anything encrypted to the old one becomes unreadable)`);
41
- }
42
- const identity = argv['from-mnemonic'] || argv.fromMnemonic
43
- ? identityFromSeed(mnemonicToSeed(readInput(argv).trim()), Number(argv['identity-index'] ?? argv.identityIndex ?? 0))
44
- : generateIdentity();
45
- const passphrase = await resolvePassphrase(argv, prompter, {
46
- confirm: true,
47
- message: 'Passphrase to protect the identity',
48
- });
49
- const stored = saveIdentity(identity, passphrase, resolveKdf(argv.kdf));
50
- identity.privateKey.fill(0);
51
- emit(argv, { recipient: stored.recipient, path: identityPath() }, () => [`identity written to ${identityPath()}`, `recipient: ${stored.recipient}`].join('\n'));
52
- };
53
- const show = (argv) => {
54
- const stored = readStoredIdentity();
55
- emit(argv, { recipient: stored.recipient }, () => stored.recipient);
56
- };
57
- const verify = async (argv, prompter) => {
58
- const passphrase = await resolvePassphrase(argv, prompter);
59
- const identity = loadIdentity(passphrase);
60
- const recipient = recipientToString(identity.publicKey);
61
- identity.privateKey.fill(0);
62
- emit(argv, { ok: true, recipient }, () => `ok — ${recipient}`);
63
- };
64
- export const keysCommand = async (argv, prompter) => {
65
- await runSubcommand(argv, prompter, {
66
- name: 'keys',
67
- usage: keysUsage,
68
- handlers: { generate, show, verify },
69
- });
70
- };
@@ -1,131 +0,0 @@
1
- import { PasskeyStore } from '@decryption/webauthn';
2
- import { runSubcommand, takeFirst } from '../utils/dispatch';
3
- import { CliError, EXIT } from '../utils/errors';
4
- import { emit, readStdin } from '../utils/io';
5
- import { openVault } from './vault';
6
- export const passkeyUsage = `
7
- Passkey Command:
8
-
9
- dcrypt passkey <subcommand> [OPTIONS]
10
-
11
- Passkeys held in the vault. dcrypt is the authenticator: it makes the key,
12
- keeps the private half encrypted, and signs the challenges a site sends. A
13
- passkey signs only for the site it was made for, so it cannot be phished.
14
-
15
- Subcommands:
16
- list [site] List stored passkeys, optionally for one site
17
- register <site> Create a passkey for a site and print the registration
18
- assert <site> Sign a sign-in challenge with the site's passkey
19
- forget <site> Delete a passkey from the vault
20
-
21
- Options:
22
- --challenge <b64url> The challenge the site issued (or --challenge-stdin)
23
- --challenge-stdin Read the challenge from stdin
24
- --origin <url> Origin to sign, defaults to https://<site>
25
- --user <name> Account name to register (default: the site's account)
26
- --credential <id> Which passkey, when a site has more than one
27
- --json Machine-readable output — what a relying party expects
28
- --passphrase-file <p> Read the master password from a file
29
- --help, -h Show this help message
30
-
31
- The response is printed as the JSON a WebAuthn relying party expects, so it can
32
- be piped straight into one:
33
-
34
- dcrypt passkey register auth.example.com --user dev@example.com \\
35
- --challenge "$(cnc webauthn begin-registration)" --json | cnc webauthn finish
36
- `;
37
- const withPasskeys = async (argv, prompter, run) => {
38
- const vault = await openVault(argv, prompter);
39
- try {
40
- await run(new PasskeyStore(vault), vault);
41
- }
42
- finally {
43
- await vault.lock();
44
- }
45
- };
46
- /**
47
- * The challenge is a public nonce, so unlike a password it is fine in argv —
48
- * but it is required: signing a challenge the caller invented proves nothing.
49
- */
50
- const resolveChallenge = (argv) => {
51
- if (argv['challenge-stdin'] || argv.challengeStdin) {
52
- return readStdin().trim();
53
- }
54
- const challenge = argv.challenge;
55
- if (typeof challenge !== 'string' || !challenge.length) {
56
- throw new CliError('a --challenge from the site is required');
57
- }
58
- return challenge;
59
- };
60
- const resolveOrigin = (argv, rpId) => typeof argv.origin === 'string' && argv.origin.length ? argv.origin : `https://${rpId}`;
61
- const describe = (record) => `${record.userName.padEnd(28)} ${record.rpId.padEnd(28)} used ${record.signCount}×`;
62
- const find = async (passkeys, site, credentialId) => {
63
- const matches = await passkeys.list(site);
64
- if (!matches.length) {
65
- throw new CliError(`no passkey for "${site}" in the vault`, EXIT.notFound);
66
- }
67
- if (!credentialId) {
68
- if (matches.length > 1) {
69
- throw new CliError(`${matches.length} passkeys for "${site}" — name one with --credential <id>`);
70
- }
71
- return matches[0];
72
- }
73
- const match = matches.find((record) => record.credentialId === credentialId);
74
- if (!match)
75
- throw new CliError(`no passkey ${credentialId} for "${site}"`, EXIT.notFound);
76
- return match;
77
- };
78
- const list = async (argv, prompter) => {
79
- const { first, newArgv } = takeFirst(argv);
80
- await withPasskeys(newArgv, prompter, async (passkeys) => {
81
- const all = await passkeys.list(first);
82
- emit(newArgv, all, () => all.map(describe).join('\n') || '(no passkeys)');
83
- });
84
- };
85
- const register = async (argv, prompter) => {
86
- const { first, newArgv } = takeFirst(argv);
87
- if (!first)
88
- throw new CliError('a site is required, e.g. auth.example.com');
89
- const challenge = resolveChallenge(newArgv);
90
- const userName = typeof newArgv.user === 'string' ? newArgv.user : first;
91
- await withPasskeys(newArgv, prompter, async (passkeys) => {
92
- const { record, response } = await passkeys.register({
93
- rpId: first,
94
- origin: resolveOrigin(newArgv, first),
95
- challenge,
96
- userName,
97
- });
98
- emit(newArgv, response, () => `registered ${record.userName} at ${record.rpId} (${record.credentialId})`);
99
- });
100
- };
101
- const assert = async (argv, prompter) => {
102
- const { first, newArgv } = takeFirst(argv);
103
- if (!first)
104
- throw new CliError('a site is required, e.g. auth.example.com');
105
- const challenge = resolveChallenge(newArgv);
106
- const credential = typeof newArgv.credential === 'string' ? newArgv.credential : undefined;
107
- await withPasskeys(newArgv, prompter, async (passkeys) => {
108
- const record = await find(passkeys, first, credential);
109
- const response = await passkeys.assert(record.itemId, {
110
- origin: resolveOrigin(newArgv, first),
111
- challenge,
112
- });
113
- emit(newArgv, response, () => `signed ${first}'s challenge as ${record.userName}`);
114
- });
115
- };
116
- const forget = async (argv, prompter) => {
117
- const { first, newArgv } = takeFirst(argv);
118
- if (!first)
119
- throw new CliError('a site is required');
120
- const credential = typeof newArgv.credential === 'string' ? newArgv.credential : undefined;
121
- await withPasskeys(newArgv, prompter, async (passkeys) => {
122
- const record = await find(passkeys, first, credential);
123
- await passkeys.forget(record.itemId);
124
- emit(newArgv, { credentialId: record.credentialId }, () => `forgot ${record.userName}'s passkey for ${record.rpId}`);
125
- });
126
- };
127
- export const passkeyCommand = async (argv, prompter) => runSubcommand(argv, prompter, {
128
- name: 'passkey',
129
- usage: passkeyUsage,
130
- handlers: { list, register, assert, forget },
131
- });