Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | /** * Secure Workspace Session Storage * * Manages workspace-scoped session tokens using the same secure storage * hierarchy as the existing credentials system: * 1. OS Keychain (via keytar) - workspace-scoped keys * 2. Encrypted file fallback (AES-256-GCM) * * Registry (~/.snapback/workspaces.json) stores non-sensitive metadata. * Sensitive tokens are stored in OS keychain or encrypted file. * * @module workspace-storage */ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises"; import { homedir, hostname, platform, userInfo } from "node:os"; import { dirname, join } from "node:path"; import { type AuthMethod, createEmptyRegistry, generateWorkspaceId, type SessionTokens, SessionTokensSchema, validateRegistry, type WorkspaceSessionEntry, type WorkspaceSessionRegistry, } from "./workspace-session"; // ============================================================================= // CONSTANTS // ============================================================================= /** * Get the global SnapBack directory path with null safety validation * @throws Error if home directory cannot be determined */ function getGlobalDir(): string { const home = homedir(); if (!home || typeof home !== "string") { throw new Error("Unable to determine home directory. Please ensure HOME environment variable is set."); } return join(home, ".snapback"); } const GLOBAL_DIR = getGlobalDir(); const REGISTRY_FILE = join(GLOBAL_DIR, "workspaces.json"); const SERVICE_NAME = "snapback-cli-workspace"; // ============================================================================= // REGISTRY FILE OPERATIONS // ============================================================================= /** * Read workspace session registry from disk */ export async function readRegistry(): Promise<WorkspaceSessionRegistry> { try { const content = await readFile(REGISTRY_FILE, "utf-8"); const data = JSON.parse(content); const validated = validateRegistry(data); return validated || createEmptyRegistry(); } catch { return createEmptyRegistry(); } } /** * Write workspace session registry to disk */ export async function writeRegistry(registry: WorkspaceSessionRegistry): Promise<void> { await mkdir(dirname(REGISTRY_FILE), { recursive: true }); await writeFile(REGISTRY_FILE, JSON.stringify(registry, null, 2), { mode: 0o600 }); } /** * Delete workspace session registry */ export async function deleteRegistry(): Promise<void> { try { await unlink(REGISTRY_FILE); } catch { // Ignore if doesn't exist } } // ============================================================================= // KEYCHAIN INTERFACE (Workspace-Scoped) // ============================================================================= interface KeychainProvider { name: string; isAvailable(): Promise<boolean>; getPassword(service: string, account: string): Promise<string | null>; setPassword(service: string, account: string, password: string): Promise<void>; deletePassword(service: string, account: string): Promise<boolean>; } /** * Create keytar provider for workspace tokens */ async function createKeytarProvider(): Promise<KeychainProvider | null> { try { const keytar = await import("keytar"); return { name: "keytar", async isAvailable(): Promise<boolean> { try { await keytar.getPassword("__snapback_test__", "__test__"); return true; } catch { return false; } }, async getPassword(service: string, account: string): Promise<string | null> { return keytar.getPassword(service, account); }, async setPassword(service: string, account: string, password: string): Promise<void> { await keytar.setPassword(service, account, password); }, async deletePassword(service: string, account: string): Promise<boolean> { return keytar.deletePassword(service, account); }, }; } catch { return null; } } // ============================================================================= // ENCRYPTED FILE STORAGE (Fallback) // ============================================================================= import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto"; const ENCRYPTION_ALGORITHM = "aes-256-gcm"; const KEY_LENGTH = 32; const IV_LENGTH = 12; const AUTH_TAG_LENGTH = 16; const SALT_LENGTH = 32; function deriveMachineKey(salt: Buffer): Buffer { const machineData = [hostname(), platform(), userInfo().username, homedir(), process.arch, process.platform].join( "|", ); return scryptSync(machineData, salt, KEY_LENGTH); } function encryptData(data: string, salt: Buffer): Buffer { const key = deriveMachineKey(salt); const iv = randomBytes(IV_LENGTH); const cipher = createCipheriv(ENCRYPTION_ALGORITHM, key, iv); const encrypted = Buffer.concat([cipher.update(data, "utf8"), cipher.final()]); const authTag = cipher.getAuthTag(); return Buffer.concat([salt, iv, authTag, encrypted]); } function decryptData(data: Buffer): string { const salt = data.subarray(0, SALT_LENGTH); const iv = data.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH); const authTag = data.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH); const encrypted = data.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH); const key = deriveMachineKey(salt); const decipher = createDecipheriv(ENCRYPTION_ALGORITHM, key, iv); decipher.setAuthTag(authTag); const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]); return decrypted.toString("utf8"); } const ENCRYPTED_TOKENS_FILE = join(GLOBAL_DIR, "workspace-tokens.enc"); interface EncryptedTokenStore { [workspaceId: string]: SessionTokens; } async function readEncryptedTokens(): Promise<EncryptedTokenStore> { try { const data = await readFile(ENCRYPTED_TOKENS_FILE); const decrypted = decryptData(data); return JSON.parse(decrypted) as EncryptedTokenStore; } catch { return {}; } } async function writeEncryptedTokens(tokens: EncryptedTokenStore): Promise<void> { const salt = randomBytes(SALT_LENGTH); const encrypted = encryptData(JSON.stringify(tokens), salt); await mkdir(dirname(ENCRYPTED_TOKENS_FILE), { recursive: true }); await writeFile(ENCRYPTED_TOKENS_FILE, encrypted, { mode: 0o600 }); } // ============================================================================= // SECURE TOKEN STORAGE // ============================================================================= class SecureTokenStorage { private provider: KeychainProvider | null = null; private initialized = false; async initialize(): Promise<void> { if (this.initialized) return; const keytarProvider = await createKeytarProvider(); if (keytarProvider && (await keytarProvider.isAvailable())) { this.provider = keytarProvider; } this.initialized = true; } private getAccountName(workspaceId: string): string { return `tokens_${workspaceId}`; } async getTokens(workspaceId: string): Promise<SessionTokens | null> { await this.initialize(); if (this.provider) { const stored = await this.provider.getPassword(SERVICE_NAME, this.getAccountName(workspaceId)); if (stored) { try { const parsed = JSON.parse(stored); const validated = SessionTokensSchema.safeParse(parsed); if (validated.success) return validated.data; } catch { // Invalid format, fall through } } } // Fallback to encrypted file const tokens = await readEncryptedTokens(); return tokens[workspaceId] || null; } async setTokens(workspaceId: string, tokens: SessionTokens): Promise<void> { await this.initialize(); if (this.provider) { await this.provider.setPassword(SERVICE_NAME, this.getAccountName(workspaceId), JSON.stringify(tokens)); return; } // Fallback to encrypted file const allTokens = await readEncryptedTokens(); allTokens[workspaceId] = tokens; await writeEncryptedTokens(allTokens); } async deleteTokens(workspaceId: string): Promise<void> { await this.initialize(); if (this.provider) { await this.provider.deletePassword(SERVICE_NAME, this.getAccountName(workspaceId)); } // Also clean up from encrypted file const allTokens = await readEncryptedTokens(); delete allTokens[workspaceId]; await writeEncryptedTokens(allTokens); } async clearAllTokens(): Promise<void> { await this.initialize(); // Get all workspace IDs from registry const registry = await readRegistry(); const workspaceIds = Object.keys(registry.workspaces); // Delete from keychain if (this.provider) { for (const workspaceId of workspaceIds) { await this.provider.deletePassword(SERVICE_NAME, this.getAccountName(workspaceId)); } } // Delete encrypted file try { await unlink(ENCRYPTED_TOKENS_FILE); } catch { // Ignore } } } // Singleton instance let secureTokenStorage: SecureTokenStorage | null = null; function getSecureTokenStorage(): SecureTokenStorage { if (!secureTokenStorage) { secureTokenStorage = new SecureTokenStorage(); } return secureTokenStorage; } // ============================================================================= // HIGH-LEVEL WORKSPACE STORAGE API // ============================================================================= /** * Store workspace session (metadata in registry, tokens in secure storage) */ export async function storeWorkspaceSession( workspacePath: string, entry: Omit<WorkspaceSessionEntry, "workspaceId">, ): Promise<void> { const workspaceId = generateWorkspaceId(workspacePath); const registry = await readRegistry(); // Store metadata in registry (non-sensitive) registry.workspaces[workspaceId] = { ...entry, workspaceId, workspacePath, }; // Store tokens in secure storage await getSecureTokenStorage().setTokens(workspaceId, entry.session); // Save registry await writeRegistry(registry); } /** * Get workspace session (combines registry metadata with secure tokens) */ export async function getWorkspaceSession(workspacePath: string): Promise<WorkspaceSessionEntry | null> { const workspaceId = generateWorkspaceId(workspacePath); const registry = await readRegistry(); const metadata = registry.workspaces[workspaceId]; if (!metadata) return null; // Get tokens from secure storage const tokens = await getSecureTokenStorage().getTokens(workspaceId); if (!tokens) return null; return { ...metadata, session: tokens, }; } /** * Update workspace session tokens (e.g., after refresh) */ export async function updateWorkspaceSessionTokens(workspacePath: string, tokens: SessionTokens): Promise<void> { const workspaceId = generateWorkspaceId(workspacePath); const registry = await readRegistry(); const metadata = registry.workspaces[workspaceId]; if (!metadata) { throw new Error(`Workspace session not found: ${workspacePath}`); } // Update tokens in secure storage await getSecureTokenStorage().setTokens(workspaceId, tokens); // Update metadata metadata.updatedAt = new Date().toISOString(); metadata.session = tokens; // Also update in registry for expiry tracking await writeRegistry(registry); } /** * Update last used timestamp */ export async function touchWorkspaceSession(workspacePath: string): Promise<void> { const workspaceId = generateWorkspaceId(workspacePath); const registry = await readRegistry(); const metadata = registry.workspaces[workspaceId]; if (metadata) { metadata.lastUsedAt = new Date().toISOString(); await writeRegistry(registry); } } /** * Delete workspace session */ export async function deleteWorkspaceSession(workspacePath: string): Promise<void> { const workspaceId = generateWorkspaceId(workspacePath); const registry = await readRegistry(); delete registry.workspaces[workspaceId]; await writeRegistry(registry); await getSecureTokenStorage().deleteTokens(workspaceId); } /** * List all workspace sessions (without tokens, but with expiresAt) */ export async function listWorkspaceSessions(): Promise< (Omit<WorkspaceSessionEntry, "session"> & { expiresAt: string })[] > { const registry = await readRegistry(); return Object.values(registry.workspaces).map(({ session, ...metadata }) => ({ ...metadata, expiresAt: session.expiresAt, })); } /** * Store global fallback credentials */ export async function storeGlobalFallback(entry: { session: SessionTokens; user: { id: string; email: string; tier: "free" | "pro" | "team" | "enterprise" }; authMethod: AuthMethod; apiKey?: string; }): Promise<void> { const registry = await readRegistry(); registry.global = entry; await writeRegistry(registry); } /** * Get global fallback credentials */ export async function getGlobalFallback(): Promise<WorkspaceSessionRegistry["global"] | null> { const registry = await readRegistry(); return registry.global || null; } /** * Clear global fallback */ export async function clearGlobalFallback(): Promise<void> { const registry = await readRegistry(); delete registry.global; await writeRegistry(registry); } /** * Clear all workspace sessions */ export async function clearAllWorkspaceSessions(): Promise<void> { await getSecureTokenStorage().clearAllTokens(); await deleteRegistry(); } /** * Cleanup expired sessions */ export async function cleanupExpiredSessions(): Promise<number> { const registry = await readRegistry(); const now = new Date(); let cleaned = 0; for (const [workspaceId, entry] of Object.entries(registry.workspaces)) { const expiresAt = new Date(entry.session.expiresAt); if (expiresAt < now) { delete registry.workspaces[workspaceId]; await getSecureTokenStorage().deleteTokens(workspaceId); cleaned++; } } registry.lastCleanupAt = now.toISOString(); await writeRegistry(registry); return cleaned; } |