File size: 796 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export interface Env {
  WORKER_FORWARD_URL: string;
  WORKER_SHARED_SECRET: string;
  TELEGRAM_WEBHOOK_SECRET: string;
}

export async function timingSafeEqualText(left: string, right: string): Promise<boolean> {
  const encoder = new TextEncoder();
  const a = encoder.encode(left || "");
  const b = encoder.encode(right || "");
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let index = 0; index < a.length; index += 1) {
    diff |= a[index] ^ b[index];
  }
  return diff === 0;
}

export async function validateTelegramSecret(request: Request, env: Env): Promise<boolean> {
  if (!env.TELEGRAM_WEBHOOK_SECRET) return true;
  const header = request.headers.get("x-telegram-bot-api-secret-token") || "";
  return timingSafeEqualText(header, env.TELEGRAM_WEBHOOK_SECRET);
}