All files / src/oauth/storage memory.ts

98.68% Statements 150/152
95.94% Branches 71/74
94.11% Functions 32/34
99.31% Lines 144/145

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                  77x             77x 222x   222x 222x 222x 222x 222x 222x 222x 222x       222x       114x 114x 1x           73x 73x 72x   73x 71x   73x       17x       8x 8x       8x 8x       10x 10x 2x 2x       8x 1x 1x   8x 1x 1x     8x 8x 8x       14x 14x   12x 11x   12x 11x     12x 12x 12x       6x         22x 22x       10x       4x 5x   1x       6x 6x 6x         13x 13x       10x       4x 4x 2x         4x         16x 16x       10x       6x 6x 6x         11x 11x             7x 7x 5x       4x 4x 4x         9x 9x 9x 9x 9x     9x 9x 6x 3x 3x         9x 2x 1x 1x         9x 2x 1x 1x         9x 2x 1x 1x       9x           6x                           117x 117x 1x         12x                   114x             114x 114x         117x 114x 114x                       68x   8x 7x           6x                           14x 14x 14x 14x 14x 14x 14x     14x 10x 7x 7x 7x   7x 7x           14x 7x 2x         14x 7x 2x         14x 7x 2x         14x 7x 1x       14x                      
/**
 * In-Memory Session Storage Backend
 *
 * Default storage for development and single-instance deployments.
 * Sessions are lost on server restart.
 */
 
import { OAuthSession, DeviceFlowState, AuthCodeFlowState, AuthorizationCode } from "../types";
import { SessionStorageBackend, SessionStorageStats } from "./types";
import { logger } from "../../logger";
 
export interface MemoryStorageOptions {
  /** Suppress initialization logging (used when wrapped by FileStorage) */
  silent?: boolean;
}
 
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>();
  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 cleanupIntervalId: ReturnType<typeof setInterval> | null = null;
  private silent: boolean;
 
  constructor(options?: MemoryStorageOptions) {
    this.silent = options?.silent ?? false;
  }
 
  async initialize(): Promise<void> {
    this.startCleanupInterval();
    if (!this.silent) {
      logger.info("Memory storage backend initialized");
    }
  }
 
  // Session operations
  async createSession(session: OAuthSession): Promise<void> {
    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);
    }
    logger.debug({ sessionId: session.id, userId: session.gitlabUserId }, "Session created");
  }
 
  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) {
      logger.warn({ sessionId }, "Attempted to update non-existent session");
      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() });
    logger.debug({ sessionId }, "Session updated");
    return true;
  }
 
  async deleteSession(sessionId: string): Promise<boolean> {
    const session = this.sessions.get(sessionId);
    if (!session) return false;
 
    if (session.mcpAccessToken) {
      this.tokenToSession.delete(session.mcpAccessToken);
    }
    if (session.mcpRefreshToken) {
      this.refreshTokenToSession.delete(session.mcpRefreshToken);
    }
 
    this.sessions.delete(sessionId);
    logger.debug({ sessionId }, "Session deleted");
    return true;
  }
 
  async getAllSessions(): Promise<OAuthSession[]> {
    return Array.from(this.sessions.values());
  }
 
  // Device flow operations
  async storeDeviceFlow(state: string, flow: DeviceFlowState): Promise<void> {
    this.deviceFlows.set(state, flow);
    logger.debug({ state, userCode: flow.userCode }, "Device flow stored");
  }
 
  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) logger.debug({ state }, "Device flow deleted");
    return deleted;
  }
 
  // Auth code flow operations
  async storeAuthCodeFlow(internalState: string, flow: AuthCodeFlowState): Promise<void> {
    this.authCodeFlows.set(internalState, flow);
    logger.debug({ internalState: internalState.substring(0, 8) + "..." }, "Auth code flow stored");
  }
 
  async getAuthCodeFlow(internalState: string): Promise<AuthCodeFlowState | undefined> {
    return this.authCodeFlows.get(internalState);
  }
 
  async deleteAuthCodeFlow(internalState: string): Promise<boolean> {
    const deleted = this.authCodeFlows.delete(internalState);
    if (deleted) {
      logger.debug(
        { internalState: internalState.substring(0, 8) + "..." },
        "Auth code flow deleted"
      );
    }
    return deleted;
  }
 
  // Authorization code operations
  async storeAuthCode(code: AuthorizationCode): Promise<void> {
    this.authCodes.set(code.code, code);
    logger.debug({ code: code.code.substring(0, 8) + "..." }, "Auth code stored");
  }
 
  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) logger.debug({ code: code.substring(0, 8) + "..." }, "Auth code deleted");
    return deleted;
  }
 
  // MCP session mapping
  async associateMcpSession(mcpSessionId: string, oauthSessionId: string): Promise<void> {
    this.mcpSessionToOAuthSession.set(mcpSessionId, oauthSessionId);
    logger.debug(
      { mcpSessionId, oauthSessionId: oauthSessionId.substring(0, 8) + "..." },
      "MCP session associated with OAuth session"
    );
  }
 
  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) logger.debug({ mcpSessionId }, "MCP session association removed");
    return deleted;
  }
 
  // Cleanup
  async cleanup(): Promise<void> {
    const now = Date.now();
    let expiredSessions = 0;
    let expiredDeviceFlows = 0;
    let expiredAuthCodeFlows = 0;
    let expiredAuthCodes = 0;
 
    // Clean up expired sessions (7 days max age)
    const maxAge = 7 * 24 * 60 * 60 * 1000;
    for (const [id, session] of this.sessions) {
      if (session.createdAt + maxAge < now) {
        await this.deleteSession(id);
        expiredSessions++;
      }
    }
 
    // Clean up expired device flows
    for (const [state, flow] of this.deviceFlows) {
      if (flow.expiresAt < now) {
        this.deviceFlows.delete(state);
        expiredDeviceFlows++;
      }
    }
 
    // Clean up expired auth code flows
    for (const [state, flow] of this.authCodeFlows) {
      if (flow.expiresAt < now) {
        this.authCodeFlows.delete(state);
        expiredAuthCodeFlows++;
      }
    }
 
    // Clean up expired auth codes
    for (const [code, auth] of this.authCodes) {
      if (auth.expiresAt < now) {
        this.authCodes.delete(code);
        expiredAuthCodes++;
      }
    }
 
    if (
      expiredSessions > 0 ||
      expiredDeviceFlows > 0 ||
      expiredAuthCodeFlows > 0 ||
      expiredAuthCodes > 0
    ) {
      logger.debug(
        {
          expiredSessions,
          expiredDeviceFlows,
          expiredAuthCodeFlows,
          expiredAuthCodes,
          remainingSessions: this.sessions.size,
        },
        "Memory storage cleanup completed"
      );
    }
  }
 
  async close(): Promise<void> {
    this.stopCleanupInterval();
    if (!this.silent) {
      logger.info("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 => logger.error({ err }, "Cleanup error"));
      },
      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 }>;
  } {
    return {
      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 }>;
  }): void {
    // Clear existing data
    this.sessions.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);
        Eif (session.mcpAccessToken) {
          this.tokenToSession.set(session.mcpAccessToken, session.id);
        }
        Eif (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);
      }
    }
 
    logger.info(
      {
        sessions: this.sessions.size,
        deviceFlows: this.deviceFlows.size,
        authCodeFlows: this.authCodeFlows.size,
        authCodes: this.authCodes.size,
      },
      "Data imported into memory storage"
    );
  }
}