2024-11-01 21:05:54 +01:00
|
|
|
import { db } from "@versia/kit/db";
|
|
|
|
|
import { Challenges } from "@versia/kit/tables";
|
2025-06-15 04:38:20 +02:00
|
|
|
import { config } from "@versia-server/config";
|
2024-06-14 10:03:51 +02:00
|
|
|
import { createChallenge } from "altcha-lib";
|
2024-11-02 00:43:33 +01:00
|
|
|
import type { Challenge } from "altcha-lib/types";
|
2025-03-30 22:21:01 +02:00
|
|
|
import { randomUUIDv7 } from "bun";
|
2024-06-14 10:03:51 +02:00
|
|
|
|
|
|
|
|
export const generateChallenge = async (
|
2025-02-15 02:47:29 +01:00
|
|
|
maxNumber?: number,
|
2024-11-02 00:43:33 +01:00
|
|
|
): Promise<{
|
|
|
|
|
id: string;
|
|
|
|
|
challenge: Challenge;
|
|
|
|
|
expiresAt: string;
|
|
|
|
|
createdAt: string;
|
|
|
|
|
}> => {
|
2025-02-15 02:47:29 +01:00
|
|
|
if (!config.validation.challenges) {
|
|
|
|
|
throw new Error("Challenges are not enabled");
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-14 10:03:51 +02:00
|
|
|
const expirationDate = new Date(
|
|
|
|
|
Date.now() + config.validation.challenges.expiration * 1000,
|
|
|
|
|
);
|
|
|
|
|
|
2025-03-30 22:21:01 +02:00
|
|
|
const uuid = randomUUIDv7();
|
2024-06-14 10:03:51 +02:00
|
|
|
|
|
|
|
|
const challenge = await createChallenge({
|
|
|
|
|
hmacKey: config.validation.challenges.key,
|
|
|
|
|
expires: expirationDate,
|
2025-02-15 02:47:29 +01:00
|
|
|
maxNumber: maxNumber ?? config.validation.challenges.difficulty,
|
2024-06-14 10:03:51 +02:00
|
|
|
algorithm: "SHA-256",
|
|
|
|
|
params: {
|
|
|
|
|
challenge_id: uuid,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const result = (
|
|
|
|
|
await db
|
|
|
|
|
.insert(Challenges)
|
|
|
|
|
.values({
|
|
|
|
|
id: uuid,
|
|
|
|
|
challenge,
|
|
|
|
|
expiresAt: expirationDate.toISOString(),
|
|
|
|
|
})
|
|
|
|
|
.returning()
|
|
|
|
|
)[0];
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
};
|