feat: simplified ui for password based secret sharing

This commit is contained in:
=
2024-08-10 22:21:17 +05:30
parent a5555c3816
commit 3ddb4cd27a
7 changed files with 89 additions and 111 deletions
+15 -34
View File
@@ -7,7 +7,11 @@ import { TSharedSecret, TViewSharedSecretResponse } from "./types";
export const secretSharingKeys = { export const secretSharingKeys = {
allSharedSecrets: () => ["sharedSecrets"] as const, allSharedSecrets: () => ["sharedSecrets"] as const,
specificSharedSecrets: ({ offset, limit }: { offset: number; limit: number }) => specificSharedSecrets: ({ offset, limit }: { offset: number; limit: number }) =>
[...secretSharingKeys.allSharedSecrets(), { offset, limit }] as const [...secretSharingKeys.allSharedSecrets(), { offset, limit }] as const,
getSecretById: (arg: { id: string; hashedHex: string; password?: string }) => [
"shared-secret",
arg
]
}; };
export const useGetSharedSecrets = ({ export const useGetSharedSecrets = ({
@@ -38,51 +42,28 @@ export const useGetSharedSecrets = ({
export const useGetActiveSharedSecretById = ({ export const useGetActiveSharedSecretById = ({
sharedSecretId, sharedSecretId,
hashedHex hashedHex,
password
}: { }: {
sharedSecretId: string; sharedSecretId: string;
hashedHex: string; hashedHex: string;
password?: string;
}) => { }) => {
return useQuery<TViewSharedSecretResponse | null>( return useQuery<TViewSharedSecretResponse>(
[`sharedSecret-${sharedSecretId}`], secretSharingKeys.getSecretById({ id: sharedSecretId, hashedHex, password }),
async () => { async () => {
const params = new URLSearchParams({ hashedHex }); const { data } = await apiRequest.post<TViewSharedSecretResponse>(
const { data } = await apiRequest.get<TViewSharedSecretResponse>(
`/api/v1/secret-sharing/public/${sharedSecretId}`, `/api/v1/secret-sharing/public/${sharedSecretId}`,
{ {
params hashedHex,
password
} }
); );
if (!data) return null return data;
return {
encryptedValue: data.encryptedValue,
iv: data.iv,
tag: data.tag,
accessType: data.accessType,
orgName: data.orgName
};
}, },
{ {
enabled: Boolean(sharedSecretId) && Boolean(hashedHex) enabled: Boolean(sharedSecretId) && Boolean(hashedHex)
} }
); );
}; };
// returns a secret (secret or undefined if password doesn't match)
export const fetchSecretIfPasswordIsValid = async (
sharedSecretId: string,
hashedHex: string,
password: string,
) => {
const { data } = await apiRequest.post<TViewSharedSecretResponse>(
`/api/v1/secret-sharing/public/${sharedSecretId}/validate`,
{
hashedHex,
password
}
);
return data;
};
+10 -6
View File
@@ -26,11 +26,14 @@ export type TCreateSharedSecretRequest = {
}; };
export type TViewSharedSecretResponse = { export type TViewSharedSecretResponse = {
encryptedValue: string; isPasswordProtected: boolean;
iv: string; secret: {
tag: string; encryptedValue: string;
accessType: SecretSharingAccessType; iv: string;
orgName?: string; tag: string;
accessType: SecretSharingAccessType;
orgName?: string;
};
}; };
export type TDeleteSharedSecretRequest = { export type TDeleteSharedSecretRequest = {
@@ -40,4 +43,5 @@ export type TDeleteSharedSecretRequest = {
export enum SecretSharingAccessType { export enum SecretSharingAccessType {
Anyone = "anyone", Anyone = "anyone",
Organization = "organization" Organization = "organization"
} }
@@ -33,7 +33,7 @@ const viewLimitOptions = [
const schema = z.object({ const schema = z.object({
name: z.string().optional(), name: z.string().optional(),
password: z.string().optional(), password: z.string().optional(),
secret: z.string(), secret: z.string().min(1),
expiresIn: z.string(), expiresIn: z.string(),
viewLimit: z.string(), viewLimit: z.string(),
accessType: z.nativeEnum(SecretSharingAccessType).optional() accessType: z.nativeEnum(SecretSharingAccessType).optional()
@@ -68,7 +68,14 @@ export const ShareSecretForm = ({ isPublic, value }: Props) => {
} }
}); });
const onFormSubmit = async ({ name, password, secret, expiresIn, viewLimit, accessType }: FormData) => { const onFormSubmit = async ({
name,
password,
secret,
expiresIn,
viewLimit,
accessType
}: FormData) => {
try { try {
const expiresAt = new Date(new Date().getTime() + Number(expiresIn)); const expiresAt = new Date(new Date().getTime() + Number(expiresIn));
@@ -159,7 +166,7 @@ export const ShareSecretForm = ({ isPublic, value }: Props) => {
label="Password" label="Password"
isError={Boolean(error)} isError={Boolean(error)}
errorText={error?.message} errorText={error?.message}
isOptional={true} isOptional
> >
<Input {...field} placeholder="Password" type="password" /> <Input {...field} placeholder="Password" type="password" />
</FormControl> </FormControl>
@@ -1,35 +1,42 @@
import { useState, useCallback, useEffect } from 'react' import { useState } from "react";
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { faArrowRight } from "@fortawesome/free-solid-svg-icons"; import { faArrowRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AxiosError } from "axios";
import { TViewSharedSecretResponse, useGetActiveSharedSecretById } from "@app/hooks/api/secretSharing"; import { useGetActiveSharedSecretById } from "@app/hooks/api/secretSharing";
import { SecretContainer, SecretErrorContainer, PasswordContainer } from "./components"; import { PasswordContainer,SecretContainer, SecretErrorContainer } from "./components";
export const ViewSecretPublicPage = () => { export const ViewSecretPublicPage = () => {
const [secret, setSecret] = useState<TViewSharedSecretResponse | null>(null);
const router = useRouter(); const router = useRouter();
const [password, setPassword] = useState<string>();
const { id, key: urlEncodedPublicKey } = router.query; const { id, key: urlEncodedPublicKey } = router.query;
const [hashedHex, key] = urlEncodedPublicKey const [hashedHex, key] = urlEncodedPublicKey
? urlEncodedPublicKey.toString().split("-") ? urlEncodedPublicKey.toString().split("-")
: ["", ""]; : ["", ""];
const { data: fetchSecret, error, isLoading } = useGetActiveSharedSecretById({ const {
data: fetchSecret,
error,
isLoading,
isFetching
} = useGetActiveSharedSecretById({
sharedSecretId: id as string, sharedSecretId: id as string,
hashedHex hashedHex,
password
}); });
useEffect(() => { const isInvalidCredential =
if (fetchSecret) setSecret(fetchSecret) ((error as AxiosError)?.response?.data as { message: string })?.message ===
}, [fetchSecret, error]) "Invalid credentials";
const handleSecret = useCallback((value: TViewSharedSecretResponse) => { const shouldShowPasswordPrompt =
setSecret(value) isInvalidCredential || (fetchSecret?.isPasswordProtected && !fetchSecret.secret);
}, [setSecret]) const isValidatingPassword = Boolean(password) && isFetching;
return ( return (
<div className="flex h-screen flex-col justify-between overflow-auto bg-gradient-to-tr from-mineshaft-700 to-bunker-800 text-gray-200 dark:[color-scheme:dark]"> <div className="flex h-screen flex-col justify-between overflow-auto bg-gradient-to-tr from-mineshaft-700 to-bunker-800 text-gray-200 dark:[color-scheme:dark]">
@@ -62,17 +69,21 @@ export const ViewSecretPublicPage = () => {
</a> </a>
</p> </p>
</div> </div>
{(shouldShowPasswordPrompt || isValidatingPassword) && (
<PasswordContainer
isSubmitting={isValidatingPassword}
onPasswordSubmit={(el) => {
setPassword(el);
}}
isInvalidCredential={!isFetching && isInvalidCredential}
/>
)}
{!isLoading && ( {!isLoading && (
<> <>
{!error && !secret && ( {!error && fetchSecret?.secret && key && (
<PasswordContainer <SecretContainer secret={fetchSecret.secret} secretKey={key} />
secretId={id as string}
hashedHex={hashedHex}
handleSecret={handleSecret}
/>
)} )}
{!error && secret && key && <SecretContainer secret={secret} secretKey={key} />} {error && !isInvalidCredential && <SecretErrorContainer />}
{error && <SecretErrorContainer />}
</> </>
)} )}
<div className="m-auto my-8 flex w-full"> <div className="m-auto my-8 flex w-full">
@@ -1,60 +1,34 @@
import { z } from "zod";
import { Controller, useForm } from "react-hook-form"; import { Controller, useForm } from "react-hook-form";
import { faArrowRight, faSpinner } from "@fortawesome/free-solid-svg-icons"; import { faArrowRight, faSpinner } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, FormControl, IconButton, Input } from "@app/components/v2"; import { Button, FormControl, IconButton, Input } from "@app/components/v2";
import { fetchSecretIfPasswordIsValid, TViewSharedSecretResponse } from "@app/hooks/api/secretSharing";
import { createNotification } from "@app/components/notifications";
type Props = { type Props = {
secretId: string; onPasswordSubmit: (val: any) => void;
hashedHex: string; isSubmitting?: boolean;
handleSecret: (val: any) => void; isInvalidCredential?: boolean;
}; };
const formSchema = z.object({ const formSchema = z.object({
password: z.string() password: z.string()
}) });
export type FormData = z.infer<typeof formSchema>; export type FormData = z.infer<typeof formSchema>;
export const PasswordContainer = ({ secretId, hashedHex, handleSecret }: Props) => { export const PasswordContainer = ({
const { onPasswordSubmit,
control, isSubmitting,
reset, isInvalidCredential
handleSubmit, }: Props) => {
formState: { isSubmitting } const { control, handleSubmit } = useForm<FormData>({
} = useForm<FormData>({ resolver: zodResolver(formSchema)
resolver: zodResolver(formSchema),
}); });
const onFormSubmit = async ({ password }: FormData) => { const onFormSubmit = async ({ password }: FormData) => {
try { onPasswordSubmit(password);
const secret: TViewSharedSecretResponse = await fetchSecretIfPasswordIsValid(
secretId,
hashedHex,
password,
)
if (secret) {
handleSecret(secret);
} else {
reset({ password: "" });
createNotification({
text: "Password is Invalid. Try again",
type: "error"
})
}
} catch (error) {
console.error("Failed to validate password:", error);
createNotification({
text: "Failed to validate password",
type: "error"
})
}
}; };
return ( return (
@@ -63,15 +37,16 @@ export const PasswordContainer = ({ secretId, hashedHex, handleSecret }: Props)
<Controller <Controller
control={control} control={control}
name="password" name="password"
defaultValue=""
render={({ field, fieldState: { error } }) => ( render={({ field, fieldState: { error } }) => (
<FormControl <FormControl
isError={Boolean(error)} isError={Boolean(error) || isInvalidCredential}
errorText={error?.message} errorText={isInvalidCredential ? "Invalid credential" : error?.message}
isRequired isRequired
label="Password" label="Password"
> >
<div className="flex items-center gap-2 justify-between rounded-md"> <div className="flex items-center justify-between gap-2 rounded-md">
<Input {...field} placeholder="Enter Password to view secret" type="password"></Input> <Input {...field} placeholder="Enter Password to view secret" type="password" />
<div className="flex"> <div className="flex">
<IconButton <IconButton
ariaLabel="copy icon" ariaLabel="copy icon"
@@ -79,9 +54,9 @@ export const PasswordContainer = ({ secretId, hashedHex, handleSecret }: Props)
className="group relative" className="group relative"
onClick={handleSubmit(onFormSubmit)} onClick={handleSubmit(onFormSubmit)}
> >
<FontAwesomeIcon <FontAwesomeIcon
className={isSubmitting ? 'fa-spin' : ''} className={isSubmitting ? "fa-spin" : ""}
icon={isSubmitting ? faSpinner : faArrowRight} icon={isSubmitting ? faSpinner : faArrowRight}
/> />
</IconButton> </IconButton>
</div> </div>
@@ -14,7 +14,7 @@ import { useTimedReset, useToggle } from "@app/hooks";
import { TViewSharedSecretResponse } from "@app/hooks/api/secretSharing"; import { TViewSharedSecretResponse } from "@app/hooks/api/secretSharing";
type Props = { type Props = {
secret: TViewSharedSecretResponse; secret: TViewSharedSecretResponse["secret"];
secretKey: string; secretKey: string;
}; };
@@ -1,3 +1,3 @@
export { PasswordContainer } from "./PasswordContainer";
export { SecretContainer } from "./SecretContainer"; export { SecretContainer } from "./SecretContainer";
export { SecretErrorContainer } from "./SecretErrorContainer"; export { SecretErrorContainer } from "./SecretErrorContainer";
export { PasswordContainer } from "./PasswordContainer";