use crate::config::DEFAULT_OPERATOR_NAME;
#[derive(Clone, Debug)]
pub(crate) struct Operator {
name: String,
url: Option<String>,
host: String,
}
impl Operator {
pub(crate) fn new(name: &str, url: Option<&str>, host: &str) -> Self {
Self {
name: name.to_owned(),
url: url.map(str::to_owned),
host: host.to_owned(),
}
}
pub(crate) fn from_config(config: &crate::Config) -> Self {
Self::new(
&crate::config::operator_name(Some(&config.operator_name)),
config.operator_url.as_deref(),
&config.public_host(),
)
}
fn is_named(&self) -> bool {
self.name != DEFAULT_OPERATOR_NAME
}
fn title(&self) -> String {
if self.is_named() {
escape(&self.name)
} else {
"Integration proxy".to_owned()
}
}
fn linked_name(&self) -> String {
match &self.url {
Some(url) => format!(
r#"<a href="{}" rel="noopener noreferrer">{}</a>"#,
escape(url),
escape(&self.name)
),
None => escape(&self.name),
}
}
}
pub fn render_home(operator: &Operator) -> String {
let brand = match &operator.url {
Some(url) => format!(
r#"<a class="brand" href="{}" rel="noopener noreferrer">{}</a>"#,
escape(url),
operator.title()
),
None => format!(r#"<a class="brand" href="/">{}</a>"#, operator.title()),
};
let run_by = if operator.is_named() {
operator.linked_name()
} else {
format!(
"the operator of <strong>{}</strong>",
escape(&operator.host)
)
};
fill(
include_str!("../static/index.html"),
&[
("title", &operator.title()),
("brand", &brand),
("host", &escape(&operator.host)),
("operator", &run_by),
],
)
}
fn fill(template: &str, values: &[(&str, &str)]) -> String {
let mut out = String::with_capacity(template.len());
let mut rest = template;
while let Some(start) = rest.find("{{") {
out.push_str(&rest[..start]);
let after = &rest[start + 2..];
let found = after.find("}}").and_then(|end| {
values
.iter()
.find(|(key, _)| *key == &after[..end])
.map(|(_, value)| (end, *value))
});
match found {
Some((end, value)) => {
out.push_str(value);
rest = &after[end + 2..];
}
None => {
out.push_str("{{");
rest = after;
}
}
}
out.push_str(rest);
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConnectKind<'a> {
OAuth,
ApiKey(ApiKeyHelp<'a>),
NoCredential,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ApiKeyHelp<'a> {
pub description: Option<&'a str>,
pub help_url: Option<&'a str>,
pub problem: Option<&'a str>,
}
pub fn render_platform_connect(
operator: &Operator,
platform: &str,
destination: &str,
csrf: &str,
kind: ConnectKind<'_>,
) -> String {
let (api_key_field, button_label) = match kind {
ConnectKind::ApiKey(help) => (
api_key_field(platform, help),
format!("Connect {}", escape(&platform_label(platform))),
),
ConnectKind::OAuth | ConnectKind::NoCredential => (
String::new(),
format!(
"Use {} to sync {} with this destination",
escape(&operator.name),
escape(&platform_label(platform))
),
),
};
let what = if kind == ConnectKind::NoCredential {
"{platform} needs no account: this proxy reads it without a credential and stores none. Connecting only records the connection."
} else {
"Connecting lets this proxy use your {platform} account on your behalf."
};
let run_by = if operator.is_named() {
operator.linked_name()
} else {
"an operator it does not name".to_owned()
};
let body = format!(
r#"
<div class="card">
<h1>Connect {platform}</h1>
<p class="operator">Integration proxy <strong>{host}</strong>, run by {run_by}.</p>
<p>Destination: <span class="email">{destination}</span></p>
<p class="secret-help">{what} The destination finishes connecting by signing with your Atomic key; it becomes the connection's owner.</p>
<form method="post" action="/connect/authorize">
<input type="hidden" name="csrf" value="{csrf}" />
{api_key_field}
<button class="button" type="submit">{button_label}</button>
</form>
</div>
<script>{script}</script>
"#,
script = CONSENT_SCRIPT,
platform = escape(&platform_label(platform)),
host = escape(&operator.host),
destination = escape(destination),
csrf = escape(csrf),
what = what.replace("{platform}", &escape(&platform_label(platform))),
);
page(
operator,
&format!("Connect {}", platform_label(platform)),
"",
&body,
)
}
fn api_key_field(platform: &str, help: ApiKeyHelp<'_>) -> String {
let mut html = String::new();
if let Some(problem) = help.problem {
html.push_str(&format!(
r#"<p class="problem" role="alert">{}</p>"#,
escape(problem)
));
}
html.push_str(&format!(
r#"<p class="secret-help">{}</p>"#,
escape(
help.description
.unwrap_or("Find this in your account settings on the platform's own site.")
)
));
if let Some(url) = help.help_url {
html.push_str(&format!(
r#"<p class="secret-help"><a href="{}" target="_blank" rel="noopener noreferrer">Where to find your {} API key</a> (opens in a new tab)</p>"#,
escape(url),
escape(&platform_label(platform))
));
}
html.push_str(
r#"<p class="secret-help">The key is stored encrypted on this proxy and never sent back to the destination.</p>
<input class="button" style="background:white;color:#202124;border:1px solid #ccc" type="password" name="api_key" autocomplete="off" placeholder="API key" required />"#,
);
html
}
pub(crate) const CONSENT_SCRIPT: &str = r#"(function(){var f=document.forms[0];if(!f)return;var b=f.querySelector('button[type="submit"]');f.addEventListener('submit',function(e){if(f.getAttribute('data-sent')){e.preventDefault();return;}f.setAttribute('data-sent','1');if(b)b.disabled=true;});window.addEventListener('pageshow',function(e){if(e.persisted){f.removeAttribute('data-sent');if(b)b.disabled=false;}});})();"#;
pub(crate) fn consent_script_hash() -> String {
use base64::{engine::general_purpose::STANDARD, Engine as _};
use sha2::{Digest, Sha256};
format!(
"'sha256-{}'",
STANDARD.encode(Sha256::digest(CONSENT_SCRIPT.as_bytes()))
)
}
pub fn render_oauth_continue(
operator: &Operator,
platform: &str,
authorization_url: &str,
) -> String {
let destination = url::Url::parse(authorization_url)
.ok()
.and_then(|url| url.host_str().map(str::to_owned))
.unwrap_or_default();
let head = format!(
r#"<meta http-equiv="refresh" content="0;url={url}" />
<meta name="referrer" content="no-referrer" />"#,
url = escape(authorization_url),
);
let body = format!(
r#"
<div class="card">
<h1>Continue to {platform}</h1>
<p>Taking you to <strong>{destination}</strong> to authorize the connection.</p>
<a class="button" href="{url}" rel="noreferrer">Continue to {platform}</a>
<p class="secret-help">If nothing happens, use the button. Approving again on the previous page will not work: each approval is used once.</p>
</div>
"#,
platform = escape(&platform_label(platform)),
destination = escape(&destination),
url = escape(authorization_url),
);
page(
operator,
&format!("Continue to {}", platform_label(platform)),
&head,
&body,
)
}
pub(crate) fn platform_label(platform: &str) -> String {
platform
.split('-')
.map(|part| {
let mut chars = part.chars();
match chars.next() {
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
})
.collect::<Vec<_>>()
.join(" ")
}
fn page(operator: &Operator, heading: &str, head: &str, body: &str) -> String {
format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{head}
<title>{heading} ยท {host}</title>
<link rel="icon" type="image/png" href="/logo.png" />
<style>
:root {{ color-scheme: light dark; }}
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
display: flex;
min-height: 100vh;
align-items: center;
justify-content: center;
margin: 0;
background: #f5f5f7;
}}
.card {{
background: white;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0,0,0,0.12);
padding: 2.5rem;
text-align: center;
max-width: 24rem;
}}
.avatar {{
width: 4rem;
height: 4rem;
border-radius: 50%;
margin-bottom: 1rem;
}}
.email {{ color: #666; margin-top: -0.5rem; }}
.secret-help {{ color: #666; font-size: 0.85rem; }}
.problem {{ color: #b3261e; font-weight: 600; }}
.operator {{ overflow-wrap: anywhere; }}
.operator a {{ color: inherit; }}
.button {{
display: inline-block;
margin-top: 1rem;
padding: 0.6rem 1.4rem;
background: #1a73e8;
color: white;
text-decoration: none;
border-radius: 6px;
font-weight: 600;
border: none;
cursor: pointer;
font-size: 1rem;
}}
.button-secondary {{ background: #5f6368; }}
@media (prefers-color-scheme: dark) {{
body {{ background: #202124; }}
.card {{ background: #303134; color: #e8eaed; }}
.email {{ color: #9aa0a6; }}
.secret-help {{ color: #9aa0a6; }}
.problem {{ color: #f2b8b5; }}
}}
</style>
</head>
<body>
<main>
<a href="/" aria-label="{title} home" style="display:block;text-align:center;margin-bottom:1rem"><img src="/logo.png" alt="" width="80" height="80" style="border-radius:8px" /></a>
{body}
</main>
</body>
</html>"#,
heading = escape(heading),
head = head,
host = escape(&operator.host),
title = operator.title(),
body = body
)
}
fn escape(input: &str) -> String {
input
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
#[cfg(test)]
mod tests {
use super::*;
fn unnamed() -> Operator {
Operator::new(DEFAULT_OPERATOR_NAME, None, "proxy.example.org")
}
fn named() -> Operator {
Operator::new(
"Atomic Data",
Some("https://atomic.place/"),
"integrations.atomic.place",
)
}
#[test]
fn home_has_no_login() {
for operator in [unnamed(), named()] {
let html = render_home(&operator);
assert!(!html.contains("/auth/login"));
assert!(!html.contains("{{"));
assert!(!html.contains("LocalThought"));
}
}
#[test]
fn home_names_the_operator_and_host() {
let html = render_home(&named());
assert!(html.contains("<title>Atomic Data ยท Connect your tools</title>"));
assert!(html.contains(
r#"<a class="brand" href="https://atomic.place/" rel="noopener noreferrer">Atomic Data</a>"#
));
assert!(html.contains("Integrations ยท integrations.atomic.place"));
assert!(html.contains(
r#"It is run by <a href="https://atomic.place/" rel="noopener noreferrer">Atomic Data</a>."#
));
}
#[test]
fn home_without_an_operator_name_stays_neutral() {
let html = render_home(&unnamed());
assert!(html.contains("<title>Integration proxy ยท Connect your tools</title>"));
assert!(html.contains(r#"<a class="brand" href="/">Integration proxy</a>"#));
assert!(html.contains("It is run by the operator of <strong>proxy.example.org</strong>."));
}
#[test]
fn home_escapes_the_operator_name_url_and_host() {
let html = render_home(&Operator::new(
r#"<script>alert("x")</script> & {{host}}"#,
Some(r#"https://evil.example/"><script>"#),
"h<o>st",
));
assert!(!html.contains("<script>"));
assert!(html.contains("<script>alert("x")</script> & {{host}}"));
assert!(html.contains(r#"href="https://evil.example/"><script>""#));
assert!(html.contains("h<o>st"));
}
#[test]
fn platform_connect_shows_one_selected_platform_and_escapes_fields() {
let html = render_platform_connect(
&unnamed(),
"google-calendar",
"https://hub.example/\"><script>alert(1)</script>",
"csrf&<\"'",
ConnectKind::OAuth,
);
assert!(html.contains("Google Calendar"));
assert!(html
.contains("Use this integration proxy to sync Google Calendar with this destination"));
assert_eq!(html.matches(r#"action="/connect/authorize""#).count(), 1);
assert!(html.contains("name=\"csrf\" value=\"csrf&<"'\""));
assert!(!html.contains("<script>alert"));
assert_eq!(html.matches("<script>").count(), 1, "only CONSENT_SCRIPT");
assert!(!html.contains("api_key"));
assert!(!html.contains("LocalThought"));
assert!(!html.to_lowercase().contains("log in"));
}
#[test]
fn consent_page_shows_the_proxy_host_and_operator() {
let html = render_platform_connect(
&named(),
"google-calendar",
"https://hub.example",
"csrf",
ConnectKind::OAuth,
);
assert!(html.contains("<title>Connect Google Calendar ยท integrations.atomic.place</title>"));
assert!(html.contains(
r#"Integration proxy <strong>integrations.atomic.place</strong>, run by <a href="https://atomic.place/" rel="noopener noreferrer">Atomic Data</a>."#
));
assert!(html.contains("Use Atomic Data to sync Google Calendar with this destination"));
assert!(html.contains(r#"aria-label="Atomic Data home""#));
}
#[test]
fn consent_page_without_an_operator_name_still_shows_the_host() {
let html = render_platform_connect(
&unnamed(),
"clockify",
"https://hub.example",
"csrf",
ConnectKind::ApiKey(ApiKeyHelp::default()),
);
assert!(html.contains(
"Integration proxy <strong>proxy.example.org</strong>, run by an operator it does not name."
));
assert!(html.contains(r#"aria-label="Integration proxy home""#));
}
#[test]
fn consent_page_escapes_the_operator_name_url_and_host() {
let html = render_platform_connect(
&Operator::new(
"Evil <img src=x onerror=alert(1)> 'Co'",
Some(r#"https://evil.example/" onmouseover="alert(1)"#),
r#"host"><script>"#,
),
"google-calendar",
"https://hub.example",
"csrf",
ConnectKind::OAuth,
);
assert_eq!(html.matches("<script>").count(), 1, "only CONSENT_SCRIPT");
assert!(!html.contains(r#""><script>"#));
assert!(!html.contains("<img src=x"));
assert!(!html.contains(r#"" onmouseover="#));
assert!(html.contains("Evil <img src=x onerror=alert(1)> 'Co'"));
assert!(html.contains(r#"href="https://evil.example/" onmouseover="alert(1)""#));
assert!(html.contains("<strong>host"><script></strong>"));
assert!(
html.contains("<title>Connect Google Calendar ยท host"><script></title>")
);
}
#[test]
fn api_key_platforms_ask_for_the_key_on_the_proxy_page() {
let html = render_platform_connect(
&unnamed(),
"clockify",
"https://hub.example",
"csrf",
ConnectKind::ApiKey(ApiKeyHelp::default()),
);
assert!(html.contains(r#"name="api_key""#));
assert!(html.contains("Connect Clockify"));
assert!(html.contains("Find this in your account settings"));
assert!(!html.contains("<a href=\"https://"));
assert!(!html.contains(r#"class="problem""#));
}
#[test]
fn api_key_page_shows_the_description_help_link_and_problem_escaped() {
let html = render_platform_connect(
&unnamed(),
"clockify",
"https://hub.example",
"csrf",
ConnectKind::ApiKey(ApiKeyHelp {
description: Some("Made under <b>Preferences</b> & Advanced."),
help_url: Some(r#"https://help.example/keys?a=1&b="x""#),
problem: Some("Clockify did not accept that key <again>."),
}),
);
assert!(html.contains("Made under <b>Preferences</b> & Advanced."));
assert!(!html.contains("Find this in your account settings"));
assert!(html.contains(
r#"<a href="https://help.example/keys?a=1&b="x"" target="_blank" rel="noopener noreferrer">Where to find your Clockify API key</a>"#
));
assert!(html.contains(
r#"<p class="problem" role="alert">Clockify did not accept that key <again>.</p>"#
));
assert!(!html.contains("http-equiv"));
assert_eq!(html.matches("<script>").count(), 1);
}
#[test]
fn no_credential_platforms_ask_for_nothing_and_say_so() {
let html = render_platform_connect(
&unnamed(),
"pets",
"https://hub.example",
"csrf",
ConnectKind::NoCredential,
);
assert!(!html.contains("api_key"));
assert!(html.contains(
"Pets needs no account: this proxy reads it without a credential and stores none."
));
assert!(!html.contains("use your Pets account"));
assert!(!html.contains("{platform}"));
assert!(html.contains("Use this integration proxy to sync Pets with this destination"));
assert!(html.contains(&format!("<script>{CONSENT_SCRIPT}</script>")));
}
#[test]
fn oauth_continue_page_refreshes_to_the_provider_and_links_it() {
let url = "https://api.provider.example/v1/oauth/authorize?client_id=c&state=s&scope=a+b";
let html = render_oauth_continue(&named(), "notion", url);
let escaped =
"https://api.provider.example/v1/oauth/authorize?client_id=c&state=s&scope=a+b";
assert!(html.contains(&format!(
r#"<meta http-equiv="refresh" content="0;url={escaped}" />"#
)));
assert!(html.contains(&format!(
r#"<a class="button" href="{escaped}" rel="noreferrer">Continue to Notion</a>"#
)));
assert!(html.contains(r#"<meta name="referrer" content="no-referrer" />"#));
assert!(html.contains("<strong>api.provider.example</strong>"));
assert!(html.contains("<title>Continue to Notion ยท integrations.atomic.place</title>"));
assert!(!html.contains("<script"));
assert!(!html.contains("<form"));
}
#[test]
fn oauth_continue_page_escapes_the_address() {
let html = render_oauth_continue(
&unnamed(),
"x",
r#"https://auth.example/a?b="><script>alert(1)</script>"#,
);
assert!(!html.contains("<script"));
assert!(html.contains(""><script>"));
}
#[test]
fn the_consent_script_hash_is_its_sha256() {
use base64::{engine::general_purpose::STANDARD, Engine as _};
use sha2::{Digest, Sha256};
let expected = STANDARD.encode(Sha256::digest(CONSENT_SCRIPT.as_bytes()));
assert_eq!(consent_script_hash(), format!("'sha256-{expected}'"));
let html = render_platform_connect(
&unnamed(),
"clockify",
"https://hub.example",
"csrf",
ConnectKind::ApiKey(ApiKeyHelp::default()),
);
assert!(html.contains(&format!("<script>{CONSENT_SCRIPT}</script>")));
}
#[test]
fn fill_replaces_known_placeholders_once() {
assert_eq!(
fill("a {{x}} b {{y}} {{z", &[("x", "{{y}}"), ("y", "2")]),
"a {{y}} b 2 {{z"
);
}
}