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): redis web access, arrow key support (#5688)
Saif Ur Rahman4bebbd63d049
diff --git a/backend/src/ee/services/pam-web-access/pam-redis-formatter.test.ts b/backend/src/ee/services/pam-web-access/pam-redis-formatter.test.tsnew file mode 100644index 0000000000..6c04ef02ec--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-redis-formatter.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from "vitest";++import { formatRedisReply, tokenizeRedisInput } from "./pam-redis-formatter";++describe("tokenizeRedisInput", () => {+ it("splits simple command", () => {+ expect(tokenizeRedisInput("SET key value")).toEqual(["SET", "key", "value"]);+ });++ it("handles double-quoted strings", () => {+ expect(tokenizeRedisInput('SET key "hello world"')).toEqual(["SET", "key", "hello world"]);+ });++ it("handles single-quoted strings", () => {+ expect(tokenizeRedisInput("SET key 'hello world'")).toEqual(["SET", "key", "hello world"]);+ });++ it("handles multiple quoted arguments", () => {+ expect(tokenizeRedisInput('MSET "key one" "value one" "key two" "value two"')).toEqual([+ "MSET",+ "key one",+ "value one",+ "key two",+ "value two"+ ]);+ });++ it("handles single word command", () => {+ expect(tokenizeRedisInput("PING")).toEqual(["PING"]);+ });++ it("handles extra whitespace", () => {+ expect(tokenizeRedisInput(" SET key value ")).toEqual(["SET", "key", "value"]);+ });++ it("handles tabs", () => {+ expect(tokenizeRedisInput("SET\tkey\tvalue")).toEqual(["SET", "key", "value"]);+ });++ it("returns empty array for empty input", () => {+ expect(tokenizeRedisInput("")).toEqual([]);+ expect(tokenizeRedisInput(" ")).toEqual([]);+ });++ it("handles empty quoted string", () => {+ expect(tokenizeRedisInput('SET key ""')).toEqual(["SET", "key", ""]);+ });++ it("handles mixed quoted and unquoted", () => {+ expect(tokenizeRedisInput('MSET key1 "value 1" key2 value2')).toEqual([+ "MSET",+ "key1",+ "value 1",+ "key2",+ "value2"+ ]);+ });+});++describe("formatRedisReply", () => {+ it("formats null as (nil)", () => {+ expect(formatRedisReply(null)).toBe("(nil)");+ });++ it("formats undefined as (nil)", () => {+ expect(formatRedisReply(undefined)).toBe("(nil)");+ });++ it("formats integer", () => {+ expect(formatRedisReply(42)).toBe("(integer) 42");+ });++ it("formats zero", () => {+ expect(formatRedisReply(0)).toBe("(integer) 0");+ });++ it("formats negative integer", () => {+ expect(formatRedisReply(-1)).toBe("(integer) -1");+ });++ it("formats string with quotes", () => {+ expect(formatRedisReply("hello world")).toBe('"hello world"');+ });++ it("formats OK with quotes", () => {+ expect(formatRedisReply("OK")).toBe('"OK"');+ });++ it("escapes embedded double quotes", () => {+ expect(formatRedisReply('He said "hello"')).toBe('"He said \\"hello\\""');+ });++ it("escapes embedded backslashes", () => {+ expect(formatRedisReply("path\\to\\file")).toBe('"path\\\\to\\\\file"');+ });++ it("formats empty array", () => {+ expect(formatRedisReply([])).toBe("(empty array)");+ });++ it("formats simple array", () => {+ const result = formatRedisReply(["foo", "bar", "baz"]);+ expect(result).toBe('1) "foo"\n2) "bar"\n3) "baz"');+ });++ it("formats array with mixed types", () => {+ const result = formatRedisReply(["key", 42, null]);+ expect(result).toBe('1) "key"\n2) (integer) 42\n3) (nil)');+ });++ it("formats nested arrays", () => {+ const result = formatRedisReply([["a", "b"], ["c"]]);+ expect(result).toContain('1) 1) "a"');+ expect(result).toContain(' 2) "b"');+ expect(result).toContain('2) 1) "c"');+ });++ it("formats Buffer as quoted string", () => {+ const result = formatRedisReply(Buffer.from("hello"));+ expect(result).toBe('"hello"');+ });++ it("formats bigint", () => {+ expect(formatRedisReply(BigInt(999))).toBe("(integer) 999");+ });+});diff --git a/backend/src/ee/services/pam-web-access/pam-redis-formatter.ts b/backend/src/ee/services/pam-web-access/pam-redis-formatter.tsnew file mode 100644index 0000000000..c709b83871--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-redis-formatter.ts@@ -0,0 +1,70 @@+import RE2 from "re2";++const escapeBackslash = new RE2(/\\/, "g");+const escapeQuote = new RE2(/"/, "g");++const escapeRedisString = (str: string): string => str.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"');++export const tokenizeRedisInput = (input: string): string[] => {+ const tokens: string[] = [];+ let current = "";+ let inQuote: "'" | '"' | null = null;++ for (let i = 0; i < input.length; i += 1) {+ const ch = input[i];++ if (inQuote) {+ if (ch === inQuote) {+ tokens.push(current);+ current = "";+ inQuote = null;+ } else {+ current += ch;+ }+ } else if (ch === '"' || ch === "'") {+ inQuote = ch;+ } else if (ch === " " || ch === "\t") {+ if (current.length > 0) {+ tokens.push(current);+ current = "";+ }+ } else {+ current += ch;+ }+ }++ if (current.length > 0) {+ tokens.push(current);+ }++ return tokens;+};++export const formatRedisReply = (reply: unknown, indent: number = 0): string => {+ const prefix = " ".repeat(indent);++ if (reply === null || reply === undefined) {+ return `${prefix}(nil)`;+ }++ if (typeof reply === "number" || typeof reply === "bigint") {+ return `${prefix}(integer) ${reply}`;+ }++ if (typeof reply === "string") {+ return `${prefix}"${escapeRedisString(reply)}"`;+ }++ if (Buffer.isBuffer(reply)) {+ return `${prefix}"${escapeRedisString(reply.toString())}"`;+ }++ if (Array.isArray(reply)) {+ if (reply.length === 0) {+ return `${prefix}(empty array)`;+ }+ return reply.map((item, i) => `${prefix}${i + 1}) ${formatRedisReply(item, indent + 3).trimStart()}`).join("\n");+ }++ return `${prefix}"${String(reply)}"`;+};diff --git a/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-redis-session-handler.tsnew file mode 100644index 0000000000..7258c682c5--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-redis-session-handler.ts@@ -0,0 +1,172 @@+import { Redis } from "ioredis";++import {+ TRedisAccountCredentials,+ TRedisResourceConnectionDetails+} from "@app/ee/services/pam-resource/redis/redis-resource-types";+import { logger } from "@app/lib/logger";++import { formatRedisReply, tokenizeRedisInput } from "./pam-redis-formatter";+import {+ parseWsClientMessage,+ resolveEndReason,+ SessionEndReason,+ TSessionContext,+ TSessionHandlerResult,+ WsMessageType+} from "./pam-web-access-types";++type TRedisSessionParams = {+ connectionDetails: TRedisResourceConnectionDetails;+ credentials: TRedisAccountCredentials;+};++const executeCommand = async (redisClient: Redis, input: string): Promise<{ output: string; shouldClose: boolean }> => {+ const trimmed = input.trim();++ if (trimmed.length === 0) {+ return { output: "", shouldClose: false };+ }++ const lower = trimmed.toLowerCase();+ if (lower === "quit" || lower === "exit") {+ return { output: "Goodbye!\n", shouldClose: true };+ }++ const tokens = tokenizeRedisInput(trimmed);+ if (tokens.length === 0) {+ return { output: "", shouldClose: false };+ }++ const [command, ...args] = tokens;++ try {+ const result = await redisClient.call(command, ...args);+ return { output: `${formatRedisReply(result)}\n`, shouldClose: false };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return { output: `(error) ${message}\n`, shouldClose: false };+ }+};++export const handleRedisSession = async (+ ctx: TSessionContext,+ params: TRedisSessionParams+): Promise<TSessionHandlerResult> => {+ const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, isNearSessionExpiry, onCleanup } =+ ctx;+ const { connectionDetails, credentials } = params;++ const redisClient = new Redis({+ host: "localhost",+ port: relayPort,+ maxRetriesPerRequest: 0,+ reconnectOnError: () => false,+ retryStrategy: () => null+ });++ try {+ await new Promise<void>((resolve, reject) => {+ redisClient.once("ready", resolve);+ redisClient.once("error", reject);+ redisClient.once("close", () => reject(new Error("Redis connection closed before ready")));+ });+ } catch (err) {+ try {+ redisClient.disconnect();+ } catch {+ /* ignore */+ }+ throw err;+ }++ const prompt = `${connectionDetails.host}:${connectionDetails.port}> `;++ sendMessage({+ type: WsMessageType.Ready,+ data: `Connected to ${resourceName} (${connectionDetails.host}:${connectionDetails.port}) as ${credentials.username || "default"}\n\n`,+ prompt+ });++ logger.info({ sessionId }, "Redis web access session established");++ // Sequential message processing to prevent concurrent command issues+ let processingPromise = Promise.resolve();++ socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {+ processingPromise = processingPromise+ .then(async () => {+ const message = parseWsClientMessage(rawData);+ if (!message) {+ sendMessage({+ type: WsMessageType.Output,+ data: "Invalid message format\n",+ prompt+ });+ return;+ }++ if (message.type === WsMessageType.Control) {+ if (message.data === "quit") {+ sendSessionEnd(SessionEndReason.UserQuit);+ onCleanup();+ socket.close();+ return;+ }+ if (message.data === "clear-buffer") {+ return;+ }+ return;+ }++ if (message.type === WsMessageType.Input) {+ const result = await executeCommand(redisClient, message.data);++ if (result.shouldClose) {+ sendSessionEnd(SessionEndReason.UserQuit);+ onCleanup();+ socket.close();+ return;+ }++ sendMessage({+ type: WsMessageType.Output,+ data: result.output,+ prompt+ });+ }+ })+ .catch((err) => {+ logger.error(err, "Error processing Redis message");+ sendMessage({+ type: WsMessageType.Output,+ data: "Internal error\n",+ prompt+ });+ });+ });++ // Tunnel drop detection+ redisClient.on("error", (err) => {+ logger.error(err, "Redis connection error");+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));+ onCleanup();+ socket.close();+ });++ redisClient.on("close", () => {+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));+ onCleanup();+ socket.close();+ });++ return {+ cleanup: async () => {+ try {+ await redisClient.quit();+ } catch (err) {+ logger.debug(err, "Error closing Redis client");+ }+ }+ };+};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 7f26b36803..c1868b3c63 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@@ -39,10 +39,12 @@ import {TPostgresAccountCredentials,TPostgresResourceConnectionDetails} from "../pam-resource/postgres/postgres-resource-types";+import { TRedisAccountCredentials, TRedisResourceConnectionDetails } from "../pam-resource/redis/redis-resource-types";import { TSSHAccountCredentials, TSSHResourceConnectionDetails } from "../pam-resource/ssh/ssh-resource-types";import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";import { PamSessionStatus } from "../pam-session/pam-session-enums";import { handlePostgresSession } from "./pam-postgres-session-handler";+import { handleRedisSession } from "./pam-redis-session-handler";import { handleSSHSession } from "./pam-ssh-session-handler";import {DEFAULT_WEB_SESSION_DURATION_MS,@@ -58,7 +60,7 @@ import {WsMessageType} from "./pam-web-access-types";-const SUPPORTED_WEB_ACCESS_RESOURCES = [PamResource.Postgres, PamResource.SSH];+const SUPPORTED_WEB_ACCESS_RESOURCES = [PamResource.Postgres, PamResource.SSH, PamResource.Redis];type TPamWebAccessServiceFactoryDep = {pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "findMetadataByAccountIds">;@@ -528,6 +530,11 @@ export const pamWebAccessServiceFactory = ({connectionDetails: resourceConnectionDetails as TSSHResourceConnectionDetails,credentials: accountCredentials as TSSHAccountCredentials});+ } else if (resource.resourceType === PamResource.Redis) {+ handlerResult = await handleRedisSession(ctx, {+ connectionDetails: resourceConnectionDetails as TRedisResourceConnectionDetails,+ credentials: accountCredentials as TRedisAccountCredentials+ });}// 7. ACTIVATE SESSIONdiff --git a/docs/docs.json b/docs/docs.jsonindex 4ea609469c..bb0262c505 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -855,6 +855,7 @@"pages": ["documentation/platform/pam/product-reference/web-access/overview","documentation/platform/pam/product-reference/web-access/postgresql",+ "documentation/platform/pam/product-reference/web-access/redis","documentation/platform/pam/product-reference/web-access/ssh"]}diff --git a/docs/documentation/platform/pam/product-reference/web-access/overview.mdx b/docs/documentation/platform/pam/product-reference/web-access/overview.mdxindex ff3c3cd2f0..a797ea28df 100644--- a/docs/documentation/platform/pam/product-reference/web-access/overview.mdx+++ b/docs/documentation/platform/pam/product-reference/web-access/overview.mdx@@ -7,7 +7,7 @@ description: "Access PAM-managed resources directly from your browser with an inInfisical PAM Web Access provides a browser-based portal for interacting with your infrastructure directly from your browser via the Infisical dashboard — no client tools or CLI required.<Info>- Web Access currently supports **PostgreSQL** databases and **SSH** servers.+ Web Access currently supports **PostgreSQL** databases, **Redis** servers, and **SSH** servers.</Info>## How It Works@@ -48,6 +48,9 @@ Sessions that exceed the idle timeout or max duration are automatically terminat<Card title="PostgreSQL" icon="database" href="/documentation/platform/pam/product-reference/web-access/postgresql">Interactive SQL terminal with psql-style output formatting.</Card>+ <Card title="Redis" icon="database" href="/documentation/platform/pam/product-reference/web-access/redis">+ Interactive Redis REPL with redis-cli-style output formatting.+ </Card><Card title="SSH" icon="terminal" href="/documentation/platform/pam/product-reference/web-access/ssh">Full interactive shell session via browser-based terminal.</Card>diff --git a/docs/documentation/platform/pam/product-reference/web-access/redis.mdx b/docs/documentation/platform/pam/product-reference/web-access/redis.mdxnew file mode 100644index 0000000000..97402d55bd--- /dev/null+++ b/docs/documentation/platform/pam/product-reference/web-access/redis.mdx@@ -0,0 +1,60 @@+---+title: "Redis Web Access"+sidebarTitle: "Redis"+description: "Run Redis commands directly from your browser with an interactive REPL."+---++The Redis web access terminal provides a `redis-cli`-like experience in your browser. It is designed for light, ad-hoc usage — quick lookups, debugging, and administrative tasks — not as a replacement for a full Redis client or long-running workloads.++## Connecting++<Steps>+ <Step title="Navigate to Account">+ Go to the **Resources** tab in your PAM project, open the Redis resource, and find the account you want to access. Click the **Connect** button next to the account.++ ++ Alternatively, if you are on the account page, click the **Access** button.++ + </Step>++ <Step title="Connect in Browser">+ In the connect modal, click **Connect in Browser** to open the web access terminal.++ + </Step>++ <Step title="End Session">+ Click the **Disconnect** button from the web access terminal status bar or type `quit` or `exit`. You can reconnect from the same page.+ </Step>+</Steps>++++## Usage++Once connected, you'll see a `>` prompt. Type Redis commands as you would in `redis-cli`:++```+> SET greeting "Hello, World!"+OK+> GET greeting+"Hello, World!"+> KEYS *+1) "greeting"+> DEL greeting+(integer) 1+```++## Limits++See the [common session limits](/documentation/platform/pam/product-reference/web-access/overview#session-limits) that apply to all web access sessions.++## FAQ++<AccordionGroup>+ <Accordion title="Is this an actual redis-cli session?">+ No. The web access terminal is not a `redis-cli` client. It is a custom REPL that connects directly to Redis and provides a `redis-cli`-like experience, including familiar prompts and reply formatting.+ </Accordion>+</AccordionGroup>diff --git a/docs/images/pam/product-reference/web-access/redis-account-connect-button.png b/docs/images/pam/product-reference/web-access/redis-account-connect-button.pngnew file mode 100644index 0000000000..84ba47bc86Binary files /dev/null and b/docs/images/pam/product-reference/web-access/redis-account-connect-button.png differdiff --git a/docs/images/pam/product-reference/web-access/redis-account-page-access-button.png b/docs/images/pam/product-reference/web-access/redis-account-page-access-button.pngnew file mode 100644index 0000000000..caf1d25bd0Binary files /dev/null and b/docs/images/pam/product-reference/web-access/redis-account-page-access-button.png differdiff --git a/docs/images/pam/product-reference/web-access/redis-connect-in-browser.png b/docs/images/pam/product-reference/web-access/redis-connect-in-browser.pngnew file mode 100644index 0000000000..854d9d80d6Binary files /dev/null and b/docs/images/pam/product-reference/web-access/redis-connect-in-browser.png differdiff --git a/docs/images/pam/product-reference/web-access/redis-web-access-terminal.png b/docs/images/pam/product-reference/web-access/redis-web-access-terminal.pngnew file mode 100644index 0000000000..b7a338527fBinary files /dev/null and b/docs/images/pam/product-reference/web-access/redis-web-access-terminal.png differdiff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 724b6e6e48..c78b6b5b21 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -104,6 +104,7 @@"tailwind-merge": "^2.5.5","tweetnacl": "^1.0.3","tweetnacl-util": "^0.15.1",+ "xterm-readline": "^1.1.2","yaml": "^2.6.1","zod": "^3.24.1","zustand": "^5.0.2"@@ -16805,6 +16806,38 @@"node": ">=0.4"}},+ "node_modules/xterm-readline": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/xterm-readline/-/xterm-readline-1.1.2.tgz",+ "integrity": "sha512-1+W2nVuQvCYz9OUYwFBiolrSQUui51aDDyacKXt4PuxeBHqzvabQEJ2kwdBDzsmOjz5BwlDTAjJmYpH2OGqLFA==",+ "license": "MIT",+ "dependencies": {+ "string-width": "^4"+ },+ "peerDependencies": {+ "@xterm/xterm": "^5.5.0"+ }+ },+ "node_modules/xterm-readline/node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "license": "MIT"+ },+ "node_modules/xterm-readline/node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/y18n": {"version": "4.0.3","resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex e1c4991534..93469e6e4f 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -113,6 +113,7 @@"tailwind-merge": "^2.5.5","tweetnacl": "^1.0.3","tweetnacl-util": "^0.15.1",+ "xterm-readline": "^1.1.2","yaml": "^2.6.1","zod": "^3.24.1","zustand": "^5.0.2"diff --git a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.tsindex 61f8cf03d4..1116c96f61 100644--- a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts+++ b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react";import { FitAddon } from "@xterm/addon-fit";import { WebLinksAddon } from "@xterm/addon-web-links";import { Terminal } from "@xterm/xterm";+import { Readline } from "xterm-readline";import { apiRequest } from "@app/config/request";import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession/types";@@ -38,6 +39,10 @@ export const useWebAccessSession = ({const inputBufferRef = useRef("");const currentPromptRef = useRef("");const promptCallbackRef = useRef<((input: string) => void) | null>(null);+ const readlineRef = useRef<Readline | null>(null);+ const readLoopActiveRef = useRef(false);+ const nextPromptResolverRef = useRef<((prompt: string) => void) | null>(null);+ const nextPromptRejecterRef = useRef<((reason: Error) => void) | null>(null);const onSessionEndRef = useRef(onSessionEnd);@@ -83,6 +88,43 @@ export const useWebAccessSession = ({const ws = new WebSocket(wsUrl);wsRef.current = ws;+ const waitForNextPrompt = (): Promise<string> => {+ return new Promise<string>((resolve, reject) => {+ nextPromptResolverRef.current = resolve;+ nextPromptRejecterRef.current = reject;+ });+ };++ const runReadLoop = async (rl: Readline, initialPrompt: string) => {+ readLoopActiveRef.current = true;+ let prompt = initialPrompt;++ while (readLoopActiveRef.current) {+ let line: string;+ try {+ // eslint-disable-next-line no-await-in-loop -- intentional sequential read loop+ line = await rl.read(prompt);+ } catch {+ break;+ }++ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {+ break;+ }++ wsRef.current.send(JSON.stringify({ type: WsMessageType.Input, data: line }));++ try {+ // eslint-disable-next-line no-await-in-loop+ prompt = await waitForNextPrompt();+ } catch {+ break;+ }+ }++ readLoopActiveRef.current = false;+ };+ws.onmessage = (event) => {let raw: unknown;try {@@ -110,7 +152,19 @@ export const useWebAccessSession = ({);}+ if (!isSSH && readlineRef.current) {+ const rl = readlineRef.current;+ if (msg.data) {+ rl.print(msg.data.replace(/\r?\n/g, "\r\n"));+ }+ runReadLoop(rl, msg.prompt || "=> ");+ } else if (!isSSH) {+ if (msg.data) terminal.write(msg.data.replace(/\r?\n/g, "\r\n"));+ if (msg.prompt) terminal.write(msg.prompt);+ }+setTimeout(() => terminal.focus(), 100);+ return;}if (msg.type === WsMessageType.SessionEnd) {@@ -123,20 +177,32 @@ export const useWebAccessSession = ({adjustWidthForOutput(msg.data, terminal, fitAddonRef.current, containerEl);}if (isSSH) {- // Raw ANSI passthrough — no newline normalizationterminal.write(msg.data);- } else {- terminal.write(msg.data.replace(/\r?\n/g, "\r\n"));+ } else if (readlineRef.current) {+ readlineRef.current.print(msg.data.replace(/\r?\n/g, "\r\n"));}}+if (msg.prompt && !isSSH) {- currentPromptRef.current = msg.prompt;- terminal.write(msg.prompt);+ if (nextPromptResolverRef.current) {+ const resolve = nextPromptResolverRef.current;+ nextPromptResolverRef.current = null;+ nextPromptRejecterRef.current = null;+ resolve(msg.prompt);+ }}};ws.onclose = () => {wsRef.current = null;+ readLoopActiveRef.current = false;++ if (nextPromptRejecterRef.current) {+ nextPromptRejecterRef.current(new Error("disconnected"));+ nextPromptResolverRef.current = null;+ nextPromptRejecterRef.current = null;+ }+if (terminalRef.current) {terminalRef.current.options.disableStdin = true;}@@ -159,6 +225,9 @@ export const useWebAccessSession = ({currentPromptRef.current = "";const prompt = (message: string): Promise<string> => {+ if (!isSSH && readlineRef.current) {+ return readlineRef.current.read(message);+ }return new Promise((resolve) => {terminal.write(message);promptCallbackRef.current = resolve;@@ -443,39 +512,19 @@ export const useWebAccessSession = ({}});} else {- // Postgres: existing line-buffered behavior- terminal.onData((data) => {- if (data === "\r") {- terminal.write("\r\n");- if (promptCallbackRef.current) {- const cb = promptCallbackRef.current;- promptCallbackRef.current = null;- cb(inputBufferRef.current);- inputBufferRef.current = "";- } else if (wsRef.current?.readyState === WebSocket.OPEN) {- wsRef.current.send(- JSON.stringify({ type: WsMessageType.Input, data: inputBufferRef.current })- );- inputBufferRef.current = "";- }- } else if (data === "\x7f") {- if (inputBufferRef.current.length > 0) {- inputBufferRef.current = inputBufferRef.current.slice(0, -1);- terminal.write("\b \b");- }- } else if (data === "\x03") {- terminal.write("^C\r\n");- inputBufferRef.current = "";+ // Non-SSH (PostgreSQL, Redis): use xterm-readline for full line-editing support+ const readlineAddon = new Readline();+ terminal.loadAddon(readlineAddon);+ readlineRef.current = readlineAddon;++ // Ctrl+C: send clear-buffer to backend (readline handles visual reset internally)+ terminal.onKey(({ domEvent }) => {+ if (domEvent.ctrlKey && domEvent.key === "c") {if (wsRef.current?.readyState === WebSocket.OPEN) {wsRef.current.send(JSON.stringify({ type: WsMessageType.Control, data: "clear-buffer" }));}- terminal.write(currentPromptRef.current);- } else if (data >= " " || data === "\t") {- const normalized = data.replace(/\r\n|\r/g, "\n");- inputBufferRef.current += normalized;- terminal.write(normalized.replace(/\n/g, "\r\n"));}});}@@ -490,6 +539,8 @@ export const useWebAccessSession = ({connect();return () => {+ readLoopActiveRef.current = false;+ readlineRef.current = null;terminalRef.current = null;fitAddonRef.current = null;window.removeEventListener("resize", handleResize);diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsxindex 74016378f7..302449f8cd 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx@@ -89,7 +89,8 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectIdconst showWebAccess =account.resource.resourceType === PamResourceType.Postgres ||- account.resource.resourceType === PamResourceType.SSH;+ account.resource.resourceType === PamResourceType.SSH ||+ account.resource.resourceType === PamResourceType.Redis;return (<Modal isOpen={isOpen} onOpenChange={onOpenChange}>