Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(teams): send team invites from the inviter's name with a text part (#9930)

Jacob Beckermanb38591cc62b2
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
index 2e1df45f09..d78c6fd4c6 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
@@ -144,6 +144,7 @@ export * from './initiativeDiscussionMetadataSenderProfilePictureUrl';
export * from './initiativeDiscussionReason';
export * from './inviteePlan';
export * from './inviteToTeamMetadata';
+export * from './inviteToTeamMetadataInviterName';
export * from './inviteToTeamMetadataRole';
export * from './inviteToTeamMetadataSenderProfilePictureUrl';
export * from './itemSharedMetadata';
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts
index cc64ccae65..2cc6e0af0d 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { InviteePlan } from './inviteePlan';
+import type { InviteToTeamMetadataInviterName } from './inviteToTeamMetadataInviterName';
import type { InviteToTeamMetadataRole } from './inviteToTeamMetadataRole';
import type { InviteToTeamMetadataSenderProfilePictureUrl } from './inviteToTeamMetadataSenderProfilePictureUrl';
@@ -16,6 +17,9 @@ export interface InviteToTeamMetadata {
invitedBy: string;
/** What the invitee gets by joining, as the team stood when the invite was sent. */
inviteePlan?: InviteePlan;
+ /** The inviter's display name, when they have set one. It is user-provided, so it is shown
+on one line, capped, and escaped; the email falls back to the inviter's address. */
+ inviterName?: InviteToTeamMetadataInviterName;
/** Whether the invite creates an agent account. */
isAgent?: boolean;
/** Whether this email reminds the invitee of an invite they have not answered. */
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadataInviterName.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadataInviterName.ts
new file mode 100644
index 0000000000..debbcc3989
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/inviteToTeamMetadataInviterName.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The inviter's display name, when they have set one. It is user-provided, so it is shown
+on one line, capped, and escaped; the email falls back to the inviter's address.
+ */
+export type InviteToTeamMetadataInviterName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
index d6fec551f2..9793bb0a1f 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
@@ -1064,6 +1064,12 @@ export const listTypedNotificationsResponse = zod
.enum(['free', 'premium'])
.optional()
.describe('What a team invitee gets by joining.'),
+ inviterName: zod
+ .string()
+ .nullish()
+ .describe(
+ "The inviter's display name, when they have set one. It is user-provided, so it is shown\non one line, capped, and escaped; the email falls back to the inviter's address."
+ ),
isAgent: zod
.boolean()
.optional()
@@ -3201,6 +3207,12 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
.enum(['free', 'premium'])
.optional()
.describe('What a team invitee gets by joining.'),
+ inviterName: zod
+ .string()
+ .nullish()
+ .describe(
+ "The inviter's display name, when they have set one. It is user-provided, so it is shown\non one line, capped, and escaped; the email falls back to the inviter's address."
+ ),
isAgent: zod
.boolean()
.optional()
@@ -5288,6 +5300,12 @@ export const getTypedNotificationsByEventItemIdResponse = zod
.enum(['free', 'premium'])
.optional()
.describe('What a team invitee gets by joining.'),
+ inviterName: zod
+ .string()
+ .nullish()
+ .describe(
+ "The inviter's display name, when they have set one. It is user-provided, so it is shown\non one line, capped, and escaped; the email falls back to the inviter's address."
+ ),
isAgent: zod
.boolean()
.optional()
@@ -7314,6 +7332,12 @@ export const getTypedNotificationByIdResponse = zod
.enum(['free', 'premium'])
.optional()
.describe('What a team invitee gets by joining.'),
+ inviterName: zod
+ .string()
+ .nullish()
+ .describe(
+ "The inviter's display name, when they have set one. It is user-provided, so it is shown\non one line, capped, and escaped; the email falls back to the inviter's address."
+ ),
isAgent: zod
.boolean()
.optional()
diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.json
index f9aaf403ec..9bc209234e 100644
--- a/apps/web/src/lib/service-clients/service-notification/openapi.json
+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json
@@ -2496,6 +2496,10 @@
"$ref": "#/components/schemas/InviteePlan",
"description": "What the invitee gets by joining, as the team stood when the invite was sent."
},
+ "inviterName": {
+ "type": ["string", "null"],
+ "description": "The inviter's display name, when they have set one. It is user-provided, so it is shown\non one line, capped, and escaped; the email falls back to the inviter's address."
+ },
"isAgent": {
"type": "boolean",
"description": "Whether the invite creates an agent account."
diff --git a/crates/email_formatting/src/lib.rs b/crates/email_formatting/src/lib.rs
index 9e23bec421..60dd26fbdc 100644
--- a/crates/email_formatting/src/lib.rs
+++ b/crates/email_formatting/src/lib.rs
@@ -139,10 +139,7 @@ impl Notification for EmailDigestNotification {
impl NotificationExtEmail for EmailDigestNotification {
fn format_email(&self) -> EmailContent {
- EmailContent {
- subject: self.subject.clone(),
- body: self.inner_html_string.clone(),
- }
+ EmailContent::new(self.subject.clone(), self.inner_html_string.clone())
}
fn rate_limit_config() -> RateLimitConfig {
diff --git a/crates/invite_email/AGENTS.md b/crates/invite_email/AGENTS.md
index 41f72ba6a0..625fa18ea1 100644
--- a/crates/invite_email/AGENTS.md
+++ b/crates/invite_email/AGENTS.md
@@ -55,6 +55,12 @@ invites, and the colleague-joined email.
sender, `teams`' `invite_users_to_team`, derives it the way `join_team`
grants entitlements: Pro only from an enterprise team or one with a
subscription. Never let the copy promise more than the join grants.
+- The team invite email is sent on the inviter's behalf: `format_email` sets
+ `from_name` (their name), `reply_to` (their address) and a plain-text `text`
+ part that mirrors the HTML copy. `inviter_name` is untrusted and optional, so
+ the subject, body and text fall back to the inviter's address; `from_name`
+ stays unset without a name, since an address as a display name looks like
+ spoofing to mail filters. `teams` looks the name up when it sends the invite.
- `InviteToTeamMetadata.reminder` marks the reminder emails `teams` sends for
unanswered invites; it only prefixes the subject with "Reminder:". A
reminder shares the invite's rate-limit bucket (one email per invite per
diff --git a/crates/invite_email/src/call_invite.rs b/crates/invite_email/src/call_invite.rs
index d32f2e12f0..68f1ca59e8 100644
--- a/crates/invite_email/src/call_invite.rs
+++ b/crates/invite_email/src/call_invite.rs
@@ -32,10 +32,10 @@ impl Notification for CallInvite {
impl NotificationExtEmail for CallInvite {
fn format_email(&self) -> EmailContent {
- EmailContent {
- subject: format!("{} invited you to {}", self.sender_display(), self.title),
- body: self.render().expect("CallInvite template must render"),
- }
+ EmailContent::new(
+ format!("{} invited you to {}", self.sender_display(), self.title),
+ self.render().expect("CallInvite template must render"),
+ )
}
fn rate_limit_config() -> RateLimitConfig {
diff --git a/crates/invite_email/src/colleague_joined.rs b/crates/invite_email/src/colleague_joined.rs
index 9c66f2cf61..f10feae167 100644
--- a/crates/invite_email/src/colleague_joined.rs
+++ b/crates/invite_email/src/colleague_joined.rs
@@ -1,7 +1,5 @@
use super::*;
-const DISPLAY_NAME_MAX_CHARS: usize = 64;
-
/// Tells someone whose address matches a team's auto-join domain that a team now exists for their
/// organization and that signing up with their work email joins it. It is an informational,
/// one-time notice that names who set the team up rather than announcing a sign-up.
@@ -21,19 +19,7 @@ pub struct ColleagueJoinedMacro {
impl ColleagueJoinedMacro {
fn display_name(&self) -> Option<String> {
- let words: Vec<&str> = self
- .joined_name
- .as_deref()?
- .split(|c: char| c.is_whitespace() || c.is_control())
- .filter(|word| !word.is_empty())
- .collect();
- let capped: String = words
- .join(" ")
- .chars()
- .take(DISPLAY_NAME_MAX_CHARS)
- .collect();
- let name = capped.trim_end();
- (!name.is_empty()).then(|| name.to_owned())
+ single_line_name(self.joined_name.as_deref())
}
fn joined_email(&self) -> &str {
@@ -60,12 +46,11 @@ impl Notification for ColleagueJoinedMacro {
impl NotificationExtEmail for ColleagueJoinedMacro {
fn format_email(&self) -> EmailContent {
- EmailContent {
- subject: "A team has been created for your organization".to_string(),
- body: self
- .render()
+ EmailContent::new(
+ "A team has been created for your organization".to_string(),
+ self.render()
.expect("ColleagueJoinedMacro template render failed in format_email"),
- }
+ )
}
fn rate_limit_config() -> RateLimitConfig {
diff --git a/crates/invite_email/src/lib.rs b/crates/invite_email/src/lib.rs
index 497d4decd8..d03d4dcb4d 100644
--- a/crates/invite_email/src/lib.rs
+++ b/crates/invite_email/src/lib.rs
@@ -34,6 +34,24 @@ use url::Url;
use utoipa::ToSchema;
use uuid::Uuid;
+const DISPLAY_NAME_MAX_CHARS: usize = 64;
+
+/// Puts an untrusted display name on one line and caps it. Returns `None` when nothing
+/// printable is left.
+fn single_line_name(raw: Option<&str>) -> Option<String> {
+ let words: Vec<&str> = raw?
+ .split(|c: char| c.is_whitespace() || c.is_control())
+ .filter(|word| !word.is_empty())
+ .collect();
+ let capped: String = words
+ .join(" ")
+ .chars()
+ .take(DISPLAY_NAME_MAX_CHARS)
+ .collect();
+ let name = capped.trim_end();
+ (!name.is_empty()).then(|| name.to_owned())
+}
+
/// Wrapper for the referral code to make it type safe
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
@@ -106,12 +124,11 @@ impl NotificationExtEmail for InviteToMacro {
.as_deref()
.or(self.sender_email.as_deref())
.unwrap_or("A Macro user");
- EmailContent {
- subject: format!("{} has invited you to join Macro", sender),
- body: self
- .render()
+ EmailContent::new(
+ format!("{} has invited you to join Macro", sender),
+ self.render()
.expect("InviteToMacro template render failed in format_email"),
- }
+ )
}
fn rate_limit_config() -> RateLimitConfig {
@@ -203,16 +220,16 @@ impl NotificationTitle for ChannelInviteMetadata {
impl NotificationExtEmail for ChannelInviteMetadata {
fn format_email(&self) -> EmailContent {
let sender = self.sender_display();
- EmailContent {
- subject: if self.is_direct_message {
- format!("{sender} sent you a message on Macro")
- } else {
- format!("{sender} has invited you to join #{}", self.channel_name)
- },
- body: self
- .render()
+ let subject = if self.is_direct_message {
+ format!("{sender} sent you a message on Macro")
+ } else {
+ format!("{sender} has invited you to join #{}", self.channel_name)
+ };
+ EmailContent::new(
+ subject,
+ self.render()
.expect("ChannelInviteMetadata template render failed in format_email"),
- }
+ )
}
fn rate_limit_config() -> RateLimitConfig {
@@ -316,6 +333,11 @@ pub struct InviteToTeamMetadata {
/// Whether the invite creates an agent account.
#[serde(default)]
pub is_agent: bool,
+
+ /// The inviter's display name, when they have set one. It is user-provided, so it is shown
+ /// on one line, capped, and escaped; the email falls back to the inviter's address.
+ #[serde(default, alias = "inviter_name")]
+ pub inviter_name: Option<String>,
}
/// What a team invitee gets by joining.
@@ -351,10 +373,47 @@ impl InviteToTeamMetadata {
url
}
- fn inviter(&self) -> &str {
+ fn inviter_email(&self) -> &str {
self.invited_by.email_str()
}
+ fn inviter_display_name(&self) -> Option<String> {
+ single_line_name(self.inviter_name.as_deref())
+ }
+
+ /// The inviter's name, or their address when they have not set one.
+ fn inviter(&self) -> String {
+ self.inviter_display_name()
+ .unwrap_or_else(|| self.inviter_email().to_owned())
+ }
+
+ /// The plain-text alternative to the HTML body. It mirrors the HTML's copy.
+ fn text_body(&self) -> String {
+ let inviter = match self.inviter_display_name() {
+ Some(name) => format!("{name} ({})", self.inviter_email()),
+ None => self.inviter_email().to_owned(),
+ };
+ let team = &self.team_name;
+ let plan = match self.invitee_plan {
+ InviteePlan::Premium => format!(
+ "Pro is included: {team} covers your seat, so you get every AI model and agent at no cost to you."
+ ),
+ InviteePlan::Free => format!(
+ "Free to join: there's nothing to pay. Accept the invite to start working with {team} in Macro."
+ ),
+ };
+ let url = self.invite_url();
+
+ format!(
+ "{inviter} invited you to the {team} team on Macro. Macro brings your documents, \
+ tasks, and conversations together in one place.\n\n\
+ {plan}\n\n\
+ Accept the invite by signing in or signing up with this email address:\n\
+ {url}\n\n\
+ Not expecting this invite? You can ignore this email.\n"
+ )
+ }
+
/// Names the team on the button unless the name would crowd it.
fn join_label(&self) -> String {
if self.team_name.chars().count() <= MAX_BUTTON_TEAM_NAME_CHARS {
@@ -381,6 +440,11 @@ impl NotificationExtEmail for InviteToTeamMetadata {
body: self
.render()
.expect("InviteToTeamMetadata template render failed in format_email"),
+ text: Some(self.text_body()),
+ // An address as a display name reads as spoofing to mail filters, so an inviter
+ // without a name leaves Macro's own sender name in place.
+ from_name: self.inviter_display_name(),
+ reply_to: Some(EmailStr(self.invited_by.email_part()).into_owned()),
}
}
diff --git a/crates/invite_email/src/test.rs b/crates/invite_email/src/test.rs
index 0c68e31355..13b718ca1c 100644
--- a/crates/invite_email/src/test.rs
+++ b/crates/invite_email/src/test.rs
@@ -23,9 +23,9 @@ fn call_invitation_links_directly_to_guest_join_and_escapes_titles() {
fn make_colleague_joined() -> ColleagueJoinedMacro {
ColleagueJoinedMacro {
team_name: "Acme".to_string(),
- joined_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ joined_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
joined_name: Some("Alice Example".to_string()),
- recipient_email: EmailStr::try_from("[email protected]".to_string()).unwrap(),
+ recipient_email: EmailStr::try_from("[email protected]".to_string()).unwrap(),
}
}
@@ -38,13 +38,13 @@ fn colleague_joined_is_an_organization_notice_that_links_to_signup() {
assert!(
email
.body
- .contains("Alice Example ([email protected]) set up the")
+ .contains("Alice Example ([email protected]) set up the")
);
assert!(email.body.contains("<strong>Acme</strong> team on Macro"));
assert!(
email
.body
- .contains("Sign up with <strong>[email protected]</strong>")
+ .contains("Sign up with <strong>[email protected]</strong>")
);
assert!(email.body.contains("one-time notice"));
assert!(
@@ -69,8 +69,8 @@ fn colleague_joined_falls_back_to_the_email_without_a_usable_name() {
}
.format_email();
assert_eq!(email.subject, COLLEAGUE_SUBJECT);
- assert!(email.body.contains("[email protected] set up the"));
- assert!(!email.body.contains("([email protected])"));
+ assert!(email.body.contains("[email protected] set up the"));
+ assert!(!email.body.contains("([email protected])"));
}
}
@@ -83,7 +83,7 @@ fn colleague_joined_puts_long_multiline_names_on_one_capped_line() {
.format_email();
assert_eq!(email.subject, COLLEAGUE_SUBJECT);
assert!(email.body.contains(&format!(
- "Alice Example {} ([email protected])",
+ "Alice Example {} ([email protected])",
"x".repeat(50)
)));
}
@@ -100,7 +100,7 @@ fn colleague_joined_escapes_the_untrusted_name_in_the_body() {
assert!(
email
.body
- .contains("&#60;b&#62;x&#60;/b&#62; ([email protected])")
+ .contains("&#60;b&#62;x&#60;/b&#62; ([email protected])")
);
}
@@ -108,7 +108,7 @@ fn colleague_joined_escapes_the_untrusted_name_in_the_body() {
fn colleague_joined_rate_limit_key_is_per_recipient() {
let to_bob = make_colleague_joined();
let to_carol = ColleagueJoinedMacro {
- recipient_email: EmailStr::try_from("[email protected]".to_string()).unwrap(),
+ recipient_email: EmailStr::try_from("[email protected]".to_string()).unwrap(),
..make_colleague_joined()
};
assert_eq!(
@@ -127,12 +127,13 @@ fn team_invite_rate_limit_key_is_per_invite() {
team_name: "Acme".to_string(),
team_id: Uuid::from_u128(1),
team_invite_id: Uuid::from_u128(10),
- invited_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ invited_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
role: None,
sender_profile_picture_url: None,
invitee_plan: InviteePlan::Free,
reminder: false,
is_agent: false,
+ inviter_name: None,
};
let to_carol = InviteToTeamMetadata {
team_invite_id: Uuid::from_u128(11),
@@ -152,16 +153,16 @@ fn team_invite_rate_limit_key_is_per_invite() {
fn colleague_joined_serde_round_trip_keeps_the_wire_shape() {
let wire = serde_json::json!({
"team_name": "Acme",
- "joined_by": "macro|[email protected]",
+ "joined_by": "macro|[email protected]",
"joined_name": "Alice Example",
- "recipient_email": "[email protected]",
+ "recipient_email": "[email protected]",
});
assert_eq!(serde_json::to_value(make_colleague_joined()).unwrap(), wire);
let parsed: ColleagueJoinedMacro = serde_json::from_value(wire).unwrap();
assert_eq!(parsed.team_name, "Acme");
- assert_eq!(parsed.joined_by.to_string(), "macro|[email protected]");
+ assert_eq!(parsed.joined_by.to_string(), "macro|[email protected]");
assert_eq!(parsed.joined_name.as_deref(), Some("Alice Example"));
- assert_eq!(String::from(parsed.recipient_email), "[email protected]");
+ assert_eq!(String::from(parsed.recipient_email), "[email protected]");
}
fn make_channel_invite() -> ChannelInviteMetadata {
@@ -322,6 +323,7 @@ fn invitation_logos_keep_the_png_aspect_ratio() {
invitee_plan: InviteePlan::Free,
reminder: false,
is_agent: false,
+ inviter_name: None,
};
for email in [
make_invite().format_email(),
@@ -474,12 +476,13 @@ fn make_team_invite(invitee_plan: InviteePlan) -> InviteToTeamMetadata {
team_name: "Acme".to_string(),
team_id: Uuid::from_u128(1),
team_invite_id: Uuid::from_u128(10),
- invited_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ invited_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
role: None,
sender_profile_picture_url: None,
invitee_plan,
reminder: false,
is_agent: false,
+ inviter_name: Some("Alice Example".to_string()),
}
}
@@ -500,15 +503,120 @@ fn team_invite_names_the_inviter_and_the_team() {
assert_eq!(
invite.format_email().subject,
- "[email protected] invited you to join Acme on Macro"
+ "Alice Example invited you to join Acme on Macro"
);
assert!(text.contains("Join Acme on Macro </h1>"));
assert!(text.contains(
- r#"<strong style="color: #222222">[email protected]</strong> invited you to the <strong style="color: #222222">Acme</strong> team."#
+ r#"<strong style="color: #222222">Alice Example</strong> ([email protected]) invited you to the <strong style="color: #222222">Acme</strong> team."#
));
assert!(text.contains(">Join Acme</a"));
}
+#[test]
+fn team_invite_falls_back_to_the_inviter_address_without_a_usable_name() {
+ for inviter_name in [None, Some(" \n\t\u{7} ".to_string())] {
+ let invite = InviteToTeamMetadata {
+ inviter_name,
+ ..make_team_invite(InviteePlan::Free)
+ };
+ let email = invite.format_email();
+
+ assert_eq!(
+ email.subject,
+ "[email protected] invited you to join Acme on Macro"
+ );
+ assert!(email.from_name.is_none());
+ assert_eq!(
+ email.reply_to.map(String::from).as_deref(),
+ );
+ assert!(team_invite_text(&invite).contains(
+ r#"<strong style="color: #222222">[email protected]</strong> invited you to the"#
+ ));
+ assert!(!email.body.contains("([email protected])"));
+ assert!(
+ email
+ .text
+ .unwrap()
+ .starts_with("[email protected] invited you to the Acme team on Macro.")
+ );
+ }
+}
+
+#[test]
+fn team_invite_is_sent_on_behalf_of_the_inviter() {
+ let email = make_team_invite(InviteePlan::Free).format_email();
+
+ assert_eq!(email.from_name.as_deref(), Some("Alice Example"));
+ assert_eq!(
+ email.reply_to.map(String::from).as_deref(),
+ );
+}
+
+#[test]
+fn team_invite_escapes_and_caps_the_inviter_name() {
+ let invite = InviteToTeamMetadata {
+ inviter_name: Some(format!(
+ "<b>Alice</b>\r\nBcc: [email protected] {}",
+ "x".repeat(100)
+ )),
+ ..make_team_invite(InviteePlan::Free)
+ };
+ let email = invite.format_email();
+ let name = format!("<b>Alice</b> Bcc: [email protected] {}", "x".repeat(32));
+
+ assert_eq!(name.chars().count(), 64);
+ assert_eq!(
+ email.subject,
+ format!("{name} invited you to join Acme on Macro")
+ );
+ assert_eq!(email.from_name.as_deref(), Some(name.as_str()));
+ assert!(!email.body.contains("<b>Alice</b>"));
+ assert!(email.body.contains("&#60;b&#62;Alice&#60;/b&#62; Bcc:"));
+}
+
+#[test]
+fn team_invite_text_part_names_the_inviter_team_plan_and_link() {
+ let free = make_team_invite(InviteePlan::Free);
+ let url = free.invite_url().to_string();
+ let text = free.format_email().text.unwrap();
+
+ assert!(
+ text.starts_with(
+ "Alice Example ([email protected]) invited you to the Acme team on Macro."
+ )
+ );
+ assert!(text.contains(
+ "Free to join: there's nothing to pay. Accept the invite to start working with Acme in Macro."
+ ));
+ assert!(text.contains(&format!("this email address:\n{url}\n")));
+ assert!(!text.contains('<'));
+
+ let pro = make_team_invite(InviteePlan::Premium)
+ .format_email()
+ .text
+ .unwrap();
+ assert!(pro.contains(
+ "Pro is included: Acme covers your seat, so you get every AI model and agent at no cost to you."
+ ));
+ assert!(!pro.contains("Free to join"));
+}
+
+#[test]
+fn team_invites_queued_before_inviter_names_fall_back_to_the_address() {
+ let mut wire = serde_json::to_value(make_team_invite(InviteePlan::Free)).unwrap();
+ assert_eq!(wire["inviterName"], "Alice Example");
+ wire.as_object_mut().unwrap().remove("inviterName");
+
+ let parsed: InviteToTeamMetadata = serde_json::from_value(wire).unwrap();
+ assert!(parsed.inviter_name.is_none());
+ assert_eq!(
+ parsed.format_email().subject,
+ "[email protected] invited you to join Acme on Macro"
+ );
+}
+
#[test]
fn team_invite_promises_pro_only_when_the_team_covers_the_seat() {
let pro = team_invite_text(&make_team_invite(InviteePlan::Premium));
@@ -591,7 +699,7 @@ fn team_invite_sent_before_plans_were_recorded_reads_as_free() {
"team_name": "Acme",
"team_id": "00000000-0000-0000-0000-000000000001",
"team_invite_id": "00000000-0000-0000-0000-00000000000a",
- "invited_by": "macro|[email protected]",
+ "invited_by": "macro|[email protected]",
"role": null,
});
@@ -608,11 +716,11 @@ fn team_invite_reminder_says_so_in_the_subject() {
};
assert_eq!(
reminder.format_email().subject,
- "Reminder: [email protected] invited you to join Acme on Macro"
+ "Reminder: Alice Example invited you to join Acme on Macro"
);
assert_eq!(
make_team_invite(InviteePlan::Free).format_email().subject,
- "[email protected] invited you to join Acme on Macro"
+ "Alice Example invited you to join Acme on Macro"
);
}
diff --git a/crates/invite_email/templates/invite_to_team.html b/crates/invite_email/templates/invite_to_team.html
index 7f5e93c023..8684262240 100644
--- a/crates/invite_email/templates/invite_to_team.html
+++ b/crates/invite_email/templates/invite_to_team.html
@@ -169,7 +169,12 @@
color: #525252;
"
>
- <strong style="color: #222222">{{ inviter() }}</strong>
+ {% if let Some(name) = self.inviter_display_name() -%}
+ <strong style="color: #222222">{{ name }}</strong>
+ ({{ self.inviter_email() }})
+ {%- else -%}
+ <strong style="color: #222222">{{ self.inviter_email() }}</strong>
+ {%- endif %}
invited you to the
<strong style="color: #222222">{{ team_name }}</strong> team.
Macro brings your documents, tasks, and conversations
diff --git a/crates/model_notifications/src/metadata.rs b/crates/model_notifications/src/metadata.rs
index 78ee4ba1a6..41a2b44045 100644
--- a/crates/model_notifications/src/metadata.rs
+++ b/crates/model_notifications/src/metadata.rs
@@ -1742,14 +1742,14 @@ impl notification::domain::models::NotificationExtEmail for CalendarEventReminde
.format_title(None)
.unwrap_or_else(|_| "Calendar reminder".into());
let when = self.format_body(None).unwrap_or_default();
- notification::domain::models::queue_message::EmailContent {
- subject: format!("Reminder: {}", title.replace(['\r', '\n'], " ")),
- body: format!(
+ notification::domain::models::queue_message::EmailContent::new(
+ format!("Reminder: {}", title.replace(['\r', '\n'], " ")),
+ format!(
"<p>{}</p><p>{}</p><p>Calendar reminder from Macro.</p>",
html_escape::encode_text(&title),
html_escape::encode_text(&when)
),
- }
+ )
}
fn rate_limit_config() -> notification::domain::models::RateLimitConfig {
notification::domain::models::RateLimitConfig {
diff --git a/crates/notification/AGENTS.md b/crates/notification/AGENTS.md
index de4c607296..426869b715 100644
--- a/crates/notification/AGENTS.md
+++ b/crates/notification/AGENTS.md
@@ -97,6 +97,14 @@ through the same service.
librdkafka out of the self-hosted daemon; keep it that way.
- Independent Kafka consumers have no durable group lag. Health logs distinguish
stale/unknown measurements from zero; they are not client-delivery ACKs.
+- `EmailContent` is queued as JSON, so its optional `text`, `from_name` and
+ `reply_to` carry `#[serde(default)]`. `EmailAdapter` turns `from_name` into an
+ `"<name> (via Macro)"` display name on Macro's own From address (quoted when
+ ASCII, RFC 2047 encoded otherwise) and sends `text` as the plain-text part.
+ Unsubscribe placeholders are signed in the HTML `body` only.
+- `EmailAdapter` takes an optional SES configuration set; with one, every send
+ uses it and carries a `notification_type` message tag. A set name that does
+ not exist in SES fails every send, so create the set before configuring it.
- Notification payloads must not be logged on tracing spans (see the
`fix(notification): stop recording notification payloads` history).
- Android call pushes carry W3C trace context inside their existing JSON offer;
diff --git a/crates/notification/src/domain/models/queue_message.rs b/crates/notification/src/domain/models/queue_message.rs
index 9840e1c3ca..e7135714fd 100644
--- a/crates/notification/src/domain/models/queue_message.rs
+++ b/crates/notification/src/domain/models/queue_message.rs
@@ -10,6 +10,7 @@ use crate::domain::models::{
};
use chrono::{DateTime, Utc};
use cowlike::CowLike;
+use macro_user_id::email::EmailStr;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use rate_limit::RateLimitExceeded;
@@ -47,12 +48,38 @@ pub struct APNSTargets<T> {
}
/// Email notification payload.
+///
+/// The optional fields are queued as JSON, so each carries `#[serde(default)]` for messages
+/// queued before it existed.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EmailContent {
/// The email subject line.
pub subject: String,
- /// The email body content.
+ /// The HTML email body. Unsubscribe placeholders are signed in this part only.
pub body: String,
+ /// A plain-text alternative to `body`.
+ #[serde(default)]
+ pub text: Option<String>,
+ /// The person the email is sent on behalf of. The sender shows it as the From display
+ /// name, marked as sent via Macro, while the address stays Macro's.
+ #[serde(default)]
+ pub from_name: Option<String>,
+ /// The address replies go to instead of Macro's no-reply sender.
+ #[serde(default)]
+ pub reply_to: Option<EmailStr<'static>>,
+}
+
+impl EmailContent {
+ /// An HTML-only email from Macro itself.
+ pub fn new(subject: String, body: String) -> Self {
+ Self {
+ subject,
+ body,
+ text: None,
+ from_name: None,
+ reply_to: None,
+ }
+ }
}
/// Email notification payload.
diff --git a/crates/notification/src/domain/ports.rs b/crates/notification/src/domain/ports.rs
index 94779f8fcc..d9a897f7c9 100644
--- a/crates/notification/src/domain/ports.rs
+++ b/crates/notification/src/domain/ports.rs
@@ -422,10 +422,12 @@ use crate::domain::models::queue_message::EmailContent;
/// Port for email delivery.
pub trait EmailSender: Send + Sync + 'static {
- /// Send an email with pre-built content to a user.
+ /// Send an email with pre-built content to a user. `notification_type` is the type name
+ /// of the notification the email delivers.
fn send_email(
&self,
recipient: MacroUserIdStr<'_>,
+ notification_type: &str,
content: &EmailContent,
) -> impl Future<Output = Result<(), Report>> + Send;
}
diff --git a/crates/notification/src/domain/service/egress.rs b/crates/notification/src/domain/service/egress.rs
index 52af59a7e1..ac539172fc 100644
--- a/crates/notification/src/domain/service/egress.rs
+++ b/crates/notification/src/domain/service/egress.rs
@@ -171,6 +171,7 @@ where
message: QueueMessage<'static, serde_json::Value, serde_json::Value>,
) -> Vec<Result<DeliverySuccess, Report<DeliveryFailure>>> {
let access_request = message.message_type() == "entity_access_requested";
+ let message_type = message.message_type().to_owned();
let content = message.into_inner();
if access_request {
let notification_id = match &content {
@@ -206,7 +207,9 @@ where
.deliver_conn_gateway(conn)
.await
.context(DeliveryFailure::Other)]),
- NotificationChannel::Email(email) => Either::Left([self.deliver_email(email).await]),
+ NotificationChannel::Email(email) => {
+ Either::Left([self.deliver_email(&message_type, email).await])
+ }
NotificationChannel::Ios(apns) => Either::Right(
self.deliver_mobile(&apns)
.await
@@ -327,6 +330,7 @@ where
/// Deliver via email.
async fn deliver_email(
&self,
+ notification_type: &str,
email: EmailNotification<'static>,
) -> Result<DeliverySuccess, Report<DeliveryFailure>> {
let EmailNotification {
@@ -356,13 +360,14 @@ where
if let Err(e) = self
.email
- .send_email(recipient.clone(), &content)
+ .send_email(recipient.clone(), notification_type, &content)
.await
.inspect_err(|e| {
+ // The subject can carry the sender's name, so the type identifies the email.
tracing::error!(
error = ?e,
recipient = %recipient,
- subject = %content.subject,
+ notification_type,
"Email delivery failed"
);
})
diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rs
index 2727dac597..3f7e399610 100644
--- a/crates/notification/src/domain/service/test.rs
+++ b/crates/notification/src/domain/service/test.rs
@@ -83,10 +83,7 @@ impl NotificationExtIos for TestNotification {
impl NotificationExtEmail for TestNotification {
fn format_email(&self) -> crate::domain::models::queue_message::EmailContent {
- EmailContent {
- subject: "Test".to_string(),
- body: self.message.clone(),
- }
+ EmailContent::new("Test".to_string(), self.message.clone())
}
fn rate_limit_config() -> RateLimitConfig {
@@ -1418,6 +1415,7 @@ impl EmailSender for MockEmailSender {
async fn send_email(
&self,
_recipient: MacroUserIdStr<'_>,
+ _notification_type: &str,
_content: &crate::domain::models::queue_message::EmailContent,
) -> Result<(), Report> {
Ok(())
diff --git a/crates/notification/src/outbound/email.rs b/crates/notification/src/outbound/email.rs
index 0857ca540a..03e2d7b78c 100644
--- a/crates/notification/src/outbound/email.rs
+++ b/crates/notification/src/outbound/email.rs
@@ -1,104 +1,253 @@
//! Email notification adapter.
-use aws_sdk_sesv2::types::{Body, Content, Destination, EmailContent as SesEmailContent, Message};
+#[cfg(test)]
+mod test;
+
+use aws_sdk_sesv2::types::{
+ Body, Content, Destination, EmailContent as SesEmailContent, Message, MessageTag,
+};
use hmac::Hmac;
use macro_user_id::email::ReadEmailParts;
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
use sha2::Sha256;
+use std::fmt::Write;
use url::Url;
use crate::domain::models::queue_message::EmailContent;
use crate::domain::models::signing::sign_unsubscribe_placeholders;
use crate::domain::ports::EmailSender;
+/// Longest sender name shown before the "via Macro" suffix.
+const FROM_NAME_MAX_CHARS: usize = 64;
+
+/// Marks a display name as someone Macro sends for, so it never reads as Macro's own mail.
+const FROM_NAME_SUFFIX: &str = " (via Macro)";
+
+/// RFC 2047 caps an encoded word at 75 characters; `=?UTF-8?Q?` and `?=` take 12 of them.
+const ENCODED_WORD_MAX_TEXT_LEN: usize = 63;
+
+/// The SES message tag that names the notification type on delivery events.
+const NOTIFICATION_TYPE_TAG: &str = "notification_type";
+
+/// SES caps message tag values at 256 characters.
+const TAG_VALUE_MAX_LEN: usize = 256;
+
/// Email notification adapter.
///
/// This adapter sends email notifications through the configured email service.
pub struct EmailAdapter<E> {
email_service: E,
from_email: String,
+ configuration_set: Option<String>,
}
impl<E> EmailAdapter<E> {
- /// Create a new email adapter.
- pub fn new(email_service: E, from_email: String) -> Self {
+ /// Create a new email adapter that sends from `from_email`. With a `configuration_set`,
+ /// every email is sent through that SES configuration set and tagged with its
+ /// notification type, so its delivery events can be counted per type.
+ pub fn new(email_service: E, from_email: String, configuration_set: Option<String>) -> Self {
Self {
email_service,
from_email,
+ configuration_set,
}
}
}
+/// Routes an email's delivery events to a configuration set.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DeliveryTracking<'a> {
+ /// The SES configuration set that publishes the delivery events.
+ pub configuration_set: &'a str,
+ /// The notification type, as a valid SES tag value.
+ pub notification_type: String,
+}
+
+/// One email, ready for the email service.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct OutgoingEmail<'a> {
+ /// The From header: Macro's address, with the sender's name when there is one.
+ pub from: String,
+ /// The recipient's address.
+ pub to: &'a str,
+ /// The address replies go to, when it is not the From address.
+ pub reply_to: Option<&'a str>,
+ /// The subject line.
+ pub subject: &'a str,
+ /// The HTML body.
+ pub html_body: &'a str,
+ /// The plain-text alternative to the HTML body.
+ pub text_body: Option<&'a str>,
+ /// Where delivery events go, when they are tracked.
+ pub tracking: Option<DeliveryTracking<'a>>,
+}
+
/// Trait for email service operations.
///
/// This allows the adapter to work with different email service implementations.
pub trait EmailServiceOps {
- /// Send an email to the given address.
+ /// Send an email.
fn send_email(
&self,
- from_email: &str,
- to_email: &str,
- subject: &str,
- html_body: &str,
+ email: &OutgoingEmail<'_>,
) -> impl std::future::Future<Output = Result<(), Report>> + Send;
}
-impl EmailServiceOps for aws_sdk_sesv2::Client {
- async fn send_email(
- &self,
- from_email: &str,
- to_email: &str,
- subject: &str,
- html_body: &str,
- ) -> Result<(), Report> {
- let dest = Destination::builder().to_addresses(to_email).build();
-
- let subject_content = Content::builder().data(subject).charset("UTF-8").build()?;
+fn utf8_content(data: &str) -> Result<Content, Report> {
+ Ok(Content::builder().data(data).charset("UTF-8").build()?)
+}
- let body_content = Content::builder()
- .data(html_body)
- .charset("UTF-8")
- .build()?;
+impl EmailServiceOps for aws_sdk_sesv2::Client {
+ async fn send_email(&self, email: &OutgoingEmail<'_>) -> Result<(), Report> {
+ let dest = Destination::builder().to_addresses(email.to).build();
- let body = Body::builder().html(body_content).build();
+ let text = email.text_body.map(utf8_content).transpose()?;
+ let body = Body::builder()
+ .html(utf8_content(email.html_body)?)
+ .set_text(text)
+ .build();
let msg = Message::builder()
- .subject(subject_content)
+ .subject(utf8_content(email.subject)?)
.body(body)
.build();
let email_content = SesEmailContent::builder().simple(msg).build();
- self.send_email()
- .from_email_address(from_email)
+ let mut request = self
+ .send_email()
+ .from_email_address(&email.from)
.destination(dest)
.content(email_content)
- .send()
- .await
- .map_err(|e| {
- rootcause::report!(
- "SES send failed: {}",
- aws_sdk_sns::error::DisplayErrorContext(&e)
- )
- })?;
+ .set_reply_to_addresses(email.reply_to.map(|address| vec![address.to_owned()]));
+
+ if let Some(tracking) = &email.tracking {
+ let tag = MessageTag::builder()
+ .name(NOTIFICATION_TYPE_TAG)
+ .value(&tracking.notification_type)
+ .build()?;
+ request = request
+ .configuration_set_name(tracking.configuration_set)
+ .email_tags(tag);
+ }
+
+ request.send().await.map_err(|e| {
+ rootcause::report!(
+ "SES send failed: {}",
+ aws_sdk_sns::error::DisplayErrorContext(&e)
+ )
+ })?;
Ok(())
}
}
+/// Puts an untrusted sender name on one line without the characters a quoted display name
+/// cannot carry, and caps it. Returns `None` when nothing printable is left.
+fn sanitize_from_name(raw: &str) -> Option<String> {
+ let unquoted: String = raw.chars().filter(|c| !matches!(c, '"' | '\\')).collect();
+ let words: Vec<&str> = unquoted
+ .split(|c: char| c.is_whitespace() || c.is_control())
+ .filter(|word| !word.is_empty())
+ .collect();
+ let capped: String = words.join(" ").chars().take(FROM_NAME_MAX_CHARS).collect();
+ let name = capped.trim();
+ (!name.is_empty()).then(|| name.to_owned())
+}
+
+/// Encodes `text` as RFC 2047 `Q` encoded words, which mail headers need for non-ASCII
+/// display names. Each word stays within the length limit and never splits a character.
+fn encoded_words(text: &str) -> String {
+ let mut words = Vec::new();
+ let mut word = String::new();
+ let mut utf8 = [0; 4];
+ for c in text.chars() {
+ let mut encoded = String::new();
+ for byte in c.encode_utf8(&mut utf8).bytes() {
+ match byte {
+ b' ' => encoded.push('_'),
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'!' | b'*' | b'+' | b'-' | b'/' => {
+ encoded.push(char::from(byte))
+ }
+ _ => {
+ let _ = write!(encoded, "={byte:02X}");
+ }
+ }
+ }
+ if word.len() + encoded.len() > ENCODED_WORD_MAX_TEXT_LEN {
+ words.push(std::mem::take(&mut word));
+ }
+ word.push_str(&encoded);
+ }
+ if !word.is_empty() {
+ words.push(word);
+ }
+
+ words
+ .iter()
+ .map(|word| format!("=?UTF-8?Q?{word}?="))
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+/// The From header for `from_email`, naming the person Macro sends for when there is one.
+fn from_header(from_email: &str, from_name: Option<&str>) -> String {
+ let Some(name) = from_name.and_then(sanitize_from_name) else {
+ return from_email.to_owned();
+ };
+
+ let display_name = format!("{name}{FROM_NAME_SUFFIX}");
+ if display_name.is_ascii() {
+ format!("\"{display_name}\" <{from_email}>")
+ } else {
+ format!("{} <{from_email}>", encoded_words(&display_name))
+ }
+}
+
+/// The notification type as an SES tag value: ASCII letters, digits, `_`, and `-`.
+fn tag_value(notification_type: &str) -> String {
+ notification_type
+ .chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .take(TAG_VALUE_MAX_LEN)
+ .collect()
+}
+
impl<E: EmailServiceOps + Send + Sync + 'static> EmailSender for EmailAdapter<E> {
async fn send_email(
&self,
recipient: MacroUserIdStr<'_>,
+ notification_type: &str,
content: &EmailContent,
) -> Result<(), Report> {
let email_part = recipient.email_part();
- let to_email = email_part.email_str();
+ let email = OutgoingEmail {
+ from: from_header(&self.from_email, content.from_name.as_deref()),
+ to: email_part.email_str(),
+ reply_to: content
+ .reply_to
+ .as_ref()
+ .map(|address| address.0.email_str()),
+ subject: &content.subject,
+ html_body: &content.body,
+ text_body: content.text.as_deref(),
+ tracking: self
+ .configuration_set
+ .as_deref()
+ .map(|configuration_set| DeliveryTracking {
+ configuration_set,
+ notification_type: tag_value(notification_type),
+ }),
+ };
- self.email_service
- .send_email(&self.from_email, to_email, &content.subject, &content.body)
- .await
+ self.email_service.send_email(&email).await
}
}
@@ -128,6 +277,7 @@ impl<S: EmailSender> EmailSender for SignedUnsubscribeLinks<S> {
async fn send_email(
&self,
recipient: MacroUserIdStr<'_>,
+ notification_type: &str,
content: &EmailContent,
) -> Result<(), Report> {
let Some(body) = sign_unsubscribe_placeholders(
@@ -136,12 +286,17 @@ impl<S: EmailSender> EmailSender for SignedUnsubscribeLinks<S> {
recipient.as_ref(),
&self.signing_key,
) else {
- return self.inner.send_email(recipient, content).await;
+ return self
+ .inner
+ .send_email(recipient, notification_type, content)
+ .await;
};
let signed = EmailContent {
- subject: content.subject.clone(),
body,
+ ..content.clone()
};
- self.inner.send_email(recipient, &signed).await
+ self.inner
+ .send_email(recipient, notification_type, &signed)
+ .await
}
}
diff --git a/crates/notification/src/outbound/email/test.rs b/crates/notification/src/outbound/email/test.rs
new file mode 100644
index 0000000000..06989fb636
--- /dev/null
+++ b/crates/notification/src/outbound/email/test.rs
@@ -0,0 +1,180 @@
+use super::*;
+use macro_user_id::email::EmailStr;
+use std::sync::Mutex;
+
+const FROM: &str = "[email protected]";
+
+#[test]
+fn from_header_without_a_name_is_the_bare_address() {
+ assert_eq!(from_header(FROM, None), FROM);
+ assert_eq!(from_header(FROM, Some(" \r\n\t\"\\ ")), FROM);
+}
+
+#[test]
+fn from_header_quotes_an_ascii_name_marked_as_via_macro() {
+ assert_eq!(
+ from_header(FROM, Some("Alice Example")),
+ r#""Alice Example (via Macro)" <[email protected]>"#
+ );
+}
+
+#[test]
+fn from_header_cannot_be_broken_out_of_by_the_name() {
+ assert_eq!(
+ from_header(
+ FROM,
+ Some("Alice \"Admin\" \\\r\nBcc: [email protected]\" <[email protected]>")
+ ),
+ r#""Alice Admin Bcc: [email protected] <[email protected]> (via Macro)" <[email protected]>"#
+ );
+}
+
+#[test]
+fn from_header_caps_the_name() {
+ let header = from_header(FROM, Some(&"x".repeat(100)));
+ assert_eq!(
+ header,
+ format!("\"{} (via Macro)\" <[email protected]>", "x".repeat(64))
+ );
+}
+
+#[test]
+fn from_header_encodes_a_non_ascii_name() {
+ assert_eq!(
+ from_header(FROM, Some("José")),
+ "=?UTF-8?Q?Jos=C3=A9_=28via_Macro=29?= <[email protected]>"
+ );
+}
+
+#[test]
+fn from_header_splits_a_long_non_ascii_name_into_short_encoded_words() {
+ let header = from_header(FROM, Some(&"é".repeat(64)));
+ let (words, address) = header.rsplit_once(' ').unwrap();
+ assert_eq!(address, "<[email protected]>");
+
+ let words: Vec<&str> = words.split(' ').collect();
+ assert!(words.len() > 1);
+ for word in &words {
+ assert!(word.len() <= 75, "{word} is too long");
+ assert!(word.starts_with("=?UTF-8?Q?") && word.ends_with("?="));
+ // No character is split across words.
+ assert!(!word.ends_with("=C3?="));
+ }
+ let text: String = words
+ .iter()
+ .map(|word| &word["=?UTF-8?Q?".len()..word.len() - "?=".len()])
+ .collect();
+ assert_eq!(text, format!("{}_=28via_Macro=29", "=C3=A9".repeat(64)));
+}
+
+#[test]
+fn tag_value_keeps_only_characters_ses_accepts() {
+ assert_eq!(tag_value("invite_to_team"), "invite_to_team");
+ assert_eq!(
+ tag_value("email-digest-notification"),
+ "email-digest-notification"
+ );
+ assert_eq!(tag_value("a.b c:d"), "a_b_c_d");
+ assert_eq!(tag_value(&"x".repeat(300)).len(), 256);
+}
+
+/// The parts of an [`OutgoingEmail`] the adapter decides.
+#[derive(Debug, PartialEq, Eq)]
+struct Sent {
+ from: String,
+ to: String,
+ reply_to: Option<String>,
+ text_body: Option<String>,
+ tracking: Option<(String, String)>,
+}
+
+#[derive(Default)]
+struct RecordingEmailService {
+ sent: Mutex<Vec<Sent>>,
+}
+
+impl EmailServiceOps for RecordingEmailService {
+ async fn send_email(&self, email: &OutgoingEmail<'_>) -> Result<(), Report> {
+ self.sent.lock().unwrap().push(Sent {
+ from: email.from.clone(),
+ to: email.to.to_owned(),
+ reply_to: email.reply_to.map(str::to_owned),
+ text_body: email.text_body.map(str::to_owned),
+ tracking: email.tracking.as_ref().map(|tracking| {
+ (
+ tracking.configuration_set.to_owned(),
+ tracking.notification_type.clone(),
+ )
+ }),
+ });
+ Ok(())
+ }
+}
+
+fn recipient() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+#[tokio::test]
+async fn sends_on_behalf_of_the_named_sender_with_a_text_part() {
+ let adapter = EmailAdapter::new(RecordingEmailService::default(), FROM.to_string(), None);
+ let content = EmailContent {
+ text: Some("Join us".to_string()),
+ from_name: Some("Alice Example".to_string()),
+ reply_to: Some(EmailStr::try_from("[email protected]".to_string()).unwrap()),
+ ..EmailContent::new("Subject".to_string(), "<p>Join us</p>".to_string())
+ };
+
+ adapter
+ .send_email(recipient(), "invite_to_team", &content)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ *adapter.email_service.sent.lock().unwrap(),
+ [Sent {
+ from: r#""Alice Example (via Macro)" <[email protected]>"#.to_string(),
+ to: "[email protected]".to_string(),
+ reply_to: Some("[email protected]".to_string()),
+ text_body: Some("Join us".to_string()),
+ tracking: None,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn sends_html_only_emails_from_macro_and_tracks_them_when_configured() {
+ let adapter = EmailAdapter::new(
+ RecordingEmailService::default(),
+ FROM.to_string(),
+ Some("notifications".to_string()),
+ );
+ let content = EmailContent::new("Subject".to_string(), "<p>Hi</p>".to_string());
+
+ adapter
+ .send_email(recipient(), "channel_invite", &content)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ *adapter.email_service.sent.lock().unwrap(),
+ [Sent {
+ from: FROM.to_string(),
+ to: "[email protected]".to_string(),
+ reply_to: None,
+ text_body: None,
+ tracking: Some(("notifications".to_string(), "channel_invite".to_string())),
+ }]
+ );
+}
+
+#[test]
+fn email_content_queued_before_the_optional_fields_still_reads() {
+ let content: EmailContent =
+ serde_json::from_str(r#"{"subject": "Subject", "body": "<p>Hi</p>"}"#).unwrap();
+
+ assert_eq!(content.subject, "Subject");
+ assert!(content.text.is_none());
+ assert!(content.from_name.is_none());
+ assert!(content.reply_to.is_none());
+}
diff --git a/crates/teams/AGENTS.md b/crates/teams/AGENTS.md
index d60f6e2cfb..a596a5ee56 100644
--- a/crates/teams/AGENTS.md
+++ b/crates/teams/AGENTS.md
@@ -71,6 +71,10 @@ event contract (schema, sanitization, delivery semantics).
409 in that same request when it is no longer the caller's team; without
`team_id` the routes act on whatever team is current.
+- Invite and reminder emails carry the inviter's display name
+ (`TeamRepository::get_user_display_name`). A failed lookup is logged and the
+ email falls back to the inviter's address, so it never blocks an invite.
+
- `team_invite.is_agent` makes an address with no account sign up as an agent.
`authentication_service`'s agent setup joins the team, so the seat is added
without a separate acceptance. Existing accounts accept like any other invite.
diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rs
index 3dfbec620a..576a102d4d 100644
--- a/crates/teams/src/domain/team_repo.rs
+++ b/crates/teams/src/domain/team_repo.rs
@@ -232,6 +232,12 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
team_id: &uuid::Uuid,
) -> impl Future<Output = Result<String, TeamError>> + Send;
+ /// Gets a user's display name (first and last name). `None` when they have not set one.
+ fn get_user_display_name(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<String>, TeamError>> + Send;
+
/// Updates a team
fn patch_team(
&self,
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index 5721975a79..b6d46ca93b 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -1300,6 +1300,17 @@ where
.ok();
}
+ /// The inviter's display name for invite emails. The email falls back to the
+ /// inviter's address, so a failed lookup is logged rather than failing the invite.
+ async fn inviter_name(&self, inviter: &MacroUserIdStr<'_>) -> Option<String> {
+ self.team_repository
+ .get_user_display_name(inviter)
+ .await
+ .inspect_err(|e| tracing::warn!(error=?e, "unable to look up the inviter's name"))
+ .ok()
+ .flatten()
+ }
+
/// Sends an invite notification for a team invite
#[tracing::instrument(skip(self), err)]
async fn send_invite_notification(
@@ -1619,6 +1630,7 @@ where
&& let Some(team_name) = team_name.clone()
{
let invited_by_owned = invited_by.clone().into_owned();
+ let inviter_name = self.inviter_name(invited_by).await;
let mut sent_invite_ids = Vec::new();
for invite in &invited {
if self
@@ -1636,6 +1648,7 @@ where
invitee_plan,
reminder: false,
is_agent: invite.is_agent,
+ inviter_name: inviter_name.clone(),
},
)
.await
diff --git a/crates/teams/src/domain/team_service/invite_reminders.rs b/crates/teams/src/domain/team_service/invite_reminders.rs
index fb798ca0cb..1de22f2fe2 100644
--- a/crates/teams/src/domain/team_service/invite_reminders.rs
+++ b/crates/teams/src/domain/team_service/invite_reminders.rs
@@ -152,6 +152,7 @@ where
let invited_by = MacroUserIdStr::parse_from_str(&reminder.invited_by)
.map_err(|e| anyhow::anyhow!("invalid inviter id: {e:?}"))?
.into_owned();
+ let inviter_name = self.inviter_name(&invited_by).await;
let request = SendNotificationRequestBuilder {
notification_entity: EntityType::Team
@@ -168,6 +169,7 @@ where
invitee_plan: invitee_plan(reminder),
reminder: true,
is_agent: reminder.is_agent,
+ inviter_name,
},
recipient_ids: HashSet::from([recipient]),
}
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index 9f10b4f0bd..38a829c7fe 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -150,6 +150,9 @@ struct MockTeamRepository {
invite_link_team: Option<TeamInviteLinkTeam>,
/// What `claim_due_invite_reminders` hands out, once.
due_invite_reminders: Arc<Mutex<Vec<DueInviteReminder>>>,
+ /// What `get_user_display_name` returns for every user.
+ user_display_name: Option<String>,
+ fail_user_display_name: bool,
}
impl MockTeamRepository {
@@ -236,6 +239,8 @@ impl MockTeamRepository {
invite_link_creator: Arc::new(Mutex::new(None)),
invite_link_team: None,
due_invite_reminders: Arc::new(Mutex::new(Vec::new())),
+ user_display_name: Some("Olivia Owner".to_string()),
+ fail_user_display_name: false,
}
}
@@ -727,6 +732,20 @@ impl TeamRepository for MockTeamRepository {
async move { Ok(name) }
}
+ fn get_user_display_name(
+ &self,
+ _: &MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<String>, TeamError>> + Send {
+ let result = if self.fail_user_display_name {
+ Err(TeamError::StorageLayerError(anyhow::anyhow!(
+ "name lookup failed"
+ )))
+ } else {
+ Ok(self.user_display_name.clone())
+ };
+ async move { result }
+ }
+
fn patch_team(
&self,
team_id: &uuid::Uuid,
@@ -3367,6 +3386,84 @@ async fn invite_users_to_team_enterprise_bypasses_billing_and_preserves_side_eff
}
}
+/// The inviter name each sent invite email carried, in send order.
+fn inviter_names_sent(notification_ingress: &MockNotificationIngress) -> Vec<serde_json::Value> {
+ notification_ingress
+ .recorded_requests
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|request| request["req"]["notification"]["content"]["inviterName"].clone())
+ .collect()
+}
+
+/// Invites one member and returns the inviter names the invite emails carried.
+async fn inviter_names_for_invite(team_repo: MockTeamRepository) -> Vec<serde_json::Value> {
+ let team_id = uuid::Uuid::from_u128(7200);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let notification_ingress = Arc::new(MockNotificationIngress::new(HashSet::new()));
+ let service = TeamServiceImpl::new(
+ team_repo,
+ MockCustomerRepository::default(),
+ RecordingChannelService::default(),
+ MockUserRolesAndPermissionsService::default(),
+ notification_ingress.clone(),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ let invites = vec![
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
+ ];
+ let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();
+ service
+ .invite_users_to_team(
+ test_team_receipt::<MemberTeamRole>(team_id, &owner_id),
+ invites,
+ false,
+ )
+ .await
+ .unwrap();
+
+ inviter_names_sent(&notification_ingress)
+}
+
+fn invite_name_team_repo() -> MockTeamRepository {
+ let team_id = uuid::Uuid::from_u128(7200);
+ MockTeamRepository::new(
+ vec![make_invite(
+ uuid::Uuid::from_u128(7201),
+ team_id,
+ )],
+ "Acme",
+ Arc::new(Mutex::new(Vec::new())),
+ )
+}
+
+#[tokio::test]
+async fn invite_email_names_the_inviter() {
+ let names = inviter_names_for_invite(invite_name_team_repo()).await;
+ assert_eq!(names, ["Olivia Owner"]);
+}
+
+/// The email falls back to the inviter's address, so neither a missing name
+/// nor a failed lookup stops the invite.
+#[tokio::test]
+async fn invite_email_is_sent_without_the_inviters_name() {
+ let mut unnamed = invite_name_team_repo();
+ unnamed.user_display_name = None;
+ let mut failed = invite_name_team_repo();
+ failed.fail_user_display_name = true;
+
+ for team_repo in [unnamed, failed] {
+ let names = inviter_names_for_invite(team_repo).await;
+ assert_eq!(names, [serde_json::Value::Null]);
+ }
+}
+
/// The plan each sent invite email promised, in send order.
fn invitee_plans_sent(notification_ingress: &MockNotificationIngress) -> Vec<serde_json::Value> {
notification_ingress
@@ -8871,6 +8968,7 @@ async fn invite_reminders_email_each_claimed_invite() {
let content = &request["req"]["notification"]["content"];
assert_eq!(content["reminder"], true);
assert_eq!(content["teamName"], "Acme");
+ assert_eq!(content["inviterName"], "Olivia Owner");
assert_eq!(
content["teamInviteId"],
uuid::Uuid::from_u128(invite).to_string()
diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rs
index 0a637981ea..8bbc39c751 100644
--- a/crates/teams/src/outbound/team_repo.rs
+++ b/crates/teams/src/outbound/team_repo.rs
@@ -1368,6 +1368,33 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(name)
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_user_display_name(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Option<String>, TeamError> {
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ NULLIF(mui.first_name, 'N/A') AS first_name,
+ NULLIF(mui.last_name, 'N/A') AS last_name
+ FROM macro_user_info mui
+ JOIN "User" u ON mui.macro_user_id = u.macro_user_id
+ WHERE u.id = $1
+ LIMIT 1
+ "#,
+ user_id.as_ref(),
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ Ok(row.and_then(|row| match (row.first_name, row.last_name) {
+ (None, None) => None,
+ (Some(name), None) | (None, Some(name)) => Some(name),
+ (Some(first), Some(last)) => Some(format!("{first} {last}")),
+ }))
+ }
+
#[tracing::instrument(skip(self), err)]
async fn patch_team(
&self,
diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rs
index a3eb1ab926..0b2cfc82ba 100644
--- a/crates/teams/src/outbound/team_repo/test.rs
+++ b/crates/teams/src/outbound/team_repo/test.rs
@@ -2147,3 +2147,53 @@ async fn agent_invites_are_visible_to_the_invitee(pool: Pool<Postgres>) -> anyho
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_user_display_name_joins_the_set_name_parts(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ for statement in [
+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+ ('b1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'cus_full'),
+ ('b2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'cus_first'),
+ ('b3333333-3333-3333-3333-333333333333', '[email protected]', '[email protected]', 'cus_unset'),
+ ('b4444444-4444-4444-4444-444444444444', '[email protected]', '[email protected]', 'cus_none')"#,
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', 'b1111111-1111-1111-1111-111111111111'),
+ ('macro|[email protected]', '[email protected]', 'b2222222-2222-2222-2222-222222222222'),
+ ('macro|[email protected]', '[email protected]', 'b3333333-3333-3333-3333-333333333333'),
+ ('macro|[email protected]', '[email protected]', 'b4444444-4444-4444-4444-444444444444')"#,
+ r#"INSERT INTO macro_user_info (macro_user_id, first_name, last_name) VALUES
+ ('b1111111-1111-1111-1111-111111111111', 'Ada', 'Lovelace'),
+ ('b2222222-2222-2222-2222-222222222222', 'Grace', 'N/A'),
+ ('b3333333-3333-3333-3333-333333333333', 'N/A', NULL)"#,
+ ] {
+ sqlx::query(statement).execute(&pool).await?;
+ }
+ let team_repo = TeamRepositoryImpl::new(pool);
+
+ let mut names = Vec::new();
+ for user in [
+ ] {
+ let user = MacroUserIdStr::parse_from_str(user)?;
+ names.push(team_repo.get_user_display_name(&user).await?);
+ }
+
+ assert_eq!(
+ names,
+ [
+ Some("Ada Lovelace".to_string()),
+ Some("Grace".to_string()),
+ None,
+ None,
+ None,
+ ]
+ );
+
+ Ok(())
+}
diff --git a/infra/stacks/notification-service/service.ts b/infra/stacks/notification-service/service.ts
index f9519535e3..ebbffcc442 100644
--- a/infra/stacks/notification-service/service.ts
+++ b/infra/stacks/notification-service/service.ts
@@ -127,8 +127,11 @@ export class NotificationService extends pulumi.ComponentResource {
'ses:SendRawEmail',
'ses:SendTemplatedEmail',
],
+ // A send that names a configuration set (SES_CONFIGURATION_SET)
+ // is also authorized against that set.
Resource: [
`arn:aws:ses:us-east-1:569036502058:identity/notification.macro.com`,
+ `arn:aws:ses:us-east-1:569036502058:configuration-set/*`,
],
Effect: 'Allow',
},
diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.ts
index 41e678a622..93bb1406b5 100644
--- a/packages/sdk/generated/notification/types.gen.ts
+++ b/packages/sdk/generated/notification/types.gen.ts
@@ -996,6 +996,11 @@ export type InviteToTeamMetadata = {
* What the invitee gets by joining, as the team stood when the invite was sent.
*/
inviteePlan?: InviteePlan;
+ /**
+ * The inviter's display name, when they have set one. It is user-provided, so it is shown
+ * on one line, capped, and escaped; the email falls back to the inviter's address.
+ */
+ inviterName?: string | null;
/**
* Whether the invite creates an agent account.
*/
diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.json
index f9aaf403ec..9bc209234e 100644
--- a/packages/sdk/specs/notification.json
+++ b/packages/sdk/specs/notification.json
@@ -2496,6 +2496,10 @@
"$ref": "#/components/schemas/InviteePlan",
"description": "What the invitee gets by joining, as the team stood when the invite was sent."
},
+ "inviterName": {
+ "type": ["string", "null"],
+ "description": "The inviter's display name, when they have set one. It is user-provided, so it is shown\non one line, capped, and escaped; the email falls back to the inviter's address."
+ },
"isAgent": {
"type": "boolean",
"description": "Whether the invite creates an agent account."
diff --git a/services/notification_service/AGENTS.md b/services/notification_service/AGENTS.md
index 89508726c7..5be5e064b7 100644
--- a/services/notification_service/AGENTS.md
+++ b/services/notification_service/AGENTS.md
@@ -49,6 +49,11 @@ worker that sends email/mobile-push/websocket notifications.
- Don't log notification payloads on tracing spans (#7892) — they can carry
sensitive content; log ids/types instead.
+- `SES_CONFIGURATION_SET` is optional. When set, every notification email is
+ sent through that SES configuration set and tagged `notification_type`, so
+ its event destination reports delivery, bounce, open and click per type. Set
+ it only once the configuration set exists in that account and region and
+ the stack's SES policy (which allows `configuration-set/*`) is deployed.
## Related
diff --git a/services/notification_service/src/config.rs b/services/notification_service/src/config.rs
index fa16c303cb..e3075a97a4 100644
--- a/services/notification_service/src/config.rs
+++ b/services/notification_service/src/config.rs
@@ -9,7 +9,7 @@ use anyhow::Context;
use database_env_vars::{DatabaseUrl, RedisUri};
use macro_auth::InternalApiKey;
use macro_env::Environment;
-use macro_env_var::{env_var, env_vars, maybe_env_var};
+use macro_env_var::{env_var, env_vars, maybe_env_vars};
env_vars! {
#[derive(Debug, Clone)]
@@ -27,9 +27,12 @@ env_vars! {
pub(crate) struct KafkaBrokers;
}
-maybe_env_var! {
+maybe_env_vars! {
#[derive(Debug, Clone)]
pub(crate) struct SnsApnsVoipPlatformArn;
+ /// SES configuration set that publishes email delivery events. Unset sends without one.
+ #[derive(Debug, Clone)]
+ pub(crate) struct SesConfigurationSet;
}
env_var!(
@@ -88,6 +91,11 @@ pub struct Config {
/// The SNS iOS VoIP platform ARN (APNS_VOIP). Optional locally.
pub(crate) sns_apns_voip_platform_arn: SnsApnsVoipPlatformArn,
+
+ /// The SES configuration set every notification email is sent through, so delivery
+ /// events are published per notification type. Optional: the set must exist in SES
+ /// before this is configured, or sends fail.
+ pub(crate) ses_configuration_set: SesConfigurationSet,
}
impl Config {
diff --git a/services/notification_service/src/main.rs b/services/notification_service/src/main.rs
index bd34a16bfc..49ab370b48 100644
--- a/services/notification_service/src/main.rs
+++ b/services/notification_service/src/main.rs
@@ -233,7 +233,11 @@ pub async fn main() -> anyhow::Result<()> {
let ses_client = aws_sdk_sesv2::Client::new(&aws_config);
let email_adapter = SignedUnsubscribeLinks::new(
- EmailAdapter::new(ses_client, crate::env::SENDER_ADDRESS.clone()),
+ EmailAdapter::new(
+ ses_client,
+ crate::env::SENDER_ADDRESS.clone(),
+ config.ses_configuration_set.value().map(str::to_owned),
+ ),
macro_service_urls::NotificationServiceUrl::new_for_environment(config.environment)?
.parse_url()?,
hmac_key.clone(),
diff --git a/tooling/notification_sandbox/src/main.rs b/tooling/notification_sandbox/src/main.rs
index 8a79d3acd6..258cdbdd1d 100644
--- a/tooling/notification_sandbox/src/main.rs
+++ b/tooling/notification_sandbox/src/main.rs
@@ -149,6 +149,7 @@ async fn main() -> Result<(), Report> {
let email_adapter = EmailAdapter::new(
aws_sdk_sesv2::Client::new(&aws_config),
"[email protected]".to_string(),
+ None,
);
let egress_service = Arc::new(NotificationEgressService {