Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

27.3 KB
Raw Blame
import net from "node:net";

import type WebSocket from "ws";

import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gateway-v2-types";
import { PamAccountType } from "@app/ee/services/pam/pam-enums";
import { enforceMfa } from "@app/ee/services/pam/pam-mfa";
import { resolveAccessControls } from "@app/ee/services/pam/pam-policies";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { setupGatewayProxy, withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { TUserDALFactory } from "@app/services/user/user-dal";

import { TPamAccessRequestServiceFactory } from "../pam-access-request/pam-access-request-service";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
import {
  extractGatewayTarget,
  getAccountAccessibilityIssues,
  PamAccountAccessibilityIssue,
  resolveSelectedHost,
  webAccessUnavailableReason
} from "../pam-account/pam-account-schemas";
import { assertUserStillActiveInOrg } from "../pam-session/pam-session-access-fns";
import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";
import { reportPamSessionEnded } from "../pam-session/pam-session-fns";
import {
  PAM_CANCELLATION_FLUSH_TIMEOUT_MS,
  PamAccessMethod,
  PamSessionEndReason,
  PamSessionStatus
} from "../pam/pam-enums";
import { checkAccountAccess, getLaunchAccessRemainingMs } from "../pam/pam-permission";
import { SESSION_HANDLERS } from "./pam-session-handlers";
import {
  DEFAULT_WEB_SESSION_DURATION_MS,
  MAX_WEB_SESSIONS_PER_USER,
  SessionEndReason,
  TEarlyBufferedMsg,
  TerminalServerMessageType,
  TIssueWebSocketTicketDTO,
  TSessionContext,
  TSessionHandlerResult,
  TWebSocketServerMessage,
  WebSocketServerMessageSchema,
  WS_IDLE_TIMEOUT_MS,
  WS_PING_INTERVAL_MS
} from "./pam-web-access-types";

type TPamWebAccessServiceFactoryDep = {
  pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithDetails">;
  pamAccessRequestService: Pick<TPamAccessRequestServiceFactory, "checkGrant">;
  permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;
  auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
  tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
  pamSessionDAL: Pick<
    TPamSessionDALFactory,
    | "create"
    | "endSessionById"
    | "activateSession"
    | "countActiveWebSessions"
    | "endExpiredWebSessions"
    | "isSessionTerminated"
    | "updateById"
    | "transaction"
  >;
  membershipDAL: Pick<TMembershipDALFactory, "lockOrgMembershipForUser" | "findResourceMembershipsForActor">;
  membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
  gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
  gatewayPoolService: Pick<
    TGatewayPoolServiceFactory,
    "resolveEffectiveGatewayId" | "runWithPoolFailover" | "assertGatewayBindingInOrg"
  >;
  kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
  userDAL: Pick<TUserDALFactory, "findById">;
  mfaSessionService: Pick<
    TMfaSessionServiceFactory,
    "createMfaSession" | "getMfaSession" | "deleteMfaSession" | "sendMfaCode"
  >;
  orgDAL: Pick<TOrgDALFactory, "findOrgById" | "findById" | "lockActorsForOrgAccess" | "findActorsWithActiveOrgAccess">;
  telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
};

export type TPamWebAccessServiceFactory = ReturnType<typeof pamWebAccessServiceFactory>;

type THandleWebSocketConnectionDTO = {
  socket: WebSocket;
  accountId: string;
  projectId: string;
  orgId: string;
  accountName: string;
  auditLogInfo: AuditLogInfo;
  userId: string;
  actorEmail: string;
  actorName: string;
  actorIp: string;
  actorUserAgent: string;
  reason: string | null | undefined;
  maxSessionDurationMs?: number;
  selectedHost?: string | null;
  preAuthMessages: TEarlyBufferedMsg[];
  preAuthHandler: (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => void;
};

export const pamWebAccessServiceFactory = ({
  pamAccountDAL,
  pamAccessRequestService,
  permissionService,
  auditLogService,
  tokenService,
  pamSessionDAL,
  gatewayV2Service,
  gatewayPoolService,
  kmsService,
  userDAL,
  mfaSessionService,
  orgDAL,
  membershipDAL,
  membershipRoleDAL,
  telemetryService
}: TPamWebAccessServiceFactoryDep) => {
  const decrypt = async (projectId: string, blob: Buffer): Promise<Record<string, unknown>> => {
    const { decryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
    return JSON.parse(decryptor({ cipherTextBlob: blob }).toString("utf-8")) as Record<string, unknown>;
  };

  const sendMessage = (socket: WebSocket, message: TWebSocketServerMessage): void => {
    try {
      if (socket.readyState === socket.OPEN) {
        const parsed = WebSocketServerMessageSchema.parse(message);
        socket.send(JSON.stringify(parsed));
      }
    } catch (err) {
      logger.error(err, "Failed to send WebSocket message");
    }
  };

  const sendSessionEndAndClose = (socket: WebSocket, reason: SessionEndReason): void => {
    try {
      if (socket.readyState === socket.OPEN) {
        const parsed = WebSocketServerMessageSchema.parse({ type: TerminalServerMessageType.SessionEnd, reason });
        socket.send(JSON.stringify(parsed), () => {
          socket.close();
        });
        return;
      }
    } catch (err) {
      logger.error(err, "Failed to send session end message");
    }
    socket.close();
  };

  const enforceRecordingConfig = (account: Parameters<typeof getAccountAccessibilityIssues>[0]) => {
    const issues = getAccountAccessibilityIssues(account);
    if (issues.includes(PamAccountAccessibilityIssue.NoRecordingConfig)) {
      throw new BadRequestError({
        message: "S3 recording must be configured before launching this account"
      });
    }
  };

  const issueWebSocketTicket = async ({
    accountId,
    projectId,
    orgId,
    actor,
    actorEmail,
    actorName,
    tokenVersionId,
    accessVersion,
    auditLogInfo,
    reason,
    mfaSessionId,
    selectedHost
  }: TIssueWebSocketTicketDTO) => {
    const account = await pamAccountDAL.findByIdWithDetails(accountId);
    if (!account || account.projectId !== projectId) {
      throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
    }

    if (!SESSION_HANDLERS[account.accountType as PamAccountType]) {
      throw new BadRequestError({ message: "Web access is not supported for this account type" });
    }

    const policy = resolveAccessControls(account.templatePolicies);
    const { requiresApproval } = policy;

    // Approval is a layer on top of standing access: gated accounts require LaunchSessions AND an
    // approved grant, so losing LaunchSessions blocks launch even while a grant is still active.
    await checkAccountAccess(
      permissionService,
      accountId,
      account.folderId,
      projectId,
      ResourcePermissionPamResourceActions.LaunchSessions,
      {
        actorId: actor.id,
        actor: actor.type,
        actorOrgId: actor.orgId,
        actorAuthMethod: actor.authMethod
      }
    );

    let grantRemainingMs: number | null = null;
    if (requiresApproval) {
      const grant = await pamAccessRequestService.checkGrant({
        // Web access is JWT-only, so the actor is always a user
        actorId: actor.id,
        actor: ActorType.USER,
        accountId,
        accountFolderId: account.folderId,
        projectId
      });
      if (!grant) {
        throw new ForbiddenRequestError({ name: "PAM_APPROVAL_REQUIRED", message: "Access request required" });
      }
      // A null expiresAt means a never-expiring grant per the checkGrant contract
      if (grant.expiresAt) {
        grantRemainingMs = new Date(grant.expiresAt).getTime() - Date.now();
        if (grantRemainingMs <= 0) {
          throw new ForbiddenRequestError({ name: "PAM_GRANT_EXPIRED", message: "Your approved access has expired" });
        }
      }
    }

    const launchAccessRemainingMs = await getLaunchAccessRemainingMs(
      membershipDAL,
      membershipRoleDAL,
      projectId,
      account,
      {
        actor: actor.type,
        actorId: actor.id
      }
    );
    if (launchAccessRemainingMs !== null && launchAccessRemainingMs <= 0) {
      throw new ForbiddenRequestError({ message: "Your access to this account is no longer active" });
    }

    enforceRecordingConfig(account);

    const connectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);

    const webAccessBlocked = webAccessUnavailableReason(account.accountType as PamAccountType, connectionDetails);
    if (webAccessBlocked) {
      throw new BadRequestError({ message: webAccessBlocked });
    }

    const resolvedHost = resolveSelectedHost(account.accountType as PamAccountType, connectionDetails, selectedHost);

    const trimmedReason = reason?.trim() || null;

    if (policy.requireReason && !trimmedReason) {
      throw new BadRequestError({
        name: "PAM_REASON_REQUIRED",
        message: "A reason is required to access this account"
      });
    }

    if (policy.requireMfa) {
      await enforceMfa(
        { mfaSessionService, orgDAL, userDAL },
        {
          userId: actor.id,
          orgId: actor.orgId,
          actorEmail,
          accountId: account.id,
          mfaSessionId,
          tokenVersionId
        }
      );
    }

    let maxSessionDurationMs = policy.maxSessionDurationSeconds
      ? policy.maxSessionDurationSeconds * 1000
      : DEFAULT_WEB_SESSION_DURATION_MS;
    if (grantRemainingMs !== null) {
      maxSessionDurationMs = Math.min(maxSessionDurationMs, grantRemainingMs);
    }
    if (launchAccessRemainingMs !== null) {
      maxSessionDurationMs = Math.min(maxSessionDurationMs, launchAccessRemainingMs);
    }

    await pamSessionDAL.endExpiredWebSessions(actor.id, projectId);
    const activeCount = await pamSessionDAL.countActiveWebSessions(actor.id, projectId);
    if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {
      throw new BadRequestError({
        message: `You have reached the maximum of ${MAX_WEB_SESSIONS_PER_USER} active web access sessions. Close an existing session and try again.`
      });
    }

    const token = await tokenService.createTokenForUser({
      type: TokenType.TOKEN_PAM_WS_TICKET,
      userId: actor.id,
      payload: JSON.stringify({
        accountId,
        projectId,
        orgId,
        accountName: account.name,
        accountType: account.accountType,
        actorEmail,
        actorName,
        tokenVersionId,
        accessVersion,
        auditLogInfo,
        reason: trimmedReason,
        maxSessionDurationMs,
        selectedHost: resolvedHost
      })
    });

    await auditLogService.createAuditLog({
      ...auditLogInfo,
      orgId,
      projectId,
      event: {
        type: EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED,
        metadata: {
          accountId,
          resourceName: account.name,
          accountName: account.name
        }
      }
    });

    return { ticket: `${actor.id}:${token}` };
  };

  const handleWebSocketConnection = async ({
    socket,
    accountId,
    projectId,
    orgId,
    accountName,
    auditLogInfo,
    userId,
    actorEmail,
    actorName,
    actorIp,
    actorUserAgent,
    reason: accessReason,
    maxSessionDurationMs: policyDurationMs,
    selectedHost,
    preAuthMessages,
    preAuthHandler
  }: THandleWebSocketConnectionDTO): Promise<void> => {
    const earlyMessages: TEarlyBufferedMsg[] = preAuthMessages;
    const releaseEarlyBuffer = () => {
      socket.off("message", preAuthHandler);
    };

    let session: { id: string; accountId?: string | null } | null = null;
    let cleanedUp = false;
    let handlerResult: TSessionHandlerResult | null = null;
    let proxyServer: { port: number; cleanup: () => Promise<void> } | null = null;
    let sessionGatewayDetails: TGatewayV2ConnectionDetails | null = null;
    let expiryTimer: ReturnType<typeof setTimeout> | null = null;
    let pingInterval: ReturnType<typeof setInterval> | null = null;
    let idleTimer: ReturnType<typeof setTimeout> | null = null;

    const cleanup = async () => {
      if (expiryTimer) {
        clearTimeout(expiryTimer);
        expiryTimer = null;
      }
      if (pingInterval) {
        clearInterval(pingInterval);
        pingInterval = null;
      }
      if (idleTimer) {
        clearTimeout(idleTimer);
        idleTimer = null;
      }

      if (handlerResult) {
        try {
          await handlerResult.cleanup();
        } catch (err) {
          logger.debug(err, "Error in handler cleanup");
        } finally {
          handlerResult = null;
        }
      }

      if (proxyServer) {
        try {
          await proxyServer.cleanup();
        } catch (err) {
          logger.debug(err, "Error closing relay server");
        } finally {
          proxyServer = null;
        }
      }

      if (session) {
        const sessionId = session.id;
        try {
          const updated = await pamSessionDAL.endSessionById(sessionId);
          if (updated) {
            await auditLogService.createAuditLog({
              ...auditLogInfo,
              orgId,
              projectId,
              event: {
                type: EventType.PAM_SESSION_END,
                metadata: { sessionId, accountId: session.accountId ?? undefined, accountName }
              }
            });

            void reportPamSessionEnded({
              session: updated,
              orgId,
              endReason: PamSessionEndReason.Completed,
              telemetryService,
              userDAL
            });
          }
        } catch (err) {
          logger.error(err, `Failed to end session in DB [sessionId=${sessionId}]`);
        } finally {
          session = null;
        }
      }

      if (sessionGatewayDetails) {
        const details = sessionGatewayDetails;
        sessionGatewayDetails = null;
        void (async () => {
          try {
            await withGatewayV2Proxy(
              (port) =>
                new Promise<void>((resolve, reject) => {
                  // The ALPN signal is the connection itself, so the tunnel must outlive the forward.
                  const cancelSocket = net.connect(port, "127.0.0.1", () => {
                    cancelSocket.end();
                  });
                  cancelSocket.setTimeout(PAM_CANCELLATION_FLUSH_TIMEOUT_MS, () => {
                    cancelSocket.destroy();
                    resolve();
                  });
                  cancelSocket.on("close", () => resolve());
                  cancelSocket.on("error", reject);
                }),
              { ...details, protocol: GatewayProxyProtocol.PamSessionCancellation }
            );
          } catch (err) {
            logger.debug(err, "Session cancellation signal failed (best-effort)");
          }
        })();
      }

      cleanedUp = true;
    };

    try {
      const account = await pamAccountDAL.findByIdWithDetails(accountId);
      if (!account || account.projectId !== projectId) {
        throw new BadRequestError({ message: "Invalid account or project" });
      }

      const handlerEntry = SESSION_HANDLERS[account.accountType as PamAccountType];
      if (!handlerEntry) {
        throw new BadRequestError({ message: "Web access is not supported for this account type" });
      }

      enforceRecordingConfig(account);

      // The single-use ticket outlives its issuance check by up to 30s, so a grant revoked in the
      // meantime must be caught here; the revoke-time session sweep can't see sessions that don't
      // exist yet.
      const { requiresApproval } = resolveAccessControls(account.templatePolicies);
      let sessionDurationCapMs = policyDurationMs || DEFAULT_WEB_SESSION_DURATION_MS;
      if (requiresApproval) {
        const grant = await pamAccessRequestService.checkGrant({
          actorId: userId,
          actor: ActorType.USER,
          accountId,
          accountFolderId: account.folderId,
          projectId
        });
        if (!grant) {
          sendMessage(socket, {
            type: TerminalServerMessageType.Output,
            data: `${SessionEndReason.ApprovalRevoked}\n`
          });
          sendSessionEndAndClose(socket, SessionEndReason.ApprovalRevoked);
          return;
        }
        if (grant.expiresAt) {
          const grantRemainingMs = new Date(grant.expiresAt).getTime() - Date.now();
          if (grantRemainingMs <= 0) {
            sendMessage(socket, {
              type: TerminalServerMessageType.Output,
              data: `${SessionEndReason.ApprovalRevoked}\n`
            });
            sendSessionEndAndClose(socket, SessionEndReason.ApprovalRevoked);
            return;
          }
          sessionDurationCapMs = Math.min(sessionDurationCapMs, grantRemainingMs);
        }
      }

      const launchAccessRemainingMs = await getLaunchAccessRemainingMs(
        membershipDAL,
        membershipRoleDAL,
        projectId,
        account,
        {
          actor: ActorType.USER,
          actorId: userId
        }
      );
      if (launchAccessRemainingMs !== null) {
        if (launchAccessRemainingMs <= 0) {
          sendMessage(socket, {
            type: TerminalServerMessageType.Output,
            data: `${SessionEndReason.AccessRevoked}\n`
          });
          sendSessionEndAndClose(socket, SessionEndReason.AccessRevoked);
          return;
        }
        sessionDurationCapMs = Math.min(sessionDurationCapMs, launchAccessRemainingMs);
      }

      await gatewayPoolService.assertGatewayBindingInOrg({
        gatewayId: account.gatewayId ?? account.templateGatewayId,
        gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId,
        orgId
      });
      const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({
        gatewayId: account.gatewayId ?? account.templateGatewayId,
        gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId
      });
      if (!effectiveGatewayId) {
        throw new BadRequestError({ message: "Gateway not configured for this account" });
      }

      await pamSessionDAL.endExpiredWebSessions(userId, projectId);
      const activeCount = await pamSessionDAL.countActiveWebSessions(userId, projectId);
      if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {
        sendMessage(socket, {
          type: TerminalServerMessageType.Output,
          data: `${SessionEndReason.SessionLimitReached}\n`
        });
        sendSessionEndAndClose(socket, SessionEndReason.SessionLimitReached);
        return;
      }

      const rawConnectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);
      // Re-checked here: the account can lose its HTTP port between ticket issue and connect.
      const webAccessBlocked = webAccessUnavailableReason(account.accountType as PamAccountType, rawConnectionDetails);
      if (webAccessBlocked) {
        throw new BadRequestError({ message: webAccessBlocked });
      }
      const gatewayTarget = await extractGatewayTarget(account.accountType as PamAccountType, rawConnectionDetails);
      const targetHost = selectedHost || gatewayTarget.host;
      const credentials = await decrypt(projectId, account.encryptedCredentials);

      const user = await userDAL.findById(userId);
      const sessionDurationMs = sessionDurationCapMs;
      const expiresAt = new Date(Date.now() + sessionDurationMs);

      session = await pamSessionDAL.transaction(async (tx) => {
        await assertUserStillActiveInOrg({ orgId, userId, membershipDAL, orgDAL, tx });

        return pamSessionDAL.create(
          {
            status: PamSessionStatus.Starting,
            accessMethod: PamAccessMethod.Web,
            expiresAt,
            accountName,
            accountType: account.accountType,
            actorEmail,
            actorIp,
            actorName,
            actorUserAgent,
            projectId,
            accountId: account.id,
            userId,
            gatewayId: effectiveGatewayId,
            reason: accessReason?.trim() || null,
            folderName: account.folderName,
            selectedHost: targetHost
          },
          tx
        );
      });

      const createdSession = session;
      const isRdp = account.accountType === PamAccountType.Windows || account.accountType === PamAccountType.WindowsAd;

      // Certs are minted per gateway, so each attempt has to re-mint. `eager` opens the tunnel
      // during setup, so an unreachable gateway fails here where another member can still be tried.
      const attempt = await gatewayPoolService.runWithPoolFailover(
        {
          gatewayId: account.gatewayId ?? account.templateGatewayId,
          poolId: account.gatewayPoolId ?? account.templateGatewayPoolId
        },
        async (gatewayId) => {
          const attemptGatewayDetails = await gatewayV2Service.getPAMConnectionDetails({
            gatewayId,
            sessionId: createdSession.id,
            accountType: handlerEntry.gatewayAccountType,
            host: targetHost,
            port: gatewayTarget.port,
            duration: sessionDurationMs,
            actorMetadata: {
              id: userId,
              type: ActorType.USER,
              name: user?.email ?? ""
            },
            // The platform opens this tunnel itself, so no client version gates the transport.
            clientSupportsDirect: true
          });

          if (!attemptGatewayDetails) {
            throw new BadRequestError({ message: "Failed to obtain gateway connection details" });
          }

          return {
            gatewayDetails: attemptGatewayDetails,
            server: await setupGatewayProxy({
              protocol: isRdp ? GatewayProxyProtocol.PamRdpBrowser : GatewayProxyProtocol.Pam,
              ...attemptGatewayDetails,
              longLived: true,
              eager: true
            })
          };
        }
      );

      const { gatewayDetails } = attempt.result;
      proxyServer = attempt.result.server;

      // The tunnel is open from here rather than from whenever the session handler first dials, so
      // a socket that closed during setup has to be caught: its "close" fired before the listener
      // further down was attached, and nothing else would release the channel until session expiry.
      if (socket.readyState !== socket.OPEN) {
        await cleanup();
        return;
      }

      // The row was written against the first pick. Cancellation and credential fetch look the
      // session up by gateway, so it has to name the one that actually answered.
      if (attempt.gatewayId !== effectiveGatewayId) {
        await pamSessionDAL.updateById(createdSession.id, { gatewayId: attempt.gatewayId });
      }

      sessionGatewayDetails = gatewayDetails;

      const isNearSessionExpiry = () => Date.now() >= expiresAt.getTime() - 30_000;

      const boundSendMessage = (msg: TWebSocketServerMessage) => sendMessage(socket, msg);
      const boundSendSessionEnd = (reason: SessionEndReason) =>
        sendMessage(socket, { type: TerminalServerMessageType.SessionEnd, reason });
      const handlerCleanup = () => {
        if (!cleanedUp) void cleanup();
      };

      const ctx: TSessionContext = {
        socket,
        relayPort: proxyServer.port,
        resourceName: account.name,
        sessionId: session.id,
        sendMessage: boundSendMessage,
        sendSessionEnd: boundSendSessionEnd,
        isNearSessionExpiry,
        onCleanup: handlerCleanup,
        earlyMessages,
        releaseEarlyBuffer
      };

      try {
        handlerResult = await handlerEntry.handler(ctx, {
          connectionDetails: rawConnectionDetails,
          credentials
        });
      } finally {
        releaseEarlyBuffer();
      }

      // RDP sessions are activated by the gateway after credential exchange,
      // not by the web access service.
      if (!isRdp) {
        await pamSessionDAL.activateSession(session.id);
      }

      logger.info({ accountId, sessionId: session.id }, "Web access session established");

      await auditLogService.createAuditLog({
        ...auditLogInfo,
        orgId,
        projectId,
        event: {
          type: EventType.PAM_ACCOUNT_ACCESS,
          metadata: {
            accountId,
            resourceName: account.name,
            accountName,
            duration: expiresAt.toISOString(),
            reason: accessReason ?? undefined
          }
        }
      });

      const resetIdleTimer = () => {
        if (idleTimer) clearTimeout(idleTimer);
        idleTimer = setTimeout(() => {
          if (!cleanedUp) {
            void cleanup();
            sendSessionEndAndClose(socket, SessionEndReason.IdleTimeout);
          }
        }, WS_IDLE_TIMEOUT_MS);
      };

      resetIdleTimer();

      let isAlive = true;

      socket.on("pong", () => {
        isAlive = true;
      });

      pingInterval = setInterval(() => {
        if (!isAlive) {
          socket.terminate();
          return;
        }
        isAlive = false;
        if (socket.readyState === socket.OPEN) {
          socket.ping();
        }

        void (async () => {
          const sessionId = session?.id;
          if (!sessionId || cleanedUp) return;
          try {
            if (!(await pamSessionDAL.isSessionTerminated(sessionId)) || cleanedUp) return;
            await cleanup();
            sendSessionEndAndClose(socket, SessionEndReason.Terminated);
          } catch (err) {
            logger.error(err, `Failed to check session termination [sessionId=${sessionId}]`);
          }
        })();
      }, WS_PING_INTERVAL_MS);

      socket.on("message", () => {
        resetIdleTimer();
      });

      expiryTimer = setTimeout(() => {
        if (!cleanedUp) {
          void cleanup();
          sendSessionEndAndClose(socket, SessionEndReason.SessionCompleted);
        }
      }, sessionDurationMs);

      socket.on("close", () => {
        logger.info({ accountId, sessionId: session?.id }, "WebSocket connection closed");
        void cleanup();
      });

      socket.on("error", (err: Error) => {
        logger.error(err, "WebSocket error");
        void cleanup();
      });
    } catch (err) {
      logger.error(err, "Failed to establish web access session");
      await cleanup();
      sendSessionEndAndClose(socket, SessionEndReason.SetupFailed);
    }
  };

  return {
    issueWebSocketTicket,
    handleWebSocketConnection
  };
};