All files / src/oauth/storage memory.ts

97.53% Statements 316/324
95.6% Branches 196/205
100% Functions 68/68
98.26% Lines 283/288

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 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765              255x                 255x                 255x                     255x               86x 38x 29x                 156x 156x 36x 26x 8x 8x     156x     255x 612x   612x 612x 612x   612x 612x 612x 612x 612x 612x 612x   612x 612x           612x       319x 319x 2x             377x 376x 376x 376x 287x                       3x 2x   2x   1x 1x       1x         3x                   67x 67x 67x 67x 67x                           22x   45x       45x 22x           7x 15x 15x                 23x 21x 6x 6x   21x   36x 36x 9x 9x       3x               3x     33x         356x 355x       463x       17x 17x       28x 28x       46x 46x 4x 4x       42x 22x 22x   42x 25x 25x     42x 42x 42x       61x 61x   57x 57x 57x 41x   57x 44x     57x 57x 57x 57x       9x       188x   382x 3x           41x 41x       27x       6x 6x   2x       6x 6x 6x                 30x 30x 30x   30x           30x         2x       28x 8x 8x   20x     20x 20x 16x   24x 24x 24x 24x   2x 1x 2x   22x       238x 238x       249x 247x 246x       10x 9x 9x 6x   9x         69x 69x       18x       6x 6x 6x         16x 16x             14x 14x 9x       6x 6x 6x         150x       64x       15x 15x 13x         133x 133x 6448x   133x           53x 53x                   35x 35x 28x           28x 28x         3x 1x           28x 28x 28x       92x 90x 89x 89x 89x       9x 9x 9x               13x 13x 7x 7x 7x                 178x 175x 175x 146x 146x       80x 74x                 9x 3x   6x       17x     17x       7x               21x 1x   21x         39x       39x   41x     39x 39x   39x 39x 39x     20x     39x 39x             39x 18x 17x 17x 4x 4x   12x 12x   5x 5x   17x       39x   39x   39x             29x                       315x 315x 2x         87x                   319x   1x         319x 319x         315x 300x 300x                           460x       23x 124x           8x                               160x 160x 15x   160x 160x 7x   160x 160x 160x 160x 160x 160x 160x 160x     160x 69x 71x 71x 66x   71x 66x           160x 65x 3x         160x 65x 9x         160x 65x 46x         160x 65x 2x       160x                
/**
 * In-Memory Session Storage Backend
 *
 * Default storage for development and single-instance deployments.
 * Sessions are lost on server restart.
 */
 
import { createHash } from 'node:crypto';
import {
  OAuthSession,
  DeviceFlowState,
  AuthCodeFlowState,
  AuthorizationCode,
  RegisteredOAuthClient,
  GitLabTokenResponse,
} from '../types';
import {
  AbandonedFlowGrantHandler,
  ExpiredSessionHandler,
  LinkedAccountCommit,
  isPastAgeLimit,
  SessionStorageBackend,
  SessionStorageStats,
} from './types';
import type { AccountSettings, AccountSettingsRecord } from '../../configuration/types';
import { logInfo, logWarn, logError, logDebug, truncateId } from '../../logger';
 
export interface MemoryStorageOptions {
  /** Suppress initialization logging (used when wrapped by FileStorage) */
  silent?: boolean;
}
 
/**
 * How many grants cleanup ends at once: a backlog (after a restart, say) goes out in steps
 * instead of one burst against GitLab's rate limits.
 */
const CLEANUP_BATCH = 5;
 
/** Run `run` over `items`, at most CLEANUP_BATCH at a time. */
async function inBatches<T>(
  items: readonly T[],
  run: (item: T) => Promise<void>,
  from = 0,
): Promise<void> {
  if (from >= items.length) return;
  await Promise.all(items.slice(from, from + CLEANUP_BATCH).map((item) => run(item)));
  return inBatches(items, run, from + CLEANUP_BATCH);
}
 
/** Remove expired entries except records an asynchronous cleanup still owns. */
function deleteExpired<K>(
  entries: Map<K, { expiresAt?: number }>,
  now: number,
  retained?: ReadonlySet<K>,
): number {
  let removed = 0;
  for (const [key, entry] of entries) {
    if (entry.expiresAt !== undefined && entry.expiresAt < now) {
      if (retained?.has(key)) continue;
      entries.delete(key);
      removed++;
    }
  }
  return removed;
}
 
