Spaces:
Sleeping
Sleeping
File size: 1,202 Bytes
f152ae2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import { argon2Verify } from "hash-wasm";
import { RateLimiterMemory } from "rate-limiter-flexible";
import { getSearchToken } from "./searchToken";
import { addVerifiedToken, isVerifiedToken } from "./verifiedTokens";
const rateLimiter = new RateLimiterMemory({
points: 2,
duration: 10,
});
export async function verifyTokenAndRateLimit(token: string | null): Promise<{
isAuthorized: boolean;
statusCode?: number;
error?: string;
}> {
if (!token) {
return {
isAuthorized: false,
statusCode: 401,
error: "Missing or invalid token",
};
}
if (!isVerifiedToken(token)) {
let isValidToken = false;
try {
isValidToken = await argon2Verify({
password: getSearchToken(),
hash: token,
});
} catch (error) {
void error;
}
if (isValidToken) {
addVerifiedToken(token);
} else {
return {
isAuthorized: false,
statusCode: 401,
error: "Unauthorized.",
};
}
}
try {
await rateLimiter.consume(token);
} catch {
return {
isAuthorized: false,
statusCode: 429,
error: "Too many requests.",
};
}
return { isAuthorized: true };
}
|