Skip to content

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

checkpoint / identity support

Daniel Hougaard702cbb643b14
diff --git a/backend/src/db/migrations/20260210210927_secret-sharing-identity-support.ts b/backend/src/db/migrations/20260210210927_secret-sharing-identity-support.ts
new file mode 100644
index 0000000000..441f61610a
--- /dev/null
+++ b/backend/src/db/migrations/20260210210927_secret-sharing-identity-support.ts
@@ -0,0 +1,23 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasIdentityIdColumn = await knex.schema.hasColumn(TableName.SecretSharing, "identityId");
+ if (!hasIdentityIdColumn) {
+ await knex.schema.alterTable(TableName.SecretSharing, (t) => {
+ t.uuid("identityId");
+ t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasIdentityIdColumn = await knex.schema.hasColumn(TableName.SecretSharing, "identityId");
+ if (hasIdentityIdColumn) {
+ await knex.schema.alterTable(TableName.SecretSharing, (t) => {
+ t.dropForeign("identityId");
+ t.dropColumn("identityId");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/secret-sharing.ts b/backend/src/db/schemas/secret-sharing.ts
index 7a7bf17bb6..01222ded40 100644
--- a/backend/src/db/schemas/secret-sharing.ts
+++ b/backend/src/db/schemas/secret-sharing.ts
@@ -28,7 +28,8 @@ export const SecretSharingSchema = z.object({
encryptedSecret: zodBuffer.nullable().optional(),
identifier: z.string().nullable().optional(),
type: z.string().default("share"),
- authorizedEmails: z.unknown().nullable().optional()
+ authorizedEmails: z.unknown().nullable().optional(),
+ identityId: z.string().uuid().nullable().optional()
});
export type TSecretSharing = z.infer<typeof SecretSharingSchema>;
diff --git a/backend/src/db/schemas/secret-versions-v2.ts b/backend/src/db/schemas/secret-versions-v2.ts
index 593a46b068..d664c22eef 100644
--- a/backend/src/db/schemas/secret-versions-v2.ts
+++ b/backend/src/db/schemas/secret-versions-v2.ts
@@ -28,7 +28,10 @@ export const SecretVersionsV2Schema = z.object({
updatedAt: z.date(),
userActorId: z.string().uuid().nullable().optional(),
identityActorId: z.string().uuid().nullable().optional(),
- actorType: z.string().nullable().optional()
+ actorType: z.string().nullable().optional(),
+ isRedacted: z.boolean().default(false),
+ redactedAt: z.date().nullable().optional(),
+ redactedByUserId: z.string().uuid().nullable().optional()
});
export type TSecretVersionsV2 = z.infer<typeof SecretVersionsV2Schema>;
diff --git a/backend/src/server/routes/v1/secret-requests-router.ts b/backend/src/server/routes/v1/secret-requests-router.ts
index 67e6afe978..42ac61fc58 100644
--- a/backend/src/server/routes/v1/secret-requests-router.ts
+++ b/backend/src/server/routes/v1/secret-requests-router.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { SecretSharingSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { NotFoundError } from "@app/lib/errors";
+import { ms } from "@app/lib/ms";
import { SecretSharingAccessType } from "@app/lib/types";
import { publicEndpointLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
@@ -285,11 +286,31 @@ export const registerSecretRequestsRouter = async (server: FastifyZodProvider) =
},
schema: {
operationId: "createSecretRequest",
- body: z.object({
- name: z.string().max(50).optional(),
- expiresAt: z.string(),
- accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization)
- }),
+ body: z
+ .object({
+ name: z.string().max(50).optional(),
+ expiresIn: z.string(),
+ accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization)
+ })
+ .superRefine((data, ctx) => {
+ const duration = ms(data.expiresIn);
+
+ if (duration > ms("30d")) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Expiration time cannot exceed 30 days",
+ path: ["expiresIn"]
+ });
+ }
+
+ if (duration < ms("5m")) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Expiration time cannot be less than 5 minutes",
+ path: ["expiresIn"]
+ });
+ }
+ }),
response: {
200: z.object({
id: z.string()
diff --git a/backend/src/server/routes/v1/secret-sharing-router.ts b/backend/src/server/routes/v1/secret-sharing-router.ts
index e527f07d8f..64da05fd5a 100644
--- a/backend/src/server/routes/v1/secret-sharing-router.ts
+++ b/backend/src/server/routes/v1/secret-sharing-router.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ms } from "@app/lib/ms";
import { SecretSharingAccessType } from "@app/lib/types";
import {
publicEndpointLimit,
@@ -43,7 +44,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
},
schema: {
hide: false,
- description: "List all shared secrets created by the authenticated user in their current organization.",
+ description:
+ "List all shared secrets created by the authenticated user or identity in their current organization.",
operationId: "listSharedSecrets",
querystring: z.object({
offset: z.coerce.number().min(0).max(100).default(0),
@@ -83,7 +85,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
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.",
+ "Returns the full shared secret object without revealing the secret value. Authentication is required for shared secrets that are scoped to an organization.",
operationId: "getSharedSecretById",
params: z.object({
id: z.string().describe("The ID of the shared secret")
@@ -113,7 +115,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
schema: {
hide: false,
description:
- "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.",
+ "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 an error if access is denied. The endpoint requires authentication if the shared secret is scoped to an organization.",
operationId: "accessSharedSecret",
params: z.object({
id: z.string().describe("The ID of the shared secret to access")
@@ -169,12 +171,32 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
schema: {
hide: true,
operationId: "createPublicSharedSecret",
- body: z.object({
- secretValue: z.string().max(10_000),
- password: z.string().optional(),
- expiresAt: z.string(),
- expiresAfterViews: z.number().min(1).optional()
- }),
+ body: z
+ .object({
+ secretValue: z.string().max(10_000),
+ password: z.string().optional(),
+ expiresIn: z.string(),
+ maxViews: z.number().min(1).optional()
+ })
+ .superRefine((data, ctx) => {
+ const duration = ms(data.expiresIn);
+
+ if (duration > ms("30d")) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Expiration time cannot exceed 30 days",
+ path: ["expiresIn"]
+ });
+ }
+
+ if (duration < ms("5m")) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Expiration time cannot be less than 5 minutes",
+ path: ["expiresIn"]
+ });
+ }
+ }),
response: {
200: z.object({
id: z.string()
@@ -200,28 +222,46 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
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(),
- password: z.string().optional(),
- secretValue: z.string(),
- expiresAt: z.string(),
- expiresAfterViews: z.number().min(1).optional(),
- accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization),
- emails: z
- .string()
- .email()
- .array()
- .max(100)
- .optional()
- .transform((val) => (val ? [...new Set(val)] : undefined))
- }),
- response: {
- 200: z.object({
- id: z.string()
+ body: z
+ .object({
+ name: z.string().max(50).optional(),
+ password: z.string().optional(),
+ secretValue: z.string(),
+ expiresIn: z.string().default("30d"),
+ maxViews: z.number().min(1).optional(),
+ accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization),
+ emails: z
+ .string()
+ .email()
+ .array()
+ .max(100)
+ .optional()
+ .transform((val) => (val ? [...new Set(val)] : undefined))
})
+ .superRefine((data, ctx) => {
+ const duration = ms(data.expiresIn);
+
+ if (duration > ms("30d")) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Expiration time cannot exceed 30 days",
+ path: ["expiresIn"]
+ });
+ }
+
+ if (duration < ms("5m")) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Expiration time cannot be less than 5 minutes",
+ path: ["expiresIn"]
+ });
+ }
+ }),
+ response: {
+ 200: SanitizedSecretSharingSchema
}
},
- onRequest: verifyAuth([AuthMode.JWT]),
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const sharedSecret = await req.server.services.secretSharing.createSharedSecret({
actor: req.permission.type,
@@ -239,8 +279,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
type: EventType.CREATE_SHARED_SECRET,
metadata: {
accessType: req.body.accessType,
- expiresAt: req.body.expiresAt,
- expiresAfterViews: req.body.expiresAfterViews,
+ expiresAt: sharedSecret.expiresAt.toISOString(),
+ expiresAfterViews: req.body.maxViews,
name: req.body.name,
id: sharedSecret.id,
usingPassword: !!req.body.password
@@ -248,7 +288,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
}
});
- return { id: sharedSecret.id };
+ return sharedSecret;
}
});
@@ -269,7 +309,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
200: SanitizedSecretSharingSchema
}
},
- onRequest: verifyAuth([AuthMode.JWT]),
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { id } = req.params;
const deletedSharedSecret = await req.server.services.secretSharing.deleteSharedSecretById({
@@ -294,7 +334,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
}
});
- return { ...deletedSharedSecret };
+ return deletedSharedSecret;
}
});
diff --git a/backend/src/services/secret-sharing/secret-sharing-dal.ts b/backend/src/services/secret-sharing/secret-sharing-dal.ts
index 08e0ad2575..95651af40e 100644
--- a/backend/src/services/secret-sharing/secret-sharing-dal.ts
+++ b/backend/src/services/secret-sharing/secret-sharing-dal.ts
@@ -50,13 +50,19 @@ export const secretSharingDALFactory = (db: TDbClient) => {
const countAllUserOrgSharedSecrets = async ({
orgId,
- userId,
- type
+ type,
+ ...actorFilters
}: {
orgId: string;
- userId: string;
type: SecretSharingType;
- }) => {
+ } & (
+ | {
+ userId: string;
+ }
+ | {
+ identityId: string;
+ }
+ )) => {
try {
interface CountResult {
count: string;
@@ -65,7 +71,14 @@ export const secretSharingDALFactory = (db: TDbClient) => {
const count = await db
.replicaNode()(TableName.SecretSharing)
.where(`${TableName.SecretSharing}.orgId`, orgId)
- .where(`${TableName.SecretSharing}.userId`, userId)
+ .where((qb) => {
+ if ("userId" in actorFilters) {
+ void qb.where(`${TableName.SecretSharing}.userId`, actorFilters.userId);
+ }
+ if ("identityId" in actorFilters) {
+ void qb.where(`${TableName.SecretSharing}.identityId`, actorFilters.identityId);
+ }
+ })
.where(`${TableName.SecretSharing}.type`, type)
.count("*")
.first();
diff --git a/backend/src/services/secret-sharing/secret-sharing-service.ts b/backend/src/services/secret-sharing/secret-sharing-service.ts
index 07877ceb8f..e1eedb31cd 100644
--- a/backend/src/services/secret-sharing/secret-sharing-service.ts
+++ b/backend/src/services/secret-sharing/secret-sharing-service.ts
@@ -8,9 +8,10 @@ import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { ms } from "@app/lib/ms";
import { OrgServiceActor, SecretSharingAccessType } from "@app/lib/types";
-import { isUuidV4 } from "@app/lib/validator";
+import { ActorType } from "../auth/auth-type";
import { TKmsServiceFactory } from "../kms/kms-service";
import { TOrgDALFactory } from "../org/org-dal";
import { TSecretShareBrandConfig } from "../org/org-types";
@@ -45,6 +46,11 @@ type TSecretSharingServiceFactoryDep = {
export type TSecretSharingServiceFactory = ReturnType<typeof secretSharingServiceFactory>;
const mapIdentifierToId = (sharedSecret: TSecretSharing): Omit<TSecretSharing, "identifier"> => {
+ // secret requests don't use identifiers and are fully ID dependant. so for secret requests we just return it as-is
+ if (sharedSecret.type === SecretSharingType.Request) {
+ return sharedSecret;
+ }
+
const { identifier, ...rest } = sharedSecret;
if (!identifier) {
@@ -69,13 +75,13 @@ export const secretSharingServiceFactory = ({
userDAL,
licenseService
}: TSecretSharingServiceFactoryDep) => {
- const $validateSharedSecretExpiry = (expiresAt: string) => {
- if (new Date(expiresAt) < new Date()) {
+ const $validateSharedSecretExpiry = (expiresAt: Date) => {
+ if (expiresAt < new Date()) {
throw new BadRequestError({ message: "Expiration date cannot be in the past" });
}
// Limit Expiry Time to 1 month
- const expiryTime = new Date(expiresAt).getTime();
+ const expiryTime = expiresAt.getTime();
const currentTime = new Date().getTime();
const thirtyDays = 30 * 24 * 60 * 60 * 1000;
if (expiryTime - currentTime > thirtyDays) {
@@ -100,8 +106,8 @@ export const secretSharingServiceFactory = ({
name,
password,
accessType,
- expiresAt,
- expiresAfterViews,
+ expiresIn,
+ maxViews,
emails
}: TCreateSharedSecretDTO) => {
const appCfg = getConfig();
@@ -115,6 +121,9 @@ export const secretSharingServiceFactory = ({
scope: OrganizationActionScope.Any
});
if (!permission) throw new ForbiddenRequestError({ name: "User is not a part of the specified organization" });
+
+ const expiresAt = new Date(Date.now() + ms(expiresIn));
+
$validateSharedSecretExpiry(expiresAt);
const rootOrg = await orgDAL.findRootOrgDetails(orgId);
@@ -131,8 +140,7 @@ export const secretSharingServiceFactory = ({
}
// Check lifetime is within org allowance
- const expiresAtTimestamp = new Date(expiresAt).getTime();
- const lifetime = expiresAtTimestamp - new Date().getTime();
+ const lifetime = expiresAt.getTime() - new Date().getTime();
// rootOrg.maxSharedSecretLifetime is in seconds
if (rootOrg.maxSharedSecretLifetime && lifetime / 1000 > rootOrg.maxSharedSecretLifetime) {
@@ -140,10 +148,7 @@ export const secretSharingServiceFactory = ({
}
// Check max view count is within org allowance
- if (
- rootOrg.maxSharedSecretViewLimit &&
- (!expiresAfterViews || expiresAfterViews > rootOrg.maxSharedSecretViewLimit)
- ) {
+ if (rootOrg.maxSharedSecretViewLimit && (!maxViews || maxViews > rootOrg.maxSharedSecretViewLimit)) {
throw new BadRequestError({ message: "Secret max views parameter exceeds organization limit" });
}
@@ -185,8 +190,9 @@ export const secretSharingServiceFactory = ({
type: SecretSharingType.Share,
password: hashedPassword,
expiresAt: new Date(expiresAt),
- expiresAfterViews,
- userId: actorId,
+ expiresAfterViews: maxViews,
+ ...(actor === ActorType.USER && { userId: actorId }),
+ ...(actor === ActorType.IDENTITY && { identityId: actorId }),
orgId,
accessType,
authorizedEmails: emails && emails.length > 0 ? JSON.stringify(emails) : undefined
@@ -229,7 +235,7 @@ export const secretSharingServiceFactory = ({
const createSecretRequest = async ({
actor,
accessType,
- expiresAt,
+ expiresIn,
name,
actorId,
orgId,
@@ -246,6 +252,8 @@ export const secretSharingServiceFactory = ({
});
if (!permission) throw new ForbiddenRequestError({ name: "User is not a part of the specified organization" });
+ const expiresAt = new Date(Date.now() + ms(expiresIn));
+
$validateSharedSecretExpiry(expiresAt);
const newSecretRequest = await secretSharingDAL.create({
@@ -255,7 +263,7 @@ export const secretSharingServiceFactory = ({
name,
encryptedSecret: null,
accessType,
- expiresAt: new Date(expiresAt)
+ expiresAt
});
return { id: newSecretRequest.id };
@@ -438,10 +446,12 @@ export const secretSharingServiceFactory = ({
const createPublicSharedSecret = async ({
password,
secretValue,
- expiresAt,
- expiresAfterViews,
+ expiresIn,
+ maxViews,
accessType
}: TCreatePublicSharedSecretDTO) => {
+ const expiresAt = new Date(Date.now() + ms(expiresIn));
+
$validateSharedSecretExpiry(expiresAt);
const encryptWithRoot = kmsService.encryptWithRootKey();
@@ -460,8 +470,8 @@ export const secretSharingServiceFactory = ({
type: SecretSharingType.Share,
encryptedSecret,
password: hashedPassword,
- expiresAt: new Date(expiresAt),
- expiresAfterViews,
+ expiresAt,
+ expiresAfterViews: maxViews,
accessType
});
@@ -491,7 +501,8 @@ export const secretSharingServiceFactory = ({
const secrets = await secretSharingDAL.find(
{
- userId: actorId,
+ ...(actor === ActorType.USER && { userId: actorId }),
+ ...(actor === ActorType.IDENTITY && { identityId: actorId }),
orgId: actorOrgId,
type
},
@@ -501,7 +512,9 @@ export const secretSharingServiceFactory = ({
const count = await secretSharingDAL.countAllUserOrgSharedSecrets({
orgId: actorOrgId,
userId: actorId,
- type
+ type,
+ ...(actor === ActorType.USER && { userId: actorId }),
+ ...(actor === ActorType.IDENTITY && { identityId: actorId })
});
return {
@@ -680,18 +693,37 @@ export const secretSharingServiceFactory = ({
});
if (!permission) throw new ForbiddenRequestError({ name: "User does not belong to the specified organization" });
- const sharedSecret = isUuidV4(sharedSecretId)
- ? await secretSharingDAL.findOne({ id: sharedSecretId, type: deleteSharedSecretInput.type })
- : await secretSharingDAL.findOne({
- identifier: Buffer.from(sharedSecretId, "base64url").toString("hex"),
- type: deleteSharedSecretInput.type
- });
+ let sharedSecret;
- if (sharedSecret.userId !== actorId) {
- throw new ForbiddenRequestError({
- message: "User does not have permission to delete shared secret"
+ if (deleteSharedSecretInput.type === SecretSharingType.Request) {
+ sharedSecret = await secretSharingDAL.findOne({
+ id: sharedSecretId
+ });
+ } else {
+ sharedSecret = await secretSharingDAL.findOne({
+ identifier: Buffer.from(sharedSecretId, "base64url").toString("hex")
});
}
+
+ if (!sharedSecret) {
+ throw new NotFoundError({ message: `Shared secret with ID '${sharedSecretId}' not found` });
+ }
+
+ if (actor === ActorType.USER) {
+ if (sharedSecret.userId !== actorId) {
+ throw new ForbiddenRequestError({
+ message: "User does not have permission to delete shared secret"
+ });
+ }
+ }
+ if (actor === ActorType.IDENTITY) {
+ if (sharedSecret.identityId !== actorId) {
+ throw new ForbiddenRequestError({
+ message: "Identity does not have permission to delete shared secret"
+ });
+ }
+ }
+
if (sharedSecret.orgId && sharedSecret.orgId !== orgId) {
throw new ForbiddenRequestError({ message: "User does not have permission to delete shared secret" });
}
diff --git a/backend/src/services/secret-sharing/secret-sharing-types.ts b/backend/src/services/secret-sharing/secret-sharing-types.ts
index 84aed6ed39..cfaa0ef955 100644
--- a/backend/src/services/secret-sharing/secret-sharing-types.ts
+++ b/backend/src/services/secret-sharing/secret-sharing-types.ts
@@ -27,8 +27,8 @@ export type TSharedSecretPermission = {
export type TCreatePublicSharedSecretDTO = {
secretValue: string;
- expiresAt: string;
- expiresAfterViews?: number;
+ expiresIn: string;
+ maxViews?: number;
password?: string;
accessType: SecretSharingAccessType;
};
@@ -49,7 +49,7 @@ export type TCreateSharedSecretDTO = TSharedSecretPermission & TCreatePublicShar
export type TCreateSecretRequestDTO = {
name?: string;
accessType: SecretSharingAccessType;
- expiresAt: string;
+ expiresIn: string;
} & TOrgPermission;
export type TRevealSecretRequestValueDTO = {
diff --git a/frontend/src/hooks/api/secretSharing/mutations.ts b/frontend/src/hooks/api/secretSharing/mutations.ts
index 58792cb303..c48d624556 100644
--- a/frontend/src/hooks/api/secretSharing/mutations.ts
+++ b/frontend/src/hooks/api/secretSharing/mutations.ts
@@ -5,6 +5,7 @@ import { apiRequest } from "@app/config/request";
import { secretSharingKeys } from "./queries";
import {
TAccessSharedSecretRequest,
+ TAccessSharedSecretResponse,
TCreatedSharedSecret,
TCreateSecretRequestRequestDTO,
TCreateSharedSecretRequest,
@@ -13,8 +14,7 @@ import {
TRevealedSecretRequest,
TRevealSecretRequestValueRequest,
TSetSecretRequestValueRequest,
- TSharedSecret,
- TViewSharedSecretResponse
+ TSharedSecret
} from "./types";
export const useCreateSharedSecret = () => {
@@ -34,11 +34,10 @@ export const useCreateSharedSecret = () => {
export const useAccessSharedSecret = () => {
return useMutation({
- mutationFn: async ({ sharedSecretId, password, hashedHex }: TAccessSharedSecretRequest) => {
- const { data } = await apiRequest.post<TViewSharedSecretResponse>(
+ mutationFn: async ({ sharedSecretId, password }: TAccessSharedSecretRequest) => {
+ const { data } = await apiRequest.post<TAccessSharedSecretResponse>(
`/api/v1/secret-sharing/${sharedSecretId}/access`,
{
- ...(hashedHex && { hashedHex }),
...(password && { password })
}
);
diff --git a/frontend/src/hooks/api/secretSharing/types.ts b/frontend/src/hooks/api/secretSharing/types.ts
index c239d474a9..40b2e8abea 100644
--- a/frontend/src/hooks/api/secretSharing/types.ts
+++ b/frontend/src/hooks/api/secretSharing/types.ts
@@ -29,8 +29,8 @@ export type TCreateSharedSecretRequest = {
name?: string;
password?: string;
secretValue: string;
- expiresAt: Date;
- expiresAfterViews?: number;
+ expiresIn: string;
+ maxViews?: number;
accessType?: SecretSharingAccessType;
emails?: string[];
};
@@ -38,7 +38,7 @@ export type TCreateSharedSecretRequest = {
export type TCreateSecretRequestRequestDTO = {
name?: string;
accessType?: SecretSharingAccessType;
- expiresAt: Date;
+ expiresIn: string;
};
export type TSetSecretRequestValueRequest = {
@@ -50,17 +50,6 @@ export type TRevealSecretRequestValueRequest = {
id: string;
};
-export type TSharedSecretResponse = {
- secretValue?: string;
- encryptedValue: string;
- iv: string;
- tag: string;
- accessType: SecretSharingAccessType;
- orgName?: string;
- expiresAt?: Date | string;
- expiresAfterViews?: number | null;
-};
-
export type TBrandingConfig = {
hasLogo: boolean;
hasFavicon: boolean;
@@ -87,15 +76,17 @@ export type TSharedSecretPublicDetails = TSanitizedSharedSecret & {
isPasswordProtected: boolean;
};
-export type TViewSharedSecretResponse = {
- isPasswordProtected: boolean;
- secret?: TSharedSecretResponse;
+export type TAccessSharedSecretResponse = {
+ secretValue: string;
+ accessType: SecretSharingAccessType;
+ orgName?: string;
+ expiresAt?: Date | string;
+ expiresAfterViews?: number | null;
};
export type TAccessSharedSecretRequest = {
sharedSecretId: string;
password?: string;
- hashedHex?: string | null;
};
export type TGetSecretRequestByIdResponse = {
diff --git a/frontend/src/lib/fn/time.ts b/frontend/src/lib/fn/time.ts
new file mode 100644
index 0000000000..4ca6525667
--- /dev/null
+++ b/frontend/src/lib/fn/time.ts
@@ -0,0 +1,13 @@
+import msFn from "ms";
+
+export const ms = (val: string) => {
+ if (typeof val !== "string") {
+ throw new Error("Date must be string");
+ }
+
+ try {
+ return msFn(val);
+ } catch {
+ throw new Error(`Invalid date format string: ${val}`);
+ }
+};
diff --git a/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx b/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx
index d508733393..d79fcfcfa4 100644
--- a/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx
+++ b/frontend/src/pages/organization/SecretSharingPage/components/RequestSecret/RequestSecretForm.tsx
@@ -21,13 +21,13 @@ const schema = z.object({
});
const expiresInOptions = [
- { label: "5 min", value: 5 * 60 * 1000 },
- { label: "30 min", value: 30 * 60 * 1000 },
- { label: "1 hour", value: 60 * 60 * 1000 },
- { label: "1 day", value: 24 * 60 * 60 * 1000 },
- { label: "7 days", value: 7 * 24 * 60 * 60 * 1000 },
- { label: "14 days", value: 14 * 24 * 60 * 60 * 1000 },
- { label: "30 days", value: 30 * 24 * 60 * 60 * 1000 }
+ { label: "5 min", value: "5m" },
+ { label: "30 min", value: "30m" },
+ { label: "1 hour", value: "1h" },
+ { label: "1 day", value: "1d" },
+ { label: "7 days", value: "7d" },
+ { label: "14 days", value: "14d" },
+ { label: "30 days", value: "30d" }
];
export type FormData = z.infer<typeof schema>;
@@ -50,16 +50,17 @@ export const RequestSecretForm = () => {
handleSubmit,
formState: { isSubmitting }
} = useForm<FormData>({
- resolver: zodResolver(schema)
+ resolver: zodResolver(schema),
+ defaultValues: {
+ expiresIn: "7d"
+ }
});
const onFormSubmit = async ({ name, accessType, expiresIn }: FormData) => {
- const expiresAt = new Date(new Date().getTime() + Number(expiresIn));
-
const { id } = await createSecretRequest({
name,
accessType,
- expiresAt
+ expiresIn
});
const link = new URL(`${window.location.origin}/secret-request/secret/${id}`);
diff --git a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx
index eb216abb56..b4af440528 100644
--- a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx
+++ b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx
@@ -23,16 +23,17 @@ import {
import { useTimedReset } from "@app/hooks";
import { useCreatePublicSharedSecret, useCreateSharedSecret } from "@app/hooks/api";
import { SecretSharingAccessType } from "@app/hooks/api/secretSharing";
+import { ms } from "@app/lib/fn/time";
// values in ms
const expiresInOptions = [
- { label: "5 min", value: 5 * 60 * 1000 },
- { label: "30 min", value: 30 * 60 * 1000 },
- { label: "1 hour", value: 60 * 60 * 1000 },
- { label: "1 day", value: 24 * 60 * 60 * 1000 },
- { label: "7 days", value: 7 * 24 * 60 * 60 * 1000 },
- { label: "14 days", value: 14 * 24 * 60 * 60 * 1000 },
- { label: "30 days", value: 30 * 24 * 60 * 60 * 1000 }
+ { label: "5 min", value: "5m" },
+ { label: "30 min", value: "30m" },
+ { label: "1 hour", value: "1h" },
+ { label: "1 day", value: "1d" },
+ { label: "7 days", value: "7d" },
+ { label: "14 days", value: "14d" },
+ { label: "30 days", value: "30d" }
];
const viewLimitOptions = [
@@ -99,7 +100,7 @@ export const ShareSecretForm = ({
// Note: maxSharedSecretLifetime is in seconds
const filteredExpiresInOptions = maxSharedSecretLifetime
- ? expiresInOptions.filter((v) => v.value / 1000 <= maxSharedSecretLifetime)
+ ? expiresInOptions.filter((v) => ms(v.value) / 1000 <= maxSharedSecretLifetime)
: expiresInOptions;
const {
@@ -131,16 +132,14 @@ export const ShareSecretForm = ({
emails,
shouldLimitView
}: FormData) => {
- const expiresAt = new Date(new Date().getTime() + Number(expiresIn));
-
const processedEmails = emails ? emails.split(",").map((e) => e.trim()) : undefined;
const { id } = await createSharedSecret.mutateAsync({
name,
password,
secretValue: secret,
- expiresAt,
- expiresAfterViews: shouldLimitView ? Number(viewLimit) : undefined,
+ expiresIn,
+ maxViews: shouldLimitView ? Number(viewLimit) : undefined,
accessType,
emails: processedEmails
});
diff --git a/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx b/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx
index 784d2cae2a..b3f74e6a35 100644
--- a/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx
+++ b/frontend/src/pages/public/ViewSharedSecretByIDPage/ViewSharedSecretByIDPage.tsx
@@ -2,7 +2,7 @@ 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";
-import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
+import { useNavigate, useParams } from "@tanstack/react-router";
import { AxiosError } from "axios";
import { addSeconds, formatISO } from "date-fns";
import { twMerge } from "tailwind-merge";
@@ -56,32 +56,11 @@ export type BrandingTheme = {
buttonBg: string;
};
-const extractDetailsFromUrl = (urlEncodedKey: string) => {
- if (urlEncodedKey) {
- const [hashedHex, key] = urlEncodedKey ? urlEncodedKey.toString().split("-") : ["", ""];
-
- return {
- hashedHex,
- key
- };
- }
-
- return {
- hashedHex: null,
- key: null
- };
-};
-
export const ViewSharedSecretByIDPage = () => {
const id = useParams({
from: ROUTE_PATHS.Public.ViewSharedSecretByIDPage.id,
select: (el) => el.secretId
});
- const urlEncodedKey = useSearch({
- from: ROUTE_PATHS.Public.ViewSharedSecretByIDPage.id,
- select: (el) => el.key
- });
- const { hashedHex, key } = extractDetailsFromUrl(urlEncodedKey);
const navigate = useNavigate();
const hasTriggeredAccess = useRef(false);
@@ -105,7 +84,7 @@ export const ViewSharedSecretByIDPage = () => {
useEffect(() => {
if (secretDetails && !secretDetails.isPasswordProtected && !hasTriggeredAccess.current) {
hasTriggeredAccess.current = true;
- accessMutation.mutate({ sharedSecretId: id, hashedHex });
+ accessMutation.mutate({ sharedSecretId: id });
}
}, [secretDetails]);
@@ -145,7 +124,7 @@ export const ViewSharedSecretByIDPage = () => {
}, [activeError]);
// UI state
- const secret = accessMutation.data?.secret;
+ const secret = accessMutation.data;
const isPasswordProtected = secretDetails?.isPasswordProtected ?? false;
const showPasswordPrompt = isPasswordProtected && !secret;
const isLoading = isLoadingDetails || (!isPasswordProtected && accessMutation.isPending);
@@ -293,15 +272,13 @@ export const ViewSharedSecretByIDPage = () => {
<PasswordContainer
isSubmitting={accessMutation.isPending}
onPasswordSubmit={(pwd) => {
- accessMutation.mutate({ sharedSecretId: id, password: pwd, hashedHex });
+ accessMutation.mutate({ sharedSecretId: id, password: pwd });
}}
isInvalidCredential={!accessMutation.isPending && isInvalidCredential}
brandingTheme={brandingTheme}
/>
)}
- {secret && (
- <SecretContainer secret={secret} secretKey={key} brandingTheme={brandingTheme} />
- )}
+ {secret && <SecretContainer secret={secret} brandingTheme={brandingTheme} />}
{!showPasswordPrompt && !isInvalidCredential && activeError && !isUnauthorized && (
<SecretErrorContainer brandingTheme={brandingTheme} error={errorMessage} />
)}
diff --git a/frontend/src/pages/public/ViewSharedSecretByIDPage/components/SecretContainer.tsx b/frontend/src/pages/public/ViewSharedSecretByIDPage/components/SecretContainer.tsx
index 21f7eb076c..4c603d18e2 100644
--- a/frontend/src/pages/public/ViewSharedSecretByIDPage/components/SecretContainer.tsx
+++ b/frontend/src/pages/public/ViewSharedSecretByIDPage/components/SecretContainer.tsx
@@ -1,4 +1,3 @@
-import { useMemo } from "react";
import {
faArrowRight,
faCheck,
@@ -8,44 +7,25 @@ import {
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { decryptSymmetric } from "@app/components/utilities/cryptography/crypto";
import { Button, IconButton } from "@app/components/v2";
import { useTimedReset, useToggle } from "@app/hooks";
-import { TSharedSecretResponse } from "@app/hooks/api/secretSharing";
+import { TAccessSharedSecretResponse } from "@app/hooks/api/secretSharing";
import { BrandingTheme } from "../ViewSharedSecretByIDPage";
import { SecretShareInfo } from "./SecretShareInfo";
type Props = {
- secret: TSharedSecretResponse;
- secretKey: string | null;
+ secret: TAccessSharedSecretResponse;
brandingTheme?: BrandingTheme;
};
-export const SecretContainer = ({ secret, secretKey: key, brandingTheme }: Props) => {
+export const SecretContainer = ({ secret, brandingTheme }: Props) => {
const [isVisible, setIsVisible] = useToggle(false);
const [, isCopyingSecret, setCopyTextSecret] = useTimedReset<string>({
initialState: "Copy to clipboard"
});
- const decryptedSecret = useMemo(() => {
- if (secret.secretValue) {
- return secret.secretValue;
- }
-
- if (secret && secret.encryptedValue && key) {
- const res = decryptSymmetric({
- ciphertext: secret.encryptedValue,
- iv: secret.iv,
- tag: secret.tag,
- key
- });
- return res;
- }
- return "";
- }, [secret, key]);
-
- const hiddenSecret = decryptedSecret ? "*".repeat(decryptedSecret.length) : "";
+ const hiddenSecret = "*".repeat(secret.secretValue.length);
const panelStyle = brandingTheme
? {
@@ -81,7 +61,7 @@ export const SecretContainer = ({ secret, secretKey: key, brandingTheme }: Props
style={secretDisplayStyle}
>
<p className="break-all whitespace-pre-wrap">
- {isVisible ? decryptedSecret : hiddenSecret}
+ {isVisible ? secret.secretValue : hiddenSecret}
</p>
<div className="flex">
<IconButton
@@ -89,7 +69,7 @@ export const SecretContainer = ({ secret, secretKey: key, brandingTheme }: Props
colorSchema="secondary"
className="group relative size-9 hover:opacity-70"
onClick={() => {
- navigator.clipboard.writeText(decryptedSecret);
+ navigator.clipboard.writeText(secret.secretValue);
setCopyTextSecret("Copied");
}}
style={iconButtonStyle}
diff --git a/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsx b/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsx
index 7b98dded34..5d38001b66 100644
--- a/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsx
+++ b/frontend/src/pages/public/ViewSharedSecretByIDPage/route.tsx
@@ -1,21 +1,11 @@
-import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
-import { zodValidator } from "@tanstack/zod-adapter";
-import { z } from "zod";
+import { createFileRoute } from "@tanstack/react-router";
import { authKeys, fetchAuthToken } from "@app/hooks/api/auth/queries";
import { ViewSharedSecretByIDPage } from "./ViewSharedSecretByIDPage";
-const SharedSecretByIDPageQuerySchema = z.object({
- key: z.string().catch("")
-});
-
export const Route = createFileRoute("/shared/secret/$secretId")({
- validateSearch: zodValidator(SharedSecretByIDPageQuerySchema),
component: ViewSharedSecretByIDPage,
- search: {
- middlewares: [stripSearchParams({ key: "" })]
- },
beforeLoad: async ({ context }) => {
// we load the auth token because the view shared secret screen serves both public and authenticated users
await context.queryClient