Skip to content

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

18.7 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from "react";
import { FitAddon } from "@xterm/addon-fit";
import { WebLinksAddon } from "@xterm/addon-web-links";
import { type ITheme, Terminal } from "@xterm/xterm";
import { Readline } from "xterm-readline";

import { type ResolvedTheme, useTheme } from "@app/components/v3/platform/ThemeProvider";
import { apiRequest } from "@app/config/request";
import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession/types";
import { PamAccountType } from "@app/hooks/api/pam";

import { WebSocketServerMessageSchema, WsMessageType } from "./web-access-types";

import "@xterm/xterm/css/xterm.css";

type UseWebAccessSessionOptions = {
  accountId: string;
  accountType: string;
  reason?: string;
  mfaSessionId?: string;
  onSessionEnd?: (endReason?: string) => void;
};

const DARK_TERMINAL_THEME: ITheme = {
  background: "#0d1117",
  foreground: "#c9d1d9",
  cursor: "#58a6ff",
  cursorAccent: "#0d1117",
  selectionBackground: "#264f78",
  black: "#0d1117",
  red: "#ff7b72",
  green: "#3fb950",
  yellow: "#d29922",
  blue: "#58a6ff",
  magenta: "#bc8cff",
  cyan: "#76e3ea",
  white: "#c9d1d9",
  brightBlack: "#484f58",
  brightRed: "#ffa198",
  brightGreen: "#56d364",
  brightYellow: "#e3b341",
  brightBlue: "#79c0ff",
  brightMagenta: "#d2a8ff",
  brightCyan: "#b3f0ff",
  brightWhite: "#f0f6fc"
};

const getLightTerminalTheme = (): ITheme => {
  const styles = getComputedStyle(document.documentElement);
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");

  const resolveToken = (token: string, fallback: string) => {
    const value = styles.getPropertyValue(token).trim();
    if (!value || !context) return fallback;
    context.fillStyle = fallback;
    context.fillStyle = value;
    return context.fillStyle;
  };

  const background = resolveToken("--color-background", "#f7f7f7");
  const foreground = resolveToken("--color-foreground", "#19191c");
  const muted = resolveToken("--color-muted", "#707174");
  const danger = resolveToken("--color-danger", "#b42318");
  const success = resolveToken("--color-success", "#1a7f37");
  const warning = resolveToken("--color-warning", "#8a5a00");
  const info = resolveToken("--color-info", "#0969da");
  const magenta = resolveToken("--color-product-ss", "#8250df");
  const cyan = resolveToken("--color-product-kms", "#087f5b");

  return {
    background,
    foreground,
    cursor: resolveToken("--color-project", "#4f6f00"),
    cursorAccent: background,
    selectionBackground: resolveToken("--color-surface-selected", "#d8dee4"),
    black: foreground,
    red: danger,
    green: success,
    yellow: warning,
    blue: info,
    magenta,
    cyan,
    white: muted,
    brightBlack: muted,
    brightRed: danger,
    brightGreen: success,
    brightYellow: warning,
    brightBlue: info,
    brightMagenta: magenta,
    brightCyan: cyan,
    brightWhite: foreground
  };
};

const getTerminalTheme = (resolvedTheme: ResolvedTheme): ITheme =>
  resolvedTheme === "light" ? getLightTerminalTheme() : DARK_TERMINAL_THEME;