export class MemoryStorageBackend implements SessionStorageBackend {
  readonly type = 'memory' as const;
 
  private sessions = new Map<string, OAuthSession>();
  private deviceFlows = new Map<string, DeviceFlowState>();
  private authCodeFlows = new Map<string, AuthCodeFlowState>();
  /** Hidden from callbacks, but retained in exports until their grant is ended. */
  private abandonedFlowsInProgress = new Set<string>();
  private authCodes = new Map<string, AuthorizationCode>();
  private tokenToSession = new Map<string, string>();
  private refreshTokenToSession = new Map<string, string>();
  private mcpSessionToOAuthSession = new Map<string, string>();
  private clients = new Map<string, RegisteredOAuthClient>();
  private accountSettings = new Map<string, AccountSettingsRecord>();
  /** Session id -> end of its GitLab refresh lease (transient, not exported). */
  private gitlabRefreshLeases = new Map<string, number>();
  private cleanupIntervalId: ReturnType<typeof setInterval> | null = null;
  private abandonedFlowGrant: AbandonedFlowGrantHandler | undefined;
  private expiredSession: ExpiredSessionHandler | undefined;
  private silent: boolean;
 
  constructor(options?: MemoryStorageOptions) {
    this.silent = options?.silent ?? false;
  }
 
  async initialize(): Promise<void> {
    this.startCleanupInterval();
    if (!this.silent) {
      logInfo('Memory storage backend initialized');
    }
  }
 
  // Session operations
  /** Synchronous insertion shared with the atomic account-link transition. */
  private insertSession(session: OAuthSession): void {
    if (this.sessions.has(session.id)) throw new Error(`Session ${session.id} already exists`);
    this.sessions.set(session.id, session);
    if (session.mcpAccessToken) this.tokenToSession.set(session.mcpAccessToken, session.id);
    if (session.mcpRefreshToken)
      this.refreshTokenToSession.set(session.mcpRefreshToken, session.id);
  }
 
  /** Restore both halves of a link after a failed file write, while its queue is held. */
  private restoreLinkedAccount(
    { account, internalState }: LinkedAccountCommit,
    stored: OAuthSession | undefined,
    previous: OAuthSession | undefined,
    flow: AuthCodeFlowState,
    accessOwner: string | undefined,
    refreshOwner: string | undefined,
  ): void {
    if (stored && previous) {
      Object.assign(stored, previous);
      // Restore unknown scopes even when the persisted legacy session omitted the key.
      stored.gitlabScopes = previous.gitlabScopes;
    } else {
      this.sessions.delete(account.id);
      Iif (account.mcpAccessToken) {
        if (accessOwner === undefined) this.tokenToSession.delete(account.mcpAccessToken);
        else this.tokenToSession.set(account.mcpAccessToken, accessOwner);
      }
      Iif (account.mcpRefreshToken) {
        if (refreshOwner === undefined) this.refreshTokenToSession.delete(account.mcpRefreshToken);
        else this.refreshTokenToSession.set(account.mcpRefreshToken, refreshOwner);
      }
    }
    this.authCodeFlows.set(internalState, flow);
  }
 
