export type RESTAuthPassword = {username: string, password: string}; export type RESTAuthToken = {token: string, state: string, redirect_endpoint: string}; export type RESTAuthData = {client_ip: string, password?: RESTAuthPassword | undefined, Token?: RESTAuthToken | undefined}; export type CreateApiAuthServerArgs = {'X-Auth-Token': string, server: string, body: RESTAuthData}; export type CreateApiAuthServerOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; /** * Authenticate to specified server * * POST /auth/{server} */ export const createApiAuthServer = async (args: CreateApiAuthServerArgs, options: CreateApiAuthServerOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") if (args['X-Auth-Token'] != null) headers.set("X-Auth-Token", String(args['X-Auth-Token'])) const url = `${baseUrl.replace(/\/+$/, '')}/auth/${encodeURIComponent(String(args.server))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return undefined };