Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
checkpoint
Daniel Hougaard329adeb7aa26
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex d27fbd1c5c..1ded2d6864 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -249,7 +249,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {await server.register(async (secretSharingRouter) => {- await secretSharingRouter.register(registerSecretSharingRouter, { prefix: "/shared" });+ await secretSharingRouter.register(registerSecretSharingRouter);await secretSharingRouter.register(registerSecretRequestsRouter, { prefix: "/requests" });},{ prefix: "/secret-sharing" }diff --git a/backend/src/server/routes/v1/secret-sharing-router.ts b/backend/src/server/routes/v1/secret-sharing-router.tsindex 043a048db3..e527f07d8f 100644--- a/backend/src/server/routes/v1/secret-sharing-router.ts+++ b/backend/src/server/routes/v1/secret-sharing-router.ts@@ -1,7 +1,6 @@import fastifyMultipart from "@fastify/multipart";import { z } from "zod";-import { SecretSharingSchema } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { SecretSharingAccessType } from "@app/lib/types";@@ -43,8 +42,9 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>rateLimit: readLimit},schema: {- operationId: "listSharedSecrets",hide: false,+ description: "List all shared secrets created by the authenticated user in their current organization.",+ operationId: "listSharedSecrets",querystring: z.object({offset: z.coerce.number().min(0).max(100).default(0),limit: z.coerce.number().min(1).max(100).default(25)@@ -56,7 +56,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>})}},- onRequest: verifyAuth([AuthMode.JWT]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {const { secrets, totalCount } = await req.server.services.secretSharing.getSharedSecrets({actor: req.permission.type,@@ -74,87 +74,89 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>}});+ server.route({+ method: "GET",+ url: "/:id",+ config: {+ rateLimit: publicEndpointLimit+ },+ schema: {+ hide: false,+ description:+ "Get a shared secret by its ID. Returns the full secret metadata without revealing the secret value. For organization-restricted secrets, authentication is required.",+ operationId: "getSharedSecretById",+ params: z.object({+ id: z.string().describe("The ID of the shared secret")+ }),+ response: {+ 200: SanitizedSecretSharingSchema.extend({+ isPasswordProtected: z.boolean()+ })+ }+ },+ handler: async (req) => {+ return req.server.services.secretSharing.getSharedSecretById(+ req.params.id,+ req.permission?.orgId,+ req.permission?.id+ );+ }+ });+server.route({method: "POST",- url: "/public/:sharedSecretId",+ url: "/:id/access",config: {rateLimit: publicEndpointLimit},+schema: {+ hide: false,description:- "Retrieve the secret value of a shared secret by it's ID. If the secret is password protected, you must provide the password in the request body.",- operationId: "getPublicSharedSecret",+ "Access a shared secret by its ID. If the secret is password protected, you must provide the password in the request body. Returns the secret value if access is granted, or indicates that a password is required.",+ operationId: "accessSharedSecret",params: z.object({- sharedSecretId: z.string()+ id: z.string().describe("The ID of the shared secret to access")}),body: z.object({- password: z.string().optional()+ password: z+ .string()+ .optional()+ .describe(+ "The password for accessing a password-protected shared secret. This field is only required if the secret is password protected."+ )}),response: {- 200: z.object({- isPasswordProtected: z.boolean(),- brandingConfig: z- .object({- hasLogo: z.boolean(),- hasFavicon: z.boolean(),- primaryColor: z.string().optional(),- secondaryColor: z.string().optional()- })- .optional(),- secret: SecretSharingSchema.pick({- expiresAt: true,- expiresAfterViews: true,- accessType: true- })- .extend({- orgName: z.string().optional(),- secretValue: z.string().optional()- })- .optional(),- error: z.string().optional()+ 200: SanitizedSecretSharingSchema.extend({+ orgName: z.string().optional(),+ secretValue: z.string().optional()})}},handler: async (req) => {- const sharedSecret = await req.server.services.secretSharing.getSharedSecretById({- sharedSecretId: req.params.sharedSecretId,+ const sharedSecret = await req.server.services.secretSharing.accessSharedSecret({+ sharedSecretId: req.params.id,password: req.body.password,orgId: req.permission?.orgId,actorId: req.permission?.id});- let brandingConfig;-if (sharedSecret.orgId) {- const orgBrandConfig = await req.server.services.secretSharing.getOrgBrandConfig(sharedSecret.orgId);-- if (orgBrandConfig) {- brandingConfig = {- hasLogo: orgBrandConfig.hasLogo,- hasFavicon: orgBrandConfig.hasFavicon,- primaryColor: orgBrandConfig.primaryColor,- secondaryColor: orgBrandConfig.secondaryColor- };- }-- // Verify that secret was actually returned- if (sharedSecret.secret) {- await server.services.auditLog.createAuditLog({- orgId: sharedSecret.orgId,- ...req.auditLogInfo,- event: {- type: EventType.READ_SHARED_SECRET,- metadata: {- id: req.params.sharedSecretId,- name: sharedSecret.secret.name || undefined,- accessType: sharedSecret.secret.accessType- }+ await server.services.auditLog.createAuditLog({+ orgId: sharedSecret.orgId,+ ...req.auditLogInfo,+ event: {+ type: EventType.READ_SHARED_SECRET,+ metadata: {+ id: req.params.id,+ name: sharedSecret.name || undefined,+ accessType: sharedSecret.accessType}- });- }+ }+ });}- return { ...sharedSecret, brandingConfig };+ return sharedSecret;}});@@ -165,6 +167,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>rateLimit: writeLimit},schema: {+ hide: true,operationId: "createPublicSharedSecret",body: z.object({secretValue: z.string().max(10_000),@@ -194,6 +197,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>rateLimit: publicSecretShareCreationLimit},schema: {+ hide: false,+ description: "Create a new shared secret that can be accessed by a link.",operationId: "createSharedSecret",body: z.object({name: z.string().max(50).optional(),@@ -249,14 +254,16 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>server.route({method: "DELETE",- url: "/:sharedSecretId",+ url: "/:id",config: {rateLimit: writeLimit},schema: {+ hide: false,+ description: "Delete a shared secret by its ID.",operationId: "deleteSharedSecret",params: z.object({- sharedSecretId: z.string()+ id: z.string().describe("The ID of the shared secret to delete")}),response: {200: SanitizedSecretSharingSchema@@ -264,14 +271,14 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const { sharedSecretId } = req.params;+ const { id } = req.params;const deletedSharedSecret = await req.server.services.secretSharing.deleteSharedSecretById({actor: req.permission.type,actorId: req.permission.id,orgId: req.permission.orgId,actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId,- sharedSecretId,+ sharedSecretId: id,type: SecretSharingType.Share});@@ -281,7 +288,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>event: {type: EventType.DELETE_SHARED_SECRET,metadata: {- id: sharedSecretId,+ id,name: deletedSharedSecret.name || undefined}}@@ -406,14 +413,19 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>}});- // Get branding config for current org+ // Get branding config.+ // When authenticated (no query param): returns branding config for the user's current org.+ // When public (with sharedSecretId query param): resolves the org from the shared secret.server.route({method: "GET",url: "/branding",config: {- rateLimit: readLimit+ rateLimit: publicEndpointLimit},schema: {+ querystring: z.object({+ sharedSecretId: z.string().optional()+ }),response: {200: z.object({hasLogo: z.boolean(),@@ -423,9 +435,25 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>})}},- onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const config = await req.server.services.secretSharing.getOrgBrandConfig(req.permission.orgId, req.permission);+ let orgId: string | null = null;++ if (req.query.sharedSecretId) {+ orgId = await req.server.services.secretSharing.getSharedSecretOrgId(req.query.sharedSecretId);++ if (!orgId) {+ throw new NotFoundError({ message: "Shared secret not found or has no organization" });+ }+ } else if (req.permission?.orgId) {+ orgId = req.permission.orgId;+ } else {+ throw new BadRequestError({ message: "Either authentication or a sharedSecretId query parameter is required" });+ }++ const config = await req.server.services.secretSharing.getOrgBrandConfig(+ orgId,+ req.query.sharedSecretId ? undefined : req.permission+ );return {hasLogo: config?.hasLogo ?? false,diff --git a/backend/src/services/secret-sharing/secret-sharing-service.ts b/backend/src/services/secret-sharing/secret-sharing-service.tsindex 0d024ff656..07877ceb8f 100644--- a/backend/src/services/secret-sharing/secret-sharing-service.ts+++ b/backend/src/services/secret-sharing/secret-sharing-service.ts@@ -1,6 +1,6 @@import { ForbiddenError } from "@casl/ability";-import { OrganizationActionScope, TSecretSharing } from "@app/db/schemas";+import { OrganizationActionScope, TOrganizations, TSecretSharing } from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { OrgPermissionSecretShareAction, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";@@ -510,6 +510,62 @@ export const secretSharingServiceFactory = ({};};+ const getSharedSecretById = async (sharedSecretId: string, orgId?: string, actorId?: string) => {+ const sharedSecret = await secretSharingDAL.findOne({+ type: SecretSharingType.Share,+ identifier: Buffer.from(sharedSecretId, "base64url").toString("hex")+ });++ if (!sharedSecret) {+ throw new NotFoundError({ message: `Shared secret with ID '${sharedSecretId}' not found` });+ }++ const { expiresAt, expiresAfterViews, accessType } = sharedSecret;++ // Auth check for org-restricted secrets+ if (accessType === SecretSharingAccessType.Organization) {+ if (!orgId) {+ throw new UnauthorizedError({ message: "Authentication required to view this secret" });+ }+ if (sharedSecret.orgId && sharedSecret.orgId !== orgId) {+ throw new ForbiddenRequestError({ message: "You do not have access to this secret" });+ }+ }++ // Check if secret is expired+ if (expiresAt !== null && expiresAt < new Date()) {+ await secretSharingDAL.softDeleteById(sharedSecret.id);+ throw new NotFoundError({ message: "The shared secret has expired" });+ }++ // Check if view limit reached+ if (expiresAfterViews !== null && expiresAfterViews === 0) {+ await secretSharingDAL.softDeleteById(sharedSecret.id);+ throw new NotFoundError({ message: "The shared secret has reached its view limit" });+ }++ // Check authorized emails if set+ if (sharedSecret.authorizedEmails && (sharedSecret.authorizedEmails as string[]).length > 0) {+ if (!actorId) {+ throw new UnauthorizedError({ message: "Authentication required to view this secret" });+ }++ const user = await userDAL.findById(actorId);+ if (!user || !user.email) {+ throw new UnauthorizedError({ message: "Authentication required to view this secret" });+ }++ if (!(sharedSecret.authorizedEmails as string[]).includes(user.email)) {+ throw new ForbiddenRequestError({ message: "You are not authorized to view this secret" });+ }+ }++ return {+ ...mapIdentifierToId(sharedSecret),+ isPasswordProtected: Boolean(sharedSecret.password)+ };+ };+const $decrementSecretViewCount = async (sharedSecret: TSecretSharing) => {const { expiresAfterViews } = sharedSecret;@@ -524,7 +580,7 @@ export const secretSharingServiceFactory = ({};/** Gets password-less secret. validates all secret's requested (must be fresh). */- const getSharedSecretById = async ({ sharedSecretId, orgId, actorId, password }: TGetActiveSharedSecretByIdDTO) => {+ const accessSharedSecret = async ({ sharedSecretId, orgId, actorId, password }: TGetActiveSharedSecretByIdDTO) => {const sharedSecret = await secretSharingDAL.findOne({type: SecretSharingType.Share,identifier: Buffer.from(sharedSecretId, "base64url").toString("hex")@@ -538,8 +594,6 @@ export const secretSharingServiceFactory = ({const { accessType, expiresAt, expiresAfterViews } = sharedSecret;- const orgName = sharedSecret.orgId ? (await orgDAL.findOrgById(sharedSecret.orgId))?.name : "";-if (accessType === SecretSharingAccessType.Organization && orgId === undefined) {throw new UnauthorizedError();}@@ -556,11 +610,7 @@ export const secretSharingServiceFactory = ({if (!user || !user.email) throw new UnauthorizedError();if (!(sharedSecret.authorizedEmails as string[]).includes(user.email))- return {- isPasswordProtected: false,- error: "You are not authorized to view this secret",- orgId: sharedSecret.orgId- };+ throw new ForbiddenRequestError({ message: "You are not authorized to view this secret" });}// all secrets pass through here, meaning we check if its expired first and then check if it needs verification@@ -568,21 +618,13 @@ export const secretSharingServiceFactory = ({if (expiresAt !== null && expiresAt < new Date()) {// check lifetime expiryawait secretSharingDAL.softDeleteById(sharedSecret.id);- return {- isPasswordProtected: false,- orgId: sharedSecret.orgId,- error: "Unable to view secret: secret has expired"- };+ throw new NotFoundError({ message: "The shared secret has expired" });}if (expiresAfterViews !== null && expiresAfterViews === 0) {// check view count expiryawait secretSharingDAL.softDeleteById(sharedSecret.id);- return {- isPasswordProtected: false,- orgId: sharedSecret.orgId,- error: "Unable to view secret: view limit reached"- };+ throw new NotFoundError({ message: "The shared secret has reached its view limit" });}// Password checks@@ -591,36 +633,38 @@ export const secretSharingServiceFactory = ({if (isPasswordProtected) {if (hasProvidedPassword) {const isMatch = await crypto.hashing().compareHash(password as string, sharedSecret.password as string);- if (!isMatch) throw new UnauthorizedError({ message: "Invalid credentials" });+ if (!isMatch) {+ throw new UnauthorizedError({ message: "Invalid credentials" });+ }} else {- return { isPasswordProtected, orgId: sharedSecret.orgId };+ throw new UnauthorizedError({ message: "Password is required to access this secret" });}}const decryptWithRoot = kmsService.decryptWithRootKey();- // If encryptedSecret is set, we know that this secret has been encrypted using KMS, and we can therefore do server-side decryption.- let decryptedSecretValue: Buffer | undefined;- if (sharedSecret.encryptedSecret) {- decryptedSecretValue = decryptWithRoot(sharedSecret.encryptedSecret);+ if (!sharedSecret.encryptedSecret) {+ throw new BadRequestError({ message: "Secret has no value specified" });+ }+ const decryptedSecretValue = decryptWithRoot(sharedSecret.encryptedSecret);++ let organization: TOrganizations | undefined;++ if (+ sharedSecret.orgId &&+ sharedSecret.orgId === orgId &&+ sharedSecret.accessType === SecretSharingAccessType.Organization+ ) {+ organization = await orgDAL.findOrgById(sharedSecret.orgId);}// decrement when we are sure the user will view secret.await $decrementSecretViewCount(sharedSecret);return {- isPasswordProtected,- orgId: sharedSecret.orgId,- secret: {- ...mapIdentifierToId(sharedSecret),- ...(decryptedSecretValue && {- secretValue: decryptedSecretValue.toString()- }),- orgName:- sharedSecret.accessType === SecretSharingAccessType.Organization && orgId === sharedSecret.orgId- ? orgName- : undefined- }+ ...mapIdentifierToId(sharedSecret),+ secretValue: decryptedSecretValue.toString(),+ orgName: organization?.name};};@@ -785,12 +829,12 @@ export const secretSharingServiceFactory = ({getSharedSecrets,deleteSharedSecretById,getSharedSecretById,+ accessSharedSecret,getSharedSecretOrgId,getOrgBrandConfig,getBrandingAsset,uploadBrandingAsset,deleteBrandingAsset,-createSecretRequest,getSecretRequestById,getSecretRequestOrgId,diff --git a/docs/api-reference/endpoints/secret-sharing/shared-secrets/access.mdx b/docs/api-reference/endpoints/secret-sharing/shared-secrets/access.mdxnew file mode 100644index 0000000000..a4a211a28f--- /dev/null+++ b/docs/api-reference/endpoints/secret-sharing/shared-secrets/access.mdx@@ -0,0 +1,4 @@+---+title: "Access"+openapi: "POST /api/v1/secret-sharing/{id}/access"+---\ No newline at end of filediff --git a/docs/api-reference/endpoints/secret-sharing/shared-secrets/create.mdx b/docs/api-reference/endpoints/secret-sharing/shared-secrets/create.mdxnew file mode 100644index 0000000000..ddfb97bd8b--- /dev/null+++ b/docs/api-reference/endpoints/secret-sharing/shared-secrets/create.mdx@@ -0,0 +1,4 @@+---+title: "Create"+openapi: "POST /api/v1/secret-sharing"+---\ No newline at end of filediff --git a/docs/api-reference/endpoints/secret-sharing/shared-secrets/delete.mdx b/docs/api-reference/endpoints/secret-sharing/shared-secrets/delete.mdxnew file mode 100644index 0000000000..71b6a8cfa1--- /dev/null+++ b/docs/api-reference/endpoints/secret-sharing/shared-secrets/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete by ID"+openapi: "DELETE /api/v1/secret-sharing/{id}"+---\ No newline at end of filediff --git a/docs/api-reference/endpoints/secret-sharing/shared-secrets/get-by-id.mdx b/docs/api-reference/endpoints/secret-sharing/shared-secrets/get-by-id.mdxnew file mode 100644index 0000000000..87b821b82c--- /dev/null+++ b/docs/api-reference/endpoints/secret-sharing/shared-secrets/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get by ID"+openapi: "GET /api/v1/secret-sharing/{id}"+---\ No newline at end of filediff --git a/docs/api-reference/endpoints/secret-sharing/shared-secrets/list.mdx b/docs/api-reference/endpoints/secret-sharing/shared-secrets/list.mdxnew file mode 100644index 0000000000..9067c47d25--- /dev/null+++ b/docs/api-reference/endpoints/secret-sharing/shared-secrets/list.mdx@@ -0,0 +1,4 @@+---+title: "List"+openapi: "GET /api/v1/secret-sharing"+---\ No newline at end of filediff --git a/docs/docs.json b/docs/docs.jsonindex b2c3352ab6..f3ec65b21a 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -2948,6 +2948,21 @@}]},+ {+ "group": "Secret Sharing",+ "pages": [+ {+ "group": "Shared Secrets",+ "pages": [+ "api-reference/endpoints/secret-sharing/shared-secrets/list",+ "api-reference/endpoints/secret-sharing/shared-secrets/get-by-id",+ "api-reference/endpoints/secret-sharing/shared-secrets/create",+ "api-reference/endpoints/secret-sharing/shared-secrets/delete",+ "api-reference/endpoints/secret-sharing/shared-secrets/access"+ ]+ }+ ]+ },{"group": "Infisical KMS","pages": [@@ -3032,7 +3047,7 @@"href": "https://infisical.com"},"api": {- "openapi": "https://app.infisical.com/api/docs/json",+ "openapi": "https://abbigail-rotund-harmonically.ngrok-free.dev/api/docs/json","mdx": {"server": ["https://app.infisical.com"]}diff --git a/frontend/src/hooks/api/secretSharing/mutations.ts b/frontend/src/hooks/api/secretSharing/mutations.tsindex 75ca8e8a10..58792cb303 100644--- a/frontend/src/hooks/api/secretSharing/mutations.ts+++ b/frontend/src/hooks/api/secretSharing/mutations.ts@@ -4,6 +4,7 @@ import { apiRequest } from "@app/config/request";import { secretSharingKeys } from "./queries";import {+ TAccessSharedSecretRequest,TCreatedSharedSecret,TCreateSecretRequestRequestDTO,TCreateSharedSecretRequest,@@ -12,7 +13,8 @@ import {TRevealedSecretRequest,TRevealSecretRequestValueRequest,TSetSecretRequestValueRequest,- TSharedSecret+ TSharedSecret,+ TViewSharedSecretResponse} from "./types";export const useCreateSharedSecret = () => {@@ -20,7 +22,7 @@ export const useCreateSharedSecret = () => {return useMutation({mutationFn: async (inputData: TCreateSharedSecretRequest) => {const { data } = await apiRequest.post<TCreatedSharedSecret>(- "/api/v1/secret-sharing/shared",+ "/api/v1/secret-sharing",inputData);return data;@@ -30,12 +32,27 @@ export const useCreateSharedSecret = () => {});};+export const useAccessSharedSecret = () => {+ return useMutation({+ mutationFn: async ({ sharedSecretId, password, hashedHex }: TAccessSharedSecretRequest) => {+ const { data } = await apiRequest.post<TViewSharedSecretResponse>(+ `/api/v1/secret-sharing/${sharedSecretId}/access`,+ {+ ...(hashedHex && { hashedHex }),+ ...(password && { password })+ }+ );+ return data;+ }+ });+};+export const useCreatePublicSharedSecret = () => {const queryClient = useQueryClient();return useMutation({mutationFn: async (inputData: TCreateSharedSecretRequest) => {const { data } = await apiRequest.post<TCreatedSharedSecret>(- "/api/v1/secret-sharing/shared/public",+ "/api/v1/secret-sharing/public",inputData);return data;@@ -88,7 +105,7 @@ export const useDeleteSharedSecret = () => {return useMutation<TSharedSecret, { message: string }, { sharedSecretId: string }>({mutationFn: async ({ sharedSecretId }: TDeleteSharedSecretRequestDTO) => {const { data } = await apiRequest.delete<TSharedSecret>(- `/api/v1/secret-sharing/shared/${sharedSecretId}`+ `/api/v1/secret-sharing/${sharedSecretId}`);return data;},@@ -124,7 +141,7 @@ export const useUploadBrandingAsset = () => {const formData = new FormData();formData.append("file", file);const { data } = await apiRequest.post<{ message: string }>(- `/api/v1/secret-sharing/shared/branding/${assetType}`,+ `/api/v1/secret-sharing/branding/${assetType}`,formData,{headers: {@@ -149,7 +166,7 @@ export const useDeleteBrandingAsset = () => {>({mutationFn: async ({ assetType }) => {const { data } = await apiRequest.delete<{ message: string }>(- `/api/v1/secret-sharing/shared/branding/${assetType}`+ `/api/v1/secret-sharing/branding/${assetType}`);return data;},diff --git a/frontend/src/hooks/api/secretSharing/queries.ts b/frontend/src/hooks/api/secretSharing/queries.tsindex 7c8d91de85..bbe96da9a0 100644--- a/frontend/src/hooks/api/secretSharing/queries.ts+++ b/frontend/src/hooks/api/secretSharing/queries.ts@@ -6,7 +6,7 @@ import {TBrandingConfig,TGetSecretRequestByIdResponse,TSharedSecret,- TViewSharedSecretResponse+ TSharedSecretPublicDetails} from "./types";export const secretSharingKeys = {@@ -16,12 +16,10 @@ export const secretSharingKeys = {allSecretRequests: () => ["secretRequests"] as const,specificSecretRequests: ({ offset, limit }: { offset: number; limit: number }) =>[...secretSharingKeys.allSecretRequests(), { offset, limit }] as const,- getSecretById: (arg: { id: string; hashedHex: string | null; password?: string }) => [- "shared-secret",- arg- ],+ getSharedSecretDetails: (id: string) => ["shared-secret", id] as const,getSecretRequestById: (arg: { id: string }) => ["secret-request", arg] as const,- brandingAssets: () => ["brandingAssets"] as const+ brandingAssets: () => ["brandingAssets"] as const,+ sharedSecretBranding: (id: string) => ["shared-secret-branding", id] as const};export const useGetSharedSecrets = ({@@ -40,7 +38,7 @@ export const useGetSharedSecrets = ({});const { data } = await apiRequest.get<{ secrets: TSharedSecret[]; totalCount: number }>(- "/api/v1/secret-sharing/shared",+ "/api/v1/secret-sharing",{params}@@ -73,30 +71,13 @@ export const useGetSecretRequests = ({}});};-export const useGetActiveSharedSecretById = ({- sharedSecretId,- hashedHex,- password-}: {- sharedSecretId: string;- hashedHex: string | null;- password?: string;-}) => {+export const useGetSharedSecretById = ({ sharedSecretId }: { sharedSecretId: string }) => {return useQuery({- queryKey: secretSharingKeys.getSecretById({- id: sharedSecretId,- hashedHex,- password- }),+ queryKey: secretSharingKeys.getSharedSecretDetails(sharedSecretId),queryFn: async () => {- const { data } = await apiRequest.post<TViewSharedSecretResponse>(- `/api/v1/secret-sharing/shared/public/${sharedSecretId}`,- {- ...(hashedHex && { hashedHex }),- password- }+ const { data } = await apiRequest.get<TSharedSecretPublicDetails>(+ `/api/v1/secret-sharing/${sharedSecretId}`);-return data;},enabled: Boolean(sharedSecretId)@@ -120,10 +101,21 @@ export const useGetBrandingConfig = () => {return useQuery({queryKey: secretSharingKeys.brandingAssets(),queryFn: async () => {- const { data } = await apiRequest.get<TBrandingConfig>(- "/api/v1/secret-sharing/shared/branding"- );+ const { data } = await apiRequest.get<TBrandingConfig>("/api/v1/secret-sharing/branding");return data;}});};++export const useGetSharedSecretBranding = ({ sharedSecretId }: { sharedSecretId: string }) => {+ return useQuery({+ queryKey: secretSharingKeys.sharedSecretBranding(sharedSecretId),+ queryFn: async () => {+ const { data } = await apiRequest.get<TBrandingConfig>("/api/v1/secret-sharing/branding", {+ params: { sharedSecretId }+ });+ return data;+ },+ enabled: Boolean(sharedSecretId)+ });+};diff --git a/frontend/src/hooks/api/secretSharing/types.ts b/frontend/src/hooks/api/secretSharing/types.tsindex dab6e6b0c1..c239d474a9 100644--- a/frontend/src/hooks/api/secretSharing/types.ts+++ b/frontend/src/hooks/api/secretSharing/types.ts@@ -68,11 +68,34 @@ export type TBrandingConfig = {secondaryColor?: string;};+// Sanitized shared secret - omits sensitive fields like password, encryptedSecret, etc.+export type TSanitizedSharedSecret = {+ id: string;+ userId: string | null;+ orgId: string | null;+ createdAt: string;+ updatedAt: string;+ name: string | null;+ lastViewedAt: string | null;+ accessType: SecretSharingAccessType;+ expiresAt: string;+ expiresAfterViews: number | null;+ authorizedEmails: string[] | null;+};++export type TSharedSecretPublicDetails = TSanitizedSharedSecret & {+ isPasswordProtected: boolean;+};+export type TViewSharedSecretResponse = {isPasswordProtected: boolean;- brandingConfig?: TBrandingConfig;secret?: TSharedSecretResponse;- error?: string;+};++export type TAccessSharedSecretRequest = {+ sharedSecretId: string;+ password?: string;+ hashedHex?: string | null;};export type TGetSecretRequestByIdResponse = {diff --git a/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingBrandingSection.tsx b/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingBrandingSection.tsxindex ad09ddec2a..3b7f3fdc0d 100644--- a/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingBrandingSection.tsx+++ b/frontend/src/pages/organization/SecretSharingPage/components/SecretSharingSettings/SecretSharingBrandingSection.tsx@@ -64,7 +64,7 @@ const fetchAssetAsDataUrl = async (assetType: "brand-logo" | "brand-favicon"): Promise<string | null> => {try {- const response = await apiRequest.get(`/api/v1/secret-sharing/shared/branding/${assetType}`, {+ const response = await apiRequest.get(`/api/v1/secret-sharing/branding/${assetType}`, {responseType: "blob"});const blob = response.data as Blob;diff --git a/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx b/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsxindex 6d37e720b4..784d2cae2a 100644--- a/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx+++ b/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef } from "react";import { Helmet } from "react-helmet";import { faArrowRight } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -11,7 +11,11 @@ import { createNotification } from "@app/components/notifications";import { Lottie } from "@app/components/v2";import { SessionStorageKeys } from "@app/const";import { ROUTE_PATHS } from "@app/const/routes";-import { TBrandingConfig, useGetActiveSharedSecretById } from "@app/hooks/api/secretSharing";+import {+ useAccessSharedSecret,+ useGetSharedSecretBranding,+ useGetSharedSecretById+} from "@app/hooks/api/secretSharing";import {PasswordContainer,SecretContainer,@@ -77,46 +81,47 @@ export const ViewSharedSecretByIDPage = () => {from: ROUTE_PATHS.Public.ViewSharedSecretByIDPage.id,select: (el) => el.key});- const [password, setPassword] = useState<string>();const { hashedHex, key } = extractDetailsFromUrl(urlEncodedKey);- // Store branding config for persistence across password attempts- const [savedBrandingConfig, setSavedBrandingConfig] = useState<TBrandingConfig | undefined>();-- const {- data: fetchSecret,- error,- isPending,- isFetching- } = useGetActiveSharedSecretById({- sharedSecretId: id,- hashedHex,- password- });-const navigate = useNavigate();+ const hasTriggeredAccess = useRef(false);- const isUnauthorized =- ((error as AxiosError)?.response?.data as { statusCode: number })?.statusCode === 401;+ // Step 1: Fetch public metadata (is it password protected? what access type?)+ const {+ data: secretDetails,+ isLoading: isLoadingDetails,+ error: detailsError+ } = useGetSharedSecretById({ sharedSecretId: id });- const isInvalidCredential =- ((error as AxiosError)?.response?.data as { message: string })?.message ===- "Invalid credentials";+ // Step 2: Access the secret value (mutation — triggered automatically or after password entry)+ const accessMutation = useAccessSharedSecret();- const isEmailUnauthorized =- ((error as AxiosError)?.response?.data as { message: string })?.message ===- "You are not authorized to view this secret";+ // Fetch branding config+ const { data: brandingConfig, isLoading: isLoadingBrandingConfig } = useGetSharedSecretBranding({+ sharedSecretId: id+ });- // Save branding config for persistence across password attempts+ // Auto-access when the secret is not password protecteduseEffect(() => {- if (fetchSecret?.brandingConfig) {- setSavedBrandingConfig(fetchSecret.brandingConfig);+ if (secretDetails && !secretDetails.isPasswordProtected && !hasTriggeredAccess.current) {+ hasTriggeredAccess.current = true;+ accessMutation.mutate({ sharedSecretId: id, hashedHex });}- }, [fetchSecret?.brandingConfig]);+ }, [secretDetails]);++ // Derive error state from whichever step failed+ const activeError = (detailsError ?? accessMutation.error) as AxiosError | null;+ const errorStatusCode = (activeError?.response?.data as { statusCode: number })?.statusCode;+ const errorMessage = (activeError?.response?.data as { message: string })?.message;+ const isUnauthorized = errorStatusCode === 401;+ const isInvalidCredential = errorMessage === "Invalid credentials";+ const isForbidden = errorStatusCode === 403;+ const isNotFound = errorStatusCode === 404;++ // Redirect to login for org-restricted secrets when not authenticateduseEffect(() => {- if (isUnauthorized && !isInvalidCredential && !isEmailUnauthorized) {- // persist current URL in session storage so that we can come back to this after successful login+ if (isUnauthorized && !isInvalidCredential) {sessionStorage.setItem(SessionStorageKeys.ORG_LOGIN_SUCCESS_REDIRECT_URL,JSON.stringify({@@ -130,34 +135,28 @@ export const ViewSharedSecretByIDPage = () => {text: "Login is required in order to access the shared secret."});- navigate({- to: "/login"- });-+ navigate({ to: "/login" });return;}- if (error) {- createNotification({- type: "error",- text: ((error as AxiosError)?.response?.data as { message: string })?.message- });+ if (activeError && !isInvalidCredential && !isForbidden && !isNotFound) {+ createNotification({ type: "error", text: errorMessage });}- }, [error]);+ }, [activeError]);- const shouldShowPasswordPrompt =- isInvalidCredential || (fetchSecret?.isPasswordProtected && !fetchSecret.secret);- const isValidatingPassword = Boolean(password) && isFetching;+ // UI state+ const secret = accessMutation.data?.secret;+ const isPasswordProtected = secretDetails?.isPasswordProtected ?? false;+ const showPasswordPrompt = isPasswordProtected && !secret;+ const isLoading = isLoadingDetails || (!isPasswordProtected && accessMutation.isPending);- const brandingConfig = fetchSecret?.brandingConfig || savedBrandingConfig;const hasCustomBranding = !!brandingConfig;- // Use proxy URLs for branding assets to avoid cross origin issuesconst logoUrl = brandingConfig?.hasLogo- ? `/api/v1/secret-sharing/shared/public/${id}/branding/brand-logo`+ ? `/api/v1/secret-sharing/public/${id}/branding/brand-logo`: DEFAULT_LOGO_URL;const faviconUrl = brandingConfig?.hasFavicon- ? `/api/v1/secret-sharing/shared/public/${id}/branding/brand-favicon`+ ? `/api/v1/secret-sharing/public/${id}/branding/brand-favicon`: DEFAULT_FAVICON_URL;const brandingTheme = useMemo((): BrandingTheme | undefined => {@@ -219,7 +218,7 @@ export const ViewSharedSecretByIDPage = () => {};}, [faviconUrl]);- if (isPending) {+ if (isLoading || isLoadingBrandingConfig) {return (<div className="flex h-screen w-screen items-center justify-center bg-bunker-800"><Lottie isAutoPlay icon="infisical_loading" className="h-32 w-32" />@@ -290,29 +289,21 @@ export const ViewSharedSecretByIDPage = () => {</p>)}</div>- {(shouldShowPasswordPrompt || isValidatingPassword) && (+ {(showPasswordPrompt || isInvalidCredential) && (<PasswordContainer- isSubmitting={isValidatingPassword}- onPasswordSubmit={(el) => {- setPassword(el);+ isSubmitting={accessMutation.isPending}+ onPasswordSubmit={(pwd) => {+ accessMutation.mutate({ sharedSecretId: id, password: pwd, hashedHex });}}- isInvalidCredential={!isFetching && isInvalidCredential}+ isInvalidCredential={!accessMutation.isPending && isInvalidCredential}brandingTheme={brandingTheme}/>)}- {!isPending && (- <>- {!error && !fetchSecret?.error && fetchSecret?.secret && (- <SecretContainer- secret={fetchSecret.secret}- secretKey={key}- brandingTheme={brandingTheme}- />- )}- {(fetchSecret?.error || (error && !isInvalidCredential && !isUnauthorized)) && (- <SecretErrorContainer brandingTheme={brandingTheme} error={fetchSecret?.error} />- )}- </>+ {secret && (+ <SecretContainer secret={secret} secretKey={key} brandingTheme={brandingTheme} />+ )}+ {!showPasswordPrompt && !isInvalidCredential && activeError && !isUnauthorized && (+ <SecretErrorContainer brandingTheme={brandingTheme} error={errorMessage} />)}{!hasCustomBranding && (<>