brain-memory 0.1.0-beta.5 → 0.1.0-beta.6

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.
@@ -1,18 +1,11 @@
1
1
  /**
2
2
  * Brain Memory — Crypto Utilities
3
3
  *
4
- * AES-256-GCM encryption for sync credentials and file content.
4
+ * AES-256-GCM encryption for memory export/import and encrypted sync.
5
5
  * Zero external dependencies — uses only Node.js built-in crypto.
6
6
  */
7
7
 
8
8
  const crypto = require('crypto');
9
- const fs = require('fs');
10
- const path = require('path');
11
- const os = require('os');
12
- const { getBrainDir } = require('../index-manager');
13
-
14
- const SYNC_DIR = '.sync';
15
- const CREDENTIALS_FILE = 'credentials.enc';
16
9
 
17
10
  const PBKDF2_ITERATIONS = 100000;
18
11
  const PBKDF2_DIGEST = 'sha512';
@@ -32,17 +25,6 @@ function deriveKey(passphrase, salt) {
32
25
  return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
33
26
  }
34
27
 
35
- /**
36
- * Generate a machine-specific identifier (convenience default, not strong security).
37
- * SHA-256 of hostname + username.
38
- *
39
- * @returns {string} Hex-encoded machine identifier
40
- */
41
- function getMachineIdentifier() {
42
- const data = `${os.hostname()}:${os.userInfo().username}`;
43
- return crypto.createHash('sha256').update(data).digest('hex');
44
- }
45
-
46
28
  /**
47
29
  * Encrypt a UTF-8 string with AES-256-GCM.
48
30
  *
@@ -73,7 +55,7 @@ function encrypt(plaintext, passphrase) {
73
55
  * @throws {Error} If passphrase is wrong or data is tampered
74
56
  */
75
57
  function decrypt(encrypted, passphrase) {
76
- if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH + 1) {
58
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
77
59
  throw new Error('Invalid encrypted data: too short');
78
60
  }
79
61
 
@@ -90,11 +72,11 @@ function decrypt(encrypted, passphrase) {
90
72
  }
91
73
 
92
74
  /**
93
- * Encrypt a Buffer with AES-256-GCM (for file content before upload).
75
+ * Encrypt a Buffer with AES-256-GCM.
94
76
  *
95
77
  * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
96
78
  *
97
- * @param {Buffer} buffer - Raw file content
79
+ * @param {Buffer} buffer - Raw buffer to encrypt
98
80
  * @param {string} passphrase - Passphrase
99
81
  * @returns {Buffer} Encrypted buffer
100
82
  */
@@ -135,81 +117,12 @@ function decryptBuffer(encrypted, passphrase) {
135
117
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
136
118
  }
137
119
 
