All files / src/oauth session-store.ts

95.55% Statements 86/90
91.66% Branches 22/24
98.24% Functions 56/57
96.59% Lines 85/88

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 519 520 521 522 523 524 525 526 527 528 529 530                                                  238x 238x             238x 238x     25x           238x   338x   338x     338x             33x   33x     33x   33x 33x             1x                     168x 167x             365x               7x             12x             24x                       5x                         104x         73x             16x             2x               99x 99x                 117x         29x 1x   28x             4x                     17x             14x             2x             2x             5x                       6x             3x                     149x             5x 1x   4x             185x             5x             78x             3x                     25x             7x             2x               19x             3x                     128x             50x         13x         128x                       11x 11x               14x                 7x                     4x             6x             2x 2x             2x                         4x 4x                 2x 2x             7x             33x   1x         33x 33x               33x 30x 30x                 88x 1x   87x 87x                                         1x 1x                 238x  
/**
 * Session Store for OAuth
 *
 * Unified interface for OAuth session storage with pluggable backends.
 * Supports in-memory, file-based, and PostgreSQL storage.
 *
 * The backend is the single source of truth: every read goes to it and every write
 * completes before the caller continues, so replicas sharing a backend see the same
 * sessions, flows and codes, and a storage failure surfaces instead of being reported
 * as a successful sign-in.
 *
 * Configuration via environment variables:
 * - OAUTH_STORAGE_TYPE: "memory" | "file" | "postgresql" (default: "memory")
 * - OAUTH_STORAGE_FILE_PATH: Path for file storage
 * - OAUTH_STORAGE_POSTGRESQL_URL: PostgreSQL connection string
 */
 
import {
  OAuthSession,
  DeviceFlowState,
  AuthorizationCode,
  AuthCodeFlowState,
  RegisteredOAuthClient,
  GitLabTokenResponse,
} from './types';
import { SessionStorageBackend, createStorageBackend } from './storage';
import { isPastAgeLimit } from './storage/types';
import type {
  AbandonedFlowGrantHandler,
  ExpiredSessionHandler,
  LinkedAccountCommit,
} from './storage/types';
import type { AccountSettings, AccountSettingsRecord } from '../configuration/types';
import { MemoryStorageBackend } from './storage/memory';
import { logInfo, logError, logDebug } from '../logger';
 
function withinAgeLimit(session: OAuthSession | undefined): OAuthSession | undefined {
  return session && !isPastAgeLimit(session) ? session : undefined;
}
 
/**
 * Session store with pluggable storage backends
 */
export class SessionStore {
  private backend: SessionStorageBackend;
  private initialized = false;
 
  private cleanupIntervalId: ReturnType<typeof setInterval> | null = null;
 
  constructor(backend?: SessionStorageBackend) {
    this.backend = backend ?? createStorageBackend();
  }
 
  /**
   * Initialize the session store and backend
   */
  async initialize(): Promise<void> {
    Iif (this.initialized) return;
 
    await this.backend.initialize();
 
    // Start cleanup interval
    this.startCleanupInterval();
 
    this.initialized = true;
    logInfo('Session store initialized', { backendType: this.backend.type });
  }
 
  /**
   * Get storage backend type
   */
  getBackendType(): string {
    return this.backend.type;
  }
 
  // ============================================================
  // Session Operations
  // ============================================================
 
  /**
   * Create a new session
   */
  async createSession(session: OAuthSession): Promise<void> {
    await this.backend.createSession(session);
    logDebug('Session created', { sessionId: session.id, userId: session.gitlabUserId });
  }
 
  /**
   * Get session by ID
   */
  async getSession(sessionId: string): Promise<OAuthSession | undefined> {
    return this.backend.getSession(sessionId);
  }
 
  /**
   * Get session by MCP access token. A session past its age limit is not found: it may
   * still be stored until cleanup ends its grants, but it authenticates nothing.
   */
  async getSessionByToken(token: string): Promise<OAuthSession | undefined> {
    return withinAgeLimit(await this.backend.getSessionByToken(token));
  }
 
  /**
   * Get session by MCP refresh token; a session past its age limit is not found.
   */
  async getSessionByRefreshToken(refreshToken: string): Promise<OAuthSession | undefined> {
    return withinAgeLimit(await this.backend.getSessionByRefreshToken(refreshToken));
  }
 