export const useWebAccessSession = ({
  accountId,
  accountType,
  reason,
  mfaSessionId,
  onSessionEnd
}: UseWebAccessSessionOptions) => {
  const { resolvedTheme } = useTheme();
  const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);
  const terminalRef = useRef<Terminal | null>(null);
  const fitAddonRef = useRef<FitAddon | null>(null);
  const isWidenedRef = useRef(false);
  const inputBufferRef = useRef("");
  const currentPromptRef = useRef("");
  const promptCallbackRef = useRef<((input: string) => void) | null>(null);
  const readlineRef = useRef<Readline | null>(null);
  const readLoopActiveRef = useRef(false);
  const nextPromptResolverRef = useRef<((prompt: string) => void) | null>(null);
  const nextPromptRejecterRef = useRef<((reason: Error) => void) | null>(null);
  const resolvedThemeRef = useRef(resolvedTheme);
  resolvedThemeRef.current = resolvedTheme;

  const onSessionEndRef = useRef(onSessionEnd);
  const endReasonRef = useRef<string | undefined>(undefined);
  const submittedReasonRef = useRef<string | undefined>(reason);
  const mfaSessionIdRef = useRef<string | undefined>(mfaSessionId);

  useEffect(() => {
    onSessionEndRef.current = onSessionEnd;
  }, [onSessionEnd]);

  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.options.theme = getTerminalTheme(resolvedTheme);
    }
  }, [resolvedTheme]);

  const adjustWidthForOutput = useCallback(
    (output: string, terminal: Terminal, fitAddon: FitAddon, container: HTMLDivElement) => {
      const lines = output.split("\n");
      const longestLine = Math.max(...lines.map((l) => l.length));

      if (longestLine <= terminal.cols) return;

      // eslint-disable-next-line no-underscore-dangle
      const cellWidth = (terminal as any)._core._renderService.dimensions.css.cell.width as number;
      if (!cellWidth) return;

      const MAX_COLS = 10000;
      const neededCols = Math.min(longestLine + 2, MAX_COLS);
      const neededWidth = neededCols * cellWidth;

      const currentWidth = container.getBoundingClientRect().width;
      if (neededWidth <= currentWidth) return;

      // eslint-disable-next-line no-param-reassign
      container.style.width = `${neededWidth}px`;
      fitAddon.fit();
      isWidenedRef.current = true;
    },
    []
  );

  // TODO: refactor when the list of supported resource type grows
  const isSSH = accountType === PamAccountType.SSH;

  // --- WebSocket lifecycle (imperative) ---

  const openWebSocket = useCallback(
    (terminal: Terminal, ticket: string) => {
      const { protocol, host } = window.location;
      const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
      const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;
      endReasonRef.current = undefined;
      const ws = new WebSocket(wsUrl);
      wsRef.current = ws;

      const waitForNextPrompt = (): Promise<string> => {
        return new Promise<string>((resolve, reject) => {
          nextPromptResolverRef.current = resolve;
          nextPromptRejecterRef.current = reject;
        });
      };

      const runReadLoop = async (rl: Readline, initialPrompt: string) => {
        readLoopActiveRef.current = true;
        let prompt = initialPrompt;

        while (readLoopActiveRef.current) {
          let line: string;
          try {
            // eslint-disable-next-line no-await-in-loop -- intentional sequential read loop
            line = await rl.read(prompt);
          } catch {
            break;
          }

          if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
            break;
          }

          wsRef.current.send(JSON.stringify({ type: WsMessageType.Input, data: line }));

          try {
            // eslint-disable-next-line no-await-in-loop
            prompt = await waitForNextPrompt();
          } catch {
            break;
          }
        }

        readLoopActiveRef.current = false;
      };

      ws.onmessage = (event) => {
        let raw: unknown;
        try {
          raw = JSON.parse(event.data as string);
        } catch {
          return;
        }
        const parsed = WebSocketServerMessageSchema.safeParse(raw);
        if (!parsed.success) return;
        const msg = parsed.data;

        if (msg.type === WsMessageType.Ready) {
          setIsConnected(true);

          // Send initial terminal dimensions so the remote PTY knows the correct size
          if (isSSH && terminalRef.current) {
            ws.send(
              JSON.stringify({
                type: WsMessageType.Resize,
                data: JSON.stringify({
                  rows: terminalRef.current.rows,
                  cols: terminalRef.current.cols
                })
              })
            );
          }

          if (!isSSH && readlineRef.current) {
            const rl = readlineRef.current;
            if (msg.data) {
              rl.print(msg.data.replace(/\r?\n/g, "\r\n"));
            }
            runReadLoop(rl, msg.prompt || "=> ");
          } else if (!isSSH) {
            if (msg.data) terminal.write(msg.data.replace(/\r?\n/g, "\r\n"));
            if (msg.prompt) terminal.write(msg.prompt);
          }

          setTimeout(() => terminal.focus(), 100);
          return;
        }

        if (msg.type === WsMessageType.SessionEnd) {
          endReasonRef.current = msg.reason;
          terminal.write(`\r\n${msg.reason.replace(/\r?\n/g, "\r\n")}\r\n`);
          return;
        }

        if (msg.data) {
          if (!isSSH && containerEl && fitAddonRef.current) {
            adjustWidthForOutput(msg.data, terminal, fitAddonRef.current, containerEl);
          }
          if (isSSH) {
            terminal.write(msg.data);
          } else if (readlineRef.current) {
            readlineRef.current.print(msg.data.replace(/\r?\n/g, "\r\n"));
          }
        }

        if (msg.prompt && !isSSH) {
          if (nextPromptResolverRef.current) {
            const resolve = nextPromptResolverRef.current;
            nextPromptResolverRef.current = null;
            nextPromptRejecterRef.current = null;
            resolve(msg.prompt);
          }
        }
      };

      ws.onclose = () => {
        wsRef.current = null;
        readLoopActiveRef.current = false;

        if (nextPromptRejecterRef.current) {
          nextPromptRejecterRef.current(new Error("disconnected"));
          nextPromptResolverRef.current = null;
          nextPromptRejecterRef.current = null;
        }

        if (terminalRef.current) {
          terminalRef.current.options.disableStdin = true;
        }
        setIsConnected(false);
        onSessionEndRef.current?.(endReasonRef.current);
      };

      ws.onerror = () => {
        // no-op: onclose always fires after onerror
      };
    },
    [accountId, containerEl, adjustWidthForOutput, isSSH]
  );

  const connect = useCallback(async () => {
    const terminal = terminalRef.current;
    if (!terminal) return;

    inputBufferRef.current = "";
    currentPromptRef.current = "";

    const prompt = (message: string): Promise<string> => {
      if (!isSSH && readlineRef.current) {
        return readlineRef.current.read(message);
      }
      return new Promise((resolve) => {
        terminal.write(message);
        promptCallbackRef.current = resolve;
      });
    };

    try {
      const { data } = await apiRequest.post<{ ticket: string }>(
        `/api/v1/pam/accounts/${accountId}/web-access-ticket`,
        { reason: submittedReasonRef.current, mfaSessionId: mfaSessionIdRef.current }
      );
      mfaSessionIdRef.current = undefined;
      if (containerEl) {
        containerEl.style.width = "";
        isWidenedRef.current = false;
      }
      if (fitAddonRef.current) fitAddonRef.current.fit();

      terminal.reset();
      openWebSocket(terminal, data.ticket);
    } catch (err: unknown) {
      const axiosErr = err as {
        response?: {
          data?: {
            error?: string;
            details?: {
              mfaSessionId?: string;
              mfaMethod?: string;
            };
          };
        };
      };

      if (axiosErr?.response?.data?.error === "SESSION_MFA_REQUIRED") {
        const newMfaSessionId = axiosErr.response!.data!.details?.mfaSessionId;

        if (!newMfaSessionId) {
          terminal.write("\r\nMFA session could not be created. Please try again.\r\n");
          return;
        }

        const mfaUrl = `${window.location.origin}/mfa-session/${newMfaSessionId}`;

        // Try to open MFA verification in a new window.
        const popup = window.open(mfaUrl, "_blank");

        terminal.write(
          "\r\nMFA verification required. Complete verification in the opened window or via this link:\r\n"
        );
        terminal.write(`\r\n  ${mfaUrl}\r\n\r\n`);
        terminal.write("Waiting for verification...\r\n");

        // Poll for MFA session to become ACTIVE
        const MFA_POLL_INTERVAL = 2000;
        const MFA_TIMEOUT = 5 * 60 * 1000; // 5 minutes
        const startTime = Date.now();

        const mfaVerified = await new Promise<boolean>((resolve) => {
          const interval = setInterval(async () => {
            if (Date.now() - startTime > MFA_TIMEOUT) {
              clearInterval(interval);
              resolve(false);
              return;
            }

            try {
              const resp = await apiRequest.get<TMfaSessionStatusResponse>(
                `/api/v2/mfa-sessions/${newMfaSessionId}/status`
              );
              if (resp.data.status === MfaSessionStatus.ACTIVE) {
                clearInterval(interval);
                resolve(true);
              }
            } catch {
              clearInterval(interval);
              resolve(false);
            }
          }, MFA_POLL_INTERVAL);
        });

        // Close popup if still open
        if (popup && !popup.closed) {
          popup.close();
        }

        if (!mfaVerified) {
          terminal.write("\r\nMFA verification timed out or failed. Please try again.\r\n");
          return;
        }

        // Retry ticket request with verified MFA session
        try {
          if (containerEl) {
            containerEl.style.width = "";
            isWidenedRef.current = false;
          }
          if (fitAddonRef.current) fitAddonRef.current.fit();
          terminal.reset();
          const { data: retryData } = await apiRequest.post<{ ticket: string }>(
            `/api/v1/pam/accounts/${accountId}/web-access-ticket`,
            { mfaSessionId: newMfaSessionId, reason: submittedReasonRef.current }
          );
          openWebSocket(terminal, retryData.ticket);
        } catch {
          terminal.write("\r\nFailed to connect after MFA verification. Please try again.\r\n");
        }
        return;
      }

      if (axiosErr?.response?.data?.error === "PAM_REASON_REQUIRED") {
        terminal.write("\r\nThis account requires a reason for access.\r\n");

        const reasonInput = await prompt("\r\nEnter reason: ");

        if (!reasonInput.trim()) {
          terminal.write("\r\nA reason is required to continue.\r\n");
          await prompt("\r\nPress Enter to try again.");
          terminal.reset();
          connect();
          return;
        }

        submittedReasonRef.current = reasonInput.trim();
        terminal.reset();
        connect();
        return;
      }

      terminal.write("\r\nFailed to connect. Please close and try again.\r\n");
    }
  }, [accountId, containerEl, openWebSocket]);

  const disconnect = useCallback(() => {
    const ws = wsRef.current;
    wsRef.current = null;

    if (ws) {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: WsMessageType.Control, data: "quit" }));
      }
      ws.close();
    }
  }, []);

  const reconnect = useCallback(() => {
    disconnect();
    if (containerEl) {
      containerEl.style.width = "";
      isWidenedRef.current = false;
    }
    if (fitAddonRef.current) fitAddonRef.current.fit();
    if (terminalRef.current) {
      terminalRef.current.reset();
      terminalRef.current.options.disableStdin = false;
    }
    connect();
  }, [disconnect, connect, containerEl]);

  // --- Terminal lifecycle (effect, tied to containerEl) ---

  useEffect(() => {
    if (!containerEl || !accountId) return undefined;

    const terminal = new Terminal({
      cursorBlink: true,
      fontSize: 14,
      fontFamily: getComputedStyle(containerEl).getPropertyValue("--font-mono").trim(),
      theme: getTerminalTheme(resolvedThemeRef.current),
      scrollback: 10000,
      allowProposedApi: true
    });

    const fitAddon = new FitAddon();
    const webLinksAddon = new WebLinksAddon();
    terminal.loadAddon(fitAddon);
    terminal.loadAddon(webLinksAddon);
    terminal.open(containerEl);
    fitAddon.fit();
    terminalRef.current = terminal;
    fitAddonRef.current = fitAddon;

    // Wire terminal keyboard input — reads wsRef/inputBufferRef/currentPromptRef dynamically
    if (isSSH) {
      // SSH: raw keystroke forwarding
      terminal.onData((data) => {
        // Handle internal prompts (MFA/approval) even in SSH mode
        if (promptCallbackRef.current) {
          if (data === "\r") {
            terminal.write("\r\n");
            const cb = promptCallbackRef.current;
            promptCallbackRef.current = null;
            cb(inputBufferRef.current);
            inputBufferRef.current = "";
          } else if (data === "\x7f") {
            if (inputBufferRef.current.length > 0) {
              inputBufferRef.current = inputBufferRef.current.slice(0, -1);
              terminal.write("\b \b");
            }
          } else {
            inputBufferRef.current += data;
            terminal.write(data);
          }
        } else if (wsRef.current?.readyState === WebSocket.OPEN) {
          // Send raw keystroke to server — no local echo, no buffering
          wsRef.current.send(JSON.stringify({ type: WsMessageType.Input, data }));
        }
      });

      // Send terminal resize events to the server
      terminal.onResize(({ rows, cols }) => {
        if (wsRef.current?.readyState === WebSocket.OPEN) {
          wsRef.current.send(
            JSON.stringify({
              type: WsMessageType.Resize,
              data: JSON.stringify({ rows, cols })
            })
          );
        }
      });
    } else {
      // Redis: use xterm-readline for full line-editing support
      const readlineAddon = new Readline();
      terminal.loadAddon(readlineAddon);
      readlineRef.current = readlineAddon;

      // Ctrl+C: send clear-buffer to backend (readline handles visual reset internally)
      terminal.onKey(({ domEvent }) => {
        if (domEvent.ctrlKey && domEvent.key === "c") {
          if (wsRef.current?.readyState === WebSocket.OPEN) {
            wsRef.current.send(
              JSON.stringify({ type: WsMessageType.Control, data: "clear-buffer" })
            );
          }
        }
      });
    }

    // Resize handling
    const handleResize = () => fitAddon.fit();
    const resizeObserver = new ResizeObserver(handleResize);
    resizeObserver.observe(containerEl);
    window.addEventListener("resize", handleResize);

    // Auto-connect
    connect();

    return () => {
      readLoopActiveRef.current = false;
      readlineRef.current = null;
      terminalRef.current = null;
      fitAddonRef.current = null;
      window.removeEventListener("resize", handleResize);
      resizeObserver.disconnect();
      disconnect();
      terminal.dispose();
      setIsConnected(false);
    };
  }, [containerEl, accountId, connect, disconnect, isSSH]);

  const containerRef = useCallback((node: HTMLDivElement | null) => {
    setContainerEl(node);
  }, []);

  return { containerRef, isConnected, disconnect, reconnect };
};