  async commitLinkedAccount(
    commit: LinkedAccountCommit,
    persist?: () => Promise<void>,
  ): Promise<boolean> {
    // No awaits between lease validation, account mutation and spending the flow: other
    // requests and abandoned-grant cleanup observe both records together. File storage
    // supplies persistence while holding its write/lease queue until this call returns.
    const { account, internalState, primaryLeaseUntil, existing } = commit;
    const now = Date.now();
    const parent = account.linkedToSessionId;
    const flow = this.authCodeFlows.get(internalState);
    if (
      !this.sessions.has(parent) ||
      this.gitlabRefreshLeases.get(parent) !== primaryLeaseUntil ||
      primaryLeaseUntil <= now ||
      !flow ||
      flow.expiresAt <= now ||
      flow.link?.stage !== 'connect' ||
      flow.link.sessionId !== parent ||
      internalState.startsWith('cleanup:') ||
      (flow.gitlabTokens &&
        (flow.gitlabTokens.access_token !== account.gitlabAccessToken ||
          flow.gitlabTokens.refresh_token !== account.gitlabRefreshToken)) ||
      this.abandonedFlowsInProgress.has(internalState)
    )
      return false;
 
    const stored = this.sessions.get(account.id);
    let previous: OAuthSession | undefined;
    let previousAccessOwner: string | undefined;
    let previousRefreshOwner: string | undefined;
    if (existing) {
      if (
        stored?.linkedToSessionId !== parent ||
        stored.gitlabRefreshToken !== existing.refreshToken ||
        this.gitlabRefreshLeases.get(account.id) !== existing.leaseUntil ||
        existing.leaseUntil <= now
      )
        return false;
      if (persist) previous = { ...stored };
      Object.assign(stored, {
        gitlabAccessToken: account.gitlabAccessToken,
        gitlabRefreshToken: account.gitlabRefreshToken,
        gitlabTokenExpiry: account.gitlabTokenExpiry,
        gitlabScopes: account.gitlabScopes,
        gitlabUsername: account.gitlabUsername,
        updatedAt: now,
      });
    } else {
      if (stored) return false;
      if (persist) {
        previousAccessOwner = this.tokenToSession.get(account.mcpAccessToken);
        previousRefreshOwner = this.refreshTokenToSession.get(account.mcpRefreshToken);
      }
      this.insertSession(account);
    }
    this.authCodeFlows.delete(internalState);
    if (persist) {
      try {
        await persist();
      } catch (error: unknown) {
        // File storage serializes this write and lease claims. Undo both records in one
        // synchronous step, preserving timestamps and indexes as well as credentials.
        this.restoreLinkedAccount(
          commit,
          stored,
          previous,
          flow,
          previousAccessOwner,
          previousRefreshOwner,
        );
        throw error;
      }
    }
    return true;
  }
 
  async createSession(session: OAuthSession): Promise<void> {
    // Creating never replaces a session, as with the primary key of the database backend.
    this.insertSession(session);
    logDebug('Session created', { sessionId: session.id, userId: session.gitlabUserId });
  }
 
  async getSession(sessionId: string): Promise<OAuthSession | undefined> {
    return this.sessions.get(sessionId);
  }
 
  async getSessionByToken(token: string): Promise<OAuthSession | undefined> {
    const sessionId = this.tokenToSession.get(token);
    return sessionId ? this.sessions.get(sessionId) : undefined;
  }
 
  async getSessionByRefreshToken(refreshToken: string): Promise<OAuthSession | undefined> {
    const sessionId = this.refreshTokenToSession.get(refreshToken);
    return sessionId ? this.sessions.get(sessionId) : undefined;
  }
 
  async updateSession(sessionId: string, updates: Partial<OAuthSession>): Promise<boolean> {
    const session = this.sessions.get(sessionId);
    if (!session) {
      logWarn('Attempted to update non-existent session', { sessionId });
      return false;
    }
 
    // Update token indexes if tokens changed
    if (updates.mcpAccessToken && updates.mcpAccessToken !== session.mcpAccessToken) {
      this.tokenToSession.delete(session.mcpAccessToken);
      this.tokenToSession.set(updates.mcpAccessToken, sessionId);
    }
    if (updates.mcpRefreshToken && updates.mcpRefreshToken !== session.mcpRefreshToken) {
      this.refreshTokenToSession.delete(session.mcpRefreshToken);
      this.refreshTokenToSession.set(updates.mcpRefreshToken, sessionId);
    }
 
    Object.assign(session, updates, { updatedAt: Date.now() });
    logDebug('Session updated', { sessionId });
    return true;
  }
 
  async deleteSession(sessionId: string): Promise<boolean> {
    const session = this.sessions.get(sessionId);
    if (!session) return false;
 
    const linked = await this.getLinkedSessions(sessionId);
    await Promise.all(linked.map((account) => this.deleteSession(account.id)));
    if (session.mcpAccessToken) {
      this.tokenToSession.delete(session.mcpAccessToken);
    }
    if (session.mcpRefreshToken) {
      this.refreshTokenToSession.delete(session.mcpRefreshToken);
    }
 
    this.sessions.delete(sessionId);
    this.gitlabRefreshLeases.delete(sessionId);
    logDebug('Session deleted', { sessionId });
    return true;
  }
 
  async getAllSessions(): Promise<OAuthSession[]> {
    return Array.from(this.sessions.values());
  }
 
  getLinkedSessions(sessionId: string): Promise<OAuthSession[]> {
    return Promise.resolve(
      Array.from(this.sessions.values())
        .filter((session) => session.linkedToSessionId === sessionId)
        .sort((a, b) => a.createdAt - b.createdAt),
    );
  }
 
