perfow-captcha-client
v0.1.0
Published
Client library for interacting with perfow-captcha-server
Maintainers
Readme
perfow-captcha-client
A frontend JavaScript/TypeScript library for interacting with a perfow-captcha-client-server (or compatible) instance.
This library handles fetching Proof-of-Work (PoW) challenges, solving them efficiently using Web Workers without blocking the main thread, and verifying the solution with the server.
Features
- Fetches CAPTCHA challenges from the server.
- Solves SHA-256 based PoW challenges in a Web Worker.
- Verifies the found solution (nonce) with the server.
- Provides a simple Promise-based API.
- Written in TypeScript, providing type definitions.
Installation
npm install perfow-captcha-client
# or
yarn add perfow-captcha-client
# or
pnpm add perfow-captcha-clientUsage
The easiest way to use the library is via the solveAndVerifyCaptcha convenience function.
import { solveAndVerifyCaptcha } from "perfow-captcha-client";
// Assuming you have an async function context
async function handleFormSubmit() {
const captchaServerUrl = "http://localhost:8080"; // Your CAPTCHA server URL
try {
console.log("Starting CAPTCHA process...");
const result = await solveAndVerifyCaptcha(captchaServerUrl);
if (result.success) {
console.log("CAPTCHA verification successful!");
// Proceed with form submission or other action
} else {
console.error("CAPTCHA verification failed:", result.message);
// Handle verification failure (e.g., show error to user)
}
} catch (error) {
console.error("An error occurred during the CAPTCHA process:", error);
// Handle errors (network, solving timeout, etc.)
}
}
// Example of triggering it
// const submitButton = document.getElementById('submit-button');
// submitButton.addEventListener('click', handleFormSubmit);Using the Class directly
For more control over the process (e.g., displaying progress), you can use the PerfowCaptchaClient class directly:
import { PerfowCaptchaClient } from "perfow-captcha-client";
// Note: The standalone solveChallenge function is not exported by default,
// but you could modify index.ts to export it if needed for advanced scenarios.
async function solveManually() {
const captchaServerUrl = "http://localhost:8080";
const client = new PerfowCaptchaClient(captchaServerUrl);
try {
console.log("Fetching challenge...");
const challengeData = await client.fetchChallenge();
console.log("Challenge data received:", challengeData);
// You might want to import and use solveChallenge directly here if exposed
// Or implement your own worker interaction logic if needed.
// For this example, we assume solveAndVerifyCaptcha's internal logic
// which uses the unexported solveChallenge.
// A practical direct usage might involve getting challenge data
// then passing it to a UI component that handles solving.
// Hypothetical example if solveChallenge was exported:
/*
import { solveChallenge } from 'perfow-captcha-client';
console.log('Solving challenge...');
const solutionNonce = await solveChallenge(challengeData);
console.log('Solution found:', solutionNonce);
console.log('Verifying solution...');
const verificationResult = await client.verifySolution(challengeData, solutionNonce);
console.log('Verification result:', verificationResult);
*/
alert(
"Manual solving example is conceptual. Use solveAndVerifyCaptcha for standard use."
);
} catch (error) {
console.error("Error in manual CAPTCHA flow:", error);
}
}Important: CORS Configuration
For this library to work in a browser, the perfow-captcha-client-server must be configured to accept requests from the origin where your frontend application is hosted.
This is done by adding your frontend's origin (e.g., http://localhost:3000, https://yourdomain.com) to the allowed_origins setting in the server's configuration (e.g., .env or config.toml file) and restarting the server.
Failure to configure CORS correctly will result in fetch errors in the browser's console.
API
solveAndVerifyCaptcha(serverBaseUrl: string): Promise<VerificationResult>
serverBaseUrl: The base URL of theperfow-captcha-client-server.- Returns: A Promise that resolves with a
VerificationResultobject ({ success: boolean; message?: string }). - Throws: An error if fetching, solving, or verification fails for any reason (network, server error, timeout, etc.).
PerfowCaptchaClient
constructor(serverBaseUrl: string)
- Creates a new client instance.
serverBaseUrl: The base URL of theperfow-captcha-client-server.
async fetchChallenge(): Promise<ChallengeData>
- Fetches a new challenge from the server.
- Returns: A Promise resolving with
ChallengeData({ salt: string; challenge: string; difficultyBits: number; maxNumber: number; signature: string; expires: number; }). - Throws: Error on network or server issues.
async verifySolution(originalChallenge: ChallengeData, solution: number): Promise<VerificationResult>
- Verifies a found solution with the server.
originalChallenge: TheChallengeDataobject received fromfetchChallenge.solution: Thenonce(number) found by the solver.- Returns: A Promise resolving with
VerificationResult. - Throws: Error on network or server issues, or if the server returns a non-OK status.
Development
- Clone the repository.
- Install dependencies:
npm install - Build the library:
npm run build - Run tests:
npm test - Lint code:
npm run lint - Format code:
npm run format
License
MIT
