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

fix(auth): patches fetch to retry on cloudflare challenge #909

Merged
merged 1 commit into from
Feb 26, 2025
Merged
Changes from all commits
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
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