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