  // Device flow operations
  async storeDeviceFlow(state: string, flow: DeviceFlowState): Promise<void> {
    this.deviceFlows.set(state, flow);
    logDebug('Device flow stored', { state, userCode: flow.userCode });
  }
 
  async getDeviceFlow(state: string): Promise<DeviceFlowState | undefined> {
    return this.deviceFlows.get(state);
  }
 
  async getDeviceFlowByDeviceCode(deviceCode: string): Promise<DeviceFlowState | undefined> {
    for (const flow of this.deviceFlows.values()) {
      if (flow.deviceCode === deviceCode) return flow;
    }
    return undefined;
  }
 
  async deleteDeviceFlow(state: string): Promise<boolean> {
    const deleted = this.deviceFlows.delete(state);
    if (deleted) logDebug('Device flow deleted', { state });
    return deleted;
  }
 
  // Auth code flow operations
  async cacheLinkedFlowTokens(
    flow: AuthCodeFlowState,
    tokens: GitLabTokenResponse,
    persist?: () => Promise<void>,
  ): Promise<boolean> {
    Iif (!flow.link) throw new Error('An account-link flow is required');
    const now = Date.now();
    const current = this.authCodeFlows.get(flow.internalState);
    const active =
      current &&
      current.expiresAt > now &&
      !flow.internalState.startsWith('cleanup:') &&
      !this.abandonedFlowsInProgress.has(flow.internalState) &&
      current.link?.sessionId === flow.link.sessionId &&
      current.link.stage === flow.link.stage;
    if (
      active &&
      current.gitlabTokens?.access_token === tokens.access_token &&
      current.gitlabTokens.refresh_token === tokens.refresh_token
    )
      return true;
 
    let state: string;
    let pending: AuthCodeFlowState;
    if (active && !current.gitlabTokens) {
      state = flow.internalState;
      pending = { ...current, gitlabTokens: tokens };
    } else {
      const grant = createHash('sha256')
        .update(JSON.stringify([tokens.access_token, tokens.refresh_token]))
        .digest('hex');
      state = `cleanup:issued:${flow.internalState}:${grant}`;
      if (this.authCodeFlows.has(state)) return false;
      pending = { ...flow, internalState: state, expiresAt: now - 1, gitlabTokens: tokens };
    }
    const previous = this.authCodeFlows.get(state);
    this.authCodeFlows.set(state, pending);
    try {
      await persist?.();
    } catch (error: unknown) {
      if (previous) this.authCodeFlows.set(state, previous);
      else this.authCodeFlows.delete(state);
      throw error;
    }
    return state === flow.internalState;
  }
 
  async storeAuthCodeFlow(internalState: string, flow: AuthCodeFlowState): Promise<void> {
    this.authCodeFlows.set(internalState, flow);
    logDebug('Auth code flow stored', { internalState: truncateId(internalState) });
  }
 
  async getAuthCodeFlow(internalState: string): Promise<AuthCodeFlowState | undefined> {
    if (internalState.startsWith('cleanup:')) return undefined;
    if (this.abandonedFlowsInProgress.has(internalState)) return undefined;
    return this.authCodeFlows.get(internalState);
  }
 
  async deleteAuthCodeFlow(internalState: string): Promise<boolean> {
    if (this.abandonedFlowsInProgress.has(internalState)) return false;
    const deleted = this.authCodeFlows.delete(internalState);
    if (deleted) {
      logDebug('Auth code flow deleted', { internalState: truncateId(internalState) });
    }
    return deleted;
  }
 
  // Authorization code operations
  async storeAuthCode(code: AuthorizationCode): Promise<void> {
    this.authCodes.set(code.code, code);
    logDebug('Auth code stored', { code: truncateId(code.code) });
  }
 
  async getAuthCode(code: string): Promise<AuthorizationCode | undefined> {
    return this.authCodes.get(code);
  }
 
  async deleteAuthCode(code: string): Promise<boolean> {
    const deleted = this.authCodes.delete(code);
    if (deleted) logDebug('Auth code deleted', { code: truncateId(code) });
    return deleted;
  }
 
  // MCP session mapping
  async associateMcpSession(mcpSessionId: string, oauthSessionId: string): Promise<void> {
    this.mcpSessionToOAuthSession.set(mcpSessionId, oauthSessionId);
    logDebug('MCP session associated with OAuth session', {
      mcpSessionId,
      oauthSessionId: truncateId(oauthSessionId),
    });
  }
 
