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
//! Shared `--cluster` / `--keypair` / `--commitment` handling for the
//! deploy-family commands (`deploy`, `upgrade`, `close`, `migrate`).
//!
//! Every command that touches a live cluster goes through here so the
//! mainnet guard is uniform: a mainnet operation is only allowed when
//! the caller passes `--cluster mainnet-beta` *explicitly*, and any
//! destructive op on mainnet (deploy/upgrade/close) prompts for an
//! interactive confirmation unless `--yes` is given. The default
//! cluster is **never** mainnet, so an accidental `hopper deploy` can
//! never push to mainnet from a stray config.
use std::io::{self, Write};
use std::process;
/// A resolved cluster target plus the per-invocation flags that map
/// onto the underlying `solana` CLI.
pub struct ClusterArgs {
/// RPC URL the operation should target.
pub url: String,
/// Human label (`devnet`, `mainnet-beta`, `localnet`, or `custom`).
pub label: String,
/// True when the target is mainnet-beta.
pub is_mainnet: bool,
/// Optional explicit keypair path (fee payer / authority).
pub keypair: Option<String>,
/// Optional commitment level.
pub commitment: Option<String>,
/// Skip interactive confirmation prompts.
pub yes: bool,
/// Arguments we did not consume, forwarded to `solana`.
pub passthrough: Vec<String>,
}
/// Translate a `--cluster` value into an RPC URL. Accepts the canonical
/// monikers and a raw URL passthrough.
pub fn cluster_url(moniker: &str) -> Option<(String, String, bool)> {
let lower = moniker.to_ascii_lowercase();
match lower.as_str() {
"devnet" | "d" => Some((
"https://api.devnet.solana.com".to_string(),
"devnet".to_string(),
false,
)),
"testnet" | "t" => Some((
"https://api.testnet.solana.com".to_string(),
"testnet".to_string(),
false,
)),
"mainnet" | "mainnet-beta" | "m" => Some((
"https://api.mainnet-beta.solana.com".to_string(),
"mainnet-beta".to_string(),
true,
)),
"localnet" | "localhost" | "l" => Some((
"http://127.0.0.1:8899".to_string(),
"localnet".to_string(),
false,
)),
other if other.starts_with("http://") || other.starts_with("https://") => {
// A provider URL does not reliably encode the Solana cluster in
// its hostname. Treat every custom endpoint as potentially
// mainnet so a branded URL cannot bypass the destructive-action
// confirmation guard.
Some((moniker.to_string(), "custom".to_string(), true))
}
_ => None,
}
}
pub fn redact_rpc_url(url: &str) -> String {
let mut redacted = url.to_string();
if let Some(authority_start) = redacted.find("://").map(|idx| idx + 3) {
let authority_end = redacted[authority_start..]
.find(['/', '?', '#'])
.map(|idx| authority_start + idx)
.unwrap_or(redacted.len());
if let Some(at) = redacted[authority_start..authority_end].rfind('@') {
redacted.replace_range(authority_start..authority_start + at, "<redacted>");
}
}
if let Some(query_start) = redacted.find('?') {
if let Some(fragment_start) = redacted[query_start..].find('#') {
redacted.replace_range(query_start + 1..query_start + fragment_start, "<redacted>");
} else {
redacted.truncate(query_start + 1);
redacted.push_str("<redacted>");
}
}
redacted
}
/// Parse the shared cluster flags out of an argument list, leaving the
/// rest in `passthrough`. The default cluster is devnet, never
/// mainnet; so omitting `--cluster` can never target mainnet.
pub fn parse_cluster_args(args: &[String]) -> Result<ClusterArgs, String> {
let mut url = "https://api.devnet.solana.com".to_string();
let mut label = "devnet".to_string();
let mut is_mainnet = false;
let mut keypair = None;
let mut commitment = None;
let mut yes = false;
let mut passthrough = Vec::new();
let mut explicit_cluster = false;
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--cluster" | "--url" | "-u" => {
let v = args
.get(i + 1)
.ok_or_else(|| format!("{} requires a value", args[i]))?;
let (resolved, lbl, mainnet) =
cluster_url(v).ok_or_else(|| format!("unknown cluster moniker: {v}"))?;
url = resolved;
label = lbl;
is_mainnet = mainnet;
explicit_cluster = true;
i += 2;
}
"--keypair" | "-k" => {
keypair = Some(
args.get(i + 1)
.ok_or_else(|| format!("{} requires a path", args[i]))?
.clone(),
);
i += 2;
}
"--commitment" => {
commitment = Some(
args.get(i + 1)
.ok_or_else(|| "--commitment requires a value".to_string())?
.clone(),
);
i += 2;
}
"--yes" | "-y" => {
yes = true;
i += 1;
}
other => {
passthrough.push(other.to_string());
i += 1;
}
}
}
// Mainnet is opt-in only: it must be named explicitly on the command
// line, regardless of what the saved Solana config says.
if is_mainnet && !explicit_cluster {
return Err(
"refusing to target mainnet from default config; pass --cluster mainnet-beta explicitly"
.to_string(),
);
}
Ok(ClusterArgs {
url,
label,
is_mainnet,
keypair,
commitment,
yes,
passthrough,
})
}
impl ClusterArgs {
pub fn display_url(&self) -> String {
redact_rpc_url(&self.url)
}
/// Build the `solana` CLI flags (`--url`, `--keypair`,
/// `--commitment`) this target implies.
pub fn solana_flags(&self) -> Vec<String> {
let mut out = vec!["--url".to_string(), self.url.clone()];
if let Some(kp) = &self.keypair {
out.push("--keypair".to_string());
out.push(kp.clone());
}
if let Some(c) = &self.commitment {
out.push("--commitment".to_string());
out.push(c.clone());
}
out
}
/// Gate a destructive operation. On mainnet, require an interactive
/// "yes" confirmation unless `--yes` was passed. On every other
/// cluster, proceed.
pub fn confirm_destructive(&self, action: &str, target: &str) {
if !self.is_mainnet || self.yes {
return;
}
let destination = if self.label == "mainnet-beta" {
"MAINNET-BETA"
} else {
"A CUSTOM CLUSTER (POTENTIALLY MAINNET-BETA)"
};
eprint!(
"About to {action} on {destination} ({target}). This is irreversible. Type 'yes' to continue: "
);
let _ = io::stderr().flush();
let mut line = String::new();
if io::stdin().read_line(&mut line).is_err() || line.trim() != "yes" {
eprintln!("aborted.");
process::exit(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn redacts_rpc_url_query_and_userinfo() {
assert_eq!(
redact_rpc_url("https://user:pass@example.invalid/path?key=secret&mode=fast"),
"https://<redacted>@example.invalid/path?<redacted>"
);
assert_eq!(
redact_rpc_url("https://example.invalid?api-key=secret#frag"),
"https://example.invalid?<redacted>#frag"
);
assert_eq!(
redact_rpc_url("https://api.devnet.solana.com"),
"https://api.devnet.solana.com"
);
}
#[test]
fn custom_rpc_urls_cannot_bypass_the_destructive_confirmation_guard() {
let (_, label, guarded) =
cluster_url("https://example-rpc-provider.invalid/project").unwrap();
assert_eq!(label, "custom");
assert!(guarded);
let args = vec![
"--url".to_string(),
"https://example-rpc-provider.invalid/project".to_string(),
];
let parsed = parse_cluster_args(&args).unwrap();
assert!(parsed.is_mainnet);
assert_eq!(parsed.label, "custom");
}
}