Skip to content

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

Add SSH web access support (#5521)

Saif Ur Rahman1048b62fef30
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
new file mode 100644
index 0000000000..0ec2d68b7f
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
@@ -0,0 +1,138 @@
+import pg from "pg";
+
+import {
+ TPostgresAccountCredentials,
+ TPostgresResourceConnectionDetails
+} from "@app/ee/services/pam-resource/postgres/postgres-resource-types";
+import { logger } from "@app/lib/logger";
+
+import { createPamSqlRepl } from "./pam-web-access-repl";
+import {
+ parseWsClientMessage,
+ resolveEndReason,
+ SessionEndReason,
+ TSessionContext,
+ TSessionHandlerResult,
+ WsMessageType
+} from "./pam-web-access-types";
+
+type TPostgresSessionParams = {
+ connectionDetails: TPostgresResourceConnectionDetails;
+ credentials: TPostgresAccountCredentials;
+};
+
+export const handlePostgresSession = async (
+ ctx: TSessionContext,
+ params: TPostgresSessionParams
+): Promise<TSessionHandlerResult> => {
+ const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, isNearSessionExpiry, onCleanup } =
+ ctx;
+ const { connectionDetails, credentials } = params;
+
+ const pgClient = new pg.Client({
+ host: "localhost",
+ port: relayPort,
+ user: credentials.username,
+ database: connectionDetails.database,
+ password: "",
+ ssl: false,
+ connectionTimeoutMillis: 30_000,
+ statement_timeout: 30_000,
+ types: {
+ getTypeParser: () => (val: string | Buffer) => (typeof val === "string" ? val : val.toString("hex"))
+ }
+ });
+
+ await pgClient.connect();
+
+ const repl = createPamSqlRepl(pgClient);
+
+ sendMessage({
+ type: WsMessageType.Ready,
+ data: `Connected to ${resourceName} (${connectionDetails.database}) as ${credentials.username}\n\n`,
+ prompt: "=> "
+ });
+
+ logger.info({ sessionId }, "Postgres web access session established");
+
+ // Sequential message processing to prevent concurrent query 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: repl.getPrompt()
+ });
+ return;
+ }
+
+ if (message.type === WsMessageType.Control) {
+ if (message.data === "quit") {
+ sendSessionEnd(SessionEndReason.UserQuit);
+ onCleanup();
+ socket.close();
+ return;
+ }
+ if (message.data === "clear-buffer") {
+ repl.clearBuffer();
+ return;
+ }
+ return;
+ }
+
+ if (message.type === WsMessageType.Input) {
+ const replResult = await repl.processInput(message.data);
+
+ if (replResult.shouldClose) {
+ sendSessionEnd(SessionEndReason.UserQuit);
+ onCleanup();
+ socket.close();
+ return;
+ }
+
+ sendMessage({
+ type: WsMessageType.Output,
+ data: replResult.output,
+ prompt: replResult.prompt
+ });
+ }
+ })
+ .catch((err) => {
+ logger.error(err, "Error processing Postgres message");
+ sendMessage({
+ type: WsMessageType.Output,
+ data: "Internal error\n",
+ prompt: "=> "
+ });
+ });
+ });
+
+ // Tunnel drop detection
+ pgClient.on("error", (err) => {
+ logger.error(err, "Database connection error");
+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));
+ onCleanup();
+ socket.close();
+ });
+
+ pgClient.on("end", () => {
+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));
+ onCleanup();
+ socket.close();
+ });
+
+ return {
+ cleanup: async () => {
+ try {
+ await pgClient.end();
+ } catch (err) {
+ logger.debug(err, "Error closing pg client");
+ }
+ }
+ };
+};
diff --git a/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts
new file mode 100644
index 0000000000..f9a4191c7a
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-ssh-session-handler.ts
@@ -0,0 +1,144 @@
+import { Client, type ClientChannel, type ConnectConfig } from "ssh2";
+
+import {
+ TSSHAccountCredentials,
+ TSSHResourceConnectionDetails
+} from "@app/ee/services/pam-resource/ssh/ssh-resource-types";
+import { logger } from "@app/lib/logger";
+
+import {
+ parseWsClientMessage,
+ resolveEndReason,
+ SessionEndReason,
+ TSessionContext,
+ TSessionHandlerResult,
+ WsMessageType
+} from "./pam-web-access-types";
+
+type TSSHSessionParams = {
+ connectionDetails: TSSHResourceConnectionDetails;
+ credentials: TSSHAccountCredentials;
+};
+
+export const handleSSHSession = async (
+ ctx: TSessionContext,
+ params: TSSHSessionParams
+): Promise<TSessionHandlerResult> => {
+ const { socket, relayPort, resourceName, sessionId, sendMessage, sendSessionEnd, isNearSessionExpiry, onCleanup } =
+ ctx;
+ const { credentials } = params;
+
+ const client = new Client();
+ let stream: ClientChannel | null = null;
+
+ const connectConfig: ConnectConfig = {
+ host: "localhost",
+ port: relayPort,
+ username: credentials.username,
+ readyTimeout: 30_000,
+ authHandler: ["none"]
+ };
+
+ return new Promise((resolve, reject) => {
+ client.on("ready", () => {
+ client.shell({ term: "xterm-256color", rows: 24, cols: 80 }, (err, shellStream) => {
+ if (err) {
+ logger.error(err, "Failed to open SSH shell");
+ sendSessionEnd(SessionEndReason.SetupFailed);
+ client.end();
+ reject(err);
+ return;
+ }
+
+ stream = shellStream;
+
+ // Send Ready message
+ sendMessage({
+ type: WsMessageType.Ready,
+ data: `Connected to ${resourceName} as ${credentials.username}\r\n`
+ });
+
+ logger.info({ sessionId }, "SSH web access session shell opened");
+
+ // SSH -> WS: forward output from remote shell to WebSocket
+ shellStream.on("data", (data: Buffer) => {
+ sendMessage({
+ type: WsMessageType.Output,
+ data: data.toString("utf-8")
+ });
+ });
+
+ shellStream.stderr.on("data", (data: Buffer) => {
+ sendMessage({
+ type: WsMessageType.Output,
+ data: data.toString("utf-8")
+ });
+ });
+
+ // WS -> SSH: forward input from WebSocket to remote shell
+ socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {
+ const message = parseWsClientMessage(rawData);
+ if (!message) return;
+
+ if (message.type === WsMessageType.Input) {
+ // Raw keystroke forwarding — no buffering, no local echo
+ shellStream.write(message.data);
+ } else if (message.type === WsMessageType.Resize) {
+ try {
+ const { rows, cols } = JSON.parse(message.data) as { rows: number; cols: number };
+ shellStream.setWindow(rows, cols, 0, 0);
+ } catch {
+ logger.debug("Invalid resize data received");
+ }
+ } else if (message.type === WsMessageType.Control) {
+ if (message.data === "quit") {
+ shellStream.close();
+ client.end();
+ }
+ }
+ });
+
+ // Shell stream close
+ shellStream.on("close", () => {
+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));
+ onCleanup();
+ socket.close();
+ });
+
+ resolve({
+ cleanup: async () => {
+ try {
+ stream?.close();
+ } catch (streamErr) {
+ logger.debug(streamErr, "Error closing SSH stream");
+ }
+ try {
+ client.end();
+ } catch (clientErr) {
+ logger.debug(clientErr, "Error closing SSH client");
+ }
+ }
+ });
+ });
+ });
+
+ client.on("error", (err) => {
+ logger.error(err, "SSH client connection error");
+ if (stream) {
+ // Session was established, then errored
+ sendSessionEnd(resolveEndReason(isNearSessionExpiry));
+ onCleanup();
+ socket.close();
+ } else {
+ // Connection never established
+ reject(err);
+ }
+ });
+
+ client.on("end", () => {
+ logger.debug({ sessionId }, "SSH client connection ended");
+ });
+
+ client.connect(connectConfig);
+ });
+};
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.ts
index 4023d81607..7f26b36803 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
@@ -1,7 +1,6 @@
import net from "node:net";
import { ForbiddenError, subject } from "@casl/ability";
-import pg from "pg";
import type WebSocket from "ws";
import { ActionProjectType } from "@app/db/schemas";
@@ -40,21 +39,27 @@ import {
TPostgresAccountCredentials,
TPostgresResourceConnectionDetails
} from "../pam-resource/postgres/postgres-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 { createPamSqlRepl } from "./pam-web-access-repl";
+import { handlePostgresSession } from "./pam-postgres-session-handler";
+import { handleSSHSession } from "./pam-ssh-session-handler";
import {
DEFAULT_WEB_SESSION_DURATION_MS,
MAX_WEB_SESSIONS_PER_USER,
SessionEndReason,
TIssueWebSocketTicketDTO,
+ TSessionContext,
+ TSessionHandlerResult,
TWebSocketServerMessage,
- WebSocketClientMessageSchema,
+ WebSocketServerMessageSchema,
WS_IDLE_TIMEOUT_MS,
WS_PING_INTERVAL_MS,
WsMessageType
} from "./pam-web-access-types";
+const SUPPORTED_WEB_ACCESS_RESOURCES = [PamResource.Postgres, PamResource.SSH];
+
type TPamWebAccessServiceFactoryDep = {
pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "findMetadataByAccountIds">;
pamResourceDAL: Pick<TPamResourceDALFactory, "findById">;
@@ -112,7 +117,8 @@ export const pamWebAccessServiceFactory = ({
const sendMessage = (socket: WebSocket, message: TWebSocketServerMessage): void => {
try {
if (socket.readyState === socket.OPEN) {
- socket.send(JSON.stringify(message));
+ const parsed = WebSocketServerMessageSchema.parse(message);
+ socket.send(JSON.stringify(parsed));
}
} catch (err) {
logger.error(err, "Failed to send WebSocket message");
@@ -149,9 +155,9 @@ export const pamWebAccessServiceFactory = ({
throw new NotFoundError({ message: `Resource with ID '${account.resourceId}' not found` });
}
- if (resource.resourceType !== PamResource.Postgres) {
+ if (!SUPPORTED_WEB_ACCESS_RESOURCES.includes(resource.resourceType as PamResource)) {
throw new BadRequestError({
- message: "Web access is currently only supported for PostgreSQL accounts"
+ message: "Web access is not supported for this resource type"
});
}
@@ -302,7 +308,7 @@ export const pamWebAccessServiceFactory = ({
}: THandleWebSocketConnectionDTO): Promise<void> => {
let session: { id: string } | null = null;
let cleanedUp = false;
- let pgClient: pg.Client | null = null;
+ let handlerResult: TSessionHandlerResult | null = null;
let relayServer: { port: number; cleanup: () => Promise<void> } | null = null;
let relayCerts: {
relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
@@ -329,18 +335,18 @@ export const pamWebAccessServiceFactory = ({
idleTimer = null;
}
- // End pg client (needs tunnel to send Terminate message)
- if (pgClient) {
+ // Handler cleanup (closes protocol client through the tunnel)
+ if (handlerResult) {
try {
- await pgClient.end();
+ await handlerResult.cleanup();
} catch (err) {
- logger.debug(err, "Error closing pg client");
+ logger.debug(err, "Error in handler cleanup");
} finally {
- pgClient = null;
+ handlerResult = null;
}
}
- // Close relay tunnel
+ // Close relay tunnel (MUST come after handler cleanup)
if (relayServer) {
try {
await relayServer.cleanup();
@@ -395,8 +401,8 @@ export const pamWebAccessServiceFactory = ({
throw new BadRequestError({ message: "Resource not found" });
}
- if (resource.resourceType !== PamResource.Postgres) {
- throw new BadRequestError({ message: "Web access is only supported for PostgreSQL" });
+ if (!SUPPORTED_WEB_ACCESS_RESOURCES.includes(resource.resourceType as PamResource)) {
+ throw new BadRequestError({ message: "Web access is not supported for this resource type" });
}
if (!resource.gatewayId) {
@@ -408,25 +414,25 @@ export const pamWebAccessServiceFactory = ({
if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {
sendMessage(socket, {
type: WsMessageType.Output,
- data: `Maximum concurrent web sessions (${MAX_WEB_SESSIONS_PER_USER}) reached. Please close an existing session first.\n`,
- prompt: ""
+ data: `Maximum concurrent web sessions (${MAX_WEB_SESSIONS_PER_USER}) reached. Please close an existing session first.\n`
});
socket.close();
return;
}
// 2. DECRYPT
- const resourceConnectionDetails = (await decryptResourceConnectionDetails({
+ const resourceConnectionDetails = await decryptResourceConnectionDetails({
projectId,
encryptedConnectionDetails: resource.encryptedConnectionDetails,
kmsService
- })) as TPostgresResourceConnectionDetails;
+ });
+ const { host, port } = resourceConnectionDetails as { host: string; port: number };
- const accountCredentials = (await decryptAccountCredentials({
+ const accountCredentials = await decryptAccountCredentials({
projectId,
encryptedCredentials: account.encryptedCredentials,
kmsService
- })) as TPostgresAccountCredentials;
+ });
// 3. CREATE SESSION
const user = await userDAL.findById(userId);
@@ -454,9 +460,9 @@ export const pamWebAccessServiceFactory = ({
const certs = await gatewayV2Service.getPAMConnectionDetails({
gatewayId: resource.gatewayId,
sessionId: session.id,
- resourceType: PamResource.Postgres,
- host: resourceConnectionDetails.host,
- port: resourceConnectionDetails.port,
+ resourceType: resource.resourceType as PamResource,
+ host,
+ port,
duration: DEFAULT_WEB_SESSION_DURATION_MS,
actorMetadata: {
id: userId,
@@ -484,27 +490,45 @@ export const pamWebAccessServiceFactory = ({
longLived: true
});
- // 6. CONNECT PG
- pgClient = new pg.Client({
- host: "localhost",
- port: relayServer.port,
- user: accountCredentials.username,
- database: resourceConnectionDetails.database,
- password: "",
- ssl: false,
- // Max time to wait for TCP connection
- connectionTimeoutMillis: 30_000,
- // Max execution time per SQL statement (sent as a PostgreSQL connection parameter)
- statement_timeout: 30_000,
- // Return raw strings for ALL types — we only display values, never compute with them.
- // Without this, pg auto-parses timestamps to JS Date objects (verbose toString()),
- // booleans to true/false (psql shows t/f), JSON to objects, arrays to JS arrays, etc.
- types: {
- getTypeParser: () => (val: string | Buffer) => (typeof val === "string" ? val : val.toString("hex"))
+ // Tunnel drop detection
+ // The gateway cert expires on the gateway's clock, which may be slightly
+ // ahead of ours (clock skew). A 30s tolerance lets us correctly attribute
+ // tunnel teardowns near session end as normal completion rather than errors.
+ const isNearSessionExpiry = () => Date.now() >= expiresAt.getTime() - 30_000;
+
+ // Bound message helpers for handlers
+ const boundSendMessage = (msg: TWebSocketServerMessage) => sendMessage(socket, msg);
+ const boundSendSessionEnd = (reason: SessionEndReason) => sendSessionEnd(socket, reason);
+ const handlerCleanup = () => {
+ if (!cleanedUp) {
+ void cleanup();
}
- });
+ };
- await pgClient.connect();
+ // Build session context once — passed to any handler
+ const ctx: TSessionContext = {
+ socket,
+ relayPort: relayServer.port,
+ resourceName: resource.name,
+ sessionId: session.id,
+ sendMessage: boundSendMessage,
+ sendSessionEnd: boundSendSessionEnd,
+ isNearSessionExpiry,
+ onCleanup: handlerCleanup
+ };
+
+ // 6. CONNECT TO RESOURCE (dispatch by type)
+ if (resource.resourceType === PamResource.Postgres) {
+ handlerResult = await handlePostgresSession(ctx, {
+ connectionDetails: resourceConnectionDetails as TPostgresResourceConnectionDetails,
+ credentials: accountCredentials as TPostgresAccountCredentials
+ });
+ } else if (resource.resourceType === PamResource.SSH) {
+ handlerResult = await handleSSHSession(ctx, {
+ connectionDetails: resourceConnectionDetails as TSSHResourceConnectionDetails,
+ credentials: accountCredentials as TSSHAccountCredentials
+ });
+ }
// 7. ACTIVATE SESSION
await pamSessionDAL.updateById(session.id, {
@@ -512,15 +536,6 @@ export const pamWebAccessServiceFactory = ({
startedAt: new Date()
});
- // 8. INIT REPL + SEND READY
- const repl = createPamSqlRepl(pgClient);
-
- sendMessage(socket, {
- type: WsMessageType.Ready,
- data: `Connected to ${resource.name} (${resourceConnectionDetails.database}) as ${accountCredentials.username}\n\n`,
- prompt: "=> "
- });
-
logger.info({ accountId, sessionId: session.id }, "Web access session established");
await auditLogService.createAuditLog({
@@ -538,7 +553,7 @@ export const pamWebAccessServiceFactory = ({
}
});
- // 9. SET UP HANDLERS
+ // 8. SET UP COMMON HANDLERS
const resetIdleTimer = () => {
if (idleTimer) clearTimeout(idleTimer);
@@ -572,122 +587,9 @@ export const pamWebAccessServiceFactory = ({
}
}, WS_PING_INTERVAL_MS);
- // Sequential message processing to prevent concurrent query issues
- let processingPromise = Promise.resolve();
-
- socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {
+ // Reset idle timer on any incoming message
+ socket.on("message", () => {
resetIdleTimer();
- processingPromise = processingPromise
- .then(async () => {
- if (cleanedUp) return;
-
- let data: string;
- if (Buffer.isBuffer(rawData)) {
- data = rawData.toString();
- } else if (Array.isArray(rawData)) {
- data = Buffer.concat(rawData).toString();
- } else {
- data = Buffer.from(rawData).toString();
- }
-
- let parsed: unknown;
- try {
- parsed = JSON.parse(data);
- } catch {
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: "Invalid message format\n",
- prompt: repl.getPrompt()
- });
- return;
- }
- const result = WebSocketClientMessageSchema.safeParse(parsed);
- if (!result.success) {
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: "Invalid message format\n",
- prompt: repl.getPrompt()
- });
- return;
- }
-
- const message = result.data;
-
- // Control messages
- if (message.type === WsMessageType.Control) {
- if (message.data === "quit") {
- sendSessionEnd(socket, SessionEndReason.UserQuit);
- void cleanup();
- socket.close();
- return;
- }
- if (message.data === "clear-buffer") {
- repl.clearBuffer();
- // No response — frontend already writes ^C and prompt locally
- return;
- }
- return;
- }
-
- // User input
- if (message.type === WsMessageType.Input) {
- const replResult = await repl.processInput(message.data);
-
- if (replResult.shouldClose) {
- sendSessionEnd(socket, SessionEndReason.UserQuit);
- void cleanup();
- socket.close();
- return;
- }
-
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: replResult.output,
- prompt: replResult.prompt
- });
- }
- })
- .catch((err) => {
- logger.error(err, "Error processing message");
- if (!cleanedUp) {
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: "Internal error\n",
- prompt: "=> "
- });
- }
- });
- });
-
- // Tunnel drop detection
- // The gateway cert expires on the gateway's clock, which may be slightly
- // ahead of ours (clock skew). A 30s tolerance lets us correctly attribute
- // tunnel teardowns near session end as normal completion rather than errors.
- const isNearSessionExpiry = () => Date.now() >= expiresAt.getTime() - 30_000;
-
- pgClient.on("error", (err) => {
- logger.error(err, "Database connection error");
- if (!cleanedUp) {
- if (isNearSessionExpiry()) {
- sendSessionEnd(socket, SessionEndReason.SessionCompleted);
- } else {
- sendSessionEnd(socket, SessionEndReason.ConnectionLost);
- }
- void cleanup();
- socket.close();
- }
- });
-
- pgClient.on("end", () => {
- if (!cleanedUp) {
- if (isNearSessionExpiry()) {
- sendSessionEnd(socket, SessionEndReason.SessionCompleted);
- } else {
- sendSessionEnd(socket, SessionEndReason.ConnectionLost);
- }
- void cleanup();
- socket.close();
- }
});
// Session expiry timer
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
index 5ad0fd9d65..d39f302b66 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts
@@ -1,3 +1,4 @@
+import type WebSocket from "ws";
import { z } from "zod";
import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";
@@ -20,21 +21,22 @@ export enum WsMessageType {
Output = "output",
Input = "input",
Control = "control",
+ Resize = "resize",
SessionEnd = "session_end"
}
export enum SessionEndReason {
SessionCompleted = "Session duration complete. Connection closed.",
UserQuit = "Goodbye!",
- ConnectionLost = "Database connection lost. Session ended.",
- SetupFailed = "Failed to establish database connection.",
+ ConnectionLost = "Connection lost. Session ended.",
+ SetupFailed = "Failed to establish connection.",
IdleTimeout = "Session closed due to inactivity."
}
const WebSocketOutputMessageSchema = z.object({
type: z.enum([WsMessageType.Ready, WsMessageType.Output]),
data: z.string(),
- prompt: z.string()
+ prompt: z.string().default("")
});
const WebSocketSessionEndMessageSchema = z.object({
@@ -47,13 +49,49 @@ export const WebSocketServerMessageSchema = z.discriminatedUnion("type", [
WebSocketSessionEndMessageSchema
]);
-export type TWebSocketServerMessage = z.infer<typeof WebSocketServerMessageSchema>;
+export type TWebSocketServerMessage = z.input<typeof WebSocketServerMessageSchema>;
export const WebSocketClientMessageSchema = z.object({
- type: z.enum([WsMessageType.Input, WsMessageType.Control]),
+ type: z.enum([WsMessageType.Input, WsMessageType.Control, WsMessageType.Resize]),
data: z.string()
});
+export type TSessionContext = {
+ socket: WebSocket;
+ relayPort: number;
+ resourceName: string;
+ sessionId: string;
+ sendMessage: (msg: TWebSocketServerMessage) => void;
+ sendSessionEnd: (reason: SessionEndReason) => void;
+ isNearSessionExpiry: () => boolean;
+ onCleanup: () => void;
+};
+
+export type TSessionHandlerResult = {
+ cleanup: () => Promise<void>;
+};
+
+export const resolveEndReason = (isNearSessionExpiry: () => boolean): SessionEndReason =>
+ isNearSessionExpiry() ? SessionEndReason.SessionCompleted : SessionEndReason.ConnectionLost;
+
+export const parseWsClientMessage = (
+ rawData: Buffer | ArrayBuffer | Buffer[]
+): z.infer<typeof WebSocketClientMessageSchema> | null => {
+ let data: string;
+ if (Buffer.isBuffer(rawData)) data = rawData.toString();
+ else if (Array.isArray(rawData)) data = Buffer.concat(rawData).toString();
+ else data = Buffer.from(rawData).toString();
+
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(data);
+ } catch {
+ return null;
+ }
+ const result = WebSocketClientMessageSchema.safeParse(parsed);
+ return result.success ? result.data : null;
+};
+
export type TIssueWebSocketTicketDTO = {
accountId: string;
projectId: string;
diff --git a/docs/docs.json b/docs/docs.json
index 9d78284cc7..c19e28629a 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -840,7 +840,8 @@
"group": "Web Access",
"pages": [
"documentation/platform/pam/product-reference/web-access/overview",
- "documentation/platform/pam/product-reference/web-access/postgresql"
+ "documentation/platform/pam/product-reference/web-access/postgresql",
+ "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.mdx
index 8cbc7b83a0..ff3c3cd2f0 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 in
Infisical 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.
+ Web Access currently supports **PostgreSQL** databases and **SSH** servers.
</Info>
## How It Works
@@ -48,4 +48,7 @@ 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="SSH" icon="terminal" href="/documentation/platform/pam/product-reference/web-access/ssh">
+ Full interactive shell session via browser-based terminal.
+ </Card>
</CardGroup>
diff --git a/docs/documentation/platform/pam/product-reference/web-access/ssh.mdx b/docs/documentation/platform/pam/product-reference/web-access/ssh.mdx
new file mode 100644
index 0000000000..a3b06e5418
--- /dev/null
+++ b/docs/documentation/platform/pam/product-reference/web-access/ssh.mdx
@@ -0,0 +1,55 @@
+---
+title: "SSH Web Access"
+sidebarTitle: "SSH"
+description: "Connect to SSH servers directly from your browser with an interactive terminal."
+---
+
+The SSH web access terminal provides a browser-based interactive shell for SSH servers. It is designed for quick interactive sessions — running commands, debugging, and administrative tasks.
+
+## Connecting
+
+<Steps>
+ <Step title="Navigate to Account">
+ Go to the **Resources** tab in your PAM project, open the SSH resource, and find the account you want to access. Click the **Connect** button next to the account.
+
+ ![Account Connect Button](/images/pam/product-reference/web-access/ssh-account-connect-button.png)
+
+ Alternatively, if you are on the account page, click the **Access** button.
+
+ ![Account Page Access Button](/images/pam/product-reference/web-access/ssh-account-page-access-button.png)
+ </Step>
+
+ <Step title="Connect in Browser">
+ In the connect modal, click **Connect in Browser** to open the web access terminal.
+
+ ![Connect in Browser](/images/pam/product-reference/web-access/ssh-connect-in-browser.png)
+ </Step>
+
+ <Step title="End Session">
+ Click the **Disconnect** button from the web access terminal status bar or type `exit` or `logout`.
+ </Step>
+</Steps>
+
+![Web Access Terminal](/images/pam/product-reference/web-access/ssh-web-access-terminal.png)
+
+## Usage
+
+Once connected, you have a full interactive shell.
+
+## Authentication Methods
+
+All three SSH [authentication methods](/documentation/platform/pam/getting-started/resources/ssh#authentication-methods) are supported:
+
+- **Password** — username and password
+- **SSH Key** — public/private key pair
+- **Certificate** — SSH certificates
+
+Credentials are injected automatically from the PAM account configuration. You never need to enter or see them.
+
+## FAQ
+
+<AccordionGroup>
+ <Accordion title="Is this a real SSH session?">
+ Yes. Unlike the PostgreSQL web access terminal which is a custom SQL REPL, the SSH terminal is a real SSH shell session proxied through the Infisical Gateway. You get a full interactive shell with all the capabilities of a native SSH connection.
+ </Accordion>
+</AccordionGroup>
diff --git a/docs/images/pam/product-reference/web-access/ssh-account-connect-button.png b/docs/images/pam/product-reference/web-access/ssh-account-connect-button.png
new file mode 100644
index 0000000000..24a13ad2eb
Binary files /dev/null and b/docs/images/pam/product-reference/web-access/ssh-account-connect-button.png differ
diff --git a/docs/images/pam/product-reference/web-access/ssh-account-page-access-button.png b/docs/images/pam/product-reference/web-access/ssh-account-page-access-button.png
new file mode 100644
index 0000000000..9a370df847
Binary files /dev/null and b/docs/images/pam/product-reference/web-access/ssh-account-page-access-button.png differ
diff --git a/docs/images/pam/product-reference/web-access/ssh-connect-in-browser.png b/docs/images/pam/product-reference/web-access/ssh-connect-in-browser.png
new file mode 100644
index 0000000000..60a17d1d8c
Binary files /dev/null and b/docs/images/pam/product-reference/web-access/ssh-connect-in-browser.png differ
diff --git a/docs/images/pam/product-reference/web-access/ssh-web-access-terminal.png b/docs/images/pam/product-reference/web-access/ssh-web-access-terminal.png
new file mode 100644
index 0000000000..67bfa5e75a
Binary files /dev/null and b/docs/images/pam/product-reference/web-access/ssh-web-access-terminal.png differ
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
index 2a7d5e5892..128a2522c4 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
@@ -29,6 +29,7 @@ const PageContent = () => {
orgId: orgId!,
resourceName: account?.resource.name ?? "",
accountName: account?.name ?? "",
+ resourceType: account?.resource.resourceType ?? "",
onSessionEnd: () => setSessionEnded(true)
});
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
index d2fed7a64d..61f8cf03d4 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
+++ b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
@@ -16,6 +16,7 @@ type UseWebAccessSessionOptions = {
orgId: string;
resourceName: string;
accountName: string;
+ resourceType: string;
onSessionEnd?: () => void;
};
@@ -25,6 +26,7 @@ export const useWebAccessSession = ({
orgId,
resourceName,
accountName,
+ resourceType,
onSessionEnd
}: UseWebAccessSessionOptions) => {
const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null);
@@ -68,6 +70,8 @@ export const useWebAccessSession = ({
},
[]
);
+ // TODO: refactor when the list of supported resource type grows
+ const isSSH = resourceType === "ssh";
// --- WebSocket lifecycle (imperative) ---
@@ -92,6 +96,20 @@ export const useWebAccessSession = ({
if (msg.type === WsMessageType.Ready) {
setIsConnected(true);
+
+ // Send initial terminal dimensions so the remote PTY knows the correct size
+ if (isSSH && terminalRef.current) {
+ ws.send(
+ JSON.stringify({
+ type: WsMessageType.Resize,
+ data: JSON.stringify({
+ rows: terminalRef.current.rows,
+ cols: terminalRef.current.cols
+ })
+ })
+ );
+ }
+
setTimeout(() => terminal.focus(), 100);
}
@@ -101,12 +119,17 @@ export const useWebAccessSession = ({
}
if (msg.data) {
- if (containerEl && fitAddonRef.current) {
+ if (!isSSH && containerEl && fitAddonRef.current) {
adjustWidthForOutput(msg.data, terminal, fitAddonRef.current, containerEl);
}
- terminal.write(msg.data.replace(/\r?\n/g, "\r\n"));
+ if (isSSH) {
+ // Raw ANSI passthrough — no newline normalization
+ terminal.write(msg.data);
+ } else {
+ terminal.write(msg.data.replace(/\r?\n/g, "\r\n"));
+ }
}
- if (msg.prompt) {
+ if (msg.prompt && !isSSH) {
currentPromptRef.current = msg.prompt;
terminal.write(msg.prompt);
}
@@ -125,7 +148,7 @@ export const useWebAccessSession = ({
// no-op: onclose always fires after onerror
};
},
- [accountId, containerEl, adjustWidthForOutput]
+ [accountId, containerEl, adjustWidthForOutput, isSSH]
);
const connect = useCallback(async () => {
@@ -382,38 +405,80 @@ export const useWebAccessSession = ({
fitAddonRef.current = fitAddon;
// Wire terminal keyboard input — reads wsRef/inputBufferRef/currentPromptRef dynamically
- terminal.onData((data) => {
- if (data === "\r") {
- terminal.write("\r\n");
+ if (isSSH) {
+ // SSH: raw keystroke forwarding
+ terminal.onData((data) => {
+ // Handle internal prompts (MFA/approval) even in SSH mode
if (promptCallbackRef.current) {
- const cb = promptCallbackRef.current;
- promptCallbackRef.current = null;
- cb(inputBufferRef.current);
- inputBufferRef.current = "";
+ if (data === "\r") {
+ terminal.write("\r\n");
+ const cb = promptCallbackRef.current;
+ promptCallbackRef.current = null;
+ cb(inputBufferRef.current);
+ inputBufferRef.current = "";
+ } else if (data === "\x7f") {
+ if (inputBufferRef.current.length > 0) {
+ inputBufferRef.current = inputBufferRef.current.slice(0, -1);
+ terminal.write("\b \b");
+ }
+ } else {
+ inputBufferRef.current += data;
+ terminal.write(data);
+ }
} else if (wsRef.current?.readyState === WebSocket.OPEN) {
+ // Send raw keystroke to server — no local echo, no buffering
+ wsRef.current.send(JSON.stringify({ type: WsMessageType.Input, data }));
+ }
+ });
+
+ // Send terminal resize events to the server
+ terminal.onResize(({ rows, cols }) => {
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(
- JSON.stringify({ type: WsMessageType.Input, data: inputBufferRef.current })
+ JSON.stringify({
+ type: WsMessageType.Resize,
+ data: JSON.stringify({ rows, cols })
+ })
);
- 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 = "";
- if (wsRef.current?.readyState === WebSocket.OPEN) {
- wsRef.current.send(JSON.stringify({ type: WsMessageType.Control, data: "clear-buffer" }));
+ });
+ } 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 = "";
+ 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"));
}
- 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"));
- }
- });
+ });
+ }
// Resize handling
const handleResize = () => fitAddon.fit();
@@ -433,7 +498,7 @@ export const useWebAccessSession = ({
terminal.dispose();
setIsConnected(false);
};
- }, [containerEl, accountId, connect, disconnect]);
+ }, [containerEl, accountId, connect, disconnect, isSSH]);
const containerRef = useCallback((node: HTMLDivElement | null) => {
setContainerEl(node);
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/web-access-types.ts b/frontend/src/pages/pam/PamAccountAccessPage/web-access-types.ts
index 86deebc007..fc0b02bf84 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/web-access-types.ts
+++ b/frontend/src/pages/pam/PamAccountAccessPage/web-access-types.ts
@@ -5,6 +5,7 @@ export enum WsMessageType {
Output = "output",
Input = "input",
Control = "control",
+ Resize = "resize",
SessionEnd = "session_end"
}
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
index a7765625c6..74016378f7 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
@@ -87,7 +87,9 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectId
if (!account) return null;
- const showWebAccess = account.resource.resourceType === PamResourceType.Postgres;
+ const showWebAccess =
+ account.resource.resourceType === PamResourceType.Postgres ||
+ account.resource.resourceType === PamResourceType.SSH;
return (
<Modal isOpen={isOpen} onOpenChange={onOpenChange}>