Files
impost/example-app/server/api/pow/challenge.post.ts
Zoe 9ba5b12dac Clean up code. Reorganize files. Port stuff from other branches. + more
This turns the project into a monorepo using pnpm workspaces,
dramatically simplifying the build process. It also fixes a lot of bugs
and just generally makes the codebase a lot cleaner.
2025-12-04 18:48:00 -06:00

48 lines
1.4 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({
challenge: z.string(),
nonce: z.string()
})
// 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) {
const errors = z.treeifyError(body.error);
const error_message = Object.entries(errors.errors).map(([key, value]) => `${key}: ${value}`).join('\n');
throw createError({
statusCode: 400,
statusMessage: error_message
})
}
let { challenge, nonce } = body.data;
const outstanding_challenge = outstandingChallenges.get(body.data.challenge)!;
// always delete the challenge on a solve attempt
clearTimeout(outstanding_challenge.timeout);
outstandingChallenges.delete(challenge);
// check if the challenge is valid
let challenge_valid = await validate_challenge(outstandingChallenges.get(challenge)!.challenge, {
challenge,
nonce,
});
if (challenge_valid) {
return {
message: 'Challenge solved'
};
}
throw createError({
statusCode: 400,
statusMessage: 'Challenge is not valid'
})
})