File size: 1,703 Bytes
43a06dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import turnstile from "$lib/api/turnstile";
import { currentApiURL } from "$lib/api/api-url";

import type { CobaltSession, CobaltErrorResponse, CobaltSessionResponse } from "$lib/types/api";

let cache: CobaltSession | undefined;

export const requestSession = async () => {
    const apiEndpoint = `${currentApiURL()}/session`;

    let requestHeaders = {};

    const turnstileResponse = turnstile.getResponse();
    if (turnstileResponse) {
        requestHeaders = {
            "cf-turnstile-response": turnstileResponse
        };
    }

    const response: CobaltSessionResponse = await fetch(apiEndpoint, {
        method: "POST",
        redirect: "manual",
        signal: AbortSignal.timeout(10000),
        headers: requestHeaders,
    })
    .then(r => r.json())
    .catch((e) => {
        if (e?.message?.includes("timed out")) {
            return {
                status: "error",
                error: {
                    code: "error.api.timed_out"
                }
            } as CobaltErrorResponse
        }
    });

    turnstile.reset();

    return response;
}

export const getSession = async () => {
    const currentTime = () => Math.floor(new Date().getTime() / 1000);

    if (cache?.token && cache?.exp - 2 > currentTime()) {
        return cache;
    }

    const newSession = await requestSession();

    if (!newSession) return {
        status: "error",
        error: {
            code: "error.api.unreachable"
        }
    } as CobaltErrorResponse

    if (!("status" in newSession)) {
        newSession.exp = currentTime() + newSession.exp;
        cache = newSession;
    }
    return newSession;
}

export const resetSession = () => cache = undefined;