brain-memory 0.1.0-beta.3 → 0.1.0-beta.30

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 (66) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +379 -95
  3. package/SECURITY.md +61 -0
  4. package/assets/brand/README.md +28 -0
  5. package/assets/brand/icon-dark.svg +19 -0
  6. package/assets/brand/icon-light.svg +20 -0
  7. package/assets/brand/linkedin_cover.png +0 -0
  8. package/assets/brand/linkedin_cover_light.png +0 -0
  9. package/assets/brand/mark-dark.svg +19 -0
  10. package/assets/brand/mark-light.svg +20 -0
  11. package/assets/brand/png/icon-dark-1024.png +0 -0
  12. package/assets/brand/png/icon-dark-128.png +0 -0
  13. package/assets/brand/png/icon-dark-256.png +0 -0
  14. package/assets/brand/png/icon-dark-512.png +0 -0
  15. package/assets/brand/png/icon-dark-64.png +0 -0
  16. package/assets/brand/png/icon-light-1024.png +0 -0
  17. package/assets/brand/png/icon-light-128.png +0 -0
  18. package/assets/brand/png/icon-light-256.png +0 -0
  19. package/assets/brand/png/icon-light-512.png +0 -0
  20. package/assets/brand/png/icon-light-64.png +0 -0
  21. package/assets/brand/png/mark-dark-1024.png +0 -0
  22. package/assets/brand/png/mark-light-1024.png +0 -0
  23. package/assets/icon.png +0 -0
  24. package/assets/icon.svg +19 -0
  25. package/bin/brain.js +111 -0
  26. package/bin/cloud-sync.js +150 -0
  27. package/bin/forget.js +122 -0
  28. package/bin/install.js +229 -254
  29. package/bin/memorize.js +458 -0
  30. package/bin/pin.js +44 -0
  31. package/bin/recall.js +251 -0
  32. package/bin/reinforce.js +187 -0
  33. package/bin/session-start.js +298 -0
  34. package/bin/skill.js +67 -0
  35. package/bin/unpin.js +38 -0
  36. package/commands/brain/forget.md +245 -15
  37. package/commands/brain/memorize.md +76 -144
  38. package/commands/brain/pin.md +79 -0
  39. package/commands/brain/remember.md +48 -105
  40. package/commands/brain/skills.md +60 -0
  41. package/commands/brain/sleep.md +69 -28
  42. package/commands/brain/status.md +24 -10
  43. package/commands/brain/sync.md +386 -0
  44. package/package.json +22 -8
  45. package/prompts/antigravity.md +180 -0
  46. package/prompts/claude.md +124 -20
  47. package/prompts/openai.md +124 -20
  48. package/prompts/opencode.md +179 -0
  49. package/src/cloud-sync.js +534 -0
  50. package/src/crypto.js +130 -0
  51. package/src/export-import.js +200 -0
  52. package/src/git-sync.js +444 -0
  53. package/src/index-manager.js +219 -18
  54. package/src/installer.js +444 -0
  55. package/src/pinning.js +124 -0
  56. package/src/scorer.js +22 -9
  57. package/src/skills.js +208 -0
  58. package/src/tfidf.js +501 -0
  59. package/commands/brain/consolidate.md +0 -153
  60. package/commands/brain/explore.md +0 -79
  61. package/commands/brain/init.md +0 -157
  62. package/commands/brain/review.md +0 -130
  63. package/commands/brain/sunshine.md +0 -337
  64. package/hooks/session-end.md +0 -48
  65. package/hooks/session-start.md +0 -48
  66. package/prompts/gemini.md +0 -76
