Skip to content

Commit

Permalink
fix(WebPoMinter): Throw an error if no integrity token is provided
Browse files Browse the repository at this point in the history
  • Loading branch information
LuanRT committed Jan 5, 2025
1 parent fd3e597 commit c07aea9
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 21 deletions.
17 changes: 9 additions & 8 deletions src/core/botGuardClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { BotGuardClientOptions, SnapshotArgs, VMFunctions } from '../utils/types.js';
import { BGError } from '../utils/index.js';

export default class BotGuardClient {
public vm: Record<string, any>;
Expand All @@ -24,10 +25,10 @@ export default class BotGuardClient {

private async load() {
if (!this.vm)
throw new Error('[BotGuardClient]: VM not found in the global object');
throw new BGError('[BotGuardClient]: VM not found in the global object');

if (!this.vm.a)
throw new Error('[BotGuardClient]: Could not load program');
throw new BGError('[BotGuardClient]: Could not load program');

const vmFunctionsCallback = (
asyncSnapshotFunction: VMFunctions['asyncSnapshotFunction'],
Expand All @@ -41,7 +42,7 @@ export default class BotGuardClient {
try {
this.syncSnapshotFunction = await this.vm.a(this.program, vmFunctionsCallback, true, this.userInteractionElement, () => {/** no-op */ }, [ [], [] ])[0];
} catch (error) {
throw new Error(`[BotGuardClient]: Failed to load program (${(error as Error).message})`);
throw new BGError(`[BotGuardClient]: Failed to load program (${(error as Error).message})`);
}

return this;
Expand All @@ -66,7 +67,7 @@ export default class BotGuardClient {
public async snapshot(args: SnapshotArgs): Promise<string> {
return new Promise((resolve, reject) => {
if (!this.vmFunctions.asyncSnapshotFunction)
return reject(new Error('[BotGuardClient]: Async snapshot function not found'));
return reject(new BGError('[BotGuardClient]: Async snapshot function not found'));

this.vmFunctions.asyncSnapshotFunction((response) => resolve(response), [
args.contentBinding,
Expand All @@ -84,7 +85,7 @@ export default class BotGuardClient {
*/
public async snapshotSynchronous(args: SnapshotArgs): Promise<string> {
if (!this.syncSnapshotFunction)
throw new Error('[BotGuardClient]: Sync snapshot function not found');
throw new BGError('[BotGuardClient]: Sync snapshot function not found');

return this.syncSnapshotFunction([
args.contentBinding,
Expand All @@ -100,7 +101,7 @@ export default class BotGuardClient {
*/
public passEvent(args: unknown): void {
if (!this.vmFunctions.passEventFunction)
throw new Error('[BotGuardClient]: Pass event function not found');
throw new BGError('[BotGuardClient]: Pass event function not found');
this.vmFunctions.passEventFunction(args);
}

Expand All @@ -110,7 +111,7 @@ export default class BotGuardClient {
*/
public checkCamera(args: unknown): void {
if (!this.vmFunctions.checkCameraFunction)
throw new Error('[BotGuardClient]: Check camera function not found');
throw new BGError('[BotGuardClient]: Check camera function not found');
this.vmFunctions.checkCameraFunction(args);
}

Expand All @@ -120,7 +121,7 @@ export default class BotGuardClient {
*/
public shutdown(): void {
if (!this.vmFunctions.shutdownFunction)
throw new Error('[BotGuardClient]: Shutdown function not found');
throw new BGError('[BotGuardClient]: Shutdown function not found');
this.vmFunctions.shutdownFunction();
}
}
6 changes: 3 additions & 3 deletions src/core/challengeFetcher.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { base64ToU8, buildURL, getHeaders } from '../utils/index.js';
import { base64ToU8, BGError, buildURL, getHeaders } from '../utils/index.js';
import type { DescrambledChallenge, BgConfig } from '../utils/index.js';

/**
Expand All @@ -12,7 +12,7 @@ export async function create(bgConfig: BgConfig, interpreterHash?: string): Prom
const requestKey = bgConfig.requestKey;

if (!bgConfig.fetch)
throw new Error('[Challenge]: Fetch function not provided');
throw new BGError('[Challenge]: Fetch function not provided');

const payload = [ requestKey ];

Expand All @@ -26,7 +26,7 @@ export async function create(bgConfig: BgConfig, interpreterHash?: string): Prom
});

if (!response.ok)
throw new Error(`[Challenge]: Failed to fetch challenge: ${response.status}`);
throw new BGError('[Challenge]: Failed to fetch challenge', { status: response.status });

const rawData = await response.json() as unknown[];

Expand Down
6 changes: 3 additions & 3 deletions src/core/webPoClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import BotGuardClient from './botGuardClient.js';
import WebPoMinter from './webPoMinter.js';
import { base64ToU8, buildURL, u8ToBase64, getHeaders } from '../utils/index.js';
import { base64ToU8, buildURL, u8ToBase64, getHeaders, BGError } from '../utils/index.js';
import type { PoTokenArgs, PoTokenResult, WebPoSignalOutput } from '../utils/index.js';

/**
Expand Down Expand Up @@ -51,7 +51,7 @@ export function generatePlaceholder(identifier: string, clientState?: number): s
const encodedIdentifier = new TextEncoder().encode(identifier);

if (encodedIdentifier.length > 118)
throw new Error('DFO:Invalid');
throw new BGError('DFO:Invalid', { identifier });

const timestamp = Math.floor(Date.now() / 1000);
const randomKeys = [ Math.floor(Math.random() * 256), Math.floor(Math.random() * 256) ];
Expand Down Expand Up @@ -101,7 +101,7 @@ export function decodePlaceholder(placeholder: string) {
const totalPacketLength = 2 + payloadLength;

if (packet.length !== totalPacketLength)
throw new Error('Invalid packet length.');
throw new BGError('Invalid packet length.', { packetLength: packet.length, expectedLength: totalPacketLength });

const payload = packet.subarray(2);

Expand Down
17 changes: 10 additions & 7 deletions src/core/webPoMinter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { base64ToU8, u8ToBase64 } from '../utils/helpers.js';
import { base64ToU8, BGError, u8ToBase64 } from '../utils/helpers.js';
import type { IntegrityTokenData, MintCallback, WebPoSignalOutput } from '../utils/types.js';

export default class WebPoMinter {
Expand All @@ -12,12 +12,15 @@ export default class WebPoMinter {
const getMinter = webPoSignalOutput[0];

if (!getMinter)
throw new Error('PMD:Undefined');

const mintCallback = await getMinter(base64ToU8(integrityTokenResponse.integrityToken ?? ''));
throw new BGError('PMD:Undefined');

if (!integrityTokenResponse.integrityToken)
throw new BGError('Failed to create WebPoMinter: No integrity token provided', integrityTokenResponse);

const mintCallback = await getMinter(base64ToU8(integrityTokenResponse.integrityToken));

if (!(mintCallback instanceof Function))
throw new Error('APF:Failed');
throw new BGError('APF:Failed');

return new WebPoMinter(mintCallback);
}
Expand All @@ -31,10 +34,10 @@ export default class WebPoMinter {
const result = await this.mintCallback(new TextEncoder().encode(identifier));

if (!result)
throw new Error('YNJ:Undefined');
throw new BGError('YNJ:Undefined');

if (!(result instanceof Uint8Array))
throw new Error('ODM:Invalid');
throw new BGError('ODM:Invalid');

return result;
}
Expand Down
11 changes: 11 additions & 0 deletions src/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ const base64urlToBase64Map = {
'.': '='
};

export class BGError extends TypeError {
public info?: any;

constructor(message: string, info?: Record<string, any>) {
super(message);
this.name = 'BGError';
if (info)
this.info = info;
}
}

export function base64ToU8(base64: string): Uint8Array {
let base64Mod;

Expand Down

0 comments on commit c07aea9

Please sign in to comment.