138
- /**
139
- * Get the path to the .sync directory.
140
- *
141
- * @param {string} [projectRoot] - Project root directory
142
- * @returns {string} Absolute path to .brain/.sync/
143
- */
144
- function getSyncDir(projectRoot) {
145
- return path.join(getBrainDir(projectRoot), SYNC_DIR);
146
- }
147
-
148
- /**
149
- * Save OAuth tokens encrypted to .brain/.sync/credentials.enc.
150
- * Sets file permissions to 0600 (owner read/write only).
151
- *
152
- * @param {Object} tokens - OAuth tokens to store
153
- * @param {string} [projectRoot] - Project root directory
154
- * @param {string} [passphrase] - Passphrase (defaults to machine identifier)
155
- */
156
- function saveCredentials(tokens, projectRoot, passphrase) {
157
- const syncDir = getSyncDir(projectRoot);
158
- fs.mkdirSync(syncDir, { recursive: true });
159
-
160
- const pass = passphrase || getMachineIdentifier();
161
- const encrypted = encrypt(JSON.stringify(tokens), pass);
162
- const credPath = path.join(syncDir, CREDENTIALS_FILE);
163
-
164
- fs.writeFileSync(credPath, encrypted);
165
- try {
166
- fs.chmodSync(credPath, 0o600);
167
- } catch {
168
- // chmod may not be supported on all platforms
169
- }
170
- }
171
-
172
- /**
173
- * Load and decrypt OAuth tokens from .brain/.sync/credentials.enc.
174
- *
175
- * @param {string} [projectRoot] - Project root directory
176
- * @param {string} [passphrase] - Passphrase (defaults to machine identifier)
177
- * @returns {Object|null} Decrypted tokens or null if file doesn't exist
178
- * @throws {Error} If passphrase is wrong
179
- */
180
- function loadCredentials(projectRoot, passphrase) {
181
- const credPath = path.join(getSyncDir(projectRoot), CREDENTIALS_FILE);
182
- if (!fs.existsSync(credPath)) return null;
183
-
184
- const pass = passphrase || getMachineIdentifier();
185
- const encrypted = fs.readFileSync(credPath);
186
- return JSON.parse(decrypt(encrypted, pass));
187
- }
188
-
189
- /**
190
- * Delete stored credentials.
191
- *
192
- * @param {string} [projectRoot] - Project root directory
193
- */
194
- function deleteCredentials(projectRoot) {
195
- const credPath = path.join(getSyncDir(projectRoot), CREDENTIALS_FILE);
196
- if (fs.existsSync(credPath)) {
197
- fs.unlinkSync(credPath);
198
- }
199
- }
200
-
201
120
  module.exports = {
202
121
  deriveKey,
203
- getMachineIdentifier,
204
122
  encrypt,
205
123
  decrypt,
206
124
  encryptBuffer,
207
125
  decryptBuffer,
208
- getSyncDir,
209
- saveCredentials,
210
- loadCredentials,
211
- deleteCredentials,
212
- // Expose constants for testing
213
126
  PBKDF2_ITERATIONS,
214
127
  SALT_LENGTH,
215
128
  IV_LENGTH,
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Brain Memory — Export / Import
3
+ *
4
+ * Single-file encrypted export/import for portable memory transfers.
5
+ * Pack all .brain/ files into one JSON blob, optionally AES-256-GCM encrypt,
6
+ * and write a single .brain-export file. Import reverses the process.
7
+ *
8
+ * Zero external dependencies — uses only Node.js built-in fs and crypto.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const { encrypt, decrypt } = require('./crypto');
14
+
15
+ // Directories inside .brain/ to skip during export
16
+ const EXCLUDED = new Set(['.sync', '.DS_Store']);
17
+
18
+ /**
19
+ * Export the entire .brain/ directory to a single file.
20
+ *
21
+ * @param {string} brainDir - Absolute path to .brain/
22
+ * @param {string} outputPath - Destination file path
23
+ * @param {string|null} [passphrase] - If provided, encrypt the export
24
+ * @returns {{ fileCount: number, outputPath: string }}
25
+ */
26
+ function exportBrain(brainDir, outputPath, passphrase) {
27
+ if (!fs.existsSync(brainDir)) {
28
+ throw new Error('.brain/ directory not found. Run /brain:init first.');
29
+ }
30
+
31
+ const files = {};
32
+ collectFiles(brainDir, brainDir, files);
33
+
34
+ const payload = JSON.stringify({ version: 1, exportedAt: new Date().toISOString(), files });
35
+
36
+ if (passphrase) {
37
+ const encrypted = encrypt(payload, passphrase);
38
+ fs.writeFileSync(outputPath, encrypted);
39
+ } else {
40
+ fs.writeFileSync(outputPath, payload, 'utf8');
41
+ }
42
+
43
+ return { fileCount: Object.keys(files).length, outputPath };
44
+ }
45
+
46
+ /**
47
+ * Recursively collect all files from brainDir into a flat { relativePath: content } map.
48
+ *
49
+ * @param {string} dir - Current directory to scan
50
+ * @param {string} brainDir - Root .brain/ directory
51
+ * @param {Object} files - Accumulator object
52
+ */
53
+ function collectFiles(dir, brainDir, files) {
54
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
55
+ for (const entry of entries) {
56
+ const rel = path.relative(brainDir, path.join(dir, entry.name));
57
+ const topLevel = rel.split(path.sep)[0];
58
+ if (EXCLUDED.has(topLevel)) continue;
59
+
60
+ const fullPath = path.join(dir, entry.name);
61
+ if (entry.isDirectory()) {
62
+ collectFiles(fullPath, brainDir, files);
63
+ } else {
64
+ // Normalize path separators to forward slash for portability
65
+ const key = rel.split(path.sep).join('/');
66
+ files[key] = fs.readFileSync(fullPath, 'utf8');
67
+ }
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Import memories from a .brain-export file into .brain/.
73
+ *
74
+ * @param {string} inputPath - Path to the export file
75
+ * @param {string} brainDir - Absolute path to .brain/
76
+ * @param {string|null} [passphrase] - Decryption passphrase (if the export is encrypted)
77
+ * @param {Object} [options]
78
+ * @param {string} [options.mode='overwrite'] - 'overwrite' replaces all files; 'merge' only imports newer files
79
+ * @returns {{ fileCount: number, skipped: number }}
80
+ */
81
+ function importBrain(inputPath, brainDir, passphrase, options = {}) {
82
+ const mode = options.mode || 'overwrite';
83
+
84
+ if (!fs.existsSync(inputPath)) {
85
+ throw new Error(`Export file not found: ${inputPath}`);
86
+ }
87
+
88
+ const raw = fs.readFileSync(inputPath);
89
+ let payload;
90
+
91
+ if (passphrase) {
92
+ try {
93
+ payload = JSON.parse(decrypt(raw, passphrase));
94
+ } catch (err) {
95
+ if (err.message.includes('Unsupported state') || err.message.includes('unable to authenticate') || err.message.includes('Invalid encrypted data')) {
96
+ throw new Error('Decryption failed — wrong passphrase or corrupted file.');
97
+ }
98
+ throw err;
99
+ }
100
+ } else {
101
+ try {
102
+ payload = JSON.parse(raw.toString('utf8'));
103
+ } catch {
104
+ throw new Error('Invalid export file. If the file is encrypted, provide a passphrase.');
105
+ }
106
+ }
107
+
108
+ if (!payload || !payload.files || typeof payload.files !== 'object') {
109
+ throw new Error('Invalid export format: missing files object.');
110
+ }
111
+
112
+ fs.mkdirSync(brainDir, { recursive: true });
113
+
114
+ let imported = 0;
115
+ let skipped = 0;
116
+
117
+ for (const [relPath, content] of Object.entries(payload.files)) {
118
+ // Convert forward-slash paths to OS-native
119
+ const nativePath = relPath.split('/').join(path.sep);
120
+ const destPath = path.join(brainDir, nativePath);
121
+
122
+ if (mode === 'merge' && fs.existsSync(destPath)) {
123
+ // In merge mode, only import if the export's file is newer
124
+ // We compare exportedAt vs local file mtime
125
+ const localMtime = fs.statSync(destPath).mtime;
126
+ const exportDate = new Date(payload.exportedAt);
127
+ if (exportDate <= localMtime) {
128
+ skipped++;
129
+ continue;
130
+ }
131
+ }
132
+
133
+ fs.mkdirSync(path.dirname(destPath), { recursive: true });
134
+ fs.writeFileSync(destPath, content, 'utf8');
135
+ imported++;
136
+ }
137
+
138
+ return { fileCount: imported, skipped };
139
+ }
140
+
141
+ /**
142
+ * Preview what an import would do without writing any files.
143
+ *
144
+ * @param {string} inputPath - Path to the export file
145
+ * @param {string} brainDir - Absolute path to .brain/
146
+ * @param {string|null} [passphrase] - Decryption passphrase
147
+ * @returns {{ totalFiles: number, newFiles: string[], existingFiles: string[], exportedAt: string }}
148
+ */
149
+ function previewImport(inputPath, brainDir, passphrase) {
150
+ const raw = fs.readFileSync(inputPath);
151
+ let payload;
152
+
153
+ if (passphrase) {
154
+ payload = JSON.parse(decrypt(raw, passphrase));
155
+ } else {
156
+ payload = JSON.parse(raw.toString('utf8'));
157
+ }
158
+
159
+ const files = Object.keys(payload.files);
160
+ const newFiles = [];
161
+ const existingFiles = [];
162
+
163
+ for (const relPath of files) {
164
+ const nativePath = relPath.split('/').join(path.sep);
165
+ const destPath = path.join(brainDir, nativePath);
166
+ if (fs.existsSync(destPath)) {
167
+ existingFiles.push(relPath);
168
+ } else {
169
+ newFiles.push(relPath);
170
+ }
171
+ }
172
+
173
+ return {
174
+ totalFiles: files.length,
175
+ newFiles,
176
+ existingFiles,
177
+ exportedAt: payload.exportedAt,
178
+ };
179
+ }
180
+
181
+ module.exports = {
182
+ exportBrain,
183
+ importBrain,
184
+ previewImport,
185
+ };