import {z} from 'zod' export type GetApiCpeArgs = {cpe: string, isVulnerable?: string | undefined}; export type GetApiCpeOptions = {baseUrl: string, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const apiCPE = z.object({edition: z.string().optional(), language: z.string().optional(), other: z.string().optional(), part: z.string().optional(), product: z.string().optional(), sw_edition: z.string().optional(), target_hw: z.string().optional(), target_sw: z.string().optional(), update: z.string().optional(), vendor: z.string().optional(), version: z.string().optional()}); export const v3controllersResponseMetadata = z.object({cpe: z.string().optional(), cpe_struct: apiCPE.optional(), timestamp: z.string().optional(), total_documents: z.number().int().optional()}); export const renderResponseWithMetadataArrayStringV3controllersResponseMetadata = z.object({_benchmark: z.number().optional(), _meta: v3controllersResponseMetadata.optional(), data: z.array(z.string()).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 }; /** * Return CVE 's associated with a specific NIST CPE * * GET /cpe */ export const getApiCpe = async (args: GetApiCpeArgs, options: GetApiCpeOptions) => { const {baseUrl, fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cpe != null) query.append("cpe", String(args.cpe)) if (args.isVulnerable != null) query.append("isVulnerable", String(args.isVulnerable)) if (Bearer !== undefined) headers.set("Authorization", Bearer) const url = `${baseUrl.replace(/\/+$/, '')}/cpe${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(renderResponseWithMetadataArrayStringV3controllersResponseMetadata, await res.json()) };