Skip to main content

node_auth/
pnpm.rs

1//! Dynamic pnpm authentication in the trusted, pnpm-specific user auth file.
2
3use crate::AuthError;
4use crate::fs::{FileTransaction, resolve};
5use crate::registry::RegistryPolicy;
6use std::collections::BTreeSet;
7use std::path::{Path, PathBuf};
8use std::str::FromStr;
9use yaml_edit::YamlFile;
10
11/// Configure pnpm without retrieving credentials or editing shared npm files.
12///
13/// Requires pnpm >=11.13.0, whose `auth.ini` supports trusted token helpers.
14/// `source` optionally selects an additional `.npmrc` registry source.
15/// `helper` optionally selects an installed executable instead of sibling/PATH discovery.
16/// Returns the auth file and whether it changed. Project configuration is read only.
17///
18/// # Errors
19/// Returns an error for unsupported pnpm versions, invalid registries, unsafe helper
20/// paths, project-local destinations, or conflicting more-specific credentials.
21pub fn configure(
22  source: Option<&Path>,
23  helper: Option<&Path>,
24) -> Result<(PathBuf, bool), AuthError> {
25  check_version()?;
26  let home = dirs::home_dir().ok_or_else(|| config_error("Cannot determine home directory"))?;
27  let cwd = std::env::current_dir()?.canonicalize()?;
28  let root = cwd
29    .ancestors()
30    .find(|p| p.join("pnpm-workspace.yaml").is_file())
31    .or_else(|| cwd.ancestors().find(|p| p.join("package.json").is_file()))
32    .unwrap_or(&cwd);
33  let config_dir = config_dir(&home)?;
34  let target = resolve(&config_dir.join("auth.ini"))?;
35  if target.starts_with(root) {
36    return Err(config_error(
37      "pnpm auth.ini resolves inside the project; choose a user-level XDG_CONFIG_HOME",
38    ));
39  }
40  let helper = resolve_helper(helper)?;
41  let global_yaml = config_dir.join("config.yaml");
42  let global_content = read_optional(&global_yaml)?;
43  let user = user_npmrc(&home, &global_content)?;
44  let user = if let Some(raw) = user
45    .to_str()
46    .and_then(|p| p.strip_prefix("~/").or_else(|| p.strip_prefix(r"~\")))
47  {
48    home.join(raw)
49  } else {
50    user
51  };
52  let mut sources = vec![resolve(&user)?, resolve(&root.join(".npmrc"))?];
53  if let Some(source) = source {
54    if !source.is_file() {
55      return Err(config_error(
56        "Registry source does not exist; check --repo-config",
57      ));
58    }
59    sources.push(resolve(source)?);
60  }
61  if sources.contains(&target) {
62    return Err(config_error("Registry source must not be pnpm auth.ini"));
63  }
64  sources.sort();
65  sources.dedup();
66  let mut paths = sources.clone();
67  paths.push(target.clone());
68  paths.push(resolve(&global_yaml)?);
69  let workspace_yaml = resolve(&root.join("pnpm-workspace.yaml"))?;
70  paths.push(workspace_yaml.clone());
71  let mut transaction = FileTransaction::new(&paths)?;
72  let mut registries = BTreeSet::new();
73  for path in &sources {
74    discover_npmrc(transaction.contents(path)?, &mut registries)?;
75  }
76  let global = transaction.contents(&resolve(&global_yaml)?)?;
77  if global != global_content {
78    return Err(config_error(
79      "Global pnpm configuration changed during discovery; run configure again",
80    ));
81  }
82  let project_npmrc = resolve(&root.join(".npmrc"))?;
83  if project_npmrc != resolve(&user)?
84    && root_ini_lines(transaction.contents(&project_npmrc)?).any(|line| {
85      ini_entry(line).is_some_and(|(key, _)| key == "tokenHelper" || key.ends_with(":tokenHelper"))
86    })
87  {
88    return Err(config_error(
89      "Project .npmrc contains tokenHelper, which pnpm rejects; remove it from the project before configuring the trusted user auth.ini",
90    ));
91  }
92  discover_yaml(global, &mut registries)?;
93  discover_yaml(transaction.contents(&workspace_yaml)?, &mut registries)?;
94  discover_npmrc(transaction.contents(&target)?, &mut registries)?;
95  if registries.is_empty() {
96    return Err(config_error(
97      "No GAR registry definitions found; set registry or @scope:registry in .npmrc, or registry/registries in pnpm-workspace.yaml",
98    ));
99  }
100  for path in sources.iter().chain(std::iter::once(&target)) {
101    check_conflicts(transaction.contents(path)?, &registries)?;
102  }
103  // Scope-specific JSON/YAML credentials can override a registry-wide helper.
104  check_yaml_auth(global, &registries)?;
105  for (key, _) in std::env::vars_os() {
106    let key = key.to_string_lossy();
107    if let Some((prefix, scoped)) = key.split_once("//")
108      && ["npm_config_", "pnpm_config_"]
109        .iter()
110        .any(|p| prefix.eq_ignore_ascii_case(p))
111    {
112      check_conflicts(&format!("//{scoped}=environment"), &registries)?;
113    }
114    if key.eq_ignore_ascii_case("pnpm_config__auth") {
115      return Err(config_error(
116        "pnpm_config__auth is set; remove the structured auth override before configuring dynamic GAR authentication",
117      ));
118    }
119  }
120  let original = transaction.contents(&target)?;
121  let updated = transform(original, &registries, &helper)?;
122  if updated == original {
123    return Ok((target, false));
124  }
125  transaction.stage(&target, &updated)?;
126  transaction.commit()?;
127  Ok((target, true))
128}
129
130fn config_error(message: &str) -> AuthError {
131  AuthError::Config(message.into())
132}
133
134fn check_version() -> Result<(), AuthError> {
135  let binaries: &[&str] = if cfg!(windows) {
136    &["pnpm.cmd", "pnpm.exe", "pnpm.bat", "pnpm"]
137  } else {
138    &["pnpm"]
139  };
140  let mut output = None;
141  for binary in binaries {
142    match std::process::Command::new(binary).arg("--version").output() {
143      Ok(result) => {
144        output = Some(result);
145        break;
146      }
147      Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
148      Err(e) => return Err(e.into()),
149    }
150  }
151  let output = output.ok_or_else(|| {
152    config_error("pnpm is missing; install pnpm >=11.13.0 and ensure it is on PATH")
153  })?;
154  let version = String::from_utf8_lossy(&output.stdout);
155  let version = version.trim();
156  let parts: Vec<_> = version.split('.').map(str::parse::<u32>).collect();
157  if !output.status.success() || parts.len() != 3 || parts.iter().any(Result::is_err) {
158    return Err(config_error(
159      "Cannot determine stable pnpm version; install pnpm >=11.13.0",
160    ));
161  }
162  let values: Vec<_> = parts.into_iter().map(Result::unwrap).collect();
163  if values.as_slice() < [11, 13, 0].as_slice() {
164    return Err(config_error(
165      "Dynamic configuration requires pnpm >=11.13.0 (trusted auth.ini tokenHelper fix); upgrade pnpm or use node-auth for static credentials",
166    ));
167  }
168  Ok(())
169}
170
171fn config_dir(home: &Path) -> Result<PathBuf, AuthError> {
172  let base = if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {
173    let path = PathBuf::from(xdg);
174    if !path.is_absolute() {
175      return Err(config_error("XDG_CONFIG_HOME must be absolute"));
176    }
177    path.join("pnpm")
178  } else if cfg!(target_os = "macos") {
179    home.join("Library/Preferences/pnpm")
180  } else if cfg!(windows) {
181    std::env::var_os("LOCALAPPDATA")
182      .filter(|v| !v.is_empty())
183      .map(|p| PathBuf::from(p).join("pnpm/config"))
184      .unwrap_or_else(|| home.join(".config/pnpm"))
185  } else {
186    home.join(".config/pnpm")
187  };
188  resolve(&base)
189}
190
191fn read_optional(path: &Path) -> Result<String, AuthError> {
192  match std::fs::read_to_string(path) {
193    Ok(s) => Ok(s),
194    Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
195    Err(e) => Err(e.into()),
196  }
197}
198
199fn yaml_root(content: &str) -> Result<Option<yaml_edit::Mapping>, AuthError> {
200  if content.trim().is_empty() {
201    return Ok(None);
202  }
203  let file = YamlFile::from_str(content).map_err(|source| AuthError::YamlInput {
204    input: "pnpm configuration",
205    source,
206  })?;
207  let doc = file
208    .document()
209    .ok_or_else(|| config_error("pnpm YAML must contain a mapping"))?;
210  Ok(Some(doc.as_mapping().ok_or_else(|| {
211    config_error("pnpm YAML must contain a mapping")
212  })?))
213}
214
215fn user_npmrc(home: &Path, global: &str) -> Result<PathBuf, AuthError> {
216  for key in [
217    "pnpm_config_npmrc_auth_file",
218    "PNPM_CONFIG_NPMRC_AUTH_FILE",
219    "pnpm_config_userconfig",
220    "PNPM_CONFIG_USERCONFIG",
221  ] {
222    if let Some(value) = std::env::var_os(key).filter(|v| !v.is_empty()) {
223      return Ok(PathBuf::from(value));
224    }
225  }
226  if let Some(root) = yaml_root(global)?
227    && let Some(value) = root.get("npmrcAuthFile")
228  {
229    let value = value
230      .as_scalar()
231      .ok_or_else(|| config_error("npmrcAuthFile must be a path string"))?
232      .as_string();
233    if value.contains("${") {
234      return Err(config_error(
235        "Expand npmrcAuthFile to an absolute path before configuring pnpm",
236      ));
237    }
238    return Ok(if let Some(rest) = value.strip_prefix("~/") {
239      home.join(rest)
240    } else {
241      PathBuf::from(value)
242    });
243  }
244  Ok(
245    std::env::var_os("npm_config_userconfig")
246      .or_else(|| std::env::var_os("NPM_CONFIG_USERCONFIG"))
247      .map(PathBuf::from)
248      .unwrap_or_else(|| home.join(".npmrc")),
249  )
250}
251
252fn add_registry(value: &str, registries: &mut BTreeSet<String>) -> Result<(), AuthError> {
253  if value.contains("${") {
254    return Err(config_error(
255      "Registry URL contains an unresolved environment variable; use a literal HTTPS GAR URL",
256    ));
257  }
258  if let Some(registry) = (RegistryPolicy {
259    allow_all_domains: false,
260  })
261  .parse(value)?
262  {
263    registries.insert(registry.npm_key().to_owned());
264  }
265  Ok(())
266}
267
268fn ini_entry(line: &str) -> Option<(&str, &str)> {
269  let line = line.trim();
270  if line.starts_with(['#', ';']) {
271    return None;
272  }
273  line.split_once('=').map(|(k, v)| (k.trim(), v.trim()))
274}
275
276// npm INI sections form nested objects; registry/auth settings must be root keys.
277fn root_ini_lines(content: &str) -> impl Iterator<Item = &str> {
278  content
279    .lines()
280    .take_while(|line| !line.trim_start().starts_with('['))
281}
282
283fn ini_value(value: &str) -> Result<String, AuthError> {
284  // npm/ini only unquotes when the entire value is quoted. A comment after a
285  // closing quote leaves the quote characters in the value, so reject that form.
286  if value.starts_with(['\'', '"']) {
287    let delimiter = value.as_bytes()[0] as char;
288    return value.strip_prefix(delimiter).and_then(|v| v.strip_suffix(delimiter))
289      .filter(|v| !v.contains('\\'))
290      .map(str::to_owned)
291      .ok_or_else(|| config_error("Unsupported quoted npm registry URL; use a literal unquoted URL before an inline comment"));
292  }
293  let mut escaped = false;
294  let mut end = value.len();
295  for (index, c) in value.char_indices() {
296    if escaped {
297      escaped = false;
298      continue;
299    }
300    if c == '\\' {
301      escaped = true;
302      continue;
303    }
304    if matches!(c, '#' | ';') {
305      end = index;
306      break;
307    }
308  }
309  Ok(value[..end].trim().replace(r"\#", "#").replace(r"\;", ";"))
310}
311
312fn discover_npmrc(content: &str, registries: &mut BTreeSet<String>) -> Result<(), AuthError> {
313  for line in root_ini_lines(content) {
314    if let Some((key, value)) = ini_entry(line)
315      && (key == "registry" || (key.starts_with('@') && key.ends_with(":registry")))
316    {
317      add_registry(&ini_value(value)?, registries)?;
318    }
319  }
320  Ok(())
321}
322
323fn discover_yaml(content: &str, registries: &mut BTreeSet<String>) -> Result<(), AuthError> {
324  let Some(root) = yaml_root(content)? else {
325    return Ok(());
326  };
327  if let Some(value) = root.get("registry") {
328    add_registry(
329      &value
330        .as_scalar()
331        .ok_or_else(|| config_error("registry must be a URL string"))?
332        .as_string(),
333      registries,
334    )?;
335  }
336  if let Some(value) = root.get("registries") {
337    let mapping = value
338      .as_mapping()
339      .ok_or_else(|| config_error("registries must be a mapping"))?;
340    for (key, value) in mapping.iter() {
341      let key = key
342        .as_scalar()
343        .ok_or_else(|| config_error("Registry key must be a string"))?
344        .as_string();
345      if key.starts_with("https://") {
346        add_registry(&key, registries)?;
347      } else {
348        add_registry(
349          &value
350            .as_scalar()
351            .ok_or_else(|| config_error("Scoped registries must contain URL strings"))?
352            .as_string(),
353          registries,
354        )?;
355      }
356    }
357  }
358  Ok(())
359}
360
361fn check_yaml_auth(content: &str, registries: &BTreeSet<String>) -> Result<(), AuthError> {
362  let Some(root) = yaml_root(content)? else {
363    return Ok(());
364  };
365  if let Some(auth) = root.get("_auth") {
366    let map = auth
367      .as_mapping()
368      .ok_or_else(|| config_error("pnpm _auth must be a mapping"))?;
369    for (key, value) in map.iter() {
370      let key = key
371        .as_scalar()
372        .ok_or_else(|| config_error("Auth registry must be a string"))?
373        .as_string();
374      let mut matched = BTreeSet::new();
375      add_registry(&key, &mut matched)?;
376      if matched
377        .iter()
378        .any(|key| registries.iter().any(|r| key.starts_with(r)))
379      {
380        let scopes = value
381          .as_mapping()
382          .ok_or_else(|| config_error("Auth scopes must be a mapping"))?;
383        if scopes
384          .iter()
385          .any(|(key, _)| key.as_scalar().is_none_or(|s| s.as_string() != "@"))
386        {
387          return Err(config_error(
388            "Scope-specific GAR credentials in global config.yaml override a registry helper; reconcile them manually first",
389          ));
390        }
391      }
392    }
393  }
394  Ok(())
395}
396
397fn check_conflicts(content: &str, registries: &BTreeSet<String>) -> Result<(), AuthError> {
398  for line in root_ini_lines(content) {
399    let Some((key, _)) = ini_entry(line) else {
400      continue;
401    };
402    let Some((scope, field)) = key.rsplit_once(':') else {
403      continue;
404    };
405    if ![
406      "_authToken",
407      "_auth",
408      "_password",
409      "username",
410      "tokenHelper",
411    ]
412    .contains(&field)
413    {
414      continue;
415    }
416    let scope = format!("{}/", scope.trim_end_matches('/'));
417    for registry in registries {
418      if !registries.contains(&scope) && scope.starts_with(registry) {
419        return Err(config_error(
420          "More-specific GAR credentials or tokenHelper override the registry helper; reconcile the child-path or package-scope entry manually first",
421        ));
422      }
423    }
424  }
425  Ok(())
426}
427
428fn resolve_helper(explicit: Option<&Path>) -> Result<String, AuthError> {
429  let name = format!("node-auth-token{}", std::env::consts::EXE_SUFFIX);
430  let path = if let Some(path) = explicit {
431    path.to_path_buf()
432  } else {
433    let sibling = std::env::current_exe()?.with_file_name(&name);
434    if sibling.is_file() {
435      sibling
436    } else {
437      std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
438        .filter(|p| p.is_absolute())
439        .map(|p| p.join(&name)).find(|p| p.is_file())
440        .ok_or_else(|| config_error("node-auth-token is missing; install all node-auth binaries or pass --token-helper with its installed path"))?
441    }
442  };
443  let path = path
444    .canonicalize()
445    .map_err(|_| config_error("node-auth-token executable does not exist"))?;
446  if !path.is_file() {
447    return Err(config_error("Token helper must be an executable file"));
448  }
449  #[cfg(unix)]
450  {
451    use std::os::unix::fs::PermissionsExt;
452    if path.metadata()?.permissions().mode() & 0o111 == 0 {
453      return Err(config_error(
454        "Token helper is not executable; fix its execute permissions",
455      ));
456    }
457  }
458  #[cfg(windows)]
459  if !path
460    .extension()
461    .is_some_and(|e| e.eq_ignore_ascii_case("exe"))
462  {
463    return Err(config_error("Token helper must be a native .exe file"));
464  }
465  let value = path
466    .to_str()
467    .ok_or_else(|| config_error("Token helper path must be UTF-8"))?;
468  let value = if cfg!(windows) {
469    // canonicalize produces Windows verbatim paths, which pnpm/Node cannot spawn.
470    if let Some(unc) = value.strip_prefix(r"\\?\UNC\") {
471      format!("//{}", unc.replace('\\', "/"))
472    } else {
473      value
474        .strip_prefix(r"\\?\")
475        .unwrap_or(value)
476        .replace('\\', "/")
477    }
478  } else {
479    value.into()
480  };
481  if value
482    .chars()
483    .any(|c| c.is_whitespace() || c.is_control() || "$%`\"'#;\\".contains(c))
484  {
485    return Err(config_error(
486      "pnpm cannot safely represent this tokenHelper path; install node-auth-token in an absolute path without spaces, quotes, $, %, backticks, backslashes, # or ;",
487    ));
488  }
489  Ok(value)
490}
491
492fn transform(
493  content: &str,
494  registries: &BTreeSet<String>,
495  helper: &str,
496) -> Result<String, AuthError> {
497  let newline = if content.contains("\r\n") {
498    "\r\n"
499  } else {
500    "\n"
501  };
502  let mut seen = BTreeSet::new();
503  let mut offset = 0;
504  let mut section_start = content.len();
505  for line in content.split_inclusive('\n') {
506    if line.trim_start().starts_with('[') {
507      section_start = offset;
508      break;
509    }
510    offset += line.len();
511  }
512  let (root, sections) = content.split_at(section_start);
513  let mut output = String::new();
514  for line in root.split_inclusive('\n') {
515    if let Some((key, _)) = ini_entry(line)
516      && let Some(registry) = key.strip_suffix(":tokenHelper")
517    {
518      // Canonicalize existing helper keys so variants without a trailing slash don't duplicate.
519      if let Some(parsed) = (RegistryPolicy {
520        allow_all_domains: false,
521      })
522      .parse_npm_key(registry)?
523      {
524        let registry = parsed.npm_key();
525        if registries.contains(registry) {
526          if seen.insert(registry.to_owned()) {
527            let replacement = format!("{registry}:tokenHelper={helper}");
528            if line.trim_end_matches(['\r', '\n']) == replacement {
529              output.push_str(line);
530            } else {
531              output.push_str(&replacement);
532              output.push_str(newline);
533            }
534          }
535          continue;
536        }
537      }
538    }
539    output.push_str(line);
540  }
541  for registry in registries.difference(&seen) {
542    if !output.is_empty() && !output.ends_with('\n') {
543      output.push_str(newline);
544    }
545    output.push_str(&format!("{registry}:tokenHelper={helper}{newline}"));
546  }
547  output.push_str(sections);
548  Ok(output)
549}