35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
import { api } from './api'
|
|
|
|
interface Challenge {
|
|
algorithm: string
|
|
challenge: string
|
|
maxnumber: number
|
|
salt: string
|
|
signature: string
|
|
}
|
|
|
|
async function hashHex(algorithm: string, data: string): Promise<string> {
|
|
const alg = algorithm.replace('-', '').toUpperCase() === 'SHA256' ? 'SHA-256' : algorithm
|
|
const buf = await crypto.subtle.digest(alg, new TextEncoder().encode(data))
|
|
return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('')
|
|
}
|
|
|
|
export async function solveAltcha(difficulty: 'normal' | 'light' = 'normal'): Promise<string> {
|
|
const ch = await api.get<Challenge>(`/altcha/challenge?difficulty=${difficulty}`)
|
|
|
|
for (let n = 0; n <= ch.maxnumber; n++) {
|
|
const hash = await hashHex(ch.algorithm, ch.salt + n)
|
|
if (hash === ch.challenge) {
|
|
return btoa(JSON.stringify({
|
|
algorithm: ch.algorithm,
|
|
challenge: ch.challenge,
|
|
number: n,
|
|
salt: ch.salt,
|
|
signature: ch.signature,
|
|
}))
|
|
}
|
|
}
|
|
|
|
throw new Error('Failed to solve challenge')
|
|
}
|