import {z} from 'zod' 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 CreateApiAuthArgs = {body: RESTAuthData}; export type CreateApiAuthOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const rESTToken = z.object({token: z.string(), fullname: z.string(), server: z.string(), username: z.string(), password: z.string(), email: z.string(), role: z.string(), timeout: z.number().int(), locale: z.string(), default_password: z.boolean(), modify_password: z.boolean(), role_domains: z.object({role: z.string().optional(), domains: z.array(z.string()).optional()}).optional(), last_login_timestamp: z.number().int(), last_login_at: z.string(), login_count: z.number().int()}); export const rESTTokenData = z.object({token: rESTToken, password_days_until_expire: z.number().int(), password_hours_until_expire: z.number().int()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Login Authentication * * POST /auth */ export const createApiAuth = async (args: CreateApiAuthArgs, options: CreateApiAuthOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/auth${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 validateResponse(rESTTokenData, await res.json()) };