@sayedhfatimi/convex-email 0.0.0-stage → 0.1.1

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 +709 -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,154 @@
1
+ import { v } from "convex/values";
2
+ import { normalizeAddress } from "../shared/address.js";
3
+ import { peekUnsubTenant, verifyUnsubToken } from "../shared/unsubToken.js";
4
+ import { vRuntimeConfig } from "../shared/validators.js";
5
+ import { internal } from "./_generated/api.js";
6
+ import {
7
+ action,
8
+ internalMutation,
9
+ type MutationCtx,
10
+ mutation,
11
+ query,
12
+ } from "./_generated/server.js";
13
+ import { fetchCredentials } from "./credentials.js";
14
+
15
+ const FAILED = { ok: false } as const;
16
+
17
+ type Result = { ok: boolean; address?: string; category?: string };
18
+
19
+ async function findUnsubscribe(
20
+ ctx: Pick<MutationCtx, "db">,
21
+ tenant: string | undefined,
22
+ address: string,
23
+ category: string,
24
+ ) {
25
+ return await ctx.db
26
+ .query("unsubscribes")
27
+ .withIndex("by_tenant_address_category", (q) =>
28
+ q.eq("tenant", tenant).eq("address", address).eq("category", category),
29
+ )
30
+ .collect();
31
+ }
32
+
33
+ async function setUnsubscribed(
34
+ ctx: MutationCtx,
35
+ tenant: string | undefined,
36
+ rawAddress: string,
37
+ category: string,
38
+ unsubscribed: boolean,
39
+ ): Promise<void> {
40
+ const address = normalizeAddress(rawAddress);
41
+ const rows = await findUnsubscribe(ctx, tenant, address, category);
42
+ if (!unsubscribed) {
43
+ for (const row of rows) await ctx.db.delete(row._id);
44
+ return;
45
+ }
46
+ if (rows.length > 0) return;
47
+ await ctx.db.insert("unsubscribes", {
48
+ tenant,
49
+ address,
50
+ category,
51
+ createdAt: Date.now(),
52
+ });
53
+ }
54
+
55
+ export const record = internalMutation({
56
+ args: {
57
+ tenant: v.optional(v.string()),
58
+ address: v.string(),
59
+ category: v.string(),
60
+ },
61
+ handler: async (ctx, { tenant, address, category }) => {
62
+ await setUnsubscribed(ctx, tenant, address, category, true);
63
+ return null;
64
+ },
65
+ });
66
+
67
+ /**
68
+ * One-click unsubscribe. The token's tenant claim only picks the secret; the
69
+ * result and anything stored come from the verified payload. A failure is
70
+ * always the bare `{ ok: false }`.
71
+ */
72
+ export const handle = action({
73
+ args: {
74
+ config: vRuntimeConfig,
75
+ method: v.union(v.literal("GET"), v.literal("POST")),
76
+ token: v.string(),
77
+ },
78
+ returns: v.object({
79
+ ok: v.boolean(),
80
+ address: v.optional(v.string()),
81
+ category: v.optional(v.string()),
82
+ }),
83
+ handler: async (ctx, { config, method, token }): Promise<Result> => {
84
+ await ctx.runMutation(internal.config.upsert, { config });
85
+ const claimed = peekUnsubTenant(token);
86
+ if (claimed === null) return FAILED;
87
+ let secret: string;
88
+ try {
89
+ // The same `provider: null` call that signed the link.
90
+ const creds = await fetchCredentials(ctx, config, {
91
+ provider: null,
92
+ tenant: claimed,
93
+ purpose: "unsubscribe",
94
+ });
95
+ const s = (creds as { unsubscribeSecret?: unknown } | null)
96
+ ?.unsubscribeSecret;
97
+ if (typeof s !== "string" || s === "") return FAILED;
98
+ secret = s;
99
+ } catch {
100
+ return FAILED;
101
+ }
102
+ const payload = await verifyUnsubToken(secret, token);
103
+ if (!payload) return FAILED;
104
+ const address = normalizeAddress(payload.address);
105
+ if (method === "POST") {
106
+ await ctx.runMutation(internal.unsubscribe.record, {
107
+ tenant: payload.tenant,
108
+ address,
109
+ category: payload.category,
110
+ });
111
+ }
112
+ return { ok: true, address, category: payload.category };
113
+ },
114
+ });
115
+
116
+ export const list = query({
117
+ args: { tenant: v.optional(v.string()), address: v.string() },
118
+ returns: v.array(
119
+ v.object({
120
+ tenant: v.optional(v.string()),
121
+ address: v.string(),
122
+ category: v.string(),
123
+ createdAt: v.number(),
124
+ }),
125
+ ),
126
+ handler: async (ctx, { tenant, address }) => {
127
+ const rows = await ctx.db
128
+ .query("unsubscribes")
129
+ .withIndex("by_tenant_address_category", (q) =>
130
+ q.eq("tenant", tenant).eq("address", normalizeAddress(address)),
131
+ )
132
+ .collect();
133
+ return rows.map((r) => ({
134
+ tenant: r.tenant,
135
+ address: r.address,
136
+ category: r.category,
137
+ createdAt: r.createdAt,
138
+ }));
139
+ },
140
+ });
141
+
142
+ export const set = mutation({
143
+ args: {
144
+ tenant: v.optional(v.string()),
145
+ address: v.string(),
146
+ category: v.string(),
147
+ unsubscribed: v.boolean(),
148
+ },
149
+ returns: v.null(),
150
+ handler: async (ctx, { tenant, address, category, unsubscribed }) => {
151
+ await setUnsubscribed(ctx, tenant, address, category, unsubscribed);
152
+ return null;
153
+ },
154
+ });
@@ -0,0 +1,84 @@
1
+ import { v } from "convex/values";
2
+ import { getAdapter } from "../adapters/index.js";
3
+ import type { ParsedWebhook, VerifyResult } from "../shared/types.js";
4
+ import {
5
+ vProviderName,
6
+ vRuntimeConfig,
7
+ vWebhookRequest,
8
+ } from "../shared/validators.js";
9
+ import { internal } from "./_generated/api.js";
10
+ import { action } from "./_generated/server.js";
11
+ import { fetchCredentials } from "./credentials.js";
12
+
13
+ type Reply = { status: number; body: string };
14
+
15
+ /** Fixed bodies: nothing from a credential, an adapter or the payload. */
16
+ const VERIFICATION_ERROR: Reply = { status: 500, body: "verification error" };
17
+ const PARSE_ERROR: Reply = { status: 500, body: "webhook parse error" };
18
+
19
+ export const ingest = action({
20
+ args: {
21
+ config: vRuntimeConfig,
22
+ provider: vProviderName,
23
+ request: vWebhookRequest,
24
+ },
25
+ returns: v.object({ status: v.number(), body: v.string() }),
26
+ handler: async (ctx, { config, provider, request }): Promise<Reply> => {
27
+ await ctx.runMutation(internal.config.upsert, { config });
28
+
29
+ // The route's tenant, else the app's default (config, not payload).
30
+ const tenant = request.tenant ?? config.defaultTenant;
31
+
32
+ let verified: VerifyResult;
33
+ let adapter: ReturnType<typeof getAdapter>;
34
+ try {
35
+ adapter = getAdapter(provider);
36
+ // The tenant is the route's, never the payload's: the payload is not
37
+ // trusted until it has been verified with this tenant's secret.
38
+ const creds = await fetchCredentials(ctx, config, {
39
+ provider,
40
+ tenant,
41
+ purpose: "verifyWebhook",
42
+ });
43
+ if ((creds as { provider?: unknown } | null)?.provider !== provider) {
44
+ throw new Error("credentials provider mismatch");
45
+ }
46
+ verified = await adapter.verifyWebhook(creds, request);
47
+ } catch {
48
+ return VERIFICATION_ERROR;
49
+ }
50
+ if (!verified.ok) {
51
+ // An adapter's status is not trusted beyond the two it may return.
52
+ const status = verified.status === 401 ? 401 : 400;
53
+ return { status, body: "rejected" };
54
+ }
55
+ if ("handled" in verified) return { status: verified.status, body: "ok" };
56
+
57
+ let parsed: ParsedWebhook;
58
+ try {
59
+ parsed = adapter.parseWebhook(
60
+ verified.payload,
61
+ verified.deliveryId,
62
+ config.adapterOptions,
63
+ );
64
+ } catch {
65
+ return PARSE_ERROR;
66
+ }
67
+
68
+ if (parsed.events.length > 0) {
69
+ await ctx.runMutation(internal.events.apply, {
70
+ provider,
71
+ tenant,
72
+ events: parsed.events,
73
+ });
74
+ }
75
+ for (const notification of parsed.inbound) {
76
+ await ctx.runMutation(internal.inbound.accept, {
77
+ provider,
78
+ tenant,
79
+ notification,
80
+ });
81
+ }
82
+ return { status: 200, body: "ok" };
83
+ },
84
+ });
@@ -0,0 +1,75 @@
1
+ export type ParsedAddress = { address: string; name?: string };
2
+
3
+ function stripQuotes(s: string): string {
4
+ const t = s.trim();
5
+ if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {
6
+ return t.slice(1, -1).replace(/\\(.)/g, "$1").trim();
7
+ }
8
+ return t;
9
+ }
10
+
11
+ /** Split on commas that are outside double quotes and angle brackets. */
12
+ function splitList(raw: string): string[] {
13
+ const parts: string[] = [];
14
+ let current = "";
15
+ let inQuotes = false;
16
+ let depth = 0;
17
+ for (let i = 0; i < raw.length; i++) {
18
+ const ch = raw[i] as string;
19
+ if (ch === "\\" && inQuotes && i + 1 < raw.length) {
20
+ current += ch + raw[++i];
21
+ continue;
22
+ }
23
+ if (ch === '"') inQuotes = !inQuotes;
24
+ else if (!inQuotes && ch === "<") depth++;
25
+ else if (!inQuotes && ch === ">" && depth > 0) depth--;
26
+ if (ch === "," && !inQuotes && depth === 0) {
27
+ parts.push(current);
28
+ current = "";
29
+ } else {
30
+ current += ch;
31
+ }
32
+ }
33
+ parts.push(current);
34
+ return parts;
35
+ }
36
+
37
+ function parseOne(raw: string): ParsedAddress | null {
38
+ const text = raw.trim();
39
+ if (!text) return null;
40
+ const open = text.lastIndexOf("<");
41
+ const close = text.lastIndexOf(">");
42
+ if (open !== -1 && close > open) {
43
+ const address = text
44
+ .slice(open + 1, close)
45
+ .trim()
46
+ .toLowerCase();
47
+ if (!address) return null;
48
+ const name = stripQuotes(text.slice(0, open));
49
+ return name ? { address, name } : { address };
50
+ }
51
+ return { address: text.toLowerCase() };
52
+ }
53
+
54
+ /** Bare, lower-cased address: display name and angle brackets removed. */
55
+ export function normalizeAddress(raw: string): string {
56
+ return parseOne(raw)?.address ?? "";
57
+ }
58
+
59
+ export function parseAddressList(raw: string | string[]): ParsedAddress[] {
60
+ const items = Array.isArray(raw) ? raw : [raw];
61
+ const out: ParsedAddress[] = [];
62
+ for (const item of items) {
63
+ for (const part of splitList(item)) {
64
+ const parsed = parseOne(part);
65
+ if (parsed) out.push(parsed);
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ export function domainOf(address: string): string {
72
+ const bare = normalizeAddress(address);
73
+ const at = bare.lastIndexOf("@");
74
+ return at === -1 ? "" : bare.slice(at + 1);
75
+ }
@@ -0,0 +1,94 @@
1
+ export type Verdict =
2
+ | "pass"
3
+ | "fail"
4
+ | "softfail"
5
+ | "neutral"
6
+ | "none"
7
+ | "temperror"
8
+ | "permerror";
9
+
10
+ const VERDICTS: ReadonlySet<string> = new Set([
11
+ "pass",
12
+ "fail",
13
+ "softfail",
14
+ "neutral",
15
+ "none",
16
+ "temperror",
17
+ "permerror",
18
+ ]);
19
+
20
+ /** A verdict word in the shared vocabulary, folded to lower case; anything else is undefined. */
21
+ export function toVerdict(value: unknown): Verdict | undefined {
22
+ if (typeof value !== "string") return undefined;
23
+ const v = value.trim().toLowerCase();
24
+ return VERDICTS.has(v) ? (v as Verdict) : undefined;
25
+ }
26
+
27
+ const RESULT = /^(spf|dkim|dmarc)(?:\/\d+)?\s*=\s*([A-Za-z]+)(?![^\s])/i;
28
+
29
+ /**
30
+ * Parse an Authentication-Results header (RFC 8601). The header is tokenised
31
+ * once so quoted strings and comments are opaque: only the first token of each
32
+ * `;`-separated clause after the authserv-id can be a method result. The first
33
+ * clause per method wins; unknown result words leave the method unset.
34
+ */
35
+ export function parseAuthenticationResults(header: string | undefined): {
36
+ spf?: Verdict;
37
+ dkim?: Verdict;
38
+ dmarc?: Verdict;
39
+ } {
40
+ const out: { spf?: Verdict; dkim?: Verdict; dmarc?: Verdict } = {};
41
+ if (!header) return out;
42
+ for (const clause of splitClauses(header).slice(1)) {
43
+ const match = RESULT.exec(clause.trim());
44
+ if (!match) continue;
45
+ const method = (match[1] as string).toLowerCase() as
46
+ | "spf"
47
+ | "dkim"
48
+ | "dmarc";
49
+ const verdict = toVerdict(match[2]);
50
+ if (verdict && out[method] === undefined) out[method] = verdict;
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /**
56
+ * Split on `;` outside quotes and comments. Comments become a space; a quoted
57
+ * string becomes a single opaque placeholder. An unterminated quote or comment
58
+ * ends the scan there: nothing after the opener is trusted (fail closed).
59
+ */
60
+ function splitClauses(s: string): string[] {
61
+ const clauses: string[] = [];
62
+ let cur = "";
63
+ let depth = 0;
64
+ let inQuote = false;
65
+ for (let i = 0; i < s.length; i++) {
66
+ const c = s[i] as string;
67
+ if (c === "\\" && (inQuote || depth > 0)) {
68
+ i++;
69
+ continue;
70
+ }
71
+ if (inQuote) {
72
+ if (c === '"') inQuote = false;
73
+ continue;
74
+ }
75
+ if (depth > 0) {
76
+ if (c === "(") depth++;
77
+ else if (c === ")") {
78
+ depth--;
79
+ if (depth === 0) cur += " ";
80
+ }
81
+ continue;
82
+ }
83
+ if (c === '"') {
84
+ inQuote = true;
85
+ cur += "\u0000";
86
+ } else if (c === "(") depth = 1;
87
+ else if (c === ";") {
88
+ clauses.push(cur);
89
+ cur = "";
90
+ } else cur += c;
91
+ }
92
+ clauses.push(cur);
93
+ return clauses;
94
+ }
@@ -0,0 +1,218 @@
1
+ import { Parser } from "htmlparser2";
2
+
3
+ /** Content of these never reaches the text. */
4
+ const SKIPPED = new Set([
5
+ "style",
6
+ "script",
7
+ "head",
8
+ "title",
9
+ "template",
10
+ "noscript",
11
+ "svg",
12
+ "math",
13
+ "object",
14
+ "iframe",
15
+ "img",
16
+ ]);
17
+ /** A paragraph break (blank line) on both sides. */
18
+ const PARAGRAPH = new Set([
19
+ "p",
20
+ "h1",
21
+ "h2",
22
+ "h3",
23
+ "h4",
24
+ "h5",
25
+ "h6",
26
+ "blockquote",
27
+ "table",
28
+ "ul",
29
+ "ol",
30
+ ]);
31
+ /** A line break on both sides. */
32
+ const LINE = new Set(["div", "tr", "li", "center", "hr", "pre"]);
33
+ const CELLS = new Set(["td", "th"]);
34
+
35
+ const ZERO_WIDTH = /\u200B|\u200C|\u200D|\u2060|\uFEFF|\u034F|\u00AD/g;
36
+ const HORIZONTAL = /[ \t\u00A0\u2000-\u200A\u202F\u205F\u3000]+/g;
37
+
38
+ /**
39
+ * True when an inline style sets display:none or visibility:hidden. Split on
40
+ * ';' and the first ':' with indexOf, so no regex can backtrack on it.
41
+ */
42
+ function isHiddenStyle(style: string): boolean {
43
+ let from = 0;
44
+ while (from <= style.length) {
45
+ let end = style.indexOf(";", from);
46
+ if (end === -1) end = style.length;
47
+ // Only the first ':' inside this declaration counts, so scan the
48
+ // segment itself, never beyond it.
49
+ let colon = from;
50
+ while (colon < end && style.charCodeAt(colon) !== 58) colon++;
51
+ if (colon < end) {
52
+ const prop = style.slice(from, colon).trim().toLowerCase();
53
+ if (prop === "display" || prop === "visibility") {
54
+ const value = style
55
+ .slice(colon + 1, end)
56
+ .trim()
57
+ .toLowerCase();
58
+ if (prop === "display" && value.startsWith("none")) return true;
59
+ if (prop === "visibility" && value.startsWith("hidden")) return true;
60
+ }
61
+ }
62
+ from = end + 1;
63
+ }
64
+ return false;
65
+ }
66
+ const LINK_HREF = /^(https?:\/\/|mailto:)/i;
67
+
68
+ /** One line of visible text, for comparing a link's text with its href. */
69
+ const flat = (s: string) =>
70
+ s.replace(ZERO_WIDTH, "").replace(/\s+/g, " ").trim();
71
+
72
+ /** `https://example.com/` and `example.com` are the same link text. */
73
+ const bare = (s: string) => {
74
+ const t = s.toLowerCase().replace(/^(https?:\/\/|mailto:)/, "");
75
+ let end = t.length;
76
+ while (end > 0 && t.charCodeAt(end - 1) === 47) end--;
77
+ return t.slice(0, end);
78
+ };
79
+
80
+ /** Beyond this much text a link's text is never compared (it is not the href). */
81
+ const MAX_LINK_TEXT = 8192;
82
+
83
+ /**
84
+ * Plain text from HTML, for mail that has no text part. Meant for the RAW
85
+ * HTML: the sanitiser keeps the text of tags it drops (title, noscript) and
86
+ * strips style attributes, so hidden content could only be skipped before it.
87
+ * The output is plain text and never rendered, so raw input is safe.
88
+ * Streams through htmlparser2, keeps no tree and does not recurse, so deep
89
+ * nesting is safe. Pure JS: runs in Convex's default runtime.
90
+ *
91
+ * Images are dropped whole, alt text included: in mail they are logos,
92
+ * spacers and tracking pixels far more often than content.
93
+ */
94
+ export function htmlToText(html: string): string {
95
+ const out: string[] = [];
96
+ /** Newlines at the very end of `out`. */
97
+ let trailing = 0;
98
+ /** Line breaks owed before the next text (1 = new line, 2 = blank line). */
99
+ let owed = 0;
100
+ /** Elements opened inside a skipped one (so the skip ends at its own close). */
101
+ let skip = 0;
102
+ let pre = 0;
103
+ /** The one open link (an anchor inside an anchor is plain text). */
104
+ let link: { href: string; text: string; over: boolean } | undefined;
105
+ // Parallel to the open elements, to pair each close with its open.
106
+ const open: ("link" | "pre" | "skipped" | "other")[] = [];
107
+
108
+ const write = (s: string) => {
109
+ if (s === "") return;
110
+ // Breaks owed never stack on newlines already there, or at the start.
111
+ if (owed > 0 && out.length > 0) {
112
+ const need = owed - trailing;
113
+ if (need > 0) out.push("\n".repeat(need));
114
+ }
115
+ owed = 0;
116
+ out.push(s);
117
+ if (link && !link.over) {
118
+ link.text += s;
119
+ if (link.text.length > MAX_LINK_TEXT) link.over = true;
120
+ }
121
+ let tail = 0;
122
+ while (tail < s.length && s.charCodeAt(s.length - 1 - tail) === 10) tail++;
123
+ trailing = tail === s.length ? trailing + tail : tail;
124
+ };
125
+ const owe = (n: number) => {
126
+ owed = Math.max(owed, n);
127
+ };
128
+
129
+ const parser = new Parser(
130
+ {
131
+ onopentag(name, attribs) {
132
+ if (skip > 0) {
133
+ skip++;
134
+ open.push("skipped");
135
+ return;
136
+ }
137
+ if (
138
+ SKIPPED.has(name) ||
139
+ attribs.hidden !== undefined ||
140
+ isHiddenStyle(attribs.style ?? "")
141
+ ) {
142
+ skip = 1;
143
+ open.push("skipped");
144
+ return;
145
+ }
146
+ if (name === "br") {
147
+ // A hard break: two in a row make a blank line.
148
+ write("\n");
149
+ open.push("other");
150
+ return;
151
+ }
152
+ if (PARAGRAPH.has(name)) owe(2);
153
+ else if (LINE.has(name)) owe(1);
154
+ if (name === "li") write("- ");
155
+ if (name === "pre") {
156
+ pre++;
157
+ open.push("pre");
158
+ } else if (name === "a" && !link) {
159
+ link = { href: (attribs.href ?? "").trim(), text: "", over: false };
160
+ open.push("link");
161
+ } else {
162
+ open.push("other");
163
+ }
164
+ },
165
+ ontext(data) {
166
+ if (skip > 0) return;
167
+ if (pre > 0) {
168
+ write(data);
169
+ return;
170
+ }
171
+ const flatText = data.replace(/[ \t\r\n\f]+/g, " ");
172
+ // Whitespace between tags is not content: after a block or at the
173
+ // start it would only add blank lines.
174
+ if (
175
+ flatText === " " &&
176
+ (owed > 0 || trailing > 0 || out.length === 0)
177
+ ) {
178
+ return;
179
+ }
180
+ write(flatText);
181
+ },
182
+ onclosetag(name) {
183
+ const kind = open.pop();
184
+ if (kind === "skipped") {
185
+ skip--;
186
+ return;
187
+ }
188
+ if (skip > 0) return;
189
+ if (kind === "pre") pre--;
190
+ if (kind === "link") {
191
+ const done = link;
192
+ link = undefined;
193
+ if (done && LINK_HREF.test(done.href)) {
194
+ const text = flat(done.text);
195
+ if (text && (done.over || bare(text) !== bare(done.href))) {
196
+ write(` [${done.href}]`);
197
+ }
198
+ }
199
+ }
200
+ if (PARAGRAPH.has(name)) owe(2);
201
+ else if (LINE.has(name)) owe(1);
202
+ else if (CELLS.has(name)) write(" ");
203
+ },
204
+ },
205
+ { decodeEntities: true },
206
+ );
207
+ parser.write(html);
208
+ parser.end();
209
+
210
+ return out
211
+ .join("")
212
+ .replace(ZERO_WIDTH, "")
213
+ .split("\n")
214
+ .map((line) => line.replace(HORIZONTAL, " ").trim())
215
+ .join("\n")
216
+ .replace(/\n{3,}/g, "\n\n")
217
+ .trim();
218
+ }
@@ -0,0 +1,80 @@
1
+ import PostalMime from "postal-mime";
2
+ import { parseAddressList } from "./address";
3
+ import type { Addr, ParsedInbound } from "./types";
4
+
5
+ type PmAddress = {
6
+ address?: string;
7
+ name?: string;
8
+ group?: PmAddress[];
9
+ };
10
+
11
+ function toAddr(a: PmAddress | undefined): Addr {
12
+ const address = (a?.address ?? "").trim().toLowerCase();
13
+ return a?.name ? { address, name: a.name } : { address };
14
+ }
15
+
16
+ function toAddrs(list: PmAddress[] | undefined): Addr[] {
17
+ const out: Addr[] = [];
18
+ for (const a of list ?? []) {
19
+ if (a.group) out.push(...toAddrs(a.group));
20
+ else if (a.address) out.push(toAddr(a));
21
+ }
22
+ return out;
23
+ }
24
+
25
+ function headerValue(
26
+ headers: { key: string; value: string }[],
27
+ name: string,
28
+ ): string | undefined {
29
+ return headers.find((h) => h.key === name)?.value;
30
+ }
31
+
32
+ /** Parse raw RFC 822 bytes. HTML is returned raw; callers sanitize separately. */
33
+ export async function parseMime(bytes: ArrayBuffer): Promise<ParsedInbound> {
34
+ const email = await PostalMime.parse(bytes);
35
+
36
+ const refsRaw = headerValue(email.headers, "references") ?? email.references;
37
+ const references = (refsRaw ?? "").split(/\s+/).filter(Boolean);
38
+
39
+ const replyTo = email.replyTo
40
+ ? toAddrs(email.replyTo)
41
+ : parseAddressList(headerValue(email.headers, "reply-to") ?? "");
42
+
43
+ const date = email.date ? Date.parse(email.date) : Number.NaN;
44
+
45
+ return {
46
+ messageId: email.messageId,
47
+ inReplyTo: email.inReplyTo,
48
+ references,
49
+ from: toAddr(email.from),
50
+ to: toAddrs(email.to),
51
+ cc: toAddrs(email.cc),
52
+ replyTo,
53
+ subject: email.subject ?? "",
54
+ text: email.text,
55
+ html: email.html,
56
+ headers: email.headers.map((h) => ({ name: h.key, value: h.value })),
57
+ date: Number.isNaN(date) ? undefined : date,
58
+ attachments: email.attachments.map((a) => {
59
+ const raw =
60
+ typeof a.content === "string"
61
+ ? new TextEncoder().encode(a.content)
62
+ : new Uint8Array(a.content);
63
+ const content = new ArrayBuffer(raw.byteLength);
64
+ new Uint8Array(content).set(raw);
65
+ return {
66
+ filename: a.filename ?? "",
67
+ contentType: a.mimeType,
68
+ size: raw.byteLength,
69
+ ...(a.contentId
70
+ ? { contentId: a.contentId.replace(/^<|>$/g, "") }
71
+ : {}),
72
+ disposition:
73
+ a.disposition === "inline" || (a.disposition == null && a.contentId)
74
+ ? "inline"
75
+ : "attachment",
76
+ content,
77
+ };
78
+ }),
79
+ };
80
+ }