Skip to content

Commit 1e81761

Browse files
authored
Expose web authentication authUrl and doneUrl in JSON error output when OTP is required in a non-interactive terminal (#12786)
Preserve web-auth OTP challenge URLs when OTP handling fails because pnpm is not running in an interactive terminal. The web-auth layer now carries authUrl and doneUrl from the registry challenge onto OtpNonInteractiveError. The pnpm error handler includes those fields in parseable JSON error output when present. The same URL preservation was added to pacquet's web-auth error type to keep the two implementations aligned. Tests cover the TS and Rust web-auth layers and the pnpm JSON error output path.
1 parent 90dd346 commit 1e81761

13 files changed

Lines changed: 433 additions & 17 deletions

File tree

‎.changeset/webauth-json-urls.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@pnpm/network.web-auth": minor
3+
"pnpm": minor
4+
---
5+
6+
Expose web authentication `authUrl` and `doneUrl` in JSON error output when OTP is required in a non-interactive terminal [#12724](https://github.com/pnpm/pnpm/issues/12724).

‎pacquet/crates/network-web-auth/src/with_otp_handling.rs‎

Lines changed: 55 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,44 @@ fn js_typeof(value: &Value) -> &'static str {
121121
--otp option if you are using a classic one-time password (OTP)"
122122
)
123123
)]
124-
pub struct OtpNonInteractiveError;
124+
pub struct OtpNonInteractiveError {
125+
#[error(not(source))]
126+
pub auth_url: Option<String>,
127+
#[error(not(source))]
128+
pub done_url: Option<String>,
129+
}
130+
131+
impl OtpNonInteractiveError {
132+
#[must_use]
133+
pub fn new(body: Option<OtpErrorBody>) -> Self {
134+
match body {
135+
Some(OtpErrorBody { auth_url, done_url }) => OtpNonInteractiveError {
136+
auth_url: auth_url.as_deref().and_then(canonical_http_url),
137+
done_url: done_url.as_deref().and_then(canonical_http_url),
138+
},
139+
None => OtpNonInteractiveError { auth_url: None, done_url: None },
140+
}
141+
}
142+
}
143+
144+
/// Canonical serialization of an `http`/`https` URL with any userinfo
145+
/// (`user:pass@`) stripped; `None` for an unparsable URL or any other scheme.
146+
///
147+
/// These URLs come from the registry and get displayed, opened in a browser,
148+
/// and carried on errors for machine consumption: the scheme restriction
149+
/// keeps a malicious registry from injecting e.g. a `javascript:` URL into
150+
/// something that opens it, and stripping userinfo keeps credential-shaped
151+
/// data out of logs (the capability tokens automation needs live in the
152+
/// path/query, which are preserved).
153+
fn canonical_http_url(value: &str) -> Option<String> {
154+
let mut parsed = url::Url::parse(value).ok()?;
155+
if !matches!(parsed.scheme(), "http" | "https") {
156+
return None;
157+
}
158+
parsed.set_username("").ok()?;
159+
parsed.set_password(None).ok()?;
160+
Some(parsed.to_string())
161+
}
125162

126163
/// The registry asked for an OTP a second time after one was already
127164
/// supplied (`ERR_PNPM_OTP_SECOND_CHALLENGE`).
@@ -203,11 +240,18 @@ where
203240
};
204241

205242
if !Sys::stdin_is_tty() || !Sys::stdout_is_tty() {
206-
return Err(WithOtpError::NonInteractive(OtpNonInteractiveError));
243+
return Err(WithOtpError::NonInteractive(OtpNonInteractiveError::new(challenge.body)));
207244
}
208245