  async getSessionByMcpSessionId(mcpSessionId: string): Promise<OAuthSession | undefined> {
    const oauthSessionId = this.mcpSessionToOAuthSession.get(mcpSessionId);
    if (!oauthSessionId) return undefined;
    return this.sessions.get(oauthSessionId);
  }
 
  async removeMcpSessionAssociation(mcpSessionId: string): Promise<boolean> {
    const deleted = this.mcpSessionToOAuthSession.delete(mcpSessionId);
    if (deleted) logDebug('MCP session association removed', { mcpSessionId });
    return deleted;
  }
 
  // Registered OAuth clients
  async storeClient(client: RegisteredOAuthClient): Promise<void> {
    this.clients.set(client.clientId, client);
  }
 
  async getClient(clientId: string): Promise<RegisteredOAuthClient | undefined> {
    return this.clients.get(clientId);
  }
 
  async markClientUsed(clientId: string): Promise<void> {
    const client = this.clients.get(clientId);
    if (client?.expiresAt !== undefined) {
      this.clients.set(clientId, { ...client, expiresAt: undefined });
    }
  }
 
  async countClientsRegisteredSince(registeredFrom: string, since: number): Promise<number> {
    let count = 0;
    for (const client of this.clients.values()) {
      if (client.registeredFrom === registeredFrom && client.createdAt >= since) count++;
    }
    return count;
  }
 
  // Account settings: records are copied in and out, so a caller changing what it holds
  // never changes the stored settings.
  async getAccountSettings(accountKey: string): Promise<AccountSettingsRecord | undefined> {
    const record = this.accountSettings.get(accountKey);
    return record ? structuredClone(record) : undefined;
  }
 
  // Compare and write run without an await in between: of concurrent writes of one
  // version in this process exactly one succeeds.
  async putAccountSettings(
    accountKey: string,
    settings: AccountSettings,
    expectedVersion: number,
  ): Promise<AccountSettingsRecord | undefined> {
    const current = this.accountSettings.get(accountKey)?.version ?? 0;
    if (current !== expectedVersion) return undefined;
    const record: AccountSettingsRecord = {
      accountKey,
      settings: structuredClone(settings),
      version: current + 1,
      updatedAt: Date.now(),
    };
    this.accountSettings.set(accountKey, record);
    return structuredClone(record);
  }
 
  /** Restore the record a failed write replaced (undefined: there was none). */
  restoreAccountSettings(accountKey: string, previous: AccountSettingsRecord | undefined): void {
    if (previous) this.accountSettings.set(accountKey, previous);
    else this.accountSettings.delete(accountKey);
  }
 
  // Single-use consumption: lookup and removal run without an await in between, so in
  // this process exactly one caller gets the record.
  async consumeAuthCode(code: string): Promise<AuthorizationCode | undefined> {
    const record = this.authCodes.get(code);
    if (record) this.authCodes.delete(code);
    return record;
  }
 
  async consumeAuthCodeFlow(internalState: string): Promise<AuthCodeFlowState | undefined> {
    if (internalState.startsWith('cleanup:')) return undefined;
    if (this.abandonedFlowsInProgress.has(internalState)) return undefined;
    const record = this.authCodeFlows.get(internalState);
    if (record) this.authCodeFlows.delete(internalState);
    return record;
  }
 
  async consumeDeviceFlow(state: string): Promise<DeviceFlowState | undefined> {
    const record = this.deviceFlows.get(state);
    if (record) this.deviceFlows.delete(state);
    return record;
  }
 
  async claimDevicePoll(
    state: string,
    now: number,
    nextPollAt: number,
  ): Promise<DeviceFlowState | undefined> {
    const flow = this.deviceFlows.get(state);
    if (!flow || (flow.nextPollAt !== undefined && flow.nextPollAt > now)) return undefined;
    const claimed = { ...flow, nextPollAt };
    this.deviceFlows.set(state, claimed);
    return claimed;
  }
 
  async claimGitLabRefresh(
    sessionId: string,
    expectedRefreshToken: string,
    now: number,
    leaseUntil: number,
  ): Promise<boolean> {
    if (this.sessions.get(sessionId)?.gitlabRefreshToken !== expectedRefreshToken) return false;
    const held = this.gitlabRefreshLeases.get(sessionId);
    if (held !== undefined && held > now) return false;
    this.gitlabRefreshLeases.set(sessionId, leaseUntil);
    return true;
  }
 
