@tuskydp/cli 0.3.0 → 0.4.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 (113) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/src/commands/account.d.ts.map +1 -1
  3. package/dist/src/commands/account.js +0 -1
  4. package/dist/src/commands/account.js.map +1 -1
  5. package/dist/src/commands/auth.d.ts.map +1 -1
  6. package/dist/src/commands/auth.js +8 -5
  7. package/dist/src/commands/auth.js.map +1 -1
  8. package/dist/src/commands/download.d.ts.map +1 -1
  9. package/dist/src/commands/download.js +2 -59
  10. package/dist/src/commands/download.js.map +1 -1
  11. package/dist/src/commands/export.d.ts +5 -26
  12. package/dist/src/commands/export.d.ts.map +1 -1
  13. package/dist/src/commands/export.js +6 -46
  14. package/dist/src/commands/export.js.map +1 -1
  15. package/dist/src/commands/files.js +2 -2
  16. package/dist/src/commands/files.js.map +1 -1
  17. package/dist/src/commands/mcp.d.ts.map +1 -1
  18. package/dist/src/commands/mcp.js +15 -9
  19. package/dist/src/commands/mcp.js.map +1 -1
  20. package/dist/src/commands/sui.d.ts +3 -0
  21. package/dist/src/commands/sui.d.ts.map +1 -0
  22. package/dist/src/commands/sui.js +64 -0
  23. package/dist/src/commands/sui.js.map +1 -0
  24. package/dist/src/commands/trash.js +1 -1
  25. package/dist/src/commands/trash.js.map +1 -1
  26. package/dist/src/commands/upload.d.ts.map +1 -1
  27. package/dist/src/commands/upload.js +3 -49
  28. package/dist/src/commands/upload.js.map +1 -1
  29. package/dist/src/commands/vault.d.ts.map +1 -1
  30. package/dist/src/commands/vault.js +2 -24
  31. package/dist/src/commands/vault.js.map +1 -1
  32. package/dist/src/config.d.ts +2 -2
  33. package/dist/src/config.d.ts.map +1 -1
  34. package/dist/src/config.js +2 -3
  35. package/dist/src/config.js.map +1 -1
  36. package/dist/src/index.js +2 -4
  37. package/dist/src/index.js.map +1 -1
  38. package/dist/src/lib/resolve.d.ts.map +1 -1
  39. package/dist/src/lib/resolve.js +4 -5
  40. package/dist/src/lib/resolve.js.map +1 -1
  41. package/dist/src/mcp/context.d.ts +1 -9
  42. package/dist/src/mcp/context.d.ts.map +1 -1
  43. package/dist/src/mcp/context.js +1 -2
  44. package/dist/src/mcp/context.js.map +1 -1
  45. package/dist/src/mcp/server.d.ts.map +1 -1
  46. package/dist/src/mcp/server.js +0 -58
  47. package/dist/src/mcp/server.js.map +1 -1
  48. package/dist/src/mcp/tools/account.d.ts.map +1 -1
  49. package/dist/src/mcp/tools/account.js +1 -3
  50. package/dist/src/mcp/tools/account.js.map +1 -1
  51. package/dist/src/mcp/tools/files.d.ts +2 -3
  52. package/dist/src/mcp/tools/files.d.ts.map +1 -1
  53. package/dist/src/mcp/tools/files.js +18 -56
  54. package/dist/src/mcp/tools/files.js.map +1 -1
  55. package/dist/src/mcp/tools/vaults.js +2 -2
  56. package/dist/src/mcp/tools/vaults.js.map +1 -1
  57. package/dist/src/tui/files-panel.d.ts +0 -1
  58. package/dist/src/tui/files-panel.d.ts.map +1 -1
  59. package/dist/src/tui/files-panel.js +1 -2
  60. package/dist/src/tui/files-panel.js.map +1 -1
  61. package/dist/src/tui/index.d.ts.map +1 -1
  62. package/dist/src/tui/index.js +7 -42
  63. package/dist/src/tui/index.js.map +1 -1
  64. package/dist/src/tui/overview.d.ts.map +1 -1
  65. package/dist/src/tui/overview.js +2 -6
  66. package/dist/src/tui/overview.js.map +1 -1
  67. package/dist/src/tui/trash-screen.js +1 -1
  68. package/dist/src/tui/trash-screen.js.map +1 -1
  69. package/package.json +3 -3
  70. package/src/__tests__/seal.test.ts +7 -54
  71. package/src/commands/account.ts +0 -1
  72. package/src/commands/auth.ts +7 -5
  73. package/src/commands/download.ts +2 -63
  74. package/src/commands/export.ts +7 -67
  75. package/src/commands/files.ts +2 -2
  76. package/src/commands/mcp.ts +16 -10
  77. package/src/commands/sui.ts +69 -0
  78. package/src/commands/trash.ts +1 -1
  79. package/src/commands/upload.ts +3 -59
  80. package/src/commands/vault.ts +2 -23
  81. package/src/config.ts +3 -4
  82. package/src/index.ts +2 -4
  83. package/src/lib/resolve.ts +3 -4
  84. package/src/mcp/context.ts +1 -11
  85. package/src/mcp/server.ts +0 -69
  86. package/src/mcp/tools/account.ts +1 -3
  87. package/src/mcp/tools/files.ts +19 -70
  88. package/src/mcp/tools/vaults.ts +3 -3
  89. package/src/tui/files-panel.ts +1 -3
  90. package/src/tui/index.ts +7 -51
  91. package/src/tui/overview.ts +2 -5
  92. package/src/tui/trash-screen.ts +1 -1
  93. package/dist/src/commands/decrypt.d.ts +0 -15
  94. package/dist/src/commands/decrypt.d.ts.map +0 -1
  95. package/dist/src/commands/decrypt.js +0 -256
  96. package/dist/src/commands/decrypt.js.map +0 -1
  97. package/dist/src/commands/encryption.d.ts +0 -3
  98. package/dist/src/commands/encryption.d.ts.map +0 -1
  99. package/dist/src/commands/encryption.js +0 -254
  100. package/dist/src/commands/encryption.js.map +0 -1
  101. package/dist/src/crypto.d.ts +0 -32
  102. package/dist/src/crypto.d.ts.map +0 -1
  103. package/dist/src/crypto.js +0 -121
  104. package/dist/src/crypto.js.map +0 -1
  105. package/dist/src/lib/keyring.d.ts +0 -4
  106. package/dist/src/lib/keyring.d.ts.map +0 -1
  107. package/dist/src/lib/keyring.js +0 -49
  108. package/dist/src/lib/keyring.js.map +0 -1
  109. package/src/__tests__/crypto.test.ts +0 -315
  110. package/src/commands/decrypt.ts +0 -309
  111. package/src/commands/encryption.ts +0 -305
  112. package/src/crypto.ts +0 -165
  113. package/src/lib/keyring.ts +0 -50
