aboutsummaryrefslogtreecommitdiffstats
path: root/src/middleware.ts
blob: 46d6e002e929e4b0fb935cb297e7de8040470f9f (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { Request, Response } from "@tinyhttp/app";
import { Context } from "telegraf";
import got from "got";
import jwt from "jsonwebtoken";

import { getPermittedUsers } from "./db";
import config from "./config";

const tgAuth = async (ctx: Context, next: () => Promise<void>): Promise<void> => {
  const userId = ctx.message?.from.id;

  const tgUsers = await getPermittedUsers();
  const tgUserIds = tgUsers.map(u => u.id);

  if (!userId || !tgUserIds.includes(userId)) {
    ctx.reply("Käyttäjälläsi ei ole oikeuksia startata HommaBottia.");
  } else {
    await next();
  }
};

const verifyGoogleJWT = async (req: Request, res: Response, next: () => void): Promise<void> => {
  if (config.nodeEnv !== "production") {
    next();
    return;
  }

  const authHeader = req.headers.authorization || null;
  if (!authHeader) {
    res.sendStatus(401);
    return;
  }

  const token = authHeader.split(" ")[1];
  if (!token) {
    res.sendStatus(401);
    return;
  }

  const decoded = jwt.decode(token, { complete: true });
  if (!decoded) {
    res.sendStatus(401);
    return;
  }

  const kid: string = decoded.header.kid;

  const response = await got("https://www.googleapis.com/oauth2/v1/certs", { json: true });
  const googleCerts: Record<string, string> = response.body;

  const cert = googleCerts[kid];
  if (!cert) {
    console.error("KID not found in google certificates");
    res.sendStatus(500);
    return;
  }

  try {
    jwt.verify(token, cert);
  } catch (err) {
    res.sendStatus(403);
    return;
  }

  next();
};

export const tgMiddleware = {
  tgAuth,
};

export const httpMiddleware = {
  verifyGoogleJWT,
};