2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-10-03 19:05:06 -04:00
|
|
|
|
2024-08-14 12:53:15 -04:00
|
|
|
use base64::prelude::BASE64_STANDARD;
|
|
|
|
use base64::Engine;
|
|
|
|
use deno_core::anyhow::bail;
|
2024-10-28 07:08:51 -04:00
|
|
|
use deno_core::anyhow::Context;
|
2024-08-14 12:53:15 -04:00
|
|
|
use deno_core::error::AnyError;
|
2024-05-23 17:26:23 -04:00
|
|
|
use deno_npm::npm_rc::RegistryConfig;
|
2024-07-17 19:37:31 -04:00
|
|
|
use http::header;
|
2024-05-23 17:26:23 -04:00
|
|
|
|
|
|
|
// TODO(bartlomieju): support more auth methods besides token and basic auth
|
|
|
|
pub fn maybe_auth_header_for_npm_registry(
|
|
|
|
registry_config: &RegistryConfig,
|
2024-08-14 12:53:15 -04:00
|
|
|
) -> Result<Option<(header::HeaderName, header::HeaderValue)>, AnyError> {
|
2024-05-23 17:26:23 -04:00
|
|
|
if let Some(token) = registry_config.auth_token.as_ref() {
|
2024-08-14 12:53:15 -04:00
|
|
|
return Ok(Some((
|
2024-05-23 17:26:23 -04:00
|
|
|
header::AUTHORIZATION,
|
|
|
|
header::HeaderValue::from_str(&format!("Bearer {}", token)).unwrap(),
|
2024-08-14 12:53:15 -04:00
|
|
|
)));
|
2024-05-23 17:26:23 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(auth) = registry_config.auth.as_ref() {
|
2024-08-14 12:53:15 -04:00
|
|
|
return Ok(Some((
|
2024-05-23 17:26:23 -04:00
|
|
|
header::AUTHORIZATION,
|
|
|
|
header::HeaderValue::from_str(&format!("Basic {}", auth)).unwrap(),
|
2024-08-14 12:53:15 -04:00
|
|
|
)));
|
2024-05-23 17:26:23 -04:00
|
|
|
}
|
|
|
|
|
2024-08-14 12:53:15 -04:00
|
|
|
let (username, password) = (
|
|
|
|
registry_config.username.as_ref(),
|
|
|
|
registry_config.password.as_ref(),
|
|
|
|
);
|
|
|
|
if (username.is_some() && password.is_none())
|
|
|
|
|| (username.is_none() && password.is_some())
|
|
|
|
{
|
|
|
|
bail!("Both the username and password must be provided for basic auth")
|
|
|
|
}
|
|
|
|
|
|
|
|
if username.is_some() && password.is_some() {
|
2024-10-28 07:08:51 -04:00
|
|
|
// The npm client does some double encoding when generating the
|
|
|
|
// bearer token value, see
|
|
|
|
// https://github.com/npm/cli/blob/780afc50e3a345feb1871a28e33fa48235bc3bd5/workspaces/config/lib/index.js#L846-L851
|
|
|
|
let pw_base64 = BASE64_STANDARD
|
|
|
|
.decode(password.unwrap())
|
|
|
|
.with_context(|| "The password in npmrc is an invalid base64 string")?;
|
|
|
|
let bearer = BASE64_STANDARD.encode(format!(
|
|
|
|
"{}:{}",
|
|
|
|
username.unwrap(),
|
|
|
|
String::from_utf8_lossy(&pw_base64)
|
|
|
|
));
|
|
|
|
|
2024-08-14 12:53:15 -04:00
|
|
|
return Ok(Some((
|
|
|
|
header::AUTHORIZATION,
|
2024-10-28 07:08:51 -04:00
|
|
|
header::HeaderValue::from_str(&format!("Basic {}", bearer)).unwrap(),
|
2024-08-14 12:53:15 -04:00
|
|
|
)));
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(None)
|
2024-05-23 17:26:23 -04:00
|
|
|
}
|