Files
impost/example-app/server/api/pow/challenge.post.ts
2025-11-28 14:53:06 -06:00

52 lines
1.5 KiB
TypeScript

import { defineEventHandler } from 'h3'
import { validate_challenge } from '@impost/lib/validator';
import * as z from 'zod';
import { outstandingChallenges } from '~~/server/utils/pow';
const challengeSchema = z.object({
salt: z.string(),
// either a string if the algorithm is kCTF, or a number if the algorithm is Argon2 or SHA256
solution: z.string().or(z.number()),
})
// post handler that takes in the challenge, and the nonce
export default defineEventHandler(async (event) => {
const body = await readValidatedBody(event, challengeSchema.safeParse);
if (!body.success) {
throw createError({
statusCode: 400,
statusMessage: 'Validation failed'
})
}
let { salt, solution } = body.data;
const outstanding_challenge = outstandingChallenges.get(salt);
if (outstanding_challenge === undefined) {
throw createError({
statusCode: 400,
statusMessage: 'Challenge not found'
})
}
// check if the challenge is valid
const challenge_valid = await validate_challenge(outstanding_challenge.challenge, solution);
console.log("CHALLENGE VALID", challenge_valid);
if (challenge_valid) {
// clear the challenge
clearTimeout(outstandingChallenges.get(salt)!.timeout);
outstandingChallenges.delete(salt);
return {
message: 'Challenge solved'
};
}
throw createError({
statusCode: 400,
statusMessage: 'Challenge is not valid'
})
})