Spaces:
Sleeping
Sleeping
File size: 1,164 Bytes
6b3405c |
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 |
import { PreviewServer, ViteDevServer } from "vite";
import { argon2Verify } from "hash-wasm";
export function validateAccessKeyServerHook<
T extends ViteDevServer | PreviewServer,
>(server: T) {
server.middlewares.use(async (req, res, next) => {
if (req.url !== "/api/validate-access-key" || req.method !== "POST") {
return next();
}
const accessKeys = process.env.ACCESS_KEYS?.split(",") ?? [];
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", async () => {
try {
const { accessKeyHash } = JSON.parse(body);
let isValid = false;
for (const key of accessKeys) {
try {
if (await argon2Verify({ password: key, hash: accessKeyHash })) {
isValid = true;
break;
}
} catch {
continue;
}
}
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ valid: isValid }));
} catch {
res.statusCode = 400;
res.end(JSON.stringify({ valid: false, error: "Invalid request" }));
}
});
});
}
|