|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The bounds a caller's message passes before the mail service sends it, for |
| 5 | + * every door a caller reaches mail through: the HTTP send door |
| 6 | + * (`POST /api/v1/email/send`, `@objectstack/rest`) and the script-body door |
| 7 | + * (`ctx.email.send`, `@objectstack/runtime`). One implementation, so the two |
| 8 | + * doors cannot admit different messages. |
| 9 | + * |
| 10 | + * What a door decides itself, before it calls this: WHO may use it (the HTTP |
| 11 | + * door's capability; the body door's declared `email.send` token) and what |
| 12 | + * shape a body may have. What this module decides, for both: |
| 13 | + * |
| 14 | + * 1. ATTRIBUTION — `sentBy` is the calling user. A message naming another |
| 15 | + * user is refused; one naming the caller (or none) is stamped with the |
| 16 | + * caller. A call with no calling user (a scheduled job's body) records no |
| 17 | + * sender, and a message naming one is refused. |
| 18 | + * 2. SENDER — the envelope sender is the deployment's configured sender |
| 19 | + * (`IEmailService.getDefaultFrom`). A `from` naming any other address is |
| 20 | + * refused; one naming the configured address is replaced by the configured |
| 21 | + * value. A deployment that reports no configured sender refuses a caller |
| 22 | + * `from`. Custom `headers` may not name the sender |
| 23 | + * ({@link SENDER_HEADER_NAMES}), and are accepted in one shape only: a |
| 24 | + * plain object mapping each header field name to a single-line string. |
| 25 | + * 3. TENANT — the message belongs to the caller's organization, which this |
| 26 | + * stamps as `organizationId`. A message naming another organization, or |
| 27 | + * naming one when the caller has none, is refused. `identityMail` is |
| 28 | + * refused: identity mail is sent by the server itself. A message restating |
| 29 | + * `identityMail: false` is admitted, and the forwarded message never |
| 30 | + * carries the caller's value. |
| 31 | + * |
| 32 | + * `replyTo` is not bounded: it is the caller's choice of Reply-To address and |
| 33 | + * makes no claim about the sender. |
| 34 | + */ |
| 35 | + |
| 36 | +import type { EmailAddress } from '@objectstack/spec/contracts'; |
| 37 | + |
| 38 | +/** |
| 39 | + * Custom header names (compared case-insensitively) a caller may not set: each |
| 40 | + * one states who the message is from, which bound 2 reserves to the configured |
| 41 | + * sender. |
| 42 | + */ |
| 43 | +export const SENDER_HEADER_NAMES: ReadonlySet<string> = new Set(['from', 'sender', 'return-path']); |
| 44 | + |
| 45 | +/** |
| 46 | + * A header field name: one or more printable US-ASCII characters other than |
| 47 | + * the colon (RFC 5322 §2.2). |
| 48 | + */ |
| 49 | +const HEADER_FIELD_NAME = /^[\x21-\x39\x3b-\x7e]+$/; |
| 50 | + |
| 51 | +/** A plain object — an object literal or a JSON-parsed object, never an array or a class instance. */ |
| 52 | +export function isPlainMailObject(value: unknown): value is Record<string, unknown> { |
| 53 | + if (value === null || typeof value !== 'object' || Array.isArray(value)) return false; |
| 54 | + const proto = Object.getPrototypeOf(value); |
| 55 | + return proto === Object.prototype || proto === null; |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Why a caller's `headers` cannot be forwarded, or `undefined` when it can. |
| 60 | + * Absent is fine. Otherwise it must be the contract's `Record<string, string>` |
| 61 | + * exactly, with no key one of {@link SENDER_HEADER_NAMES}. |
| 62 | + */ |
| 63 | +function headersRefusal(headers: unknown): string | undefined { |
| 64 | + if (headers === undefined) return undefined; |
| 65 | + if (!isPlainMailObject(headers)) { |
| 66 | + return 'Custom `headers` must be an object mapping each header name to a string value.'; |
| 67 | + } |
| 68 | + for (const [name, value] of Object.entries(headers)) { |
| 69 | + if (!HEADER_FIELD_NAME.test(name)) { |
| 70 | + return 'Custom `headers` must be keyed by header field names: printable ASCII with no space, control character or colon.'; |
| 71 | + } |
| 72 | + if (typeof value !== 'string' || /[\r\n]/.test(value)) { |
| 73 | + return `Custom \`headers\` value for \`${name}\` must be a single-line string.`; |
| 74 | + } |
| 75 | + if (SENDER_HEADER_NAMES.has(name.toLowerCase())) { |
| 76 | + return `Custom header \`${name}\` cannot be set: the sender is the deployment's configured sender.`; |
| 77 | + } |
| 78 | + } |
| 79 | + return undefined; |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * The bare address an {@link EmailAddress} names, lower-cased for comparison, |
| 84 | + * or `undefined` when it names none. For the string form a trailing |
| 85 | + * `<address>` wins over the display name before it. |
| 86 | + */ |
| 87 | +export function mailAddressOf(value: unknown): string | undefined { |
| 88 | + let raw: unknown = value; |
| 89 | + if (value && typeof value === 'object') raw = (value as { address?: unknown }).address; |
| 90 | + if (typeof raw !== 'string') return undefined; |
| 91 | + const angled = /<([^<>]*)>\s*$/.exec(raw); |
| 92 | + const address = (angled ? angled[1] : raw).trim().toLowerCase(); |
| 93 | + return address.length > 0 ? address : undefined; |
| 94 | +} |
| 95 | + |
| 96 | +/** Who is sending, as the door resolved it — never as the message says. */ |
| 97 | +export interface CallerMailIdentity { |
| 98 | + /** The calling user, or `undefined` for a call with none (a scheduled job). */ |
| 99 | + userId: string | undefined; |
| 100 | + /** The caller's active organization, or `undefined` when it has none. */ |
| 101 | + organizationId: string | undefined; |
| 102 | +} |
| 103 | + |
| 104 | +/** The part of the mail service the bounds read: its configured sender. */ |
| 105 | +export interface CallerMailSenderSource { |
| 106 | + getDefaultFrom?: () => EmailAddress | undefined; |
| 107 | +} |
| 108 | + |
| 109 | +/** The bounded message, or the reason the caller's message is refused. */ |
| 110 | +export type CallerMailBoundsResult = |
| 111 | + | { ok: true; input: Record<string, unknown> } |
| 112 | + | { ok: false; reason: string }; |
| 113 | + |
| 114 | +/** |
| 115 | + * Apply the three bounds of the module header to a caller's `message`, and |
| 116 | + * answer the message the mail service is handed, or the refusal. Pure: it |
| 117 | + * reads only its arguments and the service's configured sender. |
| 118 | + */ |
| 119 | +export function boundCallerMail( |
| 120 | + message: Record<string, unknown>, |
| 121 | + caller: CallerMailIdentity, |
| 122 | + sender: CallerMailSenderSource, |
| 123 | +): CallerMailBoundsResult { |
| 124 | + // Bound 1: attribution. |
| 125 | + if (message.sentBy !== undefined && message.sentBy !== caller.userId) { |
| 126 | + return { |
| 127 | + ok: false, |
| 128 | + reason: caller.userId |
| 129 | + ? '`sentBy` is the authenticated caller; a send cannot be attributed to another user.' |
| 130 | + : '`sentBy` cannot be set: this call has no calling user. Omit it.', |
| 131 | + }; |
| 132 | + } |
| 133 | + |
| 134 | + // Bound 2: the sender is the configured one. |
| 135 | + const headersRefused = headersRefusal(message.headers); |
| 136 | + if (headersRefused !== undefined) return { ok: false, reason: headersRefused }; |
| 137 | + let from: EmailAddress | undefined; |
| 138 | + if (message.from !== undefined) { |
| 139 | + const configured = typeof sender.getDefaultFrom === 'function' ? sender.getDefaultFrom() : undefined; |
| 140 | + const configuredAddress = mailAddressOf(configured); |
| 141 | + if (!configuredAddress || mailAddressOf(message.from) !== configuredAddress) { |
| 142 | + return { |
| 143 | + ok: false, |
| 144 | + reason: configuredAddress |
| 145 | + ? `\`from\` must be the deployment's configured sender (${configuredAddress}); omit it to send as that sender.` |
| 146 | + : '`from` cannot be chosen by the caller: this deployment reports no configured sender. Configure one in Settings → Mail → From address and omit `from`.', |
| 147 | + }; |
| 148 | + } |
| 149 | + from = configured; |
| 150 | + } |
| 151 | + |
| 152 | + // Bound 3: the caller's organization, and identity mail is the server's. |
| 153 | + const organizationId = caller.organizationId; |
| 154 | + if (message.organizationId !== undefined && message.organizationId !== organizationId) { |
| 155 | + return { |
| 156 | + ok: false, |
| 157 | + reason: organizationId |
| 158 | + ? '`organizationId` is the caller\'s active organization; a send cannot be recorded under another organization.' |
| 159 | + : '`organizationId` cannot be set: the caller has no active organization. Omit it.', |
| 160 | + }; |
| 161 | + } |
| 162 | + if (message.identityMail !== undefined && message.identityMail !== false) { |
| 163 | + return { |
| 164 | + ok: false, |
| 165 | + reason: '`identityMail` cannot be set through this door: identity mail is sent by the server itself. Omit it.', |
| 166 | + }; |
| 167 | + } |
| 168 | + |
| 169 | + const rest = { ...message }; |
| 170 | + delete rest.organizationId; |
| 171 | + delete rest.identityMail; |
| 172 | + delete rest.sentBy; |
| 173 | + return { |
| 174 | + ok: true, |
| 175 | + input: { |
| 176 | + ...rest, |
| 177 | + ...(caller.userId !== undefined ? { sentBy: caller.userId } : {}), |
| 178 | + ...(organizationId !== undefined ? { organizationId } : {}), |
| 179 | + ...(from !== undefined ? { from } : {}), |
| 180 | + }, |
| 181 | + }; |
| 182 | +} |
0 commit comments