brain-memory 0.1.0-beta.2 → 0.1.0-beta.4

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,217 @@
1
+ /**
2
+ * Brain Memory — Crypto Utilities
3
+ *
4
+ * AES-256-GCM encryption for sync credentials and file content.
5
+ * Zero external dependencies — uses only Node.js built-in crypto.
6
+ */
7
+
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
+
17
+ const PBKDF2_ITERATIONS = 100000;
18
+ const PBKDF2_DIGEST = 'sha512';
19
+ const KEY_LENGTH = 32; // 256 bits
20
+ const IV_LENGTH = 12; // 96 bits for GCM
21
+ const SALT_LENGTH = 32;
22
+ const AUTH_TAG_LENGTH = 16;
23
+
24
+ /**
25
+ * Derive an AES-256 key from a passphrase using PBKDF2.
26
+ *
27
+ * @param {string} passphrase - User-provided passphrase
28
+ * @param {Buffer} salt - 32-byte salt
29
+ * @returns {Buffer} 32-byte derived key
30
+ */
31
+ function deriveKey(passphrase, salt) {
32
+ return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
33
+ }
34
+
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
+ /**
47
+ * Encrypt a UTF-8 string with AES-256-GCM.
48
+ *
49
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
50
+ *
51
+ * @param {string} plaintext - UTF-8 string to encrypt
52
+ * @param {string} passphrase - Passphrase (key derived via PBKDF2)
53
+ * @returns {Buffer} Encrypted buffer
54
+ */
55
+ function encrypt(plaintext, passphrase) {
56
+ const salt = crypto.randomBytes(SALT_LENGTH);
57
+ const key = deriveKey(passphrase, salt);
58
+ const iv = crypto.randomBytes(IV_LENGTH);
59
+
60
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
61
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
62
+ const authTag = cipher.getAuthTag();
63
+
64
+ return Buffer.concat([salt, iv, authTag, encrypted]);
65
+ }
66
+
67
+ /**
68
+ * Decrypt an AES-256-GCM encrypted buffer back to a UTF-8 string.
69
+ *
70
+ * @param {Buffer} encrypted - Buffer produced by encrypt()
71
+ * @param {string} passphrase - Same passphrase used for encryption
72
+ * @returns {string} Decrypted UTF-8 string
73
+ * @throws {Error} If passphrase is wrong or data is tampered
74
+ */
75
+ function decrypt(encrypted, passphrase) {
76
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH + 1) {
77
+ throw new Error('Invalid encrypted data: too short');
78
+ }
79
+
80
+ const salt = encrypted.subarray(0, SALT_LENGTH);
81
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
82
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
83
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
84
+
85
+ const key = deriveKey(passphrase, salt);
86
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
87
+ decipher.setAuthTag(authTag);
88
+
89
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
90
+ }
91
+
92
+ /**
93
+ * Encrypt a Buffer with AES-256-GCM (for file content before upload).
94
+ *
95
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
96
+ *
97
+ * @param {Buffer} buffer - Raw file content
98
+ * @param {string} passphrase - Passphrase
99
+ * @returns {Buffer} Encrypted buffer
100
+ */
101
+ function encryptBuffer(buffer, passphrase) {
102
+ const salt = crypto.randomBytes(SALT_LENGTH);
103
+ const key = deriveKey(passphrase, salt);
104
+ const iv = crypto.randomBytes(IV_LENGTH);
105
+
106
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
107
+ const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
108
+ const authTag = cipher.getAuthTag();
109
+
110
+ return Buffer.concat([salt, iv, authTag, encrypted]);
111
+ }
112
+
113
+ /**
114
+ * Decrypt a Buffer encrypted with encryptBuffer().
115
+ *
116
+ * @param {Buffer} encrypted - Buffer produced by encryptBuffer()
117
+ * @param {string} passphrase - Same passphrase used for encryption
118
+ * @returns {Buffer} Decrypted buffer
119
+ * @throws {Error} If passphrase is wrong or data is tampered
120
+ */
121
+ function decryptBuffer(encrypted, passphrase) {
122
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
123
+ throw new Error('Invalid encrypted data: too short');
124
+ }
125
+
126
+ const salt = encrypted.subarray(0, SALT_LENGTH);
127
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
128
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
129
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
130
+
131
+ const key = deriveKey(passphrase, salt);
132
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
133
+ decipher.setAuthTag(authTag);
134
+
135
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
136
+ }
137
+
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
+ module.exports = {
202
+ deriveKey,
203
+ getMachineIdentifier,
204
+ encrypt,
205
+ decrypt,
206
+ encryptBuffer,
207
+ decryptBuffer,
208
+ getSyncDir,
209
+ saveCredentials,
210
+ loadCredentials,
211
+ deleteCredentials,
212
+ // Expose constants for testing
213
+ PBKDF2_ITERATIONS,
214
+ SALT_LENGTH,
215
+ IV_LENGTH,
216
+ AUTH_TAG_LENGTH,
217
+ };
@@ -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
+ };