  async releaseGitLabRefresh(sessionId: string, leaseUntil: number): Promise<void> {
    if (this.gitlabRefreshLeases.get(sessionId) === leaseUntil) {
      this.gitlabRefreshLeases.delete(sessionId);
    }
  }
 
  async rotateSession(
    sessionId: string,
    expectedRefreshToken: string,
    updates: Partial<OAuthSession>,
  ): Promise<boolean> {
    if (this.sessions.get(sessionId)?.mcpRefreshToken !== expectedRefreshToken) {
      return false;
    }
    return this.updateSession(sessionId, updates);
  }
 
  onAbandonedFlowGrant(handler: AbandonedFlowGrantHandler, leaseMs: number): void {
    Iif (!Number.isSafeInteger(leaseMs) || leaseMs <= 0) {
      throw new Error('Abandoned-flow cleanup requires a positive integer lease duration');
    }
    this.abandonedFlowGrant = handler;
  }
 
  onExpiredSession(handler: ExpiredSessionHandler): void {
    this.expiredSession = handler;
  }
 
  /**
   * Remove a session past its age limit: through the handler, which ends its grants and
   * those of its linked accounts, then directly if the handler failed or left it.
   */
  private async expire(session: OAuthSession): Promise<void> {
    await this.expiredSession?.(session).catch((error: unknown) => {
      logWarn('Could not end the grants of an expired session', { err: error as Error });
    });
    await this.deleteSession(session.id);
  }
 
  // Cleanup
  async cleanup(): Promise<void> {
    const now = Date.now();
 
    // Clean up expired sessions (7 days max age). A linked account goes with its session;
    // it is younger than the session, so only one left without a session expires by itself.
    const expired = [...this.sessions.values()].filter(
      (session) =>
        isPastAgeLimit(session, now) &&
        !(session.linkedToSessionId && this.sessions.has(session.linkedToSessionId)),
    );
    await inBatches(expired, (session) => this.expire(session));
    const expiredSessions = expired.length;
 
    const expiredDeviceFlows = deleteExpired(this.deviceFlows, now);
    const handler = this.abandonedFlowGrant;
    const abandoned = handler
      ? [...this.authCodeFlows].filter(
          ([state, flow]) =>
            flow.gitlabTokens && flow.expiresAt < now && !this.abandonedFlowsInProgress.has(state),
        )
      : [];
    for (const [state] of abandoned) this.abandonedFlowsInProgress.add(state);
    let expiredAuthCodeFlows = deleteExpired(
      this.authCodeFlows,
      now,
      this.abandonedFlowsInProgress,
    );
    // Keep the only grant copy in exports during the GitLab request too: file autosaves
    // must not erase it. Callback reads/consumption and concurrent cleanups skip its claim.
    if (handler) {
      await inBatches(abandoned, async ([state, flow]) => {
        try {
          await handler(flow, async (tokens) => {
            flow.gitlabTokens = tokens;
            this.authCodeFlows.set(state, flow);
          });
          this.authCodeFlows.delete(state);
          expiredAuthCodeFlows++;
        } catch (error: unknown) {
          logWarn('Could not end the grant of an abandoned flow', { err: error as Error });
          this.authCodeFlows.set(state, flow);
        } finally {
          this.abandonedFlowsInProgress.delete(state);
        }
      });
    }
    const expiredAuthCodes = deleteExpired(this.authCodes, now);
    // Registrations that never completed an authorization expire; used ones have no expiry
    const expiredClients = deleteExpired(this.clients, now);
 
    if (
      expiredSessions > 0 ||
      expiredDeviceFlows > 0 ||
      expiredAuthCodeFlows > 0 ||
      expiredAuthCodes > 0 ||
      expiredClients > 0
    ) {
      logDebug('Memory storage cleanup completed', {
        expiredSessions,
        expiredDeviceFlows,
        expiredAuthCodeFlows,
        expiredAuthCodes,
        expiredClients,
        remainingSessions: this.sessions.size,
      });
    }
  }
 
  async close(): Promise<void> {
    this.stopCleanupInterval();
    if (!this.silent) {
      logInfo('Memory storage backend closed');
    }
  }
 
  async getStats(): Promise<SessionStorageStats> {
    return {
      sessions: this.sessions.size,
      deviceFlows: this.deviceFlows.size,
      authCodeFlows: this.authCodeFlows.size,
      authCodes: this.authCodes.size,
      mcpSessionMappings: this.mcpSessionToOAuthSession.size,
    };
  }
 