209-
let otp = match challenge.body {
246+
let web_auth_urls = match &challenge.body {
210247
Some(OtpErrorBody { auth_url: Some(auth_url), done_url: Some(done_url) }) => {
248+
canonical_http_url(auth_url).zip(canonical_http_url(done_url))
249+
}
250+
_ => None,
251+
};
252+
253+
let otp = match web_auth_urls {
254+
Some((auth_url, done_url)) => {
211255
let qr_code = generate_qr_code(&auth_url).map_err(WithOtpError::QrCode)?;
212256
global_info::<Reporter>(&format!(
213257
"Authenticate your account at:\n{auth_url}\n\n{qr_code}",
@@ -222,12 +266,14 @@ where
222266
.map(Some)
223267
.map_err(WithOtpError::Timeout)?
224268
}
225-
_ => match Sys::input("This operation requires a one-time password.\nEnter OTP:").await {
226-
Ok(value) => value.filter(|otp| !otp.is_empty()),
227-
// The user aborted the prompt: re-throw the original challenge.
228-
Err(PromptError::Cancelled) => return Err(WithOtpError::Operation(error)),
229-
Err(other) => return Err(WithOtpError::Prompt(other)),
230-
},
269+
None => {
270+
match Sys::input("This operation requires a one-time password.\nEnter OTP:").await {
271+
Ok(value) => value.filter(|otp| !otp.is_empty()),
272+
// The user aborted the prompt: re-throw the original challenge.
273+
Err(PromptError::Cancelled) => return Err(WithOtpError::Operation(error)),
274+
Err(other) => return Err(WithOtpError::Prompt(other)),
275+
}
276+
}
231277
};
232278

233279
let Some(otp) = otp else {

‎pacquet/crates/network-web-auth/src/with_otp_handling/tests.rs‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,89 @@ async fn throws_non_interactive_error_when_stdout_is_not_interactive() {
290290
assert!(matches!(error, WithOtpError::NonInteractive(_)), "got {error:?}");
291291
}
292292

293+
#[tokio::test]
294+
async fn preserves_web_auth_urls_on_non_interactive_error() {
295+
reset();
296+
STDIN_TTY.with(|tty| tty.set(false));
297+
298+
let error = with_otp_handling::<Fake, UnexpectedReporter, String, TestError, _>(
299+
WebAuthFetchOptions::default(),
300+
async |_otp| Err(TestError::Otp { body: web_auth_body() }),
301+
)
302+
.await
303+
.expect_err("an error");
304+
305+
match error {
306+
WithOtpError::NonInteractive(error) => {
307+
assert_eq!(error.auth_url.as_deref(), Some("https://registry.npmjs.org/auth/abc"));
308+
assert_eq!(error.done_url.as_deref(), Some("https://registry.npmjs.org/auth/abc/done"));
309+
}
310+
other => panic!("expected non-interactive error, got {other:?}"),
311+
}
312+
}
313+
314+
#[tokio::test]
315+
async fn strips_credentials_from_web_auth_urls_on_non_interactive_error() {
316+
reset();
317+
STDIN_TTY.with(|tty| tty.set(false));
318+
319+
let error = with_otp_handling::<Fake, UnexpectedReporter, String, TestError, _>(
320+
WebAuthFetchOptions::default(),
321+
async |_otp| {
322+
Err(TestError::Otp {
323+
body: Some(OtpErrorBody {
324+
auth_url: Some("https://user:[email protected]/auth/abc".to_owned()),
325+
done_url: Some(
326+
"https://user:[email protected]/auth/abc/done?authId=xyz"
327+
.to_owned(),
328+
),
329+
}),
330+
})
331+
},
332+
)
333+
.await
334+
.expect_err("an error");
335+
336+
match error {
337+
WithOtpError::NonInteractive(error) => {
338+
assert_eq!(error.auth_url.as_deref(), Some("https://registry.npmjs.org/auth/abc"));
339+
assert_eq!(
340+
error.done_url.as_deref(),
341+
Some("https://registry.npmjs.org/auth/abc/done?authId=xyz"),
342+
);
343+
}
344+
other => panic!("expected non-interactive error, got {other:?}"),
345+
}
346+
}
347+
348+
#[tokio::test]
349+
async fn omits_non_http_web_auth_urls_on_non_interactive_error() {
350+
reset();
351+
STDIN_TTY.with(|tty| tty.set(false));
352+
353+
let error = with_otp_handling::<Fake, UnexpectedReporter, String, TestError, _>(
354+
WebAuthFetchOptions::default(),
355+
async |_otp| {
356+
Err(TestError::Otp {
357+
body: Some(OtpErrorBody {
358+
auth_url: Some("javascript:alert(1)".to_owned()),
359+
done_url: Some("file:///tmp/token".to_owned()),
360+
}),
361+
})
362+
},
363+
)
364+
.await
365+
.expect_err("an error");
366+
367+
match error {
368+
WithOtpError::NonInteractive(error) => {
369+
assert_eq!(error.auth_url, None);
370+
assert_eq!(error.done_url, None);
371+
}
372+
other => panic!("expected non-interactive error, got {other:?}"),
373+
}
374+
}
375+
293376
#[tokio::test]
294377
async fn classic_flow_prompts_for_otp_and_retries_operation() {
295378
reset();
@@ -444,6 +527,36 @@ async fn web_auth_flow_polls_done_url_and_uses_returned_token() {
444527
);
445528
}
446529

530+
#[tokio::test]
531+
async fn web_auth_flow_falls_back_to_classic_prompt_when_urls_are_not_http() {
532+
reset();
533+
set_input(InputResponse::Value(Some("manual-code".to_owned())));
534+
let calls = Rc::new(Cell::new(0));
535+
let counter = Rc::clone(&calls);
536+
537+
let result = with_otp_handling::<Fake, RecordingReporter, String, TestError, _>(
538+
WebAuthFetchOptions::default(),
539+
async move |otp| {
540+
counter.set(counter.get() + 1);
541+
if counter.get() == 1 {
542+
Err(TestError::Otp {
543+
body: Some(OtpErrorBody {
544+
auth_url: Some("javascript:alert(1)".to_owned()),
545+
done_url: Some("file:///tmp/token".to_owned()),
546+
}),
547+
})
548+
} else {
549+
assert_eq!(otp, Some("manual-code"));
550+
Ok("done".to_owned())
551+
}
552+
},
553+
)
554+
.await
555+
.expect("a result");
556+
557+
assert_eq!(result, "done");
558+
}
559+
447560
#[tokio::test]
448561
async fn web_auth_flow_falls_back_to_classic_prompt_when_only_auth_url_is_present() {
449562
reset();

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm11/network/web-auth/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export {
1515
} from './promptBrowserOpen.js'
1616
export { WebAuthTimeoutError } from './WebAuthTimeoutError.js'
1717
export {
18+
canonicalHttpUrl,
1819
isOtpError,
1920
type OtpContext,
2021
type OtpEnquirer,

‎pnpm11/network/web-auth/src/withOtpHandling.ts‎

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,21 +84,23 @@ export async function withOtpHandling<T> ({
8484
} catch (error) {
8585
if (!isOtpError(error)) throw error
8686
if (!process.stdin.isTTY || !process.stdout.isTTY) {
87-
throw new OtpNonInteractiveError()
87+
throw new OtpNonInteractiveError(error.body)
8888
}
8989

9090
let otp: string | undefined
9191

92-
if (error.body?.authUrl && error.body?.doneUrl) {
93-
const qrCode = generateQrCode(error.body.authUrl)
94-
globalInfo(`Authenticate your account at:\n${error.body.authUrl}\n\n${qrCode}`)
92+
const authUrl = canonicalHttpUrl(error.body?.authUrl)
93+
const doneUrl = canonicalHttpUrl(error.body?.doneUrl)
94+
if (authUrl != null && doneUrl != null) {
95+
const qrCode = generateQrCode(authUrl)
96+
globalInfo(`Authenticate your account at:\n${authUrl}\n\n${qrCode}`)
9597
const pollPromise = pollForWebAuthToken({
9698
context,
97-
doneUrl: error.body.doneUrl,
99+
doneUrl,
98100
fetchOptions,
99101
})
100102
otp = await promptBrowserOpen({
101-
authUrl: error.body.authUrl,
103+
authUrl,
102104
context,
103105
pollPromise,
104106
})
@@ -176,10 +178,46 @@ export class SyntheticOtpError extends Error implements OtpError {
176178
}
177179

178180
export class OtpNonInteractiveError extends PnpmError {
179-
constructor () {
181+
readonly authUrl?: string
182+
readonly doneUrl?: string
183+
184+
constructor (body?: OtpErrorBody) {
180185
super('OTP_NON_INTERACTIVE', 'The registry requires additional authentication, but pnpm is not running in an interactive terminal', {
181186
hint: 'Re-run this command in an interactive terminal to complete authentication, or provide the --otp option if you are using a classic one-time password (OTP)',
182187
})
188+
const authUrl = canonicalHttpUrl(body?.authUrl)
189+
if (authUrl != null) {
190+
this.authUrl = authUrl
191+
}
192+
const doneUrl = canonicalHttpUrl(body?.doneUrl)
193+
if (doneUrl != null) {
194+
this.doneUrl = doneUrl
195+
}
196+
}
197+
}
198+
199+
/**
200+
* Returns the canonical serialization of an `http:`/`https:` URL with any
201+
* userinfo (`user:pass@`) stripped, or `undefined` for a non-string, an
202+
* unparsable URL, or any other scheme.
203+
*
204+
* These URLs come from the registry and get displayed, opened in a browser,
205+
* and emitted in parseable error output: the scheme restriction keeps a
206+
* malicious registry from injecting e.g. a `javascript:` URL into something
207+
* that opens it, and stripping userinfo keeps credential-shaped data out of
208+
* logs (the capability tokens automation needs live in the path/query, which
209+
* are preserved).
210+
*/
211+
export function canonicalHttpUrl (value: unknown): string | undefined {
212+
if (typeof value !== 'string') return undefined
213+
try {
214+
const url = new URL(value)
215+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined
216+
url.username = ''
217+
url.password = ''
218+
return url.href
219+
} catch {
220+
return undefined
183221
}
184222
}
185223

0 commit comments

Comments
 (0)