Created
April 22, 2020 20:46
-
-
Save Fyko/79ce8606c7331f39b7487f03dd36921b to your computer and use it in GitHub Desktop.
util function for verifiying hcaptcha token, sorry dom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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