Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pam): azure cli access
x5512e14d9a4f
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.tsindex 6b22e01ff4..e521248231 100644--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts@@ -547,6 +547,59 @@ export const ACCOUNT_TYPE_CONFIGS = {tooltip: "The ARN of the IAM role the user will assume when accessing this account."}}+ },++ [PamAccountType.AzureCli]: {+ name: "Azure CLI",+ icon: "Microsoft Azure.png",+ connectionDetails: z.object({+ tenantId: z+ .string()+ .trim()+ .min(1)+ .max(255)+ .regex(new RE2(/^[A-Za-z0-9.-]+$/), "Must be a valid Azure tenant ID or domain"),+ subscriptionId: z+ .string()+ .trim()+ .refine((v) => v === "" || z.string().uuid().safeParse(v).success, {+ message: "Must be a valid Azure subscription ID"+ })+ .transform((v) => v || undefined)+ .optional()+ }),+ credentials: z.object({+ clientId: z.string().trim().uuid("Must be a valid Azure application (client) ID"),+ clientSecret: z+ .string()+ .trim()+ .max(512)+ .transform((v) => v || undefined)+ .optional()+ }),+ sanitizedCredentials: z.object({+ clientId: z.string().optional()+ }),+ ui: {+ tenantId: {+ label: "Tenant ID",+ tooltip: "The Microsoft Entra ID (Azure AD) directory (tenant) ID the service principal belongs to."+ },+ subscriptionId: {+ label: "Subscription ID",+ tooltip: "Optional. The Azure subscription the CLI session defaults to (az account set)."+ },+ clientId: {+ label: "Client ID",+ tooltip: "The application (client) ID of the service principal Infisical brokers access to."+ },+ clientSecret: {+ label: "Client Secret",+ widget: PamFieldWidget.Password,+ secret: true,+ tooltip: "A client secret for the service principal. Stored encrypted and never returned in read responses."+ }+ }}} as const satisfies Partial<Record<@@ -660,6 +713,8 @@ export const extractGatewayTarget = async (return { host: "googleapis.com", port: 443 };case PamAccountType.AwsIam:throw new Error("AWS IAM accounts do not use gateway routing");+ case PamAccountType.AzureCli:+ return { host: "management.azure.com", port: 443 };default:throw new Error(`No gateway target extraction defined for account type '${accountType}'`);}diff --git a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts b/backend/src/ee/services/pam-project/pam-project-bootstrap.tsindex c8cb14f157..0b5877def7 100644--- a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts+++ b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts@@ -111,6 +111,14 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [recordingStorageBackend: PamRecordingStorageBackend.Postgres}},+ {+ name: "azure-cli",+ type: PamAccountType.AzureCli,+ settings: {+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres+ }+ },{name: "windows",type: PamAccountType.Windows,diff --git a/backend/src/ee/services/pam-session/azure/azure-federation.ts b/backend/src/ee/services/pam-session/azure/azure-federation.tsnew file mode 100644index 0000000000..d6eeb896c6--- /dev/null+++ b/backend/src/ee/services/pam-session/azure/azure-federation.ts@@ -0,0 +1,66 @@+import axios from "axios";++import { BadRequestError, InternalServerError } from "@app/lib/errors";++export const AZURE_SCOPES = {+ arm: "https://management.azure.com/.default",+ graph: "https://graph.microsoft.com/.default",+ keyvault: "https://vault.azure.net/.default",+ storage: "https://storage.azure.com/.default"+} as const;++type TAzureAudience = keyof typeof AZURE_SCOPES;+type TServicePrincipal = { tenantId: string; clientId: string; clientSecret: string };+type TAzureTokenResponse = { access_token?: string };+type TAzureTokenErrorResponse = { error?: string; error_description?: string };++export const getAzureAccessToken = async ({+ tenantId,+ clientId,+ clientSecret,+ scope+}: TServicePrincipal & { scope: string }): Promise<string> => {+ const body = new URLSearchParams({+ grant_type: "client_credentials",+ client_id: clientId,+ client_secret: clientSecret,+ scope+ });++ let response;+ try {+ response = await axios.post<TAzureTokenResponse>(+ `https://login.microsoftonline.com/${encodeURIComponent(tenantId)}/oauth2/v2.0/token`,+ body.toString(),+ { headers: { "Content-Type": "application/x-www-form-urlencoded" }, timeout: 10000, maxRedirects: 0 }+ );+ } catch (err) {+ if (axios.isAxiosError(err) && err.response) {+ const data = err.response.data as TAzureTokenErrorResponse;+ throw new BadRequestError({+ message: `Azure rejected the service principal credentials: ${data.error_description || data.error || "unknown error"}`+ });+ }+ throw new InternalServerError({ message: "Failed to reach the Azure token endpoint" });+ }++ if (!response.data.access_token) {+ throw new InternalServerError({ message: "Azure token endpoint did not return an access token" });+ }++ return response.data.access_token;+};++export const getAzureAccessTokens = async (sp: TServicePrincipal): Promise<Record<string, string>> => {+ const arm = await getAzureAccessToken({ ...sp, scope: AZURE_SCOPES.arm });++ const otherAudiences = (Object.keys(AZURE_SCOPES) as TAzureAudience[]).filter((aud) => aud !== "arm");+ const results = await Promise.allSettled(+ otherAudiences.map(async (aud) => [aud, await getAzureAccessToken({ ...sp, scope: AZURE_SCOPES[aud] })] as const)+ );++ return {+ arm,+ ...Object.fromEntries(results.flatMap((r) => (r.status === "fulfilled" ? [r.value] : [])))+ };+};diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex 663ca8a514..03c8669136 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -66,6 +66,7 @@ import {extractAwsAccountIdFromArn,generateAwsIamSessionCredentials} from "./aws-iam/aws-iam-federation";+import { getAzureAccessTokens } from "./azure/azure-federation";import { DEFAULT_SESSION_DURATION_MS } from "./pam-session-constants";import { TPamSessionDALFactory } from "./pam-session-dal";import { TPamSessionExpirationServiceFactory } from "./pam-session-expiration-queue";@@ -309,6 +310,18 @@ export const pamSessionServiceFactory = ({delete credentials.serviceAccountKeyJson;}+ if (account.accountType === PamAccountType.AzureCli) {+ if (!credentials.clientSecret) {+ throw new BadRequestError({ message: "Azure account has no client secret configured" });+ }+ credentials.tokens = await getAzureAccessTokens({+ tenantId: connectionDetails.tenantId as string,+ clientId: credentials.clientId as string,+ clientSecret: credentials.clientSecret as string+ });+ delete credentials.clientSecret;+ }+const sessionStarted = session.status === PamSessionStatus.Starting;if (sessionStarted) {@@ -691,6 +704,12 @@ export const pamSessionServiceFactory = ({if (account.accountType === PamAccountType.GcpServiceAccount) {metadata.serviceAccountEmail = rawConnectionDetails.serviceAccountEmail as string;metadata.authMethod = rawCredentials.authMethod as string;+ } else if (account.accountType === PamAccountType.AzureCli) {+ metadata.tenantId = rawConnectionDetails.tenantId as string;+ metadata.clientId = rawCredentials.clientId as string;+ if (rawConnectionDetails.subscriptionId) {+ metadata.subscriptionId = rawConnectionDetails.subscriptionId as string;+ }} else if (account.accountType === PamAccountType.Kubernetes) {metadata.authMethod = rawCredentials.authMethod as string;if (rawCredentials.namespace) {diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.mdindex a9f5696741..8d303f5057 100644--- a/backend/src/ee/services/pam/CLAUDE.md+++ b/backend/src/ee/services/pam/CLAUDE.md@@ -89,7 +89,7 @@ There is exactly one PAM project (`ProjectType.PAM`) per org, holding all folder- **`pamProjectResolverFactory` (`pam-project-resolver.ts`)** -- `resolve(orgId)` returns the project id, creating it on first use. It is wrapped in `withCache` (Redis, `KeyStorePrefixes.PamDefaultProject`, `PamDefaultProjectInSeconds` TTL); on a miss it calls `findDefaultProjectId` (newest `type=pam` project via `projectDAL.find`, already excludes soft-deleted) and falls back to `ensureDefaultProject`.- **`ensureDefaultProject`** serializes concurrent first-use bootstraps for an org with `SELECT pg_advisory_xact_lock(hashtext('pam-bootstrap:' || orgId))` inside a transaction, then **re-checks** `findDefaultProjectId(orgId, tx)` on the primary before creating. There is no DB unique constraint to lean on because old zombie PAM projects also have `type=pam`, so an org can legitimately have several rows; the lock + in-lock re-check is what prevents duplicates and picks the consolidated one. The lock auto-releases at transaction end.- **Admin seeding:** the bootstrap seeds the org's current admins (users, identities, and groups with a non-temporary org `admin` role) as PAM **project** admins. This is required because the PAM permission model has **no org-admin fallback** (`getProjectPermission` needs project-scoped membership) -- without seeding, no one could administer the freshly-created project.-- **`bootstrapPamProject` (`pam-project-bootstrap.ts`)** creates the project, the `DEFAULT_ACCOUNT_TEMPLATES` (11 of them), and the admin memberships. It takes `adminUserIds` / `adminIdentityIds` / `adminGroupIds`; the migration and sub-org creation call it directly, the resolver derives those lists from current org admins.+- **`bootstrapPamProject` (`pam-project-bootstrap.ts`)** creates the project, the `DEFAULT_ACCOUNT_TEMPLATES` (one per account type), and the admin memberships. It takes `adminUserIds` / `adminIdentityIds` / `adminGroupIds`; the migration and sub-org creation call it directly, the resolver derives those lists from current org admins.- **Request wiring:** the `injectPamProjectId` preValidation hook (on all `/api/v1/pam/*` routes) calls `resolve(actorOrgId)` and sets `req.internalPamProjectId`, so by the time any PAM handler runs the project exists. `GET /api/v1/pam/project` just returns that id -- the frontend hits it to trigger the lazy create for an org whose `getOrgById.pamProjectId` came back null, then seeds the id into its org cache.- **`getOrgById` derivation:** `pamProjectId` in the org DTO is derived from the newest `type=pam` project (nullable), it is **not** a stored column and is not resolved/bootstrapped there (keeps the read a pure query).@@ -136,6 +136,19 @@ Most types need only backend changes -- the frontend auto-renders from metadata.No changes to the account form components, router schemas, or field renderers are needed. The per-type route bodies use `config.connectionDetails`/`config.credentials` directly, the detail response (`SanitizedAccountDetailSchema`) is a discriminated union auto-derived from `ACCOUNT_TYPE_CONFIGS` (each variant pulls `connectionDetails` and `sanitizedCredentials` from the config), and the frontend forms render from `GET /pam/accounts/types`.+### Cloud account types++There are two brokering models for cloud types.++**Gateway-less (`AwsIam`)**: sets `requiresGateway: false` and branches early in `pam-session-service.access()` (before the gateway path) to mint short-lived STS credentials and return them in the session `metadata` map. The temporary credentials reach the client, but the root credentials never leave the backend. `extractGatewayTarget` `throw`s for it. Supports a browser flow (STS federation console URL) and is added to the web-access set explicitly in `pam-account-router.ts` (alongside `SESSION_HANDLERS` keys) so `supportsWebAccess` is true, with a dedicated frontend `AwsIamAccessContent` page. CLI side: `packages/pam/local/aws-iam-access.go` writes an isolated credentials profile.++**Gateway-injection (`GcpServiceAccount`, `AzureCli`)**: the preferred model. It is a normal gateway type (`requiresGateway` defaults to true) and reuses the full gateway path in `access()`. The gateway MITMs the cloud REST endpoint and injects a backend-minted **short-lived token** into every request, so **no credential of any kind reaches the client** and every request is captured to the session log. Conventions:++- `extractGatewayTarget` returns the cloud API host (`googleapis.com:443` for GCP, `management.azure.com:443` for Azure) so the session cert routes to it.+- The short-lived token is minted in `getSessionCredentials` (not `access()`), set as `credentials.token`, and the long-lived secret is deleted from the blob before it is returned to the gateway. GCP uses impersonation / a static-key JWT; Azure uses the client-credentials grant in `pam-session/azure/azure-federation.ts`. `HandlePAMProxy` caps `credentialExpiryTime` at ~1h for both since the tokens are short-lived.+- CLI/gateway side lives in the CLI repo. Gateway handler `packages/pam/handlers/<provider>/proxy.go` (a TLS-terminating HTTP proxy using a client-supplied ephemeral CA) overwrites the `Authorization` header with `credentials.Token` and logs each request/response via `SessionLogger.LogHttpEvent`. Client handler `packages/pam/local/<provider>-proxy.go` runs the local proxy tunnel and points the vendor CLI at it. `gcloud` is configured via `gcloud config` + a static-token-file placeholder; `az` (which has no static-token knob) is instead wired via `HTTPS_PROXY` + `REQUESTS_CA_BUNDLE` + an isolated `AZURE_CONFIG_DIR`, and the gateway additionally intercepts the Entra ID token endpoint to hand `az` a placeholder token so it believes login succeeded. Register the type in `pam-proxy.go` (`GetSupportedResourceTypes`, the `HandlePAMProxy` switch) and `session/uploader.go` (resource-type constant, filename regex, HTTP-events upload branch).+- Neither GCP nor Azure has a browser flow, so both stay out of the web-access set (`supportsWebAccess` false → `LaunchSessionSheet` shows the `infisical pam access` command). Neither has a `PamAccountAccessPage` entry (the browser web-access route is never linked for them); the launch sheet is the only surface.+## PoliciesPolicies are the governance controls applied to a template (require MFA, require reason, max session duration). They are registry-driven, defined once in `PAM_POLICY_DEFINITIONS` in `pam/pam-policies.ts`, keyed by `PamPolicyType`. Each entry is `{ label, description, appliesTo, schema }` where `appliesTo` is an account-type list or `"all"`, and `schema` is the Zod schema for that policy's value (a primitive or object).diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex 32b25a4026..c3d972cdc1 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -9,6 +9,7 @@ export enum PamAccountType {Kubernetes = "kubernetes",AwsIam = "aws-iam",GcpServiceAccount = "gcp-service-account",+ AzureCli = "azure-cli",Windows = "windows",WindowsAd = "windows-ad"}diff --git a/docs/cli/commands/pam.mdx b/docs/cli/commands/pam.mdxindex 3a2c378871..1b4861a5f6 100644--- a/docs/cli/commands/pam.mdx+++ b/docs/cli/commands/pam.mdx@@ -190,6 +190,24 @@ Based on the account's template, the CLI starts the appropriate local proxy or cThe session blocks until `Ctrl+C` or expiry. On shutdown, your `gcloud` configuration is restored.</Accordion>+ <Accordion title="Azure CLI">+ Starts an isolated, authenticated `az` shell for the session (using a temporary `AZURE_CONFIG_DIR`, so your own `az` login is untouched). Requires the [Azure CLI (`az`)](https://learn.microsoft.com/cli/azure/install-azure-cli) to be installed. All traffic is proxied through the Infisical Gateway, which injects the brokered token before forwarding to `management.azure.com`.++ ```bash+ # Example+ infisical pam access azure/prod-reader+ ```++ Run `az` as normal inside the session shell:++ ```bash+ az account show+ az group list+ ```++ Type `exit` to end the session (or press `Ctrl+C`, or wait for expiry). The isolated session state is wiped on shutdown.+ </Accordion>+<Accordion title="Windows / RDP">Starts a local RDP proxy. Connect your RDP client to `127.0.0.1` on the assigned port.diff --git a/docs/docs.json b/docs/docs.jsonindex 36ed0fe3ca..4d5ec0a7df 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1070,6 +1070,7 @@"documentation/platform/pam/accounts/kubernetes","documentation/platform/pam/accounts/aws-iam","documentation/platform/pam/accounts/gcp-service-account",+ "documentation/platform/pam/accounts/azure-cli","documentation/platform/pam/accounts/windows","documentation/platform/pam/accounts/windows-ad"]diff --git a/docs/documentation/platform/pam/accounts/azure-cli.mdx b/docs/documentation/platform/pam/accounts/azure-cli.mdxnew file mode 100644index 0000000000..24260e0b01--- /dev/null+++ b/docs/documentation/platform/pam/accounts/azure-cli.mdx@@ -0,0 +1,90 @@+---+title: "Azure CLI"+sidebarTitle: "Azure CLI"+description: "Add and connect to Azure via a brokered service principal, using the Azure CLI."+---++Azure CLI accounts let you broker credential-less access to Azure. Instead of handing out a service principal's client secret, users request access through Infisical and run `az` commands as the target service principal through a [Gateway](/documentation/platform/gateways/overview), with every command logged. The secret never leaves Infisical.++<Note>+Azure CLI accounts are available through the **CLI and API only**. There is no in-browser (web) access.+</Note>++## How It Works++Each account points at a single Microsoft Entra ID (Azure AD) service principal, identified by its tenant ID and client ID, with a client secret stored encrypted. When a user starts a session:++1. Infisical obtains short-lived access tokens for the service principal (via the OAuth 2.0 client-credentials grant), one per supported Azure plane: Resource Manager, Microsoft Graph, Key Vault, and Storage.+2. The user's `az` traffic is routed through a local proxy to the Infisical **Gateway**, which reaches Azure on their behalf.+3. The Gateway injects the token for the plane each request targets before forwarding it, so the user never handles a real credential. To `az`, the local login only ever holds a placeholder token.++A plane is only usable if the service principal has permission for it (RBAC for Resource Manager, Key Vault, and Storage; application permissions with admin consent for Microsoft Graph). Planes the principal can't get a token for are simply not brokered.++## Creating an Account++Before adding the account, create a service principal in Azure and give it access.++<Steps>+ <Step title="Create a service principal">+ In the Azure Portal, go to **Microsoft Entra ID → App registrations → New registration**, give it a name (e.g., `infisical-pam`), and register it. From the app's **Overview**, record the **Application (client) ID** and **Directory (tenant) ID**.+ </Step>+ <Step title="Create a client secret">+ In the app, go to **Certificates & secrets → New client secret**, then copy the secret **Value** immediately (it is shown only once). This is the secret you paste into Infisical, not the Secret ID.+ </Step>+ <Step title="Grant the service principal access">+ RBAC role assignments are made on the resource, not on the app. Open the subscription (or a resource group) you want to grant access to, go to **Access control (IAM) → Add role assignment**, pick a role (for example **Reader**), and on the **Members** tab select your app registration. Assign a more privileged role only if the session needs write access.+ </Step>+ <Step title="Start adding the account in Infisical">+ Go to **Privileged Access Management → Accounts** and click **Add Account**. Choose which [folder](/documentation/platform/pam/folders/overview) to add the account to, then select an Azure CLI [template](/documentation/platform/pam/templates/overview).++ The template (or the account) must be assigned a [Gateway](/documentation/platform/gateways/overview): Azure traffic is proxied through it, so the Gateway needs outbound access on port `443` to `login.microsoftonline.com`, `management.azure.com`, `graph.microsoft.com`, `*.vault.azure.net`, and `*.core.windows.net`.+ </Step>+ <Step title="Enter connection details and credentials">+ | Field | Description |+ |-------|-------------|+ | **Name** | A descriptive name (e.g., `prod-reader`) |+ | **Tenant ID** | The directory (tenant) ID, a GUID or a domain such as `contoso.onmicrosoft.com` |+ | **Subscription ID** | Optional. The subscription the CLI session defaults to |+ | **Client ID** | The application (client) ID of the service principal (a GUID) |+ | **Client Secret** | A client secret for the service principal. Stored encrypted and never returned to clients |+ </Step>+ <Step title="Save">+ Click **Create**.+ </Step>+</Steps>++## Connecting++Use the CLI to start a session. This requires the [Azure CLI (`az`)](https://learn.microsoft.com/cli/azure/install-azure-cli) to be installed locally.++```bash+infisical pam access my-folder/prod-reader+```++The command starts an isolated, authenticated shell for the session. It does not touch your own `az` login. Run `az` commands as normal:++```bash+az account show+az group list+```++Type `exit` to end the session (or press **Ctrl+C**, or wait for it to expire). The isolated session state is wiped when the session ends.++**Flags:**+- `--reason <reason>`: provide an access reason (if required by the template)+- `--duration <duration>`: request a session duration (e.g., `30m`), capped at the template maximum++<Note>+An Azure session recording is a log of the HTTP requests and responses made to Azure during the session: each request's method and URL, and its response body. Key Vault request and response bodies are redacted in the log, since they carry secret values.+</Note>++## Next Steps++<CardGroup cols={2}>+ <Card title="GCP Service Account Accounts" icon="google" href="/documentation/platform/pam/accounts/gcp-service-account">+ Add GCP service account accounts.+ </Card>+ <Card title="Sessions" icon="display" href="/documentation/platform/pam/sessions/overview">+ View and manage sessions.+ </Card>+</CardGroup>diff --git a/docs/documentation/platform/pam/accounts/overview.mdx b/docs/documentation/platform/pam/accounts/overview.mdxindex e3ca5e3972..d9f0f231fe 100644--- a/docs/documentation/platform/pam/accounts/overview.mdx+++ b/docs/documentation/platform/pam/accounts/overview.mdx@@ -22,6 +22,7 @@ PAM supports the following account types:| [**Kubernetes**](/documentation/platform/pam/accounts/kubernetes) | Kubernetes clusters | || [**AWS IAM**](/documentation/platform/pam/accounts/aws-iam) | AWS IAM roles | ✓ || [**GCP Service Account**](/documentation/platform/pam/accounts/gcp-service-account) | GCP service accounts | |+| [**Azure CLI**](/documentation/platform/pam/accounts/azure-cli) | Azure via a service principal | || [**Windows**](/documentation/platform/pam/accounts/windows) | Windows servers (RDP) | ✓ || [**Windows AD**](/documentation/platform/pam/accounts/windows-ad) | Windows via Active Directory | ✓ |diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex 944f9829c4..69a48b7aca 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -9,6 +9,7 @@ export enum PamAccountType {Kubernetes = "kubernetes",AwsIam = "aws-iam",GcpServiceAccount = "gcp-service-account",+ AzureCli = "azure-cli",Windows = "windows",WindowsAd = "windows-ad"}diff --git a/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsxindex 45259c2554..0bcccae2e4 100644--- a/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsx+++ b/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsx@@ -53,17 +53,21 @@ type Props = {onTerminate: (session: TPamSession) => void;};+const decodeBase64Utf8 = (b64: string): string => {+ try {+ const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));+ return new TextDecoder("utf-8").decode(bytes);+ } catch {+ return b64;+ }+};+const getLogText = (log: TPamSessionLog): string => {if ("input" in log && "output" in log) {return [log.input, log.output].filter(Boolean).join(" ");}if ("data" in log) {- try {- const bytes = Uint8Array.from(atob(log.data), (c) => c.charCodeAt(0));- return new TextDecoder("utf-8").decode(bytes);- } catch {- return log.data;- }+ return decodeBase64Utf8(log.data);}if ("method" in log) {return `${log.method} ${log.url}`;@@ -74,6 +78,16 @@ const getLogText = (log: TPamSessionLog): string => {return "";};+const getLogBody = (log: TPamSessionLog): string | null => {+ if (!("body" in log) || !log.body) return null;+ const decoded = decodeBase64Utf8(log.body);+ try {+ return JSON.stringify(JSON.parse(decoded), null, 2);+ } catch {+ return decoded;+ }+};+const DESTRUCTIVE_PREFIXES = ["DROP ", "DELETE ", "TRUNCATE ", "ALTER "];const isDestructiveQuery = (text: string): boolean => {@@ -81,10 +95,19 @@ const isDestructiveQuery = (text: string): boolean => {return DESTRUCTIVE_PREFIXES.some((prefix) => upper.startsWith(prefix));};-const LogEntry = ({ log, highlight }: { log: TPamSessionLog; highlight: string }) => {+const LogEntry = ({+ log,+ text,+ bodyText,+ highlight+}: {+ log: TPamSessionLog;+ text: string;+ bodyText: string | null;+ highlight: string;+}) => {const [expanded, setExpanded] = useState(false);const [overflows, setOverflows] = useState(false);- const text = getLogText(log);const textRef = useCallback((node: HTMLElement | null) => {@@ -97,8 +120,12 @@ const LogEntry = ({ log, highlight }: { log: TPamSessionLog; highlight: string }if (!text) return null;+ const term = highlight.trim().toLowerCase();+ const bodyMatch = Boolean(bodyText) && term.length > 0 && bodyText!.toLowerCase().includes(term);+ const showBody = Boolean(bodyText) && (expanded || bodyMatch);+const destructive = isDestructiveQuery(text);- const expandable = overflows || expanded;+ const expandable = overflows || expanded || Boolean(bodyText);const body = (<>@@ -116,7 +143,7 @@ const LogEntry = ({ log, highlight }: { log: TPamSessionLog; highlight: string }<div className="flex items-start gap-2">{expandable && (<ChevronRightIcon- className={`mt-0.5 size-3.5 shrink-0 text-muted transition-transform ${expanded ? "rotate-90" : ""}`}+ className={`mt-0.5 size-3.5 shrink-0 text-muted transition-transform ${showBody || expanded ? "rotate-90" : ""}`}/>)}<code@@ -128,6 +155,11 @@ const LogEntry = ({ log, highlight }: { log: TPamSessionLog; highlight: string }<HighlightText text={text} highlight={highlight} /></code></div>+ {showBody && bodyText && (+ <pre className="mt-1.5 max-h-96 thin-scrollbar overflow-auto rounded bg-container px-3 py-2 font-mono text-[11px] leading-relaxed break-all whitespace-pre-wrap text-muted">+ <HighlightText text={bodyText} highlight={highlight} />+ </pre>+ )}</>);@@ -173,17 +205,28 @@ export const SessionDetailSheet = ({ sessionId, isOpen, onOpenChange, onTerminaterror: logsError} = useDecryptedSessionLogs(sessionId ?? "", isOpen && !!sessionId, isActive);+ const decoded = useMemo(+ () =>+ new Map<unknown, { text: string; body: string | null }>(+ events+ .filter((event) => !isBrokenChunkMarker(event))+ .map((event) => {+ const log = event as TPamSessionLog;+ return [event, { text: getLogText(log), body: getLogBody(log) }] as const;+ })+ ),+ [events]+ );+const filteredEvents = useMemo(() => {const term = logSearch.trim().toLowerCase();if (!term) return events;- return events.filter(- (event) =>- !isBrokenChunkMarker(event) &&- getLogText(event as TPamSessionLog)- .toLowerCase()- .includes(term)- );- }, [events, logSearch]);+ return events.filter((event) => {+ const d = decoded.get(event);+ if (!d) return false;+ return `${d.text}\n${d.body ?? ""}`.toLowerCase().includes(term);+ });+ }, [events, logSearch, decoded]);if (!session) {return <PamDetailSheet isOpen={isOpen} onOpenChange={onOpenChange} isLoading={isLoading} />;@@ -283,7 +326,16 @@ export const SessionDetailSheet = ({ sessionId, isOpen, onOpenChange, onTerminat}const log = event as TPamSessionLog;- return <LogEntry key={`log-${log.timestamp}-${i + 1}`} log={log} highlight={logSearch} />;+ const d = decoded.get(event);+ return (+ <LogEntry+ key={`log-${log.timestamp}-${i + 1}`}+ log={log}+ text={d?.text ?? ""}+ bodyText={d?.body ?? null}+ highlight={logSearch}+ />+ );})}</div>);