  private startCleanupInterval(): void {
    this.cleanupIntervalId = setInterval(
      () => {
        this.cleanup().catch((err) => logError('Cleanup error', { err }));
      },
      5 * 60 * 1000,
    );
 
    Eif (this.cleanupIntervalId.unref) {
      this.cleanupIntervalId.unref();
    }
  }
 
  private stopCleanupInterval(): void {
    if (this.cleanupIntervalId) {
      clearInterval(this.cleanupIntervalId);
      this.cleanupIntervalId = null;
    }
  }
 
  /** Export all data for file persistence */
  exportData(): {
    sessions: OAuthSession[];
    deviceFlows: Array<{ state: string; flow: DeviceFlowState }>;
    authCodeFlows: Array<{ internalState: string; flow: AuthCodeFlowState }>;
    authCodes: AuthorizationCode[];
    mcpSessionMappings: Array<{ mcpSessionId: string; oauthSessionId: string }>;
    clients: RegisteredOAuthClient[];
    accountSettings: AccountSettingsRecord[];
  } {
    return {
      clients: Array.from(this.clients.values()),
      accountSettings: Array.from(this.accountSettings.values()),
      sessions: Array.from(this.sessions.values()),
      deviceFlows: Array.from(this.deviceFlows.entries()).map(([state, flow]) => ({ state, flow })),
      authCodeFlows: Array.from(this.authCodeFlows.entries()).map(([internalState, flow]) => ({
        internalState,
        flow,
      })),
      authCodes: Array.from(this.authCodes.values()),
      mcpSessionMappings: Array.from(this.mcpSessionToOAuthSession.entries()).map(
        ([mcpSessionId, oauthSessionId]) => ({ mcpSessionId, oauthSessionId }),
      ),
    };
  }
 
  /** Import data from file persistence */
  importData(data: {
    sessions?: OAuthSession[];
    deviceFlows?: Array<{ state: string; flow: DeviceFlowState }>;
    authCodeFlows?: Array<{ internalState: string; flow: AuthCodeFlowState }>;
    authCodes?: AuthorizationCode[];
    mcpSessionMappings?: Array<{ mcpSessionId: string; oauthSessionId: string }>;
    clients?: RegisteredOAuthClient[];
    accountSettings?: AccountSettingsRecord[];
  }): void {
    // Clear existing data
    this.clients.clear();
    for (const client of data.clients ?? []) {
      this.clients.set(client.clientId, client);
    }
    this.accountSettings.clear();
    for (const record of data.accountSettings ?? []) {
      this.accountSettings.set(record.accountKey, record);
    }
    this.sessions.clear();
    this.gitlabRefreshLeases.clear();
    this.deviceFlows.clear();
    this.authCodeFlows.clear();
    this.authCodes.clear();
    this.tokenToSession.clear();
    this.refreshTokenToSession.clear();
    this.mcpSessionToOAuthSession.clear();
 
    // Import sessions
    if (data.sessions) {
      for (const session of data.sessions) {
        this.sessions.set(session.id, session);
        if (session.mcpAccessToken) {
          this.tokenToSession.set(session.mcpAccessToken, session.id);
        }
        if (session.mcpRefreshToken) {
          this.refreshTokenToSession.set(session.mcpRefreshToken, session.id);
        }
      }
    }
 
    // Import device flows
    if (data.deviceFlows) {
      for (const { state, flow } of data.deviceFlows) {
        this.deviceFlows.set(state, flow);
      }
    }
 
    // Import auth code flows
    if (data.authCodeFlows) {
      for (const { internalState, flow } of data.authCodeFlows) {
        this.authCodeFlows.set(internalState, flow);
      }
    }
 
    // Import auth codes
    if (data.authCodes) {
      for (const code of data.authCodes) {
        this.authCodes.set(code.code, code);
      }
    }
 
    // Import MCP session mappings
    if (data.mcpSessionMappings) {
      for (const { mcpSessionId, oauthSessionId } of data.mcpSessionMappings) {
        this.mcpSessionToOAuthSession.set(mcpSessionId, oauthSessionId);
      }
    }
 
    logInfo('Data imported into memory storage', {
      sessions: this.sessions.size,
      deviceFlows: this.deviceFlows.size,
      authCodeFlows: this.authCodeFlows.size,
      authCodes: this.authCodes.size,
    });
  }
}