forked from Yara724/api
44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
import { Injectable } from "@nestjs/common";
|
|
import { ConfigService } from "@nestjs/config";
|
|
import * as svgCaptcha from "svg-captcha";
|
|
|
|
export interface GeneratedCaptcha {
|
|
text: string;
|
|
image: string;
|
|
expiresAt: number;
|
|
}
|
|
|
|
@Injectable()
|
|
export class CaptchaService {
|
|
generate(): GeneratedCaptcha {
|
|
const captcha = svgCaptcha.create({
|
|
size: 5,
|
|
ignoreChars: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
|
noise: 1,
|
|
color: false,
|
|
background: "#f8fafc",
|
|
width: 160,
|
|
height: 56,
|
|
fontSize: 52,
|
|
});
|
|
|
|
return {
|
|
text: captcha.text,
|
|
image: `data:image/svg+xml;base64,${Buffer.from(captcha.data, "utf8").toString("base64")}`,
|
|
expiresAt: this.buildExpireAt(),
|
|
};
|
|
}
|
|
|
|
normalizeAnswer(input: string): string {
|
|
return input.trim().toLowerCase();
|
|
}
|
|
|
|
buildExpireAt(): number {
|
|
const raw = Number(
|
|
process.env.EXP_CAPTCHA_TIME ?? process.env.EXP_OTP_TIME ?? "2",
|
|
);
|
|
const minutes = Number.isFinite(raw) && raw > 0 ? raw : 2;
|
|
return Date.now() + minutes * 60 * 1000;
|
|
}
|
|
}
|