diff --git a/packages/api-client/src/turnstile-api.ts b/packages/api-client/src/turnstile-api.ts new file mode 100644 index 00000000..9a7cabb7 --- /dev/null +++ b/packages/api-client/src/turnstile-api.ts @@ -0,0 +1,28 @@ +import CobaltSessionHandler from "./internal/session"; +import BaseCobaltAPI from "./internal/base-api"; +import { CobaltRequest } from "./types/request"; +import { CobaltAuthError } from "./types/errors"; + +export default class TurnstileCobaltAPI extends BaseCobaltAPI { + #session: CobaltSessionHandler; + + constructor(baseURL: string) { + super(baseURL); + this.#session = new CobaltSessionHandler(baseURL); + } + + async request(data: CobaltRequest, turnstileResponse?: string) { + const sessionOrError = await this.#session.getSession(turnstileResponse); + const headers: Record = {}; + + if ("error" in sessionOrError) { + if (sessionOrError.error.code !== CobaltAuthError.NotConfigured) { + return sessionOrError; + } + } else { + headers['Authorization'] = `Bearer ${sessionOrError.token}`; + } + + return super._request(data, headers); + } +} diff --git a/packages/api-client/src/types/errors.ts b/packages/api-client/src/types/errors.ts index ef09ce0a..d91bdd5d 100644 --- a/packages/api-client/src/types/errors.ts +++ b/packages/api-client/src/types/errors.ts @@ -1,4 +1,5 @@ export enum CobaltAuthError { + NotConfigured = 'error.api.auth.not_configured', JWTMissing = 'error.api.auth.jwt.missing', JWTInvalid = 'error.api.auth.jwt.invalid', TurnstileMissing = 'error.api.auth.turnstile.missing', diff --git a/packages/api-client/src/types/interface.ts b/packages/api-client/src/types/interface.ts new file mode 100644 index 00000000..8bea525c --- /dev/null +++ b/packages/api-client/src/types/interface.ts @@ -0,0 +1,6 @@ +import { CobaltRequest } from "./request"; +import { CobaltResponse } from "./response"; + +export interface CobaltAPIClient { + request(data: CobaltRequest): Promise; +} diff --git a/packages/api-client/src/unauthenticated-api.ts b/packages/api-client/src/unauthenticated-api.ts new file mode 100644 index 00000000..cf656ef8 --- /dev/null +++ b/packages/api-client/src/unauthenticated-api.ts @@ -0,0 +1,13 @@ +import BaseCobaltAPI from "./internal/base-api"; +import { CobaltRequest } from "./types/request"; +import { CobaltAPIClient } from "./types/interface"; + +export default class UnauthenticatedCobaltAPI extends BaseCobaltAPI implements CobaltAPIClient { + constructor(baseURL: string, userAgent?: string) { + super(baseURL, userAgent); + } + + async request(data: CobaltRequest) { + return super._request(data, {}); + } +}