Skip to content

Commit

Permalink
fix(clerk-js): Block /tokens requests until fraud detection completes (
Browse files Browse the repository at this point in the history
  • Loading branch information
nikosdouvlis authored Nov 18, 2024
1 parent afcc517 commit ba97f62
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
25 changes: 25 additions & 0 deletions packages/clerk-js/src/core/fraudProtection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* TODO: @nikos Move captcha and fraud detection logic to this class
*/
class FraudProtectionService {
private inflightRequest: Promise<unknown> | null = null;

public async execute<T extends () => Promise<any>>(cb: T): Promise<Awaited<ReturnType<T>>> {
if (this.inflightRequest) {
await this.inflightRequest;
}

const prom = cb();
this.inflightRequest = prom;
return prom.then(res => {
this.inflightRequest = null;
return res;
});
}

public blockUntilReady() {
return this.inflightRequest ? this.inflightRequest.then(() => null) : Promise.resolve();
}
}

export const fraudProtection = new FraudProtectionService();
15 changes: 9 additions & 6 deletions packages/clerk-js/src/core/resources/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { getCaptchaToken, retrieveCaptchaInfo } from '../../utils/captcha';
import { unixEpochToDate } from '../../utils/date';
import { clerkInvalidStrategy } from '../errors';
import { eventBus, events } from '../events';
import { fraudProtection } from '../fraudProtection';
import { SessionTokenCache } from '../tokenCache';
import { BaseResource, PublicUserData, Token, User } from './internal';
import { SessionVerification } from './SessionVerification';
Expand Down Expand Up @@ -272,16 +273,18 @@ export class Session extends BaseResource implements SessionResource {
// TODO: update template endpoint to accept organizationId
const params: Record<string, string | null> = template ? {} : { organizationId };

await fraudProtection.blockUntilReady();

const createTokenWithCaptchaProtection = async () => {
try {
return await Token.create(path, params);
} catch (e) {
return Token.create(path, params).catch(e => {
if (isClerkAPIResponseError(e) && e.errors[0].code === 'requires_captcha') {
const captchaParams = await this.#triggerCaptchaChallenge();
return Token.create(path, { ...params, ...captchaParams });
return fraudProtection.execute(async () => {
const captchaParams = await this.#triggerCaptchaChallenge();
return Token.create(path, { ...params, ...captchaParams });
});
}
throw e;
}
});
};

const tokenResolver = createTokenWithCaptchaProtection();
Expand Down

0 comments on commit ba97f62

Please sign in to comment.