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

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.
@@ -0,0 +1,430 @@
1
+ /**
2
+ * Brain Memory — OAuth2 Authentication
3
+ *
4
+ * PKCE authorization code flow + Device Code Flow fallback.
5
+ * Zero external dependencies — uses only Node.js built-in http, crypto, fetch.
6
+ */
7
+
8
+ const crypto = require('crypto');
9
+ const http = require('http');
10
+ const { execSync } = require('child_process');
11
+ const { saveCredentials } = require('./crypto-utils');
12
+
13
+ /**
14
+ * Provider-specific OAuth configurations.
15
+ * Users must register their own OAuth app with each provider
16
+ * and supply their client ID via .brain/.sync/config.json.
17
+ */
18
+ const OAUTH_CONFIGS = {
19
+ dropbox: {
20
+ authUrl: 'https://www.dropbox.com/oauth2/authorize',
21
+ tokenUrl: 'https://api.dropboxapi.com/oauth2/token',
22
+ revokeUrl: 'https://api.dropboxapi.com/2/auth/token/revoke',
23
+ scopes: [],
24
+ extraAuthParams: { token_access_type: 'offline' },
25
+ supportsDeviceCode: false,
26
+ supportsPKCE: true,
27
+ },
28
+ 'google-drive': {
29
+ authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
30
+ tokenUrl: 'https://oauth2.googleapis.com/token',
31
+ revokeUrl: 'https://oauth2.googleapis.com/revoke',
32
+ scopes: ['https://www.googleapis.com/auth/drive.appdata'],
33
+ extraAuthParams: { access_type: 'offline', prompt: 'consent' },
34
+ supportsDeviceCode: true,
35
+ deviceAuthUrl: 'https://oauth2.googleapis.com/device/code',
36
+ supportsPKCE: true,
37
+ },
38
+ onedrive: {
39
+ authUrl: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize',
40
+ tokenUrl: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token',
41
+ revokeUrl: null, // OneDrive doesn't have a standard revoke endpoint
42
+ scopes: ['Files.ReadWrite.AppFolder', 'offline_access'],
43
+ extraAuthParams: {},
44
+ supportsDeviceCode: true,
45
+ deviceAuthUrl: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode',
46
+ supportsPKCE: true,
47
+ },
48
+ };
49
+
50
+ /**
51
+ * Generate a cryptographically random code verifier for PKCE.
52
+ * 64 random bytes → base64url → 86 characters.
53
+ *
54
+ * @returns {string} Code verifier (86 chars, base64url)
55
+ */
56
+ function generateCodeVerifier() {
57
+ return crypto.randomBytes(64).toString('base64url');
58
+ }
59
+
60
+ /**
61
+ * Generate a code challenge from a verifier (S256 method).
62
+ * SHA-256 of verifier → base64url.
63
+ *
64
+ * @param {string} verifier - Code verifier string
65
+ * @returns {string} Code challenge (base64url-encoded SHA-256)
66
+ */
67
+ function generateCodeChallenge(verifier) {
68
+ return crypto.createHash('sha256').update(verifier).digest('base64url');
69
+ }
70
+
71
+ /**
72
+ * Start a temporary loopback HTTP server to receive the OAuth callback.
73
+ * Listens on 127.0.0.1 with an OS-assigned port. Returns an HTML success
74
+ * page to the browser on callback, then shuts down.
75
+ *
76
+ * @param {Function} onCode - Callback receiving (code, error) from the redirect
77
+ * @returns {Promise<{server: http.Server, port: number, close: Function}>}
78
+ */
79
+ function startLoopbackServer(onCode) {
80
+ return new Promise((resolve, reject) => {
81
+ const server = http.createServer((req, res) => {
82
+ const url = new URL(req.url, `http://127.0.0.1`);
83
+ const code = url.searchParams.get('code');
84
+ const error = url.searchParams.get('error');
85
+
86
+ res.writeHead(200, { 'Content-Type': 'text/html' });
87
+ if (code) {
88
+ res.end(`<html><body><h2>Authorization successful!</h2>
89
+ <p>You can close this tab and return to your terminal.</p></body></html>`);
90
+ onCode(code, null);
91
+ } else {
92
+ const errMsg = error || 'No authorization code received';
93
+ res.end(`<html><body><h2>Authorization failed</h2>
94
+ <p>${errMsg}</p></body></html>`);
95
+ onCode(null, new Error(errMsg));
96
+ }
97
+
98
+ // Shut down after response
99
+ setTimeout(() => server.close(), 500);
100
+ });
101
+
102
+ server.listen(0, '127.0.0.1', () => {
103
+ const { port } = server.address();
104
+
105
+ // Auto-timeout after 5 minutes
106
+ const timeout = setTimeout(() => {
107
+ server.close();
108
+ onCode(null, new Error('Authorization timed out (300s)'));
109
+ }, 300000);
110
+
111
+ const close = () => {
112
+ clearTimeout(timeout);
113
+ server.close();
114
+ };
115
+
116
+ resolve({ server, port, close });
117
+ });
118
+
119
+ server.on('error', reject);
120
+ });
121
+ }
122
+
123
+ /**
124
+ * Open a URL in the user's default browser.
125
+ * Platform-specific: open (macOS), xdg-open (Linux), start (Windows).
126
+ *
127
+ * @param {string} url - URL to open
128
+ */
129
+ function openBrowser(url) {
130
+ const platform = process.platform;
131
+ try {
132
+ if (platform === 'darwin') {
133
+ execSync(`open "${url}"`);
134
+ } else if (platform === 'win32') {
135
+ execSync(`start "" "${url}"`);
136
+ } else {
137
+ execSync(`xdg-open "${url}"`);
138
+ }
139
+ } catch {
140
+ // If exec fails, the user will need to open manually
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Exchange an authorization code for tokens via POST to the token endpoint.
146
+ *
147
+ * @param {string} tokenUrl - Provider's token endpoint
148
+ * @param {Object} params - Key-value pairs for the POST body
149
+ * @returns {Promise<Object>} Token response
150
+ * @throws {Error} If the exchange fails
151
+ */
152
+ async function exchangeCodeForTokens(tokenUrl, params) {
153
+ const body = new URLSearchParams(params).toString();
154
+
155
+ const response = await fetch(tokenUrl, {
156
+ method: 'POST',
157
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
158
+ body,
159
+ });
160
+
161
+ if (!response.ok) {
162
+ const text = await response.text();
163
+ throw new Error(`Token exchange failed (${response.status}): ${text}`);
164
+ }
165
+
166
+ return response.json();
167
+ }
168
+
169
+ /**
170
+ * Refresh an access token using a refresh token.
171
+ *
172
+ * @param {string} tokenUrl - Provider's token endpoint
173
+ * @param {string} clientId - OAuth client ID
174
+ * @param {string} refreshToken - Refresh token
175
+ * @returns {Promise<Object>} New token response
176
+ * @throws {Error} If refresh fails
177
+ */
178
+ async function refreshAccessToken(tokenUrl, clientId, refreshToken) {
179
+ return exchangeCodeForTokens(tokenUrl, {
180
+ grant_type: 'refresh_token',
181
+ client_id: clientId,
182
+ refresh_token: refreshToken,
183
+ });
184
+ }
185
+
186
+ /**
187
+ * Full PKCE authorization flow:
188
+ * 1. Generate code verifier + challenge
189
+ * 2. Start loopback server
190
+ * 3. Open browser with auth URL
191
+ * 4. Wait for callback with auth code
192
+ * 5. Exchange code for tokens
193
+ *
194
+ * @param {Object} config
195
+ * @param {string} config.provider - Provider name (dropbox, google-drive, onedrive)
196
+ * @param {string} config.clientId - OAuth client ID
197
+ * @returns {Promise<Object>} OAuth tokens
198
+ */
199
+ async function authorizeWithPKCE(config) {
200
+ const { provider, clientId } = config;
201
+ const oauthConfig = OAUTH_CONFIGS[provider];
202
+ if (!oauthConfig) throw new Error(`Unknown provider: ${provider}`);
203
+
204
+ const verifier = generateCodeVerifier();
205
+ const challenge = generateCodeChallenge(verifier);
206
+
207
+ // Wait for the auth code via loopback
208
+ let resolveCode, rejectCode;
209
+ const codePromise = new Promise((resolve, reject) => {
210
+ resolveCode = resolve;
211
+ rejectCode = reject;
212
+ });
213
+
214
+ const { port, close } = await startLoopbackServer((code, error) => {
215
+ if (error) rejectCode(error);
216
+ else resolveCode(code);
217
+ });
218
+
219
+ const redirectUri = `http://127.0.0.1:${port}`;
220
+
221
+ // Build auth URL
222
+ const authParams = new URLSearchParams({
223
+ client_id: clientId,
224
+ response_type: 'code',
225
+ redirect_uri: redirectUri,
226
+ code_challenge: challenge,
227
+ code_challenge_method: 'S256',
228
+ ...oauthConfig.extraAuthParams,
229
+ });
230
+
231
+ if (oauthConfig.scopes.length > 0) {
232
+ authParams.set('scope', oauthConfig.scopes.join(' '));
233
+ }
234
+
235
+ const authUrl = `${oauthConfig.authUrl}?${authParams.toString()}`;
236
+
237
+ openBrowser(authUrl);
238
+
239
+ try {
240
+ const code = await codePromise;
241
+
242
+ // Exchange code for tokens
243
+ const tokens = await exchangeCodeForTokens(oauthConfig.tokenUrl, {
244
+ grant_type: 'authorization_code',
245
+ client_id: clientId,
246
+ code,
247
+ redirect_uri: redirectUri,
248
+ code_verifier: verifier,
249
+ });
250
+
251
+ // Add metadata
252
+ tokens.obtained_at = Date.now();
253
+ if (tokens.expires_in) {
254
+ tokens.expires_at = Date.now() + tokens.expires_in * 1000;
255
+ }
256
+
257
+ return tokens;
258
+ } finally {
259
+ close();
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Device Code Flow authorization (fallback for headless/SSH).
265
+ * Polls the token endpoint until the user authorizes in their browser.
266
+ *
267
+ * @param {Object} config
268
+ * @param {string} config.provider - Provider name
269
+ * @param {string} config.clientId - OAuth client ID
270
+ * @param {Function} [config.onUserCode] - Callback to display the user code and verification URI
271
+ * @returns {Promise<Object>} OAuth tokens
272
+ */
273
+ async function authorizeWithDeviceCode(config) {
274
+ const { provider, clientId, onUserCode } = config;
275
+ const oauthConfig = OAUTH_CONFIGS[provider];
276
+ if (!oauthConfig) throw new Error(`Unknown provider: ${provider}`);
277
+ if (!oauthConfig.supportsDeviceCode) {
278
+ throw new Error(`${provider} does not support Device Code Flow`);
279
+ }
280
+
281
+ // Request device code
282
+ const deviceParams = new URLSearchParams({ client_id: clientId });
283
+ if (oauthConfig.scopes.length > 0) {
284
+ deviceParams.set('scope', oauthConfig.scopes.join(' '));
285
+ }
286
+
287
+ const deviceResponse = await fetch(oauthConfig.deviceAuthUrl, {
288
+ method: 'POST',
289
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
290
+ body: deviceParams.toString(),
291
+ });
292
+
293
+ if (!deviceResponse.ok) {
294
+ const text = await deviceResponse.text();
295
+ throw new Error(`Device code request failed (${deviceResponse.status}): ${text}`);
296
+ }
297
+
298
+ const deviceData = await deviceResponse.json();
299
+ const {
300
+ device_code: deviceCode,
301
+ user_code: userCode,
302
+ verification_uri: verificationUri,
303
+ verification_url, // Google uses this field name
304
+ interval = 5,
305
+ expires_in: expiresIn = 900,
306
+ } = deviceData;
307
+
308
+ const verifyUrl = verificationUri || verification_url;
309
+
310
+ // Notify the user
311
+ if (onUserCode) {
312
+ onUserCode({ userCode, verifyUrl, expiresIn });
313
+ }
314
+
315
+ // Poll for authorization
316
+ const pollInterval = Math.max(interval, 5) * 1000;
317
+ const deadline = Date.now() + expiresIn * 1000;
318
+
319
+ while (Date.now() < deadline) {
320
+ await new Promise((r) => setTimeout(r, pollInterval));
321
+
322
+ const tokenResponse = await fetch(oauthConfig.tokenUrl, {
323
+ method: 'POST',
324
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
325
+ body: new URLSearchParams({
326
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
327
+ client_id: clientId,
328
+ device_code: deviceCode,
329
+ }).toString(),
330
+ });
331
+
332
+ if (tokenResponse.ok) {
333
+ const tokens = await tokenResponse.json();
334
+ tokens.obtained_at = Date.now();
335
+ if (tokens.expires_in) {
336
+ tokens.expires_at = Date.now() + tokens.expires_in * 1000;
337
+ }
338
+ return tokens;
339
+ }
340
+
341
+ const errorData = await tokenResponse.json().catch(() => ({}));
342
+ const errorCode = errorData.error;
343
+
344
+ if (errorCode === 'authorization_pending' || errorCode === 'slow_down') {
345
+ // Keep polling
346
+ continue;
347
+ }
348
+
349
+ // Any other error is terminal
350
+ throw new Error(`Device authorization failed: ${errorCode || tokenResponse.status}`);
351
+ }
352
+
353
+ throw new Error('Device authorization timed out');
354
+ }
355
+
356
+ /**
357
+ * Check if stored tokens are expired (with 5-minute buffer).
358
+ *
359
+ * @param {Object} tokens - Token object with expires_at or expires_in + obtained_at
360
+ * @returns {boolean} True if tokens are expired or about to expire
361
+ */
362
+ function isTokenExpired(tokens) {
363
+ if (!tokens) return true;
364
+
365
+ const bufferMs = 5 * 60 * 1000; // 5 minutes
366
+
367
+ if (tokens.expires_at) {
368
+ return Date.now() >= tokens.expires_at - bufferMs;
369
+ }
370
+
371
+ if (tokens.expires_in && tokens.obtained_at) {
372
+ const expiresAt = tokens.obtained_at + tokens.expires_in * 1000;
373
+ return Date.now() >= expiresAt - bufferMs;
374
+ }
375
+
376
+ // If no expiry info, assume not expired (some providers like Dropbox
377
+ // issue non-expiring access tokens with offline access)
378
+ return false;
379
+ }
380
+
381
+ /**
382
+ * Ensure tokens are fresh. If expired, refresh and persist.
383
+ *
384
+ * @param {Object} tokens - Current tokens
385
+ * @param {string} provider - Provider name
386
+ * @param {string} clientId - OAuth client ID
387
+ * @param {string} [projectRoot] - Project root for credential storage
388
+ * @param {string} [passphrase] - Passphrase for credential encryption
389
+ * @returns {Promise<Object>} Fresh tokens
390
+ * @throws {Error} If refresh fails and no refresh_token available
391
+ */
392
+ async function ensureFreshTokens(tokens, provider, clientId, projectRoot, passphrase) {
393
+ if (!isTokenExpired(tokens)) return tokens;
394
+
395
+ if (!tokens.refresh_token) {
396
+ throw new Error('Access token expired and no refresh token available. Please re-authorize.');
397
+ }
398
+
399
+ const oauthConfig = OAUTH_CONFIGS[provider];
400
+ const newTokens = await refreshAccessToken(oauthConfig.tokenUrl, clientId, tokens.refresh_token);
401
+
402
+ // Preserve refresh token if not returned in refresh response
403
+ if (!newTokens.refresh_token) {
404
+ newTokens.refresh_token = tokens.refresh_token;
405
+ }
406
+
407
+ newTokens.obtained_at = Date.now();
408
+ if (newTokens.expires_in) {
409
+ newTokens.expires_at = Date.now() + newTokens.expires_in * 1000;
410
+ }
411
+
412
+ // Persist refreshed tokens
413
+ saveCredentials(newTokens, projectRoot, passphrase);
414
+
415
+ return newTokens;
416
+ }
417
+
418
+ module.exports = {
419
+ OAUTH_CONFIGS,
420
+ generateCodeVerifier,
421
+ generateCodeChallenge,
422
+ startLoopbackServer,
423
+ openBrowser,
424
+ exchangeCodeForTokens,
425
+ refreshAccessToken,
426
+ authorizeWithPKCE,
427
+ authorizeWithDeviceCode,
428
+ isTokenExpired,
429
+ ensureFreshTokens,
430
+ };
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Brain Memory — Sync Provider Base Class & Factory
3
+ *
4
+ * Unified interface for cloud storage providers.
5
+ * All paths are relative to the brain root (e.g. 'index.json', 'professional/skills/ts.md').
6
+ */
7
+
8
+ /**
9
+ * Abstract base class for sync providers.
10
+ * Each provider translates relative brain paths to its own addressing model.
11
+ */
12
+ class SyncProvider {
13
+ /**
14
+ * @param {Object} config
15
+ * @param {string} config.accessToken - OAuth access token
16
+ * @param {Object} [config.options] - Provider-specific options
17
+ */
18
+ constructor(config) {
19
+ if (new.target === SyncProvider) {
20
+ throw new Error('SyncProvider is abstract and cannot be instantiated directly');
21
+ }
22
+ this.accessToken = config.accessToken;
23
+ this.options = config.options || {};
24
+ }
25
+
26
+ /**
27
+ * List all files in the remote brain folder.
28
+ *
29
+ * @param {string|null} cursor - Pagination/delta cursor from previous call, or null for full listing
30
+ * @returns {Promise<{files: Array<{path: string, rev: string, hash: string, modified: string, size: number}>, cursor: string, hasMore: boolean}>}
31
+ */
32
+ async listFiles(_cursor) {
33
+ throw new Error('listFiles() not implemented');
34
+ }
35
+
36
+ /**
37
+ * Download a single file.
38
+ *
39
+ * @param {string} remotePath - Relative path (e.g. 'index.json')
40
+ * @returns {Promise<{content: Buffer, rev: string, hash: string}>}
41
+ */
42
+ async downloadFile(_remotePath) {
43
+ throw new Error('downloadFile() not implemented');
44
+ }
45
+
46
+ /**
47
+ * Upload a single file. Uses rev for optimistic concurrency (409 = conflict).
48
+ *
49
+ * @param {string} remotePath - Relative path
50
+ * @param {Buffer} content - File content
51
+ * @param {Object} [options]
52
+ * @param {string} [options.rev] - Expected revision for conditional write
53
+ * @param {string} [options.mode] - 'add' for new files, 'update' for existing
54
+ * @returns {Promise<{rev: string, hash: string}>}
55
+ */
56
+ async uploadFile(_remotePath, _content, _options) {
57
+ throw new Error('uploadFile() not implemented');
58
+ }
59
+
60
+ /**
61
+ * Delete a single file.
62
+ *
63
+ * @param {string} remotePath - Relative path
64
+ * @returns {Promise<{success: boolean}>}
65
+ */
66
+ async deleteFile(_remotePath) {
67
+ throw new Error('deleteFile() not implemented');
68
+ }
69
+
70
+ /**
71
+ * Get metadata for a single file.
72
+ *
73
+ * @param {string} remotePath - Relative path
74
+ * @returns {Promise<{rev: string, hash: string, modified: string, size: number}|null>}
75
+ */
76
+ async getFileMetadata(_remotePath) {
77
+ throw new Error('getFileMetadata() not implemented');
78
+ }
79
+
80
+ /**
81
+ * Create a folder (some providers require explicit creation).
82
+ *
83
+ * @param {string} remotePath - Relative folder path
84
+ * @returns {Promise<void>}
85
+ */
86
+ async createFolder(_remotePath) {
87
+ // Default no-op — providers that need explicit folder creation override this
88
+ }
89
+
90
+ /**
91
+ * Test the connection and return account info.
92
+ *
93
+ * @returns {Promise<{ok: boolean, account: string}>}
94
+ */
95
+ async testConnection() {
96
+ throw new Error('testConnection() not implemented');
97
+ }
98
+
99
+ /**
100
+ * Refresh auth tokens if needed. Called before operations.
101
+ */
102
+ async refreshAuth() {
103
+ // Default no-op — subclasses override if needed
104
+ }
105
+
106
+ /**
107
+ * Compute a provider-specific content hash for a buffer.
108
+ * Used to compare local and remote file content.
109
+ *
110
+ * @param {Buffer} buffer - File content
111
+ * @returns {string} Hash string
112
+ */
113
+ computeContentHash(_buffer) {
114
+ throw new Error('computeContentHash() not implemented');
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Factory function to create a provider instance.
120
+ *
121
+ * @param {string} name - Provider name: 'dropbox', 'google-drive', 'onedrive'
122
+ * @param {Object} config - Provider configuration (accessToken, options)
123
+ * @returns {SyncProvider} Provider instance
124
+ */
125
+ function createProvider(name, config) {
126
+ switch (name) {
127
+ case 'dropbox': {
128
+ const { DropboxProvider } = require('./providers/dropbox');
129
+ return new DropboxProvider(config);
130
+ }
131
+ case 'google-drive': {
132
+ const { GoogleDriveProvider } = require('./providers/google-drive');
133
+ return new GoogleDriveProvider(config);
134
+ }
135
+ case 'onedrive': {
136
+ const { OneDriveProvider } = require('./providers/onedrive');
137
+ return new OneDriveProvider(config);
138
+ }
139
+ default:
140
+ throw new Error(`Unknown sync provider: ${name}`);
141
+ }
142
+ }
143
+
144
+ module.exports = { SyncProvider, createProvider };