1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! In-place editor for `.npmrc` files.
//!
//! `aube login` / `aube logout` need to set or remove single keys in the
//! user's `~/.npmrc` without disturbing the rest of the file. The registry
//! crate already has a *reader* (`NpmConfig::load`) which collapses the
//! file into a typed struct — that's lossy for rewriting (comments,
//! ordering, env-var placeholders all get thrown away). This module keeps
//! the raw lines verbatim and only mutates matching `key=value` entries.
//!
//! Keys are matched by literal equality of the part before `=`. That's
//! enough for the auth use case, where the keys are fully qualified
//! (`//host/:_authToken`, `@scope:registry`, `_authToken`).
use aube_registry::config::{NpmConfig, normalize_registry_url_pub, registry_uri_key_pub};
use miette::{Context, IntoDiagnostic, miette};
use std::path::{Path, PathBuf};
/// Re-export of [`registry_uri_key_pub`] under the name used elsewhere
/// in aube. `login` and `logout` call this to build the
/// `//host[:port]/path/` prefix that keys `.npmrc` auth entries; the
/// canonical implementation lives in `aube-registry` so both the
/// registry client and the npmrc editor agree on the shape of the key.
pub fn registry_host_key(url: &str) -> String {
registry_uri_key_pub(url)
}
/// Parsed-ish view of a `.npmrc`: each line is kept as-is except for
/// `key=value` lines, which are split so `set` / `remove` can address them
/// by key. Comments, blanks, and malformed lines pass through untouched.
pub struct NpmrcEdit {
lines: Vec<Line>,
}
enum Line {
Raw(String),
Entry { key: String, value: String },
}
impl NpmrcEdit {
pub fn load(path: &Path) -> miette::Result<Self> {
let content = if path.exists() {
std::fs::read_to_string(path)
.into_diagnostic()
.wrap_err_with(|| format!("failed to read {}", path.display()))?
} else {
String::new()
};
let mut lines = Vec::new();
for line in content.lines() {
let trimmed = line.trim_start();
if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
lines.push(Line::Raw(line.to_string()));
continue;
}
if let Some((k, v)) = line.split_once('=') {
lines.push(Line::Entry {
key: k.trim().to_string(),
value: v.trim().to_string(),
});
} else {
lines.push(Line::Raw(line.to_string()));
}
}
Ok(Self { lines })
}
/// Set `key=value`, removing every existing entry for `key` first and
/// appending the new one. Removing all duplicates (rather than
/// updating just the first) matters because `NpmConfig::apply` is
/// last-write-wins at parse time — a stale trailing duplicate would
/// otherwise silently override the value we just set.
pub fn set(&mut self, key: &str, value: &str) {
self.lines.retain(|line| match line {
Line::Entry { key: k, .. } => k != key,
Line::Raw(_) => true,
});
self.lines.push(Line::Entry {
key: key.to_string(),
value: value.to_string(),
});
}
/// Return every `key=value` entry in file order, dropping raw
/// comment/blank lines. Used by `config list` to enumerate the file
/// without reparsing it and duplicating the comment-handling logic.
pub fn entries(&self) -> Vec<(String, String)> {
self.lines
.iter()
.filter_map(|line| match line {
Line::Entry { key, value } => Some((key.clone(), value.clone())),
Line::Raw(_) => None,
})
.collect()
}
/// Remove all entries matching `key`. Returns `true` if any were
/// removed.
pub fn remove(&mut self, key: &str) -> bool {
let before = self.lines.len();
self.lines.retain(|line| match line {
Line::Entry { key: k, .. } => k != key,
Line::Raw(_) => true,
});
before != self.lines.len()
}
/// Atomically replace `path` with the current contents. Writes into a
/// sibling temp file and `rename`s over the target — on POSIX the
/// rename is atomic, so a crash/OOM/disk-full mid-write leaves the
/// original `~/.npmrc` intact rather than truncated (which would
/// silently wipe every stored auth token).
pub fn save(&self, path: &Path) -> miette::Result<()> {
let mut out = String::new();
for line in &self.lines {
match line {
Line::Raw(s) => out.push_str(s),
Line::Entry { key, value } => {
out.push_str(key);
out.push('=');
out.push_str(value);
}
}
out.push('\n');
}
aube_util::fs_atomic::atomic_write(path, out.as_bytes())
.into_diagnostic()
.wrap_err_with(|| format!("failed to write {}", path.display()))?;
// .npmrc commonly holds _authToken values. Default umask
// leaves the file at 0644 after the rename, readable by every
// other user on a shared host. Force 0600 so only the owner
// can read the token back.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Err(e) = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) {
tracing::warn!(
"failed to chmod 0600 {}: {e}. File may be world-readable, check filesystem permissions",
path.display()
);
}
}
Ok(())
}
}
/// Resolve the registry URL that `login` / `logout` should act on.
/// Precedence:
/// 1. `--registry` flag.
/// 2. `--scope` → the scope's registry from merged `.npmrc` (if set).
/// 3. The default `registry` from merged `.npmrc` (falls back to npmjs).
///
/// Lives here rather than in either command module so both sides pick up
/// any future change (env-var support, `--prefix`, etc) without drifting.
pub fn resolve_registry(flag: Option<&str>, scope: Option<&str>) -> miette::Result<String> {
if let Some(r) = flag {
return Ok(normalize_registry_url_pub(r));
}
let cwd = crate::dirs::project_root_or_cwd().unwrap_or_else(|_| std::path::PathBuf::from("."));
let config = NpmConfig::load(&cwd);
if let Some(scope) = scope
&& let Some(url) = config.scoped_registries.get(scope)
{
return Ok(url.clone());
}
Ok(config.registry)
}
/// `~/.npmrc`, or an error if we can't locate the user's home directory.
///
/// Reads HOME first (every Unix, and POSIX-compat Windows toolchains
/// that set it). Falls back to USERPROFILE on Windows since vanilla
/// Windows does not set HOME. Old code was HOME-only, so `aube login`
/// on a native Windows shell errored out with "$HOME is not set"
/// instead of using C:\Users\<user>\.npmrc. Same issue would make
/// `aube logout` fail and `aube config` never find the user file.
pub fn user_npmrc_path() -> miette::Result<PathBuf> {
let home = read_home_env().ok_or_else(|| {
miette!("could not locate home directory. set HOME or USERPROFILE to point at ~/.npmrc")
})?;
Ok(home.join(".npmrc"))
}
fn read_home_env() -> Option<PathBuf> {
if let Some(h) = std::env::var_os("HOME") {
return Some(PathBuf::from(h));
}
#[cfg(windows)]
{
if let Some(p) = std::env::var_os("USERPROFILE") {
return Some(PathBuf::from(p));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn set_replaces_existing_and_preserves_comments() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".npmrc");
std::fs::write(
&path,
"# top comment\n\
registry=https://registry.npmjs.org/\n\
//registry.npmjs.org/:_authToken=old\n\
; trailing\n",
)
.unwrap();
let mut edit = NpmrcEdit::load(&path).unwrap();
edit.set("//registry.npmjs.org/:_authToken", "new");
edit.save(&path).unwrap();
let after = std::fs::read_to_string(&path).unwrap();
assert!(after.contains("# top comment"));
assert!(after.contains("registry=https://registry.npmjs.org/"));
assert!(after.contains("//registry.npmjs.org/:_authToken=new"));
assert!(!after.contains("=old"));
assert!(after.contains("; trailing"));
}
#[test]
fn set_appends_when_absent() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".npmrc");
std::fs::write(&path, "registry=https://r.example.com/\n").unwrap();
let mut edit = NpmrcEdit::load(&path).unwrap();
edit.set("//r.example.com/:_authToken", "tok");
edit.save(&path).unwrap();
let after = std::fs::read_to_string(&path).unwrap();
assert!(after.contains("//r.example.com/:_authToken=tok"));
}
#[test]
fn remove_drops_matching_line() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".npmrc");
std::fs::write(
&path,
"registry=https://r.example.com/\n\
//r.example.com/:_authToken=tok\n",
)
.unwrap();
let mut edit = NpmrcEdit::load(&path).unwrap();
assert!(edit.remove("//r.example.com/:_authToken"));
edit.save(&path).unwrap();
let after = std::fs::read_to_string(&path).unwrap();
assert!(after.contains("registry=https://r.example.com/"));
assert!(!after.contains("_authToken"));
}
#[test]
fn remove_missing_key_is_false() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".npmrc");
std::fs::write(&path, "registry=https://r.example.com/\n").unwrap();
let mut edit = NpmrcEdit::load(&path).unwrap();
assert!(!edit.remove("//r.example.com/:_authToken"));
}
#[test]
fn load_nonexistent_is_empty() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("missing.npmrc");
let mut edit = NpmrcEdit::load(&path).unwrap();
edit.set("foo", "bar");
edit.save(&path).unwrap();
let after = std::fs::read_to_string(&path).unwrap();
assert_eq!(after, "foo=bar\n");
}
#[test]
fn registry_host_key_strips_scheme() {
assert_eq!(
registry_host_key("https://registry.npmjs.org/"),
"//registry.npmjs.org/"
);
assert_eq!(
registry_host_key("http://localhost:4873/"),
"//localhost:4873/"
);
}
}