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): add Windows RDP support to PAM revamp
bernie-g3e85fc48e33a
diff --git a/backend/src/db/migrations/20260603030053_pam-revamp.ts b/backend/src/db/migrations/20260603030053_pam-revamp.tsindex 95f070ac35..b4e51e49e2 100644--- a/backend/src/db/migrations/20260603030053_pam-revamp.ts+++ b/backend/src/db/migrations/20260603030053_pam-revamp.ts@@ -187,6 +187,9 @@ export async function up(knex: Knex): Promise<void> {for (const t of templates) {templateMap[t.type] = t.id;}+ if (templateMap.windows && !templateMap["active-directory"]) {+ templateMap["active-directory"] = templateMap.windows;+ }const oldPamProjects = await knex(TableName.Project).where({ orgId, type: ProjectType.PAM })diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.tsindex 567789a9a8..c70062835e 100644--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts@@ -381,6 +381,32 @@ export const ACCOUNT_TYPE_CONFIGS = {namespace: { label: "Namespace" },serviceAccountName: { label: "Service Account Name" }}+ },++ [PamAccountType.Windows]: {+ name: "Windows",+ icon: "Windows.png",+ connectionDetails: z.object({+ host: z.string().trim().min(1).max(255),+ port: z.coerce.number().int().min(1).max(65535)+ }),+ credentials: z.object({+ username: z.string().trim().min(1).max(255),+ password: z+ .string()+ .trim()+ .max(255)+ .transform((v) => v || undefined)+ .optional(),+ domain: z.string().trim().max(255).optional()+ }),+ sanitizedCredentials: z.object({+ username: z.string().optional(),+ domain: z.string().optional()+ }),+ ui: {+ password: { widget: PamFieldWidget.Password, secret: true }+ }}} as const satisfies Partial<Record<@@ -410,8 +436,9 @@ export const ACCOUNT_TYPE_CONFIGS = {type TSupportedAccountType = keyof typeof ACCOUNT_TYPE_CONFIGS;-const getAccountTypeConfig = (accountType: PamAccountType) => {- const config = ACCOUNT_TYPE_CONFIGS[accountType as TSupportedAccountType];+const getAccountTypeConfig = (accountType: PamAccountType | string) => {+ const resolved = resolveAccountType(accountType);+ const config = ACCOUNT_TYPE_CONFIGS[resolved as TSupportedAccountType];if (!config) {throw new Error(`Account type '${accountType}' is not supported in this phase`);}@@ -419,6 +446,13 @@ const getAccountTypeConfig = (accountType: PamAccountType) => {};export const validateConnectionDetails = (accountType: PamAccountType, data: unknown) => {+ const resolved = resolveAccountType(accountType);+ if (resolved === PamAccountType.Windows && data && typeof data === "object") {+ const raw = data as Record<string, unknown>;+ if (!raw.host && raw.hostname) {+ raw.host = raw.hostname;+ }+ }return getAccountTypeConfig(accountType).connectionDetails.parse(data) as z.output<(typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]["connectionDetails"]>;@@ -449,6 +483,7 @@ export const extractGatewayTarget = async (case PamAccountType.Postgres:case PamAccountType.MySQL:case PamAccountType.MsSQL:+ case PamAccountType.Windows:return {host: (validated as { host: string; port: number }).host,port: (validated as { host: string; port: number }).portdiff --git a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts b/backend/src/ee/services/pam-project/pam-project-bootstrap.tsindex 28a11b51b6..82310293e1 100644--- a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts+++ b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts@@ -164,22 +164,6 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [requireSymbols: true}}- },- {- name: "active-directory",- type: PamAccountType.ActiveDirectory,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.AwsS3,- passwordConstraints: {- minLength: 14,- maxLength: 127,- requireUppercase: true,- requireLowercase: true,- requireNumbers: true,- requireSymbols: true- }- }}];diff --git a/backend/src/ee/services/pam-session-recording/pam-recording-chunk-service.ts b/backend/src/ee/services/pam-session-recording/pam-recording-chunk-service.tsindex 7e3ebcb581..1e1fe90c39 100644--- a/backend/src/ee/services/pam-session-recording/pam-recording-chunk-service.ts+++ b/backend/src/ee/services/pam-session-recording/pam-recording-chunk-service.ts@@ -4,12 +4,18 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";+import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { PamSessionStatus } from "../pam/pam-enums";import { checkAccountAccess, TActorContext } from "../pam/pam-permission";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";+import { PamTemplateSettingsSchema } from "../pam-account-template/pam-account-template-schemas";import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";import { ResourcePermissionPamResourceActions } from "../permission/resource-permission";import { TPamSessionEventChunkDALFactory } from "./pam-recording-chunk-dal";@@ -25,6 +31,7 @@ type TPamSessionChunkServiceFactoryDep = {pamAccountDAL: Pick<TPamAccountDALFactory, "findByIdWithDetails">;permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;};export type TPamSessionChunkServiceFactory = ReturnType<typeof pamSessionChunkServiceFactory>;@@ -35,16 +42,52 @@ function assertGatewayActor(actor: OrgServiceActor) {}}-// eslint-disable-next-line @typescript-eslint/no-unused-vars-const resolveRecordingConfig = async (projectId: string): Promise<TPamRecordingResolvedConfig | null> => null;-export const pamSessionChunkServiceFactory = ({pamSessionDAL,pamSessionEventChunkDAL,pamAccountDAL,permissionService,- kmsService+ kmsService,+ appConnectionDAL}: TPamSessionChunkServiceFactoryDep) => {+ const resolveRecordingConfig = async (accountId: string): Promise<TPamRecordingResolvedConfig | null> => {+ const account = await pamAccountDAL.findByIdWithDetails(accountId);+ if (!account) return null;++ const parsed = account.templateSettings ? PamTemplateSettingsSchema.safeParse(account.templateSettings) : null;+ const settings = parsed?.success ? parsed.data : null;+ if (!settings) return null;++ if (settings.recordingStorageBackend === PamRecordingStorageBackend.AwsS3) {+ const connectionId = account.recordingConnectionId;+ if (!connectionId || !settings.recordingS3Config) return null;++ const raw = await appConnectionDAL.findById(connectionId);+ if (!raw) {+ logger.warn({ connectionId, accountId }, `Recording app connection not found [connectionId=${connectionId}]`);+ return null;+ }++ const appConnection = await decryptAppConnection(raw, kmsService);+ const awsConfig = await getAwsConnectionConfig(+ appConnection as unknown as TAwsConnectionConfig,+ (settings.recordingS3Config.region as AWSRegion) ?? AWSRegion.US_EAST_1+ );++ return {+ backend: PamRecordingStorageBackend.AwsS3,+ bucket: settings.recordingS3Config.bucket,+ region: settings.recordingS3Config.region as AWSRegion,+ keyPrefix: settings.recordingS3Config.keyPrefix ?? null,+ awsCredentials: awsConfig.credentials+ };+ }++ return {+ backend: PamRecordingStorageBackend.Postgres,+ keyPrefix: null+ };+ };const checkSessionViewAccess = async (session: { accountId?: string | null; projectId: string },actor: OrgServiceActor@@ -110,7 +153,7 @@ export const pamSessionChunkServiceFactory = ({verifyGatewayUploadToken(uploadToken, session.gatewayUploadTokenHash ?? null);- const config = await resolveRecordingConfig(session.projectId);+ const config = session.accountId ? await resolveRecordingConfig(session.accountId) : null;if (!config || config.backend === PamRecordingStorageBackend.Postgres) {throw new BadRequestError({message:@@ -194,7 +237,7 @@ export const pamSessionChunkServiceFactory = ({throw new BadRequestError({ message: "iv must be 12 bytes (AES-GCM standard)" });}- const config = await resolveRecordingConfig(session.projectId);+ const config = session.accountId ? await resolveRecordingConfig(session.accountId) : null;const backend = config?.backend ?? PamRecordingStorageBackend.Postgres;if (backend === PamRecordingStorageBackend.Postgres) {@@ -269,7 +312,7 @@ export const pamSessionChunkServiceFactory = ({const chunks = await pamSessionEventChunkDAL.findAllBySessionId(sessionId);let presignedGetByObjectKey: Record<string, { url: string }> = {};- const config = await resolveRecordingConfig(session.projectId);+ const config = session.accountId ? await resolveRecordingConfig(session.accountId) : null;if (config?.backend === PamRecordingStorageBackend.AwsS3) {const provider = PAM_RECORDING_STORAGE_FACTORY_MAP[config.backend]();const minted = await Promise.all(diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex 1ddcdc74a4..2c9c263efb 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -20,7 +20,7 @@ import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-sessionimport { TOrgDALFactory } from "@app/services/org/org-dal";import { TUserDALFactory } from "@app/services/user/user-dal";-import { PamAccessMethod, PamAccountType, PamSessionStatus } from "../pam/pam-enums";+import { PamAccessMethod, PamAccountType, PamSessionStatus, resolveAccountType } from "../pam/pam-enums";import { enforceMfa } from "../pam/pam-mfa";import {checkAccountAccess,@@ -30,7 +30,15 @@ import {} from "../pam/pam-permission";import { resolveAccessControls } from "../pam/pam-policies";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";-import { extractGatewayTarget, parseInternalMetadata } from "../pam-account/pam-account-schemas";+import {+ extractGatewayTarget,+ parseInternalMetadata,+ validateConnectionDetails+} from "../pam-account/pam-account-schemas";+import {+ PamTemplateAccessPolicySchema,+ PamTemplateSettingsSchema+} from "../pam-account-template/pam-account-template-schemas";import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";import { generateSessionRecordingSecrets } from "../pam-session-recording/pam-recording-secrets";@@ -211,17 +219,32 @@ export const pamSessionServiceFactory = ({gatewayUploadTokenHash: secrets.uploadTokenHash});+ const templateSettingsParsed = account.templateSettings+ ? PamTemplateSettingsSchema.safeParse(account.templateSettings)+ : null;+ const resolvedBackend =+ templateSettingsParsed?.success && templateSettingsParsed.data.recordingStorageBackend+ ? templateSettingsParsed.data.recordingStorageBackend+ : PamRecordingStorageBackend.Postgres;+recording = {sessionKey: secrets.sessionKey.toString("base64"),uploadToken: secrets.uploadToken.toString("base64"),- storageBackend: PamRecordingStorageBackend.Postgres,+ storageBackend: resolvedBackend,projectId: session.projectId,sessionId};}+ const resolved = resolveAccountType(account.accountType);+ const normalizedConnectionDetails = validateConnectionDetails(resolved, connectionDetails);++ if (sessionStarted) {+ await pamSessionDAL.activateSession(sessionId);+ }+return {- credentials: { ...connectionDetails, ...credentials },+ credentials: { ...normalizedConnectionDetails, ...credentials },recording,projectId: session.projectId,accountId: session.accountId,diff --git a/backend/src/ee/services/pam-web-access/pam-session-handlers.ts b/backend/src/ee/services/pam-web-access/pam-session-handlers.tsindex 005f459f90..4e545e2439 100644--- a/backend/src/ee/services/pam-web-access/pam-session-handlers.ts+++ b/backend/src/ee/services/pam-web-access/pam-session-handlers.ts@@ -2,6 +2,7 @@ import { PamAccountType } from "@app/ee/services/pam/pam-enums";import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";import { handlePostgresSession } from "./postgres/pam-postgres-session-handler";+import { handleRdpSession } from "./rdp/pam-rdp-session-handler";import { handleSSHSession } from "./ssh/pam-ssh-session-handler";export type TWebAccessHandler = (@@ -22,5 +23,9 @@ export const SESSION_HANDLERS: Partial<Record<PamAccountType, TSessionHandlerEnt[PamAccountType.SSH]: {gatewayAccountType: PamAccountType.SSH,handler: handleSSHSession+ },+ [PamAccountType.Windows]: {+ gatewayAccountType: PamAccountType.Windows,+ handler: handleRdpSession}};diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.tsindex dd809c5644..987f41b5d9 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts@@ -8,6 +8,7 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2import { 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 { PamTemplateAccessPolicySchema } from "@app/ee/services/pam-account-template/pam-account-template-schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";@@ -144,7 +145,7 @@ export const pamWebAccessServiceFactory = ({throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });}- if (!SESSION_HANDLERS[account.accountType as PamAccountType]) {+ if (!SESSION_HANDLERS[account.accountType]) {throw new BadRequestError({ message: "Web access is not supported for this account type" });}@@ -352,7 +353,7 @@ export const pamWebAccessServiceFactory = ({throw new BadRequestError({ message: "Invalid account or project" });}- const handlerEntry = SESSION_HANDLERS[account.accountType as PamAccountType];+ const handlerEntry = SESSION_HANDLERS[account.accountType];if (!handlerEntry) {throw new BadRequestError({ message: "Web access is not supported for this account type" });}@@ -427,8 +428,10 @@ export const pamWebAccessServiceFactory = ({gateway: certs.gateway};+ const isRdp = account.accountType === PamAccountType.Windows;+relayServer = await setupRelayServer({- protocol: GatewayProxyProtocol.Pam,+ protocol: isRdp ? GatewayProxyProtocol.PamRdpBrowser : GatewayProxyProtocol.Pam,relayHost: certs.relayHost,relay: certs.relay,gateway: certs.gateway,@@ -466,7 +469,11 @@ export const pamWebAccessServiceFactory = ({releaseEarlyBuffer();}- await pamSessionDAL.activateSession(session.id);+ // 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");diff --git a/backend/src/ee/services/pam-web-access/rdp/pam-rdp-session-handler.ts b/backend/src/ee/services/pam-web-access/rdp/pam-rdp-session-handler.tsnew file mode 100644index 0000000000..5f22416d59--- /dev/null+++ b/backend/src/ee/services/pam-web-access/rdp/pam-rdp-session-handler.ts@@ -0,0 +1,116 @@+import net from "node:net";++import { logger } from "@app/lib/logger";++import { TSessionContext, TSessionHandlerResult } from "../pam-web-access-types";++const RDP_TCP_CONNECT_TIMEOUT_MS = 30_000;+const WS_HIGH_WATER_MARK = 1024 * 1024;++const wsRawToBuffer = (raw: Buffer | ArrayBuffer | Buffer[]): Buffer => {+ if (Buffer.isBuffer(raw)) return raw;+ if (Array.isArray(raw)) return Buffer.concat(raw);+ return Buffer.from(raw);+};++export const handleRdpSession = async (ctx: TSessionContext): Promise<TSessionHandlerResult> => {+ const { socket, relayPort, sessionId, onCleanup, earlyMessages, releaseEarlyBuffer } = ctx;++ const tcpSocket = new net.Socket();+ let cleanedUp = false;++ const teardown = () => {+ if (cleanedUp) return;+ cleanedUp = true;+ try {+ tcpSocket.destroy();+ } catch (err) {+ logger.debug(err, "rdp session: error destroying tcp socket");+ }+ };++ return new Promise<TSessionHandlerResult>((resolve, reject) => {+ const connectTimeout = setTimeout(() => {+ logger.error({ sessionId }, "rdp session: relay connect timed out");+ teardown();+ reject(new Error("RDP relay connection timed out"));+ }, RDP_TCP_CONNECT_TIMEOUT_MS);++ tcpSocket.once("connect", () => {+ clearTimeout(connectTimeout);+ tcpSocket.removeAllListeners("error");++ releaseEarlyBuffer();+ for (const msg of earlyMessages) {+ if (msg.isBinary && tcpSocket.writable) {+ tcpSocket.write(msg.data);+ }+ }++ socket.on("message", (raw: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {+ if (cleanedUp || tcpSocket.destroyed || !tcpSocket.writable) return;+ if (!isBinary) return;+ const buf = wsRawToBuffer(raw);+ if (buf.length === 0) return;+ try {+ tcpSocket.write(buf);+ } catch {+ if (!cleanedUp) onCleanup();+ teardown();+ }+ });++ tcpSocket.on("data", (chunk: Buffer) => {+ if (cleanedUp || socket.readyState !== socket.OPEN) return;+ if (socket.bufferedAmount > WS_HIGH_WATER_MARK) {+ tcpSocket.pause();+ }+ socket.send(chunk, { binary: true }, (err) => {+ if (err) {+ logger.error(err, "rdp session: ws send failed");+ if (!cleanedUp) onCleanup();+ teardown();+ return;+ }+ if (tcpSocket.isPaused() && socket.bufferedAmount <= WS_HIGH_WATER_MARK) {+ tcpSocket.resume();+ }+ });+ });++ tcpSocket.on("close", () => {+ logger.info({ sessionId }, "rdp session: tcp socket closed");+ onCleanup();+ try {+ socket.close();+ } catch (err) {+ logger.debug(err, "rdp session: error closing ws after tcp close");+ }+ });++ tcpSocket.on("error", (err) => {+ logger.error(err, "rdp session: tcp socket error");+ if (!cleanedUp) {+ onCleanup();+ }+ teardown();+ });++ resolve({+ cleanup: async () => {+ teardown();+ }+ });+ });++ tcpSocket.once("error", (err) => {+ clearTimeout(connectTimeout);+ logger.error(err, "rdp session: failed to connect to relay");+ teardown();+ reject(err);+ });++ tcpSocket.connect(relayPort, "127.0.0.1");+ });+};+diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex 21a9628191..e598c41f62 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -8,10 +8,16 @@ export enum PamAccountType {Redis = "redis",Kubernetes = "kubernetes",AwsIam = "aws-iam",- Windows = "windows",- ActiveDirectory = "active-directory"+ Windows = "windows"}+const LEGACY_ACCOUNT_TYPE_ALIASES: Record<string, PamAccountType> = {+ "active-directory": PamAccountType.Windows+};++export const resolveAccountType = (raw: string): PamAccountType =>+ LEGACY_ACCOUNT_TYPE_ALIASES[raw] ?? (raw as PamAccountType);+export enum PamResourceRole {Admin = "admin",Connector = "connector",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 261bd3b016..3f53f621ab 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1810,7 +1810,8 @@ export const registerRoutes = async (pamSessionEventChunkDAL,pamAccountDAL,permissionService,- kmsService+ kmsService,+ appConnectionDAL});const pamWebAccessService = pamWebAccessServiceFactory({diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex 60013bf213..cec84539e1 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -21,7 +21,7 @@ export enum PamPolicyType {export enum SessionChannelType {Terminal = "terminal",Exec = "exec",- Sftp = "sftp"+ Rdp = "rdp"}export enum PamSessionStatus {diff --git a/frontend/src/hooks/api/pam/index.ts b/frontend/src/hooks/api/pam/index.tsindex f49a872a5a..dda90a234c 100644--- a/frontend/src/hooks/api/pam/index.ts+++ b/frontend/src/hooks/api/pam/index.ts@@ -1,4 +1,5 @@export * from "./enums";+export * from "./maps";export * from "./mutations";export * from "./queries";export * from "./types";diff --git a/frontend/src/hooks/api/pam/maps.ts b/frontend/src/hooks/api/pam/maps.tsnew file mode 100644index 0000000000..bf8b4ba10f--- /dev/null+++ b/frontend/src/hooks/api/pam/maps.ts@@ -0,0 +1,32 @@+import { PamAccountType } from "./enums";++export const PAM_ACCOUNT_TYPE_MAP: Record<PamAccountType, { name: string; image: string }> = {+ [PamAccountType.Postgres]: { name: "PostgreSQL", image: "Postgres.png" },+ [PamAccountType.MySQL]: { name: "MySQL", image: "MySql.png" },+ [PamAccountType.SSH]: { name: "SSH", image: "SSH.png" },+ [PamAccountType.Kubernetes]: { name: "Kubernetes", image: "Kubernetes.png" },+ [PamAccountType.OracleDB]: { name: "OracleDB", image: "Oracle.png" },+ [PamAccountType.MsSQL]: { name: "Microsoft SQL Server", image: "MsSql.png" },+ [PamAccountType.Redis]: { name: "Redis", image: "Redis.png" },+ [PamAccountType.MongoDB]: { name: "MongoDB", image: "MongoDB.png" },+ [PamAccountType.AwsIam]: { name: "AWS IAM", image: "Amazon Web Services.png" },+ [PamAccountType.Windows]: { name: "Windows", image: "Windows.png" },+ [PamAccountType.ActiveDirectory]: { name: "Windows", image: "Windows.png" }+};++const LEGACY_TYPE_ALIASES: Record<string, PamAccountType> = {+ "active-directory": PamAccountType.Windows+};++const PAM_ACCOUNT_TYPE_FALLBACK = { name: "Unknown", image: "Windows.png" };++export const resolvePamAccountType = (accountType: string): string =>+ LEGACY_TYPE_ALIASES[accountType] ?? accountType;++export const getPamAccountTypeInfo = (accountType: string): { name: string; image: string } => {+ const resolved = LEGACY_TYPE_ALIASES[accountType] ?? accountType;+ return (+ (PAM_ACCOUNT_TYPE_MAP as Record<string, { name: string; image: string }>)[resolved] ??+ PAM_ACCOUNT_TYPE_FALLBACK+ );+};diff --git a/frontend/src/pages/pam/PamAccessPage/components/AccountPlatformIcon.tsx b/frontend/src/pages/pam/PamAccessPage/components/AccountPlatformIcon.tsxindex ee36ba8643..440bc35aff 100644--- a/frontend/src/pages/pam/PamAccessPage/components/AccountPlatformIcon.tsx+++ b/frontend/src/pages/pam/PamAccessPage/components/AccountPlatformIcon.tsx@@ -1,4 +1,4 @@-import { PamAccountType, usePamAccountTypeMap } from "@app/hooks/api/pam";+import { PamAccountType, resolvePamAccountType, usePamAccountTypeMap } from "@app/hooks/api/pam";type Props = {accountType: PamAccountType;@@ -7,7 +7,8 @@ type Props = {export const AccountPlatformIcon = ({ accountType, size = 28 }: Props) => {const { map } = usePamAccountTypeMap();- const meta = map[accountType];+ const resolved = resolvePamAccountType(accountType);+ const meta = map[resolved as PamAccountType];if (!meta) return null;diff --git a/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsx b/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsxindex 5a7d37e6a0..a0633bf302 100644--- a/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsx+++ b/frontend/src/pages/pam/PamAccessPage/components/AccountRow.tsx@@ -10,7 +10,7 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { TAccessiblePamAccount, usePamAccountTypeMap } from "@app/hooks/api/pam";+import { PamAccountType, resolvePamAccountType, TAccessiblePamAccount, usePamAccountTypeMap } from "@app/hooks/api/pam";import { AccountPlatformIcon } from "./AccountPlatformIcon";@@ -23,7 +23,8 @@ type Props = {export const AccountRow = ({ account, search, onLaunch, indented }: Props) => {const { map } = usePamAccountTypeMap();- const typeName = map[account.accountType]?.name ?? account.accountType;+ const resolved = resolvePamAccountType(account.accountType);+ const typeName = map[resolved as PamAccountType]?.name ?? account.accountType;const { canLaunch } = account;return (diff --git a/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsx b/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsxindex 8fa08a722c..a7d55170a5 100644--- a/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsx+++ b/frontend/src/pages/pam/PamAccessPage/components/LaunchSessionSheet.tsx@@ -18,6 +18,8 @@ import {} from "@app/components/v3";import { useOrganization } from "@app/context";import {+ PamAccountType,+ resolvePamAccountType,TAccessiblePamAccount,TPamFieldDescriptor,useGetPamAccountById,@@ -150,7 +152,8 @@ export const LaunchSessionSheet = ({ account, isOpen, onOpenChange }: Props) =>if (!account) return null;- const typeMeta = map[account.accountType];+ const resolved = resolvePamAccountType(account.accountType);+ const typeMeta = map[resolved as PamAccountType];const typeName = typeMeta?.name ?? account.accountType;const supportsWebAccess = Boolean(typeMeta?.supportsWebAccess);diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsxindex 6379cbf021..17e65bec15 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx@@ -3,10 +3,11 @@ import { Helmet } from "react-helmet";import { useParams } from "@tanstack/react-router";import { TriangleAlert } from "lucide-react";-import { PamAccountType, TPamAccount, useGetPamAccountById } from "@app/hooks/api/pam";+import { PamAccountType, resolvePamAccountType, TPamAccount, useGetPamAccountById } from "@app/hooks/api/pam";import { PamDataExplorerPage } from "@app/pages/pam/PamDataExplorerPage/PamDataExplorerPage";import { DisconnectedScreen } from "./DisconnectedScreen";+import { RdpContent } from "./RdpContent";import { SessionAccessGate } from "./ReasonGate";import { useWebAccessSession } from "./useWebAccessSession";import { WebAccessStatusCard } from "./WebAccessStatusCard";@@ -109,13 +110,22 @@ const PageContent = () => {);}+ const resolvedType = resolvePamAccountType(account.accountType);++ if (resolvedType === PamAccountType.SSH) {+ return <TerminalContent account={account} orgId={orgId!} />;+ }+return (<SessionAccessGate account={account}>{({ reason, mfaSessionId }) => {- if (account.accountType === PamAccountType.Postgres) {+ if (resolvedType === PamAccountType.Postgres) {return <PamDataExplorerPage reason={reason} mfaSessionId={mfaSessionId} />;}- return <TerminalContent account={account} reason={reason} mfaSessionId={mfaSessionId} />;+ if (resolvedType === PamAccountType.Windows) {+ return <RdpContent account={account} reason={reason} mfaSessionId={mfaSessionId} />;+ }+ return <TerminalContent account={account} orgId={orgId!} reason={reason} mfaSessionId={mfaSessionId} />;}}</SessionAccessGate>);diff --git a/frontend/src/pages/pam/PamAccountAccessPage/RdpContent.tsx b/frontend/src/pages/pam/PamAccountAccessPage/RdpContent.tsxindex f2762bd182..0e85c8206a 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/RdpContent.tsx+++ b/frontend/src/pages/pam/PamAccountAccessPage/RdpContent.tsx@@ -11,27 +11,15 @@ import { WebAccessStatusCard } from "./WebAccessStatusCard";type RdpContentProps = {account: TPamAccount;- projectId: string;- resourceId: string;- resourceName: string;reason?: string;};-export const RdpContent = ({- account,- projectId,- resourceId,- resourceName,- reason-}: RdpContentProps) => {+export const RdpContent = ({ account, reason }: RdpContentProps) => {const [sessionEnded, setSessionEnded] = useState(false);const { containerRef, isConnected, error, disconnect, reconnect } = useRdpSession({accountId: account.id,- projectId,- resourceId,- resourceName,- destination: resourceName,+ accountName: account.name,reason,onSessionEnd: () => setSessionEnded(true)});@@ -95,11 +83,6 @@ export const RdpContent = ({)}</span><div className="flex items-center gap-4">- <span>- <span className="text-muted">Resource:</span>{" "}- <span className="text-muted">{resourceName}</span>- </span>- <span className="text-muted">|</span><span><span className="text-muted">Account:</span>{" "}<span className="text-muted">{account.name}</span>diff --git a/frontend/src/pages/pam/PamAccountAccessPage/useRdpSession.ts b/frontend/src/pages/pam/PamAccountAccessPage/useRdpSession.tsindex a8ceaad17a..6ca3ca8b2e 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/useRdpSession.ts+++ b/frontend/src/pages/pam/PamAccountAccessPage/useRdpSession.ts@@ -77,20 +77,14 @@ const ensureRdpBackend = () => {type UseRdpSessionOptions = {accountId: string;- projectId: string;- resourceId: string;- resourceName: string;- destination: string;+ accountName: string;reason?: string;onSessionEnd?: () => void;};export const useRdpSession = ({accountId,- projectId,- resourceId,- resourceName,- destination,+ accountName,reason,onSessionEnd}: UseRdpSessionOptions) => {@@ -142,7 +136,7 @@ export const useRdpSession = ({const { data } = await apiRequest.post<{ ticket: string }>(`/api/v1/pam/accounts/${accountId}/web-access-ticket`,- { projectId, reason, resourceId }+ { reason });if (!isCurrent()) return;const proxyAddress = buildProxyAddress(data.ticket);@@ -166,7 +160,7 @@ export const useRdpSession = ({.configBuilder().withUsername(BROWSER_ACCEPTOR_USERNAME).withPassword(BROWSER_ACCEPTOR_PASSWORD)- .withDestination(destination || resourceName)+ .withDestination(accountName).withProxyAddress(proxyAddress).withAuthToken("infisical").withDesktopSize(DEFAULT_DESKTOP_SIZE)@@ -204,16 +198,7 @@ export const useRdpSession = ({containerRef.current.appendChild(el);elementRef.current = el;- }, [- accountId,- projectId,- resourceId,- reason,- destination,- resourceName,- buildProxyAddress,- teardown- ]);+ }, [accountId, accountName, reason, buildProxyAddress, teardown]);const handleConnectError = useCallback((err: unknown) => {let message = "Failed to start RDP session";diff --git a/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/RdpReplayView.tsx b/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/RdpReplayView.tsxnew file mode 100644index 0000000000..13640947f4--- /dev/null+++ b/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/RdpReplayView.tsx@@ -0,0 +1,292 @@+import { useEffect, useRef, useState } from "react";+import { AnimatePresence, motion } from "framer-motion";+import { Loader2Icon, PauseIcon, PlayIcon, RotateCcwIcon } from "lucide-react";++import { IconButton } from "@app/components/v3";+import { TSessionEvent } from "@app/hooks/api/pam";+import { isBrokenChunkMarker } from "@app/hooks/api/pam/session-playback";++import { parseRdpLogEntry, RdpEvent, RdpReplayPlayer } from "./rdpReplayPlayer";++const CANVAS_W = 1920;+const CANVAS_H = 1080;+const OUTER_ASPECT_W = 16;+const OUTER_ASPECT_H = 9;+const OUTER_ASPECT = OUTER_ASPECT_W / OUTER_ASPECT_H;++const formatMs = (ms: number) => {+ const s = Math.floor(ms / 1000);+ const h = Math.floor(s / 3600);+ const m = Math.floor((s % 3600) / 60);+ const r = s % 60;+ const mm = m.toString().padStart(2, "0");+ const ss = r.toString().padStart(2, "0");+ return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;+};++const parseRange = (events: TSessionEvent[], start: number, end: number): RdpEvent[] => {+ const out: RdpEvent[] = [];+ for (let i = start; i < end; i += 1) {+ const ev = parseRdpLogEntry(events[i]);+ if (ev) out.push(ev);+ }+ return out;+};++type Props = {+ events: TSessionEvent[];+ isStreaming?: boolean;+ totalDurationMs?: number;+};++export const RdpReplayView = ({ events, isStreaming = false, totalDurationMs }: Props) => {+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const playerRef = useRef<RdpReplayPlayer | null>(null);+ const lastParsedIndexRef = useRef(0);+ const progressFillRef = useRef<HTMLDivElement | null>(null);+ const timeTextRef = useRef<HTMLSpanElement | null>(null);+ const currentMsRef = useRef(0);+ const [isPlaying, setIsPlaying] = useState(false);+ const [isBuffering, setIsBuffering] = useState(false);+ const [lastSeenEventMs, setLastSeenEventMs] = useState(0);+ const [error, setError] = useState<string | null>(null);+ const [playerReady, setPlayerReady] = useState(false);+ const [feedback, setFeedback] = useState<{+ icon: "play" | "pause";+ nonce: number;+ } | null>(null);+ const totalMs = totalDurationMs && totalDurationMs > 0 ? totalDurationMs : lastSeenEventMs;+ const [contentBounds, setContentBounds] = useState({+ width: CANVAS_W,+ height: CANVAS_H+ });++ const totalMsRef = useRef(totalMs);+ totalMsRef.current = totalMs;++ const writeProgress = (ms: number) => {+ currentMsRef.current = ms;+ const total = totalMsRef.current;+ if (progressFillRef.current) {+ const pct = total > 0 ? Math.min(1, ms / total) * 100 : 0;+ progressFillRef.current.style.width = `${pct}%`;+ }+ if (timeTextRef.current) {+ timeTextRef.current.textContent = `${formatMs(ms)} / ${formatMs(total)}`;+ }+ };++ useEffect(() => {+ let cancelled = false;+ const canvas = canvasRef.current;+ if (!canvas) return undefined;++ for (let i = 0; i < events.length; i += 1) {+ const ev = events[i];+ if (isBrokenChunkMarker(ev)) {+ setError(`Chunk ${ev.chunkIndex}: ${ev.message}`);+ return undefined;+ }+ }++ const initial = parseRange(events, 0, events.length);+ lastParsedIndexRef.current = events.length;+ if (initial.length > 0) setLastSeenEventMs(initial[initial.length - 1].elapsedMs);++ RdpReplayPlayer.create(initial, canvas, {+ onTick: writeProgress,+ onEnded: () => {+ setIsPlaying(false);+ setIsBuffering(false);+ },+ onContentBoundsChange: (width, height) => setContentBounds({ width, height }),+ onBuffering: (b) => setIsBuffering(b)+ })+ .then((player) => {+ if (cancelled) {+ player.dispose();+ return;+ }+ playerRef.current = player;+ setPlayerReady(true);+ })+ .catch((e: unknown) => {+ setError(e instanceof Error ? e.message : "Failed to initialize RDP replay player");+ });++ return () => {+ cancelled = true;+ if (playerRef.current) {+ playerRef.current.dispose();+ playerRef.current = null;+ }+ lastParsedIndexRef.current = 0;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ const player = playerRef.current;+ if (!player) return;+ if (events.length <= lastParsedIndexRef.current) return;+ for (let i = lastParsedIndexRef.current; i < events.length; i += 1) {+ const ev = events[i];+ if (isBrokenChunkMarker(ev)) {+ player.pause();+ setError(`Chunk ${ev.chunkIndex}: ${ev.message}`);+ return;+ }+ }+ const more = parseRange(events, lastParsedIndexRef.current, events.length);+ lastParsedIndexRef.current = events.length;+ if (more.length > 0) {+ player.appendEvents(more);+ setLastSeenEventMs(more[more.length - 1].elapsedMs);+ }+ }, [events, playerReady]);++ useEffect(() => {+ if (!isStreaming && playerRef.current) {+ playerRef.current.markStreamComplete();+ }+ }, [isStreaming, playerReady]);++ useEffect(() => {+ writeProgress(currentMsRef.current);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [totalMs]);++ const onPlayPause = () => {+ const p = playerRef.current;+ if (!p) return;+ if (p.isPlaying) {+ p.pause();+ setIsPlaying(false);+ setFeedback({ icon: "pause", nonce: Date.now() });+ return;+ }+ const willAutoReplay = p.currentMs >= p.totalMs && p.totalMs > 0;+ p.play();+ if (willAutoReplay) {+ setContentBounds({ width: CANVAS_W, height: CANVAS_H });+ }+ setIsPlaying(true);+ setFeedback({ icon: "play", nonce: Date.now() });+ };++ useEffect(() => {+ if (!feedback) return undefined;+ const t = setTimeout(() => setFeedback(null), 400);+ return () => clearTimeout(t);+ }, [feedback]);++ const onRestart = () => {+ const p = playerRef.current;+ if (!p) return;+ p.restart();+ setIsPlaying(false);+ setIsBuffering(false);+ setContentBounds({ width: CANVAS_W, height: CANVAS_H });+ };++ if (error) {+ return (+ <div className="flex flex-col gap-1 rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-xs text-danger">+ <span>Playback halted: recording chunks are unavailable or corrupted.</span>+ <span className="text-danger/70">{error}</span>+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-3">+ <button+ type="button"+ onClick={onPlayPause}+ aria-label={isPlaying ? "Pause" : "Play"}+ className="group relative flex cursor-pointer items-center justify-center overflow-hidden rounded-md border border-border bg-black focus-visible:ring-2 focus-visible:ring-foreground/30 focus-visible:outline-none"+ style={{ aspectRatio: `${OUTER_ASPECT_W} / ${OUTER_ASPECT_H}` }}+ >+ <div+ className="relative overflow-hidden"+ style={{+ aspectRatio: `${contentBounds.width} / ${contentBounds.height}`,+ ...(contentBounds.width / contentBounds.height <= OUTER_ASPECT+ ? { height: "100%" }+ : { width: "100%" })+ }}+ >+ <canvas+ ref={canvasRef}+ width={CANVAS_W}+ height={CANVAS_H}+ style={{+ width: `${(CANVAS_W / contentBounds.width) * 100}%`,+ height: `${(CANVAS_H / contentBounds.height) * 100}%`,+ display: "block"+ }}+ aria-label="RDP session replay"+ />+ </div>+ <AnimatePresence>+ {feedback && (+ <motion.div+ key={feedback.nonce}+ initial={{ opacity: 0, scale: 0.6 }}+ animate={{ opacity: 1, scale: 1 }}+ exit={{ opacity: 0, scale: 1.4 }}+ transition={{ duration: 0.35, ease: "easeOut" }}+ className="pointer-events-none absolute inset-0 flex items-center justify-center"+ >+ <div className="flex size-16 items-center justify-center rounded-full bg-black/60 backdrop-blur-sm">+ {feedback.icon === "play" ? (+ <PlayIcon className="size-8 text-white" />+ ) : (+ <PauseIcon className="size-8 text-white" />+ )}+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ {isBuffering && (+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-black/40">+ <div className="flex items-center gap-2 rounded-md bg-black/70 px-3 py-1.5 text-xs text-foreground">+ <Loader2Icon className="size-3.5 animate-spin" />+ <span>Buffering...</span>+ </div>+ </div>+ )}+ </button>+ <div className="flex items-center gap-3">+ <IconButton+ variant="project"+ size="sm"+ onClick={onPlayPause}+ aria-label={isPlaying ? "Pause" : "Play"}+ >+ {isPlaying ? <PauseIcon /> : <PlayIcon />}+ </IconButton>+ <div className="relative h-1 flex-1 overflow-hidden rounded-full bg-foreground/10">+ <div+ ref={progressFillRef}+ className="absolute inset-y-0 left-0 rounded-full bg-foreground/70"+ style={{ width: "0%" }}+ />+ </div>+ <span ref={timeTextRef} className="font-mono text-xs text-muted tabular-nums">+ {formatMs(0)} / {formatMs(totalMs)}+ </span>+ <IconButton+ variant="ghost-muted"+ size="sm"+ onClick={onRestart}+ aria-label="Restart from beginning"+ >+ <RotateCcwIcon />+ </IconButton>+ </div>+ </div>+ );+};++export default RdpReplayView;diff --git a/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/index.ts b/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/index.tsnew file mode 100644index 0000000000..d868ea6193--- /dev/null+++ b/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/index.ts@@ -0,0 +1 @@+export { RdpReplayView } from "./RdpReplayView";diff --git a/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/rdpReplayPlayer.ts b/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/rdpReplayPlayer.tsnew file mode 100644index 0000000000..87cd96379f--- /dev/null+++ b/frontend/src/pages/pam/PamSessionsPage/components/RdpReplayView/rdpReplayPlayer.ts@@ -0,0 +1,331 @@+import wasmInit, { InitOutput, RdpDecoder } from "@app/lib/ironrdp-decoder/infisical_rdp_decoder";++export type RdpEventType = "keyboard" | "unicode" | "mouse" | "target_frame";++export type RdpEvent = {+ type: RdpEventType;+ elapsedMs: number;+ scancode?: number;+ codePoint?: number;+ x?: number;+ y?: number;+ wheelDelta?: number;+ flags?: number;+ action?: "x224" | "fastpath";+ payload?: Uint8Array;+};++type PlayerCallbacks = {+ onTick: (currentMs: number) => void;+ onEnded: () => void;+ onContentBoundsChange: (width: number, height: number) => void;+ onBuffering: (buffering: boolean) => void;+};++let wasmReady: Promise<InitOutput> | null = null;+const ensureWasm = (): Promise<InitOutput> => {+ if (!wasmReady) wasmReady = wasmInit();+ return wasmReady;+};++export class RdpReplayPlayer {+ private events: RdpEvent[];++ private canvas: HTMLCanvasElement;++ private ctx: CanvasRenderingContext2D;++ private callbacks: PlayerCallbacks;++ private decoder: RdpDecoder;++ private wasm: InitOutput;++ private index = 0;++ private clockMs = 0;++ private wallStart: number | null = null;++ private raf: number | null = null;++ private wantPlay = false;++ private streamComplete = false;++ private buffering = false;++ private contentMaxX = 0;++ private contentMaxY = 0;++ private constructor(+ events: RdpEvent[],+ canvas: HTMLCanvasElement,+ callbacks: PlayerCallbacks,+ decoder: RdpDecoder,+ wasm: InitOutput+ ) {+ this.events = events;+ this.canvas = canvas;+ const c = canvas.getContext("2d");+ if (!c) throw new Error("2d context unavailable");+ this.ctx = c;+ this.callbacks = callbacks;+ this.decoder = decoder;+ this.wasm = wasm;+ }++ static async create(+ events: RdpEvent[],+ canvas: HTMLCanvasElement,+ callbacks: PlayerCallbacks+ ): Promise<RdpReplayPlayer> {+ const wasm = await ensureWasm();+ const decoder = new RdpDecoder(canvas.width, canvas.height);+ decoder.move_pointer(0xffff, 0xffff);+ return new RdpReplayPlayer(events, canvas, callbacks, decoder, wasm);+ }++ get totalMs(): number {+ const last = this.events[this.events.length - 1];+ return last ? last.elapsedMs : 0;+ }++ get currentMs(): number {+ return this.clockMs;+ }++ get isPlaying(): boolean {+ return this.wantPlay;+ }++ get isBuffering(): boolean {+ return this.buffering;+ }++ play = () => {+ if (this.wantPlay) return;+ if (this.streamComplete && this.index >= this.events.length) {+ this.resetForReplay();+ }+ this.wantPlay = true;+ if (this.index >= this.events.length) {+ this.setBuffering(true);+ return;+ }+ this.startRaf();+ };++ pause = () => {+ this.wantPlay = false;+ this.stopRaf();+ this.setBuffering(false);+ };++ restart = () => {+ this.resetForReplay();+ this.wantPlay = false;+ };++ private resetForReplay = () => {+ this.stopRaf();+ this.setBuffering(false);+ this.index = 0;+ this.clockMs = 0;+ this.contentMaxX = 0;+ this.contentMaxY = 0;+ this.decoder.free();+ this.decoder = new RdpDecoder(this.canvas.width, this.canvas.height);+ this.decoder.move_pointer(0xffff, 0xffff);+ this.ctx.fillStyle = "#000";+ this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);+ this.callbacks.onTick(0);+ };++ appendEvents = (more: RdpEvent[]) => {+ if (more.length === 0) return;+ this.events.push(...more);+ if (this.buffering && this.wantPlay) {+ this.setBuffering(false);+ this.startRaf();+ }+ };++ markStreamComplete = () => {+ if (this.streamComplete) return;+ this.streamComplete = true;+ if (this.buffering) {+ this.setBuffering(false);+ this.wantPlay = false;+ this.callbacks.onEnded();+ }+ };++ dispose = () => {+ this.stopRaf();+ this.wantPlay = false;+ this.buffering = false;+ try {+ this.decoder.free();+ } catch {+ /* ignore */+ }+ };++ private startRaf = () => {+ if (this.raf !== null) return;+ this.wallStart = performance.now() - this.clockMs;+ this.tick();+ };++ private stopRaf = () => {+ if (this.raf === null) return;+ cancelAnimationFrame(this.raf);+ this.raf = null;+ this.wallStart = null;+ };++ private setBuffering = (value: boolean) => {+ if (this.buffering === value) return;+ this.buffering = value;+ this.callbacks.onBuffering(value);+ };++ private tick = () => {+ if (this.wallStart === null) return;+ const now = performance.now();+ this.clockMs = now - this.wallStart;++ while (this.index < this.events.length && this.events[this.index].elapsedMs <= this.clockMs) {+ try {+ this.apply(this.events[this.index]);+ } catch (err) {+ // eslint-disable-next-line no-console+ console.warn("RDP replay: apply failed, skipping event", err);+ }+ this.index += 1;+ }++ this.callbacks.onTick(this.clockMs);++ if (this.index >= this.events.length) {+ this.raf = null;+ this.wallStart = null;+ if (this.streamComplete) {+ this.wantPlay = false;+ this.callbacks.onEnded();+ } else {+ this.setBuffering(true);+ }+ return;+ }++ this.raf = requestAnimationFrame(this.tick);+ };++ private apply = (ev: RdpEvent) => {+ switch (ev.type) {+ case "target_frame":+ if (ev.payload) this.feedFrame(ev);+ break;+ case "mouse":+ if (ev.x !== undefined && ev.y !== undefined) {+ const count = this.decoder.move_pointer(ev.x, ev.y);+ if (count > 0) this.blitDirtyRects(count, false);+ }+ break;+ case "keyboard":+ case "unicode":+ break;+ default:+ break;+ }+ };++ private blitDirtyRects = (count: number, expandBounds = true) => {+ const ptr = this.decoder.buffer_ptr();+ const len = this.decoder.buffer_len();+ const width = this.decoder.width();+ const height = this.decoder.height();+ const fb = new Uint8ClampedArray(this.wasm.memory.buffer, ptr, len);+ const fullImage = new ImageData(fb, width, height);++ let boundsExpanded = false;+ for (let i = 0; i < count; i += 1) {+ const r = this.decoder.dirty_rect(i);+ if (r) {+ this.ctx.putImageData(fullImage, 0, 0, r.x, r.y, r.w, r.h);+ if (expandBounds) {+ const right = r.x + r.w;+ const bottom = r.y + r.h;+ if (right > this.contentMaxX) {+ this.contentMaxX = right;+ boundsExpanded = true;+ }+ if (bottom > this.contentMaxY) {+ this.contentMaxY = bottom;+ boundsExpanded = true;+ }+ }+ r.free();+ }+ }+ if (boundsExpanded) {+ this.callbacks.onContentBoundsChange(this.contentMaxX, this.contentMaxY);+ }+ };++ private feedFrame = (ev: RdpEvent) => {+ if (!ev.payload) return;+ if (ev.action === "x224") return;+ let count: number;+ try {+ count = this.decoder.feed(1, ev.payload);+ } catch {+ return;+ }+ if (count === 0) return;+ this.blitDirtyRects(count);+ };+}++const decodeBase64ToUint8 = (b64: string): Uint8Array => {+ const bin = atob(b64);+ const out = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);+ return out;+};++export const parseRdpLogEntry = (entry: unknown): RdpEvent | null => {+ const e = entry as { data?: string; channelType?: string };+ if (e?.channelType !== "rdp" || typeof e.data !== "string") return null;+ let rec: Record<string, unknown>;+ try {+ rec = JSON.parse(atob(e.data));+ } catch {+ return null;+ }+ const type = rec.type as RdpEventType | undefined;+ if (!type) return null;+ const elapsedMs = Number(rec.elapsedNs ?? 0) / 1e6;++ const ev: RdpEvent = { type, elapsedMs };+ if (type === "keyboard") {+ ev.scancode = Number(rec.scancode ?? 0);+ ev.flags = Number(rec.flags ?? 0);+ } else if (type === "unicode") {+ ev.codePoint = Number(rec.codePoint ?? 0);+ ev.flags = Number(rec.flags ?? 0);+ } else if (type === "mouse") {+ ev.x = Number(rec.x ?? 0);+ ev.y = Number(rec.y ?? 0);+ ev.flags = Number(rec.flags ?? 0);+ ev.wheelDelta = Number(rec.wheelDelta ?? 0);+ } else if (type === "target_frame") {+ ev.action = rec.action as "x224" | "fastpath";+ const payloadB64 = rec.payload as string | undefined;+ if (payloadB64) ev.payload = decodeBase64ToUint8(payloadB64);+ }+ return ev;+};diff --git a/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsx b/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsxindex d03bc77b12..e6e60431d0 100644--- a/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsx+++ b/frontend/src/pages/pam/PamSessionsPage/components/SessionDetailSheet.tsx@@ -1,10 +1,11 @@-import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";+import { lazy, type ReactNode, Suspense, useCallback, useEffect, useMemo, useState } from "react";import { format } from "date-fns";import {AlertTriangleIcon,Ban,ChevronRightIcon,ClipboardListIcon,+ MonitorPlayIcon,MoreHorizontalIcon,SearchIcon} from "lucide-react";@@ -27,9 +28,11 @@ import {Skeleton} from "@app/components/v3";import {+ PamAccountType,PamResourcePermissionActions,PamResourcePermissionSub,PamSessionStatus,+ resolvePamAccountType,useGetPamSessionById,usePamAccountTypeMap} from "@app/hooks/api/pam";@@ -38,6 +41,8 @@ import { useDecryptedSessionLogs } from "@app/hooks/api/pam/session-playback/queimport { isBrokenChunkMarker } from "@app/hooks/api/pam/session-playback/types";import { TPamSession, TPamSessionLog } from "@app/hooks/api/pam/types";+const RdpReplayView = lazy(() => import("./RdpReplayView/RdpReplayView"));+import { LiveDot } from "../../components/LiveDot";import { PamDetailSheet } from "../../components/PamDetailSheet";import { capitalize, formatDuration, STATUS_BADGE } from "../constants";@@ -280,43 +285,90 @@ export const SessionDetailSheet = ({ sessionId, isOpen, onOpenChange, onTerminat);}- const tabs = [- {- value: "logs",- label: "Session Logs",- icon: <ClipboardListIcon className="mr-1.5 size-4" />,- content: (- <div className="flex flex-1 flex-col gap-4 p-4">- <Card>- <CardHeader className="flex items-center justify-between border-b">- <CardTitle className="text-base">Session Logs</CardTitle>- {isActive && (- <Badge variant="pam">- <LiveDot className="bg-product-pam" />- Live- </Badge>- )}- </CardHeader>- <CardContent className="flex flex-col gap-3">- <InputGroup>- <InputGroupAddon>- <SearchIcon />- </InputGroupAddon>- <InputGroupInput- value={logSearch}- onChange={(e) => setLogSearch(e.target.value)}- placeholder="Search logs..."- />- </InputGroup>- <div className="overflow-hidden rounded-md border border-border bg-popover">- {logContent}- </div>- </CardContent>- </Card>- </div>- )- }- ];+ const isRdpSession = resolvePamAccountType(session.accountType) === PamAccountType.Windows;++ const tabs = isRdpSession+ ? [+ {+ value: "recording",+ label: "Session Recording",+ icon: <MonitorPlayIcon className="mr-1.5 size-4" />,+ content: (+ <div className="flex flex-1 flex-col gap-4 p-4">+ <Card>+ <CardHeader className="flex items-center justify-between border-b">+ <CardTitle className="text-base">Session Recording</CardTitle>+ {isActive && (+ <Badge variant="pam">+ <LiveDot className="bg-product-pam" />+ Live+ </Badge>+ )}+ </CardHeader>+ <CardContent>+ {showLogSkeleton ? (+ <div className="flex flex-col gap-2 p-4">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={`rec-skeleton-${i + 1}`} className="h-4 w-full" />+ ))}+ </div>+ ) : (+ <Suspense+ fallback={+ <div className="flex items-center justify-center p-10 text-sm text-muted">+ Loading player...+ </div>+ }+ >+ <RdpReplayView+ events={filteredEvents.filter((e) => !isBrokenChunkMarker(e))}+ isStreaming={isActive}+ />+ </Suspense>+ )}+ </CardContent>+ </Card>+ </div>+ )+ }+ ]+ : [+ {+ value: "logs",+ label: "Session Logs",+ icon: <ClipboardListIcon className="mr-1.5 size-4" />,+ content: (+ <div className="flex flex-1 flex-col gap-4 p-4">+ <Card>+ <CardHeader className="flex items-center justify-between border-b">+ <CardTitle className="text-base">Session Logs</CardTitle>+ {isActive && (+ <Badge variant="pam">+ <LiveDot className="bg-product-pam" />+ Live+ </Badge>+ )}+ </CardHeader>+ <CardContent className="flex flex-col gap-3">+ <InputGroup>+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={logSearch}+ onChange={(e) => setLogSearch(e.target.value)}+ placeholder="Search logs..."+ />+ </InputGroup>+ <div className="overflow-hidden rounded-md border border-border bg-popover">+ {logContent}+ </div>+ </CardContent>+ </Card>+ </div>+ )+ }+ ];return (<PamDetailSheetdiff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsxindex c1412dedef..f5cfa6ed60 100644--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx@@ -18,12 +18,21 @@ import {FieldLabel,GatewayPicker,Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,TextArea} from "@app/components/v3";import { Skeleton } from "@app/components/v3/generic/Skeleton";+import { useProject } from "@app/context";+import { AppConnection, useListAvailableAppConnections } from "@app/hooks/api/appConnections";import {accountTypeRequiresRecording,PamAccountType,+ resolvePamAccountType,useGetPamAccountTemplate,usePamAccountTypeMap,useUpdatePamAccountTemplate@@ -39,7 +48,13 @@ import { RecordingConnectionPicker } from "../../PamAccountsPage/components/Recoconst configSchema = z.object({name: z.string().min(1, "Name is required").max(64),- description: z.string().max(256).optional()+ description: z.string().max(256).optional(),+ recordingEnabled: z.boolean(),+ recordingStorageBackend: z.enum(["postgres", "aws-s3"]),+ recordingConnectionId: z.string().nullable(),+ s3Bucket: z.string().optional(),+ s3Region: z.string().optional(),+ s3KeyPrefix: z.string().optional()});type ConfigForm = z.infer<typeof configSchema>;@@ -68,17 +83,37 @@ const ConfigurationTab = ({}) => {const { data: template, isLoading } = useGetPamAccountTemplate(templateId);const updateTemplate = useUpdatePamAccountTemplate();+ const { currentProject } = useProject();+ const { data: awsConnections = [] } = useListAvailableAppConnections(+ AppConnection.AWS,+ currentProject.id+ );++ const isWindows =+ template?.type && resolvePamAccountType(template.type) === PamAccountType.Windows;const {control,handleSubmit,reset,+ watch,formState: { isDirty }} = useForm<ConfigForm>({resolver: zodResolver(configSchema),- defaultValues: { name: "", description: "" }+ defaultValues: {+ name: "",+ description: "",+ recordingEnabled: true,+ recordingStorageBackend: "postgres",+ recordingConnectionId: null,+ s3Bucket: "",+ s3Region: "",+ s3KeyPrefix: ""+ }});+ const storageBackend = watch("recordingStorageBackend");+useEffect(() => {onDirtyChange?.(isDirty);return () => onDirtyChange?.(false);@@ -86,13 +121,50 @@ const ConfigurationTab = ({useEffect(() => {if (template) {- reset({ name: template.name, description: template.description ?? "" });+ const settings = (template.settings ?? {}) as Record<string, unknown>;+ const s3Config = (settings.recordingS3Config ?? {}) as Record<string, string>;+ const isWin =+ resolvePamAccountType(template.type) === PamAccountType.Windows;+ const savedBackend = settings.recordingStorageBackend as "postgres" | "aws-s3" | undefined;+ reset({+ name: template.name,+ description: template.description ?? "",+ recordingEnabled: settings.recordingEnabled !== false,+ recordingStorageBackend: isWin ? "aws-s3" : (savedBackend ?? "postgres"),+ recordingConnectionId: (template.recordingConnectionId as string) ?? null,+ s3Bucket: s3Config.bucket ?? "",+ s3Region: s3Config.region ?? "",+ s3KeyPrefix: s3Config.keyPrefix ?? ""+ });}}, [template, reset]);const onSubmit = (data: ConfigForm) => {+ const settings: Record<string, unknown> = {+ ...((template?.settings ?? {}) as Record<string, unknown>),+ recordingEnabled: data.recordingEnabled,+ recordingStorageBackend: data.recordingStorageBackend+ };++ if (data.recordingStorageBackend === "aws-s3" && data.s3Bucket) {+ settings.recordingS3Config = {+ bucket: data.s3Bucket,+ region: data.s3Region || "us-east-1",+ ...(data.s3KeyPrefix ? { keyPrefix: data.s3KeyPrefix } : {})+ };+ } else {+ delete settings.recordingS3Config;+ }+updateTemplate.mutate(- { templateId, name: data.name, description: data.description || null },+ {+ templateId,+ name: data.name,+ description: data.description || null,+ settings,+ recordingConnectionId:+ data.recordingStorageBackend === "aws-s3" ? data.recordingConnectionId : null+ },{onSuccess: () => createNotification({ type: "success", text: "Template updated" })}@@ -148,6 +220,128 @@ const ConfigurationTab = ({</CardContent></Card>+ <Card>+ <CardHeader className="border-b">+ <CardTitle className="text-base">Recording</CardTitle>+ <CardDescription>Configure how sessions are recorded and stored.</CardDescription>+ </CardHeader>+ <CardContent className="flex flex-col gap-6">+ <Field orientation="horizontal" className="items-center!">+ <FieldContent>+ <FieldTitle>Enable recording</FieldTitle>+ <FieldDescription>Record session activity for audit and playback.</FieldDescription>+ </FieldContent>+ <Controller+ name="recordingEnabled"+ control={control}+ render={({ field }) => (+ <Switch checked={field.value} variant="pam" onCheckedChange={field.onChange} />+ )}+ />+ </Field>++ <Controller+ name="recordingStorageBackend"+ control={control}+ render={({ field }) => (+ <Field>+ <FieldLabel>Storage backend</FieldLabel>+ <FieldContent>+ <Select value={field.value} onValueChange={(v) => field.onChange(v)}>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {!isWindows && <SelectItem value="postgres">PostgreSQL (default)</SelectItem>}+ <SelectItem value="aws-s3">AWS S3</SelectItem>+ </SelectContent>+ </Select>+ <FieldDescription>+ {isWindows+ ? "RDP recordings require S3 storage."+ : "PostgreSQL stores recordings in the database. S3 is recommended for large or long sessions."}+ </FieldDescription>+ </FieldContent>+ </Field>+ )}+ />++ {storageBackend === "aws-s3" && (+ <>+ <Controller+ name="recordingConnectionId"+ control={control}+ render={({ field }) => (+ <Field>+ <FieldLabel>AWS Connection</FieldLabel>+ <FieldContent>+ <Select+ value={field.value ?? ""}+ onValueChange={(v) => field.onChange(v || null)}+ >+ <SelectTrigger>+ <SelectValue placeholder="Select an AWS connection" />+ </SelectTrigger>+ <SelectContent>+ {awsConnections.map((conn) => (+ <SelectItem key={conn.id} value={conn.id}>+ {conn.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldDescription>+ The AWS connection used to authenticate with S3.+ </FieldDescription>+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ name="s3Bucket"+ control={control}+ render={({ field }) => (+ <Field>+ <FieldLabel>S3 Bucket</FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="my-recordings-bucket" />+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ name="s3Region"+ control={control}+ render={({ field }) => (+ <Field>+ <FieldLabel>Region</FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="us-east-1" />+ </FieldContent>+ </Field>+ )}+ />++ <Controller+ name="s3KeyPrefix"+ control={control}+ render={({ field }) => (+ <Field>+ <FieldLabel>Key prefix (optional)</FieldLabel>+ <FieldContent>+ <Input {...field} placeholder="pam-recordings/" />+ <FieldDescription>Optional prefix for S3 object keys.</FieldDescription>+ </FieldContent>+ </Field>+ )}+ />+ </>+ )}+ </CardContent>+ </Card>+<div aria-hidden className="h-8 shrink-0" />{isDirty && <SheetSaveBar isPending={updateTemplate.isPending} onDiscard={() => reset()} />}</form>