Skip to content

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

feat(pam): in-browser web access terminal for PAM postgres accounts (#5425)

Saif Ur Rahmanececf6d70338
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 593874e224..3f29948b13 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -118,6 +118,7 @@
"pg": "^8.11.3",
"pg-boss": "^10.1.5",
"pg-query-stream": "^4.5.3",
+ "pg-types": "^2.2.0",
"picomatch": "^3.0.1",
"pino": "^8.16.2",
"pkcs11js": "^2.1.6",
@@ -29666,6 +29667,7 @@
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
+ "license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
diff --git a/backend/package.json b/backend/package.json
index 368e0e5d38..4e376212eb 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -232,6 +232,7 @@
"pg": "^8.11.3",
"pg-boss": "^10.1.5",
"pg-query-stream": "^4.5.3",
+ "pg-types": "^2.2.0",
"picomatch": "^3.0.1",
"pino": "^8.16.2",
"pkcs11js": "^2.1.6",
diff --git a/backend/src/db/migrations/20260210074536_pam-session-access-method.ts b/backend/src/db/migrations/20260210074536_pam-session-access-method.ts
new file mode 100644
index 0000000000..67f2c053bf
--- /dev/null
+++ b/backend/src/db/migrations/20260210074536_pam-session-access-method.ts
@@ -0,0 +1,25 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PamSession)) {
+ const hasCol = await knex.schema.hasColumn(TableName.PamSession, "accessMethod");
+ if (!hasCol) {
+ await knex.schema.alterTable(TableName.PamSession, (t) => {
+ t.string("accessMethod").nullable();
+ });
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PamSession)) {
+ const hasCol = await knex.schema.hasColumn(TableName.PamSession, "accessMethod");
+ if (hasCol) {
+ await knex.schema.alterTable(TableName.PamSession, (t) => {
+ t.dropColumn("accessMethod");
+ });
+ }
+ }
+}
diff --git a/backend/src/db/schemas/pam-sessions.ts b/backend/src/db/schemas/pam-sessions.ts
index 12e4adfcff..4ddea2140a 100644
--- a/backend/src/db/schemas/pam-sessions.ts
+++ b/backend/src/db/schemas/pam-sessions.ts
@@ -27,7 +27,8 @@ export const PamSessionsSchema = z.object({
startedAt: z.date().nullable().optional(),
endedAt: z.date().nullable().optional(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ accessMethod: z.string().nullable().optional()
});
export type TPamSessions = z.infer<typeof PamSessionsSchema>;
diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
index 1ade2cfc68..e921b080f8 100644
--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
+++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
@@ -1,7 +1,7 @@
import type WebSocket from "ws";
import { z } from "zod";
-import { AuditLogInfo, EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { AuditLogInfo, EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { PamAccountOrderBy, PamAccountView } from "@app/ee/services/pam-account/pam-account-enums";
import { SanitizedAwsIamAccountWithResourceSchema } from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
import { SanitizedKubernetesAccountWithResourceSchema } from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
@@ -18,7 +18,7 @@ import { ms } from "@app/lib/ms";
import { OrderByDirection } from "@app/lib/types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { TokenType } from "@app/services/auth-token/auth-token-types";
const SanitizedAccountSchema = z.discriminatedUnion("resourceType", [
@@ -247,7 +247,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
accountId: z.string().uuid()
}),
body: z.object({
- projectId: z.string().uuid()
+ projectId: z.string().uuid(),
+ mfaSessionId: z.string().optional()
}),
response: {
200: z.object({ ticket: z.string() })
@@ -255,12 +256,20 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
+ // Narrows TypeScript type so req.auth.user is available below (verifyAuth hook already enforces JWT)
+ if (req.auth.authMode !== AuthMode.JWT) {
+ throw new BadRequestError({ message: "Web access requires JWT authentication" });
+ }
+
const { ticket } = await server.services.pamWebAccess.issueWebSocketTicket({
accountId: req.params.accountId,
projectId: req.body.projectId,
orgId: req.permission.orgId,
actor: req.permission,
- auditLogInfo: req.auditLogInfo
+ actorEmail: req.auth.user.email ?? "",
+ actorName: `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim(),
+ auditLogInfo: req.auditLogInfo,
+ mfaSessionId: req.body.mfaSessionId
});
return { ticket };
@@ -316,12 +325,14 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
orgId: z.string(),
resourceName: z.string(),
accountName: z.string(),
+ actorEmail: z.string(),
+ actorName: z.string(),
auditLogInfo: z.object({
ipAddress: z.string().optional(),
userAgent: z.string().optional(),
- userAgentType: z.string().optional(),
+ userAgentType: z.nativeEnum(UserAgentType).optional(),
actor: z.object({
- type: z.string(),
+ type: z.nativeEnum(ActorType),
metadata: z.record(z.unknown())
})
})
@@ -340,7 +351,12 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
orgId: payload.orgId,
resourceName: payload.resourceName,
accountName: payload.accountName,
- auditLogInfo: payload.auditLogInfo as AuditLogInfo
+ actorEmail: payload.actorEmail,
+ actorName: payload.actorName,
+ auditLogInfo: payload.auditLogInfo as AuditLogInfo,
+ userId,
+ actorIp: req.realIp ?? "",
+ actorUserAgent: req.headers["user-agent"] ?? ""
});
} catch (err) {
logger.error(err, "WebSocket ticket validation failed");
diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.ts
index 094614859c..48928bf6e7 100644
--- a/backend/src/ee/services/pam-session/pam-session-dal.ts
+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts
@@ -24,6 +24,18 @@ export const pamSessionDALFactory = (db: TDbClient) => {
return session;
};
+ const countActiveWebSessions = async (userId: string, projectId: string, tx?: Knex): Promise<number> => {
+ const result = await (tx || db.replicaNode())(TableName.PamSession)
+ .where("userId", userId)
+ .where("projectId", projectId)
+ .where("accessMethod", "web")
+ .whereIn("status", [PamSessionStatus.Starting, PamSessionStatus.Active])
+ .count("id as count")
+ .first();
+
+ return Number((result as { count?: string | number })?.count ?? 0);
+ };
+
const expireSessionById = async (sessionId: string, tx?: Knex) => {
const now = new Date();
@@ -38,5 +50,5 @@ export const pamSessionDALFactory = (db: TDbClient) => {
return updatedCount;
};
- return { ...orm, findById, expireSessionById };
+ return { ...orm, findById, expireSessionById, countActiveWebSessions };
};
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-repl.test.ts b/backend/src/ee/services/pam-web-access/pam-web-access-repl.test.ts
new file mode 100644
index 0000000000..a8e6a15694
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-repl.test.ts
@@ -0,0 +1,238 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createPamSqlRepl, TQueryExecutor } from "./pam-web-access-repl";
+
+describe("createPamSqlRepl", () => {
+ let queryFn: ReturnType<typeof vi.fn>;
+ let mockExecutor: TQueryExecutor;
+ let repl: ReturnType<typeof createPamSqlRepl>;
+
+ beforeEach(() => {
+ queryFn = vi.fn().mockResolvedValue({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "?column?", dataTypeID: 23 }],
+ rows: [{ "?column?": 1 }]
+ });
+ mockExecutor = { query: queryFn };
+ repl = createPamSqlRepl(mockExecutor);
+ });
+
+ // Statement execution
+ it("executes complete statement", async () => {
+ const result = await repl.processInput("SELECT 1;");
+ expect(queryFn).toHaveBeenCalledWith("SELECT 1");
+ expect(result.output).toContain("1");
+ expect(result.prompt).toBe("=> ");
+ expect(result.shouldClose).toBe(false);
+ });
+
+ it("buffers incomplete input", async () => {
+ const result = await repl.processInput("SELECT *");
+ expect(queryFn).not.toHaveBeenCalled();
+ expect(result.output).toBe("");
+ expect(result.prompt).toBe("-> ");
+ expect(result.shouldClose).toBe(false);
+ });
+
+ it("executes after completing buffered statement", async () => {
+ await repl.processInput("SELECT *");
+ expect(queryFn).not.toHaveBeenCalled();
+
+ const result = await repl.processInput("FROM users;");
+ expect(queryFn).toHaveBeenCalledWith("SELECT *\nFROM users");
+ expect(result.prompt).toBe("=> ");
+ });
+
+ it("executes multiple statements sequentially", async () => {
+ queryFn
+ .mockResolvedValueOnce({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "?column?", dataTypeID: 23 }],
+ rows: [{ "?column?": 1 }]
+ })
+ .mockResolvedValueOnce({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "?column?", dataTypeID: 23 }],
+ rows: [{ "?column?": 2 }]
+ });
+
+ const result = await repl.processInput("SELECT 1; SELECT 2;");
+ expect(queryFn).toHaveBeenCalledTimes(2);
+ expect(queryFn).toHaveBeenCalledWith("SELECT 1");
+ expect(queryFn).toHaveBeenCalledWith("SELECT 2");
+ expect(result.prompt).toBe("=> ");
+ });
+
+ // Quit
+ it("returns shouldClose for \\q", async () => {
+ const result = await repl.processInput("\\q");
+ expect(result.shouldClose).toBe(true);
+ expect(result.output).toBe("Goodbye!\n");
+ expect(queryFn).not.toHaveBeenCalled();
+ });
+
+ it("returns shouldClose for quit", async () => {
+ const result = await repl.processInput("quit");
+ expect(result.shouldClose).toBe(true);
+ });
+
+ it("returns shouldClose for exit", async () => {
+ const result = await repl.processInput("exit");
+ expect(result.shouldClose).toBe(true);
+ });
+
+ it("treats quit as SQL when buffer non-empty", async () => {
+ await repl.processInput("SELECT");
+ const result = await repl.processInput("quit;");
+ expect(result.shouldClose).toBe(false);
+ expect(queryFn).toHaveBeenCalledWith("SELECT\nquit");
+ });
+
+ // Buffer management
+ it("clearBuffer resets to empty", async () => {
+ await repl.processInput("SELECT *");
+ expect(repl.getPrompt()).toBe("-> ");
+
+ repl.clearBuffer();
+ expect(repl.getPrompt()).toBe("=> ");
+ });
+
+ it("getPrompt returns => when buffer empty", () => {
+ expect(repl.getPrompt()).toBe("=> ");
+ });
+
+ it("getPrompt returns -> when buffer has content", async () => {
+ await repl.processInput("SELECT *");
+ expect(repl.getPrompt()).toBe("-> ");
+ });
+
+ // Error handling
+ it("catches query error and returns formatted error", async () => {
+ queryFn.mockRejectedValueOnce({
+ message: 'relation "nonexistent" does not exist'
+ });
+
+ const result = await repl.processInput("SELECT * FROM nonexistent;");
+ expect(result.output).toContain("ERROR:");
+ expect(result.output).toContain("nonexistent");
+ expect(result.shouldClose).toBe(false);
+ expect(result.prompt).toBe("=> ");
+ });
+
+ it("continues working after error", async () => {
+ queryFn.mockRejectedValueOnce({ message: "error" }).mockResolvedValueOnce({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "?column?", dataTypeID: 23 }],
+ rows: [{ "?column?": 1 }]
+ });
+
+ await repl.processInput("BAD SQL;");
+ const result = await repl.processInput("SELECT 1;");
+ expect(result.output).toContain("1");
+ expect(result.prompt).toBe("=> ");
+ });
+
+ // Empty input
+ it("re-prompts on empty input with empty buffer", async () => {
+ const result = await repl.processInput("");
+ expect(queryFn).not.toHaveBeenCalled();
+ expect(result.prompt).toBe("=> ");
+ });
+
+ it("skips empty statements (bare ;)", async () => {
+ const result = await repl.processInput(";");
+ expect(queryFn).not.toHaveBeenCalled();
+ expect(result.prompt).toBe("=> ");
+ });
+
+ it("handles mixed complete + incomplete on one input", async () => {
+ queryFn.mockResolvedValueOnce({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "?column?", dataTypeID: 23 }],
+ rows: [{ "?column?": 1 }]
+ });
+
+ const result = await repl.processInput("SELECT 1; SELECT");
+ expect(queryFn).toHaveBeenCalledTimes(1);
+ expect(queryFn).toHaveBeenCalledWith("SELECT 1");
+ expect(result.prompt).toBe("-> ");
+
+ // Complete the second statement
+ queryFn.mockResolvedValueOnce({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "?column?", dataTypeID: 23 }],
+ rows: [{ "?column?": 2 }]
+ });
+
+ const result2 = await repl.processInput("2;");
+ expect(queryFn).toHaveBeenCalledTimes(2);
+ expect(result2.prompt).toBe("=> ");
+ });
+
+ it("DML result formatting", async () => {
+ queryFn.mockResolvedValueOnce({
+ command: "INSERT",
+ rowCount: 1,
+ fields: [],
+ rows: []
+ });
+
+ const result = await repl.processInput("INSERT INTO t VALUES(1);");
+ expect(result.output).toBe("INSERT 0 1\n");
+ });
+
+ it("returns error and clears buffer when input exceeds 1 MB limit", async () => {
+ const oversized = "A".repeat(1024 * 1024 + 1);
+ const result = await repl.processInput(oversized);
+ expect(result.output).toContain("buffer size exceeded");
+ expect(result.prompt).toBe("=> ");
+ expect(result.shouldClose).toBe(false);
+ expect(queryFn).not.toHaveBeenCalled();
+
+ // REPL should still work after buffer was cleared
+ queryFn.mockResolvedValueOnce({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "?column?", dataTypeID: 23 }],
+ rows: [{ "?column?": 1 }]
+ });
+ const next = await repl.processInput("SELECT 1;");
+ expect(next.output).toContain("1");
+ expect(next.prompt).toBe("=> ");
+ });
+
+ it("multi-statement paste", async () => {
+ queryFn
+ .mockResolvedValueOnce({
+ command: "CREATE TABLE",
+ rowCount: null,
+ fields: [],
+ rows: []
+ })
+ .mockResolvedValueOnce({
+ command: "INSERT",
+ rowCount: 1,
+ fields: [],
+ rows: []
+ })
+ .mockResolvedValueOnce({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "id", dataTypeID: 23 }],
+ rows: [{ id: 1 }]
+ });
+
+ const result = await repl.processInput("CREATE TABLE t(id int); INSERT INTO t VALUES(1); SELECT * FROM t;");
+ expect(queryFn).toHaveBeenCalledTimes(3);
+ expect(result.output).toContain("CREATE TABLE");
+ expect(result.output).toContain("INSERT 0 1");
+ expect(result.output).toContain("(1 row)");
+ expect(result.prompt).toBe("=> ");
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-repl.ts b/backend/src/ee/services/pam-web-access/pam-web-access-repl.ts
new file mode 100644
index 0000000000..47c5bfb965
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-repl.ts
@@ -0,0 +1,93 @@
+import { formatCommandResult, formatError, formatTable } from "./pam-web-access-sql-formatter";
+import { splitStatements } from "./pam-web-access-sql-lexer";
+
+/**
+ * The REPL only depends on this interface, not on pg.Client directly.
+ * pg.Client satisfies this interface out of the box.
+ */
+export type TQueryExecutor = {
+ query(sql: string): Promise<{
+ command: string;
+ rowCount: number | null;
+ fields: Array<{ name: string; dataTypeID: number }>;
+ rows: Record<string, unknown>[];
+ }>;
+};
+
+export type TPamSqlRepl = ReturnType<typeof createPamSqlRepl>;
+
+const MAX_BUFFER_SIZE = 1024 * 1024; // 1 MB
+
+export const createPamSqlRepl = (queryExecutor: TQueryExecutor) => {
+ let buffer = "";
+
+ const executeStatement = async (sql: string): Promise<string> => {
+ try {
+ const result = await queryExecutor.query(sql);
+
+ if (result.fields?.length > 0) {
+ return formatTable(result);
+ }
+ return formatCommandResult(result);
+ } catch (err) {
+ return formatError(err);
+ }
+ };
+
+ const processInput = async (
+ rawInput: string
+ ): Promise<{
+ output: string;
+ prompt: string;
+ shouldClose: boolean;
+ }> => {
+ // Check for quit commands when buffer is empty
+ if (buffer.trim().length === 0) {
+ const trimmed = rawInput.trim();
+ if (trimmed === "\\q" || trimmed === "quit" || trimmed === "exit") {
+ return { output: "Goodbye!\n", prompt: "", shouldClose: true };
+ }
+ }
+
+ // Append input to buffer
+ if (buffer.length > 0) {
+ buffer += `\n${rawInput}`;
+ } else {
+ buffer = rawInput;
+ }
+
+ if (buffer.length > MAX_BUFFER_SIZE) {
+ buffer = "";
+ return {
+ output: "ERROR: buffer size exceeded (1 MB limit). Buffer cleared.\n",
+ prompt: "=> ",
+ shouldClose: false
+ };
+ }
+
+ // Split into complete and incomplete statements
+ const { complete, remainder } = splitStatements(buffer);
+ buffer = remainder;
+
+ // Execute each complete statement
+ let output = "";
+ for (const stmt of complete) {
+ const trimmed = stmt.trim();
+ if (trimmed.length > 0) {
+ // eslint-disable-next-line no-await-in-loop
+ output += await executeStatement(trimmed);
+ }
+ }
+
+ const prompt = buffer.trim().length > 0 ? "-> " : "=> ";
+ return { output, prompt, shouldClose: false };
+ };
+
+ const clearBuffer = () => {
+ buffer = "";
+ };
+
+ const getPrompt = () => (buffer.trim().length > 0 ? "-> " : "=> ");
+
+ return { processInput, clearBuffer, getPrompt };
+};
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 33678e346d..65d445bd0a 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,27 +1,57 @@
+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";
import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionPamAccountActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError, PolicyViolationError } from "@app/lib/errors";
+import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { createGatewayConnection, createRelayConnection, setupRelayServer } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
+import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";
+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+import { APPROVAL_POLICY_FACTORY_MAP } from "@app/services/approval-policy/approval-policy-factory";
+import { TApprovalRequestGrantsDALFactory } from "@app/services/approval-policy/approval-request-dal";
+import { ActorType, MfaMethod } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { TokenType } from "@app/services/auth-token/auth-token-types";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
+import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TPamSessionExpirationServiceFactory } from "@app/services/pam-session-expiration/pam-session-expiration-queue";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { TUserDALFactory } from "@app/services/user/user-dal";
import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
+import { decryptAccountCredentials } from "../pam-account/pam-account-fns";
import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";
+import { decryptResourceConnectionDetails } from "../pam-resource/pam-resource-fns";
+import {
+ TPostgresAccountCredentials,
+ TPostgresResourceConnectionDetails
+} from "../pam-resource/postgres/postgres-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 {
- PAM_WEB_ACCESS_PROMPT,
+ DEFAULT_WEB_SESSION_DURATION_MS,
+ MAX_WEB_SESSIONS_PER_USER,
+ SessionEndReason,
TIssueWebSocketTicketDTO,
- TWebSocketClientMessage,
TWebSocketServerMessage,
WebSocketClientMessageSchema,
+ WS_IDLE_TIMEOUT_MS,
+ WS_PING_INTERVAL_MS,
WsMessageType
} from "./pam-web-access-types";
@@ -31,6 +61,19 @@ type TPamWebAccessServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
+ pamSessionDAL: Pick<TPamSessionDALFactory, "create" | "updateById" | "countActiveWebSessions">;
+ pamSessionExpirationService: Pick<TPamSessionExpirationServiceFactory, "scheduleSessionExpiration">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ userDAL: Pick<TUserDALFactory, "findById">;
+ mfaSessionService: Pick<
+ TMfaSessionServiceFactory,
+ "createMfaSession" | "getMfaSession" | "deleteMfaSession" | "sendMfaCode"
+ >;
+ approvalPolicyDAL: TApprovalPolicyDALFactory;
+ approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;
+ orgDAL: Pick<TOrgDALFactory, "findOrgById">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
};
export type TPamWebAccessServiceFactory = ReturnType<typeof pamWebAccessServiceFactory>;
@@ -43,14 +86,28 @@ type THandleWebSocketConnectionDTO = {
resourceName: string;
accountName: string;
auditLogInfo: AuditLogInfo;
+ userId: string;
+ actorEmail: string;
+ actorName: string;
+ actorIp: string;
+ actorUserAgent: string;
};
-
export const pamWebAccessServiceFactory = ({
pamAccountDAL,
pamResourceDAL,
permissionService,
auditLogService,
- tokenService
+ tokenService,
+ pamSessionDAL,
+ pamSessionExpirationService,
+ gatewayV2Service,
+ kmsService,
+ userDAL,
+ mfaSessionService,
+ approvalPolicyDAL,
+ approvalRequestGrantsDAL,
+ orgDAL,
+ projectDAL
}: TPamWebAccessServiceFactoryDep) => {
const sendMessage = (socket: WebSocket, message: TWebSocketServerMessage): void => {
try {
@@ -62,12 +119,19 @@ export const pamWebAccessServiceFactory = ({
}
};
+ const sendSessionEnd = (socket: WebSocket, reason: SessionEndReason): void => {
+ sendMessage(socket, { type: WsMessageType.SessionEnd, reason });
+ };
+
const issueWebSocketTicket = async ({
accountId,
projectId,
orgId,
actor,
- auditLogInfo
+ actorEmail,
+ actorName,
+ auditLogInfo,
+ mfaSessionId
}: TIssueWebSocketTicketDTO) => {
const account = await pamAccountDAL.findById(accountId);
@@ -91,23 +155,102 @@ export const pamWebAccessServiceFactory = ({
});
}
- const { permission } = await permissionService.getProjectPermission({
- actor: actor.type,
- actorId: actor.id,
- actorAuthMethod: actor.authMethod,
- actorOrgId: actor.orgId,
- projectId: account.projectId,
- actionProjectType: ActionProjectType.PAM
- });
+ // Approval policy check
+ const approvalPolicy = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.PamAccess](ApprovalPolicyType.PamAccess);
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionPamAccountActions.Access,
- subject(ProjectPermissionSub.PamAccounts, {
- resourceName: resource.name,
- accountName: account.name
- })
+ const policyInputs = {
+ resourceId: resource.id,
+ resourceName: resource.name,
+ accountName: account.name
+ };
+
+ const hasApprovalGrant = await approvalPolicy.canAccess(
+ approvalRequestGrantsDAL,
+ resource.projectId,
+ actor.id,
+ policyInputs
);
+ if (!hasApprovalGrant) {
+ const matchedPolicy = await approvalPolicy.matchPolicy(approvalPolicyDAL, resource.projectId, policyInputs);
+
+ if (matchedPolicy) {
+ throw new PolicyViolationError({
+ message: "A policy is in place for this resource",
+ details: {
+ policyId: matchedPolicy.id,
+ policyName: matchedPolicy.name,
+ policyType: matchedPolicy.type
+ }
+ });
+ }
+
+ // If there isn't a policy in place, continue with checking permission
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ projectId: account.projectId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamAccountActions.Access,
+ subject(ProjectPermissionSub.PamAccounts, {
+ resourceName: resource.name,
+ accountName: account.name
+ })
+ );
+ }
+
+ // MFA check
+ if (account.requireMfa && !mfaSessionId) {
+ const project = await projectDAL.findById(account.projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${account.projectId}' not found` });
+
+ const actorUser = await userDAL.findById(actor.id);
+ if (!actorUser) throw new NotFoundError({ message: `User with ID '${actor.id}' not found` });
+
+ const org = await orgDAL.findOrgById(project.orgId);
+ if (!org) throw new NotFoundError({ message: `Organization with ID '${project.orgId}' not found` });
+
+ // Determine which MFA method to use
+ // Priority: org-enforced > user-selected > email as fallback
+ const orgMfaMethod = org.enforceMfa ? (org.selectedMfaMethod as MfaMethod | null) : undefined;
+ const userMfaMethod = actorUser.isMfaEnabled ? (actorUser.selectedMfaMethod as MfaMethod | null) : undefined;
+ const mfaMethod = (orgMfaMethod ?? userMfaMethod ?? MfaMethod.EMAIL) as MfaMethod;
+
+ const newMfaSessionId = await mfaSessionService.createMfaSession(actorUser.id, account.id, mfaMethod);
+
+ if (mfaMethod === MfaMethod.EMAIL && actorUser.email) {
+ await mfaSessionService.sendMfaCode(actorUser.id, actorUser.email);
+ }
+
+ throw new BadRequestError({
+ message: "MFA verification required to access PAM account",
+ name: "SESSION_MFA_REQUIRED",
+ details: {
+ mfaSessionId: newMfaSessionId,
+ mfaMethod
+ }
+ });
+ }
+
+ if (account.requireMfa && mfaSessionId) {
+ const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
+ if (
+ !mfaSession ||
+ mfaSession.userId !== actor.id ||
+ mfaSession.resourceId !== account.id ||
+ mfaSession.status !== MfaSessionStatus.ACTIVE
+ ) {
+ throw new BadRequestError({ message: "Invalid or expired MFA session" });
+ }
+
+ await mfaSessionService.deleteMfaSession(mfaSessionId);
+ }
+
const token = await tokenService.createTokenForUser({
type: TokenType.TOKEN_PAM_WS_TICKET,
userId: actor.id,
@@ -117,6 +260,8 @@ export const pamWebAccessServiceFactory = ({
orgId,
resourceName: resource.name,
accountName: account.name,
+ actorEmail,
+ actorName,
auditLogInfo
})
});
@@ -145,22 +290,235 @@ export const pamWebAccessServiceFactory = ({
orgId,
resourceName,
accountName,
- auditLogInfo
+ auditLogInfo,
+ userId,
+ actorEmail,
+ actorName,
+ actorIp,
+ actorUserAgent
}: THandleWebSocketConnectionDTO): Promise<void> => {
+ let session: { id: string } | null = null;
+ let cleanedUp = false;
+ let pgClient: pg.Client | null = null;
+ let relayServer: { port: number; cleanup: () => Promise<void> } | null = null;
+ let relayCerts: {
+ relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
+ gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
+ relayHost: string;
+ } | null = null;
+ let expiryTimer: ReturnType<typeof setTimeout> | null = null;
+ let pingInterval: ReturnType<typeof setInterval> | null = null;
+ let idleTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const cleanup = async () => {
+ // Each operation is individually idempotent — null checks skip already-cleaned resources,
+ // and finally blocks ensure references are cleared even if an operation throws.
+ if (expiryTimer) {
+ clearTimeout(expiryTimer);
+ expiryTimer = null;
+ }
+ if (pingInterval) {
+ clearInterval(pingInterval);
+ pingInterval = null;
+ }
+ if (idleTimer) {
+ clearTimeout(idleTimer);
+ idleTimer = null;
+ }
+
+ // End pg client (needs tunnel to send Terminate message)
+ if (pgClient) {
+ try {
+ await pgClient.end();
+ } catch (err) {
+ logger.debug(err, "Error closing pg client");
+ } finally {
+ pgClient = null;
+ }
+ }
+
+ // Close relay tunnel
+ if (relayServer) {
+ try {
+ await relayServer.cleanup();
+ } catch (err) {
+ logger.debug(err, "Error closing relay server");
+ } finally {
+ relayServer = null;
+ }
+ }
+
+ // Best-effort ALPN session cancellation (fire-and-forget).
+ // Triggers gateway-side cleanup: log upload, and session end via API.
+ // If this fails, the scheduled queue job will expire the session at expiresAt time.
+ if (relayCerts) {
+ const certs = relayCerts;
+ relayCerts = null;
+ void (async () => {
+ let relayConn: net.Socket | null = null;
+ try {
+ relayConn = await createRelayConnection({
+ relayHost: certs.relayHost,
+ clientCertificate: certs.relay.clientCertificate,
+ clientPrivateKey: certs.relay.clientPrivateKey,
+ serverCertificateChain: certs.relay.serverCertificateChain
+ });
+ const cancelConn = await createGatewayConnection(
+ relayConn,
+ certs.gateway,
+ GatewayProxyProtocol.PamSessionCancellation
+ );
+ cancelConn.end();
+ } catch (err) {
+ logger.debug(err, "Session cancellation signal failed (best-effort)");
+ } finally {
+ relayConn?.destroy();
+ }
+ })();
+ }
+
+ cleanedUp = true;
+ };
+
try {
+ // 1. VALIDATE
const account = await pamAccountDAL.findById(accountId);
-
if (!account || account.projectId !== projectId) {
throw new BadRequestError({ message: "Invalid account or project" });
}
+ const resource = await pamResourceDAL.findById(account.resourceId);
+ if (!resource) {
+ throw new BadRequestError({ message: "Resource not found" });
+ }
+
+ if (resource.resourceType !== PamResource.Postgres) {
+ throw new BadRequestError({ message: "Web access is only supported for PostgreSQL" });
+ }
+
+ if (!resource.gatewayId) {
+ throw new BadRequestError({ message: "Gateway not configured for this resource" });
+ }
+
+ // Check web session limit
+ const activeCount = await pamSessionDAL.countActiveWebSessions(userId, projectId);
+ 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: ""
+ });
+ socket.close();
+ return;
+ }
+
+ // 2. DECRYPT
+ const resourceConnectionDetails = (await decryptResourceConnectionDetails({
+ projectId,
+ encryptedConnectionDetails: resource.encryptedConnectionDetails,
+ kmsService
+ })) as TPostgresResourceConnectionDetails;
+
+ const accountCredentials = (await decryptAccountCredentials({
+ projectId,
+ encryptedCredentials: account.encryptedCredentials,
+ kmsService
+ })) as TPostgresAccountCredentials;
+
+ // 3. CREATE SESSION
+ const user = await userDAL.findById(userId);
+ const expiresAt = new Date(Date.now() + DEFAULT_WEB_SESSION_DURATION_MS);
+
+ session = await pamSessionDAL.create({
+ status: PamSessionStatus.Starting,
+ accessMethod: "web",
+ expiresAt,
+ accountName,
+ actorEmail,
+ actorIp,
+ actorName,
+ actorUserAgent,
+ projectId,
+ resourceName: resource.name,
+ resourceType: resource.resourceType,
+ accountId: account.id,
+ userId
+ });
+
+ await pamSessionExpirationService.scheduleSessionExpiration(session.id, expiresAt);
+
+ // 4. GET CERTIFICATES
+ const certs = await gatewayV2Service.getPAMConnectionDetails({
+ gatewayId: resource.gatewayId,
+ sessionId: session.id,
+ resourceType: PamResource.Postgres,
+ host: resourceConnectionDetails.host,
+ port: resourceConnectionDetails.port,
+ duration: DEFAULT_WEB_SESSION_DURATION_MS,
+ actorMetadata: {
+ id: userId,
+ type: ActorType.USER,
+ name: user?.email ?? ""
+ }
+ });
+
+ if (!certs) {
+ throw new BadRequestError({ message: "Failed to obtain gateway connection details" });
+ }
+
+ relayCerts = {
+ relayHost: certs.relayHost,
+ relay: certs.relay,
+ gateway: certs.gateway
+ };
+
+ // 5. START TUNNEL
+ relayServer = await setupRelayServer({
+ protocol: GatewayProxyProtocol.Pam,
+ relayHost: certs.relayHost,
+ relay: certs.relay,
+ gateway: certs.gateway,
+ 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"))
+ }
+ });
+
+ await pgClient.connect();
+
+ // 7. ACTIVATE SESSION
+ await pamSessionDAL.updateById(session.id, {
+ status: PamSessionStatus.Active,
+ startedAt: new Date()
+ });
+
+ // 8. INIT REPL + SEND READY
+ const repl = createPamSqlRepl(pgClient);
+
sendMessage(socket, {
type: WsMessageType.Ready,
- data: "Connected (echo mode)...\n",
- prompt: PAM_WEB_ACCESS_PROMPT
+ data: `Connected to ${resource.name} (${resourceConnectionDetails.database}) as ${accountCredentials.username}\n\n`,
+ prompt: "=> "
});
- logger.info({ accountId }, "Web access session established (echo mode)");
+ logger.info({ accountId, sessionId: session.id }, "Web access session established");
await auditLogService.createAuditLog({
...auditLogInfo,
@@ -172,14 +530,54 @@ export const pamWebAccessServiceFactory = ({
accountId,
resourceName,
accountName,
- duration: new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ duration: expiresAt.toISOString()
}
}
});
+ // 9. SET UP HANDLERS
+
+ const resetIdleTimer = () => {
+ if (idleTimer) clearTimeout(idleTimer);
+ idleTimer = setTimeout(() => {
+ if (!cleanedUp) {
+ sendSessionEnd(socket, SessionEndReason.IdleTimeout);
+ void cleanup();
+ socket.close();
+ }
+ }, WS_IDLE_TIMEOUT_MS);
+ };
+
+ resetIdleTimer();
+
+ // WebSocket keep-alive to survive ALB idle timeout (default 60s)
+ let isAlive = true;
+
+ socket.on("pong", () => {
+ isAlive = true;
+ });
+
+ pingInterval = setInterval(() => {
+ if (!isAlive) {
+ // Client didn't respond to last ping — connection is dead
+ socket.terminate();
+ return;
+ }
+ isAlive = false;
+ if (socket.readyState === socket.OPEN) {
+ socket.ping();
+ }
+ }, WS_PING_INTERVAL_MS);
+
+ // Sequential message processing to prevent concurrent query issues
+ let processingPromise = Promise.resolve();
+
socket.on("message", (rawData: Buffer | ArrayBuffer | Buffer[]) => {
- const handleMessage = async () => {
- try {
+ resetIdleTimer();
+ processingPromise = processingPromise
+ .then(async () => {
+ if (cleanedUp) return;
+
let data: string;
if (Buffer.isBuffer(rawData)) {
data = rawData.toString();
@@ -188,101 +586,130 @@ export const pamWebAccessServiceFactory = ({
} else {
data = Buffer.from(rawData).toString();
}
- const parsed: unknown = JSON.parse(data);
+ 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: PAM_WEB_ACCESS_PROMPT
+ prompt: repl.getPrompt()
});
return;
}
- const message: TWebSocketClientMessage = result.data;
+ const message = result.data;
- // Programmatic disconnect sent by the frontend's disconnect button
+ // Control messages
if (message.type === WsMessageType.Control) {
if (message.data === "quit") {
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: "Session ended\n",
- prompt: ""
- });
+ 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-typed input
+ // User input
if (message.type === WsMessageType.Input) {
- const input = message.data.trim();
-
- // Empty input — just re-prompt
- if (input.length === 0) {
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: "",
- prompt: PAM_WEB_ACCESS_PROMPT
- });
- return;
- }
+ const replResult = await repl.processInput(message.data);
- if (input === "\\q" || input === "quit" || input === "exit") {
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: "Goodbye!\n",
- prompt: ""
- });
+ if (replResult.shouldClose) {
+ sendSessionEnd(socket, SessionEndReason.UserQuit);
+ void cleanup();
socket.close();
return;
}
- // Echo mode: split on newlines, combine output, single prompt at end
- const echoLines = input
- .split("\n")
- .map((l) => l.trim())
- .filter((l) => l.length > 0)
- .map((l) => `[echo] ${l}\n`)
- .join("");
-
sendMessage(socket, {
type: WsMessageType.Output,
- data: echoLines,
- prompt: PAM_WEB_ACCESS_PROMPT
+ data: replResult.output,
+ prompt: replResult.prompt
});
}
- } catch (err) {
- logger.error(err, "Error processing WebSocket message");
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: "Failed to process message\n",
- prompt: PAM_WEB_ACCESS_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();
+ }
+ });
- void handleMessage();
+ pgClient.on("end", () => {
+ if (!cleanedUp) {
+ if (isNearSessionExpiry()) {
+ sendSessionEnd(socket, SessionEndReason.SessionCompleted);
+ } else {
+ sendSessionEnd(socket, SessionEndReason.ConnectionLost);
+ }
+ void cleanup();
+ socket.close();
+ }
});
+ // Session expiry timer
+ expiryTimer = setTimeout(() => {
+ if (!cleanedUp) {
+ sendSessionEnd(socket, SessionEndReason.SessionCompleted);
+ void cleanup();
+ socket.close();
+ }
+ }, DEFAULT_WEB_SESSION_DURATION_MS);
+
+ // WebSocket close/error
socket.on("close", () => {
- logger.info({ accountId }, "WebSocket connection closed");
+ logger.info({ accountId, sessionId: session?.id }, "WebSocket connection closed");
+ void cleanup();
});
socket.on("error", (err: Error) => {
logger.error(err, "WebSocket error");
+ void cleanup();
});
} catch (err) {
logger.error(err, "Failed to establish web access session");
-
- // TODO: always provide generic message to users when database/gateway errors occur
- const errorMessage = err instanceof Error ? err.message : "Failed to establish web access session";
- sendMessage(socket, {
- type: WsMessageType.Output,
- data: `${errorMessage}\n`,
- prompt: ""
- });
+ sendSessionEnd(socket, SessionEndReason.SetupFailed);
+ await cleanup();
socket.close();
}
};
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.test.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.test.ts
new file mode 100644
index 0000000000..09e3d72d12
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.test.ts
@@ -0,0 +1,247 @@
+import { builtins } from "pg-types";
+import { describe, expect, it } from "vitest";
+
+import { formatCommandResult, formatError, formatTable } from "./pam-web-access-sql-formatter";
+
+describe("formatTable", () => {
+ it("formats a simple two-column result", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 2,
+ fields: [
+ { name: "id", dataTypeID: builtins.INT4 },
+ { name: "name", dataTypeID: builtins.TEXT }
+ ],
+ rows: [
+ { id: 1, name: "Alice" },
+ { id: 2, name: "Bob" }
+ ]
+ });
+
+ expect(result).toContain("id");
+ expect(result).toContain("name");
+ expect(result).toContain("Alice");
+ expect(result).toContain("Bob");
+ expect(result).toContain("(2 rows)");
+ expect(result).toContain("+");
+ expect(result).toContain("-");
+ });
+
+ it("right-aligns numeric columns", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 2,
+ fields: [{ name: "num", dataTypeID: builtins.INT4 }],
+ rows: [{ num: 1 }, { num: 100 }]
+ });
+
+ const lines = result.split("\n");
+ // Data rows should have right-aligned numbers
+ const dataLine1 = lines[2]; // first data row
+ const dataLine2 = lines[3]; // second data row
+ // "1" should be padded to width of "100"
+ expect(dataLine1).toContain(" 1");
+ expect(dataLine2).toContain("100");
+ });
+
+ it("handles NULL values as empty strings", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [
+ { name: "id", dataTypeID: builtins.INT4 },
+ { name: "name", dataTypeID: builtins.TEXT }
+ ],
+ rows: [{ id: 1, name: null }]
+ });
+
+ expect(result).toContain("(1 row)");
+ });
+
+ it("zero rows with fields", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 0,
+ fields: [
+ { name: "id", dataTypeID: builtins.INT4 },
+ { name: "name", dataTypeID: builtins.TEXT }
+ ],
+ rows: []
+ });
+
+ expect(result).toContain("id");
+ expect(result).toContain("name");
+ expect(result).toContain("(0 rows)");
+ });
+
+ it("single row uses singular footer", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "val", dataTypeID: builtins.INT4 }],
+ rows: [{ val: 42 }]
+ });
+
+ expect(result).toContain("(1 row)");
+ expect(result).not.toContain("(1 rows)");
+ });
+
+ it("column width matches longest value", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "x", dataTypeID: builtins.TEXT }],
+ rows: [{ x: "longvalue" }]
+ });
+
+ // The separator should be at least as wide as "longvalue"
+ const lines = result.split("\n");
+ const separator = lines[1];
+ // "longvalue" is 9 chars, column should be at least 9 + 2 (padding) = 11
+ expect(separator.length).toBeGreaterThanOrEqual(11);
+ });
+
+ it("formats Date values as ISO-like timestamps", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "created_at", dataTypeID: builtins.TIMESTAMPTZ }],
+ rows: [{ created_at: new Date("2026-02-05T19:04:52.000Z") }]
+ });
+
+ expect(result).toContain("2026-02-05 19:04:52");
+ expect(result).not.toContain("GMT");
+ expect(result).not.toContain("Coordinated Universal Time");
+ });
+
+ it("formats raw string timestamps as-is", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "ts", dataTypeID: builtins.TIMESTAMPTZ }],
+ rows: [{ ts: "2026-02-05 19:04:52+00" }]
+ });
+
+ expect(result).toContain("2026-02-05 19:04:52+00");
+ });
+
+ it("formats Buffer values as hex", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "data", dataTypeID: builtins.BYTEA }],
+ rows: [{ data: Buffer.from([0xde, 0xad, 0xbe, 0xef]) }]
+ });
+
+ expect(result).toContain("\\xdeadbeef");
+ });
+
+ it("formats Array values with braces", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 1,
+ fields: [{ name: "tags", dataTypeID: 1009 }],
+ rows: [{ tags: ["a", "b", "c"] }]
+ });
+
+ expect(result).toContain("{a,b,c}");
+ });
+
+ it("returns empty string for no fields", () => {
+ const result = formatTable({
+ command: "SELECT",
+ rowCount: 0,
+ fields: [],
+ rows: []
+ });
+
+ expect(result).toBe("");
+ });
+});
+
+describe("formatCommandResult", () => {
+ it("INSERT with row count", () => {
+ const result = formatCommandResult({
+ command: "INSERT",
+ rowCount: 3,
+ fields: [],
+ rows: []
+ });
+ expect(result).toBe("INSERT 0 3\n");
+ });
+
+ it("CREATE TABLE", () => {
+ const result = formatCommandResult({
+ command: "CREATE TABLE",
+ rowCount: null,
+ fields: [],
+ rows: []
+ });
+ expect(result).toBe("CREATE TABLE\n");
+ });
+
+ it("BEGIN", () => {
+ const result = formatCommandResult({
+ command: "BEGIN",
+ rowCount: null,
+ fields: [],
+ rows: []
+ });
+ expect(result).toBe("BEGIN\n");
+ });
+
+ it("UPDATE with row count", () => {
+ const result = formatCommandResult({
+ command: "UPDATE",
+ rowCount: 5,
+ fields: [],
+ rows: []
+ });
+ expect(result).toBe("UPDATE 5\n");
+ });
+
+ it("DELETE with zero rows", () => {
+ const result = formatCommandResult({
+ command: "DELETE",
+ rowCount: 0,
+ fields: [],
+ rows: []
+ });
+ expect(result).toBe("DELETE\n");
+ });
+});
+
+describe("formatError", () => {
+ it("formats pg error with message", () => {
+ const result = formatError({ message: 'relation "nonexistent" does not exist' });
+ expect(result).toBe('ERROR: relation "nonexistent" does not exist\n');
+ });
+
+ it("includes DETAIL if present", () => {
+ const result = formatError({
+ message: "duplicate key violation",
+ detail: "Key (id)=(1) already exists."
+ });
+ expect(result).toContain("ERROR: duplicate key violation\n");
+ expect(result).toContain("DETAIL: Key (id)=(1) already exists.\n");
+ });
+
+ it("includes HINT if present", () => {
+ const result = formatError({
+ message: "column does not exist",
+ hint: 'Perhaps you meant to reference the column "user"."name".'
+ });
+ expect(result).toContain("ERROR: column does not exist\n");
+ expect(result).toContain("HINT:");
+ });
+
+ it("handles non-pg errors", () => {
+ const result = formatError("something went wrong");
+ expect(result).toBe("ERROR: something went wrong\n");
+ });
+
+ it("handles null/undefined", () => {
+ const result = formatError(null);
+ expect(result).toContain("ERROR:");
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.ts
new file mode 100644
index 0000000000..f776b8b53f
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-sql-formatter.ts
@@ -0,0 +1,119 @@
+import { builtins } from "pg-types";
+
+// PostgreSQL numeric type OIDs for right-alignment
+const NUMERIC_TYPE_IDS = new Set([
+ builtins.INT8,
+ builtins.INT2,
+ builtins.INT4,
+ builtins.OID,
+ builtins.FLOAT4,
+ builtins.FLOAT8,
+ builtins.MONEY,
+ builtins.NUMERIC
+]);
+
+type TQueryResult = {
+ command: string;
+ rowCount: number | null;
+ fields: Array<{ name: string; dataTypeID: number }>;
+ rows: Record<string, unknown>[];
+};
+
+/**
+ * Formats a SELECT query result as a psql-style ASCII table.
+ */
+export const formatTable = (result: TQueryResult): string => {
+ const { fields, rows } = result;
+
+ if (!fields || fields.length === 0) {
+ return "";
+ }
+
+ // Convert all values to display strings.
+ // With raw type parsers all values are already strings, but handle
+ // Date/Buffer/Array defensively in case parsed types slip through.
+ const displayRows = rows.map((row) =>
+ fields.map((field) => {
+ const val = row[field.name];
+ if (val === null || val === undefined) return "";
+ if (val instanceof Date) return val.toISOString().replace("T", " ").replace("Z", "+00");
+ if (Buffer.isBuffer(val)) return `\\x${val.toString("hex")}`;
+ if (Array.isArray(val)) return `{${val.map((v) => String(v ?? "NULL")).join(",")}}`;
+ return String(val);
+ })
+ );
+
+ // Calculate column widths: max of header length and all value lengths
+ const colWidths = fields.map((field, colIdx) => {
+ let maxLen = field.name.length;
+ for (const row of displayRows) {
+ if (row[colIdx].length > maxLen) {
+ maxLen = row[colIdx].length;
+ }
+ }
+ return maxLen;
+ });
+
+ // Determine alignment per column
+ const isNumeric = fields.map((field) => NUMERIC_TYPE_IDS.has(field.dataTypeID));
+
+ // Build header row
+ const headerCells = fields.map((field, i) => ` ${field.name.padEnd(colWidths[i])} `);
+ const headerLine = headerCells.join("|");
+
+ // Build separator row
+ const separatorCells = colWidths.map((w) => "-".repeat(w + 2));
+ const separatorLine = separatorCells.join("+");
+
+ // Build data rows
+ const dataLines = displayRows.map((row) => {
+ const cells = row.map((val, i) => {
+ const padded = isNumeric[i] ? val.padStart(colWidths[i]) : val.padEnd(colWidths[i]);
+ return ` ${padded} `;
+ });
+ return cells.join("|");
+ });
+
+ // Footer
+ const rowCount = rows.length;
+ const footer = `(${rowCount} ${rowCount === 1 ? "row" : "rows"})`;
+
+ // Assemble
+ const parts = [headerLine, separatorLine, ...dataLines, footer, ""];
+ return parts.join("\n");
+};
+
+/**
+ * Formats a DML/DDL command result (e.g. "INSERT 0 3", "CREATE TABLE", "BEGIN").
+ */
+export const formatCommandResult = (result: TQueryResult): string => {
+ const { command, rowCount } = result;
+ if (rowCount != null && rowCount > 0) {
+ // INSERT returns "INSERT 0 <count>" in psql
+ if (command === "INSERT") {
+ return `INSERT 0 ${rowCount}\n`;
+ }
+ // UPDATE, DELETE return "<COMMAND> <count>"
+ return `${command} ${rowCount}\n`;
+ }
+ return `${command}\n`;
+};
+
+/**
+ * Formats a PostgreSQL error in psql style.
+ */
+export const formatError = (err: unknown): string => {
+ if (err && typeof err === "object") {
+ const pgErr = err as { message?: string; detail?: string; hint?: string; severity?: string };
+ const parts: string[] = [];
+ parts.push(`ERROR: ${pgErr.message ?? "Unknown error"}\n`);
+ if (pgErr.detail) {
+ parts.push(`DETAIL: ${pgErr.detail}\n`);
+ }
+ if (pgErr.hint) {
+ parts.push(`HINT: ${pgErr.hint}\n`);
+ }
+ return parts.join("");
+ }
+ return `ERROR: ${String(err)}\n`;
+};
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.test.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.test.ts
new file mode 100644
index 0000000000..95f827f02c
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from "vitest";
+
+import { splitStatements } from "./pam-web-access-sql-lexer";
+
+describe("splitStatements", () => {
+ // Basic cases
+ it("single complete statement", () => {
+ const result = splitStatements("SELECT 1;");
+ expect(result.complete).toEqual(["SELECT 1"]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("multiple statements on one line", () => {
+ const result = splitStatements("SELECT 1; SELECT 2;");
+ expect(result.complete).toEqual(["SELECT 1", " SELECT 2"]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("incomplete statement (no ;)", () => {
+ const result = splitStatements("SELECT 1");
+ expect(result.complete).toEqual([]);
+ expect(result.remainder).toBe("SELECT 1");
+ });
+
+ it("mixed complete + incomplete", () => {
+ const result = splitStatements("SELECT 1; SELECT");
+ expect(result.complete).toEqual(["SELECT 1"]);
+ expect(result.remainder).toBe(" SELECT");
+ });
+
+ it("empty statements", () => {
+ const result = splitStatements(";;;");
+ expect(result.complete).toEqual(["", "", ""]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("multi-line statement", () => {
+ const result = splitStatements("SELECT *\nFROM users;");
+ expect(result.complete).toEqual(["SELECT *\nFROM users"]);
+ expect(result.remainder).toBe("");
+ });
+
+ // Quoting
+ it("semicolon inside single quotes", () => {
+ const result = splitStatements("SELECT 'a;b';");
+ expect(result.complete).toEqual(["SELECT 'a;b'"]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("escaped single quote", () => {
+ const result = splitStatements("SELECT 'it''s';");
+ expect(result.complete).toEqual(["SELECT 'it''s'"]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("dollar-quoted string", () => {
+ const result = splitStatements("SELECT $$a;b$$;");
+ expect(result.complete).toEqual(["SELECT $$a;b$$"]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("dollar-quoted with tag", () => {
+ const result = splitStatements("SELECT $fn$a;b$fn$;");
+ expect(result.complete).toEqual(["SELECT $fn$a;b$fn$"]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("dollar sign not a quote (positional param)", () => {
+ const result = splitStatements("SELECT $1;");
+ expect(result.complete).toEqual(["SELECT $1"]);
+ expect(result.remainder).toBe("");
+ });
+
+ // Comments
+ it("line comment with semicolon", () => {
+ const result = splitStatements("SELECT 1; -- comment;\nSELECT 2;");
+ expect(result.complete).toHaveLength(2);
+ expect(result.complete[0]).toBe("SELECT 1");
+ expect(result.complete[1].trim()).toContain("SELECT 2");
+ });
+
+ it("block comment with semicolon", () => {
+ const result = splitStatements("SELECT /* ; */ 1;");
+ expect(result.complete).toEqual(["SELECT /* ; */ 1"]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("nested block comments", () => {
+ const result = splitStatements("SELECT /* /* ; */ */ 1;");
+ expect(result.complete).toEqual(["SELECT /* /* ; */ */ 1"]);
+ expect(result.remainder).toBe("");
+ });
+
+ // Edge cases
+ it("empty input", () => {
+ const result = splitStatements("");
+ expect(result.complete).toEqual([]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("only whitespace", () => {
+ const result = splitStatements(" ");
+ expect(result.complete).toEqual([]);
+ expect(result.remainder).toBe(" ");
+ });
+
+ it("only semicolons", () => {
+ const result = splitStatements(";;;");
+ expect(result.complete).toEqual(["", "", ""]);
+ expect(result.remainder).toBe("");
+ });
+
+ it("statement after line comment", () => {
+ const result = splitStatements("-- comment\nSELECT 1;");
+ expect(result.complete).toHaveLength(1);
+ expect(result.complete[0]).toContain("SELECT 1");
+ });
+
+ it("unclosed single quote keeps everything in remainder", () => {
+ const result = splitStatements("SELECT 'unclosed;");
+ expect(result.complete).toEqual([]);
+ expect(result.remainder).toBe("SELECT 'unclosed;");
+ });
+
+ it("unclosed block comment keeps everything in remainder", () => {
+ const result = splitStatements("SELECT /* unclosed ;");
+ expect(result.complete).toEqual([]);
+ expect(result.remainder).toBe("SELECT /* unclosed ;");
+ });
+
+ it("CREATE FUNCTION with dollar-quoted body", () => {
+ const sql = `CREATE FUNCTION test() RETURNS void AS $$ BEGIN PERFORM 1; END; $$ LANGUAGE plpgsql;`;
+ const result = splitStatements(sql);
+ expect(result.complete).toHaveLength(1);
+ expect(result.complete[0]).toContain("PERFORM 1;");
+ expect(result.remainder).toBe("");
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.ts b/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.ts
new file mode 100644
index 0000000000..792e2022a7
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-sql-lexer.ts
@@ -0,0 +1,169 @@
+type TSplitResult = {
+ complete: string[];
+ remainder: string;
+};
+
+enum LexerState {
+ Normal = "normal",
+ SingleQuote = "single_quote",
+ DollarQuote = "dollar_quote",
+ LineComment = "line_comment",
+ BlockComment = "block_comment"
+}
+
+/**
+ * Tries to parse a dollar-quote tag starting at position i.
+ * Returns the full tag (e.g. "$$" or "$fn$") if found, null otherwise.
+ */
+const tryParseDollarTag = (sql: string, i: number): string | null => {
+ // Must start with $
+ if (sql[i] !== "$") return null;
+
+ // Check for $$ (empty tag)
+ if (i + 1 < sql.length && sql[i + 1] === "$") {
+ return "$$";
+ }
+
+ // Check for $identifier$ pattern
+ // Identifier must start with [A-Za-z_\x80-\xff]
+ const startChar = i + 1 < sql.length ? sql.charCodeAt(i + 1) : 0;
+ const isValidStart =
+ (startChar >= 65 && startChar <= 90) || // A-Z
+ (startChar >= 97 && startChar <= 122) || // a-z
+ startChar === 95 || // _
+ startChar >= 128; // \x80-\xff
+
+ if (!isValidStart) return null;
+
+ // Scan for the rest of the identifier + closing $
+ let j = i + 2;
+ while (j < sql.length) {
+ const code = sql.charCodeAt(j);
+ const isValidContinue =
+ (code >= 65 && code <= 90) || // A-Z
+ (code >= 97 && code <= 122) || // a-z
+ (code >= 48 && code <= 57) || // 0-9
+ code === 95 || // _
+ code >= 128; // \x80-\xff
+
+ if (code === 36) {
+ // Found closing $
+ return sql.substring(i, j + 1);
+ }
+ if (!isValidContinue) {
+ return null;
+ }
+ j += 1;
+ }
+
+ return null;
+};
+
+/**
+ * Splits a SQL string into individual statements by detecting semicolons
+ * that are actual statement boundaries (not inside strings, comments, etc.).
+ *
+ * Returns complete statements (terminated by ;) and any remaining text.
+ */
+export const splitStatements = (sql: string): TSplitResult => {
+ const complete: string[] = [];
+ let buffer = "";
+ let state = LexerState.Normal;
+ let dollarTag = "";
+ let blockDepth = 0;
+ let i = 0;
+
+ while (i < sql.length) {
+ const ch = sql[i];
+ const next = i + 1 < sql.length ? sql[i + 1] : "";
+
+ switch (state) {
+ case LexerState.Normal:
+ if (ch === ";") {
+ complete.push(buffer);
+ buffer = "";
+ } else if (ch === "'") {
+ buffer += ch;
+ state = LexerState.SingleQuote;
+ } else if (ch === "$") {
+ // Check for dollar-quote tag: $$ or $identifier$
+ const tag = tryParseDollarTag(sql, i);
+ if (tag !== null) {
+ buffer += tag;
+ dollarTag = tag;
+ state = LexerState.DollarQuote;
+ i += tag.length - 1; // -1 because the loop will i++
+ } else {
+ buffer += ch;
+ }
+ } else if (ch === "-" && next === "-") {
+ buffer += "--";
+ state = LexerState.LineComment;
+ i += 1;
+ } else if (ch === "/" && next === "*") {
+ buffer += "/*";
+ state = LexerState.BlockComment;
+ blockDepth = 1;
+ i += 1;
+ } else {
+ buffer += ch;
+ }
+ break;
+
+ case LexerState.SingleQuote:
+ if (ch === "'" && next === "'") {
+ // Escaped single quote
+ buffer += "''";
+ i += 1;
+ } else if (ch === "'") {
+ buffer += ch;
+ state = LexerState.Normal;
+ } else {
+ buffer += ch;
+ }
+ break;
+
+ case LexerState.DollarQuote:
+ // Check if we've hit the closing dollar tag
+ if (ch === "$" && sql.substring(i, i + dollarTag.length) === dollarTag) {
+ buffer += dollarTag;
+ i += dollarTag.length - 1;
+ state = LexerState.Normal;
+ } else {
+ buffer += ch;
+ }
+ break;
+
+ case LexerState.LineComment:
+ buffer += ch;
+ if (ch === "\n") {
+ state = LexerState.Normal;
+ }
+ break;
+
+ case LexerState.BlockComment:
+ if (ch === "/" && next === "*") {
+ buffer += "/*";
+ blockDepth += 1;
+ i += 1;
+ } else if (ch === "*" && next === "/") {
+ buffer += "*/";
+ blockDepth -= 1;
+ if (blockDepth === 0) {
+ state = LexerState.Normal;
+ }
+ i += 1;
+ } else {
+ buffer += ch;
+ }
+ break;
+
+ default:
+ buffer += ch;
+ }
+
+ i += 1;
+ }
+
+ return { complete, remainder: buffer };
+};
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 e9887400ee..5ad0fd9d65 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
@@ -3,21 +3,50 @@ import { z } from "zod";
import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";
import { ProjectServiceActor } from "@app/lib/types";
-export const PAM_WEB_ACCESS_PROMPT = "=> ";
+// Default session duration for web access sessions (1 hour in ms)
+export const DEFAULT_WEB_SESSION_DURATION_MS = 60 * 60 * 1000;
+
+// Maximum concurrent web access sessions per user per project
+export const MAX_WEB_SESSIONS_PER_USER = 5;
+
+// WebSocket ping interval (ms) — keeps ALB from killing idle connections (default 60s timeout)
+export const WS_PING_INTERVAL_MS = 30000;
+
+// Idle timeout (ms) — auto-close sessions with no user input/control messages
+export const WS_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
export enum WsMessageType {
Ready = "ready",
Output = "output",
Input = "input",
- Control = "control"
+ Control = "control",
+ 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.",
+ IdleTimeout = "Session closed due to inactivity."
}
-export const WebSocketServerMessageSchema = z.object({
+const WebSocketOutputMessageSchema = z.object({
type: z.enum([WsMessageType.Ready, WsMessageType.Output]),
data: z.string(),
prompt: z.string()
});
+const WebSocketSessionEndMessageSchema = z.object({
+ type: z.literal(WsMessageType.SessionEnd),
+ reason: z.nativeEnum(SessionEndReason)
+});
+
+export const WebSocketServerMessageSchema = z.discriminatedUnion("type", [
+ WebSocketOutputMessageSchema,
+ WebSocketSessionEndMessageSchema
+]);
+
export type TWebSocketServerMessage = z.infer<typeof WebSocketServerMessageSchema>;
export const WebSocketClientMessageSchema = z.object({
@@ -25,12 +54,13 @@ export const WebSocketClientMessageSchema = z.object({
data: z.string()
});
-export type TWebSocketClientMessage = z.infer<typeof WebSocketClientMessageSchema>;
-
export type TIssueWebSocketTicketDTO = {
accountId: string;
projectId: string;
orgId: string;
actor: ProjectServiceActor;
+ actorEmail: string;
+ actorName: string;
auditLogInfo: AuditLogInfo;
+ mfaSessionId?: string;
};
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index e8f614666d..e99c24a478 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -76,7 +76,7 @@ export const createRelayConnection = async ({
});
};
-const createGatewayConnection = async (
+export const createGatewayConnection = async (
relayConn: net.Socket,
gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string },
protocol: GatewayProxyProtocol
@@ -86,7 +86,9 @@ const createGatewayConnection = async (
const protocolToAlpn = {
[GatewayProxyProtocol.Http]: "infisical-http-proxy",
[GatewayProxyProtocol.Tcp]: "infisical-tcp-proxy",
- [GatewayProxyProtocol.Ping]: "infisical-ping"
+ [GatewayProxyProtocol.Ping]: "infisical-ping",
+ [GatewayProxyProtocol.Pam]: "infisical-pam-proxy",
+ [GatewayProxyProtocol.PamSessionCancellation]: "infisical-pam-session-cancellation"
};
const tlsOptions: tls.ConnectionOptions = {
@@ -137,13 +139,15 @@ export const setupRelayServer = async ({
relayHost,
gateway,
relay,
- httpsAgent
+ httpsAgent,
+ longLived
}: {
protocol: GatewayProxyProtocol;
relayHost: string;
gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
relay: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string };
httpsAgent?: https.Agent;
+ longLived?: boolean;
}): Promise<IGatewayRelayServer> => {
const relayErrorMsg: string[] = [];
@@ -167,6 +171,18 @@ export const setupRelayServer = async ({
// Stage 2: Establish mTLS connection to gateway through the relay
const gatewayConn = await createGatewayConnection(relayConn, gateway, protocol);
+ if (longLived) {
+ // Disable the 30s idle-activity timeout that was set during connection establishment.
+ // Without this, the socket is destroyed after 30s of no data, killing idle sessions.
+ relayConn.setTimeout(0);
+ gatewayConn.setTimeout(0);
+
+ // Enable TCP keep-alive probes every 30s to detect dead connections
+ // without terminating idle-but-alive ones.
+ relayConn.setKeepAlive(true, 30000);
+ gatewayConn.setKeepAlive(true, 30000);
+ }
+
// Send protocol-specific configuration for HTTP requests
if (protocol === GatewayProxyProtocol.Http) {
if (httpsAgent) {
diff --git a/backend/src/lib/gateway/types.ts b/backend/src/lib/gateway/types.ts
index e9b8b71141..aafdd28f02 100644
--- a/backend/src/lib/gateway/types.ts
+++ b/backend/src/lib/gateway/types.ts
@@ -7,7 +7,9 @@ export type TGatewayTlsOptions = { ca: string; cert: string; key: string };
export enum GatewayProxyProtocol {
Http = "http",
Tcp = "tcp",
- Ping = "ping"
+ Ping = "ping",
+ Pam = "pam",
+ PamSessionCancellation = "pam-session-cancellation"
}
export enum GatewayHttpProxyActions {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index eb8e70c6e3..a42e7ce57d 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2613,7 +2613,17 @@ export const registerRoutes = async (
pamResourceDAL,
permissionService,
auditLogService,
- tokenService
+ tokenService,
+ pamSessionDAL,
+ pamSessionExpirationService,
+ gatewayV2Service,
+ kmsService,
+ userDAL,
+ mfaSessionService,
+ approvalPolicyDAL,
+ approvalRequestGrantsDAL,
+ orgDAL,
+ projectDAL
});
const aiMcpServerService = aiMcpServerServiceFactory({
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index d0ece1fe03..80936c270b 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -58,6 +58,7 @@
"@types/nprogress": "^0.2.3",
"@ucast/mongo2js": "^1.3.4",
"@xterm/addon-fit": "^0.10.0",
+ "@xterm/addon-web-links": "^0.12.0",
"@xterm/xterm": "^5.5.0",
"@xyflow/react": "^12.4.4",
"argon2-browser": "^1.18.0",
@@ -6187,6 +6188,12 @@
"@xterm/xterm": "^5.0.0"
}
},
+ "node_modules/@xterm/addon-web-links": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.12.0.tgz",
+ "integrity": "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==",
+ "license": "MIT"
+ },
"node_modules/@xterm/xterm": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index cf6f156632..a114a8edca 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -67,6 +67,7 @@
"@types/nprogress": "^0.2.3",
"@ucast/mongo2js": "^1.3.4",
"@xterm/addon-fit": "^0.10.0",
+ "@xterm/addon-web-links": "^0.12.0",
"@xterm/xterm": "^5.5.0",
"@xyflow/react": "^12.4.4",
"argon2-browser": "^1.18.0",
diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.ts
index 44543b1d27..27ddc3fa58 100644
--- a/frontend/src/const/routes.ts
+++ b/frontend/src/const/routes.ts
@@ -377,6 +377,10 @@ export const ROUTE_PATHS = Object.freeze({
PamAccountByIDPage: setRoute(
"/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId",
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId"
+ ),
+ PamAccountAccessPage: setRoute(
+ "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access",
+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"
)
},
Public: {
diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx
index ed9f69a93a..9223050d01 100644
--- a/frontend/src/hooks/api/pam/mutations.tsx
+++ b/frontend/src/hooks/api/pam/mutations.tsx
@@ -167,19 +167,6 @@ export const useAccessPamAccount = () => {
});
};
-// Web Access
-export const useCreatePamWebAccessTicket = () => {
- return useMutation({
- mutationFn: async ({ accountId, projectId }: { accountId: string; projectId: string }) => {
- const { data } = await apiRequest.post<{ ticket: string }>(
- `/api/v1/pam/accounts/${accountId}/web-access-ticket`,
- { projectId }
- );
- return data.ticket;
- }
- });
-};
-
// Folders
export const useCreatePamFolder = () => {
const queryClient = useQueryClient();
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
new file mode 100644
index 0000000000..2a7d5e5892
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
@@ -0,0 +1,123 @@
+import { useState } from "react";
+import { Helmet } from "react-helmet";
+import { useParams } from "@tanstack/react-router";
+
+import { useGetPamAccountById } from "@app/hooks/api/pam";
+
+import { useWebAccessSession } from "./useWebAccessSession";
+
+const PageContent = () => {
+ const params = useParams({
+ strict: false
+ }) as {
+ accountId?: string;
+ projectId?: string;
+ orgId?: string;
+ resourceType?: string;
+ resourceId?: string;
+ };
+
+ const { accountId, projectId, orgId } = params;
+
+ const { data: account, isPending } = useGetPamAccountById(accountId);
+
+ const [sessionEnded, setSessionEnded] = useState(false);
+
+ const { containerRef, isConnected, disconnect, reconnect } = useWebAccessSession({
+ accountId: accountId!,
+ projectId: projectId!,
+ orgId: orgId!,
+ resourceName: account?.resource.name ?? "",
+ accountName: account?.name ?? "",
+ onSessionEnd: () => setSessionEnded(true)
+ });
+
+ const handleReconnect = () => {
+ setSessionEnded(false);
+ reconnect();
+ };
+
+ if (isPending) {
+ return (
+ <div className="flex h-screen w-screen items-center justify-center bg-[#0d1117] text-mineshaft-300">
+ Loading...
+ </div>
+ );
+ }
+
+ if (!account) {
+ return (
+ <div className="flex h-screen w-screen items-center justify-center bg-[#0d1117]">
+ <p className="text-mineshaft-300">Could not find PAM Account with ID {accountId}</p>
+ </div>
+ );
+ }
+
+ let statusLabel = "Connecting";
+ let statusDotClass = "bg-yellow-500";
+ if (isConnected) {
+ statusLabel = "Connected";
+ statusDotClass = "bg-green-500";
+ } else if (sessionEnded) {
+ statusLabel = "Disconnected";
+ statusDotClass = "bg-mineshaft-400";
+ }
+
+ return (
+ <div className="flex h-screen w-screen flex-col bg-[#0d1117]">
+ <div
+ className="thin-scrollbar flex-1 overflow-x-auto overflow-y-hidden p-2 [&_.xterm-viewport]:thin-scrollbar"
+ style={{ minHeight: 0 }}
+ >
+ <div ref={containerRef} className="h-full" style={{ minWidth: "100%" }} />
+ </div>
+ <div className="flex items-center justify-between border-t border-mineshaft-600 bg-mineshaft-800 px-3 py-1.5 text-xs">
+ <span className="flex items-center gap-1.5">
+ <span className={`inline-block size-2 rounded-full ${statusDotClass}`} />
+ <span className="text-mineshaft-300">{statusLabel}</span>
+ {isConnected && (
+ <button
+ type="button"
+ onClick={disconnect}
+ className="ml-2 text-mineshaft-400 hover:text-red-400"
+ >
+ Disconnect
+ </button>
+ )}
+ {sessionEnded && (
+ <button
+ type="button"
+ onClick={handleReconnect}
+ className="ml-2 text-mineshaft-400 hover:text-green-400"
+ >
+ Reconnect
+ </button>
+ )}
+ </span>
+ <div className="flex items-center gap-4">
+ <span>
+ <span className="text-mineshaft-400">Resource:</span>{" "}
+ <span className="text-mineshaft-300">{account.resource.name}</span>
+ </span>
+ <span className="text-mineshaft-500">|</span>
+ <span>
+ <span className="text-mineshaft-400">Account:</span>{" "}
+ <span className="text-mineshaft-300">{account.name}</span>
+ </span>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export const PamAccountAccessPage = () => {
+ return (
+ <>
+ <Helmet>
+ <title>Web Access | Infisical</title>
+ <link rel="icon" href="/infisical.ico" />
+ </Helmet>
+ <PageContent />
+ </>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/route.tsx b/frontend/src/pages/pam/PamAccountAccessPage/route.tsx
new file mode 100644
index 0000000000..3a635c36e8
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountAccessPage/route.tsx
@@ -0,0 +1,9 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { PamAccountAccessPage } from "./PamAccountAccessPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"
+)({
+ component: PamAccountAccessPage
+});
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
new file mode 100644
index 0000000000..d2fed7a64d
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountAccessPage/useWebAccessSession.ts
@@ -0,0 +1,443 @@
+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 { apiRequest } from "@app/config/request";
+import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession/types";
+
+import { WebSocketServerMessageSchema, WsMessageType } from "./web-access-types";
+
+import "@xterm/xterm/css/xterm.css";
+
+type UseWebAccessSessionOptions = {
+ accountId: string;
+ projectId: string;
+ orgId: string;
+ resourceName: string;
+ accountName: string;
+ onSessionEnd?: () => void;
+};
+
+export const useWebAccessSession = ({
+ accountId,
+ projectId,
+ orgId,
+ resourceName,
+ accountName,
+ onSessionEnd
+}: UseWebAccessSessionOptions) => {
+ const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null);
+ const [isConnected, setIsConnected] = useState(false);
+ const wsRef = useRef<WebSocket | null>(null);
+ const terminalRef = useRef<Terminal | null>(null);
+ const fitAddonRef = useRef<FitAddon | null>(null);
+ const isWidenedRef = useRef(false);
+ const inputBufferRef = useRef("");
+ const currentPromptRef = useRef("");
+ const promptCallbackRef = useRef<((input: string) => void) | null>(null);
+
+ const onSessionEndRef = useRef(onSessionEnd);
+
+ useEffect(() => {
+ onSessionEndRef.current = onSessionEnd;
+ }, [onSessionEnd]);
+
+ const adjustWidthForOutput = useCallback(
+ (output: string, terminal: Terminal, fitAddon: FitAddon, container: HTMLDivElement) => {
+ const lines = output.split("\n");
+ const longestLine = Math.max(...lines.map((l) => l.length));
+
+ if (longestLine <= terminal.cols) return;
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, no-underscore-dangle
+ const cellWidth = (terminal as any)._core._renderService.dimensions.css.cell.width as number;
+ if (!cellWidth) return;
+
+ const MAX_COLS = 10000;
+ const neededCols = Math.min(longestLine + 2, MAX_COLS);
+ const neededWidth = neededCols * cellWidth;
+
+ const currentWidth = container.getBoundingClientRect().width;
+ if (neededWidth <= currentWidth) return;
+
+ // eslint-disable-next-line no-param-reassign
+ container.style.width = `${neededWidth}px`;
+ fitAddon.fit();
+ isWidenedRef.current = true;
+ },
+ []
+ );
+
+ // --- WebSocket lifecycle (imperative) ---
+
+ const openWebSocket = useCallback(
+ (terminal: Terminal, ticket: string) => {
+ const { protocol, host } = window.location;
+ const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
+ const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;
+ const ws = new WebSocket(wsUrl);
+ wsRef.current = ws;
+
+ ws.onmessage = (event) => {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(event.data as string);
+ } catch {
+ return;
+ }
+ const parsed = WebSocketServerMessageSchema.safeParse(raw);
+ if (!parsed.success) return;
+ const msg = parsed.data;
+
+ if (msg.type === WsMessageType.Ready) {
+ setIsConnected(true);
+ setTimeout(() => terminal.focus(), 100);
+ }
+
+ if (msg.type === WsMessageType.SessionEnd) {
+ terminal.write(`\r\n${msg.reason.replace(/\r?\n/g, "\r\n")}\r\n`);
+ return;
+ }
+
+ if (msg.data) {
+ if (containerEl && fitAddonRef.current) {
+ adjustWidthForOutput(msg.data, terminal, fitAddonRef.current, containerEl);
+ }
+ terminal.write(msg.data.replace(/\r?\n/g, "\r\n"));
+ }
+ if (msg.prompt) {
+ currentPromptRef.current = msg.prompt;
+ terminal.write(msg.prompt);
+ }
+ };
+
+ ws.onclose = () => {
+ wsRef.current = null;
+ if (terminalRef.current) {
+ terminalRef.current.options.disableStdin = true;
+ }
+ setIsConnected(false);
+ onSessionEndRef.current?.();
+ };
+
+ ws.onerror = () => {
+ // no-op: onclose always fires after onerror
+ };
+ },
+ [accountId, containerEl, adjustWidthForOutput]
+ );
+
+ const connect = useCallback(async () => {
+ const terminal = terminalRef.current;
+ if (!terminal) return;
+
+ inputBufferRef.current = "";
+ currentPromptRef.current = "";
+
+ const prompt = (message: string): Promise<string> => {
+ return new Promise((resolve) => {
+ terminal.write(message);
+ promptCallbackRef.current = resolve;
+ });
+ };
+
+ try {
+ const { data } = await apiRequest.post<{ ticket: string }>(
+ `/api/v1/pam/accounts/${accountId}/web-access-ticket`,
+ { projectId }
+ );
+ if (containerEl) {
+ containerEl.style.width = "";
+ isWidenedRef.current = false;
+ }
+ if (fitAddonRef.current) fitAddonRef.current.fit();
+ terminal.reset();
+ openWebSocket(terminal, data.ticket);
+ } catch (err: unknown) {
+ const axiosErr = err as {
+ response?: {
+ data?: {
+ error?: string;
+ details?: {
+ mfaSessionId?: string;
+ mfaMethod?: string;
+ policyId?: string;
+ policyName?: string;
+ policyType?: string;
+ };
+ };
+ };
+ };
+
+ if (axiosErr?.response?.data?.error === "SESSION_MFA_REQUIRED") {
+ const mfaSessionId = axiosErr.response!.data!.details?.mfaSessionId;
+
+ if (!mfaSessionId) {
+ terminal.write("\r\nMFA session could not be created. Please try again.\r\n");
+ return;
+ }
+
+ const mfaUrl = `${window.location.origin}/mfa-session/${mfaSessionId}`;
+
+ // Try to open MFA verification in a new window.
+ const popup = window.open(mfaUrl, "_blank");
+
+ terminal.write(
+ "\r\nMFA verification required. Complete verification in the opened window or via this link:\r\n"
+ );
+ terminal.write(`\r\n ${mfaUrl}\r\n\r\n`);
+ terminal.write("Waiting for verification...\r\n");
+
+ // Poll for MFA session to become ACTIVE
+ const MFA_POLL_INTERVAL = 2000;
+ const MFA_TIMEOUT = 5 * 60 * 1000; // 5 minutes
+ const startTime = Date.now();
+
+ const mfaVerified = await new Promise<boolean>((resolve) => {
+ const interval = setInterval(async () => {
+ if (Date.now() - startTime > MFA_TIMEOUT) {
+ clearInterval(interval);
+ resolve(false);
+ return;
+ }
+
+ try {
+ const resp = await apiRequest.get<TMfaSessionStatusResponse>(
+ `/api/v2/mfa-sessions/${mfaSessionId}/status`
+ );
+ if (resp.data.status === MfaSessionStatus.ACTIVE) {
+ clearInterval(interval);
+ resolve(true);
+ }
+ } catch {
+ clearInterval(interval);
+ resolve(false);
+ }
+ }, MFA_POLL_INTERVAL);
+ });
+
+ // Close popup if still open
+ if (popup && !popup.closed) {
+ popup.close();
+ }
+
+ if (!mfaVerified) {
+ terminal.write("\r\nMFA verification timed out or failed. Please try again.\r\n");
+ return;
+ }
+
+ // Retry ticket request with verified MFA session
+ try {
+ if (containerEl) {
+ containerEl.style.width = "";
+ isWidenedRef.current = false;
+ }
+ if (fitAddonRef.current) fitAddonRef.current.fit();
+ terminal.reset();
+ const { data: retryData } = await apiRequest.post<{ ticket: string }>(
+ `/api/v1/pam/accounts/${accountId}/web-access-ticket`,
+ { projectId, mfaSessionId }
+ );
+ openWebSocket(terminal, retryData.ticket);
+ } catch {
+ terminal.write("\r\nFailed to connect after MFA verification. Please try again.\r\n");
+ }
+ return;
+ }
+
+ // Check for PolicyViolationError
+ if (axiosErr?.response?.data?.error === "PolicyViolationError") {
+ const policyName = axiosErr.response!.data!.details?.policyName ?? "Unknown Policy";
+
+ terminal.write(`\r\nThis account is protected by approval policy: "${policyName}"\r\n`);
+
+ const answer = await prompt(
+ "\r\nThis action requires approval. Would you like to create an approval request? [Y/n]: "
+ );
+
+ if (answer.trim().toLowerCase() === "n") {
+ terminal.write("\r\nApproval request was not created.\r\n");
+ await prompt("\r\nPress Enter to try again.");
+ terminal.reset();
+ connect();
+ return;
+ }
+
+ const justification = await prompt(
+ "\r\nEnter justification (optional, press Enter to skip): "
+ );
+
+ terminal.write("\r\nCreating approval request...\r\n");
+
+ try {
+ const { data: approvalData } = await apiRequest.post<{ request: { id: string } }>(
+ "/api/v1/approval-policies/pam-access/requests",
+ {
+ projectId,
+ requestData: {
+ accessDuration: "1h",
+ resourceName,
+ accountName
+ },
+ justification: justification.trim() || undefined
+ }
+ );
+
+ terminal.write("\r\nApproval request created successfully!\r\n");
+
+ const approvalUrl = `${window.location.origin}/organizations/${orgId}/projects/pam/${projectId}/approval-requests/${approvalData.request.id}`;
+ terminal.write(`View details at: ${approvalUrl}\r\n`);
+
+ await prompt("\r\nOnce approved, press Enter to reconnect.");
+ terminal.reset();
+ connect();
+ } catch (approvalErr: unknown) {
+ const approvalAxiosErr = approvalErr as {
+ response?: { data?: { message?: string } };
+ };
+ const errorMsg =
+ approvalAxiosErr?.response?.data?.message ?? "Failed to create approval request.";
+ terminal.write(`\r\n${errorMsg}\r\n`);
+ await prompt("\r\nPress Enter to try again.");
+ terminal.reset();
+ connect();
+ }
+ return;
+ }
+
+ terminal.write("\r\nFailed to connect. Please close and try again.\r\n");
+ }
+ }, [accountId, projectId, orgId, resourceName, accountName, containerEl, openWebSocket]);
+
+ const disconnect = useCallback(() => {
+ const ws = wsRef.current;
+ wsRef.current = null;
+
+ if (ws) {
+ if (ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ type: WsMessageType.Control, data: "quit" }));
+ }
+ ws.close();
+ }
+ }, []);
+
+ const reconnect = useCallback(() => {
+ disconnect();
+ if (containerEl) {
+ containerEl.style.width = "";
+ isWidenedRef.current = false;
+ }
+ if (fitAddonRef.current) fitAddonRef.current.fit();
+ if (terminalRef.current) {
+ terminalRef.current.reset();
+ terminalRef.current.options.disableStdin = false;
+ }
+ connect();
+ }, [disconnect, connect, containerEl]);
+
+ // --- Terminal lifecycle (effect, tied to containerEl) ---
+
+ useEffect(() => {
+ if (!containerEl || !accountId) return undefined;
+
+ const terminal = new Terminal({
+ cursorBlink: true,
+ fontSize: 14,
+ fontFamily: '"JetBrains Mono", "Fira Code", Menlo, Monaco, "Courier New", monospace',
+ theme: {
+ background: "#0d1117",
+ foreground: "#c9d1d9",
+ cursor: "#58a6ff",
+ cursorAccent: "#0d1117",
+ selectionBackground: "#264f78",
+ black: "#0d1117",
+ red: "#ff7b72",
+ green: "#3fb950",
+ yellow: "#d29922",
+ blue: "#58a6ff",
+ magenta: "#bc8cff",
+ cyan: "#76e3ea",
+ white: "#c9d1d9",
+ brightBlack: "#484f58",
+ brightRed: "#ffa198",
+ brightGreen: "#56d364",
+ brightYellow: "#e3b341",
+ brightBlue: "#79c0ff",
+ brightMagenta: "#d2a8ff",
+ brightCyan: "#b3f0ff",
+ brightWhite: "#f0f6fc"
+ },
+ scrollback: 10000,
+ allowProposedApi: true
+ });
+
+ const fitAddon = new FitAddon();
+ const webLinksAddon = new WebLinksAddon();
+ terminal.loadAddon(fitAddon);
+ terminal.loadAddon(webLinksAddon);
+ terminal.open(containerEl);
+ fitAddon.fit();
+ terminalRef.current = terminal;
+ fitAddonRef.current = fitAddon;
+
+ // Wire terminal keyboard input — reads wsRef/inputBufferRef/currentPromptRef dynamically
+ 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"));
+ }
+ });
+
+ // Resize handling
+ const handleResize = () => fitAddon.fit();
+ const resizeObserver = new ResizeObserver(handleResize);
+ resizeObserver.observe(containerEl);
+ window.addEventListener("resize", handleResize);
+
+ // Auto-connect
+ connect();
+
+ return () => {
+ terminalRef.current = null;
+ fitAddonRef.current = null;
+ window.removeEventListener("resize", handleResize);
+ resizeObserver.disconnect();
+ disconnect();
+ terminal.dispose();
+ setIsConnected(false);
+ };
+ }, [containerEl, accountId, connect, disconnect]);
+
+ const containerRef = useCallback((node: HTMLDivElement | null) => {
+ setContainerEl(node);
+ }, []);
+
+ return { containerRef, isConnected, disconnect, reconnect };
+};
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/web-access-types.ts b/frontend/src/pages/pam/PamAccountAccessPage/web-access-types.ts
new file mode 100644
index 0000000000..86deebc007
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountAccessPage/web-access-types.ts
@@ -0,0 +1,25 @@
+import { z } from "zod";
+
+export enum WsMessageType {
+ Ready = "ready",
+ Output = "output",
+ Input = "input",
+ Control = "control",
+ SessionEnd = "session_end"
+}
+
+const WebSocketOutputMessageSchema = z.object({
+ type: z.enum([WsMessageType.Ready, WsMessageType.Output]),
+ data: z.string(),
+ prompt: z.string()
+});
+
+const WebSocketSessionEndMessageSchema = z.object({
+ type: z.literal(WsMessageType.SessionEnd),
+ reason: z.string()
+});
+
+export const WebSocketServerMessageSchema = z.discriminatedUnion("type", [
+ WebSocketOutputMessageSchema,
+ WebSocketSessionEndMessageSchema
+]);
diff --git a/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx b/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx
index 839ff35e18..e920d34298 100644
--- a/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx
+++ b/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx
@@ -28,7 +28,6 @@ import { PamAccessAccountModal } from "../PamAccountsPage/components/PamAccessAc
import { PamDeleteAccountModal } from "../PamAccountsPage/components/PamDeleteAccountModal";
import { PamRequestAccountAccessModal } from "../PamAccountsPage/components/PamRequestAccountAccessModal";
import { PamUpdateAccountModal } from "../PamAccountsPage/components/PamUpdateAccountModal";
-import { PamWebAccessModal } from "../PamAccountsPage/components/PamWebAccess";
import { useAccessAwsIamAccount } from "../PamAccountsPage/components/useAccessAwsIamAccount";
import {
PamAccountCredentialsSection,
@@ -55,7 +54,6 @@ const PageContent = () => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"accessAccount",
- "webAccess",
"requestAccount",
"deleteAccount"
] as const);
@@ -234,16 +232,6 @@ const PageContent = () => {
onOpenChange={(isOpen) => handlePopUpToggle("accessAccount", isOpen)}
account={popUp.accessAccount.data?.account}
projectId={projectId!}
- onOpenWebAccess={() => {
- handlePopUpOpen("webAccess", { account: popUp.accessAccount.data?.account });
- }}
- />
-
- <PamWebAccessModal
- isOpen={popUp.webAccess.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("webAccess", isOpen)}
- account={popUp.webAccess.data?.account}
- projectId={projectId!}
/>
<PamRequestAccountAccessModal
diff --git a/frontend/src/pages/pam/PamAccountByIDPage/route.tsx b/frontend/src/pages/pam/PamAccountByIDPage/route.tsx
index c12bdf508f..1e89f2526f 100644
--- a/frontend/src/pages/pam/PamAccountByIDPage/route.tsx
+++ b/frontend/src/pages/pam/PamAccountByIDPage/route.tsx
@@ -3,7 +3,7 @@ import { createFileRoute, linkOptions } from "@tanstack/react-router";
import { PamAccountByIDPage } from "./PamAccountByIDPage";
export const Route = createFileRoute(
- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId"
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId/"
)({
component: PamAccountByIDPage,
beforeLoad: ({ context, params }) => {
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
index 9c84950585..a7765625c6 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx
@@ -2,30 +2,24 @@ import { useMemo, useState } from "react";
import { faCopy } from "@fortawesome/free-regular-svg-icons";
import { faTerminal, faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Link } from "@tanstack/react-router";
import ms from "ms";
import { createNotification } from "@app/components/notifications";
-import { Button, FormLabel, IconButton, Input, Modal, ModalContent } from "@app/components/v2";
+import { FormLabel, IconButton, Input, Modal, ModalContent } from "@app/components/v2";
+import { ROUTE_PATHS } from "@app/const/routes";
+import { useOrganization } from "@app/context";
import { PamResourceType, TPamAccount } from "@app/hooks/api/pam";
-// Feature flag — set to false to hide the browser web access option while it's in development
-const ENABLE_WEB_ACCESS = false;
-
type Props = {
account?: TPamAccount;
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
- onOpenWebAccess?: () => void;
projectId: string;
};
-export const PamAccessAccountModal = ({
- isOpen,
- onOpenChange,
- onOpenWebAccess,
- account,
- projectId
-}: Props) => {
+export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectId }: Props) => {
+ const { currentOrg } = useOrganization();
const [duration, setDuration] = useState("4h");
const { protocol, hostname, port } = window.location;
@@ -93,10 +87,7 @@ export const PamAccessAccountModal = ({
if (!account) return null;
- const showWebAccess =
- ENABLE_WEB_ACCESS &&
- account.resource.resourceType === PamResourceType.Postgres &&
- onOpenWebAccess;
+ const showWebAccess = account.resource.resourceType === PamResourceType.Postgres;
return (
<Modal isOpen={isOpen} onOpenChange={onOpenChange}>
@@ -105,63 +96,80 @@ export const PamAccessAccountModal = ({
title="Access Account"
subTitle={`Connect to ${account.name}`}
>
- <p className="mb-2 text-sm text-mineshaft-300">Connect using the Infisical CLI</p>
- <FormLabel
- label="Duration"
- tooltipText="The maximum duration of your session. Ex: 1h, 3w, 30d"
- />
- <Input
- value={duration}
- onChange={(e) => setDuration(e.target.value)}
- placeholder="permanent"
- isError={!isDurationValid}
- />
- <FormLabel label="CLI Command" className="mt-4" />
- <div className="flex gap-2">
- <Input value={command} isDisabled />
- <IconButton
- ariaLabel="copy"
- variant="outline_bg"
- colorSchema="secondary"
- onClick={() => {
- navigator.clipboard.writeText(command);
-
- createNotification({
- text: "Command copied to clipboard",
- type: "info"
- });
-
- onOpenChange(false);
- }}
- className="w-10"
- >
- <FontAwesomeIcon icon={faCopy} />
- </IconButton>
- </div>
- <a
- href="https://infisical.com/docs/cli/overview"
- target="_blank"
- className="mt-2 flex h-4 w-fit items-center gap-2 border-b border-mineshaft-400 text-sm text-mineshaft-400 transition-colors duration-100 hover:border-yellow-400 hover:text-yellow-400"
- rel="noreferrer"
- >
- <span>Install the Infisical CLI</span>
- <FontAwesomeIcon icon={faUpRightFromSquare} className="size-3" />
- </a>
- {showWebAccess && (
- <>
- <div className="my-4 border-t border-mineshaft-600" />
- <p className="mb-2 text-sm text-mineshaft-300">Connect directly from your browser</p>
- <Button
+ <div className="py-1">
+ <p className="text-sm font-medium text-mineshaft-400">Terminal</p>
+ <p className="mb-2 text-xs text-mineshaft-400">Connect using the Infisical CLI</p>
+ <FormLabel
+ label="Duration"
+ tooltipText="The maximum duration of your session. Ex: 1h, 3w, 30d"
+ />
+ <Input
+ value={duration}
+ onChange={(e) => setDuration(e.target.value)}
+ placeholder="permanent"
+ isError={!isDurationValid}
+ />
+ <FormLabel label="CLI Command" className="mt-4" />
+ <div className="flex gap-2">
+ <Input value={command} isDisabled />
+ <IconButton
+ ariaLabel="copy"
+ variant="outline_bg"
+ colorSchema="secondary"
onClick={() => {
+ navigator.clipboard.writeText(command);
+
+ createNotification({
+ text: "Command copied to clipboard",
+ type: "info"
+ });
+
onOpenChange(false);
- onOpenWebAccess();
}}
- leftIcon={<FontAwesomeIcon icon={faTerminal} />}
- className="w-full"
- colorSchema="primary"
+ className="w-10"
>
- Connect in Browser
- </Button>
+ <FontAwesomeIcon icon={faCopy} />
+ </IconButton>
+ </div>
+ <a
+ href="https://infisical.com/docs/cli/overview"
+ target="_blank"
+ className="mt-2 flex h-4 w-fit items-center gap-2 border-b border-mineshaft-400 text-sm text-mineshaft-400 transition-colors duration-100 hover:border-yellow-400 hover:text-yellow-400"
+ rel="noreferrer"
+ >
+ <span>Install the Infisical CLI</span>
+ <FontAwesomeIcon icon={faUpRightFromSquare} className="size-3" />
+ </a>
+ </div>
+ {showWebAccess && (
+ <>
+ <div className="relative my-6">
+ <div className="absolute inset-0 flex items-center">
+ <div className="w-full border-t border-mineshaft-600" />
+ </div>
+ <div className="relative flex justify-center text-xs">
+ <span className="bg-mineshaft-900 px-2 text-mineshaft-400">OR</span>
+ </div>
+ </div>
+ <div className="py-1">
+ <p className="text-sm font-medium text-mineshaft-400">Browser</p>
+ <p className="mb-2 text-xs text-mineshaft-400">Connect directly from your browser</p>
+ <Link
+ to={ROUTE_PATHS.Pam.PamAccountAccessPage.path}
+ params={{
+ orgId: currentOrg.id,
+ projectId,
+ resourceType: account.resource.resourceType,
+ resourceId: account.resource.id,
+ accountId: account.id
+ }}
+ target="_blank"
+ className="flex w-full items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-black transition-colors hover:bg-primary/80"
+ >
+ <FontAwesomeIcon icon={faTerminal} />
+ Connect in Browser
+ </Link>
+ </div>
</>
)}
</ModalContent>
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/PamWebAccessModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/PamWebAccessModal.tsx
deleted file mode 100644
index acb2730de3..0000000000
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/PamWebAccessModal.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { useEffect } from "react";
-
-import { Button, Modal, ModalContent } from "@app/components/v2";
-import { TPamAccount } from "@app/hooks/api/pam";
-
-import { usePamWebAccessSession } from "./usePamWebAccessSession";
-
-type Props = {
- isOpen: boolean;
- onOpenChange: (isOpen: boolean) => void;
- account?: TPamAccount;
- projectId: string;
-};
-
-export const PamWebAccessModal = ({ isOpen, onOpenChange, account, projectId }: Props) => {
- const { containerRef, isConnected, disconnect } = usePamWebAccessSession({
- accountId: account?.id || "",
- projectId
- });
-
- useEffect(() => {
- if (!isConnected) return undefined;
-
- const handler = (e: BeforeUnloadEvent) => {
- e.preventDefault();
- };
-
- window.addEventListener("beforeunload", handler);
- return () => window.removeEventListener("beforeunload", handler);
- }, [isConnected]);
-
- // Disconnect when modal closes
- useEffect(() => {
- if (!isOpen) {
- disconnect();
- }
- }, [isOpen, disconnect]);
-
- const handleDisconnect = () => {
- disconnect();
- onOpenChange(false);
- };
-
- if (!account) return null;
-
- return (
- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
- <ModalContent
- className="max-w-[90vw]"
- title="Web Launcher"
- subTitle={`${account.name} (${account.resource.name})`}
- >
- <div className="flex flex-col gap-4">
- <div className="h-[70vh] overflow-hidden rounded-md border border-mineshaft-600">
- <div
- className="h-full w-full overflow-hidden rounded-md bg-[#0d1117] p-2 [&_.xterm-viewport]:thin-scrollbar"
- style={{ minHeight: "300px" }}
- >
- <div ref={containerRef} className="h-full w-full" />
- </div>
- </div>
-
- <div className="flex justify-end">
- {isConnected ? (
- <Button onClick={handleDisconnect} variant="outline_bg">
- Disconnect
- </Button>
- ) : (
- <Button onClick={() => onOpenChange(false)} variant="outline_bg">
- Close
- </Button>
- )}
- </div>
- </div>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/index.ts b/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/index.ts
deleted file mode 100644
index 07b1b1419d..0000000000
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { PamWebAccessModal } from "./PamWebAccessModal";
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/pam-web-access-types.ts b/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/pam-web-access-types.ts
deleted file mode 100644
index a84612d8ec..0000000000
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/pam-web-access-types.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { z } from "zod";
-
-export enum WsMessageType {
- Ready = "ready",
- Output = "output",
- Input = "input",
- Control = "control"
-}
-
-export const WebSocketServerMessageSchema = z.object({
- type: z.enum([WsMessageType.Ready, WsMessageType.Output]),
- data: z.string(),
- prompt: z.string()
-});
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/usePamWebAccessSession.ts b/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/usePamWebAccessSession.ts
deleted file mode 100644
index a8c4fbb941..0000000000
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamWebAccess/usePamWebAccessSession.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-import { FitAddon } from "@xterm/addon-fit";
-import { Terminal } from "@xterm/xterm";
-
-import { useCreatePamWebAccessTicket } from "@app/hooks/api/pam";
-
-import { WebSocketServerMessageSchema, WsMessageType } from "./pam-web-access-types";
-
-import "@xterm/xterm/css/xterm.css";
-
-type UsePamWebAccessSessionOptions = {
- accountId: string;
- projectId: string;
- onSessionStart?: () => void;
- onSessionEnd?: () => void;
-};
-
-export const usePamWebAccessSession = ({
- accountId,
- projectId,
- onSessionStart,
- onSessionEnd
-}: UsePamWebAccessSessionOptions) => {
- const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null);
- const [isConnected, setIsConnected] = useState(false);
- const wsRef = useRef<WebSocket | null>(null);
- const createTicket = useCreatePamWebAccessTicket();
-
- const onSessionStartRef = useRef(onSessionStart);
- const onSessionEndRef = useRef(onSessionEnd);
- const createTicketRef = useRef(createTicket);
-
- useEffect(() => {
- onSessionStartRef.current = onSessionStart;
- onSessionEndRef.current = onSessionEnd;
- createTicketRef.current = createTicket;
- }, [onSessionStart, onSessionEnd, createTicket]);
-
- // Main lifecycle effect — fires when containerEl becomes non-null
- useEffect(() => {
- if (!containerEl || !accountId) return undefined;
-
- let disposed = false;
- let focusTimeout: ReturnType<typeof setTimeout> | null = null;
- const inputBuffer = { current: "" };
- const currentPrompt = { current: "" };
-
- // 1. Create terminal
- const terminal = new Terminal({
- cursorBlink: true,
- fontSize: 14,
- fontFamily: '"JetBrains Mono", "Fira Code", Menlo, Monaco, "Courier New", monospace',
- theme: {
- background: "#0d1117",
- foreground: "#c9d1d9",
- cursor: "#58a6ff",
- cursorAccent: "#0d1117",
- selectionBackground: "#264f78",
- black: "#0d1117",
- red: "#ff7b72",
- green: "#3fb950",
- yellow: "#d29922",
- blue: "#58a6ff",
- magenta: "#bc8cff",
- cyan: "#76e3ea",
- white: "#c9d1d9",
- brightBlack: "#484f58",
- brightRed: "#ffa198",
- brightGreen: "#56d364",
- brightYellow: "#e3b341",
- brightBlue: "#79c0ff",
- brightMagenta: "#d2a8ff",
- brightCyan: "#b3f0ff",
- brightWhite: "#f0f6fc"
- },
- scrollback: 10000,
- allowProposedApi: true
- });
-
- const fitAddon = new FitAddon();
- terminal.loadAddon(fitAddon);
- terminal.open(containerEl);
- fitAddon.fit();
-
- // 2. Wire terminal keyboard input
- terminal.onData((data) => {
- // Enter — submit the current input buffer
- if (data === "\r") {
- terminal.write("\r\n");
- if (wsRef.current?.readyState === WebSocket.OPEN) {
- wsRef.current.send(
- JSON.stringify({ type: WsMessageType.Input, data: inputBuffer.current })
- );
- }
- inputBuffer.current = "";
- // Backspace — erase the last character
- } else if (data === "\x7f") {
- if (inputBuffer.current.length > 0) {
- inputBuffer.current = inputBuffer.current.slice(0, -1);
- terminal.write("\b \b");
- }
- // Ctrl+C — cancel the current input
- } else if (data === "\x03") {
- terminal.write("^C\r\n");
- inputBuffer.current = "";
- terminal.write(currentPrompt.current);
- // Printable characters and tab — append to input buffer
- } else if (data >= " " || data === "\t") {
- // Normalize embedded newlines from paste
- const normalized = data.replace(/\r\n|\r/g, "\n");
- inputBuffer.current += normalized;
- terminal.write(normalized.replace(/\n/g, "\r\n"));
- }
- });
-
- // 3. Resize handling
- const handleResize = () => fitAddon.fit();
- const resizeObserver = new ResizeObserver(handleResize);
- resizeObserver.observe(containerEl);
- window.addEventListener("resize", handleResize);
-
- // 4. Create ticket and open WebSocket
- const startSession = async () => {
- try {
- if (disposed) return;
- const ticket = await createTicketRef.current.mutateAsync({ accountId, projectId });
- if (disposed) return;
-
- const { protocol, host } = window.location;
- const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
- const wsUrl = `${wsProtocol}//${host}/api/v1/pam/accounts/${accountId}/web-access?ticket=${encodeURIComponent(ticket)}`;
- const ws = new WebSocket(wsUrl);
- wsRef.current = ws;
-
- ws.onmessage = (event) => {
- if (disposed) return;
- let raw: unknown;
- try {
- raw = JSON.parse(event.data as string);
- } catch {
- return;
- }
- const parsed = WebSocketServerMessageSchema.safeParse(raw);
- if (!parsed.success) return;
- const msg = parsed.data;
-
- if (msg.type === WsMessageType.Ready) {
- setIsConnected(true);
- onSessionStartRef.current?.();
- focusTimeout = setTimeout(() => terminal.focus(), 100);
- }
-
- // Write directly to terminal — no indirection
- if (msg.data) {
- // xterm requires \r\n; bare \n moves the cursor down without returning to column 0
- terminal.write(msg.data.replace(/\r?\n/g, "\r\n"));
- }
- if (msg.prompt) {
- currentPrompt.current = msg.prompt;
- terminal.write(msg.prompt);
- }
- };
-
- ws.onclose = () => {
- if (disposed) return;
- wsRef.current = null;
- setIsConnected(false);
- onSessionEndRef.current?.();
- };
-
- ws.onerror = () => {
- // no-op: onclose always fires after onerror
- };
- } catch {
- if (!disposed) {
- terminal.write("\r\nFailed to connect. Please close and try again.\r\n");
- }
- }
- };
-
- startSession();
-
- // 5. Cleanup
- return () => {
- disposed = true;
- if (focusTimeout) clearTimeout(focusTimeout);
- window.removeEventListener("resize", handleResize);
- resizeObserver.disconnect();
-
- const ws = wsRef.current;
- if (ws) {
- if (ws.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify({ type: WsMessageType.Control, data: "quit" }));
- }
- ws.close();
- wsRef.current = null;
- }
-
- terminal.dispose();
- setIsConnected(false);
- };
- }, [containerEl, accountId, projectId]);
-
- const disconnect = useCallback(() => {
- const ws = wsRef.current;
- wsRef.current = null;
-
- if (ws) {
- if (ws.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify({ type: WsMessageType.Control, data: "quit" }));
- }
- ws.close();
- }
- }, []);
-
- const containerRef = useCallback((node: HTMLDivElement | null) => {
- setContainerEl(node);
- }, []);
-
- return { containerRef, isConnected, disconnect };
-};
diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx
index 4fddc493dc..0f8c1b016a 100644
--- a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx
+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx
@@ -46,7 +46,6 @@ import { PamAddAccountModal } from "../../PamAccountsPage/components/PamAddAccou
import { PamDeleteAccountModal } from "../../PamAccountsPage/components/PamDeleteAccountModal";
import { PamRequestAccountAccessModal } from "../../PamAccountsPage/components/PamRequestAccountAccessModal";
import { PamUpdateAccountModal } from "../../PamAccountsPage/components/PamUpdateAccountModal";
-import { PamWebAccessModal } from "../../PamAccountsPage/components/PamWebAccess";
import { useAccessAwsIamAccount } from "../../PamAccountsPage/components/useAccessAwsIamAccount";
type Props = {
@@ -65,7 +64,6 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"addAccount",
"accessAccount",
- "webAccess",
"requestAccount",
"updateAccount",
"deleteAccount"
@@ -339,16 +337,6 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {
onOpenChange={(isOpen) => handlePopUpToggle("accessAccount", isOpen)}
account={popUp.accessAccount.data?.account}
projectId={projectId!}
- onOpenWebAccess={() => {
- handlePopUpOpen("webAccess", { account: popUp.accessAccount.data?.account });
- }}
- />
-
- <PamWebAccessModal
- isOpen={popUp.webAccess.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("webAccess", isOpen)}
- account={popUp.webAccess.data?.account}
- projectId={projectId!}
/>
<PamRequestAccountAccessModal
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index 58a0ae86f5..74280192c3 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -242,6 +242,7 @@ import { Route as secretManagerIntegrationsAwsSecretManagerConfigurePageRouteImp
import { Route as secretManagerIntegrationsAwsSecretManagerAuthorizePageRouteImport } from './pages/secret-manager/integrations/AwsSecretManagerAuthorizePage/route'
import { Route as secretManagerIntegrationsAwsParameterStoreConfigurePageRouteImport } from './pages/secret-manager/integrations/AwsParameterStoreConfigurePage/route'
import { Route as secretManagerIntegrationsAwsParameterStoreAuthorizePageRouteImport } from './pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/route'
+import { Route as pamPamAccountAccessPageRouteImport } from './pages/pam/PamAccountAccessPage/route'
import { Route as secretManagerIntegrationsVercelOauthCallbackPageRouteImport } from './pages/secret-manager/integrations/VercelOauthCallbackPage/route'
import { Route as secretManagerSecretSyncDetailsByIDPageRouteImport } from './pages/secret-manager/SecretSyncDetailsByIDPage/route'
import { Route as secretManagerIntegrationsNetlifyOauthCallbackPageRouteImport } from './pages/secret-manager/integrations/NetlifyOauthCallbackPage/route'
@@ -255,8 +256,8 @@ import { Route as secretManagerIntegrationsAzureAppConfigurationOauthCallbackPag
import { Route as secretManagerCommitsPageRouteImport } from './pages/secret-manager/CommitsPage/route'
import { Route as pamPamResourceByIDPageRouteImport } from './pages/pam/PamResourceByIDPage/route'
import { Route as secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteImport } from './pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/route'
-import { Route as pamPamAccountByIDPageRouteImport } from './pages/pam/PamAccountByIDPage/route'
import { Route as secretManagerCommitDetailsPageRouteImport } from './pages/secret-manager/CommitDetailsPage/route'
+import { Route as pamPamAccountByIDPageRouteImport } from './pages/pam/PamAccountByIDPage/route'
// Create Virtual Routes
@@ -371,6 +372,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManag
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId',
)()
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdImport =
+ createFileRoute(
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId',
+ )()
// Create/Update Routes
@@ -2296,6 +2301,13 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManag
} as any,
)
+const pamPamAccountAccessPageRouteRoute =
+ pamPamAccountAccessPageRouteImport.update({
+ id: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access',
+ path: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access',
+ getParentRoute: () => middlewaresInjectOrgDetailsRoute,
+ } as any)
+
const secretManagerIntegrationsVercelOauthCallbackPageRouteRoute =
secretManagerIntegrationsVercelOauthCallbackPageRouteImport.update({
id: '/vercel/oauth2/callback',
@@ -2394,6 +2406,16 @@ const pamPamResourceByIDPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdRoute,
} as any)
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRoute =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdImport.update(
+ {
+ id: '/accounts/$accountId',
+ path: '/accounts/$accountId',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdRoute,
+ } as any,
+ )
+
const secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute =
secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteImport.update({
id: '/restore',
@@ -2402,15 +2424,6 @@ const secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRoute,
} as any)
-const pamPamAccountByIDPageRouteRoute = pamPamAccountByIDPageRouteImport.update(
- {
- id: '/accounts/$accountId',
- path: '/accounts/$accountId',
- getParentRoute: () =>
- AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdRoute,
- } as any,
-)
-
const secretManagerCommitDetailsPageRouteRoute =
secretManagerCommitDetailsPageRouteImport.update({
id: '/',
@@ -2419,6 +2432,15 @@ const secretManagerCommitDetailsPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRoute,
} as any)
+const pamPamAccountByIDPageRouteRoute = pamPamAccountByIDPageRouteImport.update(
+ {
+ id: '/',
+ path: '/',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRoute,
+ } as any,
+)
+
// Populate the FileRoutesByPath interface
declare module '@tanstack/react-router' {
@@ -4306,6 +4328,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof secretManagerIntegrationsVercelOauthCallbackPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsImport
}
+ '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': {
+ id: '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'
+ path: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'
+ fullPath: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'
+ preLoaderRoute: typeof pamPamAccountAccessPageRouteImport
+ parentRoute: typeof middlewaresInjectOrgDetailsImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId'
path: '/$commitId'
@@ -4320,13 +4349,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof secretManagerCommitDetailsPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdImport
}
- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId': {
- id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId'
- path: '/accounts/$accountId'
- fullPath: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId'
- preLoaderRoute: typeof pamPamAccountByIDPageRouteImport
- parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdImport
- }
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore': {
id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore'
path: '/restore'
@@ -4334,6 +4356,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId'
+ path: '/accounts/$accountId'
+ fullPath: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId'
+ preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdImport
+ }
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId/': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId/'
+ path: '/'
+ fullPath: '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/'
+ preLoaderRoute: typeof pamPamAccountByIDPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdImport
+ }
}
}
@@ -4599,15 +4635,30 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsKmsProjectI
AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsKmsProjectIdRouteChildren,
)
+interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteChildren {
+ pamPamAccountByIDPageRouteRoute: typeof pamPamAccountByIDPageRouteRoute
+}
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteChildren =
+ {
+ pamPamAccountByIDPageRouteRoute: pamPamAccountByIDPageRouteRoute,
+ }
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteWithChildren =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRoute._addFileChildren(
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteChildren,
+ )
+
interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdRouteChildren {
pamPamResourceByIDPageRouteRoute: typeof pamPamResourceByIDPageRouteRoute
- pamPamAccountByIDPageRouteRoute: typeof pamPamAccountByIDPageRouteRoute
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteWithChildren
}
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdRouteChildren =
{
pamPamResourceByIDPageRouteRoute: pamPamResourceByIDPageRouteRoute,
- pamPamAccountByIDPageRouteRoute: pamPamAccountByIDPageRouteRoute,
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRoute:
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteWithChildren,
}
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdRouteWithChildren =
@@ -5382,6 +5433,7 @@ interface middlewaresInjectOrgDetailsRouteChildren {
AuthenticateInjectOrgDetailsAdminRoute: typeof AuthenticateInjectOrgDetailsAdminRouteWithChildren
redirectsOrganizationRedirectRoute: typeof redirectsOrganizationRedirectRoute
redirectsProjectRedirectRoute: typeof redirectsProjectRedirectRoute
+ pamPamAccountAccessPageRouteRoute: typeof pamPamAccountAccessPageRouteRoute
}
const middlewaresInjectOrgDetailsRouteChildren: middlewaresInjectOrgDetailsRouteChildren =
@@ -5391,6 +5443,7 @@ const middlewaresInjectOrgDetailsRouteChildren: middlewaresInjectOrgDetailsRoute
AuthenticateInjectOrgDetailsAdminRouteWithChildren,
redirectsOrganizationRedirectRoute: redirectsOrganizationRedirectRoute,
redirectsProjectRedirectRoute: redirectsProjectRedirectRoute,
+ pamPamAccountAccessPageRouteRoute: pamPamAccountAccessPageRouteRoute,
}
const middlewaresInjectOrgDetailsRouteWithChildren =
@@ -5781,10 +5834,12 @@ export interface FileRoutesByFullPath {
'/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback': typeof secretManagerIntegrationsNetlifyOauthCallbackPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRouteWithChildren
'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/': typeof secretManagerCommitDetailsPageRouteRoute
- '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId': typeof pamPamAccountByIDPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteWithChildren
+ '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/': typeof pamPamAccountByIDPageRouteRoute
}
export interface FileRoutesByTo {
@@ -6029,9 +6084,10 @@ export interface FileRoutesByTo {
'/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback': typeof secretManagerIntegrationsNetlifyOauthCallbackPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId': typeof secretManagerCommitDetailsPageRouteRoute
- '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId': typeof pamPamAccountByIDPageRouteRoute
'/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute
+ '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId': typeof pamPamAccountByIDPageRouteRoute
}
export interface FileRoutesById {
@@ -6305,10 +6361,12 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/netlify/oauth2/callback': typeof secretManagerIntegrationsNetlifyOauthCallbackPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/secret-syncs/$destination/$syncId': typeof secretManagerSecretSyncDetailsByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/vercel/oauth2/callback': typeof secretManagerIntegrationsVercelOauthCallbackPageRouteRoute
+ '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access': typeof pamPamAccountAccessPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsSecretManagementProjectIdSecretManagerLayoutCommitsEnvironmentFolderIdCommitIdRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/': typeof secretManagerCommitDetailsPageRouteRoute
- '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId': typeof pamPamAccountByIDPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore': typeof secretManagerCommitDetailsPageComponentsRollbackPreviewTabRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdProjectsPamProjectIdPamLayoutResourcesResourceTypeResourceIdAccountsAccountIdRouteWithChildren
+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId/': typeof pamPamAccountByIDPageRouteRoute
}
export interface FileRouteTypes {
@@ -6571,10 +6629,12 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback'
+ | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'
| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId'
| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/'
- | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId'
| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore'
+ | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId'
+ | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/'
fileRoutesByTo: FileRoutesByTo
to:
| '/'
@@ -6818,9 +6878,10 @@ export interface FileRouteTypes {
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/netlify/oauth2/callback'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/secret-syncs/$destination/$syncId'
| '/organizations/$orgId/projects/secret-management/$projectId/integrations/vercel/oauth2/callback'
+ | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'
| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId'
- | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId'
| '/organizations/$orgId/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore'
+ | '/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId'
id:
| '__root__'
| '/'
@@ -7092,10 +7153,12 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/netlify/oauth2/callback'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/secret-syncs/$destination/$syncId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations/vercel/oauth2/callback'
+ | '/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/'
- | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId'
| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId'
+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId/'
fileRoutesById: FileRoutesById
}
@@ -7211,7 +7274,8 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout",
"/_authenticate/_inject-org-details/admin",
"/_authenticate/_inject-org-details/organization/$",
- "/_authenticate/_inject-org-details/projects/$"
+ "/_authenticate/_inject-org-details/projects/$",
+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access"
]
},
"/_authenticate/personal-settings": {
@@ -8555,6 +8619,10 @@ export const routeTree = rootRoute
"filePath": "secret-manager/integrations/VercelOauthCallbackPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/integrations"
},
+ "/_authenticate/_inject-org-details/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access": {
+ "filePath": "pam/PamAccountAccessPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details"
+ },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId": {
"filePath": "",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId",
@@ -8567,13 +8635,20 @@ export const routeTree = rootRoute
"filePath": "secret-manager/CommitDetailsPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId"
},
- "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId": {
- "filePath": "pam/PamAccountByIDPage/route.tsx",
- "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId"
- },
"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId/restore": {
"filePath": "secret-manager/CommitDetailsPage/components/RollbackPreviewTab/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/secret-management/$projectId/_secret-manager-layout/commits/$environment/$folderId/$commitId"
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId": {
+ "filePath": "",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId",
+ "children": [
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId/"
+ ]
+ },
+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId/": {
+ "filePath": "pam/PamAccountByIDPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/pam/$projectId/_pam-layout/resources/$resourceType/$resourceId/accounts/$accountId"
}
}
}
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index f93fdc8cb9..fb13effe73 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -379,7 +379,7 @@ const pamRoutes = route("/organizations/$orgId/projects/pam/$projectId", [
index("pam/PamResourcesPage/route.tsx"),
route("/$resourceType/$resourceId", [
index("pam/PamResourceByIDPage/route.tsx"),
- route("/accounts/$accountId", "pam/PamAccountByIDPage/route.tsx")
+ route("/accounts/$accountId", [index("pam/PamAccountByIDPage/route.tsx")])
])
]),
route("/audit-logs", "project/AuditLogsPage/route-pam.tsx"),
@@ -396,6 +396,11 @@ const pamRoutes = route("/organizations/$orgId/projects/pam/$projectId", [
])
]);
+const pamAccessRoute = route(
+ "/organizations/$orgId/projects/pam/$projectId/resources/$resourceType/$resourceId/accounts/$accountId/access",
+ "pam/PamAccountAccessPage/route.tsx"
+);
+
const organizationRoutes = route("/organizations/$orgId", [
route("/projects", "organization/ProjectsPage/route.tsx"),
route("/access-management", "organization/AccessManagementPage/route.tsx"),
@@ -464,6 +469,7 @@ export const routes = rootRoute("root.tsx", [
route("/organization/$", "redirects/organization-redirect.tsx"),
route("/projects/$", "redirects/project-redirect.tsx"),
adminRoute,
+ pamAccessRoute,
layout("org-layout", "organization/layout.tsx", [
organizationRoutes,
route("/organizations/$orgId/secret-manager/$projectId", [