@@ -1,309 +0,0 @@
1
- /**
2
- * `tusky decrypt` — Decrypt a file downloaded from Walrus.
3
- *
4
- * Works in two modes:
5
- * 1. With --export <manifest.json> — reads wrappedKey/iv from the export
6
- * manifest, derives master key from passphrase + salt. Fully offline.
7
- * 2. Without --export — fetches encryption params from the Tusky API and
8
- * looks up the file metadata by ID. Requires API access.
9
- *
10
- * In both modes, the passphrase is resolved from:
11
- * --passphrase flag > TUSKYDP_PASSWORD env var > interactive prompt
12
- */
13
-
14
- import type { Command } from 'commander';
15
- import { readFileSync, writeFileSync, existsSync } from 'fs';
16
- import { resolve, basename } from 'path';
17
- import chalk from 'chalk';
18
- import ora from 'ora';
19
- import inquirer from 'inquirer';
20
- import { getApiUrl, getApiKey } from '../config.js';
21
- import { createSDKClient } from '../sdk.js';
22
- import { createSpinner } from '../lib/progress.js';
23
- import { loadMasterKey } from '../lib/keyring.js';
24
- import {
25
- deriveMasterKey,
26
- verifyPassphrase,
27
- unwrapMasterKey,
28
- decryptBuffer,
29
- } from '../crypto.js';
30
- import type { ExportManifest, ExportedFile } from './export.js';
31
-
32
- // ---------------------------------------------------------------------------
33
- // Helpers
34
- // ---------------------------------------------------------------------------
35
-
36
- /**
37
- * Resolve the master key. Priority:
38
- * 1. Session keyring (~/.tusky/session.enc)
39
- * 2. Passphrase derivation (requires API or --salt/--encrypted-master-key)
40
- */
41
- async function resolveMasterKey(options: {
42
- passphrase?: string;
43
- salt?: string;
44
- verifier?: string;
45
- encryptedMasterKey?: string;
46
- }): Promise<Buffer> {
47
- // Try session keyring first
48
- const sessionKey = loadMasterKey();
49
- if (sessionKey) return sessionKey;
50
-
51
- // Need passphrase
52
- let passphrase = options.passphrase ?? process.env.TUSKYDP_PASSWORD;
53
- if (!passphrase) {
54
- const answers = await inquirer.prompt([{
55
- type: 'password',
56
- name: 'passphrase',
57
- message: 'Enter encryption passphrase:',
58
- mask: '*',
59
- }]);
60
- passphrase = answers.passphrase as string;
61
- }
62
-
63
- if (!options.salt) {
64
- throw new Error('Cannot derive master key: salt is required. Use --export with an export manifest, or ensure the Tusky API is accessible.');
65
- }
66
-
67
- const salt = Buffer.from(options.salt, 'base64');
68
- const wrappingKey = deriveMasterKey(passphrase, salt);
69
-
70
- // Verify if we have a verifier
71
- if (options.verifier) {
72
- const verifierBuf = Buffer.from(options.verifier, 'base64');
73
- if (!verifyPassphrase(wrappingKey, verifierBuf)) {
74
- throw new Error('Invalid passphrase.');
75
- }
76
- }
77
-
78
- // Unwrap master key if account has one
79
- if (options.encryptedMasterKey) {
80
- return unwrapMasterKey(Buffer.from(options.encryptedMasterKey, 'base64'), wrappingKey);
81
- }
82
-
83
- // Legacy: wrapping key IS the master key
84
- return wrappingKey;
85
- }
86
-
87
- // ---------------------------------------------------------------------------
88
- // Command registration
89
- // ---------------------------------------------------------------------------
90
-
91
- async function readStdin(): Promise<Buffer> {
92
- return new Promise((resolve, reject) => {
93
- const chunks: Buffer[] = [];
94
- process.stdin.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
95
- process.stdin.on('end', () => resolve(Buffer.concat(chunks)));
96
- process.stdin.on('error', reject);
97
- });
98
- }
99
-
100
- export function registerDecryptCommand(program: Command) {
101
- program
102
- .command('decrypt [encrypted-file]')
103
- .description('Decrypt a file downloaded from Walrus using your encryption passphrase')
104
- .option('-o, --output <path>', 'Output path for decrypted file')
105
- .option('--stdin', 'Read ciphertext from stdin (for sandboxed agents without filesystem access)')
106
- .option('--stdout', 'Write plaintext to stdout instead of a file')
107
- .option('--file-id <id>', 'Tusky file ID (to look up wrappedKey/iv from API)')
108
- .option('--export <path>', 'Path to tusky-export.json manifest (for offline decryption)')
109
- .option('--passphrase <passphrase>', 'Encryption passphrase (also reads TUSKYDP_PASSWORD env var)')
110
- .option('--wrapped-key <key>', 'Per-file wrapped key (base64, from export manifest)')
111
- .option('--iv <iv>', 'Per-file encryption IV (base64, from export manifest)')
112
- .option('--checksum <sha256>', 'Expected plaintext SHA-256 checksum (hex)')
113
- .action(async (encryptedFile: string | undefined, options: {
114
- output?: string;
115
- stdin?: boolean;
116
- stdout?: boolean;
117
- fileId?: string;
118
- export?: string;
119
- passphrase?: string;
120
- wrappedKey?: string;
121
- iv?: string;
122
- checksum?: string;
123
- }) => {
124
- // When piping to stdout, send spinner to stderr to avoid polluting the binary stream
125
- const spinnerStream = options.stdout ? process.stderr : process.stdout;
126
- const spinner = ora({ text: 'Preparing decryption...', stream: spinnerStream as NodeJS.WritableStream });
127
- spinner.start();
128
-
129
- try {
130
- // Resolve ciphertext source: --stdin, or file path
131
- let ciphertext: Buffer;
132
- let defaultFileName = 'decrypted';
133
-
134
- if (options.stdin) {
135
- spinner.text = 'Reading ciphertext from stdin...';
136
- ciphertext = await readStdin();
137
- } else {
138
- if (!encryptedFile) {
139
- spinner.fail('Provide an encrypted file path, or use --stdin to read from stdin.');
140
- return;
141
- }
142
- const inputPath = resolve(encryptedFile);
143
- if (!existsSync(inputPath)) {
144
- spinner.fail(`File not found: ${inputPath}`);
145
- return;
146
- }
147
- defaultFileName = basename(inputPath).replace(/\.enc$/, '');
148
- ciphertext = readFileSync(inputPath);
149
- }
150
-
151
- let wrappedKey: string;
152
- let iv: string;
153
- let checksum: string | undefined = options.checksum;
154
- let fileName: string = defaultFileName;
155
- let encryptionParams: { salt?: string; verifier?: string; encryptedMasterKey?: string } = {};
156
-
157
- // ── Mode 1: Export manifest ──────────────────────────────────
158
- if (options.export) {
159
- spinner.text = 'Reading export manifest...';
160
- const manifestPath = resolve(options.export);
161
- if (!existsSync(manifestPath)) {
162
- spinner.fail(`Export manifest not found: ${manifestPath}`);
163
- return;
164
- }
165
-
166
- const manifest: ExportManifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
167
- let exportedFile: ExportedFile | undefined;
168
-
169
- if (options.fileId) {
170
- exportedFile = manifest.files.find((f) => f.fileId === options.fileId);
171
- } else {
172
- exportedFile = manifest.files.find((f) =>
173
- f.name === defaultFileName || f.name === encryptedFile,
174
- );
175
-
176
- if (!exportedFile && manifest.files.length === 1) {
177
- exportedFile = manifest.files[0];
178
- }
179
- }
180
-
181
- if (!exportedFile) {
182
- spinner.fail(
183
- options.fileId
184
- ? `File ID ${options.fileId} not found in export manifest.`
185
- : `Could not match "${defaultFileName}" to a file in the export manifest. Use --file-id to specify.`,
186
- );
187
- return;
188
- }
189
-
190
- if (!exportedFile.encrypted) {
191
- spinner.fail(`File "${exportedFile.name}" is not encrypted (public vault). No decryption needed.`);
192
- return;
193
- }
194
-
195
- if (!exportedFile.wrappedKey || !exportedFile.encryptionIv) {
196
- spinner.fail(`File "${exportedFile.name}" is missing encryption metadata in the export.`);
197
- return;
198
- }
199
-
200
- wrappedKey = exportedFile.wrappedKey;
201
- iv = exportedFile.encryptionIv;
202
- checksum = checksum ?? exportedFile.plaintextChecksumSha256 ?? undefined;
203
- fileName = exportedFile.name;
204
-
205
- // Read account-level encryption params from manifest
206
- if (manifest.encryption) {
207
- encryptionParams = {
208
- salt: manifest.encryption.salt ?? undefined,
209
- verifier: manifest.encryption.verifier ?? undefined,
210
- encryptedMasterKey: manifest.encryption.encryptedMasterKey ?? undefined,
211
- };
212
- }
213
-
214
- // ── Mode 2: Direct flags ─────────────────────────────────────
215
- } else if (options.wrappedKey && options.iv) {
216
- wrappedKey = options.wrappedKey;
217
- iv = options.iv;
218
-
219
- // ── Mode 3: Fetch from API ───────────────────────────────────
220
- } else if (options.fileId) {
221
- spinner.text = 'Fetching file metadata from API...';
222
- const apiUrl = getApiUrl(program.opts().apiUrl);
223
- const apiKey = getApiKey(program.opts().apiKey);
224
- const sdk = createSDKClient(apiUrl, apiKey);
225
-
226
- const file = await sdk.files.get(options.fileId);
227
- if (!file.encrypted) {
228
- spinner.fail('This file is not encrypted. No decryption needed.');
229
- return;
230
- }
231
- if (!file.wrappedKey || !file.encryptionIv) {
232
- spinner.fail('File is missing encryption metadata.');
233
- return;
234
- }
235
-
236
- wrappedKey = file.wrappedKey;
237
- iv = file.encryptionIv;
238
- checksum = checksum ?? file.plaintextChecksumSha256 ?? undefined;
239
- fileName = file.name;
240
-
241
- // Also fetch encryption params for master key derivation
242
- const params = await sdk.account.getEncryptionParams();
243
- encryptionParams = {
244
- salt: params.salt ?? undefined,
245
- verifier: params.verifier ?? undefined,
246
- encryptedMasterKey: params.encryptedMasterKey ?? undefined,
247
- };
248
-
249
- } else {
250
- spinner.fail(
251
- 'Need encryption metadata. Use one of:\n' +
252
- ' --export <manifest.json> (offline, from tusky export)\n' +
253
- ' --file-id <id> (online, fetches from API)\n' +
254
- ' --wrapped-key <key> --iv <iv> (manual, base64 values)',
255
- );
256
- return;
257
- }
258
-
259
- // If we don't have encryption params yet, try API
260
- if (!encryptionParams.salt) {
261
- try {
262
- const apiUrl = getApiUrl(program.opts().apiUrl);
263
- const apiKey = getApiKey(program.opts().apiKey);
264
- const sdk = createSDKClient(apiUrl, apiKey);
265
- const params = await sdk.account.getEncryptionParams();
266
- encryptionParams = {
267
- salt: params.salt ?? undefined,
268
- verifier: params.verifier ?? undefined,
269
- encryptedMasterKey: params.encryptedMasterKey ?? undefined,
270
- };
271
- } catch {
272
- // API unavailable — that's ok if we have a session key
273
- }
274
- }
275
-
276
- // Resolve master key
277
- spinner.text = 'Deriving encryption key...';
278
- const masterKey = await resolveMasterKey({
279
- passphrase: options.passphrase,
280
- ...encryptionParams,
281
- });
282
-
283
- // Decrypt
284
- spinner.text = 'Decrypting...';
285
- const plaintext = decryptBuffer(ciphertext, wrappedKey, iv, masterKey, checksum);
286
-
287
- if (options.stdout) {
288
- spinner.stop();
289
- process.stdout.write(plaintext);
290
- if (checksum) {
291
- process.stderr.write(chalk.dim(' Integrity check passed (SHA-256)\n'));
292
- }
293
- } else {
294
- // Write to disk
295
- const outputPath = options.output ? resolve(options.output) : resolve(fileName);
296
- writeFileSync(outputPath, plaintext);
297
- spinner.succeed(`Decrypted -> ${outputPath} (${plaintext.length} bytes)`);
298
- if (checksum) {
299
- console.log(chalk.dim(' Integrity check passed (SHA-256)'));
300
- }
301
- }
302
- } catch (err: any) {
303
- spinner.fail(`Decryption failed: ${err.message}`);
304
- if (err.message.includes('Unsupported state') || err.message.includes('auth tag')) {
305
- console.log(chalk.dim(' This usually means the passphrase is incorrect or the file is corrupted.'));
306
- }
307
- }
308
- });
309
- }
@@ -1,305 +0,0 @@
1
- import type { Command } from 'commander';
2
- import chalk from 'chalk';
3
- import inquirer from 'inquirer';
4
- import { getSDKClientFromParent } from '../sdk.js';
5
- import {
6
- deriveMasterKey,
7
- computeVerifier,
8
- verifyPassphrase,
9
- generateSalt,
10
- generateMasterKey,
11
- generateRecoveryKey,
12
- wrapMasterKey,
13
- unwrapMasterKey,
14
- } from '../crypto.js';
15
- import { storeMasterKey, loadMasterKey, clearSession } from '../lib/keyring.js';
16
-
17
- export function registerEncryptionCommands(program: Command) {
18
- const encryption = program.command('encryption').description('Manage E2E encryption');
19
-
20
- encryption.command('setup')
21
- .description('Set encryption passphrase (first time only)')
22
- .action(async () => {
23
- const sdk = getSDKClientFromParent(encryption);
24
-
25
- // Check if already set up
26
- const { setupComplete } = await sdk.account.getEncryptionParams();
27
- if (setupComplete) {
28
- console.log(chalk.yellow('Encryption is already set up.'));
29
- console.log(chalk.dim('Use: tusky encryption change-passphrase'));
30
- return;
31
- }
32
-
33
- // Get passphrase
34
- const answers = await inquirer.prompt([
35
- {
36
- type: 'password',
37
- name: 'passphrase',
38
- message: 'Enter encryption passphrase:',
39
- mask: '*',
40
- validate: (input: string) => input.length >= 8 || 'Passphrase must be at least 8 characters',
41
- },
42
- {
43
- type: 'password',
44
- name: 'confirm',
45
- message: 'Confirm passphrase:',
46
- mask: '*',
47
- },
48
- ]);
49
-
50
- if (answers.passphrase !== answers.confirm) {
51
- console.error(chalk.red('Passphrases do not match.'));
52
- return;
53
- }
54
-
55
- // Generate random master key and derive wrapping key from passphrase
56
- const masterKey = generateMasterKey();
57
- const salt = generateSalt();
58
- const wrappingKey = deriveMasterKey(answers.passphrase, salt);
59
- const verifier = computeVerifier(wrappingKey);
60
-
61
- // Wrap master key with wrapping key (for passphrase unlock)
62
- const encryptedMasterKey = wrapMasterKey(masterKey, wrappingKey);
63
-
64
- // Wrap master key with recovery key (for recovery flow)
65
- const recoveryKeyRaw = generateRecoveryKey();
66
- const wrappedMasterKeyBackup = wrapMasterKey(masterKey, recoveryKeyRaw);
67
- const recoveryKeyBase64 = recoveryKeyRaw.toString('base64');
68
-
69
- // Send to server
70
- await sdk.account.setupEncryption({
71
- salt: salt.toString('base64'),
72
- verifier: verifier.toString('base64'),
73
- encryptedMasterKey: encryptedMasterKey.toString('base64'),
74
- wrappedMasterKeyBackup: wrappedMasterKeyBackup.toString('base64'),
75
- });
76
-
77
- // Store master key in session
78
- storeMasterKey(masterKey);
79
-
80
- // Display recovery key
81
- console.log('');
82
- console.log(chalk.yellow.bold('SAVE YOUR RECOVERY KEY — it will not be shown again:'));
83
- console.log('');
84
- console.log(chalk.bold(` ${recoveryKeyBase64}`));
85
- console.log('');
86
-
87
- const confirmSaved = await inquirer.prompt([{
88
- type: 'confirm',
89
- name: 'saved',
90
- message: 'Have you saved your recovery key?',
91
- default: false,
92
- }]);
93
-
94
- if (!confirmSaved.saved) {
95
- console.log(chalk.yellow('Please save your recovery key before continuing!'));
96
- console.log(chalk.bold(` ${recoveryKeyBase64}`));
97
- }
98
-
99
- console.log(chalk.green('Encryption configured successfully.'));
100
- });
101
-
102
- encryption.command('unlock')
103
- .description('Unlock encryption for this session')
104
- .option('--passphrase <passphrase>', 'Passphrase (non-interactive; also reads TUSKYDP_PASSWORD env var)')
105
- .action(async (options: { passphrase?: string }) => {
106
- const sdk = getSDKClientFromParent(encryption);
107
-
108
- const { setupComplete, salt, verifier, encryptedMasterKey } = await sdk.account.getEncryptionParams();
109
- if (!setupComplete) {
110
- console.error(chalk.red('Encryption not set up. Run: tusky encryption setup'));
111
- return;
112
- }
113
-
114
- // Resolve passphrase: flag > env var > interactive prompt
115
- let passphrase = options.passphrase ?? process.env.TUSKYDP_PASSWORD;
116
- if (!passphrase) {
117
- const answers = await inquirer.prompt([{
118
- type: 'password',
119
- name: 'passphrase',
120
- message: 'Enter encryption passphrase:',
121
- mask: '*',
122
- }]);
123
- passphrase = answers.passphrase as string;
124
- }
125
-
126
- const saltBuffer = Buffer.from(salt!, 'base64');
127
- const verifierBuffer = Buffer.from(verifier!, 'base64');
128
- const wrappingKey = deriveMasterKey(passphrase, saltBuffer);
129
-
130
- if (!verifyPassphrase(wrappingKey, verifierBuffer)) {
131
- console.error(chalk.red('Invalid passphrase.'));
132
- process.exit(1);
133
- }
134
-
135
- // Unwrap the real master key (or fall back to legacy where wrapping key = master key)
136
- let masterKey: Buffer;
137
- if (encryptedMasterKey) {
138
- masterKey = unwrapMasterKey(Buffer.from(encryptedMasterKey, 'base64'), wrappingKey);
139
- } else {
140
- masterKey = wrappingKey;
141
- }
142
-
143
- storeMasterKey(masterKey);
144
- console.log(chalk.green('Encryption session unlocked.'));
145
- });
146
-
147
- encryption.command('status')
148
- .description('Show encryption status')
149
- .action(async () => {
150
- const sdk = getSDKClientFromParent(encryption);
151
- const { setupComplete } = await sdk.account.getEncryptionParams();
152
- const sessionActive = loadMasterKey() !== null;
153
-
154
- console.log(`Encryption setup: ${setupComplete ? chalk.green('Complete') : chalk.yellow('Not set up')}`);
155
- console.log(`Session unlocked: ${sessionActive ? chalk.green('Yes') : chalk.yellow('No')}`);
156
- });
157
-
158
- encryption.command('change-passphrase')
159
- .description('Change encryption passphrase')
160
- .action(async () => {
161
- const sdk = getSDKClientFromParent(encryption);
162
-
163
- const { setupComplete, salt, verifier, encryptedMasterKey } = await sdk.account.getEncryptionParams();
164
- if (!setupComplete) {
165
- console.error(chalk.red('Encryption not set up. Run: tusky encryption setup'));
166
- return;
167
- }
168
-
169
- const answers = await inquirer.prompt([
170
- {
171
- type: 'password',
172
- name: 'currentPassphrase',
173
- message: 'Enter current passphrase:',
174
- mask: '*',
175
- },
176
- {
177
- type: 'password',
178
- name: 'newPassphrase',
179
- message: 'Enter new passphrase:',
180
- mask: '*',
181
- validate: (input: string) => input.length >= 8 || 'Passphrase must be at least 8 characters',
182
- },
183
- {
184
- type: 'password',
185
- name: 'confirmNew',
186
- message: 'Confirm new passphrase:',
187
- mask: '*',
188
- },
189
- ]);
190
-
191
- if (answers.newPassphrase !== answers.confirmNew) {
192
- console.error(chalk.red('New passphrases do not match.'));
193
- return;
194
- }
195
-
196
- // Verify current passphrase
197
- const currentSalt = Buffer.from(salt!, 'base64');
198
- const currentVerifier = Buffer.from(verifier!, 'base64');
199
- const currentWrappingKey = deriveMasterKey(answers.currentPassphrase, currentSalt);
200
-
201
- if (!verifyPassphrase(currentWrappingKey, currentVerifier)) {
202
- console.error(chalk.red('Invalid current passphrase.'));
203
- return;
204
- }
205
-
206
- // Unwrap the real master key (or use wrapping key as legacy fallback)
207
- let masterKey: Buffer;
208
- if (encryptedMasterKey) {
209
- masterKey = unwrapMasterKey(Buffer.from(encryptedMasterKey, 'base64'), currentWrappingKey);
210
- } else {
211
- masterKey = currentWrappingKey;
212
- }
213
-
214
- // Derive new wrapping key, re-wrap master key
215
- const newSalt = generateSalt();
216
- const newWrappingKey = deriveMasterKey(answers.newPassphrase, newSalt);
217
- const newVerifier = computeVerifier(newWrappingKey);
218
- const newEncryptedMasterKey = wrapMasterKey(masterKey, newWrappingKey);
219
-
220
- // Generate new recovery key and wrap master key with it
221
- const newRecoveryKey = generateRecoveryKey();
222
- const newWrappedBackup = wrapMasterKey(masterKey, newRecoveryKey);
223
-
224
- await sdk.account.resetEncryption({
225
- salt: newSalt.toString('base64'),
226
- verifier: newVerifier.toString('base64'),
227
- encryptedMasterKey: newEncryptedMasterKey.toString('base64'),
228
- wrappedMasterKeyBackup: newWrappedBackup.toString('base64'),
229
- });
230
-
231
- storeMasterKey(masterKey);
232
-
233
- console.log(chalk.yellow.bold('NEW RECOVERY KEY (save it!):'));
234
- console.log(chalk.bold(` ${newRecoveryKey.toString('base64')}`));
235
- console.log(chalk.green('Passphrase changed successfully.'));
236
- });
237
-
238
- encryption.command('recover')
239
- .description('Recover master key with recovery key')
240
- .action(async () => {
241
- const sdk = getSDKClientFromParent(encryption);
242
-
243
- const answers = await inquirer.prompt([
244
- {
245
- type: 'input',
246
- name: 'recoveryKey',
247
- message: 'Enter your recovery key (base64):',
248
- },
249
- {
250
- type: 'password',
251
- name: 'newPassphrase',
252
- message: 'Enter new passphrase:',
253
- mask: '*',
254
- validate: (input: string) => input.length >= 8 || 'Passphrase must be at least 8 characters',
255
- },
256
- {
257
- type: 'password',
258
- name: 'confirmNew',
259
- message: 'Confirm new passphrase:',
260
- mask: '*',
261
- },
262
- ]);
263
-
264
- if (answers.newPassphrase !== answers.confirmNew) {
265
- console.error(chalk.red('Passphrases do not match.'));
266
- return;
267
- }
268
-
269
- // Get wrapped master key backup from server
270
- const { wrappedMasterKeyBackup } = await sdk.account.getRecoveryData();
271
- const wrappedData = Buffer.from(wrappedMasterKeyBackup!, 'base64');
272
- const recoveryKeyRaw = Buffer.from(answers.recoveryKey, 'base64');
273
-
274
- let masterKey: Buffer;
275
- try {
276
- masterKey = unwrapMasterKey(wrappedData, recoveryKeyRaw);
277
- } catch {
278
- console.error(chalk.red('Invalid recovery key.'));
279
- return;
280
- }
281
-
282
- // Derive new wrapping key from new passphrase, wrap the RECOVERED master key
283
- const newSalt = generateSalt();
284
- const newWrappingKey = deriveMasterKey(answers.newPassphrase, newSalt);
285
- const newVerifier = computeVerifier(newWrappingKey);
286
- const newEncryptedMasterKey = wrapMasterKey(masterKey, newWrappingKey);
287
-
288
- // Generate new recovery key and wrap master key with it
289
- const newRecoveryKey = generateRecoveryKey();
290
- const newWrappedBackup = wrapMasterKey(masterKey, newRecoveryKey);
291
-
292
- await sdk.account.resetEncryption({
293
- salt: newSalt.toString('base64'),
294
- verifier: newVerifier.toString('base64'),
295
- encryptedMasterKey: newEncryptedMasterKey.toString('base64'),
296
- wrappedMasterKeyBackup: newWrappedBackup.toString('base64'),
297
- });
298
-
299
- storeMasterKey(masterKey);
300
-
301
- console.log(chalk.yellow.bold('NEW RECOVERY KEY (save it!):'));
302
- console.log(chalk.bold(` ${newRecoveryKey.toString('base64')}`));
303
- console.log(chalk.green('Recovery successful. Passphrase reset.'));
304
- });
305
- }