use crate::{EventPayload, PayloadValue};
pub const MAX_SCHEME_LEN: usize = 64;
const REFUSED_SCHEMES: &[&str] = &[
"http",
"https",
"file",
"javascript",
"vbscript",
"data",
"blob",
"about",
"asset",
];
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct AuthSessionRequest {
pub url: String,
pub callback_scheme: String,
pub ephemeral: bool,
}
impl AuthSessionRequest {
pub fn new(url: impl Into<String>, callback_scheme: impl Into<String>) -> Self {
Self {
url: url.into(),
callback_scheme: callback_scheme.into(),
ephemeral: false,
}
}
pub fn ephemeral(mut self, ephemeral: bool) -> Self {
self.ephemeral = ephemeral;
self
}
pub fn check(&self) -> Result<(), String> {
crate::open_url::check_url(&self.url)
.map_err(|e| e.replacen("openUrl:", "openAuthSession:", 1))?;
let parsed =
url::Url::parse(&self.url).map_err(|e| format!("openAuthSession: not a URL: {e}"))?;
if !matches!(parsed.scheme(), "https" | "http") {
return Err(format!(
"openAuthSession: the sign-in page is a web address, not a `{}:` URL",
parsed.scheme()
));
}
let scheme = &self.callback_scheme;
if scheme.len() > MAX_SCHEME_LEN {
return Err(format!(
"openAuthSession: a callback scheme has at most {MAX_SCHEME_LEN} bytes"
));
}
let mut chars = scheme.chars();
let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
if !valid {
return Err(format!(
"openAuthSession: `{scheme}` is not a URL scheme (give it without `:`)"
));
}
if REFUSED_SCHEMES.contains(&scheme.to_ascii_lowercase().as_str()) {
return Err(format!(
"openAuthSession: `{scheme}:` is not a callback scheme (use one of the app's own)"
));
}
Ok(())
}
pub(crate) fn scheme(&self) -> String {
self.callback_scheme.to_ascii_lowercase()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthSessionOutcome {
Completed(String),
Cancelled,
}
impl AuthSessionOutcome {
pub fn payload(&self, id: u32) -> EventPayload {
let mut fields = vec![("id", PayloadValue::Number(id as f64))];
match self {
AuthSessionOutcome::Completed(url) => {
fields.push(("url", PayloadValue::Str(url.clone())))
}
AuthSessionOutcome::Cancelled => {
fields.push(("action", PayloadValue::Str("cancelled".into())));
}
}
EventPayload::Map(fields)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct AuthSessionError {
pub code: Option<String>,
pub message: String,
}
impl AuthSessionError {
pub fn failed(message: impl Into<String>) -> Self {
Self {
code: None,
message: message.into(),
}
}
pub fn unavailable(message: impl Into<String>) -> Self {
Self {
code: Some(crate::element::codes::UNAVAILABLE.into()),
message: message.into(),
}
}
pub fn payload(&self, id: u32) -> EventPayload {
let mut fields = vec![
("id", PayloadValue::Number(id as f64)),
("error", PayloadValue::Str(self.message.clone())),
];
if let Some(code) = &self.code {
fields.push(("code", PayloadValue::Str(code.clone())));
}
EventPayload::Map(fields)
}
}
impl std::fmt::Display for AuthSessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for AuthSessionError {}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct AuthSessionPage {
pub url: String,
pub callback_scheme: String,
pub ephemeral: bool,
}
impl AuthSessionPage {
pub(crate) fn new(request: &AuthSessionRequest) -> Self {
Self {
url: request.url.clone(),
callback_scheme: request.scheme(),
ephemeral: request.ephemeral,
}
}
}
pub(crate) fn answer_from_payload(
payload: &EventPayload,
) -> Option<(u32, Result<AuthSessionOutcome, AuthSessionError>)> {
let EventPayload::Map(fields) = payload else {
return None;
};
let text = |key: &str| {
fields.iter().find_map(|(k, v)| match v {
PayloadValue::Str(s) if *k == key => Some(s.clone()),
_ => None,
})
};
let id = fields.iter().find_map(|(k, v)| match v {
PayloadValue::Number(n) if *k == "id" => Some(*n as u32),
_ => None,
})?;
if let Some(message) = text("error") {
return Some((
id,
Err(AuthSessionError {
code: text("code"),
message,
}),
));
}
let outcome = match text("url") {
Some(url) => AuthSessionOutcome::Completed(url),
None => AuthSessionOutcome::Cancelled,
};
Some((id, Ok(outcome)))
}
pub(crate) fn is_callback(url: &str, scheme: &str) -> bool {
url::Url::parse(url).is_ok_and(|parsed| parsed.scheme() == scheme)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_request_opens_a_web_page_and_ends_with_an_app_scheme() {
let ok = AuthSessionRequest::new("https://example.com/authorize?x=1", "com.example.app");
assert!(ok.check().is_ok());
assert!(
AuthSessionRequest::new("http://127.0.0.1:8080/authorize", "my-app+1")
.check()
.is_ok()
);
for (url, scheme) in [
("myapp://authorize", "myapp"),
("javascript:alert(1)", "myapp"),
("https://example.com/a b", "myapp"),
("https://example.com", ""),
("https://example.com", "myapp:"),
("https://example.com", "1app"),
("https://example.com", "https"),
("https://example.com", "HTTP"),
("https://example.com", "file"),
] {
assert!(
AuthSessionRequest::new(url, scheme).check().is_err(),
"{url} {scheme}"
);
}
let long = "a".repeat(MAX_SCHEME_LEN + 1);
assert!(
AuthSessionRequest::new("https://example.com", long)
.check()
.is_err()
);
}
#[test]
fn payloads_round_trip() {
let done = AuthSessionOutcome::Completed("myapp://done?code=1".into());
assert_eq!(answer_from_payload(&done.payload(3)), Some((3, Ok(done))));
let cancelled = AuthSessionOutcome::Cancelled;
assert_eq!(
answer_from_payload(&cancelled.payload(4)),
Some((4, Ok(cancelled)))
);
let error = AuthSessionError::unavailable("no browser");
assert_eq!(
answer_from_payload(&error.payload(5)),
Some((5, Err(error)))
);
assert_eq!(answer_from_payload(&EventPayload::None), None);
}
#[test]
fn a_callback_is_a_url_of_the_scheme() {
let page = AuthSessionPage::new(&AuthSessionRequest::new("https://example.com", "MyApp"));
assert_eq!(page.callback_scheme, "myapp");
assert!(is_callback("MYAPP://done?code=1", &page.callback_scheme));
assert!(!is_callback("other://done", &page.callback_scheme));
assert!(!is_callback("not a url", &page.callback_scheme));
}
}