  /**
   * Update an existing session
   */
  async updateSession(sessionId: string, updates: Partial<OAuthSession>): Promise<boolean> {
    return this.backend.updateSession(sessionId, updates);
  }
 
  /**
   * Apply updates only while the session still holds `expectedRefreshToken`; of concurrent
   * refreshes on any replica exactly one succeeds.
   */
  async rotateSession(
    sessionId: string,
    expectedRefreshToken: string,
    updates: Partial<OAuthSession>,
  ): Promise<boolean> {
    return this.backend.rotateSession(sessionId, expectedRefreshToken, updates);
  }
 
  /**
   * Lease the session's single-use GitLab refresh token until `leaseUntil`; false while
   * another replica holds an unexpired lease or the token already changed.
   */
  async claimGitLabRefresh(
    sessionId: string,
    expectedRefreshToken: string,
    now: number,
    leaseUntil: number,
  ): Promise<boolean> {
    return this.backend.claimGitLabRefresh(sessionId, expectedRefreshToken, now, leaseUntil);
  }
 
  /** End the caller's GitLab refresh lease, named by the `leaseUntil` it claimed. */
  async releaseGitLabRefresh(sessionId: string, leaseUntil: number): Promise<void> {
    await this.backend.releaseGitLabRefresh(sessionId, leaseUntil);
  }
 
  /**
   * Delete a session
   */
  async deleteSession(sessionId: string): Promise<boolean> {
    return this.backend.deleteSession(sessionId);
  }
 
  /**
   * Get all sessions
   */
  async getAllSessions(): Promise<OAuthSession[]> {
    return this.backend.getAllSessions();
  }
 
  /**
   * Whether the backend can read and atomically commit linked accounts. Older database
   * packages must not enable linking with only part of its storage contract implemented.
   */
  linksAccounts(): boolean {
    const backend = this.backend as Partial<SessionStorageBackend>;
    return (
      typeof backend.getLinkedSessions === 'function' &&
      typeof backend.commitLinkedAccount === 'function' &&
      typeof backend.cacheLinkedFlowTokens === 'function'
    );
  }
 
  /** The GitLab accounts linked to a session, oldest first. */
  async getLinkedSessions(sessionId: string): Promise<OAuthSession[]> {
    return this.backend.getLinkedSessions(sessionId);
  }
 
  /** Commit an account and consume its flow under the same storage transaction. */
  async commitLinkedAccount(commit: LinkedAccountCommit): Promise<boolean> {
    if (!this.backend.commitLinkedAccount) {
      throw new Error('The session storage backend cannot commit account links atomically');
    }
    return this.backend.commitLinkedAccount(commit);
  }
 
  /**
   * Get session count
   */
  async getSessionCount(): Promise<number> {
    return (await this.backend.getStats()).sessions;
  }
 
  // ============================================================
  // Device Flow Operations
  // ============================================================
 
  /**
   * Store a device flow state
   */
  async storeDeviceFlow(state: string, flow: DeviceFlowState): Promise<void> {
    await this.backend.storeDeviceFlow(state, flow);
  }
 
  /**
   * Get device flow by state parameter
   */
  async getDeviceFlow(state: string): Promise<DeviceFlowState | undefined> {
    return this.backend.getDeviceFlow(state);
  }
 
  /**
   * Get device flow by device code
   */
  async getDeviceFlowByDeviceCode(deviceCode: string): Promise<DeviceFlowState | undefined> {
    return this.backend.getDeviceFlowByDeviceCode(deviceCode);
  }
 
  /**
   * Delete a device flow
   */
  async deleteDeviceFlow(state: string): Promise<boolean> {
    return this.backend.deleteDeviceFlow(state);
  }
 
  /**
   * Remove and return a device flow; exactly one concurrent caller receives it.
   */
  async consumeDeviceFlow(state: string): Promise<DeviceFlowState | undefined> {
    return this.backend.consumeDeviceFlow(state);
  }
 
  /**
   * Reserve the next GitLab poll of a device flow; of concurrent pollers on any replica
   * one wins each interval, the others get undefined.
   */
  async claimDevicePoll(
    state: string,
    now: number,
    nextPollAt: number,
  ): Promise<DeviceFlowState | undefined> {
    return this.backend.claimDevicePoll(state, now, nextPollAt);
  }
 
