import { CONSTANTS } from "../constants"; import type { EndpointOverrides, NetworkClient, SsoInitResponse } from "../types"; import { joinUrl } from "../utils/url"; export class SsoClient { constructor( private readonly fetcher: NetworkClient, private readonly ssoUrl: string, private readonly endpoints: EndpointOverrides = {} ) {} async init(apiKey: string): Promise { const response = await this.fetcher( joinUrl(this.ssoUrl, this.endpoints.init ?? CONSTANTS.defaultPaths.init), { method: "POST", headers: { ...CONSTANTS.requestHeaders, "Content-Type": "application/json", }, body: JSON.stringify({ apiKey }), } ); if (!response.ok) { throw new Error(`SSO init failed: ${response.status} ${await response.text()}`); } return (await response.json()) as SsoInitResponse; } async refresh(jwt: string): Promise { const response = await this.fetcher( joinUrl(this.ssoUrl, this.endpoints.refresh ?? CONSTANTS.defaultPaths.refresh), { method: "POST", headers: { ...CONSTANTS.requestHeaders, "Content-Type": "application/json", }, body: JSON.stringify({ jwt }), } ); if (!response.ok) { return null; } const payload = (await response.json()) as { jwt?: string }; return payload.jwt ?? null; } }