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(email): inject signature server-side on send (#4378)

Evan Hutnik58c1cb05924c
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index f30bb54874..03325cbdc9 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -125,6 +125,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -311,6 +312,7 @@
"document_sub_type",
"documents",
"email",
+ "email_db_client",
"email_utils",
"email_validator",
"embedding",
@@ -444,6 +446,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -516,6 +519,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -686,6 +690,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -779,6 +784,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -1019,6 +1025,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -1144,6 +1151,7 @@
"deleted_item_poller",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -1483,6 +1491,7 @@
"document_upload_finalizer_handler",
"documents",
"email",
+ "email_db_client",
"email_utils",
"embedding",
"entity_access",
@@ -1565,6 +1574,7 @@
"document_sub_type",
"documents",
"email",
+ "email_db_client",
"email_utils",
"embedding",
"entity_access",
@@ -1639,6 +1649,7 @@
"document_sub_type",
"docx_unzip_handler",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -1698,6 +1709,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -1712,6 +1724,7 @@
"model_file_type",
"model_user",
"models_bulk_upload",
+ "models_email",
"models_pagination",
"models_permissions",
"non_empty",
@@ -1764,6 +1777,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_refresh_handler",
"email_utils",
"entity_access",
@@ -1804,6 +1818,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_scheduled_handler",
"email_utils",
"entity_access",
@@ -1919,6 +1934,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_service_client",
"email_utils",
"entity_access",
@@ -1952,6 +1968,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_sfs_delete_handler",
"email_utils",
"entity_access",
@@ -2145,6 +2162,7 @@
"document_sub_type",
"documents",
"email",
+ "email_db_client",
"email_utils",
"embedding",
"entity_access",
@@ -2411,6 +2429,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -3036,6 +3055,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -3116,6 +3136,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -3341,6 +3362,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -3381,6 +3403,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -3862,6 +3885,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -3928,6 +3952,7 @@
"document_storage_service_client",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -4086,6 +4111,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_db_utils",
@@ -4151,6 +4177,7 @@
"crm",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -4304,6 +4331,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"embedding",
"entity_access",
@@ -4374,6 +4402,7 @@
"decode_jwt",
"document_sub_type",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -4441,6 +4470,7 @@
"document_sub_type",
"dynamodb_client",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
@@ -4482,6 +4512,7 @@
"document_sub_type",
"dynamodb_client",
"email",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInput.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInput.ts
index 3d55e95e72..e6de3c933a 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInput.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInput.ts
@@ -11,6 +11,7 @@ import type { ApiDraftInputBodyText } from './apiDraftInputBodyText';
import type { ApiDraftInputCc } from './apiDraftInputCc';
import type { ApiDraftInputDbId } from './apiDraftInputDbId';
import type { ApiDraftInputHeadersJson } from './apiDraftInputHeadersJson';
+import type { ApiDraftInputIncludeSignature } from './apiDraftInputIncludeSignature';
import type { ApiDraftInputProviderId } from './apiDraftInputProviderId';
import type { ApiDraftInputProviderThreadId } from './apiDraftInputProviderThreadId';
import type { ApiDraftInputReplyingToId } from './apiDraftInputReplyingToId';
@@ -34,6 +35,10 @@ export interface ApiDraftInput {
/** Existing message DB ID (for updating an existing draft). */
db_id?: ApiDraftInputDbId;
headers_json?: ApiDraftInputHeadersJson;
+ /** Per-message override for whether to include the signature on send:
+`Some(false)` to exclude (user dismissed it). Omit to use the inbox's
+default policy. Ignored for drafts. */
+ include_signature?: ApiDraftInputIncludeSignature;
/** Provider message ID. */
provider_id?: ApiDraftInputProviderId;
/** Provider thread ID. */
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputIncludeSignature.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputIncludeSignature.ts
new file mode 100644
index 0000000000..3ccd40f4d8
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputIncludeSignature.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Per-message override for whether to include the signature on send:
+`Some(false)` to exclude (user dismissed it). Omit to use the inbox's
+default policy. Ignored for drafts.
+ */
+export type ApiDraftInputIncludeSignature = boolean | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index 0e07502fae..4cea6e2435 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -43,6 +43,7 @@ export * from './apiDraftInputBodyText';
export * from './apiDraftInputCc';
export * from './apiDraftInputDbId';
export * from './apiDraftInputHeadersJson';
+export * from './apiDraftInputIncludeSignature';
export * from './apiDraftInputProviderId';
export * from './apiDraftInputProviderThreadId';
export * from './apiDraftInputReplyingToId';
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index 0c97d28718..f029e02eff 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -3059,6 +3059,10 @@
}
]
},
+ "include_signature": {
+ "type": ["boolean", "null"],
+ "description": "Per-message override for whether to include the signature on send:\n`Some(false)` to exclude (user dismissed it). Omit to use the inbox's\ndefault policy. Ignored for drafts."
+ },
"provider_id": {
"type": ["string", "null"],
"description": "Provider message ID."
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 8d109be160..498c9f577f 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4328,12 +4328,14 @@ dependencies = [
"crm",
"doppleganger",
"either",
+ "email_db_client",
"email_utils",
"entity_access",
"filter_ast",
"frecency",
"futures",
"item_filters",
+ "lol_html",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
@@ -4345,6 +4347,7 @@ dependencies = [
"recursion",
"redis",
"schemars 1.2.1",
+ "scraper",
"serde",
"serde_json",
"serde_with",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 662fa98e7c..1a04409f5c 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -124,6 +124,7 @@ livekit-api = { version = "0.4.16", default-features = false, features = [
] }
livekit-protocol = "0.7.2"
log = "0.4.26"
+lol_html = "2.4.0"
mockall = "0.13"
nom = "8"
opentelemetry = "0.31.0"
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index fa114a176b..dc4065635f 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -35,7 +35,7 @@ axum = [
]
gmail_token = ["dep:authentication_service_client", "dep:redis", "ports"]
inbound = ["ports"]
-outbound = ["dep:sqlx", "ports"]
+outbound = ["dep:sqlx", "dep:email_db_client", "ports"]
ports = ["crm/ports", "dep:tokio", "frecency/ports"]
[dependencies]
@@ -56,6 +56,9 @@ email_utils = { path = "../email_utils" }
filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency" }
item_filters = { path = "../item_filters" }
+lol_html = { workspace = true }
+scraper = { workspace = true }
+email_db_client = { path = "../email_db_client", optional = true }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model-entity = { path = "../model-entity" }
diff --git a/rust/cloud-storage/email/src/domain/models/draft.rs b/rust/cloud-storage/email/src/domain/models/draft.rs
index 4c1d1d7210..b8af1583dd 100644
--- a/rust/cloud-storage/email/src/domain/models/draft.rs
+++ b/rust/cloud-storage/email/src/domain/models/draft.rs
@@ -35,6 +35,10 @@ pub struct CreateDraftInput {
pub headers_json: Option<JsonValue>,
/// Scheduled send time.
pub send_time: Option<DateTime<Utc>>,
+ /// Per-message override for signature inclusion: `Some(false)` to exclude
+ /// (the user dismissed it), `Some(true)` to force-include, `None` to apply
+ /// the inbox's default policy. Only consulted on send (ignored for drafts).
+ pub include_signature: Option<bool>,
}
/// A draft input with all IDs resolved, ready for database insertion.
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index ae04c4a27d..956b977025 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -39,6 +39,16 @@ pub trait EmailMessageEnqueuer: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
+/// The sending inbox's signature preferences, used by the send pipeline to
+/// decide whether to inject the signature into the outgoing body.
+#[derive(Debug, Clone, Default)]
+pub struct LinkEmailSettings {
+ /// The saved signature HTML (already sanitized server-side), if any.
+ pub signature: Option<String>,
+ /// Whether the signature should be added on replies and forwards.
+ pub signature_on_replies_forwards: bool,
+}
+
pub trait EmailRepo: Send + Sync + 'static {
type Err: Send;
fn previews_for_view_cursor(
@@ -290,6 +300,16 @@ pub trait EmailRepo: Send + Sync + 'static {
&self,
link_id: Uuid,
) -> impl Future<Output = Result<Vec<EmailFilter>, Self::Err>> + Send;
+
+ /// Fetch the inbox's signature preferences. Defaults to "no signature" so
+ /// repos that don't override it (and the send path when settings are
+ /// missing) simply skip signature injection.
+ fn fetch_email_settings(
+ &self,
+ _link_id: Uuid,
+ ) -> impl Future<Output = Result<LinkEmailSettings, EmailErr>> + Send {
+ async { Ok(LinkEmailSettings::default()) }
+ }
}
/// Read-only trait for fetching email thread previews.
diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rs
index d1e954c532..ebba506dd1 100644
--- a/rust/cloud-storage/email/src/domain/service/draft.rs
+++ b/rust/cloud-storage/email/src/domain/service/draft.rs
@@ -55,6 +55,13 @@ where
decode_html_body(&mut input)?;
+ // On send (not drafts), inject the inbox's signature into the body per
+ // the user's settings + per-message override. Best-effort: never blocks
+ // the send.
+ if !is_draft {
+ self.maybe_inject_signature(link, &mut input).await;
+ }
+
// Build parsed addresses
let from_email = String::from(link.email_address.clone());
let addresses = ParsedAddresses {
@@ -119,6 +126,71 @@ where
})
}
+ /// Appends the inbox's signature to the outgoing body (send path only).
+ /// Gated by the per-message override and the inbox's settings; replies and
+ /// forwards (a `replying_to_id` is present) require
+ /// `signature_on_replies_forwards`. Best-effort — any failure just skips.
+ async fn maybe_inject_signature(&self, link: &Link, input: &mut CreateDraftInput) {
+ if input.include_signature == Some(false) {
+ // Honor "exclude" literally: drop any server-wrapped signature a
+ // client may have baked in, rather than just declining to add one.
+ if input
+ .body_html
+ .as_deref()
+ .is_some_and(super::signature::has_signature)
+ && let Some(body_html) = input.body_html.take()
+ {
+ input.body_html = Some(super::signature::strip_signature(&body_html));
+ }
+ return;
+ }
+ // Idempotent: if the body already carries a signature — a client still
+ // baking it in during the FE cutover, or a re-sent message — don't add
+ // another (and leave body_text alone too).
+ if input
+ .body_html
+ .as_deref()
+ .is_some_and(super::signature::has_signature)
+ {
+ return;
+ }
+ let settings = match self.email_repo.fetch_email_settings(link.id).await {
+ Ok(settings) => settings,
+ Err(e) => {
+ tracing::warn!(error = ?e, "failed to fetch settings for signature; skipping");
+ return;
+ }
+ };
+ let Some(signature) = settings.signature.filter(|s| !s.trim().is_empty()) else {
+ return;
+ };
+ let include = match input.include_signature {
+ Some(value) => value,
+ None => {
+ if input.replying_to_id.is_some() {
+ settings.signature_on_replies_forwards
+ } else {
+ true
+ }
+ }
+ };
+ if !include {
+ return;
+ }
+ if let Some(body_html) = input.body_html.take() {
+ input.body_html = Some(super::signature::inject_signature(&body_html, &signature));
+ }
+ let plain = super::signature::signature_plain_text(&signature);
+ if !plain.is_empty()
+ && let Some(existing) = input.body_text.take().filter(|s| !s.is_empty())
+ {
+ // Only append to an existing plain-text body. HTML-only sends
+ // (body_text None/empty, e.g. the AI path) keep no text part rather
+ // than getting a signature-only one that drops the message body.
+ input.body_text = Some(format!("{existing}\n\n{plain}"));
+ }
+ }
+
async fn validate_existing_message(
&self,
link_id: Uuid,
diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rs
index b7efd056eb..26f5783a0d 100644
--- a/rust/cloud-storage/email/src/domain/service/mod.rs
+++ b/rust/cloud-storage/email/src/domain/service/mod.rs
@@ -1,6 +1,7 @@
mod draft;
mod previews;
mod send;
+mod signature;
mod thread;
mod thread_labels;
diff --git a/rust/cloud-storage/email/src/domain/service/signature.rs b/rust/cloud-storage/email/src/domain/service/signature.rs
new file mode 100644
index 0000000000..cbc7501331
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/service/signature.rs
@@ -0,0 +1,114 @@
+use lol_html::html_content::ContentType;
+use lol_html::{HtmlRewriter, Settings, element};
+use scraper::{Html, Selector};
+use std::cell::Cell;
+
+#[cfg(test)]
+mod test;
+
+/// Marker class wrapping an injected signature.
+const SIGNATURE_CLASS: &str = "macro-email-signature";
+
+/// Whether the body already carries an injected signature, so the caller can
+/// stay idempotent across a client that still bakes it in and across re-sends.
+pub(crate) fn has_signature(body_html: &str) -> bool {
+ Selector::parse(&format!(".{SIGNATURE_CLASS}"))
+ .ok()
+ .map(|sel| {
+ Html::parse_fragment(body_html)
+ .select(&sel)
+ .next()
+ .is_some()
+ })
+ .unwrap_or(false)
+}
+
+/// Injects the (already-sanitized) signature into the outgoing HTML body,
+/// wrapped in a `.macro-email-signature` marker div. Placed after the message
+/// but above any quoted/forwarded thread (Gmail's ordering): inserted before the
+/// first `.macro_quote` block if present, else appended to `<body>`. If neither
+/// matches (e.g. a bare fragment with no `<body>`), it is appended to the end so
+/// the signature is never silently dropped.
+pub(crate) fn inject_signature(body_html: &str, signature_html: &str) -> String {
+ let wrapped = format!(r#"<div class="{SIGNATURE_CLASS}">{signature_html}</div>"#);
+
+ let has_quote = Selector::parse(".macro_quote")
+ .ok()
+ .map(|sel| {
+ Html::parse_fragment(body_html)
+ .select(&sel)
+ .next()
+ .is_some()
+ })
+ .unwrap_or(false);
+
+ let done = Cell::new(false);
+ let selector = if has_quote { ".macro_quote" } else { "body" };
+ let mut output = Vec::new();
+ let mut rewriter = HtmlRewriter::new(
+ Settings {
+ element_content_handlers: vec![element!(selector, |el| {
+ if !done.get() {
+ if has_quote {
+ el.before(&wrapped, ContentType::Html);
+ } else {
+ el.append(&wrapped, ContentType::Html);
+ }
+ done.set(true);
+ }
+ Ok(())
+ })],
+ ..Settings::default()
+ },
+ |c: &[u8]| output.extend_from_slice(c),
+ );
+
+ if rewriter.write(body_html.as_bytes()).is_err() {
+ return format!("{body_html}{wrapped}");
+ }
+ if rewriter.end().is_err() {
+ return format!("{body_html}{wrapped}");
+ }
+ let mut result = match String::from_utf8(output) {
+ Ok(result) => result,
+ Err(_) => return format!("{body_html}{wrapped}"),
+ };
+ // Neither a `<body>` nor a `.macro_quote` matched (e.g. a bare fragment) —
+ // append rather than drop the signature.
+ if !done.get() {
+ result.push_str(&wrapped);
+ }
+ result
+}
+
+/// Removes any server-wrapped signature (the `.macro-email-signature` element
+/// and its contents) from the body. Used to honor an explicit
+/// `include_signature = false` even when a client already baked one in.
+pub(crate) fn strip_signature(body_html: &str) -> String {
+ let selector = format!(".{SIGNATURE_CLASS}");
+ let mut output = Vec::new();
+ let mut rewriter = HtmlRewriter::new(
+ Settings {
+ element_content_handlers: vec![element!(selector.as_str(), |el| {
+ el.remove();
+ Ok(())
+ })],
+ ..Settings::default()
+ },
+ |c: &[u8]| output.extend_from_slice(c),
+ );
+ if rewriter.write(body_html.as_bytes()).is_err() {
+ return body_html.to_string();
+ }
+ if rewriter.end().is_err() {
+ return body_html.to_string();
+ }
+ String::from_utf8(output).unwrap_or_else(|_| body_html.to_string())
+}
+
+/// Extracts the signature's visible text for the `text/plain` MIME alternative.
+/// Uses a block-aware HTML->text conversion so inline tags (`<strong>`, `<a>`, …)
+/// stay on one line and only block boundaries introduce newlines.
+pub(crate) fn signature_plain_text(signature_html: &str) -> String {
+ email_utils::body_parsed::html_to_plaintext(signature_html).unwrap_or_default()
+}
diff --git a/rust/cloud-storage/email/src/domain/service/signature/test.rs b/rust/cloud-storage/email/src/domain/service/signature/test.rs
new file mode 100644
index 0000000000..39d710cf7e
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/service/signature/test.rs
@@ -0,0 +1,72 @@
+use super::*;
+
+#[test]
+fn appends_to_body_after_message_when_no_quote() {
+ let out = inject_signature("<body><p>Hi there</p></body>", "<p>Regards</p>");
+ assert!(out.contains("macro-email-signature"), "got: {out}");
+ // The signature lands after the message content.
+ assert!(out.find("Hi there").unwrap() < out.find("macro-email-signature").unwrap());
+}
+
+#[test]
+fn inserts_above_quote_for_replies_and_forwards() {
+ let body = r#"<body><p>My reply</p><div class="macro_quote"><p>Quoted</p></div></body>"#;
+ let out = inject_signature(body, "<p>Regards</p>");
+ let sig = out.find("macro-email-signature").unwrap();
+ let quote = out.find("macro_quote").unwrap();
+ assert!(
+ sig < quote,
+ "signature should sit above the quoted thread: {out}"
+ );
+}
+
+#[test]
+fn appends_to_bare_fragment_without_body_or_quote() {
+ // No <body> element and no quote: the signature must still be added
+ // (regression for the "selector didn't match" gap).
+ let out = inject_signature("<p>Hello</p>", "<p>Regards</p>");
+ assert!(out.contains("Hello"), "got: {out}");
+ assert!(out.contains("macro-email-signature"), "got: {out}");
+}
+
+#[test]
+fn is_idempotent_when_signature_already_present() {
+ assert!(has_signature(
+ r#"<body><div class="macro-email-signature">x</div></body>"#
+ ));
+ assert!(!has_signature("<body><p>no signature here</p></body>"));
+}
+
+#[test]
+fn plain_text_joins_block_nodes_with_newlines() {
+ // Block boundaries become newlines (not run together as "ThanksAlice").
+ assert_eq!(
+ signature_plain_text("<div>Thanks</div><div>Alice</div>"),
+ "Thanks\nAlice"
+ );
+}
+
+#[test]
+fn plain_text_keeps_inline_markup_on_one_line() {
+ // Inline tags must not introduce a line break (regression for the previous
+ // text-node join that produced "Thanks\nAlice").
+ assert_eq!(
+ signature_plain_text("<div>Thanks <strong>Alice</strong></div>"),
+ "Thanks **Alice**"
+ );
+}
+
+#[test]
+fn strips_server_wrapped_signature() {
+ let body = inject_signature("<body><p>Hi there</p></body>", "<p>Regards</p>");
+ assert!(has_signature(&body));
+ let stripped = strip_signature(&body);
+ assert!(
+ !has_signature(&stripped),
+ "signature not removed: {stripped}"
+ );
+ assert!(
+ stripped.contains("Hi there"),
+ "message body must remain: {stripped}"
+ );
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/draft.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/draft.rs
index 66fd358e1e..f2dc1f592f 100644
--- a/rust/cloud-storage/email/src/inbound/axum/api_types/draft.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/draft.rs
@@ -66,6 +66,11 @@ pub struct ApiDraftInput {
pub body_macro: Option<String>,
/// Headers JSON.
pub headers_json: Option<JsonValue>,
+ /// Per-message override for whether to include the signature on send:
+ /// `Some(false)` to exclude (user dismissed it). Omit to use the inbox's
+ /// default policy. Ignored for drafts.
+ #[serde(default)]
+ pub include_signature: Option<bool>,
}
/// Request body for creating a draft.
@@ -154,6 +159,7 @@ impl CreateDraftRequest {
body_macro: draft.body_macro,
headers_json: draft.headers_json,
send_time: self.send_time,
+ include_signature: draft.include_signature,
}
}
}
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/send.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/send.rs
index b257ebede7..0ddd786c4d 100644
--- a/rust/cloud-storage/email/src/inbound/axum/api_types/send.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/send.rs
@@ -56,6 +56,7 @@ impl SendMessageRequest {
body_macro: msg.body_macro,
headers_json: msg.headers_json,
send_time: None,
+ include_signature: msg.include_signature,
}
}
}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/send_email.rs b/rust/cloud-storage/email/src/inbound/toolset/send_email.rs
index edc0912313..047aa9671a 100644
--- a/rust/cloud-storage/email/src/inbound/toolset/send_email.rs
+++ b/rust/cloud-storage/email/src/inbound/toolset/send_email.rs
@@ -120,6 +120,8 @@ where
body_macro: None,
headers_json: None,
send_time: None,
+ // None = let the backend apply the default signature policy.
+ include_signature: None,
};
let sent = service_context
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
index 2a9ccdca3c..351adbb53e 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
@@ -1,11 +1,11 @@
use crate::domain::{
models::{
- Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailFilter,
- EmailThreadPreview, Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow,
- ParsedAddresses, PreviewCursorQuery, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo,
- ThreadRow, UpsertEmailFilterInput, UpsertedContacts, UserProvider,
+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailErr,
+ EmailFilter, EmailThreadPreview, Label, Link, LinkLabel, MessageAttachment, MessageLabel,
+ MessageRow, ParsedAddresses, PreviewCursorQuery, ResolvedDraftInput, SimpleMessage,
+ SimpleMessageInfo, ThreadRow, UpsertEmailFilterInput, UpsertedContacts, UserProvider,
},
- ports::{EmailRepo, RecipientsByMessageId},
+ ports::{EmailRepo, LinkEmailSettings, RecipientsByMessageId},
};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
@@ -57,6 +57,16 @@ impl EmailPgRepo {
impl EmailRepo for EmailPgRepo {
type Err = sqlx::Error;
+ async fn fetch_email_settings(&self, link_id: Uuid) -> Result<LinkEmailSettings, EmailErr> {
+ let settings = email_db_client::settings::fetch_settings(&self.pool, link_id)
+ .await
+ .map_err(EmailErr::RepoErr)?;
+ Ok(LinkEmailSettings {
+ signature: settings.signature,
+ signature_on_replies_forwards: settings.signature_on_replies_forwards,
+ })
+ }
+
async fn previews_for_view_cursor(
&self,
query: PreviewCursorQuery,
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 2996e1b05d..6c9c0d36a1 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -100,7 +100,7 @@ html-escape = "0.2"
http-body-util = { workspace = true }
infer = "0.19.0"
item_filters = { path = "../item_filters" }
-lol_html = "2.4.0"
+lol_html = { workspace = true }
macro_auth = { path = "../macro_auth" }
macro_cors = { path = "../macro_cors" }
macro_config = { path = "../macro_config" }
diff --git a/rust/cloud-storage/email_utils/src/body_parsed.rs b/rust/cloud-storage/email_utils/src/body_parsed.rs
index f7f144e95e..17f8578c2d 100644
--- a/rust/cloud-storage/email_utils/src/body_parsed.rs
+++ b/rust/cloud-storage/email_utils/src/body_parsed.rs
@@ -44,6 +44,19 @@ pub fn compute_body_parsed_linkless(
})
}
+/// Convert an HTML fragment to block-aware plaintext: block elements are
+/// separated by newlines, but inline runs (`<strong>`, `<em>`, `<a>`, …) stay
+/// on one line. Returns `None` if conversion fails. Suitable for building a
+/// `text/plain` MIME alternative from a small HTML snippet (e.g. a signature).
+pub fn html_to_plaintext(html: &str) -> Option<String> {
+ let config = html2text::config::plain()
+ .no_table_borders()
+ .link_footnotes(false)
+ .no_link_wrapping();
+
+ parse_html_to_text(html, config)
+}
+
fn parse_html_to_text(html: &str, config: Config<PlainDecorator>) -> Option<String> {
match config.string_from_read(html.as_bytes(), usize::MAX) {
Ok(text) => {
@@ -132,6 +145,22 @@ mod tests {
assert!(text.contains("123 Business St."));
}
+ #[test]
+ fn test_html_to_plaintext_inline_vs_block() {
+ // Inline tags stay on one line — no spurious break between the runs.
+ // Emphasis renders as markdown markers, matching the rest of our
+ // HTML->plaintext conversion.
+ assert_eq!(
+ html_to_plaintext("<div>Thanks <strong>Alice</strong></div>"),
+ Some("Thanks **Alice**".to_string())
+ );
+ // Block elements are separated by newlines.
+ assert_eq!(
+ html_to_plaintext("<div>Thanks</div><div>Alice</div>"),
+ Some("Thanks\nAlice".to_string())
+ );
+ }
+
#[test]
fn test_linkless_strips_brackets() {
let body = Some("<p>Visit <a href=\"https://example.com\">example</a></p>".to_string());