  /**
   * Get device flow count
   */
  async getDeviceFlowCount(): Promise<number> {
    return (await this.backend.getStats()).deviceFlows;
  }
 
  // ============================================================
  // Authorization Code Flow Operations
  // ============================================================
 
  /**
   * Store an authorization code flow state
   */
  async storeAuthCodeFlow(internalState: string, flow: AuthCodeFlowState): Promise<void> {
    await this.backend.storeAuthCodeFlow(internalState, flow);
  }
 
  async cacheLinkedFlowTokens(
    flow: AuthCodeFlowState,
    tokens: GitLabTokenResponse,
  ): Promise<boolean> {
    if (!this.backend.cacheLinkedFlowTokens) {
      throw new Error('The session storage backend cannot safely cache account-link tokens');
    }
    return this.backend.cacheLinkedFlowTokens(flow, tokens);
  }
 
  /**
   * Get authorization code flow by internal state
   */
  async getAuthCodeFlow(internalState: string): Promise<AuthCodeFlowState | undefined> {
    return this.backend.getAuthCodeFlow(internalState);
  }
 
  /**
   * Delete an authorization code flow
   */
  async deleteAuthCodeFlow(internalState: string): Promise<boolean> {
    return this.backend.deleteAuthCodeFlow(internalState);
  }
 
  /**
   * Remove and return an authorization code flow; exactly one concurrent caller receives it.
   */
  async consumeAuthCodeFlow(internalState: string): Promise<AuthCodeFlowState | undefined> {
    return this.backend.consumeAuthCodeFlow(internalState);
  }
 
  /**
   * Get auth code flow count
   */
  async getAuthCodeFlowCount(): Promise<number> {
    return (await this.backend.getStats()).authCodeFlows;
  }
 
  // ============================================================
  // Authorization Code Operations
  // ============================================================
 
  /**
   * Store an authorization code
   */
  async storeAuthCode(code: AuthorizationCode): Promise<void> {
    await this.backend.storeAuthCode(code);
  }
 
  /**
   * Get authorization code
   */
  async getAuthCode(code: string): Promise<AuthorizationCode | undefined> {
    return this.backend.getAuthCode(code);
  }
 
  /**
   * Delete authorization code
   */
  async deleteAuthCode(code: string): Promise<boolean> {
    return this.backend.deleteAuthCode(code);
  }
 
  /**
   * Remove and return an authorization code (single use); exactly one concurrent caller
   * receives it.
   */
  async consumeAuthCode(code: string): Promise<AuthorizationCode | undefined> {
    return this.backend.consumeAuthCode(code);
  }
 
  /**
   * Get auth code count
   */
  async getAuthCodeCount(): Promise<number> {
    return (await this.backend.getStats()).authCodes;
  }
 
  // ============================================================
  // Registered OAuth Clients
  // ============================================================
 
  /**
   * Store a client registered through Dynamic Client Registration
   */
  async storeClient(client: RegisteredOAuthClient): Promise<void> {
    await this.backend.storeClient(client);
  }
 
  /**
   * Get a registered client
   */
  async getClient(clientId: string): Promise<RegisteredOAuthClient | undefined> {
    return this.backend.getClient(clientId);
  }
 
  /** Record that the client completed an authorization, so its registration stays. */
  async markClientUsed(clientId: string): Promise<void> {
    await this.backend.markClientUsed(clientId);
  }
 
  /** How many clients `registeredFrom` registered at or after `since` (epoch ms), used or not. */
  async countClientsRegisteredSince(registeredFrom: string, since: number): Promise<number> {
    return this.backend.countClientsRegisteredSince(registeredFrom, since);
  }
 
  // ============================================================
  // Account Settings
  // ============================================================
 
  /**
   * Whether account settings can live here: the backend survives a restart and has the
   * settings methods, which a database package older than this server lacks.
   */
  keepsAccountSettings(): boolean {
    const backend = this.backend as Partial<SessionStorageBackend>;
    return (
      this.backend.type !== 'memory' &&
      typeof backend.getAccountSettings === 'function' &&
      typeof backend.putAccountSettings === 'function'
    );
  }
 
  async getAccountSettings(accountKey: string): Promise<AccountSettingsRecord | undefined> {
    return this.backend.getAccountSettings(accountKey);
  }
 
