import is from '@sindresorhus/is' ; import type { Options } from 'got' ; import { GITHUB_API_USING_HOST_TYPES , GITLAB_API_USING_HOST_TYPES , PlatformId , } from '../../constants' ; import type { GotOptions } from './types' ; export function applyAuthorization ( inOptions ) { const options = { ... inOptions } ; if ( options . headers ?. authorization || options . noAuth ) { return options ; } options . headers ??= { } ; if ( options . token ) { if ( options . hostType === PlatformId . Gitea ) { options . headers . authorization = `token ${ options . token }` ; } else if ( options . hostType && GITHUB_API_USING_HOST_TYPES . includes ( options . hostType ) ) { options . headers . authorization = `token ${ options . token }` ; if ( options . token . startsWith ( 'x-access-token:' ) ) { const appToken = options . token . replace ( 'x-access-token:' , '' ) ; options . headers . authorization = `token ${ appToken }` ; if ( is . string ( options . headers . accept ) ) { options . headers . accept = options . headers . accept . replace ( 'application/vnd.github.v3+json' , 'application/vnd.github.machine-man-preview+json' ) ; } } } else if ( options . hostType && GITLAB_API_USING_HOST_TYPES . includes ( options . hostType ) ) { if ( options . token . length === 20 ) { options . headers [ 'Private-token' ] = options . token ; } else { options . headers . authorization = `Bearer ${ options . token }` ; } } else { const type = options . context ?. authType ?? 'Bearer' ; if ( type === 'Token-Only' ) { options . headers . authorization = options . token ; } else { options . headers . authorization = `${ type } ${ options . token }` ; } } delete options . token ; } else if ( options . password !== undefined ) { const auth = Buffer . from ( `${ options . username ?? '' }:${ options . password }` ) . toString ( 'base64' ) ; options . headers . authorization = `Basic ${ auth }` ; delete options . username ; delete options . password ; } return options ; } function isAmazon ( options ) { return ! ! options . search ?. includes ( 'X-Amz-Algorithm' ) ; } function isAzureBlob ( options ) { return ! ! ( options . hostname ?. endsWith ( '.blob.core.windows.net' ) && options . href ?. includes ( '/docker/registry' ) ) ; } export function removeAuthorization ( options ) { if ( ! options . password && ! options . headers ?. authorization ) { return ; } if ( isAmazon ( options ) || isAzureBlob ( options ) ) { const portInUrl = options . href ?. split ?. ( '/' ) ?. [ 2 ] ?. split ( ':' ) ?. [ 1 ] ; if ( ! portInUrl ) { delete options . port ; } if ( options ?. headers ?. authorization ) { delete options . headers . authorization ; } delete options . username ; delete options . password ; } }