Skip to content

Instantly share code, notes, and snippets.

@Fyko
Created April 22, 2020 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fyko/79ce8606c7331f39b7487f03dd36921b to your computer and use it in GitHub Desktop.
Save Fyko/79ce8606c7331f39b7487f03dd36921b to your computer and use it in GitHub Desktop.
util function for verifiying hcaptcha token, sorry dom
import fetch from 'node-fetch';
import qs from 'querystring';
enum ErrorCode {
'missing-input-secret' = 'Your secret key is missing.',
'invalid-input-secret' = 'Your secret key is invalid or malformed.',
'missing-input-response' = 'The response parameter (verification token) is missing.',
'invalid-input-response' = 'The response parameter (verification token) is invalid or malformed.',
'bad-request' = 'The request is invalid or malformed.',
'invalid-or-already-seen-response' = 'The response parameter has already been checked, or has another issue.',
'sitekey-secret-mismatch' = 'The sitekey is not registered with the provided secret.',
}
export interface VerifyResponse {
success: boolean;
challenge_ts: number;
hostname: string;
credit: boolean;
'error-codes': (keyof typeof ErrorCode)[];
}
export interface ErrorResponse {
errors: typeof ErrorCode[keyof typeof ErrorCode][];
}
export async function verify(secret: string, response: string): Promise<VerifyResponse | ErrorResponse> {
const query = qs.stringify({ secret, response });
const res = await fetch(`https://hcaptcha.com/siteverify?${query}`, {
method: 'POST',
});
const json: VerifyResponse = await res.json();
if (json['error-codes'].length) return { errors: json['error-codes'].map(e => ErrorCode[e]) };
return json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment