@sayedhfatimi/convex-email 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +700 -2
  3. package/dist/adapters/index.d.ts +2 -0
  4. package/dist/adapters/index.d.ts.map +1 -0
  5. package/dist/adapters/index.js +7 -0
  6. package/dist/adapters/index.js.map +1 -0
  7. package/dist/adapters/registry.d.ts +9 -0
  8. package/dist/adapters/registry.d.ts.map +1 -0
  9. package/dist/adapters/registry.js +20 -0
  10. package/dist/adapters/registry.js.map +1 -0
  11. package/dist/adapters/resend/inbound.d.ts +5 -0
  12. package/dist/adapters/resend/inbound.d.ts.map +1 -0
  13. package/dist/adapters/resend/inbound.js +207 -0
  14. package/dist/adapters/resend/inbound.js.map +1 -0
  15. package/dist/adapters/resend/index.d.ts +4 -0
  16. package/dist/adapters/resend/index.d.ts.map +1 -0
  17. package/dist/adapters/resend/index.js +27 -0
  18. package/dist/adapters/resend/index.js.map +1 -0
  19. package/dist/adapters/resend/parse.d.ts +3 -0
  20. package/dist/adapters/resend/parse.d.ts.map +1 -0
  21. package/dist/adapters/resend/parse.js +94 -0
  22. package/dist/adapters/resend/parse.js.map +1 -0
  23. package/dist/adapters/resend/send.d.ts +15 -0
  24. package/dist/adapters/resend/send.d.ts.map +1 -0
  25. package/dist/adapters/resend/send.js +117 -0
  26. package/dist/adapters/resend/send.js.map +1 -0
  27. package/dist/adapters/resend/webhook.d.ts +6 -0
  28. package/dist/adapters/resend/webhook.d.ts.map +1 -0
  29. package/dist/adapters/resend/webhook.js +66 -0
  30. package/dist/adapters/resend/webhook.js.map +1 -0
  31. package/dist/adapters/ses/inbound.d.ts +3 -0
  32. package/dist/adapters/ses/inbound.d.ts.map +1 -0
  33. package/dist/adapters/ses/inbound.js +52 -0
  34. package/dist/adapters/ses/inbound.js.map +1 -0
  35. package/dist/adapters/ses/index.d.ts +4 -0
  36. package/dist/adapters/ses/index.d.ts.map +1 -0
  37. package/dist/adapters/ses/index.js +28 -0
  38. package/dist/adapters/ses/index.js.map +1 -0
  39. package/dist/adapters/ses/parse.d.ts +7 -0
  40. package/dist/adapters/ses/parse.d.ts.map +1 -0
  41. package/dist/adapters/ses/parse.js +209 -0
  42. package/dist/adapters/ses/parse.js.map +1 -0
  43. package/dist/adapters/ses/send.d.ts +10 -0
  44. package/dist/adapters/ses/send.d.ts.map +1 -0
  45. package/dist/adapters/ses/send.js +179 -0
  46. package/dist/adapters/ses/send.js.map +1 -0
  47. package/dist/adapters/ses/sigv4.d.ts +19 -0
  48. package/dist/adapters/ses/sigv4.d.ts.map +1 -0
  49. package/dist/adapters/ses/sigv4.js +50 -0
  50. package/dist/adapters/ses/sigv4.js.map +1 -0
  51. package/dist/adapters/ses/sns.d.ts +23 -0
  52. package/dist/adapters/ses/sns.d.ts.map +1 -0
  53. package/dist/adapters/ses/sns.js +281 -0
  54. package/dist/adapters/ses/sns.js.map +1 -0
  55. package/dist/adapters/types.d.ts +11 -0
  56. package/dist/adapters/types.d.ts.map +1 -0
  57. package/dist/adapters/types.js +2 -0
  58. package/dist/adapters/types.js.map +1 -0
  59. package/dist/client/index.d.ts +214 -0
  60. package/dist/client/index.d.ts.map +1 -0
  61. package/dist/client/index.js +304 -0
  62. package/dist/client/index.js.map +1 -0
  63. package/dist/component/_generated/api.d.ts +62 -0
  64. package/dist/component/_generated/api.d.ts.map +1 -0
  65. package/dist/component/_generated/api.js +31 -0
  66. package/dist/component/_generated/api.js.map +1 -0
  67. package/dist/component/_generated/component.d.ts +345 -0
  68. package/dist/component/_generated/component.d.ts.map +1 -0
  69. package/dist/component/_generated/component.js +11 -0
  70. package/dist/component/_generated/component.js.map +1 -0
  71. package/dist/component/_generated/dataModel.d.ts +46 -0
  72. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  73. package/dist/component/_generated/dataModel.js +11 -0
  74. package/dist/component/_generated/dataModel.js.map +1 -0
  75. package/dist/component/_generated/server.d.ts +133 -0
  76. package/dist/component/_generated/server.d.ts.map +1 -0
  77. package/dist/component/_generated/server.js +80 -0
  78. package/dist/component/_generated/server.js.map +1 -0
  79. package/dist/component/attachments.d.ts +21 -0
  80. package/dist/component/attachments.d.ts.map +1 -0
  81. package/dist/component/attachments.js +66 -0
  82. package/dist/component/attachments.js.map +1 -0
  83. package/dist/component/cleanup.d.ts +15 -0
  84. package/dist/component/cleanup.d.ts.map +1 -0
  85. package/dist/component/cleanup.js +152 -0
  86. package/dist/component/cleanup.js.map +1 -0
  87. package/dist/component/config.d.ts +34 -0
  88. package/dist/component/config.d.ts.map +1 -0
  89. package/dist/component/config.js +33 -0
  90. package/dist/component/config.js.map +1 -0
  91. package/dist/component/convex.config.d.ts +3 -0
  92. package/dist/component/convex.config.d.ts.map +1 -0
  93. package/dist/component/convex.config.js +8 -0
  94. package/dist/component/convex.config.js.map +1 -0
  95. package/dist/component/credentials.d.ts +19 -0
  96. package/dist/component/credentials.d.ts.map +1 -0
  97. package/dist/component/credentials.js +45 -0
  98. package/dist/component/credentials.js.map +1 -0
  99. package/dist/component/deliver.d.ts +58 -0
  100. package/dist/component/deliver.d.ts.map +1 -0
  101. package/dist/component/deliver.js +328 -0
  102. package/dist/component/deliver.js.map +1 -0
  103. package/dist/component/events.d.ts +15 -0
  104. package/dist/component/events.d.ts.map +1 -0
  105. package/dist/component/events.js +141 -0
  106. package/dist/component/events.js.map +1 -0
  107. package/dist/component/inbound.d.ts +354 -0
  108. package/dist/component/inbound.d.ts.map +1 -0
  109. package/dist/component/inbound.js +933 -0
  110. package/dist/component/inbound.js.map +1 -0
  111. package/dist/component/queries.d.ts +76 -0
  112. package/dist/component/queries.d.ts.map +1 -0
  113. package/dist/component/queries.js +175 -0
  114. package/dist/component/queries.js.map +1 -0
  115. package/dist/component/schema.d.ts +473 -0
  116. package/dist/component/schema.d.ts.map +1 -0
  117. package/dist/component/schema.js +185 -0
  118. package/dist/component/schema.js.map +1 -0
  119. package/dist/component/send.d.ts +112 -0
  120. package/dist/component/send.d.ts.map +1 -0
  121. package/dist/component/send.js +393 -0
  122. package/dist/component/send.js.map +1 -0
  123. package/dist/component/status.d.ts +2 -0
  124. package/dist/component/status.d.ts.map +1 -0
  125. package/dist/component/status.js +8 -0
  126. package/dist/component/status.js.map +1 -0
  127. package/dist/component/suppression.d.ts +36 -0
  128. package/dist/component/suppression.d.ts.map +1 -0
  129. package/dist/component/suppression.js +89 -0
  130. package/dist/component/suppression.js.map +1 -0
  131. package/dist/component/unsubscribe.d.ts +58 -0
  132. package/dist/component/unsubscribe.d.ts.map +1 -0
  133. package/dist/component/unsubscribe.js +129 -0
  134. package/dist/component/unsubscribe.js.map +1 -0
  135. package/dist/component/webhooks.d.ts +36 -0
  136. package/dist/component/webhooks.d.ts.map +1 -0
  137. package/dist/component/webhooks.js +71 -0
  138. package/dist/component/webhooks.js.map +1 -0
  139. package/dist/shared/address.d.ts +9 -0
  140. package/dist/shared/address.d.ts.map +1 -0
  141. package/dist/shared/address.js +76 -0
  142. package/dist/shared/address.js.map +1 -0
  143. package/dist/shared/authResults.d.ts +15 -0
  144. package/dist/shared/authResults.d.ts.map +1 -0
  145. package/dist/shared/authResults.js +86 -0
  146. package/dist/shared/authResults.js.map +1 -0
  147. package/dist/shared/htmlToText.d.ts +13 -0
  148. package/dist/shared/htmlToText.d.ts.map +1 -0
  149. package/dist/shared/htmlToText.js +221 -0
  150. package/dist/shared/htmlToText.js.map +1 -0
  151. package/dist/shared/mime.d.ts +4 -0
  152. package/dist/shared/mime.d.ts.map +1 -0
  153. package/dist/shared/mime.js +63 -0
  154. package/dist/shared/mime.js.map +1 -0
  155. package/dist/shared/readCapped.d.ts +7 -0
  156. package/dist/shared/readCapped.d.ts.map +1 -0
  157. package/dist/shared/readCapped.js +38 -0
  158. package/dist/shared/readCapped.js.map +1 -0
  159. package/dist/shared/sanitize.d.ts +10 -0
  160. package/dist/shared/sanitize.d.ts.map +1 -0
  161. package/dist/shared/sanitize.js +68 -0
  162. package/dist/shared/sanitize.js.map +1 -0
  163. package/dist/shared/threading.d.ts +6 -0
  164. package/dist/shared/threading.d.ts.map +1 -0
  165. package/dist/shared/threading.js +23 -0
  166. package/dist/shared/threading.js.map +1 -0
  167. package/dist/shared/types.d.ts +260 -0
  168. package/dist/shared/types.d.ts.map +1 -0
  169. package/dist/shared/types.js +2 -0
  170. package/dist/shared/types.js.map +1 -0
  171. package/dist/shared/unsubToken.d.ts +15 -0
  172. package/dist/shared/unsubToken.d.ts.map +1 -0
  173. package/dist/shared/unsubToken.js +83 -0
  174. package/dist/shared/unsubToken.js.map +1 -0
  175. package/dist/shared/validators.d.ts +760 -0
  176. package/dist/shared/validators.d.ts.map +1 -0
  177. package/dist/shared/validators.js +200 -0
  178. package/dist/shared/validators.js.map +1 -0
  179. package/package.json +88 -4
  180. package/src/adapters/index.ts +8 -0
  181. package/src/adapters/registry.ts +28 -0
  182. package/src/adapters/resend/inbound.ts +245 -0
  183. package/src/adapters/resend/index.ts +29 -0
  184. package/src/adapters/resend/parse.ts +118 -0
  185. package/src/adapters/resend/send.ts +125 -0
  186. package/src/adapters/resend/webhook.ts +77 -0
  187. package/src/adapters/ses/inbound.ts +63 -0
  188. package/src/adapters/ses/index.ts +30 -0
  189. package/src/adapters/ses/parse.ts +236 -0
  190. package/src/adapters/ses/send.ts +206 -0
  191. package/src/adapters/ses/sigv4.ts +56 -0
  192. package/src/adapters/ses/sns.ts +321 -0
  193. package/src/adapters/types.ts +27 -0
  194. package/src/client/index.ts +549 -0
  195. package/src/component/_generated/api.ts +78 -0
  196. package/src/component/_generated/component.ts +475 -0
  197. package/src/component/_generated/dataModel.ts +60 -0
  198. package/src/component/_generated/server.ts +169 -0
  199. package/src/component/attachments.ts +69 -0
  200. package/src/component/cleanup.ts +173 -0
  201. package/src/component/config.ts +52 -0
  202. package/src/component/convex.config.ts +9 -0
  203. package/src/component/credentials.ts +63 -0
  204. package/src/component/deliver.ts +380 -0
  205. package/src/component/events.ts +179 -0
  206. package/src/component/inbound.ts +1107 -0
  207. package/src/component/queries.ts +203 -0
  208. package/src/component/schema.ts +222 -0
  209. package/src/component/send.ts +467 -0
  210. package/src/component/status.ts +8 -0
  211. package/src/component/suppression.ts +114 -0
  212. package/src/component/unsubscribe.ts +154 -0
  213. package/src/component/webhooks.ts +84 -0
  214. package/src/shared/address.ts +75 -0
  215. package/src/shared/authResults.ts +94 -0
  216. package/src/shared/htmlToText.ts +218 -0
  217. package/src/shared/mime.ts +80 -0
  218. package/src/shared/readCapped.ts +39 -0
  219. package/src/shared/sanitize.ts +73 -0
  220. package/src/shared/threading.ts +26 -0
  221. package/src/shared/types.ts +254 -0
  222. package/src/shared/unsubToken.ts +95 -0
  223. package/src/shared/validators.ts +282 -0
  224. package/src/test.ts +25 -0