@@ -0,0 +1,534 @@
1
+ /**
2
+ * Brain Memory — Cloud Sync Engine
3
+ *
4
+ * Push/pull ~/.brain/ memories via the Brain Cloud API (api.brainmemory.ai).
5
+ * Uses the device code OAuth flow for CLI authentication.
6
+ *
7
+ * Zero external dependencies — uses Node.js built-in https, fs, child_process.
8
+ */
9
+
10
+ const { execFileSync } = require('child_process');
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const os = require('os');
14
+ const https = require('https');
15
+ const http = require('http');
16
+
17
+ const CLOUD_DIR = '.cloud';
18
+ const CONFIG_FILE = 'config.json';
19
+ const DEFAULT_API_URL = 'https://api.brainmemory.ai';
20
+
21
+ // Files/dirs inside ~/.brain/ that should NOT be synced
22
+ const TAR_EXCLUDES = ['.sync', '.cloud', '.DS_Store', '_archived'];
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // HTTP helpers (zero-dependency, works on Node >= 18)
26
+ // ---------------------------------------------------------------------------
27
+
28
+ /**
29
+ * Make an HTTP(S) request. Returns { status, headers, body }.
30
+ *
31
+ * @param {string} url
32
+ * @param {Object} [opts]
33
+ * @param {string} [opts.method='GET']
34
+ * @param {Object} [opts.headers]
35
+ * @param {Buffer|string} [opts.body]
36
+ * @returns {Promise<{status: number, headers: Object, body: string}>}
37
+ */
38
+ function request(url, opts = {}, _redirectCount = 0) {
39
+ return new Promise((resolve, reject) => {
40
+ if (_redirectCount > 5) return reject(new Error('Too many redirects'));
41
+
42
+ const parsed = new URL(url);
43
+ const mod = parsed.protocol === 'https:' ? https : http;
44
+ const reqOpts = {
45
+ method: opts.method || 'GET',
46
+ hostname: parsed.hostname,
47
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
48
+ path: parsed.pathname + parsed.search,
49
+ headers: opts.headers || {},
50
+ };
51
+
52
+ const req = mod.request(reqOpts, (res) => {
53
+ // Follow redirects
54
+ if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
55
+ const redirectUrl = new URL(res.headers.location, url).href;
56
+ // For 307/308, preserve method and body; for 301/302, switch to GET.
57
+ // When dropping the body we must also drop the body-describing headers,
58
+ // or the redirected GET advertises a Content-Length it never sends and
59
+ // the socket hangs waiting to flush a body that isn't coming.
60
+ let newOpts;
61
+ if ([307, 308].includes(res.statusCode)) {
62
+ newOpts = opts;
63
+ } else {
64
+ const headers = { ...(opts.headers || {}) };
65
+ for (const h of Object.keys(headers)) {
66
+ if (/^content-(length|type)$/i.test(h)) delete headers[h];
67
+ }
68
+ newOpts = { ...opts, method: 'GET', body: undefined, headers };
69
+ }
70
+ res.resume(); // drain the response
71
+ return resolve(request(redirectUrl, newOpts, _redirectCount + 1));
72
+ }
73
+
74
+ const chunks = [];
75
+ res.on('data', (chunk) => chunks.push(chunk));
76
+ res.on('end', () => {
77
+ resolve({
78
+ status: res.statusCode,
79
+ headers: res.headers,
80
+ body: Buffer.concat(chunks).toString('utf8'),
81
+ });
82
+ });
83
+ });
84
+
85
+ req.on('error', reject);
86
+ req.setTimeout(60000, () => { req.destroy(new Error('Request timed out')); });
87
+
88
+ if (opts.body) req.write(opts.body);
89
+ req.end();
90
+ });
91
+ }
92
+
93
+ /**
94
+ * JSON POST/PUT helper.
95
+ */
96
+ async function jsonRequest(url, method, data, token) {
97
+ const headers = { 'Content-Type': 'application/json' };
98
+ if (token) headers['Authorization'] = `Bearer ${token}`;
99
+ const body = data != null ? JSON.stringify(data) : undefined;
100
+ if (body) headers['Content-Length'] = Buffer.byteLength(body).toString();
101
+ const res = await request(url, { method, headers, body });
102
+ try {
103
+ return { status: res.status, data: JSON.parse(res.body) };
104
+ } catch {
105
+ throw new Error(`Non-JSON response (${res.status}) from ${method} ${url}: ${res.body.slice(0, 200)}`);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Upload a file as multipart/form-data.
111
+ */
112
+ async function uploadFile(url, filePath, token) {
113
+ const boundary = '----BrainCloudUpload' + Date.now();
114
+ const fileContent = fs.readFileSync(filePath);
115
+ const header = Buffer.from(
116
+ `--${boundary}\r\n` +
117
+ `Content-Disposition: form-data; name="brain"; filename="brain.tar.gz"\r\n` +
118
+ `Content-Type: application/gzip\r\n\r\n`
119
+ );
120
+ const footer = Buffer.from(`\r\n--${boundary}--\r\n`);
121
+ const body = Buffer.concat([header, fileContent, footer]);
122
+
123
+ return request(url, {
124
+ method: 'PUT',
125
+ headers: {
126
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
127
+ 'Content-Length': body.length.toString(),
128
+ 'Authorization': `Bearer ${token}`,
129
+ },
130
+ body,
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Download a file from URL, save to disk.
136
+ */
137
+ function downloadFile(url, destPath, token, _redirectCount = 0) {
138
+ return new Promise((resolve, reject) => {
139
+ if (_redirectCount > 5) return reject(new Error('Too many redirects'));
140
+
141
+ const parsed = new URL(url);
142
+ const mod = parsed.protocol === 'https:' ? https : http;
143
+ const reqOpts = {
144
+ method: 'GET',
145
+ hostname: parsed.hostname,
146
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
147
+ path: parsed.pathname + parsed.search,
148
+ headers: { 'Authorization': `Bearer ${token}` },
149
+ };
150
+
151
+ const req = mod.request(reqOpts, (res) => {
152
+ // Follow redirects
153
+ if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
154
+ const redirectUrl = new URL(res.headers.location, url).href;
155
+ res.resume();
156
+ return resolve(downloadFile(redirectUrl, destPath, token, _redirectCount + 1));
157
+ }
158
+
159
+ if (res.statusCode !== 200) {
160
+ const chunks = [];
161
+ res.on('data', (c) => chunks.push(c));
162
+ res.on('end', () => {
163
+ reject(new Error(`Download failed (${res.statusCode}): ${Buffer.concat(chunks).toString()}`));
164
+ });
165
+ return;
166
+ }
167
+
168
+ const ws = fs.createWriteStream(destPath);
169
+ res.pipe(ws);
170
+ ws.on('finish', () => {
171
+ ws.close();
172
+ resolve({ checksum: res.headers['x-checksum'] || null });
173
+ });
174
+ ws.on('error', reject);
175
+ });
176
+
177
+ req.on('error', reject);
178
+ req.setTimeout(300000, () => { req.destroy(new Error('Download timed out')); });
179
+ req.end();
180
+ });
181
+ }
182
+
183
+ // ---------------------------------------------------------------------------
184
+ // Config management — stored at ~/.brain/.cloud/config.json
185
+ // ---------------------------------------------------------------------------
186
+
187
+ function resolvePaths(brainDir) {
188
+ const cloudDir = path.join(brainDir, CLOUD_DIR);
189
+ const configPath = path.join(cloudDir, CONFIG_FILE);
190
+ return { cloudDir, configPath };
191
+ }
192
+
193
+ function readConfig(brainDir) {
194
+ const { configPath } = resolvePaths(brainDir);
195
+ try {
196
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+
202
+ function writeConfig(brainDir, config) {
203
+ const { cloudDir, configPath } = resolvePaths(brainDir);
204
+ fs.mkdirSync(cloudDir, { recursive: true });
205
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
206
+ }
207
+
208
+ function deleteConfig(brainDir) {
209
+ const { cloudDir } = resolvePaths(brainDir);
210
+ fs.rmSync(cloudDir, { recursive: true, force: true });
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // Token management
215
+ // ---------------------------------------------------------------------------
216
+
217
+ /**
218
+ * Get a valid access token, refreshing if needed.
219
+ *
220
+ * @param {string} brainDir
221
+ * @returns {Promise<string>} access token
222
+ */
223
+ async function getValidToken(brainDir) {
224
+ const config = readConfig(brainDir);
225
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
226
+
227
+ const now = Math.floor(Date.now() / 1000);
228
+
229
+ // Token still valid (with 30s buffer)
230
+ if (config.expires_at && now < config.expires_at - 30) {
231
+ return config.access_token;
232
+ }
233
+
234
+ // Try refresh
235
+ if (!config.refresh_token) {
236
+ throw new Error('Session expired and no refresh token. Run cloud login again.');
237
+ }
238
+
239
+ const res = await jsonRequest(
240
+ `${config.api_url}/auth/refresh`,
241
+ 'POST',
242
+ { refresh_token: config.refresh_token }
243
+ );
244
+
245
+ if (res.status !== 200) {
246
+ throw new Error('Token refresh failed. Run cloud login again.');
247
+ }
248
+
249
+ config.access_token = res.data.access_token;
250
+ config.refresh_token = res.data.refresh_token;
251
+ config.expires_at = res.data.expires_at;
252
+ writeConfig(brainDir, config);
253
+
254
+ return config.access_token;
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // Device code auth flow
259
+ // ---------------------------------------------------------------------------
260
+
261
+ /**
262
+ * Start the device code login flow.
263
+ * Returns the device code info so the caller can display it to the user.
264
+ *
265
+ * @param {string} apiUrl
266
+ * @returns {Promise<{device_code: string, user_code: string, verify_url: string, expires_in: number}>}
267
+ */
268
+ async function requestDeviceCode(apiUrl) {
269
+ const res = await jsonRequest(`${apiUrl}/auth/device/request`, 'POST', {});
270
+ if (res.status !== 200) {
271
+ throw new Error(`Failed to request device code: ${JSON.stringify(res.data)}`);
272
+ }
273
+ return res.data;
274
+ }
275
+
276
+ /**
277
+ * Poll for device code approval.
278
+ *
279
+ * @param {string} apiUrl
280
+ * @param {string} deviceCode
281
+ * @param {number} interval - Poll interval in ms (default 5000)
282
+ * @param {number} timeout - Max wait in ms (default 600000 = 10 min)
283
+ * @returns {Promise<{access_token: string, refresh_token: string, expires_at: number}>}
284
+ */
285
+ async function pollDeviceCode(apiUrl, deviceCode, interval = 5000, timeout = 600000) {
286
+ const deadline = Date.now() + timeout;
287
+
288
+ while (Date.now() < deadline) {
289
+ const res = await jsonRequest(`${apiUrl}/auth/device/poll`, 'POST', { device_code: deviceCode });
290
+
291
+ if (res.status === 200 && res.data.status === 'approved' && res.data.tokens) {
292
+ return res.data.tokens;
293
+ }
294
+
295
+ if (res.status === 404 || (res.data && res.data.error && res.data.error.includes('expired'))) {
296
+ throw new Error('Device code expired. Try again.');
297
+ }
298
+
299
+ // Still pending — wait and retry
300
+ await new Promise((r) => setTimeout(r, interval));
301
+ }
302
+
303
+ throw new Error('Login timed out. Try again.');
304
+ }
305
+
306
+ /**
307
+ * Full login flow: request code, poll, save config.
308
+ *
309
+ * @param {string} brainDir
310
+ * @param {string} [apiUrl]
311
+ * @returns {Promise<{user_code: string, verify_url: string, waitForApproval: () => Promise<void>}>}
312
+ */
313
+ async function login(brainDir, apiUrl) {
314
+ const url = apiUrl || DEFAULT_API_URL;
315
+ const codeInfo = await requestDeviceCode(url);
316
+
317
+ return {
318
+ user_code: codeInfo.user_code,
319
+ verify_url: codeInfo.verify_url,
320
+ expires_in: codeInfo.expires_in,
321
+ waitForApproval: async () => {
322
+ const tokens = await pollDeviceCode(url, codeInfo.device_code);
323
+
324
+ // Fetch user info + default brain
325
+ const meRes = await jsonRequest(`${url}/auth/me`, 'GET', null, tokens.access_token);
326
+ let userEmail = '';
327
+ if (meRes.status === 200 && meRes.data.user) {
328
+ userEmail = meRes.data.user.email;
329
+ }
330
+
331
+ const brainsRes = await jsonRequest(`${url}/api/brains`, 'GET', null, tokens.access_token);
332
+ let brainId = null;
333
+ if (brainsRes.status === 200 && Array.isArray(brainsRes.data) && brainsRes.data.length > 0) {
334
+ brainId = brainsRes.data[0].id;
335
+ }
336
+
337
+ writeConfig(brainDir, {
338
+ api_url: url,
339
+ access_token: tokens.access_token,
340
+ refresh_token: tokens.refresh_token,
341
+ expires_at: tokens.expires_at,
342
+ brain_id: brainId,
343
+ user_email: userEmail,
344
+ connected_at: new Date().toISOString(),
345
+ });
346
+ },
347
+ };
348
+ }
349
+
350
+ /**
351
+ * Logout — clear stored tokens.
352
+ *
353
+ * @param {string} brainDir
354
+ */
355
+ function logout(brainDir) {
356
+ deleteConfig(brainDir);
357
+ }
358
+
359
+ // ---------------------------------------------------------------------------
360
+ // Tar helpers
361
+ // ---------------------------------------------------------------------------
362
+
363
+ function packBrain(brainDir) {
364
+ const tmpFile = path.join(os.tmpdir(), `brain-upload-${Date.now()}.tar.gz`);
365
+ const excludeArgs = TAR_EXCLUDES.flatMap((e) => ['--exclude', e]);
366
+
367
+ execFileSync('tar', ['czf', tmpFile, ...excludeArgs, '-C', brainDir, '.'], {
368
+ stdio: 'pipe',
369
+ timeout: 120000,
370
+ });
371
+
372
+ return tmpFile;
373
+ }
374
+
375
+ function unpackBrain(tarPath, brainDir) {
376
+ // Extract into brain dir, overwriting existing files
377
+ execFileSync('tar', ['xzf', tarPath, '-C', brainDir], {
378
+ stdio: 'pipe',
379
+ timeout: 120000,
380
+ });
381
+ }
382
+
383
+ // ---------------------------------------------------------------------------
384
+ // Push / Pull
385
+ // ---------------------------------------------------------------------------
386
+
387
+ /**
388
+ * Push ~/.brain/ to the cloud.
389
+ *
390
+ * @param {string} brainDir
391
+ * @returns {Promise<{size_bytes: number, file_count: number, checksum: string}>}
392
+ */
393
+ async function push(brainDir) {
394
+ const config = readConfig(brainDir);
395
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
396
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
397
+
398
+ const token = await getValidToken(brainDir);
399
+
400
+ // Pack ~/.brain/ into tar.gz
401
+ const tarPath = packBrain(brainDir);
402
+
403
+ try {
404
+ const tarSize = fs.statSync(tarPath).size;
405
+ const url = `${config.api_url}/api/brains/${config.brain_id}/sync`;
406
+
407
+ const res = await uploadFile(url, tarPath, token);
408
+
409
+ if (res.status !== 200) {
410
+ const data = JSON.parse(res.body);
411
+ throw new Error(`Push failed (${res.status}): ${data.error || res.body}`);
412
+ }
413
+
414
+ const result = JSON.parse(res.body);
415
+
416
+ // Update config with last push time
417
+ config.last_push = new Date().toISOString();
418
+ writeConfig(brainDir, config);
419
+
420
+ return { ...result, local_size: tarSize };
421
+ } finally {
422
+ // Clean up temp file
423
+ try { fs.unlinkSync(tarPath); } catch { /* ignore */ }
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Pull from the cloud into ~/.brain/.
429
+ *
430
+ * @param {string} brainDir
431
+ * @returns {Promise<{size_bytes: number, checksum: string|null}>}
432
+ */
433
+ async function pull(brainDir) {
434
+ const config = readConfig(brainDir);
435
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
436
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
437
+
438
+ const token = await getValidToken(brainDir);
439
+ const url = `${config.api_url}/api/brains/${config.brain_id}/sync`;
440
+ const tmpFile = path.join(os.tmpdir(), `brain-download-${Date.now()}.tar.gz`);
441
+
442
+ try {
443
+ const { checksum } = await downloadFile(url, tmpFile, token);
444
+ const size = fs.statSync(tmpFile).size;
445
+
446
+ // Extract into ~/.brain/
447
+ unpackBrain(tmpFile, brainDir);
448
+
449
+ // Update config
450
+ config.last_pull = new Date().toISOString();
451
+ writeConfig(brainDir, config);
452
+
453
+ return { size_bytes: size, checksum };
454
+ } finally {
455
+ try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
456
+ }
457
+ }
458
+
459
+ // ---------------------------------------------------------------------------
460
+ // Status
461
+ // ---------------------------------------------------------------------------
462
+
463
+ /**
464
+ * Get cloud sync status.
465
+ *
466
+ * @param {string} brainDir
467
+ * @returns {Promise<Object>}
468
+ */
469
+ async function status(brainDir) {
470
+ const config = readConfig(brainDir);
471
+ if (!config) {
472
+ return { connected: false };
473
+ }
474
+
475
+ let brain = null;
476
+ let user = null;
477
+
478
+ try {
479
+ const token = await getValidToken(brainDir);
480
+
481
+ const meRes = await jsonRequest(`${config.api_url}/auth/me`, 'GET', null, token);
482
+ if (meRes.status === 200) {
483
+ user = meRes.data.user;
484
+ }
485
+
486
+ if (config.brain_id) {
487
+ const brainRes = await jsonRequest(
488
+ `${config.api_url}/api/brains/${config.brain_id}`,
489
+ 'GET', null, token
490
+ );
491
+ if (brainRes.status === 200) {
492
+ brain = brainRes.data;
493
+ }
494
+ }
495
+ } catch {
496
+ // Token may be expired — still report config
497
+ }
498
+
499
+ return {
500
+ connected: true,
501
+ api_url: config.api_url,
502
+ user_email: config.user_email || (user && user.email) || null,
503
+ brain_id: config.brain_id,
504
+ brain_name: brain ? brain.name : null,
505
+ brain_size: brain ? brain.size_bytes : null,
506
+ brain_files: brain ? brain.file_count : null,
507
+ last_synced: brain && brain.last_synced_at ? brain.last_synced_at : null,
508
+ last_push: config.last_push || null,
509
+ last_pull: config.last_pull || null,
510
+ connected_at: config.connected_at || null,
511
+ };
512
+ }
513
+
514
+ // ---------------------------------------------------------------------------
515
+ // Exports
516
+ // ---------------------------------------------------------------------------
517
+
518
+ module.exports = {
519
+ login,
520
+ logout,
521
+ push,
522
+ pull,
523
+ status,
524
+ readConfig,
525
+ writeConfig,
526
+ // Internal — exported for testing
527
+ requestDeviceCode,
528
+ pollDeviceCode,
529
+ getValidToken,
530
+ packBrain,
531
+ unpackBrain,
532
+ resolvePaths,
533
+ DEFAULT_API_URL,
534
+ };
package/src/crypto.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Brain Memory — Crypto Utilities
3
+ *
4
+ * AES-256-GCM encryption for memory export/import and encrypted sync.
5
+ * Zero external dependencies — uses only Node.js built-in crypto.
6
+ */
7
+
8
+ const crypto = require('crypto');
9
+
10
+ const PBKDF2_ITERATIONS = 100000;
11
+ const PBKDF2_DIGEST = 'sha512';
12
+ const KEY_LENGTH = 32; // 256 bits
13
+ const IV_LENGTH = 12; // 96 bits for GCM
14
+ const SALT_LENGTH = 32;
15
+ const AUTH_TAG_LENGTH = 16;
16
+
17
+ /**
18
+ * Derive an AES-256 key from a passphrase using PBKDF2.
19
+ *
20
+ * @param {string} passphrase - User-provided passphrase
21
+ * @param {Buffer} salt - 32-byte salt
22
+ * @returns {Buffer} 32-byte derived key
23
+ */
24
+ function deriveKey(passphrase, salt) {
25
+ return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
26
+ }
27
+
28
+ /**
29
+ * Encrypt a UTF-8 string with AES-256-GCM.
30
+ *
31
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
32
+ *
33
+ * @param {string} plaintext - UTF-8 string to encrypt
34
+ * @param {string} passphrase - Passphrase (key derived via PBKDF2)
35
+ * @returns {Buffer} Encrypted buffer
36
+ */
37
+ function encrypt(plaintext, passphrase) {
38
+ const salt = crypto.randomBytes(SALT_LENGTH);
39
+ const key = deriveKey(passphrase, salt);
40
+ const iv = crypto.randomBytes(IV_LENGTH);
41
+
42
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
43
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
44
+ const authTag = cipher.getAuthTag();
45
+
46
+ return Buffer.concat([salt, iv, authTag, encrypted]);
47
+ }
48
+
49
+ /**
50
+ * Decrypt an AES-256-GCM encrypted buffer back to a UTF-8 string.
51
+ *
52
+ * @param {Buffer} encrypted - Buffer produced by encrypt()
53
+ * @param {string} passphrase - Same passphrase used for encryption
54
+ * @returns {string} Decrypted UTF-8 string
55
+ * @throws {Error} If passphrase is wrong or data is tampered
56
+ */
57
+ function decrypt(encrypted, passphrase) {
58
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
59
+ throw new Error('Invalid encrypted data: too short');
60
+ }
61
+
62
+ const salt = encrypted.subarray(0, SALT_LENGTH);
63
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
64
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
65
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
66
+
67
+ const key = deriveKey(passphrase, salt);
68
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
69
+ decipher.setAuthTag(authTag);
70
+
71
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
72
+ }
73
+
74
+ /**
75
+ * Encrypt a Buffer with AES-256-GCM.
76
+ *
77
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
78
+ *
79
+ * @param {Buffer} buffer - Raw buffer to encrypt
80
+ * @param {string} passphrase - Passphrase
81
+ * @returns {Buffer} Encrypted buffer
82
+ */
83
+ function encryptBuffer(buffer, passphrase) {
84
+ const salt = crypto.randomBytes(SALT_LENGTH);
85
+ const key = deriveKey(passphrase, salt);
86
+ const iv = crypto.randomBytes(IV_LENGTH);
87
+
88
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
89
+ const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
90
+ const authTag = cipher.getAuthTag();
91
+
92
+ return Buffer.concat([salt, iv, authTag, encrypted]);
93
+ }
94
+
95
+ /**
96
+ * Decrypt a Buffer encrypted with encryptBuffer().
97
+ *
98
+ * @param {Buffer} encrypted - Buffer produced by encryptBuffer()
99
+ * @param {string} passphrase - Same passphrase used for encryption
100
+ * @returns {Buffer} Decrypted buffer
101
+ * @throws {Error} If passphrase is wrong or data is tampered
102
+ */
103
+ function decryptBuffer(encrypted, passphrase) {
104
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
105
+ throw new Error('Invalid encrypted data: too short');
106
+ }
107
+
108
+ const salt = encrypted.subarray(0, SALT_LENGTH);
109
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
110
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
111
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
112
+
113
+ const key = deriveKey(passphrase, salt);
114
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
115
+ decipher.setAuthTag(authTag);
116
+
117
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
118
+ }
119
+
120
+ module.exports = {
121
+ deriveKey,
122
+ encrypt,
123
+ decrypt,
124
+ encryptBuffer,
125
+ decryptBuffer,
126
+ PBKDF2_ITERATIONS,
127
+ SALT_LENGTH,
128
+ IV_LENGTH,
129
+ AUTH_TAG_LENGTH,
130
+ };