import {z} from 'zod' export type Ipaddr = string; export type OauthScope = 'att' | 'chn' | 'cnt' | 'tpl' | 'evt' | 'jny' | 'lst' | 'nu' | 'pln' | 'psh' | 'rpt' | 'sch'; export type Subject = unknown; export type RequestTokenBasicAuth = {grant_type: 'client_credentials', ipaddr?: Ipaddr | undefined, scope?: OauthScope | undefined, sub: Subject}; export type AssertionJwt = {alg: 'ES384', kid: string, aud: string, exp: number, iat: number, ipaddr?: string | undefined, iss: string, nonce: string, scope?: OauthScope | undefined, sub: Subject}; export type RequestTokenWithAssertion = {assertion: AssertionJwt, grant_type: 'client_credentials'}; export type CreateApiTokenArgs = {'Content-Type': string, body: RequestTokenBasicAuth | RequestTokenWithAssertion}; export type CreateApiTokenOptions = {baseUrl?: string | undefined, basicOauth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const oauthScope = z.enum(["att", "chn", "cnt", "tpl", "evt", "jny", "lst", "nu", "pln", "psh", "rpt", "sch"]); export const okOauthTokenResponse = z.object({access_token: z.string().optional(), expires_in: z.number().int().optional(), scope: oauthScope.optional(), token_type: z.literal("Bearer").optional()}); 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 }; /** * Request token * * POST /token */ export const createApiToken = async (args: CreateApiTokenArgs, options?: CreateApiTokenOptions) => { const {baseUrl = "https://go.urbanairship.com", fetch: fetchFn = fetch, basicOauth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/x-www-form-urlencoded") headers.set('accept', "application/json") if (args['Content-Type'] != null) headers.set("Content-Type", String(args['Content-Type'])) if (basicOauth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicOauth.username}:${basicOauth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/token${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: new URLSearchParams(Object.entries(args.body).flatMap(([key, value]) => (value == null ? [] : [[key, String(value)]])))}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(okOauthTokenResponse, await res.json()) };