@kanadi/core
Version:
Multi-Layer CAPTCHA Framework with customizable validators and challenge bundles
63 lines (52 loc) • 1.4 kB
text/typescript
import { randomBytes } from "crypto";
import type { IChallengeValidator } from "../middleware";
import type { IBundle } from "./types";
export class Bundle implements IBundle {
public id: string;
private validators: Map<
string,
{ validatorId: string; validator: IChallengeValidator; data: any }
> = new Map();
private published: boolean = false;
constructor(bundleId: string) {
this.id = bundleId;
}
async add(validatorId: string, data: any): Promise<void> {
if (this.published) {
throw new Error("Cannot add validators to a published bundle");
}
const validatorSessionId = this.generateValidatorSessionId();
this.validators.set(validatorSessionId, {
validatorId,
validator: null as any,
data,
});
}
registerValidator(
validatorSessionId: string,
validator: IChallengeValidator,
): void {
const existing = this.validators.get(validatorSessionId);
if (existing) {
existing.validator = validator;
}
}
async publish(): Promise<void> {
if (this.published) {
throw new Error("Bundle already published");
}
this.published = true;
}
getValidators(): Map<
string,
{ validatorId: string; validator: IChallengeValidator; data: any }
> {
return this.validators;
}
isPublished(): boolean {
return this.published;
}
private generateValidatorSessionId(): string {
return randomBytes(8).toString("hex").toUpperCase();
}
}