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