Diffinery

homeflare/celldpublic

feat(bindings): send_email binding for Email Sending

Jason Schwarzenberger authored 1 parent 588fd42commit 3962d406231bfe72c04aa7f9449e7f46c3593415Browse files
9 files changed+219−2
Files (9)
modifiedHOMEFLARE.md+1−0View file
@@ -26,6 +26,7 @@
2626 | `media` binding (Media Transformations) | palm makes video thumbnails with `env.MEDIA_TRANSFORMS.input(stream).transform(...).output({ mode: "frame" })`. The Wrangler `media` key becomes a binding (config → manifest → `WorkerConfig::with_media` → `__makeMediaBinding`) that reads the input and posts it, with both option objects in the `x-media-transform` header, to `CELLD_MEDIA_URL/transform`: Homeflare's `homeflare-media` (ffmpeg). Its answers and `{code, message}` errors (as `MediaError`) are the binding's. Without `CELLD_MEDIA_URL` a result rejects with code 9500. |
2727 | `version_metadata` binding | Upstream celld had none, so Homeflare passed the version ID as a plain string. The binding is now Cloudflare's frozen `{ id, tag, timestamp }`. The config may set all three (Homeflare passes its own version ID, tag and time, so they match its Dashboard and `wrangler versions`); otherwise the id is the deployment's version, the tag is empty and the timestamp is the deploy time. |
2828 | `ratelimits` binding | Diffinery limits sign-ins and API calls with `env.RL_*.limit({ key })`. Each entry becomes a binding counted on the node by a `__ratelimit` op: fixed windows of the period (10 or 60 s), keyed by namespace id and key and shared by the node's isolates, as each Cloudflare location counts on its own. |
29+| `send_email` binding (Email Sending) | Diffinery sends sign-up codes, invitations and notifications with `env.EMAIL.send({ from, to, subject, html, text })`. The binding checks the message and the binding's `allowed_sender_addresses` / `destination_address` / `allowed_destination_addresses`, then posts it in the REST API's shape (`{address, name}`, `reply_to`, base64 attachments) to `CELLD_EMAIL_URL/send` with `CELLD_EMAIL_TOKEN` as a bearer. Homeflare relays it to Cloudflare's Email Sending API. The result is `{ messageId, delivered, queued, permanent_bounces, suppressed_recipients }`; API errors become the binding's `E_*` codes. The legacy raw `EmailMessage` isn't supported (celld has no `cloudflare:email`). |
2930 | `homeflare:` line in `celld --version` | Lists what this build adds (`HOMEFLARE_FEATURES` in `lib.rs`), so Homeflare sends a config key only to a celld that accepts it. Add a feature there with each patch. |
3031
3132 ## Building
modifiedcrates/celld/deploy.rs+62−1View file
@@ -60,6 +60,7 @@
6060 "media",
6161 "version_metadata",
6262 "ratelimits",
63+ "send_email",
6364 "containers",
6465 "no_bundle",
6566 "define",
@@ -570,6 +571,10 @@
570571 binding.get("period").and_then(Value::as_u64).unwrap_or(0)
571572 ),
572573 )),
574+ Some("send_email") => Some((
575+ format!("env.{name} (Email)"),
576+ "Email Sending".to_string(),
577+ )),
573578 Some("plain_text") => Some((
574579 format!("env.{name} (Text)"),
575580 "Environment Variable".to_string(),
@@ -2030,6 +2035,61 @@
20302035 }
20312036 Some(_) => bail!("config `ratelimits` must be an array"),
20322037 }
2038+ // `send_email` (Homeflare patch): Cloudflare's Email Sending binding,
2039+ // `env.EMAIL.send({ from, to, subject, ... })`. The node relays each
2040+ // message to the email service at CELLD_EMAIL_URL (Homeflare sends it on
2041+ // through Cloudflare's Email Sending API). The address restrictions are
2042+ // checked by the binding.
2043+ let mut send_email = Vec::new();
2044+ match object.get("send_email") {
2045+ None => {}
2046+ Some(Value::Array(list)) => {
2047+ for entry in list {
2048+ let Value::Object(entry) = entry else {
2049+ bail!("each `send_email` entry must be an object");
2050+ };
2051+ let name = match entry.get("name") {
2052+ Some(Value::String(name)) if valid_binding(name) => name.clone(),
2053+ _ => bail!("a `send_email` entry needs a valid `name`"),
2054+ };
2055+ let addresses = |key: &str| -> anyhow::Result<Value> {
2056+ match entry.get(key) {
2057+ None | Some(Value::Null) => Ok(Value::Null),
2058+ Some(Value::Array(list)) if list.iter().all(Value::is_string) => {
2059+ Ok(Value::Array(list.clone()))
2060+ }
2061+ Some(_) => bail!("send_email {name}: `{key}` must be a list of addresses"),
2062+ }
2063+ };
2064+ let destination = match entry.get("destination_address") {
2065+ None | Some(Value::Null) => Value::Null,
2066+ Some(Value::String(address)) => Value::String(address.clone()),
2067+ Some(_) => bail!("send_email {name}: `destination_address` must be a string"),
2068+ };
2069+ if let Some(key) = entry.keys().find(|key| {
2070+ !matches!(
2071+ key.as_str(),
2072+ "name"
2073+ | "destination_address"
2074+ | "allowed_destination_addresses"
2075+ | "allowed_sender_addresses"
2076+ | "remote"
2077+ )
2078+ }) {
2079+ bail!("send_email {name} sets `{key}`, which celld does not support");
2080+ }
2081+ bindings.push(json!({
2082+ "type": "send_email",
2083+ "name": name,
2084+ "destination_address": destination,
2085+ "allowed_destination_addresses": addresses("allowed_destination_addresses")?,
2086+ "allowed_sender_addresses": addresses("allowed_sender_addresses")?,
2087+ }));
2088+ send_email.push(name);
2089+ }
2090+ }
2091+ Some(_) => bail!("config `send_email` must be an array"),
2092+ }
20332093 let mut vars = BTreeMap::new();
20342094 match object.get("vars") {
20352095 None => {}
@@ -2098,7 +2158,8 @@
20982158 || !worker_loaders.is_empty()
20992159 || media_binding.is_some()
21002160 || version_metadata.is_some()
2101- || !ratelimits.is_empty())
2161+ || !ratelimits.is_empty()
2162+ || !send_email.is_empty())
21022163 {
21032164 bail!("an asset-only project cannot declare Worker bindings");
21042165 }
modifiedcrates/celld/fleet.rs+2−1View file
@@ -921,8 +921,9 @@
921921 ))
922922 });
923923 // Bindings the Homeflare patches install from their manifest entry as is
924- // (`ratelimit`).
924+ // (`ratelimit`, `send_email`).
925925 let homeflare_bindings = bindings(&manifest, "ratelimit")
926+ .chain(bindings(&manifest, "send_email"))
926927 .cloned()
927928 .collect();
928929 let services = service_bindings(&manifest);
modifiedcrates/celld/js/bootstrap.rs+16−0View file
@@ -703,6 +703,22 @@
703703 ));
704704 }
705705 }
706+ // Email Sending (Homeflare patch): the binding relays to the node's
707+ // email service, or says it has none.
708+ let email_service = serde_json::to_string(
709+ &std::env::var("CELLD_EMAIL_URL").ok().filter(|url| !url.trim().is_empty()),
710+ )
711+ .unwrap_or_else(|_| "null".into());
712+ let email_token = serde_json::to_string(&std::env::var("CELLD_EMAIL_TOKEN").ok())
713+ .unwrap_or_else(|_| "null".into());
714+ for binding in &config.homeflare_bindings {
715+ if binding.get("type").and_then(serde_json::Value::as_str) == Some("send_email") {
716+ let name = binding.get("name").cloned().unwrap_or(serde_json::Value::Null);
717+ lines.push_str(&format!(
718+ "e[{name}] = __celld.__makeSendEmail({name}, {binding}, {email_service}, {email_token});\n"
719+ ));
720+ }
721+ }
706722 // Media Transformations (Homeflare patch): the binding posts to the
707723 // node's media service, or says it has none.
708724 if !config.media_bindings.is_empty() {
modifiedcrates/celld/js/harness.js+102−0View file
@@ -1241,6 +1241,108 @@
12411241 return { success: __ratelimit(`${namespace}\u0000${key}`, limit, period) };
12421242 },
12431243 });
1244+// A `send_email` binding (Homeflare patch): Cloudflare's Email Sending API,
1245+// `await env.EMAIL.send({ from, to, subject, html, text, ... })` ->
1246+// `{ messageId }`. The binding checks the message and the binding's address
1247+// restrictions, then posts it in the REST API's shape to the node's email
1248+// service (CELLD_EMAIL_URL; Homeflare relays it to Cloudflare's Email
1249+// Sending API). The answer's delivered, queued, permanent_bounces and
1250+// suppressed_recipients come back alongside messageId.
1251+const __EMAIL_CODES = {
1252+ 10001: "E_VALIDATION_ERROR", 10202: "E_VALIDATION_ERROR", 10200: "E_CONTENT_TOO_LARGE",
1253+ 10201: "E_VALIDATION_ERROR", 10004: "E_RATE_LIMIT_EXCEEDED", 10203: "E_EMAIL_SENDING_NOT_READY",
1254+ 10207: "E_ACCOUNT_SUSPENDED", 10105: "E_EMAIL_SENDING_NOT_READY", 10002: "E_INTERNAL_SERVER_ERROR",
1255+};
1256+const __emailError = (code, message) => Object.assign(new Error(message), { code });
1257+const __emailAddress = (binding, field, value) => {
1258+ if (typeof value === "string" && value !== "") return value;
1259+ if (value && typeof value === "object" && typeof value.email === "string" && typeof value.name === "string") {
1260+ return { address: value.email, name: value.name };
1261+ }
1262+ throw new TypeError(`${binding}.send(): ${field} must be an address string or { email, name }`);
1263+};
1264+const __emailAddresses = (binding, field, value) =>
1265+ value === undefined ? [] : (Array.isArray(value) ? value : [value]).map((v) => __emailAddress(binding, field, v));
1266+const __emailBare = (a) => (typeof a === "string" ? a : a.address).replace(/^.*<([^>]+)>\s*$/, "$1").trim().toLowerCase();
1267+const __base64 = (content) => {
1268+ if (typeof content === "string") return content;
1269+ const bytes = content instanceof ArrayBuffer
1270+ ? new Uint8Array(content)
1271+ : new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
1272+ let binary = "";
1273+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
1274+ return btoa(binary);
1275+};
1276+__celld.__makeSendEmail = (binding, config, service, token) => ({
1277+ async send(message) {
1278+ if (!message || typeof message !== "object" || "raw" in message) {
1279+ throw new TypeError(`${binding}.send() takes an Email Sending message ({ from, to, subject, ... }); celld has no raw EmailMessage`);
1280+ }
1281+ if (message.from === undefined) throw new TypeError(`${binding}.send(): from is required`);
1282+ if (typeof message.subject !== "string") throw new TypeError(`${binding}.send(): subject is required`);
1283+ const from = __emailAddress(binding, "from", message.from);
1284+ const to = __emailAddresses(binding, "to", message.to);
1285+ const cc = __emailAddresses(binding, "cc", message.cc);
1286+ const bcc = __emailAddresses(binding, "bcc", message.bcc);
1287+ const recipients = [...to, ...cc, ...bcc];
1288+ if (recipients.length === 0) throw new TypeError(`${binding}.send(): give at least one of to, cc or bcc`);
1289+ if (recipients.length > 50) throw __emailError("E_TOO_MANY_RECIPIENTS", `${binding}: at most 50 recipients`);
1290+ const attachments = message.attachments ?? [];
1291+ if (!Array.isArray(attachments)) throw new TypeError(`${binding}.send(): attachments must be an array`);
1292+ if (attachments.length > 32) throw __emailError("E_TOO_MANY_ATTACHMENTS", `${binding}: at most 32 attachments`);
1293+ const senders = config.allowed_sender_addresses;
1294+ if (Array.isArray(senders) && !senders.map((a) => a.toLowerCase()).includes(__emailBare(from))) {
1295+ throw __emailError("E_SENDER_NOT_VERIFIED", `${binding}: ${__emailBare(from)} isn't one of this binding's allowed senders`);
1296+ }
1297+ const allowed = config.destination_address != null
1298+ ? [config.destination_address]
1299+ : config.allowed_destination_addresses;
1300+ if (Array.isArray(allowed)) {
1301+ const list = allowed.map((a) => a.toLowerCase());
1302+ const refused = recipients.map(__emailBare).find((a) => !list.includes(a));
1303+ if (refused) throw __emailError("E_RECIPIENT_NOT_ALLOWED", `${binding}: ${refused} isn't an allowed destination for this binding`);
1304+ }
1305+ if (!service) {
1306+ throw __emailError("E_EMAIL_SENDING_NOT_READY", `${binding}: this celld node has no email service (set CELLD_EMAIL_URL)`);
1307+ }
1308+ const body = { from, subject: message.subject };
1309+ if (to.length) body.to = to;
1310+ if (cc.length) body.cc = cc;
1311+ if (bcc.length) body.bcc = bcc;
1312+ if (message.replyTo !== undefined) body.reply_to = __emailAddress(binding, "replyTo", message.replyTo);
1313+ if (message.html !== undefined) body.html = String(message.html);
1314+ if (message.text !== undefined) body.text = String(message.text);
1315+ if (message.headers !== undefined) body.headers = message.headers;
1316+ if (attachments.length) {
1317+ body.attachments = attachments.map((a) => {
1318+ const out = { content: __base64(a.content), filename: a.filename, type: a.type, disposition: a.disposition ?? "attachment" };
1319+ if (a.contentId !== undefined) out.content_id = a.contentId;
1320+ return out;
1321+ });
1322+ }
1323+ let response;
1324+ try {
1325+ response = await fetch(`${service.replace(/\/+$/, "")}/send`, {
1326+ method: "POST",
1327+ headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
1328+ body: JSON.stringify(body),
1329+ });
1330+ } catch (error) {
1331+ throw __emailError("E_INTERNAL_SERVER_ERROR", `${binding}: the email service at ${service} can't be reached (${error?.message ?? error})`);
1332+ }
1333+ let answer = null;
1334+ try { answer = await response.json(); } catch { /* not JSON */ }
1335+ if (!response.ok || !answer?.success) {
1336+ const first = answer?.errors?.[0];
1337+ const code = (typeof first?.code === "string" && first.code.startsWith("E_") && first.code)
1338+ || __EMAIL_CODES[first?.code]
1339+ || (response.status === 429 ? "E_RATE_LIMIT_EXCEEDED" : "E_DELIVERY_FAILED");
1340+ throw __emailError(code, `${binding}: ${first?.message ?? `email service answered ${response.status}`}`);
1341+ }
1342+ const result = answer.result ?? {};
1343+ return { ...result, messageId: result.message_id };
1344+ },
1345+});
12441346 __celld.__makeR2Bucket = (binding, bucketName) => ({
12451347 async head(key) {
12461348 const name = __r2Key(binding, "head", key);
modifiedcrates/celld/lib.rs+1−0View file
@@ -324,4 +324,5 @@
324324 "media",
325325 "version-metadata",
326326 "ratelimits",
327+ "send-email",
327328 ];
modifieddocs/cloudflare-compat.md+1−0View file
@@ -29,6 +29,7 @@
2929 | [R2](services/r2.md) | **Yes** |
3030 | Version metadata (`version_metadata` binding) | **Yes** — `{ id, tag, timestamp }`; a platform can set all three in the config (Homeflare patch) |
3131 | Rate Limiting (`ratelimits`) | **Yes** — `limit({ key })`, counted per node in fixed windows of the period (Homeflare patch) |
32+| Email Sending (`send_email` binding) | **Partial** — the Email Sending message object (no raw `EmailMessage`); needs an email service at `CELLD_EMAIL_URL`, such as Homeflare's relay to Cloudflare Email Sending (Homeflare patch) |
3233 | Media Transformations (`media` binding) | **Partial** — needs a media service at `CELLD_MEDIA_URL`, such as Homeflare's `homeflare-media` (Homeflare patch) |
3334 | Workers AI | **No** |
3435 | Vectorize | **No** |
addedhomeflare/smoke/send-email/index.js+25−0View file
@@ -1,0 +1,25 @@
1+// Smoke test for the send_email binding without an email service: argument
2+// checks, the binding's address restrictions, and the "no service" error.
3+// (run.sh starts celld without CELLD_EMAIL_URL.)
4+const expectEqual = (name, got, want) => ({ name, ok: JSON.stringify(got) === JSON.stringify(want), got });
5+const outcome = async (promise) => {
6+ try { await promise; return "sent"; } catch (e) { return e.code ?? e.constructor.name; }
7+};
8+
9+export default {
10+ async fetch(request, env) {
11+ const ok = { from: "[email protected]", to: "[email protected]", subject: "Hi", text: "Hello" };
12+ const checks = [
13+ expectEqual("has send()", typeof env.EMAIL.send, "function"),
14+ expectEqual("no recipient", await outcome(env.EMAIL.send({ from: "[email protected]", subject: "x", text: "y" })), "TypeError"),
15+ expectEqual("named address needs a name", await outcome(env.EMAIL.send({ ...ok, from: { email: "[email protected]" } })), "TypeError"),
16+ expectEqual("raw EmailMessage", await outcome(env.EMAIL.send({ from: "[email protected]", to: "[email protected]", raw: "x" })), "TypeError"),
17+ expectEqual("51 recipients", await outcome(env.EMAIL.send({ ...ok, to: Array.from({ length: 51 }, (_, i) => `r${i}@example.com`) })), "E_TOO_MANY_RECIPIENTS"),
18+ expectEqual("sender not allowed", await outcome(env.LOCKED.send({ ...ok, from: "[email protected]" })), "E_SENDER_NOT_VERIFIED"),
19+ expectEqual("destination not allowed", await outcome(env.LOCKED.send({ ...ok, to: "[email protected]" })), "E_RECIPIENT_NOT_ALLOWED"),
20+ expectEqual("no email service", await outcome(env.LOCKED.send({ ...ok, from: { email: "[email protected]", name: "Bot" } })), "E_EMAIL_SENDING_NOT_READY"),
21+ ];
22+ const failed = checks.filter((c) => !c.ok);
23+ return Response.json({ ok: failed.length === 0, failed, checks }, { status: failed.length ? 500 : 200 });
24+ },
25+};
addedhomeflare/smoke/send-email/wrangler.jsonc+9−0View file
@@ -1,0 +1,9 @@
1+{
2+ "name": "send-email",
3+ "main": "index.js",
4+ "compatibility_date": "2026-01-01",
5+ "send_email": [
6+ { "name": "EMAIL" },
7+ { "name": "LOCKED", "allowed_sender_addresses": ["[email protected]"], "destination_address": "[email protected]" }
8+ ]
9+}