diff --git a/packages/api-client/src/internal/session.ts b/packages/api-client/src/internal/session.ts index 7a709701..96219aee 100644 --- a/packages/api-client/src/internal/session.ts +++ b/packages/api-client/src/internal/session.ts @@ -1,29 +1,32 @@ import { CobaltSession, CobaltResponseType, CobaltSessionResponse } from "../types/response"; import { CobaltReachabilityError } from "../types/errors"; import type { TurnstileObject } from "turnstile-types"; +import { CobaltAPIClient } from "../types/interface"; const currentTime = () => Math.floor(new Date().getTime() / 1000); const EXPIRY_THRESHOLD_SECONDS = 2; export default class CobaltSessionHandler { - #baseURL: string; + #client: CobaltAPIClient; #turnstile: TurnstileObject; #session: CobaltSession | undefined; - constructor(baseURL: string, turnstile: TurnstileObject) { - this.#baseURL = baseURL; + constructor(client: CobaltAPIClient, turnstile: TurnstileObject) { + this.#client = client; this.#turnstile = turnstile; } async #requestSession(): Promise { - const endpoint = new URL('/session', this.#baseURL); + const baseURL = this.#client.getBaseURL(); + if (!baseURL) throw "baseURL is undefined"; + const endpoint = new URL('/session', baseURL); const response = await fetch(endpoint, { method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(10000), headers: { - 'cf-turnstile-response': this.#turnstile.getResponse('turnstile-widget') + 'cf-turnstile-response': this.#turnstile.getResponse('#turnstile-widget') } }) .then(r => r.json()) @@ -46,7 +49,7 @@ export default class CobaltSessionHandler { } } - this.#turnstile.reset('turnstile-widget'); + this.#turnstile.reset('#turnstile-widget'); return response; } @@ -55,6 +58,10 @@ export default class CobaltSessionHandler { return this.#session && this.#session.exp - EXPIRY_THRESHOLD_SECONDS > currentTime(); } + reset() { + this.#session = undefined; + } + async getSession(): Promise { if (this.hasSession()) { return this.#session!;