@@ -0,0 +1,118 @@
1
+ import { domainOf, parseAddressList } from "../../shared/address.js";
2
+ import type {
3
+ AdapterOptions,
4
+ EventType,
5
+ NormalizedEvent,
6
+ ParsedWebhook,
7
+ } from "../../shared/types.js";
8
+
9
+ type Json = Record<string, unknown>;
10
+
11
+ const EVENT_TYPES: Record<string, EventType> = {
12
+ "email.sent": "sent",
13
+ "email.delivered": "delivered",
14
+ "email.delivery_delayed": "delivery_delayed",
15
+ "email.bounced": "bounced",
16
+ "email.complained": "complained",
17
+ "email.failed": "failed",
18
+ };
19
+
20
+ const isObject = (x: unknown): x is Json =>
21
+ typeof x === "object" && x !== null && !Array.isArray(x);
22
+
23
+ const asList = (x: unknown): string[] =>
24
+ typeof x === "string" ? [x] : Array.isArray(x) ? x.filter(isString) : [];
25
+
26
+ function isString(x: unknown): x is string {
27
+ return typeof x === "string";
28
+ }
29
+
30
+ function addresses(...fields: unknown[]): string[] {
31
+ const out: string[] = [];
32
+ for (const f of fields) {
33
+ for (const a of parseAddressList(asList(f))) {
34
+ if (a.address && !out.includes(a.address)) out.push(a.address);
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+
40
+ function bounceType(raw: unknown): NormalizedEvent["bounceType"] {
41
+ const t = typeof raw === "string" ? raw.toLowerCase() : "";
42
+ if (t === "permanent") return "hard";
43
+ if (t === "transient") return "soft";
44
+ return "undetermined";
45
+ }
46
+
47
+ function detailOf(type: EventType, data: Json): string | undefined {
48
+ const section = (k: string) => (isObject(data[k]) ? (data[k] as Json) : {});
49
+ const text =
50
+ type === "bounced"
51
+ ? section("bounce").message
52
+ : type === "failed"
53
+ ? section("failed").reason
54
+ : undefined;
55
+ return typeof text === "string" && text ? text : undefined;
56
+ }
57
+
58
+ export function parseResendWebhook(
59
+ payload: unknown,
60
+ deliveryId: string,
61
+ options: AdapterOptions,
62
+ ): ParsedWebhook {
63
+ const result: ParsedWebhook = { events: [], inbound: [], ignored: 0 };
64
+ if (!isObject(payload) || typeof payload.type !== "string") {
65
+ result.ignored = 1;
66
+ return result;
67
+ }
68
+ const data = isObject(payload.data) ? payload.data : {};
69
+ const emailId = typeof data.email_id === "string" ? data.email_id : "";
70
+
71
+ if (payload.type === "email.received") {
72
+ const recipients = addresses(data.to, data.cc, data.bcc);
73
+ const own = new Set(
74
+ (options.resend?.ownDomains ?? []).map((d) => d.toLowerCase()),
75
+ );
76
+ // Resend delivers every domain on the account to every webhook: only mail
77
+ // for a domain this deployment owns is ours.
78
+ const ours = recipients.some((r) => own.has(domainOf(r)));
79
+ if (!emailId || !ours) {
80
+ result.ignored = 1;
81
+ return result;
82
+ }
83
+ const from = addresses(data.from)[0];
84
+ result.inbound.push({
85
+ providerId: emailId,
86
+ recipients,
87
+ ...(from ? { from } : {}),
88
+ location: { kind: "resend", emailId },
89
+ });
90
+ return result;
91
+ }
92
+
93
+ const type = EVENT_TYPES[payload.type];
94
+ if (!type || !emailId) {
95
+ result.ignored = 1;
96
+ return result;
97
+ }
98
+ const stamp = Date.parse(String(payload.created_at ?? data.created_at ?? ""));
99
+ const event: NormalizedEvent = {
100
+ providerId: emailId,
101
+ providerEventId: deliveryId,
102
+ type,
103
+ at: Number.isNaN(stamp) ? Date.now() : stamp,
104
+ recipients: addresses(data.to),
105
+ };
106
+ if (type === "bounced") {
107
+ event.bounceType = bounceType(
108
+ isObject(data.bounce) ? data.bounce.type : undefined,
109
+ );
110
+ }
111
+ const detail = detailOf(type, data);
112
+ if (detail) event.detail = detail;
113
+ if (typeof data.message_id === "string" && data.message_id) {
114
+ event.rfcMessageId = data.message_id;
115
+ }
116
+ result.events.push(event);
117
+ return result;
118
+ }
@@ -0,0 +1,125 @@
1
+ import type { OutboundPayload, SendResult } from "../../shared/types.js";
2
+
3
+ export const RESEND_API = "https://api.resend.com";
4
+
5
+ /**
6
+ * 10 MiB raw (bodies plus attachments). Resend itself takes 40 MB after base64
7
+ * (about 30 MiB raw), but a send reads every attachment and builds the base64
8
+ * body in memory, in Convex's default runtime: this is held well below that
9
+ * runtime's memory limit. The live probes (Task 14) measure the real ceiling.
10
+ */
11
+ export const RESEND_MAX_BYTES = 10 * 1024 * 1024;
12
+
13
+ /** Provider error text kept on a failed message, at most. */
14
+ const MAX_ERROR = 1000;
15
+
16
+ /** The reserved tag that carries the component message id (idempotency key). */
17
+ export const MESSAGE_TAG = "cx_message";
18
+
19
+ function toBase64(bytes: ArrayBuffer): string {
20
+ const view = new Uint8Array(bytes);
21
+ const parts: string[] = [];
22
+ for (let i = 0; i < view.length; i += 0x8000) {
23
+ parts.push(String.fromCharCode(...view.subarray(i, i + 0x8000)));
24
+ }
25
+ return btoa(parts.join(""));
26
+ }
27
+
28
+ /**
29
+ * `send` validates app tags against Resend's charset, so every app tag goes
30
+ * through; reserved `cx_` entries never go to Resend.
31
+ */
32
+ function resendTags(tags: Record<string, string>) {
33
+ return Object.entries(tags)
34
+ .filter(([name]) => !name.startsWith("cx_"))
35
+ .map(([name, value]) => ({ name, value }));
36
+ }
37
+
38
+ function scrub(text: string, apiKey: string): string {
39
+ return apiKey ? text.split(apiKey).join("[redacted]") : text;
40
+ }
41
+
42
+ export async function sendViaResend(
43
+ creds: { apiKey: string },
44
+ msg: OutboundPayload,
45
+ ): Promise<SendResult> {
46
+ const headers: Record<string, string> = {};
47
+ for (const h of msg.headers) headers[h.name] = h.value;
48
+
49
+ const body: Record<string, unknown> = {
50
+ from: msg.from,
51
+ to: msg.to,
52
+ subject: msg.subject,
53
+ };
54
+ if (msg.cc.length > 0) body.cc = msg.cc;
55
+ if (msg.bcc.length > 0) body.bcc = msg.bcc;
56
+ if (msg.replyTo.length > 0) body.reply_to = msg.replyTo;
57
+ if (msg.html !== undefined) body.html = msg.html;
58
+ if (msg.text !== undefined) body.text = msg.text;
59
+ if (Object.keys(headers).length > 0) body.headers = headers;
60
+ if (msg.attachments.length > 0) {
61
+ body.attachments = msg.attachments.map((a) => ({
62
+ filename: a.filename,
63
+ content: toBase64(a.content),
64
+ content_type: a.contentType,
65
+ ...(a.contentId ? { content_id: a.contentId } : {}),
66
+ }));
67
+ }
68
+ const tags = resendTags(msg.tags);
69
+ if (tags.length > 0) body.tags = tags;
70
+
71
+ const requestHeaders: Record<string, string> = {
72
+ Authorization: `Bearer ${creds.apiKey}`,
73
+ "Content-Type": "application/json",
74
+ };
75
+ const idempotencyKey = msg.tags[MESSAGE_TAG];
76
+ if (idempotencyKey) requestHeaders["Idempotency-Key"] = idempotencyKey;
77
+
78
+ let res: Response;
79
+ try {
80
+ res = await fetch(`${RESEND_API}/emails`, {
81
+ method: "POST",
82
+ headers: requestHeaders,
83
+ body: JSON.stringify(body),
84
+ signal: AbortSignal.timeout(30_000),
85
+ });
86
+ } catch {
87
+ // Fixed text: a network error message must never carry request details.
88
+ return {
89
+ ok: false,
90
+ retryable: true,
91
+ ambiguous: true,
92
+ error: "Resend request failed",
93
+ };
94
+ }
95
+
96
+ let json: { id?: unknown; message?: unknown; name?: unknown } = {};
97
+ try {
98
+ json = (await res.json()) as typeof json;
99
+ } catch {
100
+ // Non-JSON body: fall through to the status handling.
101
+ }
102
+
103
+ if (res.ok) {
104
+ if (typeof json.id === "string" && json.id) {
105
+ return { ok: true, providerId: json.id };
106
+ }
107
+ // The Idempotency-Key makes a retry safe.
108
+ return {
109
+ ok: false,
110
+ retryable: true,
111
+ ambiguous: true,
112
+ error: "Resend accepted the request but returned no id",
113
+ };
114
+ }
115
+
116
+ const message =
117
+ typeof json.message === "string" && json.message
118
+ ? scrub(json.message, creds.apiKey).slice(0, MAX_ERROR)
119
+ : `Resend responded ${res.status}`;
120
+ const retryable =
121
+ res.status === 429 ||
122
+ res.status >= 500 ||
123
+ (res.status === 409 && json.name === "concurrent_idempotent_requests");
124
+ return { ok: false, retryable, error: message };
125
+ }
@@ -0,0 +1,77 @@
1
+ import type { VerifyResult, WebhookRequest } from "../../shared/types.js";
2
+
3
+ const TOLERANCE_SECONDS = 5 * 60;
4
+
5
+ function fromBase64(b64: string): Uint8Array<ArrayBuffer> {
6
+ const bin = atob(b64);
7
+ const out = new Uint8Array(bin.length);
8
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
9
+ return out;
10
+ }
11
+
12
+ const reject = (status: 401 | 400, reason: string): VerifyResult => ({
13
+ ok: false,
14
+ status,
15
+ reason,
16
+ });
17
+
18
+ /** Svix signature scheme, on WebCrypto. */
19
+ export async function verifyResendWebhook(
20
+ creds: { webhookSecret: string },
21
+ req: WebhookRequest,
22
+ nowMs: number = Date.now(),
23
+ ): Promise<VerifyResult> {
24
+ const header = (name: string) =>
25
+ Object.entries(req.headers).find(([k]) => k.toLowerCase() === name)?.[1];
26
+ const id = header("svix-id");
27
+ const timestamp = header("svix-timestamp");
28
+ const signatures = header("svix-signature");
29
+ if (!id || !timestamp || !signatures) {
30
+ return reject(400, "missing svix headers");
31
+ }
32
+ const ts = Number(timestamp);
33
+ if (!Number.isFinite(ts)) return reject(401, "invalid timestamp");
34
+ if (Math.abs(nowMs / 1000 - ts) > TOLERANCE_SECONDS) {
35
+ return reject(401, "timestamp outside tolerance");
36
+ }
37
+
38
+ let key: CryptoKey;
39
+ try {
40
+ const raw = creds.webhookSecret.startsWith("whsec_")
41
+ ? creds.webhookSecret.slice(6)
42
+ : creds.webhookSecret;
43
+ key = await crypto.subtle.importKey(
44
+ "raw",
45
+ fromBase64(raw),
46
+ { name: "HMAC", hash: "SHA-256" },
47
+ false,
48
+ ["verify"],
49
+ );
50
+ } catch {
51
+ return reject(401, "invalid signature");
52
+ }
53
+
54
+ const signed = new TextEncoder().encode(`${id}.${timestamp}.${req.body}`);
55
+ let matched = false;
56
+ for (const candidate of signatures.split(" ")) {
57
+ const [version, sig] = candidate.split(",");
58
+ if (version !== "v1" || !sig) continue;
59
+ try {
60
+ // `verify` compares in constant time.
61
+ if (await crypto.subtle.verify("HMAC", key, fromBase64(sig), signed)) {
62
+ matched = true;
63
+ }
64
+ } catch {
65
+ // Malformed base64: not a match.
66
+ }
67
+ }
68
+ if (!matched) return reject(401, "invalid signature");
69
+
70
+ let payload: unknown;
71
+ try {
72
+ payload = JSON.parse(req.body);
73
+ } catch {
74
+ return reject(400, "body is not JSON");
75
+ }
76
+ return { ok: true, payload, deliveryId: id };
77
+ }
@@ -0,0 +1,63 @@
1
+ import { parseMime } from "../../shared/mime.js";
2
+ import { readCapped } from "../../shared/readCapped.js";
3
+ import type {
4
+ InboundNotification,
5
+ ParsedInbound,
6
+ SesCredentials,
7
+ } from "../../shared/types.js";
8
+ import { SES_MAX_BYTES } from "./send.js";
9
+ import { assertBucket, assertRegion, awsClient, awsDomain } from "./sigv4.js";
10
+
11
+ const INBOUND_TIMEOUT_MS = 60_000;
12
+
13
+ /**
14
+ * Encodes per path segment. An empty key and `.`/`..` segments are refused:
15
+ * the URL parser would normalise them out of the bucket path.
16
+ */
17
+ function encodeKey(key: string): string {
18
+ const segments = key.split("/");
19
+ if (!key || segments.some((s) => s === "." || s === "..")) {
20
+ throw new Error("invalid S3 object key");
21
+ }
22
+ return segments.map(encodeURIComponent).join("/");
23
+ }
24
+
25
+ export async function fetchSesInbound(
26
+ creds: SesCredentials,
27
+ n: InboundNotification,
28
+ ): Promise<ParsedInbound> {
29
+ if (n.location.kind !== "s3") {
30
+ throw new Error("not an SES inbound notification");
31
+ }
32
+ const region = assertRegion(creds.region);
33
+ const bucket = assertBucket(n.location.bucket);
34
+ if (!creds.inboundBuckets?.includes(bucket)) {
35
+ throw new Error("S3 bucket is not an allowed inbound bucket");
36
+ }
37
+ const url = `https://s3.${region}.${awsDomain(region)}/${bucket}/${encodeKey(n.location.key)}`;
38
+
39
+ let res: Response;
40
+ try {
41
+ // No redirects: a redirect target would not have been validated.
42
+ res = await awsClient(creds, "s3").fetch(url, {
43
+ method: "GET",
44
+ redirect: "manual",
45
+ signal: AbortSignal.timeout(INBOUND_TIMEOUT_MS),
46
+ });
47
+ } catch {
48
+ throw new Error("SES inbound fetch failed");
49
+ }
50
+ if (
51
+ res.type === "opaqueredirect" ||
52
+ (res.status >= 300 && res.status < 400)
53
+ ) {
54
+ throw new Error("SES inbound fetch was redirected");
55
+ }
56
+ if (!res.ok) {
57
+ await res.body?.cancel();
58
+ throw new Error(`SES inbound fetch failed (${res.status})`);
59
+ }
60
+ const bytes = await readCapped(res, SES_MAX_BYTES);
61
+ if (!bytes) throw new Error("SES inbound message exceeds the size limit");
62
+ return parseMime(bytes);
63
+ }
@@ -0,0 +1,30 @@
1
+ import type { SesCredentials } from "../../shared/types.js";
2
+ import type { ProviderAdapter } from "../types.js";
3
+ import { fetchSesInbound } from "./inbound.js";
4
+ import { parseSesWebhook } from "./parse.js";
5
+ import { SES_MAX_BYTES, sendViaSes } from "./send.js";
6
+ import { verifySnsWebhook } from "./sns.js";
7
+
8
+ export const sesAdapter: ProviderAdapter<SesCredentials> = {
9
+ name: "ses",
10
+ capabilities: {
11
+ tenants: true,
12
+ listManagement: true,
13
+ inbound: true,
14
+ maxMessageBytes: SES_MAX_BYTES,
15
+ maxAttachmentBytes: SES_MAX_BYTES,
16
+ events: [
17
+ "sent",
18
+ "delivered",
19
+ "delivery_delayed",
20
+ "bounced",
21
+ "complained",
22
+ "rejected",
23
+ "failed",
24
+ ],
25
+ },
26
+ send: sendViaSes,
27
+ verifyWebhook: (creds, req) => verifySnsWebhook(creds.trustedTopicArns, req),
28
+ parseWebhook: parseSesWebhook,
29
+ fetchInbound: fetchSesInbound,
30
+ };
@@ -0,0 +1,236 @@
1
+ import type { Verdict } from "../../shared/authResults.js";
2
+ import type {
3
+ AdapterOptions,
4
+ EventType,
5
+ InboundNotification,
6
+ NormalizedEvent,
7
+ ParsedWebhook,
8
+ } from "../../shared/types.js";
9
+
10
+ type Json = Record<string, unknown>;
11
+
12
+ const EVENT_TYPES: Record<string, EventType> = {
13
+ Send: "sent",
14
+ Delivery: "delivered",
15
+ DeliveryDelay: "delivery_delayed",
16
+ Bounce: "bounced",
17
+ Complaint: "complained",
18
+ Reject: "rejected",
19
+ "Rendering Failure": "failed",
20
+ };
21
+
22
+ const isObject = (x: unknown): x is Json =>
23
+ typeof x === "object" && x !== null && !Array.isArray(x);
24
+ const section = (parent: Json, key: string): Json => {
25
+ const v = parent[key];
26
+ return isObject(v) ? v : {};
27
+ };
28
+ const str = (x: unknown): string => (typeof x === "string" ? x : "");
29
+ const strings = (x: unknown): string[] =>
30
+ Array.isArray(x) ? x.filter((v): v is string => typeof v === "string") : [];
31
+
32
+ /** `emailAddress` of each `{ emailAddress }` entry. */
33
+ function addressesOf(x: unknown): string[] {
34
+ if (!Array.isArray(x)) return [];
35
+ return x.flatMap((r) =>
36
+ isObject(r) && typeof r.emailAddress === "string" ? [r.emailAddress] : [],
37
+ );
38
+ }
39
+
40
+ function bounceType(raw: unknown): NormalizedEvent["bounceType"] {
41
+ const t = str(raw).toLowerCase();
42
+ if (t === "permanent") return "hard";
43
+ if (t === "transient") return "soft";
44
+ return "undetermined";
45
+ }
46
+
47
+ const VERDICTS: Record<string, Verdict> = {
48
+ PASS: "pass",
49
+ FAIL: "fail",
50
+ GRAY: "neutral",
51
+ PROCESSING_FAILED: "temperror",
52
+ };
53
+
54
+ function verdictOf(receipt: Json, key: string): Verdict | undefined {
55
+ return VERDICTS[str(section(receipt, key).status)];
56
+ }
57
+
58
+ function bracketed(id: string): string {
59
+ const t = id.trim();
60
+ return t.startsWith("<") ? t : `<${t}>`;
61
+ }
62
+
63
+ /** First parseable candidate; the SNS envelope Timestamp, then now, last. */
64
+ function stamp(fallback: string, ...candidates: unknown[]): number {
65
+ for (const c of [...candidates, fallback]) {
66
+ const t = Date.parse(str(c));
67
+ if (!Number.isNaN(t)) return t;
68
+ }
69
+ return Date.now();
70
+ }
71
+
72
+ /** What each event type contributes: recipients, a timestamp and a detail. */
73
+ function eventParts(
74
+ eventType: string,
75
+ payload: Json,
76
+ mail: Json,
77
+ fallback: string,
78
+ ): { recipients: string[]; at: number; detail?: string } {
79
+ const destination = strings(mail.destination);
80
+ switch (eventType) {
81
+ case "Delivery": {
82
+ const d = section(payload, "delivery");
83
+ const recipients = strings(d.recipients);
84
+ return {
85
+ recipients: recipients.length > 0 ? recipients : destination,
86
+ at: stamp(fallback, d.timestamp, mail.timestamp),
87
+ detail: str(d.smtpResponse) || undefined,
88
+ };
89
+ }
90
+ case "DeliveryDelay": {
91
+ const d = section(payload, "deliveryDelay");
92
+ const delayed = addressesOf(d.delayedRecipients);
93
+ return {
94
+ recipients: delayed.length > 0 ? delayed : destination,
95
+ at: stamp(fallback, d.timestamp, mail.timestamp),
96
+ detail: str(d.delayType) || undefined,
97
+ };
98
+ }
99
+ case "Bounce": {
100
+ const b = section(payload, "bounce");
101
+ const bounced = addressesOf(b.bouncedRecipients);
102
+ const first = Array.isArray(b.bouncedRecipients)
103
+ ? b.bouncedRecipients[0]
104
+ : undefined;
105
+ const diagnostic = isObject(first) ? str(first.diagnosticCode) : "";
106
+ const kind = [str(b.bounceType), str(b.bounceSubType)]
107
+ .filter(Boolean)
108
+ .join("/");
109
+ return {
110
+ recipients: bounced.length > 0 ? bounced : destination,
111
+ at: stamp(fallback, b.timestamp, mail.timestamp),
112
+ detail: [kind, diagnostic].filter(Boolean).join(": ") || undefined,
113
+ };
114
+ }
115
+ case "Complaint": {
116
+ const c = section(payload, "complaint");
117
+ const complained = addressesOf(c.complainedRecipients);
118
+ return {
119
+ recipients: complained.length > 0 ? complained : destination,
120
+ at: stamp(fallback, c.timestamp, mail.timestamp),
121
+ detail: str(c.complaintFeedbackType) || undefined,
122
+ };
123
+ }
124
+ case "Reject":
125
+ return {
126
+ recipients: destination,
127
+ at: stamp(fallback, mail.timestamp),
128
+ detail: str(section(payload, "reject").reason) || undefined,
129
+ };
130
+ case "Rendering Failure":
131
+ return {
132
+ recipients: destination,
133
+ at: stamp(fallback, mail.timestamp),
134
+ detail:
135
+ str(section(payload, "failure").errorMessage) ||
136
+ str(section(payload, "renderingFailure").errorMessage) ||
137
+ undefined,
138
+ };
139
+ default:
140
+ return { recipients: destination, at: stamp(fallback, mail.timestamp) };
141
+ }
142
+ }
143
+
144
+ function parseReceipt(payload: Json): InboundNotification | null {
145
+ const mail = section(payload, "mail");
146
+ const receipt = section(payload, "receipt");
147
+ const action = section(receipt, "action");
148
+ const bucket = str(action.bucketName);
149
+ const key = str(action.objectKey);
150
+ const providerId = str(mail.messageId);
151
+ if (!providerId || !bucket || !key) return null;
152
+ const recipients = strings(receipt.recipients);
153
+ const from =
154
+ str(mail.source) || strings(section(mail, "commonHeaders").from)[0];
155
+ const verdicts: InboundNotification["verdicts"] = {};
156
+ for (const [name, field] of [
157
+ ["spf", "spfVerdict"],
158
+ ["dkim", "dkimVerdict"],
159
+ ["dmarc", "dmarcVerdict"],
160
+ ] as const) {
161
+ const v = verdictOf(receipt, field);
162
+ if (v) verdicts[name] = v;
163
+ }
164
+ return {
165
+ providerId,
166
+ recipients: recipients.length > 0 ? recipients : strings(mail.destination),
167
+ ...(from ? { from } : {}),
168
+ location: { kind: "s3", bucket, key },
169
+ ...(Object.keys(verdicts).length > 0 ? { verdicts } : {}),
170
+ };
171
+ }
172
+
173
+ /**
174
+ * Takes the verified SNS envelope (its `Message` is the SES JSON); the bare
175
+ * SES JSON is accepted too.
176
+ */
177
+ export function parseSesWebhook(
178
+ payload: unknown,
179
+ deliveryId: string,
180
+ _options: AdapterOptions,
181
+ ): ParsedWebhook {
182
+ const result: ParsedWebhook = { events: [], inbound: [], ignored: 0 };
183
+ let body = payload;
184
+ let envelopeTimestamp = "";
185
+ if (isObject(body) && body.Type === "Notification" && "Message" in body) {
186
+ envelopeTimestamp = str(body.Timestamp);
187
+ try {
188
+ body = JSON.parse(str(body.Message));
189
+ } catch {
190
+ body = null;
191
+ }
192
+ }
193
+ if (!isObject(body)) {
194
+ result.ignored = 1;
195
+ return result;
196
+ }
197
+
198
+ if (body.notificationType === "Received") {
199
+ const inbound = parseReceipt(body);
200
+ if (inbound) result.inbound.push(inbound);
201
+ else result.ignored = 1;
202
+ return result;
203
+ }
204
+
205
+ const eventType = str(body.eventType);
206
+ const type = EVENT_TYPES[eventType];
207
+ const mail = section(body, "mail");
208
+ const providerId = str(mail.messageId);
209
+ if (!type || !providerId) {
210
+ result.ignored = 1;
211
+ return result;
212
+ }
213
+ const parts = eventParts(eventType, body, mail, envelopeTimestamp);
214
+ const event: NormalizedEvent = {
215
+ providerId,
216
+ providerEventId: deliveryId,
217
+ type,
218
+ at: parts.at,
219
+ recipients: parts.recipients,
220
+ };
221
+ if (type === "bounced") {
222
+ event.bounceType = bounceType(section(body, "bounce").bounceType);
223
+ }
224
+ if (parts.detail) event.detail = parts.detail.slice(0, 500);
225
+ if (type === "sent") {
226
+ const rfc = str(section(mail, "commonHeaders").messageId).trim();
227
+ // Real SES puts its bare internal id here (no "@"), which no reply will
228
+ // ever cite; only a full Message-ID is authoritative. Otherwise keep the
229
+ // `<id@region.amazonses.com>` stored at send time.
230
+ if (rfc.replace(/^<|>$/g, "").includes("@")) {
231
+ event.rfcMessageId = bracketed(rfc);
232
+ }
233
+ }
234
+ result.events.push(event);
235
+ return result;
236
+ }