File size: 1,192 Bytes
7a4c980
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { decodeBase64 } from "@std/encoding/base64";
import { Aes } from "crypto/aes.ts";
import { Ecb, Padding } from "crypto/block-modes.ts";
import type { Config } from "./config.ts";

export const verifyRequest = (
    stringToCheck: string,
    videoId: string,
    config: Config,
): boolean => {
    try {
        const decipher = new Ecb(
            Aes,
            new TextEncoder().encode(config.server.secret_key),
            Padding.PKCS7,
        );

        const encryptedData = new TextDecoder().decode(
            decipher.decrypt(
                decodeBase64(
                    stringToCheck.replace(/-/g, "+").replace(/_/g, "/"),
                ),
            ),
        );
        const [parsedTimestamp, parsedVideoId] = encryptedData.split("|");
        const parsedTimestampInt = parseInt(parsedTimestamp);
        const timestampNow = Math.round(+new Date() / 1000);
        if (parsedVideoId !== videoId) {
            return false;
        }
        // only allow ID to live for 6 hours
        if ((timestampNow + 6 * 60 * 60) - parsedTimestampInt < 0) {
            return false;
        }
    } catch (_) {
        return false;
    }
    return true;
};