Cotton code
435 lines · 24.9 KB · TypeScriptRaw
/** * MAIL ON THE PERSON'S OWN DOMAIN, the object's half (22 Nov * 2026; assets/design/chat/OWN-MAIL.md). The Worker's `email` handler * (src/mail/receive.ts) finds the object by the domain (the Directory's * `mail_domain`) and hands it each message; this file decides whether the * address is the person's, keeps the message sealed at arrival, and sends * what the person taps Send on. * * WHAT THE OBJECT KEEPS IN THE CLEAR (settings and counts, never a word of * any mail): * *     mail_domain   a domain the person brings: its proof code, when proved, whether every address at it is theirs *     mail_address  an address of theirs: where a copy also goes (stage 1), whether it is the default From, and *                   `lands`: an alias, delivered into another address's mailbox (Post CONTRACT row 14) *     mail_address_gone  an address the person deleted: refused "No such mailbox here", catch-all or not *     mail_arrival  one row per message received: when, whether the copy went, what was kept, Cloudflare's verdicts *     mail_send     one row per draft sent: the ledger that makes a send happen once * * WHAT IT KEEPS SEALED: the raw message (`<db>/mail/in/<arrival>.eml`) and * each attachment (`<db>/mail/<email>/<index>`) as arrival files to the * arrival key; the `email`, `email_thread` and `email_participant` rows the * Mac would write for the same message (cotton-rules `mail::arrive`, run * as WASM), sealed at arrival. It never holds a key that opens them again. */import type { Engine, Outcome } from "../engine.ts";import type { Env } from "../env.ts";import { refuse } from "../http.ts";import { mailArrive, mailAttachment, type Fetched } from "../rules/index.ts";import type { Store } from "../store.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS mail_domain (domain TEXT PRIMARY KEY, code TEXT NOT NULL, proved_at INTEGER, catch_all INTEGER NOT NULL DEFAULT 0, added_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS mail_address (address TEXT PRIMARY KEY, forward_to TEXT, is_default INTEGER NOT NULL DEFAULT 0, added_at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS mail_address_gone (address TEXT PRIMARY KEY, at INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS mail_arrival (id TEXT PRIMARY KEY, received_at INTEGER NOT NULL, address TEXT NOT NULL, email_id TEXT, forwarded TEXT NOT NULL, kept TEXT NOT NULL, raw_key TEXT, size INTEGER NOT NULL, spf TEXT, dkim TEXT, dmarc TEXT, words TEXT);CREATE INDEX IF NOT EXISTS mail_arrival_by_time ON mail_arrival (received_at);CREATE INDEX IF NOT EXISTS mail_arrival_by_email ON mail_arrival (email_id);CREATE TABLE IF NOT EXISTS mail_send (draft TEXT PRIMARY KEY, state TEXT NOT NULL, from_address TEXT NOT NULL, message_id TEXT, code TEXT, words TEXT, started_at INTEGER NOT NULL, ended_at INTEGER, delivery TEXT, delivery_words TEXT, email_id TEXT);CREATE INDEX IF NOT EXISTS mail_send_by_message ON mail_send (message_id);`;/** Columns added since the table was first made (each object, once): an alias's mailbox. */export function migrate(sql: SqlStorage): void {  const columns = sql.exec<{ name: string }>("PRAGMA table_info(mail_address)").toArray().map((c) => c.name);  if (!columns.includes("lands")) sql.exec("ALTER TABLE mail_address ADD COLUMN lands TEXT");}/** Cloudflare's own inbound limit: larger is refused at its door, so anything larger here is not mail it sent us. */export const MAX_MESSAGE_BYTES = 25 * 1024 * 1024;/** Email Sending's limits (Limits, 22 Nov 2026). */export const MAX_RECIPIENTS = 50;export const MAX_SEND_BYTES = 25 * 1024 * 1024;/** A send the object began but never heard the end of is said `unknown` after this long. */export const SEND_UNKNOWN_MS = 2 * 60_000;/** What the object holds of the person's own domains and addresses, and its mail's arrivals. */export interface MailHost {  env: Env;  store: Store;  sql: SqlStorage;  databaseId: string;  now(): number;  /** The arrival public key, or null while no device has handed one over. */  arrivalPub(): Uint8Array | null;  /** `plain` sealed at arrival for `key` (`<db>/mail/…`) and put in the person's media. */  keepFile(key: string, plain: Uint8Array): Promise<void>;  /** One write whose rows in sealed tables are sealed at arrival (business.ts `writeSealing`). */  writeSealed<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): Promise<T>;  /** Tell the person's phones that mail came: "New mail", nothing more. */  alert(): Promise<void>;}type Row = Record<string, SqlStorageValue>;const ADDRESS = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+)$/;const DOMAIN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;/** An address as Cotton compares it: trimmed, lower-cased; null when it is not one. */export function addressOf(text: unknown): string | null {  if (typeof text !== "string") return null;  const a = text.trim().toLowerCase();  return a.length <= 254 && ADDRESS.test(a) ? a : null;}/** An address with its `+detail` cut (plus addressing, RFC 5233): the mailbox it is for. */export function mailboxOf(address: string): string {  const [local, domain] = address.split("@") as [string, string];  const plus = local.indexOf("+");  return `${plus > 0 ? local.slice(0, plus) : local}@${domain}`;}export function domainOf(address: string): string {  return address.slice(address.lastIndexOf("@") + 1);}export function isDomain(text: unknown): text is string {  return typeof text === "string" && text.length <= 253 && DOMAIN.test(text);}// ── The person's domains and addresses ──────────────────────────────────/** The TXT record that proves a domain is the person's: its name and value. */export function proofRecord(domain: string, code: string): { name: string; value: string } {  return { name: `_cotton.${domain}`, value: `cotton-verify=${code}` };}export function domains(host: MailHost): { domain: string; proved: boolean; catchAll: boolean; proof: { name: string; value: string } }[] {  return host.sql    .exec<Row>("SELECT domain, code, proved_at, catch_all FROM mail_domain ORDER BY domain")    .toArray()    .map((r) => ({ domain: String(r.domain), proved: r.proved_at !== null, catchAll: r.catch_all === 1, proof: proofRecord(String(r.domain), String(r.code)) }));}export function addresses(host: MailHost): { address: string; forwardTo: string | null; isDefault: boolean; lands: string | null }[] {  return host.sql    .exec<Row>("SELECT address, forward_to, is_default, lands FROM mail_address ORDER BY address")    .toArray()    .map((r) => ({ address: String(r.address), forwardTo: (r.forward_to as string | null) ?? null, isDefault: r.is_default === 1, lands: (r.lands as string | null) ?? null }));}/** A domain added: its proof code, made once and kept. */export function addDomain(host: MailHost, domain: string): { domain: string; proof: { name: string; value: string } } {  if (!isDomain(domain)) refuse(400, "bad_domain", `${String(domain)} is not a domain name`);  const held = host.sql.exec<Row>("SELECT code FROM mail_domain WHERE domain = ?", domain).toArray()[0];  const code = held ? String(held.code) : randomCode();  if (!held) host.sql.exec("INSERT INTO mail_domain (domain, code, added_at) VALUES (?, ?, ?)", domain, code, host.now());  return { domain, proof: proofRecord(domain, code) };}export function provedDomain(host: MailHost, domain: string): void {  host.sql.exec("UPDATE mail_domain SET proved_at = coalesce(proved_at, ?) WHERE domain = ?", host.now(), domain);}export function setCatchAll(host: MailHost, domain: string, on: boolean): void {  host.sql.exec("UPDATE mail_domain SET catch_all = ? WHERE domain = ?", on ? 1 : 0, domain);}/** An address of the person's at one of their domains: kept, with where a copy also goes and whether it is the default From. */export function setAddress(host: MailHost, input: { address: unknown; forwardTo?: unknown; isDefault?: unknown; lands?: unknown }): { address: string; forwardTo: string | null; isDefault: boolean; lands: string | null } {  const address = addressOf(input.address) ?? refuse(400, "bad_address", `${String(input.address)} is not an email address`);  if (address !== mailboxOf(address)) refuse(400, "bad_address", "an address is kept without its +part; mail to any +part reaches it");  const domain = domainOf(address);  if (!host.sql.exec<Row>("SELECT 1 FROM mail_domain WHERE domain = ?", domain).toArray().length) refuse(409, "unknown_domain", `add ${domain} first`);  const forwardTo = input.forwardTo === undefined || input.forwardTo === null || input.forwardTo === "" ? null : (addressOf(input.forwardTo) ?? refuse(400, "bad_address", `${String(input.forwardTo)} is not an email address`));  if (forwardTo && domainOf(forwardTo) === domain) refuse(400, "forward_loop", "a copy cannot go to an address at the same domain: it would come back here");  const isDefault = input.isDefault === true;  // An alias (Post CONTRACT, own domains): delivered as another of the person's addresses, into its mailbox, its copy  // going where that one's goes. It lands on a plain address only, never on itself or on another alias.  const lands = input.lands === undefined || input.lands === null || input.lands === "" ? null : (addressOf(input.lands) ?? refuse(400, "bad_address", `${String(input.lands)} is not an email address`));  if (lands !== null) {    if (lands === address) refuse(400, "alias_loop", "an address cannot land on itself");    const target = host.sql.exec<Row>("SELECT lands FROM mail_address WHERE address = ?", lands).toArray()[0];    if (!target) refuse(409, "unknown_address", `add ${lands} first: an alias lands on one of your addresses`);    if (target.lands !== null) refuse(400, "alias_loop", `${lands} is itself an alias: land on the address it lands on`);    if (forwardTo !== null) refuse(400, "bad_request", "an alias takes the copy of the address it lands on: give forwardTo there");    if (host.sql.exec<Row>("SELECT 1 FROM mail_address WHERE lands = ?", address).toArray().length) refuse(409, "aliases_land_here", `other addresses land on ${address}: it cannot become an alias itself`);  }  host.sql.exec(    "INSERT INTO mail_address (address, forward_to, is_default, added_at, lands) VALUES (?, ?, ?, ?, ?) ON CONFLICT (address) DO UPDATE SET forward_to = excluded.forward_to, is_default = excluded.is_default, lands = excluded.lands",    address,    forwardTo,    isDefault ? 1 : 0,    host.now(),    lands,  );  host.sql.exec("DELETE FROM mail_address_gone WHERE address = ?", address);  if (isDefault) host.sql.exec("UPDATE mail_address SET is_default = 0 WHERE address != ?", address);  return { address, forwardTo, isDefault, lands };}/** * An address deleted, with every alias that lands on it: each is remembered as gone, so mail to it is refused "No such * mailbox here" from now on, even at a catch-all domain, never dropped. Adding it again takes it back. */export function dropAddress(host: MailHost, raw: string): { removed: string[] } {  const address = addressOf(raw) ?? refuse(400, "bad_address", `${String(raw)} is not an email address`);  const removed = [address, ...host.sql.exec<Row>("SELECT address FROM mail_address WHERE lands = ?", address).toArray().map((r) => String(r.address))];  for (const a of removed) {    host.sql.exec("DELETE FROM mail_address WHERE address = ?", a);    host.sql.exec("INSERT INTO mail_address_gone (address, at) VALUES (?, ?) ON CONFLICT (address) DO UPDATE SET at = excluded.at", a, host.now());  }  return { removed };}function randomCode(): string {  const bytes = crypto.getRandomValues(new Uint8Array(12));  return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");}// ── Receiving ───────────────────────────────────────────────────────────/** Whether mail to `to` is the person's, and where its copy goes. */export interface MailPlan {  accept: boolean;  /** The mailbox it is for (its +part cut). */  mailbox: string;  forwardTo: string | null;}export function plan(host: MailHost, to: string): MailPlan {  const address = addressOf(to);  if (!address) return { accept: false, mailbox: String(to), forwardTo: null };  const mailbox = mailboxOf(address);  const domain = host.sql.exec<Row>("SELECT proved_at, catch_all FROM mail_domain WHERE domain = ?", domainOf(mailbox)).toArray()[0];  if (!domain || domain.proved_at === null) return { accept: false, mailbox, forwardTo: null };  const held = host.sql.exec<Row>("SELECT forward_to, lands FROM mail_address WHERE address = ?", mailbox).toArray()[0];  if (held && typeof held.lands === "string") {    // An alias: delivered into the mailbox it lands on, with that one's copy. Its own address stays in the message's To.    const target = host.sql.exec<Row>("SELECT forward_to FROM mail_address WHERE address = ?", held.lands).toArray()[0];    if (!target) return { accept: false, mailbox, forwardTo: null };    return { accept: true, mailbox: held.lands, forwardTo: (target.forward_to as string | null) ?? null };  }  if (held) return { accept: true, mailbox, forwardTo: (held.forward_to as string | null) ?? null };  // Deleted: refused, catch-all or not.  if (host.sql.exec<Row>("SELECT 1 FROM mail_address_gone WHERE address = ?", mailbox).toArray().length) return { accept: false, mailbox, forwardTo: null };  if (domain.catch_all !== 1) return { accept: false, mailbox, forwardTo: null };  // Any address at a catch-all domain is the person's; its copy goes where the default address's goes.  const fallback = host.sql.exec<Row>("SELECT forward_to FROM mail_address WHERE is_default = 1 AND address LIKE ?", `%@${domainOf(mailbox)}`).toArray()[0];  return { accept: true, mailbox, forwardTo: (fallback?.forward_to as string | null) ?? null };}/** One message handed over by the Worker's email handler. */export interface Arrival {  raw: Uint8Array;  /** The envelope recipient, as Cloudflare gave it. */  to: string;  /** Whether the copy to the present mailbox went: `ok`, `failed`, or `none` when none was asked. */  forwarded: "ok" | "failed" | "none";  received: number;  /** What IMAP said of it, when Cotton fetched it from a mailbox (src/mail/fetcher.ts): its state comes from these. */  fetched?: Fetched;}/** What the arrival kept: rows and files, the raw message only (the phone finishes it), a message already held, or nothing (no key, and it was forwarded). */export type Kept = "rows" | "raw" | "duplicate" | "no_key";export interface Arrived {  id: string;  kept: Kept;  /** Milliseconds per step (raw, decode, attachments, rows, alert): what the proof at size reads. */  steps?: Record<string, number>;  email?: string;  words?: string;}interface Decoded {  email: { id: string; data: Record<string, unknown> };  thread: { id: string; key: string; data: Record<string, unknown> };  participants: { id: string; data: Record<string, unknown> }[];  attachments: { index: number; name: string; mime: string | null; size: number | null }[];  auth: { spf: string; dkim: string; dmarc: string } | null;  sentAt: string;}/** * Keep one message, sealed. The raw message goes first: if what follows * fails, it is still there for the phone. With no arrival key the message * cannot be kept without being kept readable, which is never done: when its * copy went to the present mailbox it is counted and let go (nothing is * lost); when it did not, this throws, and the handler does not tell * Cloudflare the message was taken. */export async function arrive(host: MailHost, arrival: Arrival): Promise<Arrived> {  const id = crypto.randomUUID();  // Each step's milliseconds (a Worker's clock moves across I/O, not across its own code: a step of 0 ran no I/O).  const steps: Record<string, number> = {};  let mark = Date.now();  const step = (name: string) => {    const now = Date.now();    steps[name] = (steps[name] ?? 0) + now - mark;    mark = now;  };  const mailbox = mailboxOf(addressOf(arrival.to) ?? arrival.to.toLowerCase());  const tally = (kept: Kept, fields: { email?: string; raw?: string; auth?: Decoded["auth"]; words?: string } = {}): Arrived => {    host.sql.exec(      "INSERT INTO mail_arrival (id, received_at, address, email_id, forwarded, kept, raw_key, size, spf, dkim, dmarc, words) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",      id,      arrival.received,      mailbox,      fields.email ?? null,      arrival.forwarded,      kept,      fields.raw ?? null,      arrival.raw.byteLength,      fields.auth?.spf ?? null,      fields.auth?.dkim ?? null,      fields.auth?.dmarc ?? null,      fields.words ?? null,    );    return { id, kept, steps, ...(fields.email ? { email: fields.email } : {}), ...(fields.words ? { words: fields.words } : {}) };  };  if (arrival.raw.byteLength > MAX_MESSAGE_BYTES) refuse(413, "too_large", "a message is at most 25 MiB");  if (!host.arrivalPub()) {    if (arrival.forwarded === "ok") return tally("no_key", { words: "no device has handed this database its arrival key yet; the copy went to the present mailbox" });    refuse(409, "no_arrival_key", "no device has handed this database its arrival key yet, and mail is never kept readable");  }  const raw = `${host.databaseId}/mail/in/${id}.eml`;  const input = { database: host.databaseId, account: mailbox, received: arrival.received, ...(arrival.fetched ? { fetched: arrival.fetched } : {}) };  // Read first, and a message already kept keeps nothing more: fetched mail (the fetcher reads history again after a  // new UIDVALIDITY) and mail sent again by anyone, so a resent message never stores its bytes twice (AUDIT A M5).  const decoded = mailArrive<Decoded>(arrival.raw, input);  step("decode");  if ("ok" in decoded && host.store.any("email", decoded.ok.email.id)) return tally("duplicate", { email: decoded.ok.email.id, auth: decoded.ok.auth });  await host.keepFile(raw, arrival.raw);  step("raw");  if ("error" in decoded) return tally("raw", { raw, words: decoded.error });  const mail = decoded.ok;  if (host.store.any("email", mail.email.id)) return tally("duplicate", { email: mail.email.id, raw, auth: mail.auth });  // Each attachment's bytes, sealed, named where the row says.  const attachments: Record<string, unknown>[] = [];  for (const a of mail.attachments) {    const bytes = mailAttachment(arrival.raw, a.index);    const entry: Record<string, unknown> = { name: a.name, ...(a.mime ? { mime: a.mime } : {}), ...(a.size !== null ? { size: a.size } : {}) };    if (bytes) {      const key = `${host.databaseId}/mail/${mail.email.id}/${a.index}`;      await host.keepFile(key, bytes);      entry.key = key;    }    attachments.push(entry);  }  const data = { ...mail.email.data, attachments };  step("attachments");  await host.writeSealed((engine, version, outcome) => {    const thread = host.store.get("email_thread", mail.thread.id);    if (!thread) engine.create("email_thread", mail.thread.data, version, outcome, 0, { id: mail.thread.id });    else if (String(thread.data.last_at ?? "") < mail.sentAt) engine.update(thread, { last_at: mail.sentAt }, version, outcome);    for (const p of mail.participants) if (!host.store.get("email_participant", p.id)) engine.create("email_participant", p.data, version, outcome, 0, { id: p.id });    engine.create("email", data, version, outcome, 0, { id: mail.email.id });    return null;  });  step("rows");  const arrived = tally("rows", { email: mail.email.id, raw, auth: mail.auth });  await host.alert();  step("alert");  return arrived;}/** The tally's last days, for the stage-1 proof: per day, how many came, how many were copied and kept. */export function tallyDays(host: MailHost, days: number): { day: string; came: number; forwarded: number; forwardFailed: number; rows: number; raw: number; duplicate: number; noKey: number }[] {  const since = host.now() - days * 86_400_000;  return host.sql    .exec<Row>(      `SELECT date(received_at / 1000, 'unixepoch') AS day, count(*) AS came,        sum(forwarded = 'ok') AS forwarded, sum(forwarded = 'failed') AS forward_failed,        sum(kept = 'rows') AS rows, sum(kept = 'raw') AS raw, sum(kept = 'duplicate') AS duplicate, sum(kept = 'no_key') AS no_key       FROM mail_arrival WHERE received_at >= ? GROUP BY day ORDER BY day`,      since,    )    .toArray()    .map((r) => ({ day: String(r.day), came: Number(r.came), forwarded: Number(r.forwarded), forwardFailed: Number(r.forward_failed), rows: Number(r.rows), raw: Number(r.raw), duplicate: Number(r.duplicate), noKey: Number(r.no_key) }));}/** * Which of these email ids arrived by the domain: the Mac's cross-check of the mail it reads from the present * mailbox. The ids are bound as ONE JSON parameter: the Mac asks up to 1,000 at once, and a Durable Object's * SQLite binds at most 100 parameters ("too many SQL variables", the Mac's mail stuck at 500 on 23 Nov 2026). */export function arrivedIds(host: MailHost, ids: string[]): string[] {  if (!ids.length) return [];  return host.sql    .exec<Row>("SELECT DISTINCT email_id FROM mail_arrival WHERE email_id IN (SELECT value FROM json_each(?))", JSON.stringify(ids))    .toArray()    .map((r) => String(r.email_id));}/** The raw messages the object kept but could not read into rows: the phone reads them (`mail.arrive` in the core) and says so. */export function rawOnly(host: MailHost, limit = 100): { id: string; key: string; address: string; received: number; words: string | null }[] {  return host.sql    .exec<Row>("SELECT id, raw_key, address, received_at, words FROM mail_arrival WHERE kept = 'raw' ORDER BY received_at LIMIT ?", limit)    .toArray()    .map((r) => ({ id: String(r.id), key: String(r.raw_key), address: String(r.address), received: Number(r.received_at), words: (r.words as string | null) ?? null }));}export function rawRead(host: MailHost, id: string, email: string | null): void {  host.sql.exec("UPDATE mail_arrival SET kept = 'rows', email_id = coalesce(?, email_id), words = NULL WHERE id = ? AND kept = 'raw'", email, id);}// ── The Sent copy ───────────────────────────────────────────────────────/** RFC 2047's encoded-word for a header that is not plain ASCII. */function headerText(value: string): string {  if (/^[\x20-\x7e]*$/.test(value)) return value;  const bytes = new TextEncoder().encode(value);  let bin = "";  for (const b of bytes) bin += String.fromCharCode(b);  return `=?UTF-8?B?${btoa(bin)}?=`;}/** The message as it went, written out as mail: what the decoder reads to make the Sent copy's rows. */export function sentMessage(m: { from: string; to: string[]; cc: string[]; subject: string; text: string; messageId: string; inReplyTo: string | null; references: string[]; at: number }): Uint8Array {  const lines = [    `From: ${m.from}`,    `To: ${m.to.join(", ")}`,    ...(m.cc.length ? [`Cc: ${m.cc.join(", ")}`] : []),    `Subject: ${headerText(m.subject)}`,    `Date: ${new Date(m.at).toUTCString().replace("GMT", "+0000")}`,    `Message-ID: ${m.messageId}`,    ...(m.inReplyTo ? [`In-Reply-To: ${m.inReplyTo}`] : []),    ...(m.references.length ? [`References: ${m.references.join(" ")}`] : []),    "MIME-Version: 1.0",    "Content-Type: text/plain; charset=utf-8",    "Content-Transfer-Encoding: 8bit",    "",    m.text,  ];  return new TextEncoder().encode(lines.join("\r\n"));}/** * What was sent, kept in Sent: the same rows an arrival makes (one decoder), * marked as the person's own (out, read, not in the inbox), sealed at * arrival. A reply joins the conversation its draft was written in. */export async function keepSent(host: MailHost, raw: Uint8Array, from: string, thread: string | null): Promise<string | null> {  if (!host.arrivalPub()) return null;  const decoded = mailArrive<Decoded>(raw, { database: host.databaseId, account: from, received: host.now() });  if ("error" in decoded) return null;  const mail = decoded.ok;  if (host.store.any("email", mail.email.id)) return mail.email.id;  const held = thread ? host.store.get("email_thread", thread) : null;  const threadId = held ? held.id : mail.thread.id;  const data = { ...mail.email.data, thread_id: threadId, direction: "out", unread: false, in_inbox: false };  await host.writeSealed((engine, version, outcome) => {    const t = host.store.get("email_thread", threadId);    if (!t) engine.create("email_thread", mail.thread.data, version, outcome, 0, { id: threadId });    else if (String(t.data.last_at ?? "") < mail.sentAt) engine.update(t, { last_at: mail.sentAt }, version, outcome);    // A new conversation gets its people; one already held keeps those it has.    if (threadId === mail.thread.id) for (const p of mail.participants) if (!host.store.get("email_participant", p.id)) engine.create("email_participant", p.data, version, outcome, 0, { id: p.id });    engine.create("email", data, version, outcome, 0, { id: mail.email.id });    return null;  });  return mail.email.id;}