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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 | /** * Workspace Session Manager * * High-level API for workspace-scoped session management with: * - Automatic session refresh via BetterAuth (or injected refresh function) * - Single-flight pattern for concurrent refresh prevention * - Backwards compatibility with global credentials * - Integration with existing secure storage * * @module workspace-session-manager */ import { auth } from "./auth"; import { type AuthMethod, credentialsToWorkspaceSession, getExpiresIn, isSessionExpired, type SessionTokens, WorkspaceAuthError, WorkspaceAuthErrorCode, type WorkspaceSession, type WorkspaceSessionInfo, } from "./workspace-session"; import { cleanupExpiredSessions, deleteWorkspaceSession, getGlobalFallback, getWorkspaceSession, listWorkspaceSessions, storeGlobalFallback, storeWorkspaceSession, touchWorkspaceSession, updateWorkspaceSessionTokens, } from "./workspace-storage"; // ============================================================================= // SINGLE-FLIGHT REFRESH PATTERN // ============================================================================= interface RefreshPromise { promise: Promise<SessionTokens | null>; timestamp: number; } const refreshFlights = new Map<string, RefreshPromise>(); const REFLIGHT_TIMEOUT_MS = 30000; // 30 seconds /** Clear refresh flight cache (for testing) */ export function clearRefreshFlights(): void { refreshFlights.clear(); } /** * Execute with single-flight pattern to prevent concurrent refreshes */ async function withSingleFlight<T extends SessionTokens | null>(key: string, fn: () => Promise<T>): Promise<T> { const existing = refreshFlights.get(key); // Return existing promise if still valid if (existing && Date.now() - existing.timestamp < REFLIGHT_TIMEOUT_MS) { return existing.promise as Promise<T>; } // Create new promise const promise = fn().finally(() => { // Clean up after completion setTimeout(() => { refreshFlights.delete(key); }, 100); }); refreshFlights.set(key, { promise, timestamp: Date.now(), }); return promise; } // ============================================================================= // BETTERAUTH SESSION REFRESH (DEFAULT IMPLEMENTATION) // ============================================================================= const api = auth.api as typeof auth.api & { refreshToken?: (params: { body: { refreshToken: string } }) => Promise<{ token: string; refreshToken: string; expiresIn: number; }>; }; /** * Refresh session tokens via BetterAuth * This is the default implementation used when no custom refreshFn is provided */ async function refreshWithBetterAuth(refreshToken: string): Promise<SessionTokens | null> { try { if (!api.refreshToken) { console.error("[WorkspaceSessionManager] BetterAuth refreshToken not available"); return null; } const result = await api.refreshToken({ body: { refreshToken }, }); if (!result?.token) { return null; } return { accessToken: result.token, refreshToken: result.refreshToken, expiresAt: new Date(Date.now() + result.expiresIn * 1000).toISOString(), sessionId: `sess_${Date.now()}`, }; } catch (error) { console.error("[WorkspaceSessionManager] Refresh failed:", error); return null; } } // ============================================================================= // WORKSPACE SESSION MANAGER // ============================================================================= export interface WorkspaceSessionManagerOptions { /** API URL for session refresh */ apiUrl?: string; /** Proactive refresh buffer in seconds (default: 60) */ refreshBufferSeconds?: number; /** Callback when session expires */ onSessionExpired?: (workspaceId: string) => void; /** Callback when session is refreshed */ onSessionRefreshed?: (workspaceId: string, session: WorkspaceSession) => void; /** Optional custom refresh function for dependency injection (e.g., for testing or custom auth providers) */ refreshFn?: (refreshToken: string) => Promise<SessionTokens | null>; } export class WorkspaceSessionManager { private options: WorkspaceSessionManagerOptions; constructor(options: WorkspaceSessionManagerOptions = {}) { this.options = { refreshBufferSeconds: 60, ...options, }; } // ========================================================================= // CORE SESSION OPERATIONS // ========================================================================= /** * Get valid session for workspace (auto-refresh if needed, auto-link if available) */ async getSession(workspacePath: string): Promise<WorkspaceSession | null> { // Validate workspacePath parameter if (!workspacePath || typeof workspacePath !== "string") { throw new WorkspaceAuthError( "Invalid workspace path: path must be a non-empty string", WorkspaceAuthErrorCode.INVALID_WORKSPACE, ); } // Try workspace-scoped session first const entry = await getWorkspaceSession(workspacePath); if (entry) { // Check if expired and needs refresh if (this.needsRefresh(entry.session)) { try { const refreshed = await this.refreshSession(workspacePath); if (refreshed) { return refreshed; } } catch (error) { // Refresh failed but we have the old session - still return it // The API call will fail with 401 and trigger re-auth console.warn("[WorkspaceSessionManager] Refresh failed, returning old session:", error); } } await touchWorkspaceSession(workspacePath); return { workspaceId: entry.workspaceId, workspacePath: entry.workspacePath, tokens: entry.session, user: entry.user, authMethod: entry.authMethod, isValid: !isSessionExpired(entry.session.expiresAt), expiresIn: getExpiresIn(entry.session.expiresAt), }; } // Try auto-link to existing session before falling back const autoLinked = await this.autoLinkWorkspace(workspacePath); if (autoLinked) { // Retry getting the session (now it should exist) return this.getSession(workspacePath); } // Fall back to global credentials return this.getGlobalFallbackSession(workspacePath); } /** * Set session for workspace (after login) */ async setSession( workspacePath: string, session: SessionTokens, user: { id: string; email: string; name?: string; tier: "free" | "pro" | "team" | "enterprise"; organizationId?: string; }, authMethod: AuthMethod, apiKey?: string, ): Promise<void> { const now = new Date().toISOString(); await storeWorkspaceSession(workspacePath, { workspacePath, session, user, authMethod: authMethod === "global-fallback" ? "oauth" : authMethod, createdAt: now, updatedAt: now, lastUsedAt: now, apiKey, }); } /** * Clear session for workspace (logout) */ async clearSession(workspacePath: string): Promise<void> { await deleteWorkspaceSession(workspacePath); } /** * Check if workspace has valid session */ async hasSession(workspacePath: string): Promise<boolean> { const session = await getWorkspaceSession(workspacePath); if (!session) return false; return !isSessionExpired(session.session.expiresAt, this.options.refreshBufferSeconds); } /** * Refresh session explicitly */ async refreshSession(workspacePath: string): Promise<WorkspaceSession | null> { const entry = await getWorkspaceSession(workspacePath); if (!entry) return null; // Use single-flight to prevent concurrent refreshes // Use injected refreshFn if provided, otherwise fall back to BetterAuth const refreshFn = this.options.refreshFn ?? refreshWithBetterAuth; const refreshedTokens = await withSingleFlight(`refresh:${entry.workspaceId}`, () => refreshFn(entry.session.refreshToken), ); if (!refreshedTokens) { this.options.onSessionExpired?.(entry.workspaceId); throw new WorkspaceAuthError( "Session refresh failed", WorkspaceAuthErrorCode.REFRESH_FAILED, entry.workspaceId, ); } // Update stored tokens await updateWorkspaceSessionTokens(workspacePath, refreshedTokens); const session: WorkspaceSession = { workspaceId: entry.workspaceId, workspacePath, tokens: refreshedTokens, user: entry.user, authMethod: entry.authMethod, isValid: true, expiresIn: getExpiresIn(refreshedTokens.expiresAt), }; this.options.onSessionRefreshed?.(entry.workspaceId, session); return session; } /** * List all authenticated workspaces */ async listSessions(): Promise<WorkspaceSessionInfo[]> { const sessions = await listWorkspaceSessions(); return sessions.map((s) => ({ workspaceId: s.workspaceId, workspacePath: s.workspacePath, userEmail: s.user.email, tier: s.user.tier, authMethod: s.authMethod, expiresAt: new Date().toISOString(), // Session tokens not included in list lastUsedAt: s.lastUsedAt, })); } // ========================================================================= // GLOBAL FALLBACK (BACKWARDS COMPATIBILITY) // ========================================================================= /** * Migrate global credentials to workspace-scoped */ async migrateGlobalCredentials( workspacePath: string, credentials: { accessToken: string; refreshToken?: string; email: string; tier: "free" | "pro"; expiresAt?: string; }, ): Promise<boolean> { try { const session = credentialsToWorkspaceSession(workspacePath, credentials, "global-fallback"); await storeWorkspaceSession(workspacePath, session); // Also store as global fallback for other workspaces await storeGlobalFallback({ session: session.session, user: session.user, authMethod: "device-code", }); return true; } catch (error) { console.error("[WorkspaceSessionManager] Migration failed:", error); return false; } } /** * Get or create session from global fallback */ private async getGlobalFallbackSession(workspacePath: string): Promise<WorkspaceSession | null> { const global = await getGlobalFallback(); if (!global) return null; // Don't use expired global fallback if (isSessionExpired(global.session.expiresAt)) { return null; } // Auto-migrate to workspace-scoped await this.migrateGlobalCredentials(workspacePath, { accessToken: global.session.accessToken, refreshToken: global.session.refreshToken, email: global.user.email, tier: global.user.tier === "free" ? "free" : "pro", expiresAt: global.session.expiresAt, }); return { workspaceId: `ws_${Date.now()}`, workspacePath, tokens: global.session, user: global.user, authMethod: "global-fallback", isValid: !isSessionExpired(global.session.expiresAt), expiresIn: getExpiresIn(global.session.expiresAt), }; } // ========================================================================= // UTILITY METHODS // ========================================================================= /** * Check if session needs refresh */ private needsRefresh(session: SessionTokens): boolean { return isSessionExpired(session.expiresAt, this.options.refreshBufferSeconds); } /** * Cleanup expired sessions */ async cleanup(): Promise<number> { return cleanupExpiredSessions(); } /** * Auto-link workspace to existing session * * Only links to global fallback credentials for security. * Does NOT clone sessions from other workspaces to prevent * unauthorized session sharing across different projects. * * @param workspacePath - New workspace to link * @returns true if linked successfully, false if no existing session found */ async autoLinkWorkspace(workspacePath: string): Promise<boolean> { // Check if already has session const existing = await getWorkspaceSession(workspacePath); if (existing) { return true; // Already linked } // Try global fallback only (most recent auth) const global = await getGlobalFallback(); if (global && !isSessionExpired(global.session.expiresAt, 60)) { // Auto-migrate global to workspace-scoped await this.migrateGlobalCredentials(workspacePath, { accessToken: global.session.accessToken, refreshToken: global.session.refreshToken, email: global.user.email, tier: global.user.tier === "free" ? "free" : "pro", expiresAt: global.session.expiresAt, }); // Log to stderr to avoid polluting stdout for LLM consumption console.error(`[WorkspaceSessionManager] Auto-linked workspace to global session: ${workspacePath}`); return true; } return false; // No existing session to link } /** * Get auth headers for API requests */ async getAuthHeaders(workspacePath: string): Promise<Record<string, string>> { const session = await this.getSession(workspacePath); if (!session) { return {}; } return { Authorization: `Bearer ${session.tokens.accessToken}`, }; } // ========================================================================= // ENV VAR FALLBACK (STATIC) // ========================================================================= /** * Get API key from environment variables * * Checks SNAPBACK_API_KEY first, then SNAPBACK_AUTH_TOKEN (legacy). * This is a fallback when no workspace session exists. * * @returns API key from env vars, or null if not set */ static getEnvVarApiKey(): string | null { return process.env.SNAPBACK_API_KEY ?? process.env.SNAPBACK_AUTH_TOKEN ?? null; } /** * Check if using legacy SNAPBACK_AUTH_TOKEN env var */ static isUsingLegacyEnvVar(): boolean { return !process.env.SNAPBACK_API_KEY && !!process.env.SNAPBACK_AUTH_TOKEN; } } // ============================================================================= // SINGLETON INSTANCE // ============================================================================= let defaultManager: WorkspaceSessionManager | null = null; /** * Get default workspace session manager instance */ export function getWorkspaceSessionManager(options?: WorkspaceSessionManagerOptions): WorkspaceSessionManager { if (!defaultManager) { defaultManager = new WorkspaceSessionManager(options); } return defaultManager; } // ============================================================================= // CONVENIENCE EXPORTS // ============================================================================= /** * Quick access to workspace session */ export async function getWorkspaceSessionQuick(workspacePath: string): Promise<WorkspaceSession | null> { return getWorkspaceSessionManager().getSession(workspacePath); } /** * Quick check if authenticated */ export async function isWorkspaceAuthenticated(workspacePath: string): Promise<boolean> { return getWorkspaceSessionManager().hasSession(workspacePath); } /** * Get auth headers for workspace */ export async function getWorkspaceAuthHeaders(workspacePath: string): Promise<Record<string, string>> { return getWorkspaceSessionManager().getAuthHeaders(workspacePath); } /** * Auto-link workspace to existing session */ export async function autoLinkWorkspaceSession(workspacePath: string): Promise<boolean> { return getWorkspaceSessionManager().autoLinkWorkspace(workspacePath); } |