  /** Compare-and-set write; undefined when another write changed the settings first. */
  async putAccountSettings(
    accountKey: string,
    settings: AccountSettings,
    expectedVersion: number,
  ): Promise<AccountSettingsRecord | undefined> {
    return this.backend.putAccountSettings(accountKey, settings, expectedVersion);
  }
 
  // ============================================================
  // MCP Session Mapping Operations
  // ============================================================
 
  /**
   * Associate an MCP session ID with an OAuth session ID
   */
  async associateMcpSession(mcpSessionId: string, oauthSessionId: string): Promise<void> {
    await this.backend.associateMcpSession(mcpSessionId, oauthSessionId);
  }
 
  /**
   * Get OAuth session by MCP session ID; a session past its age limit is not found.
   */
  async getSessionByMcpSessionId(mcpSessionId: string): Promise<OAuthSession | undefined> {
    return withinAgeLimit(await this.backend.getSessionByMcpSessionId(mcpSessionId));
  }
 
  /**
   * Get GitLab token by MCP session ID
   */
  async getGitLabTokenByMcpSessionId(mcpSessionId: string): Promise<string | undefined> {
    const session = await this.getSessionByMcpSessionId(mcpSessionId);
    return session?.gitlabAccessToken;
  }
 
  /**
   * Remove MCP session association
   */
  async removeMcpSessionAssociation(mcpSessionId: string): Promise<boolean> {
    return this.backend.removeMcpSessionAssociation(mcpSessionId);
  }
 
  // ============================================================
  // Cleanup Operations
  // ============================================================
 
  /**
   * End the GitLab grant of each expired authorization flow cleanup removes unfinished.
   * A database package older than this server has no such hook; its cleanup removes those
   * flows as before.
   */
  onAbandonedFlowGrant(handler: AbandonedFlowGrantHandler, leaseMs: number): void {
    const backend = this.backend as Partial<SessionStorageBackend>;
    backend.onAbandonedFlowGrant?.(handler, leaseMs);
  }
 
  /**
   * Remove each session that reaches its age limit through `handler`, which ends its GitLab
   * grants and those of its linked accounts. A database package older than this server has
   * no such hook; its cleanup deletes those sessions as before.
   */
  onExpiredSession(handler: ExpiredSessionHandler): void {
    const backend = this.backend as Partial<SessionStorageBackend>;
    backend.onExpiredSession?.(handler);
  }
 
  /**
   * Clean up all expired entries
   */
  async cleanup(): Promise<void> {
    await this.backend.cleanup();
  }
 
  /**
   * Start automatic cleanup interval
   */
  private startCleanupInterval(): void {
    this.cleanupIntervalId = setInterval(
      () => {
        this.cleanup().catch((err: unknown) => logError('Session store cleanup failed', { err }));
      },
      5 * 60 * 1000,
    );
 
    Eif (this.cleanupIntervalId.unref) {
      this.cleanupIntervalId.unref();
    }
  }
 
  /**
   * Stop cleanup interval
   */
  stopCleanupInterval(): void {
    if (this.cleanupIntervalId) {
      clearInterval(this.cleanupIntervalId);
      this.cleanupIntervalId = null;
    }
  }
 
  /**
   * Clear all data (for testing). Only the in-memory backend can be cleared; a shared
   * database is never wiped from application code.
   */
  clear(): void {
    if (!(this.backend instanceof MemoryStorageBackend)) {
      throw new TypeError('clear() is only supported for in-memory storage');
    }
    this.backend.importData({});
    logDebug('Session store cleared');
  }
 
  /**
   * Graceful shutdown
   */
  async close(): Promise<void> {
    this.stopCleanupInterval();
    await this.backend.close();
    logInfo('Session store closed');
  }
 
  /**
   * Get store statistics
   */
  async getStats(): Promise<{
    sessions: number;
    deviceFlows: number;
    authCodeFlows: number;
    authCodes: number;
  }> {
    const { sessions, deviceFlows, authCodeFlows, authCodes } = await this.backend.getStats();
    return { sessions, deviceFlows, authCodeFlows, authCodes };
  }
}
 
/**
 * Singleton session store instance
 *
 * Note: Must call sessionStore.initialize() before use
 */
export const sessionStore = new SessionStore();