Skip to content
679 linesCodeBlameRaw
1//! Transactional email through Cloudflare Email Sending.
2
3use g1t_kit::js;
4use serde::Serialize;
5use worker::{Env, Result};
6
7const FROM: &str = "g1t <noreply@g1t.sh>";
8const SITE: &str = "https://g1t.sh";
9
10/// Where links in mail point: SITE_URL, or g1t.sh when it is not set (a
11/// self-hosted installation sets it from its PUBLIC_URL).
12pub fn site(env: &Env) -> String {
13 let value = env.var("SITE_URL").map(|value| value.to_string()).unwrap_or_default();
14 let value = value.trim().trim_end_matches('/');
15 if value.is_empty() { SITE.to_owned() } else { value.to_owned() }
16}
17
18/// Who mail is from: MAIL_FROM, or g1t.sh's address when it is not set.
19fn from(env: &Env) -> String {
20 let value = env.var("MAIL_FROM").map(|value| value.to_string()).unwrap_or_default();
21 if value.trim().is_empty() { FROM.to_owned() } else { value.trim().to_owned() }
22}
23
24/// A site's address without its scheme, as mail names it in a sentence.
25fn bare(site: &str) -> &str {
26 site.split_once("://").map_or(site, |(_, rest)| rest)
27}
28
29#[derive(Serialize)]
30struct Message<'a> {
31 to: &'a str,
32 from: &'a str,
33 subject: &'a str,
34 text: String,
35 html: String,
36}
37
38/// What one email says, before it is laid out as text and HTML.
39#[derive(Debug, Default)]
40pub struct Letter {
41 pub paragraphs: Vec<String>,
42 /// Quoted passages, each with who or what it is from: a note from the
43 /// person who sent an invite, or what someone asking for access said.
44 pub quotes: Vec<(String, String)>,
45 /// A code to type, shown large before the button, with the line that
46 /// leads from it to the button.
47 pub code: Option<Code>,
48 /// The button: what it says, and where it goes.
49 pub action: Option<(String, String)>,
50 pub footer: String,
51}
52
53/// A code in a letter, and what joins it to the button after it.
54#[derive(Debug, Default, PartialEq, Eq)]
55pub struct Code {
56 pub code: String,
57 /// Said between the code and the button, such as "or follow the link".
58 pub then: String,
59}
60
61/// The plain text and HTML of a letter. Everything in it is escaped:
62/// names, notes and requests people wrote can reach every line.
63pub fn render(letter: &Letter, site: &str) -> (String, String) {
64 let mut text = String::new();
65 let mut html = format!(
66 "<div style=\"font-family:system-ui,sans-serif;max-width:480px;margin:0 auto;padding:32px 16px;color:#16150f\">\
67 <p style=\"margin:0 0 20px\"><img src=\"{site}/brand/g1t-logo.png\" width=\"60\" height=\"28\" alt=\"g1t\" style=\"display:block;border:0\"></p>"
68 );
69 for paragraph in &letter.paragraphs {
70 text.push_str(paragraph);
71 text.push_str("\n\n");
72 html.push_str(&format!("<p style=\"font-size:15px;line-height:1.6\">{}</p>", escape(paragraph)));
73 }
74 for (from, quote) in &letter.quotes {
75 text.push_str(&format!("{from}:\n"));
76 for line in quote.lines() {
77 text.push_str(&format!("> {line}\n"));
78 }
79 text.push('\n');
80 html.push_str(&format!(
81 "<p style=\"margin:20px 0 6px;font-size:13px;color:#6e6a5e\">{}</p>\
82 <blockquote style=\"margin:0;padding:2px 0 2px 14px;border-left:3px solid #b9a6f2;font-size:15px;line-height:1.6;white-space:pre-line\">{}</blockquote>",
83 escape(from),
84 escape(quote)
85 ));
86 }
87 if let Some(code) = &letter.code {
88 text.push_str(&format!(" {}\n\n{}\n\n", code.code, code.then));
89 html.push_str(&format!(
90 "<p style=\"margin:24px 0;padding:16px 0;text-align:center;background:#f3f1ea;border-radius:8px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:34px;font-weight:600;letter-spacing:10px;color:#16150f\">{}</p>\
91 <p style=\"font-size:15px;line-height:1.6\">{}</p>",
92 escape(&code.code),
93 escape(&code.then)
94 ));
95 }
96 if let Some((label, link)) = &letter.action {
97 text.push_str(&format!("{label}: {link}\n\n"));
98 html.push_str(&format!(
99 "<p style=\"margin:24px 0\"><a href=\"{}\" style=\"background:#16150f;color:#fff;text-decoration:none;padding:10px 18px;border-radius:6px;font-size:15px\">{}</a></p>",
100 escape(link),
101 escape(label)
102 ));
103 }
104 text.push_str(&letter.footer);
105 text.push('\n');
106 html.push_str(&format!(
107 "<p style=\"font-size:13px;line-height:1.6;color:#6e6a5e\">{}</p></div>",
108 escape(&letter.footer)
109 ));
110 (text, html)
111}
112
113/// Sends a letter.
114pub async fn send(env: &Env, to: &str, subject: &str, letter: &Letter) -> Result<()> {
115 let (text, html) = render(letter, &site(env));
116 let from = from(env);
117 let message = Message {
118 to,
119 from: &from,
120 subject,
121 text,
122 html,
123 };
124 let binding = js::binding(env, "EMAIL")?;
125 js::call(&binding, "send", &[js::to_js(&message)?]).await?;
126 Ok(())
127}
128
129/// A short message with one link to follow.
130pub async fn send_link(
131 env: &Env,
132 to: &str,
133 subject: &str,
134 intro: &str,
135 action: &str,
136 link: &str,
137 footer: &str,
138) -> Result<()> {
139 let letter = Letter {
140 paragraphs: vec![intro.to_owned()],
141 quotes: Vec::new(),
142 code: None,
143 action: Some((action.to_owned(), link.to_owned())),
144 footer: footer.to_owned(),
145 };
146 send(env, to, subject, &letter).await
147}
148
149/// Text made safe to put in HTML, in an element or a quoted attribute.
150fn escape(text: &str) -> String {
151 let mut escaped = String::with_capacity(text.len());
152 for c in text.chars() {
153 match c {
154 '&' => escaped.push_str("&amp;"),
155 '<' => escaped.push_str("&lt;"),
156 '>' => escaped.push_str("&gt;"),
157 '"' => escaped.push_str("&quot;"),
158 '\'' => escaped.push_str("&#39;"),
159 c => escaped.push(c),
160 }
161 }
162 escaped
163}
164
165/// What a confirmation email is for.
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub enum Confirming {
168 /// The address a new account signed up with (or changed to before
169 /// confirming any).
170 NewAccount,
171 /// An address added to an account in use.
172 AddedAddress,
173}
174
175/// A confirmation email: the code to type, large, and the link that does
176/// the same, either one enough. The code leads the subject, so a phone's
177/// notification shows it.
178pub fn confirmation_letter(confirming: Confirming, username: &str, code: &str, link: &str) -> (String, Letter) {
179 let minutes = g1t_contracts::accounts::CONFIRM_TTL_SECONDS / 60;
180 let (intro, ignore) = match confirming {
181 Confirming::NewAccount => (
182 format!("Welcome to g1t, {username}. To finish creating your account, enter this code on the confirmation page:"),
183 "If you did not create a g1t account, you can ignore this message.",
184 ),
185 Confirming::AddedAddress => (
186 format!("To add this address to the g1t account {username}, enter this code on the confirmation page:"),
187 "If you did not add this address to a g1t account, you can ignore this message.",
188 ),
189 };
190 let letter = Letter {
191 paragraphs: vec![intro],
192 quotes: Vec::new(),
193 code: Some(Code {
194 code: code.to_owned(),
195 then: "Or skip the code and confirm with this link instead. Either one works; you need only one.".to_owned(),
196 }),
197 action: Some(("Confirm email".to_owned(), link.to_owned())),
198 footer: format!(
199 "The code and the link work for {minutes} minutes, and only once. Asking for a new email ends them both. {ignore}"
200 ),
201 };
202 (format!("{code} is your g1t confirmation code"), letter)
203}
204
205/// Sends a confirmation email with `code` and the link for `token`.
206pub async fn send_confirmation(env: &Env, to: &str, username: &str, confirming: Confirming, token: &str, code: &str) -> Result<()> {
207 let link = format!("{}/verify?token={token}", site(env));
208 let (subject, letter) = confirmation_letter(confirming, username, code, &link);
209 send(env, to, &subject, &letter).await
210}
211
212pub async fn send_password_reset(env: &Env, to: &str, username: &str, token: &str) -> Result<()> {
213 send_link(
214 env,
215 to,
216 "Reset your g1t password",
217 &format!("Someone asked to reset the password for the g1t account {username}."),
218 "Choose a new password",
219 &format!("{}/reset?token={token}", site(env)),
220 "This link works for 1 hour. If this was not you, ignore this message and your password stays the same.",
221 )
222 .await
223}
224
225/// What a security notice says: one sentence about what changed.
226pub fn security_wording(username: &str, change: &str) -> (String, String) {
227 (
228 format!("Security notice for your g1t account {username}"),
229 format!("{change}. This is about your g1t account {username}."),
230 )
231}
232
233/// Tells an account's addresses that something about its security changed.
234pub async fn send_security_notice(env: &Env, to: &str, username: &str, change: &str) -> Result<()> {
235 let (subject, intro) = security_wording(username, change);
236 send_link(
237 env,
238 to,
239 &subject,
240 &intro,
241 "Review your email settings",
242 &format!("{}/settings/emails", site(env)),
243 &format!(
244 "If this was you, there is nothing to do. If it was not, reset your password at {}/forgot straight away and remove any address you do not recognise.",
245 bare(&site(env))
246 ),
247 )
248 .await
249}
250
251/// An invite email: to make an account, or for an existing one to join a
252/// workspace.
253pub struct InviteEmail<'a> {
254 pub to: &'a str,
255 /// Who sent it (a name, or a username); None when g1t staff did.
256 pub from: Option<&'a str>,
257 /// The workspace it joins, by name.
258 pub workspace: Option<&'a str>,
259 pub joins_existing_account: bool,
260 pub code: &'a str,
261 pub days: u64,
262 /// A line from whoever sent it, such as staff approving a request.
263 pub note: Option<&'a str>,
264}
265
266/// The subject and letter of an invite email.
267pub fn invite_letter(invite: &InviteEmail, site: &str) -> (String, Letter) {
268 let (subject, intro) = invite_wording(invite.from, invite.workspace, invite.joins_existing_account);
269 let action = match invite.workspace {
270 Some(workspace) if invite.joins_existing_account => format!("Join {workspace}"),
271 _ => "Accept invite".to_owned(),
272 };
273 let quotes = match invite.note.map(str::trim).filter(|note| !note.is_empty()) {
274 Some(note) => vec![(
275 match invite.from {
276 Some(from) => format!("A note from {from}"),
277 None => "A note from the g1t team".to_owned(),
278 },
279 note.to_owned(),
280 )],
281 None => Vec::new(),
282 };
283 let letter = Letter {
284 paragraphs: vec![intro],
285 quotes,
286 code: None,
287 action: Some((action, format!("{site}/invite/{}", invite.code))),
288 footer: format!(
289 "This invite works for {} days, only for this address. If you were not expecting it, you can ignore this message.",
290 invite.days
291 ),
292 };
293 (subject, letter)
294}
295
296pub async fn send_invite(env: &Env, invite: &InviteEmail<'_>) -> Result<()> {
297 let (subject, letter) = invite_letter(invite, &site(env));
298 send(env, invite.to, &subject, &letter).await
299}
300
301/// Where staff decide on access requests.
302pub const SUDO_WAITLIST: &str = "https://sudo.g1t.sh/invites?tab=waitlist";
303
304/// The one confirmation someone gets after asking for access.
305pub fn waitlist_confirmation(site: &str) -> (String, Letter) {
306 (
307 "You're on the list for g1t".to_owned(),
308 Letter {
309 paragraphs: vec![
310 "Thanks for asking to try g1t. You're on the list, and we'll email you an invite at this address when there's a place for you.".to_owned(),
311 "g1t is invite-only while we open it up a few people at a time, so we can't say exactly when that will be. Someone already on g1t can also invite you sooner.".to_owned(),
312 ],
313 quotes: Vec::new(),
314 code: None,
315 action: None,
316 footer: format!("You're getting this because this address asked for access at {}/register. If that wasn't you, ignore this message; nothing more is sent unless you're invited.", bare(site)),
317 },
318 )
319}
320
321pub async fn send_waitlist_confirmation(env: &Env, to: &str) -> Result<()> {
322 let (subject, letter) = waitlist_confirmation(&site(env));
323 send(env, to, &subject, &letter).await
324}
325
326/// One access request, as a staff summary lists it.
327pub struct Requested {
328 pub email: String,
329 pub about: Option<String>,
330}
331
332/// The most requests one summary lists; the rest are counted.
333pub const SUMMARY_LISTS: usize = 20;
334
335/// The summary staff get of new access requests: every one since the last
336/// summary, and how many are waiting in all.
337pub fn waitlist_summary(new: &[Requested], waiting: u32) -> (String, Letter) {
338 let subject = match new {
339 [one] => format!("g1t access request from {}", one.email),
340 _ => format!("{} new g1t access requests", new.len()),
341 };
342 let asked = match new.len() {
343 1 => "Someone asked for access to g1t.".to_owned(),
344 n => format!("{n} people asked for access to g1t since the last summary."),
345 };
346 let in_all = if waiting as usize > new.len() {
347 format!(" {waiting} requests are waiting in all.")
348 } else {
349 String::new()
350 };
351 let mut quotes: Vec<(String, String)> = new
352 .iter()
353 .take(SUMMARY_LISTS)
354 .map(|request| {
355 (
356 request.email.clone(),
357 request
358 .about
359 .as_deref()
360 .map(str::trim)
361 .filter(|about| !about.is_empty())
362 .unwrap_or("(They did not say what they will build.)")
363 .to_owned(),
364 )
365 })
366 .collect();
367 if new.len() > SUMMARY_LISTS {
368 quotes.push(("And more".to_owned(), format!("{} more requests are on the waitlist.", new.len() - SUMMARY_LISTS)));
369 }
370 let letter = Letter {
371 paragraphs: vec![format!("{asked}{in_all}")],
372 quotes,
373 code: None,
374 action: Some(("Review the waitlist".to_owned(), SUDO_WAITLIST.to_owned())),
375 footer: "Sent to WAITLIST_NOTIFY_EMAIL at most once every 15 minutes. A request that arrives in between is in the next summary, and every request is in sudo straight away.".to_owned(),
376 };
377 (subject, letter)
378}
379
380pub async fn send_waitlist_summary(env: &Env, to: &str, new: &[Requested], waiting: u32) -> Result<()> {
381 let (subject, letter) = waitlist_summary(new, waiting);
382 send(env, to, &subject, &letter).await
383}
384
385/// An invitation to collaborate on one repository. `code` is set when the
386/// address has no account yet: the link then makes one and accepts; without
387/// it, the link opens the invitation to accept or decline.
388pub async fn send_repo_invite(
389 env: &Env,
390 to: &str,
391 from: &str,
392 repo: &str,
393 role: &str,
394 code: Option<&str>,
395 days: u64,
396) -> Result<()> {
397 let (subject, intro) = repo_invite_wording(from, repo, role, code.is_some());
398 let link = match code {
399 Some(code) => format!("{}/invite/{code}", site(env)),
400 None => format!("{}/{repo}/invitations", site(env)),
401 };
402 send_link(
403 env,
404 to,
405 &subject,
406 &intro,
407 "View invitation",
408 &link,
409 &format!("This invitation works for {days} days. If you were not expecting it, you can ignore this message."),
410 )
411 .await
412}
413
414/// Why a person is emailed about an inbox item, as the end of a sentence.
415fn notified_because(reason: g1t_contracts::inbox::Reason) -> &'static str {
416 use g1t_contracts::inbox::Reason;
417 match reason {
418 Reason::Agent => "an agent is waiting on you",
419 Reason::ReviewRequested => "you were asked to review",
420 Reason::Assign => "you were assigned",
421 Reason::Mention => "you were mentioned",
422 Reason::TeamMention => "a team you are in was mentioned",
423 Reason::CiActivity => "it is about your work",
424 Reason::SecurityAlert => "you look after this repository's security",
425 Reason::StateChange => "you are subscribed to it",
426 Reason::Author => "you opened it",
427 Reason::Comment => "you commented on it",
428 Reason::Manual => "you subscribed to it",
429 Reason::Subscribed => "you watch this repository",
430 }
431}
432
433/// An item from the inbox, by email: what happened, what it happened to,
434/// and a link to it.
435pub fn notification_letter(a: &g1t_contracts::inbox::NotifyByEmailArgs, site: &str) -> Letter {
436 let path = if a.path.starts_with('/') { a.path.clone() } else { format!("/{}", a.path) };
437 Letter {
438 paragraphs: [a.subject.trim(), a.intro.trim()]
439 .into_iter()
440 .filter(|line| !line.is_empty())
441 .map(str::to_owned)
442 .collect(),
443 quotes: a.quote.iter().cloned().collect(),
444 code: None,
445 action: Some(("Open on g1t".to_owned(), format!("{site}{path}"))),
446 footer: format!(
447 "You are getting this because {}. Choose what you are emailed for at {site}/settings/notifications.",
448 notified_because(a.reason)
449 ),
450 }
451}
452
453pub async fn send_notification(env: &Env, to: &str, a: &g1t_contracts::inbox::NotifyByEmailArgs) -> Result<()> {
454 let letter = notification_letter(a, &site(env));
455 send(env, to, &a.subject, &letter).await
456}
457
458/// The subject and first line of a repository invitation.
459pub fn repo_invite_wording(from: &str, repo: &str, role: &str, new_account: bool) -> (String, String) {
460 let subject = format!("{from} invited you to {repo} on g1t");
461 let intro = if new_account {
462 format!(
463 "{from} invited you to collaborate on {repo} on g1t, with the {role} role. Accepting makes your g1t account and gives you access to {repo}."
464 )
465 } else {
466 format!("{from} invited you to collaborate on {repo} on g1t, with the {role} role.")
467 };
468 (subject, intro)
469}
470
471/// The subject and first line of an invite email.
472pub fn invite_wording(from: Option<&str>, workspace: Option<&str>, joins_existing_account: bool) -> (String, String) {
473 let who = from.unwrap_or("The g1t team");
474 match (workspace, joins_existing_account) {
475 (Some(workspace), true) => (
476 format!("{who} invited you to {workspace} on g1t"),
477 format!("{who} invited you to join the {workspace} workspace on g1t."),
478 ),
479 (Some(workspace), false) => (
480 format!("{who} invited you to {workspace} on g1t"),
481 format!(
482 "{who} invited you to join the {workspace} workspace on g1t, where people and agents ship software together. Accepting makes your account and joins you to {workspace}."
483 ),
484 ),
485 (None, _) => (
486 match from {
487 Some(from) => format!("{from} invited you to g1t"),
488 None => "Your invite to g1t".to_owned(),
489 },
490 format!("{who} invited you to g1t, where people and agents ship software together. g1t is invite-only for now; this invite lets you make your account."),
491 ),
492 }
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 #[test]
500 fn html_is_escaped() {
501 assert_eq!(
502 escape("<a href=\"x\">Tom & Jerry's</a>"),
503 "&lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&#39;s&lt;/a&gt;"
504 );
505 assert_eq!(escape("https://g1t.sh/verify?token=ab12"), "https://g1t.sh/verify?token=ab12");
506 }
507
508 #[test]
509 fn an_inbox_item_says_what_happened_and_why_it_was_sent() {
510 let a = g1t_contracts::inbox::NotifyByEmailArgs {
511 username: "ana".into(),
512 repo_id: "rep_1".into(),
513 subject: "bo asked you to review acme/rocket#7".into(),
514 intro: "Add the inbox".into(),
515 quote: None,
516 path: "/acme/rocket/pull/7".into(),
517 reason: g1t_contracts::inbox::Reason::ReviewRequested,
518 };
519 let letter = notification_letter(&a, SITE);
520 assert_eq!(letter.paragraphs, vec!["bo asked you to review acme/rocket#7", "Add the inbox"]);
521 assert_eq!(letter.action.unwrap().1, "https://g1t.sh/acme/rocket/pull/7");
522 assert!(letter.footer.starts_with("You are getting this because you were asked to review."));
523 assert!(letter.footer.ends_with("https://g1t.sh/settings/notifications."));
524 }
525
526 #[test]
527 fn invites_say_who_sent_them_and_what_they_are_for() {
528 let (subject, intro) = invite_wording(Some("ada"), None, false);
529 assert_eq!(subject, "ada invited you to g1t");
530 assert!(intro.starts_with("ada invited you to g1t"));
531 let (subject, _) = invite_wording(None, None, false);
532 assert_eq!(subject, "Your invite to g1t");
533 let (subject, intro) = invite_wording(Some("ada"), Some("acme"), true);
534 assert_eq!(subject, "ada invited you to acme on g1t");
535 assert_eq!(intro, "ada invited you to join the acme workspace on g1t.");
536 let (_, intro) = invite_wording(Some("ada"), Some("acme"), false);
537 assert!(intro.contains("makes your account and joins you to acme"));
538 }
539
540 fn invite<'a>(note: Option<&'a str>, from: Option<&'a str>) -> InviteEmail<'a> {
541 InviteEmail {
542 to: "ada@example.com",
543 from,
544 workspace: Some("Flagon, Inc."),
545 joins_existing_account: false,
546 code: "g1t-abcd",
547 days: 30,
548 note,
549 }
550 }
551
552 #[test]
553 fn an_invite_links_to_its_page_and_carries_a_note() {
554 let (subject, letter) = invite_letter(&invite(Some("Welcome aboard <3"), None), SITE);
555 assert_eq!(subject, "The g1t team invited you to Flagon, Inc. on g1t");
556 assert_eq!(letter.action.as_ref().unwrap().1, "https://g1t.sh/invite/g1t-abcd");
557 assert_eq!(letter.quotes, vec![("A note from the g1t team".to_owned(), "Welcome aboard <3".to_owned())]);
558 let (text, html) = render(&letter, SITE);
559 assert!(text.contains("> Welcome aboard <3"));
560 assert!(html.contains("Welcome aboard &lt;3"));
561 assert!(!html.contains("<3"));
562 // No note, no quote; a blank note is no note.
563 assert!(invite_letter(&invite(None, Some("Chase Pierce")), SITE).1.quotes.is_empty());
564 assert!(invite_letter(&invite(Some(" "), Some("Chase Pierce")), SITE).1.quotes.is_empty());
565 assert_eq!(invite_letter(&invite(Some("hi"), Some("Chase Pierce")), SITE).1.quotes[0].0, "A note from Chase Pierce");
566 }
567
568 #[test]
569 fn links_point_at_the_site_they_are_given() {
570 let (_, letter) = invite_letter(&invite(None, None), "http://localhost:8787");
571 assert_eq!(letter.action.as_ref().unwrap().1, "http://localhost:8787/invite/g1t-abcd");
572 let (text, html) = render(&letter, "http://localhost:8787");
573 assert!(html.contains("http://localhost:8787/brand/g1t-logo.png"));
574 assert!(!text.contains("g1t.sh/") && !html.contains("https://g1t.sh"));
575 let (_, letter) = waitlist_confirmation("http://localhost:8787");
576 assert!(letter.footer.contains("localhost:8787/register"));
577 assert_eq!(bare("https://git.example.com"), "git.example.com");
578 }
579
580 #[test]
581 fn the_waitlist_confirmation_promises_no_date() {
582 let (subject, letter) = waitlist_confirmation(SITE);
583 assert_eq!(subject, "You're on the list for g1t");
584 let (text, _) = render(&letter, SITE);
585 assert!(text.contains("g1t.sh/register"));
586 assert!(text.contains("we'll email you an invite"));
587 assert!(text.contains("can't say exactly when"));
588 assert!(letter.action.is_none());
589 }
590
591 #[test]
592 fn staff_summaries_list_each_request_and_link_to_sudo() {
593 let one = [Requested { email: "ada@example.com".into(), about: Some("A compiler <for> fun".into()) }];
594 let (subject, letter) = waitlist_summary(&one, 1);
595 assert_eq!(subject, "g1t access request from ada@example.com");
596 assert_eq!(letter.paragraphs, vec!["Someone asked for access to g1t."]);
597 assert_eq!(letter.action.as_ref().unwrap().1, SUDO_WAITLIST);
598 let (_, html) = render(&letter, SITE);
599 assert!(html.contains("A compiler &lt;for&gt; fun"));
600
601 let many: Vec<Requested> = (0..25).map(|n| Requested { email: format!("p{n}@example.com"), about: None }).collect();
602 let (subject, letter) = waitlist_summary(&many, 40);
603 assert_eq!(subject, "25 new g1t access requests");
604 assert_eq!(
605 letter.paragraphs[0],
606 "25 people asked for access to g1t since the last summary. 40 requests are waiting in all."
607 );
608 assert_eq!(letter.quotes.len(), SUMMARY_LISTS + 1);
609 assert_eq!(letter.quotes[0].1, "(They did not say what they will build.)");
610 assert!(letter.quotes.last().unwrap().1.starts_with("5 more"));
611 }
612
613 #[test]
614 fn a_confirmation_email_shows_the_code_large_and_the_link_as_the_other_way() {
615 let (subject, letter) = confirmation_letter(Confirming::NewAccount, "ada", "482913", "https://g1t.sh/verify?token=ab12");
616 assert_eq!(subject, "482913 is your g1t confirmation code");
617 assert!(letter.paragraphs[0].starts_with("Welcome to g1t, ada."));
618 assert_eq!(letter.action.as_ref().unwrap().1, "https://g1t.sh/verify?token=ab12");
619 assert!(letter.footer.contains("60 minutes, and only once"));
620 let (text, html) = render(&letter, SITE);
621 // The code comes before the link, and says either one works.
622 let code_at = text.find(" 482913").unwrap();
623 let link_at = text.find("Confirm email: https://g1t.sh/verify?token=ab12").unwrap();
624 assert!(code_at < link_at);
625 assert!(text.contains("Either one works"));
626 assert!(html.contains("font-size:34px"));
627 assert!(html.contains(">482913</p>"));
628 assert!(html.find("482913").unwrap() < html.find("verify?token=ab12").unwrap());
629 let (_, added) = confirmation_letter(Confirming::AddedAddress, "ada", "000001", "x");
630 assert!(added.paragraphs[0].contains("add this address to the g1t account ada"));
631 assert!(added.footer.contains("did not add this address"));
632 }
633
634 /// Writes each email as HTML for a look in a browser:
635 /// `G1T_WRITE_EMAILS=<dir> cargo test -p g1t-identity write_emails`.
636 #[test]
637 fn write_emails() {
638 let Ok(dir) = std::env::var("G1T_WRITE_EMAILS") else { return };
639 let page = |name: &str, subject: &str, letter: &Letter| {
640 let (_, html) = render(letter, SITE);
641 std::fs::write(
642 format!("{dir}/{name}.html"),
643 format!("<!doctype html><meta charset=utf-8><title>{}</title><body style=\"margin:0;background:#fff\">{html}", escape(subject)),
644 )
645 .unwrap();
646 };
647 let (subject, letter) = waitlist_confirmation(SITE);
648 page("waitlist-confirmation", &subject, &letter);
649 let requests = [
650 Requested { email: "ada@example.com".into(), about: Some("A compiler for a teaching language, with agents writing the test suite.".into()) },
651 Requested { email: "linus@example.com".into(), about: None },
652 ];
653 let (subject, letter) = waitlist_summary(&requests, 7);
654 page("waitlist-summary", &subject, &letter);
655 let (subject, letter) = invite_letter(&InviteEmail {
656 to: "margaret@example.com",
657 from: Some("Chase Pierce"),
658 workspace: Some("Flagon, Inc."),
659 joins_existing_account: false,
660 code: "g1t-k7m2-q9xd-4hpw-abcd-0123-4567-89ef-ghjk",
661 days: 30,
662 note: None,
663 }, SITE);
664 page("workspace-invite", &subject, &letter);
665 let (subject, letter) = invite_letter(&InviteEmail {
666 to: "ada@example.com",
667 from: None,
668 workspace: None,
669 joins_existing_account: false,
670 code: "g1t-k7m2-q9xd-4hpw-abcd-0123-4567-89ef-ghjk",
671 days: 30,
672 note: Some("Thanks for waiting. We would love to see the compiler."),
673 }, SITE);
674 page("waitlist-approved", &subject, &letter);
675 let (subject, letter) =
676 confirmation_letter(Confirming::NewAccount, "ada", "482913", "https://g1t.sh/verify?token=4f9c2a7e0b13d5c8");
677 page("confirm-email", &subject, &letter);
678 }
679}