Skip to content

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

7.9 KB
Raw Blame
import { useState } from "react";
import { Link } from "@tanstack/react-router";
import { Copy, Globe, Rocket, Terminal } from "lucide-react";

import { createNotification } from "@app/components/notifications";
import {
  Button,
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Field,
  FieldLabel,
  IconButton,
  RadioGroup,
  RadioGroupItem
} from "@app/components/v3";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@app/components/v3/generic/Select";
import { useOrganization } from "@app/context";
import { TAccessiblePamAccount } from "@app/hooks/api/pam";
import { PamSheetTab } from "@app/hooks/usePamSheetState";

import { useAccountSheetDetails } from "./accountSheetDetails";
import { PamDetailSheet } from "./PamDetailSheet";

type Props = {
  account: TAccessiblePamAccount | null;
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
};

type LaunchMethod = "browser" | "cli";

const LaunchTab = ({
  account,
  supportsWebAccess,
  webAccessUnavailableReason,
  hosts
}: {
  account: TAccessiblePamAccount;
  supportsWebAccess: boolean;
  webAccessUnavailableReason: string | null;
  hosts: string[];
}) => {
  const { currentOrg } = useOrganization();
  const browserDisabled = Boolean(webAccessUnavailableReason);
  const [method, setMethod] = useState<LaunchMethod>(supportsWebAccess ? "browser" : "cli");
  // The reason arrives with the account, after this state is seeded, so the render has to re-decide.
  const effectiveMethod: LaunchMethod = browserDisabled ? "cli" : method;

  const needsHost = hosts.length > 1;
  const [selectedHost, setSelectedHost] = useState<string | undefined>(
    needsHost ? undefined : hosts[0]
  );
  const hostMissing = needsHost && !selectedHost;

  const cliHost = selectedHost ?? (needsHost ? "HOST" : undefined);
  const cliCommand = `infisical pam access ${account.folderName}/${account.name}${
    cliHost ? ` --target '${cliHost}'` : ""
  } --domain '${window.location.origin}'`;
  const handleCopyCommand = async () => {
    await navigator.clipboard.writeText(cliCommand);
    createNotification({ text: "Command copied to clipboard", type: "success" });
  };

  return (
    <div className="flex flex-1 flex-col gap-4 p-4">
      <Card>
        <CardHeader className="border-b">
          <CardTitle className="text-base">Launch Session</CardTitle>
          <CardDescription>Choose how to connect to this account.</CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-5">
          {needsHost && (
            <div>
              <p className="mb-2.5 text-sm font-medium text-foreground">Host</p>
              <Select value={selectedHost ?? ""} onValueChange={setSelectedHost}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="Select a host" />
                </SelectTrigger>
                <SelectContent position="popper">
                  {hosts.map((host) => (
                    <SelectItem key={host} value={host}>
                      {host}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {supportsWebAccess && (
            <div>
              <p className="mb-3 text-sm font-medium text-foreground">Launch method</p>
              <RadioGroup
                value={effectiveMethod}
                onValueChange={(value) => setMethod(value as LaunchMethod)}
                className="grid-cols-2 gap-3"
              >
                <FieldLabel htmlFor="launch-browser" variant="pam">
                  <Field orientation="horizontal" className="items-center gap-3">
                    <Globe className="size-5 shrink-0 text-foreground" />
                    <div className="flex-1 text-left">
                      <p className="text-sm font-medium text-foreground">Browser</p>
                      <p className="text-xs text-muted">
                        {webAccessUnavailableReason ?? "Connect directly from your browser."}
                      </p>
                    </div>
                    <RadioGroupItem
                      id="launch-browser"
                      value="browser"
                      disabled={browserDisabled}
                      className="sr-only"
                    />
                  </Field>
                </FieldLabel>
                <FieldLabel htmlFor="launch-cli" variant="pam">
                  <Field orientation="horizontal" className="items-center gap-3">
                    <Terminal className="size-5 shrink-0 text-foreground" />
                    <div className="flex-1 text-left">
                      <p className="text-sm font-medium text-foreground">CLI</p>
                      <p className="text-xs text-muted">
                        Use a custom client with the Infisical CLI.
                      </p>
                    </div>
                    <RadioGroupItem id="launch-cli" value="cli" className="sr-only" />
                  </Field>
                </FieldLabel>
              </RadioGroup>
            </div>
          )}

          {effectiveMethod === "browser" && (
            <div>
              <p className="mb-2.5 text-sm text-foreground">Launch browser client</p>
              {hostMissing ? (
                <Button variant="pam" className="w-full" isDisabled>
                  <Rocket className="size-4" />
                  Connect in Browser
                </Button>
              ) : (
                <Button variant="pam" className="w-full" asChild>
                  <Link
                    to="/organizations/$orgId/pam/accounts/$accountType/$accountId/access"
                    params={{
                      orgId: currentOrg.id,
                      accountType: account.accountType,
                      accountId: account.id
                    }}
                    search={{ host: selectedHost }}
                    target="_blank"
                  >
                    <Rocket className="size-4" />
                    Connect in Browser
                  </Link>
                </Button>
              )}
            </div>
          )}

          {effectiveMethod === "cli" && (
            <div>
              <p className="mb-2.5 text-sm text-foreground">Run this command</p>
              <div className="flex items-center justify-between gap-3 rounded-md border border-border bg-container px-4 py-3">
                <code className="font-mono text-sm break-all text-foreground">
                  <span className="text-product-pam">$</span> {cliCommand}
                </code>
                <IconButton
                  variant="ghost"
                  aria-label="Copy command"
                  onClick={handleCopyCommand}
                  className="shrink-0 text-muted hover:text-foreground"
                >
                  <Copy className="size-4" />
                </IconButton>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export const LaunchSessionSheet = ({ account, isOpen, onOpenChange }: Props) => {
  const { typeMeta, typeName, subtitle, metadata, hosts, webAccessUnavailableReason } =
    useAccountSheetDetails(account, isOpen);

  if (!account) return null;

  const supportsWebAccess = Boolean(typeMeta?.supportsWebAccess);

  return (
    <PamDetailSheet
      isOpen={isOpen}
      onOpenChange={onOpenChange}
      accountType={account.accountType}
      title={account.name}
      subtitle={subtitle}
      typeBadge={typeName}
      metadata={metadata}
      tabs={[
        {
          value: PamSheetTab.Launch,
          label: "Launch",
          icon: <Rocket className="mr-1.5 size-4" />,
          content: (
            <LaunchTab
              account={account}
              supportsWebAccess={supportsWebAccess}
              webAccessUnavailableReason={webAccessUnavailableReason}
              hosts={hosts}
            />
          )
        }
      ]}
    />
  );
};