Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implemented redirects using context.config #2755

Merged
merged 6 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const StateManager = ({
children,
workflowId,
initialContext,
config,
}: StateManagerProps) => {
const machine = useMemo(() => {
const initialMachineState = {
Expand All @@ -31,6 +32,7 @@ export const StateManager = ({
);

machine.overrideContext(initialMachineState);

return machine;
}, []);

Expand Down Expand Up @@ -60,13 +62,16 @@ export const StateManager = ({
},
state,
payload: contextPayload,
config,
isPluginLoading: isPluginLoading,
};

return ctx;
}, [
state,
contextPayload,
isPluginLoading,
config,
getState,
sendEvent,
invokePlugin,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { StateMachineAPI } from '@/components/organisms/DynamicUI/StateManager/hooks/useMachineLogic';
import { CollectionFlowContext } from '@/domains/collection-flow/types/flow-context.types';
import {
CollectionFlowConfig,
CollectionFlowContext,
} from '@/domains/collection-flow/types/flow-context.types';
import { AnyChildren, AnyObject } from '@ballerine/ui';
import { MachineConfig } from 'xstate';

Expand All @@ -9,6 +12,7 @@ export interface StateManagerContext {
stateApi: StateMachineAPI;
state: string;
payload: AnyObject;
config?: CollectionFlowConfig;
isPluginLoading: boolean;
}

Expand All @@ -21,4 +25,5 @@ export interface StateManagerProps {
extensions: AnyObject;
children: AnyChildren | StateManagerChildCallback;
initialContext: CollectionFlowContext | null;
config?: CollectionFlowConfig;
}
14 changes: 11 additions & 3 deletions apps/kyb-app/src/domains/collection-flow/collection-flow.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import {
TUser,
UISchema,
} from '@/domains/collection-flow/types';
import { CollectionFlowContext } from '@/domains/collection-flow/types/flow-context.types';
import {
CollectionFlowConfig,
CollectionFlowContext,
CollectionFlowContextData,
} from '@/domains/collection-flow/types/flow-context.types';
import posthog from 'posthog-js';

export const fetchUser = async (): Promise<TUser> => {
Expand Down Expand Up @@ -64,8 +68,12 @@ export const fetchCustomer = async (): Promise<TCustomer> => {
return await request.get('collection-flow/customer').json<TCustomer>();
};

export const fetchFlowContext = async (): Promise<CollectionFlowContext> => {
export const fetchFlowContext = async (): Promise<CollectionFlowContextData> => {
const result = await request.get('collection-flow/context');
const resultJson = await result.json<{
context: CollectionFlowContext;
config: CollectionFlowConfig;
}>();

return (await result.json<{ context: CollectionFlowContext }>()).context || {};
return resultJson;
};
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { UIOptions } from '@/domains/collection-flow/types';

export interface FlowConfig {
apiUrl: string;
tokenId: string;
Expand All @@ -9,3 +11,11 @@ export interface FlowConfig {
export type CollectionFlowContext = Record<string, unknown> & {
flowConfig?: FlowConfig;
};

export interface CollectionFlowConfig {
uiOptions?: UIOptions;
}
export interface CollectionFlowContextData {
context: CollectionFlowContext;
config: CollectionFlowConfig;
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
import { useStateManagerContext } from '@/components/organisms/DynamicUI/StateManager/components/StateProvider';
import { UIOptions } from '@/domains/collection-flow';
import { useLanguage } from '@/hooks/useLanguage';
import { useUISchemasQuery } from '@/hooks/useUISchemasQuery';
import { useEffect } from 'react';
import { useEffect, useMemo } from 'react';

export const useUIOptionsRedirect = (state: 'success' | 'failure') => {
const { data } = useUISchemasQuery(useLanguage());
const { config } = useStateManagerContext();

const uiOptions: UIOptions | null = useMemo(() => {
// Config has priority over uiOptions in data
if (config?.uiOptions?.redirectUrls) return config.uiOptions;

if (data?.uiOptions?.redirectUrls) return data.uiOptions;

return null;
}, [data, config]);

const redirectUrls: UIOptions['redirectUrls'] | null = useMemo(() => {
if (!uiOptions) return null;

return uiOptions.redirectUrls;
}, [uiOptions]);

useEffect(() => {
if (data?.uiOptions?.redirectUrls?.[state]) {
location.href = data.uiOptions.redirectUrls?.[state] as string;
if (redirectUrls?.[state]) {
const redirectUrl = redirectUrls[state] as string;
console.info(`Collection Flow resolved to ${state}. Redirecting to ${redirectUrl}`);
location.href = redirectUrls[state] as string;
}
Comment on lines +27 to 31
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Validate redirect URLs to prevent potential security risks

Since the redirect URLs are sourced from configuration or data, there is a potential risk if these URLs are not validated. To prevent open redirect vulnerabilities, consider adding validation to ensure that the redirectUrl is an allowed domain or matches an expected pattern before performing the redirection.

}, [data, state]);
}, [redirectUrls, state]);
};
34 changes: 20 additions & 14 deletions apps/kyb-app/src/pages/CollectionFlow/CollectionFlow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,25 @@ export const useCompleteLastStep = () => {
const isPendingSync = useRef(false);

useEffect(() => {
(async () => {
void (async () => {
if (state !== 'finish') return;

const { data: context } = await refetch();
const { data: contextData } = await refetch();

if (
!context ||
context?.flowConfig?.stepsProgress?.[elements?.at(-1)?.stateName ?? '']?.isCompleted ||
!contextData ||
contextData?.context?.flowConfig?.stepsProgress?.[elements?.at(-1)?.stateName ?? '']
?.isCompleted ||
isPendingSync.current
) {
return;
}

set(context, `flowConfig.stepsProgress.${elements?.at(-1)?.stateName}.isCompleted`, true);
set(
contextData.context,
`flowConfig.stepsProgress.${elements?.at(-1)?.stateName}.isCompleted`,
true,
);
await stateApi.invokePlugin('sync_workflow_runtime');
isPendingSync.current = true;
})();
Expand All @@ -88,15 +93,15 @@ const isFailed = (state: string) => state === 'failed';
export const CollectionFlow = withSessionProtected(() => {
const { language } = useLanguageParam();
const { data: schema } = useUISchemasQuery(language);
const { data: context } = useFlowContextQuery();
const { data: contextData } = useFlowContextQuery();
const { customer } = useCustomer();
const { t } = useTranslation();
const { themeDefinition } = useTheme();

const elements = schema?.uiSchema?.elements;
const definition = schema?.definition.definition;

const pageErrors = usePageErrors(context ?? {}, elements || []);
const pageErrors = usePageErrors(contextData ?? {}, elements || []);
const isRevision = useMemo(
() => pageErrors.some(error => error.errors?.some(error => error.type === 'warning')),
[pageErrors],
Expand All @@ -108,24 +113,24 @@ export const CollectionFlow = withSessionProtected(() => {
const initialContext: CollectionFlowContext | null = useMemo(() => {
const appState =
filteredNonEmptyErrors?.[0]?.stateName ||
context?.flowConfig?.appState ||
contextData?.context?.flowConfig?.appState ||
elements?.at(0)?.stateName;

if (!appState) return null;

return {
...context,
...contextData?.context,
flowConfig: {
...context?.flowConfig,
...contextData?.context?.flowConfig,
appState,
},
state: appState,
};
}, [context, elements, filteredNonEmptyErrors]);
}, [contextData, elements, filteredNonEmptyErrors]);

const initialUIState = useMemo(() => {
return prepareInitialUIState(elements || [], context || {}, isRevision);
}, [elements, context, isRevision]);
return prepareInitialUIState(elements || [], contextData?.context || {}, isRevision);
}, [elements, contextData, isRevision]);

// Breadcrumbs now using scrollIntoView method to make sure that breadcrumb is always in viewport.
// Due to dynamic dimensions of logo it doesnt work well if scroll happens before logo is loaded.
Expand All @@ -143,14 +148,15 @@ export const CollectionFlow = withSessionProtected(() => {

if (initialContext?.flowConfig?.appState == 'rejected') return <Rejected />;

return definition && context ? (
return definition && contextData ? (
<DynamicUI initialState={initialUIState}>
<DynamicUI.StateManager
initialContext={initialContext}
workflowId="1"
definitionType={schema?.definition.definitionType}
extensions={schema?.definition.extensions}
definition={definition as State}
config={contextData?.config}
>
{({ state, stateApi }) => {
// Temp state, has to be resolved to success or failure by plugins
Expand Down
2 changes: 1 addition & 1 deletion services/workflows-service/prisma/data-migrations
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class ColectionFlowController {
async getContext(@TokenScope() tokenScope: ITokenScope) {
return await this.workflowService.getWorkflowRuntimeDataById(
tokenScope.workflowRuntimeDataId,
{ select: { context: true, state: true } },
{ select: { context: true, state: true, config: true } },
[tokenScope.projectId],
);
}
Expand Down
10 changes: 9 additions & 1 deletion services/workflows-service/src/workflow/schemas/zod-schemas.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SubscriptionSchema } from '@/common/types';
import { z } from 'zod';
import { WorkflowDefinitionConfigThemeSchema } from '@ballerine/common';
import { z } from 'zod';

export const ConfigSchema = z
.object({
Expand Down Expand Up @@ -63,6 +63,14 @@ export const ConfigSchema = z
maxBusinessReports: z.number().nonnegative().optional(),
isMerchantMonitoringEnabled: z.boolean().optional(),
isChatbotEnabled: z.boolean().optional(),
uiOptions: z
.object({
redirectUrls: z.object({
success: z.string().url().optional(),
failure: z.string().url().optional(),
}),
})
.optional(),
})
.strict()
.optional();
Expand Down
Loading