Skip to content

Commit

Permalink
fix(auth): patches fetch to retry on cloudflare challenge
Browse files Browse the repository at this point in the history
refs #836
  • Loading branch information
ygrishajev authored Feb 26, 2025
1 parent c8399ae commit c6f4c7d
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion apps/deploy-web/src/components/turnstile/Turnstile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { managedWalletHttpService } from "@src/services/managed-wallet-http/mana

const HTTP_SERVICES = [managedWalletHttpService, services.user, services.stripe, services.tx, services.template, services.auth, services.deploymentSetting];

const originalFetch = typeof window !== "undefined" && window.fetch;

const addResponseInterceptor = (interceptor: (value: AxiosError) => AxiosResponse | Promise<AxiosResponse>) => {
const removes = HTTP_SERVICES.map(service => {
const interceptorId = service.interceptors.response.use(null, interceptor);
Expand All @@ -40,7 +42,26 @@ export const Turnstile: FC = () => {
const dismissedSubject = useRef(new Subject<void>());

useEffect(() => {
return addResponseInterceptor(async error => {
if (originalFetch) {
window.fetch = async (...args) => {
let response = await originalFetch(...args);

if (typeof args[0] === "string" && args[0].startsWith("/") && response.status > 400 && turnstileRef.current) {
turnstileRef.current?.render();
turnstileRef.current?.execute();

const turnstileResponse = await Promise.race([turnstileRef.current.getResponsePromise(), firstValueFrom(dismissedSubject.current.asObservable())]);

if (turnstileResponse) {
response = await originalFetch(...args);
}
}

return response;
};
}

const ejectInterceptors = addResponseInterceptor(async error => {
const request = error?.request;

if ((!request?.status || request?.status > 400) && turnstileRef.current) {
Expand All @@ -56,6 +77,13 @@ export const Turnstile: FC = () => {

return Promise.reject(error);
});

return () => {
ejectInterceptors();
if (originalFetch) {
window.fetch = originalFetch;
}
};
}, []);

const resetWidget = useCallback(() => {
Expand Down

0 comments on commit c6f4c7d

Please sign in to comment.