19 lines
589 B
TypeScript
19 lines
589 B
TypeScript
import type { MiddlewareHandler } from 'hono';
|
|
import { env } from './env.ts';
|
|
|
|
// 常量时间比较,防 timing attack
|
|
const safeEqual = (a: string, b: string): boolean => {
|
|
if (a.length !== b.length) return false;
|
|
let diff = 0;
|
|
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
return diff === 0;
|
|
};
|
|
|
|
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
|
const header = c.req.header('X-Sandbox-Secret');
|
|
if (!header || !safeEqual(header, env.orchSecret)) {
|
|
return c.json({ error: 'unauthorized' }, 401);
|
|
}
|
|
await next();
|
|
};
|