@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.
- package/LICENSE +201 -0
- package/README.md +700 -2
- package/dist/adapters/index.d.ts +2 -0
- package/dist/adapters/index.d.ts.map +1 -0
- package/dist/adapters/index.js +7 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/registry.d.ts +9 -0
- package/dist/adapters/registry.d.ts.map +1 -0
- package/dist/adapters/registry.js +20 -0
- package/dist/adapters/registry.js.map +1 -0
- package/dist/adapters/resend/inbound.d.ts +5 -0
- package/dist/adapters/resend/inbound.d.ts.map +1 -0
- package/dist/adapters/resend/inbound.js +207 -0
- package/dist/adapters/resend/inbound.js.map +1 -0
- package/dist/adapters/resend/index.d.ts +4 -0
- package/dist/adapters/resend/index.d.ts.map +1 -0
- package/dist/adapters/resend/index.js +27 -0
- package/dist/adapters/resend/index.js.map +1 -0
- package/dist/adapters/resend/parse.d.ts +3 -0
- package/dist/adapters/resend/parse.d.ts.map +1 -0
- package/dist/adapters/resend/parse.js +94 -0
- package/dist/adapters/resend/parse.js.map +1 -0
- package/dist/adapters/resend/send.d.ts +15 -0
- package/dist/adapters/resend/send.d.ts.map +1 -0
- package/dist/adapters/resend/send.js +117 -0
- package/dist/adapters/resend/send.js.map +1 -0
- package/dist/adapters/resend/webhook.d.ts +6 -0
- package/dist/adapters/resend/webhook.d.ts.map +1 -0
- package/dist/adapters/resend/webhook.js +66 -0
- package/dist/adapters/resend/webhook.js.map +1 -0
- package/dist/adapters/ses/inbound.d.ts +3 -0
- package/dist/adapters/ses/inbound.d.ts.map +1 -0
- package/dist/adapters/ses/inbound.js +52 -0
- package/dist/adapters/ses/inbound.js.map +1 -0
- package/dist/adapters/ses/index.d.ts +4 -0
- package/dist/adapters/ses/index.d.ts.map +1 -0
- package/dist/adapters/ses/index.js +28 -0
- package/dist/adapters/ses/index.js.map +1 -0
- package/dist/adapters/ses/parse.d.ts +7 -0
- package/dist/adapters/ses/parse.d.ts.map +1 -0
- package/dist/adapters/ses/parse.js +209 -0
- package/dist/adapters/ses/parse.js.map +1 -0
- package/dist/adapters/ses/send.d.ts +10 -0
- package/dist/adapters/ses/send.d.ts.map +1 -0
- package/dist/adapters/ses/send.js +179 -0
- package/dist/adapters/ses/send.js.map +1 -0
- package/dist/adapters/ses/sigv4.d.ts +19 -0
- package/dist/adapters/ses/sigv4.d.ts.map +1 -0
- package/dist/adapters/ses/sigv4.js +50 -0
- package/dist/adapters/ses/sigv4.js.map +1 -0
- package/dist/adapters/ses/sns.d.ts +23 -0
- package/dist/adapters/ses/sns.d.ts.map +1 -0
- package/dist/adapters/ses/sns.js +281 -0
- package/dist/adapters/ses/sns.js.map +1 -0
- package/dist/adapters/types.d.ts +11 -0
- package/dist/adapters/types.d.ts.map +1 -0
- package/dist/adapters/types.js +2 -0
- package/dist/adapters/types.js.map +1 -0
- package/dist/client/index.d.ts +214 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +304 -0
- package/dist/client/index.js.map +1 -0
- package/dist/component/_generated/api.d.ts +62 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +345 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +133 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +80 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/attachments.d.ts +21 -0
- package/dist/component/attachments.d.ts.map +1 -0
- package/dist/component/attachments.js +66 -0
- package/dist/component/attachments.js.map +1 -0
- package/dist/component/cleanup.d.ts +15 -0
- package/dist/component/cleanup.d.ts.map +1 -0
- package/dist/component/cleanup.js +152 -0
- package/dist/component/cleanup.js.map +1 -0
- package/dist/component/config.d.ts +34 -0
- package/dist/component/config.d.ts.map +1 -0
- package/dist/component/config.js +33 -0
- package/dist/component/config.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +8 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/credentials.d.ts +19 -0
- package/dist/component/credentials.d.ts.map +1 -0
- package/dist/component/credentials.js +45 -0
- package/dist/component/credentials.js.map +1 -0
- package/dist/component/deliver.d.ts +58 -0
- package/dist/component/deliver.d.ts.map +1 -0
- package/dist/component/deliver.js +328 -0
- package/dist/component/deliver.js.map +1 -0
- package/dist/component/events.d.ts +15 -0
- package/dist/component/events.d.ts.map +1 -0
- package/dist/component/events.js +141 -0
- package/dist/component/events.js.map +1 -0
- package/dist/component/inbound.d.ts +354 -0
- package/dist/component/inbound.d.ts.map +1 -0
- package/dist/component/inbound.js +933 -0
- package/dist/component/inbound.js.map +1 -0
- package/dist/component/queries.d.ts +76 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +175 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +473 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +185 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/send.d.ts +112 -0
- package/dist/component/send.d.ts.map +1 -0
- package/dist/component/send.js +393 -0
- package/dist/component/send.js.map +1 -0
- package/dist/component/status.d.ts +2 -0
- package/dist/component/status.d.ts.map +1 -0
- package/dist/component/status.js +8 -0
- package/dist/component/status.js.map +1 -0
- package/dist/component/suppression.d.ts +36 -0
- package/dist/component/suppression.d.ts.map +1 -0
- package/dist/component/suppression.js +89 -0
- package/dist/component/suppression.js.map +1 -0
- package/dist/component/unsubscribe.d.ts +58 -0
- package/dist/component/unsubscribe.d.ts.map +1 -0
- package/dist/component/unsubscribe.js +129 -0
- package/dist/component/unsubscribe.js.map +1 -0
- package/dist/component/webhooks.d.ts +36 -0
- package/dist/component/webhooks.d.ts.map +1 -0
- package/dist/component/webhooks.js +71 -0
- package/dist/component/webhooks.js.map +1 -0
- package/dist/shared/address.d.ts +9 -0
- package/dist/shared/address.d.ts.map +1 -0
- package/dist/shared/address.js +76 -0
- package/dist/shared/address.js.map +1 -0
- package/dist/shared/authResults.d.ts +15 -0
- package/dist/shared/authResults.d.ts.map +1 -0
- package/dist/shared/authResults.js +86 -0
- package/dist/shared/authResults.js.map +1 -0
- package/dist/shared/htmlToText.d.ts +13 -0
- package/dist/shared/htmlToText.d.ts.map +1 -0
- package/dist/shared/htmlToText.js +221 -0
- package/dist/shared/htmlToText.js.map +1 -0
- package/dist/shared/mime.d.ts +4 -0
- package/dist/shared/mime.d.ts.map +1 -0
- package/dist/shared/mime.js +63 -0
- package/dist/shared/mime.js.map +1 -0
- package/dist/shared/readCapped.d.ts +7 -0
- package/dist/shared/readCapped.d.ts.map +1 -0
- package/dist/shared/readCapped.js +38 -0
- package/dist/shared/readCapped.js.map +1 -0
- package/dist/shared/sanitize.d.ts +10 -0
- package/dist/shared/sanitize.d.ts.map +1 -0
- package/dist/shared/sanitize.js +68 -0
- package/dist/shared/sanitize.js.map +1 -0
- package/dist/shared/threading.d.ts +6 -0
- package/dist/shared/threading.d.ts.map +1 -0
- package/dist/shared/threading.js +23 -0
- package/dist/shared/threading.js.map +1 -0
- package/dist/shared/types.d.ts +260 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/types.js +2 -0
- package/dist/shared/types.js.map +1 -0
- package/dist/shared/unsubToken.d.ts +15 -0
- package/dist/shared/unsubToken.d.ts.map +1 -0
- package/dist/shared/unsubToken.js +83 -0
- package/dist/shared/unsubToken.js.map +1 -0
- package/dist/shared/validators.d.ts +760 -0
- package/dist/shared/validators.d.ts.map +1 -0
- package/dist/shared/validators.js +200 -0
- package/dist/shared/validators.js.map +1 -0
- package/package.json +88 -4
- package/src/adapters/index.ts +8 -0
- package/src/adapters/registry.ts +28 -0
- package/src/adapters/resend/inbound.ts +245 -0
- package/src/adapters/resend/index.ts +29 -0
- package/src/adapters/resend/parse.ts +118 -0
- package/src/adapters/resend/send.ts +125 -0
- package/src/adapters/resend/webhook.ts +77 -0
- package/src/adapters/ses/inbound.ts +63 -0
- package/src/adapters/ses/index.ts +30 -0
- package/src/adapters/ses/parse.ts +236 -0
- package/src/adapters/ses/send.ts +206 -0
- package/src/adapters/ses/sigv4.ts +56 -0
- package/src/adapters/ses/sns.ts +321 -0
- package/src/adapters/types.ts +27 -0
- package/src/client/index.ts +549 -0
- package/src/component/_generated/api.ts +78 -0
- package/src/component/_generated/component.ts +475 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +169 -0
- package/src/component/attachments.ts +69 -0
- package/src/component/cleanup.ts +173 -0
- package/src/component/config.ts +52 -0
- package/src/component/convex.config.ts +9 -0
- package/src/component/credentials.ts +63 -0
- package/src/component/deliver.ts +380 -0
- package/src/component/events.ts +179 -0
- package/src/component/inbound.ts +1107 -0
- package/src/component/queries.ts +203 -0
- package/src/component/schema.ts +222 -0
- package/src/component/send.ts +467 -0
- package/src/component/status.ts +8 -0
- package/src/component/suppression.ts +114 -0
- package/src/component/unsubscribe.ts +154 -0
- package/src/component/webhooks.ts +84 -0
- package/src/shared/address.ts +75 -0
- package/src/shared/authResults.ts +94 -0
- package/src/shared/htmlToText.ts +218 -0
- package/src/shared/mime.ts +80 -0
- package/src/shared/readCapped.ts +39 -0
- package/src/shared/sanitize.ts +73 -0
- package/src/shared/threading.ts +26 -0
- package/src/shared/types.ts +254 -0
- package/src/shared/unsubToken.ts +95 -0
- package/src/shared/validators.ts +282 -0
- package/src/test.ts +25 -0
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import { getAdapter } from "../adapters/index.js";
|
|
3
|
+
import {
|
|
4
|
+
domainOf,
|
|
5
|
+
normalizeAddress,
|
|
6
|
+
parseAddressList,
|
|
7
|
+
} from "../shared/address.js";
|
|
8
|
+
import { buildReferences, generateMessageId } from "../shared/threading.js";
|
|
9
|
+
import {
|
|
10
|
+
vMessageStatus,
|
|
11
|
+
vRuntimeConfig,
|
|
12
|
+
vStream,
|
|
13
|
+
} from "../shared/validators.js";
|
|
14
|
+
import type { Doc, Id } from "./_generated/dataModel.js";
|
|
15
|
+
import { type MutationCtx, mutation } from "./_generated/server.js";
|
|
16
|
+
import { upsertConfig } from "./config.js";
|
|
17
|
+
import { enqueueDelivery } from "./deliver.js";
|
|
18
|
+
import { isSuppressed, isUnsubscribed } from "./suppression.js";
|
|
19
|
+
|
|
20
|
+
const TAG_VALUE = /^[A-Za-z0-9_-]{1,256}$/;
|
|
21
|
+
const TAG_KEY = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
22
|
+
/** The component sets these; an app-supplied copy would corrupt threading or unsubscribe. */
|
|
23
|
+
const HEADER_NAME = /^[!-9;-~]+$/;
|
|
24
|
+
const RESERVED_HEADERS = new Set([
|
|
25
|
+
"from",
|
|
26
|
+
"to",
|
|
27
|
+
"cc",
|
|
28
|
+
"bcc",
|
|
29
|
+
"sender",
|
|
30
|
+
"reply-to",
|
|
31
|
+
"subject",
|
|
32
|
+
"date",
|
|
33
|
+
"return-path",
|
|
34
|
+
"mime-version",
|
|
35
|
+
"message-id",
|
|
36
|
+
"in-reply-to",
|
|
37
|
+
"references",
|
|
38
|
+
"list-unsubscribe",
|
|
39
|
+
"list-unsubscribe-post",
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
export const vSendInput = v.object({
|
|
43
|
+
from: v.string(),
|
|
44
|
+
to: v.union(v.string(), v.array(v.string())),
|
|
45
|
+
cc: v.optional(v.union(v.string(), v.array(v.string()))),
|
|
46
|
+
bcc: v.optional(v.union(v.string(), v.array(v.string()))),
|
|
47
|
+
replyTo: v.optional(v.union(v.string(), v.array(v.string()))),
|
|
48
|
+
subject: v.string(),
|
|
49
|
+
html: v.optional(v.string()),
|
|
50
|
+
text: v.optional(v.string()),
|
|
51
|
+
attachments: v.optional(v.array(v.id("attachments"))),
|
|
52
|
+
inReplyTo: v.optional(v.union(v.id("messages"), v.string())),
|
|
53
|
+
category: v.optional(v.string()),
|
|
54
|
+
tenant: v.optional(v.string()),
|
|
55
|
+
stream: v.optional(vStream),
|
|
56
|
+
tags: v.optional(v.record(v.string(), v.string())),
|
|
57
|
+
headers: v.optional(
|
|
58
|
+
v.array(v.object({ name: v.string(), value: v.string() })),
|
|
59
|
+
),
|
|
60
|
+
idempotencyKey: v.optional(v.string()),
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const MESSAGE_ID = /^<[^<>\s@]+@[^<>\s]+>$/;
|
|
64
|
+
const MAX_LINE = 998;
|
|
65
|
+
const MAX_HEADERS = 50;
|
|
66
|
+
const MAX_TAGS = 50;
|
|
67
|
+
const MAX_RECIPIENTS = 100;
|
|
68
|
+
|
|
69
|
+
/** CR, LF and other control characters (tab only where `allowTab`). */
|
|
70
|
+
function hasControl(value: string, allowTab = false): boolean {
|
|
71
|
+
for (let i = 0; i < value.length; i++) {
|
|
72
|
+
const c = value.charCodeAt(i);
|
|
73
|
+
if ((c < 32 && !(allowTab && c === 9)) || c === 127) return true;
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function noControl(label: string, value: string, allowTab = false) {
|
|
79
|
+
if (hasControl(value, allowTab)) {
|
|
80
|
+
throw new Error(`${label} must not contain control characters`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** One `@` with a non-empty local part and domain, no control or whitespace. */
|
|
85
|
+
function validAddress(a: string): boolean {
|
|
86
|
+
if (hasControl(a) || /[\s<>,]/.test(a)) return false;
|
|
87
|
+
const at = a.indexOf("@");
|
|
88
|
+
return at > 0 && at === a.lastIndexOf("@") && at < a.length - 1;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const bytes = (s: string | undefined) =>
|
|
92
|
+
s === undefined ? 0 : new TextEncoder().encode(s).byteLength;
|
|
93
|
+
|
|
94
|
+
const unique = (xs: string[]) => [...new Set(xs)];
|
|
95
|
+
|
|
96
|
+
const addresses = (raw: string | string[] | undefined) =>
|
|
97
|
+
unique(parseAddressList(raw ?? []).map((a) => a.address));
|
|
98
|
+
|
|
99
|
+
type Parent = Pick<
|
|
100
|
+
Doc<"messages">,
|
|
101
|
+
"rfcMessageId" | "references" | "threadId" | "tenant"
|
|
102
|
+
>;
|
|
103
|
+
|
|
104
|
+
async function resolveParent(
|
|
105
|
+
ctx: MutationCtx,
|
|
106
|
+
tenant: string | undefined,
|
|
107
|
+
inReplyTo: string,
|
|
108
|
+
): Promise<Parent | null> {
|
|
109
|
+
const id = ctx.db.normalizeId("messages", inReplyTo);
|
|
110
|
+
if (id) {
|
|
111
|
+
const parent = await ctx.db.get(id);
|
|
112
|
+
if (!parent) throw new Error("inReplyTo: no such message");
|
|
113
|
+
if (parent.tenant !== tenant) {
|
|
114
|
+
throw new Error("inReplyTo: message belongs to another tenant");
|
|
115
|
+
}
|
|
116
|
+
return parent;
|
|
117
|
+
}
|
|
118
|
+
return await ctx.db
|
|
119
|
+
.query("messages")
|
|
120
|
+
.withIndex("by_tenant_rfcMessageId", (q) =>
|
|
121
|
+
q.eq("tenant", tenant).eq("rfcMessageId", inReplyTo),
|
|
122
|
+
)
|
|
123
|
+
.first();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export const enqueue = mutation({
|
|
127
|
+
args: { config: vRuntimeConfig, message: vSendInput },
|
|
128
|
+
returns: v.object({
|
|
129
|
+
messageId: v.id("messages"),
|
|
130
|
+
// `queued | test | suppressed` for a fresh send; a deduplicated replay
|
|
131
|
+
// returns whatever the first message has since become.
|
|
132
|
+
status: vMessageStatus,
|
|
133
|
+
deduplicated: v.boolean(),
|
|
134
|
+
}),
|
|
135
|
+
handler: async (ctx, { config, message }) => {
|
|
136
|
+
const tenant = message.tenant ?? config.defaultTenant;
|
|
137
|
+
|
|
138
|
+
// An idempotent replay returns the first message before anything else,
|
|
139
|
+
// so a replay with attachments does not trip the one-link rule.
|
|
140
|
+
if (message.idempotencyKey !== undefined) {
|
|
141
|
+
const seen = await ctx.db
|
|
142
|
+
.query("messages")
|
|
143
|
+
.withIndex("by_tenant_idempotencyKey", (q) =>
|
|
144
|
+
q.eq("tenant", tenant).eq("idempotencyKey", message.idempotencyKey),
|
|
145
|
+
)
|
|
146
|
+
.first();
|
|
147
|
+
if (seen) {
|
|
148
|
+
await upsertConfig(ctx, config);
|
|
149
|
+
return { messageId: seen._id, status: seen.status, deduplicated: true };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// 1. Validate. Everything here runs before any storage or db write.
|
|
154
|
+
if (!config.providers.includes(config.sendVia)) {
|
|
155
|
+
throw new Error(
|
|
156
|
+
`sendVia "${config.sendVia}" is not among the configured providers`,
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
const stream = message.stream ?? "transactional";
|
|
160
|
+
if (message.html === undefined && message.text === undefined) {
|
|
161
|
+
throw new Error("a message needs html or text");
|
|
162
|
+
}
|
|
163
|
+
if (message.subject.length > MAX_LINE) {
|
|
164
|
+
throw new Error(`subject is over the ${MAX_LINE} character limit`);
|
|
165
|
+
}
|
|
166
|
+
noControl("subject", message.subject);
|
|
167
|
+
noControl("from", message.from);
|
|
168
|
+
const tags = Object.entries(message.tags ?? {});
|
|
169
|
+
if (tags.length > MAX_TAGS) {
|
|
170
|
+
throw new Error(`more than ${MAX_TAGS} tags`);
|
|
171
|
+
}
|
|
172
|
+
for (const [key, value] of tags) {
|
|
173
|
+
if (key.startsWith("cx_")) {
|
|
174
|
+
throw new Error(`tag key "${key}" uses the reserved "cx_" prefix`);
|
|
175
|
+
}
|
|
176
|
+
if (!TAG_KEY.test(key)) {
|
|
177
|
+
throw new Error(`tag key "${key}" must match ${TAG_KEY.source}`);
|
|
178
|
+
}
|
|
179
|
+
if (!TAG_VALUE.test(value)) {
|
|
180
|
+
throw new Error(`tag "${key}" value must match ${TAG_VALUE.source}`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const headers = message.headers ?? [];
|
|
184
|
+
if (headers.length > MAX_HEADERS) {
|
|
185
|
+
throw new Error(`more than ${MAX_HEADERS} headers`);
|
|
186
|
+
}
|
|
187
|
+
const seenHeaders = new Set<string>();
|
|
188
|
+
for (const h of headers) {
|
|
189
|
+
if (!HEADER_NAME.test(h.name)) {
|
|
190
|
+
throw new Error(`header name "${h.name}" is not a valid field name`);
|
|
191
|
+
}
|
|
192
|
+
const lower = h.name.toLowerCase();
|
|
193
|
+
if (seenHeaders.has(lower)) {
|
|
194
|
+
throw new Error(`header "${h.name}" is given more than once`);
|
|
195
|
+
}
|
|
196
|
+
seenHeaders.add(lower);
|
|
197
|
+
if (RESERVED_HEADERS.has(lower) || lower.startsWith("content-")) {
|
|
198
|
+
throw new Error(`header "${h.name}" is set by the component`);
|
|
199
|
+
}
|
|
200
|
+
if (h.value.length > MAX_LINE) {
|
|
201
|
+
throw new Error(
|
|
202
|
+
`header "${h.name}" value is over ${MAX_LINE} characters`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
noControl(`header "${h.name}" value`, h.value, true);
|
|
206
|
+
}
|
|
207
|
+
if (
|
|
208
|
+
stream === "bulk" &&
|
|
209
|
+
message.category !== undefined &&
|
|
210
|
+
!config.unsubscribe
|
|
211
|
+
) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
"a bulk message with a category needs an unsubscribe configuration",
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const from = parseAddressList(message.from)[0];
|
|
218
|
+
if (!from || !validAddress(from.address)) {
|
|
219
|
+
throw new Error("from is not a valid address");
|
|
220
|
+
}
|
|
221
|
+
const domain = config.messageIdDomain ?? domainOf(from.address);
|
|
222
|
+
if (!domain) throw new Error("no domain for the Message-ID");
|
|
223
|
+
|
|
224
|
+
const toList = addresses(message.to);
|
|
225
|
+
const ccList = addresses(message.cc);
|
|
226
|
+
const bccList = addresses(message.bcc);
|
|
227
|
+
const all = [...toList, ...ccList, ...bccList];
|
|
228
|
+
if (all.length === 0) throw new Error("a message needs a recipient");
|
|
229
|
+
if (all.length > MAX_RECIPIENTS) {
|
|
230
|
+
throw new Error(`more than ${MAX_RECIPIENTS} recipients`);
|
|
231
|
+
}
|
|
232
|
+
if (
|
|
233
|
+
message.category !== undefined &&
|
|
234
|
+
config.unsubscribe &&
|
|
235
|
+
all.length !== 1
|
|
236
|
+
) {
|
|
237
|
+
// One List-Unsubscribe token per message, so it must name the only
|
|
238
|
+
// recipient (several would share, and could expose, one address).
|
|
239
|
+
throw new Error(
|
|
240
|
+
"a message with a category needs exactly one recipient across to, cc and bcc",
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
const replyToList = addresses(message.replyTo);
|
|
244
|
+
for (const a of [...all, ...replyToList]) {
|
|
245
|
+
if (!validAddress(a)) throw new Error(`"${a}" is not a valid address`);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const attachmentDocs: Doc<"attachments">[] = [];
|
|
249
|
+
for (const id of message.attachments ?? []) {
|
|
250
|
+
const att = await ctx.db.get(id);
|
|
251
|
+
if (!att) throw new Error("attachment: no such attachment");
|
|
252
|
+
if (att.tenant !== tenant) {
|
|
253
|
+
throw new Error("attachment: belongs to another tenant");
|
|
254
|
+
}
|
|
255
|
+
if (att.messageId) {
|
|
256
|
+
throw new Error("attachment: already linked to a message");
|
|
257
|
+
}
|
|
258
|
+
attachmentDocs.push(att);
|
|
259
|
+
}
|
|
260
|
+
const caps = getAdapter(config.sendVia).capabilities;
|
|
261
|
+
for (const att of attachmentDocs) {
|
|
262
|
+
if (att.size > caps.maxAttachmentBytes) {
|
|
263
|
+
throw new Error(
|
|
264
|
+
`attachment "${att.filename}" is ${att.size} bytes; ${config.sendVia} allows ${caps.maxAttachmentBytes}`,
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const total =
|
|
269
|
+
bytes(message.html) +
|
|
270
|
+
bytes(message.text) +
|
|
271
|
+
attachmentDocs.reduce((n, a) => n + a.size, 0);
|
|
272
|
+
if (total > caps.maxMessageBytes) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
`message is ${total} bytes; ${config.sendVia} allows ${caps.maxMessageBytes}`,
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Threading (reads only).
|
|
279
|
+
let inReplyTo: string | undefined;
|
|
280
|
+
let references: string[] = [];
|
|
281
|
+
const rfcMessageId = generateMessageId(domain);
|
|
282
|
+
let threadId = rfcMessageId;
|
|
283
|
+
if (message.inReplyTo !== undefined) {
|
|
284
|
+
const isId = ctx.db.normalizeId("messages", message.inReplyTo) !== null;
|
|
285
|
+
if (!isId && !MESSAGE_ID.test(message.inReplyTo)) {
|
|
286
|
+
throw new Error("inReplyTo is not a message id or an RFC Message-ID");
|
|
287
|
+
}
|
|
288
|
+
const parent = await resolveParent(ctx, tenant, message.inReplyTo);
|
|
289
|
+
if (parent) {
|
|
290
|
+
inReplyTo = parent.rfcMessageId;
|
|
291
|
+
references = buildReferences(parent);
|
|
292
|
+
threadId = parent.threadId;
|
|
293
|
+
} else {
|
|
294
|
+
inReplyTo = message.inReplyTo;
|
|
295
|
+
references = [message.inReplyTo];
|
|
296
|
+
threadId = message.inReplyTo;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// 2 and 3. Suppression, then unsubscribes for the category.
|
|
301
|
+
const dropped: string[] = [];
|
|
302
|
+
const keep = async (list: string[]) => {
|
|
303
|
+
const kept: string[] = [];
|
|
304
|
+
for (const address of list) {
|
|
305
|
+
const out =
|
|
306
|
+
(await isSuppressed(ctx, tenant, address)) ||
|
|
307
|
+
(message.category !== undefined &&
|
|
308
|
+
(await isUnsubscribed(ctx, tenant, address, message.category)));
|
|
309
|
+
(out ? dropped : kept).push(address);
|
|
310
|
+
}
|
|
311
|
+
return kept;
|
|
312
|
+
};
|
|
313
|
+
const to = await keep(toList);
|
|
314
|
+
const cc = await keep(ccList);
|
|
315
|
+
const bcc = await keep(bccList);
|
|
316
|
+
const remaining = unique([...to, ...cc, ...bcc]);
|
|
317
|
+
|
|
318
|
+
// 4. Bodies and row. Writes begin here.
|
|
319
|
+
await upsertConfig(ctx, config);
|
|
320
|
+
const htmlStorageId =
|
|
321
|
+
message.html === undefined
|
|
322
|
+
? undefined
|
|
323
|
+
: await ctx.storage.store(
|
|
324
|
+
new Blob([message.html], { type: "text/html" }),
|
|
325
|
+
);
|
|
326
|
+
const textStorageId =
|
|
327
|
+
message.text === undefined
|
|
328
|
+
? undefined
|
|
329
|
+
: await ctx.storage.store(
|
|
330
|
+
new Blob([message.text], { type: "text/plain" }),
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
// 5. Test mode: only a fully allowlisted recipient list reaches the provider.
|
|
334
|
+
let status: "queued" | "test" | "suppressed";
|
|
335
|
+
// Every To dropped: the rest are not sent a message with no To.
|
|
336
|
+
if (remaining.length === 0 || (toList.length > 0 && to.length === 0)) {
|
|
337
|
+
status = "suppressed";
|
|
338
|
+
} else if (config.testMode) {
|
|
339
|
+
const allow = new Set(config.testAllowlist.map(normalizeAddress));
|
|
340
|
+
status = remaining.every((a) => allow.has(a)) ? "queued" : "test";
|
|
341
|
+
} else {
|
|
342
|
+
status = "queued";
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const now = Date.now();
|
|
346
|
+
const messageId: Id<"messages"> = await ctx.db.insert("messages", {
|
|
347
|
+
direction: "outbound",
|
|
348
|
+
provider: config.sendVia,
|
|
349
|
+
tenant,
|
|
350
|
+
stream,
|
|
351
|
+
from: message.from.trim(),
|
|
352
|
+
to,
|
|
353
|
+
cc,
|
|
354
|
+
bcc,
|
|
355
|
+
replyTo: replyToList,
|
|
356
|
+
subject: message.subject,
|
|
357
|
+
htmlStorageId,
|
|
358
|
+
textStorageId,
|
|
359
|
+
headers,
|
|
360
|
+
rfcMessageId,
|
|
361
|
+
inReplyTo,
|
|
362
|
+
references,
|
|
363
|
+
threadId,
|
|
364
|
+
status,
|
|
365
|
+
category: message.category,
|
|
366
|
+
unsubscribeHeader:
|
|
367
|
+
message.category !== undefined && config.unsubscribe ? true : undefined,
|
|
368
|
+
unsubscribe:
|
|
369
|
+
message.category !== undefined && config.unsubscribe
|
|
370
|
+
? {
|
|
371
|
+
url: config.unsubscribe.url,
|
|
372
|
+
...(config.unsubscribe.mailto
|
|
373
|
+
? { mailto: config.unsubscribe.mailto }
|
|
374
|
+
: {}),
|
|
375
|
+
}
|
|
376
|
+
: undefined,
|
|
377
|
+
tags: message.tags ?? {},
|
|
378
|
+
idempotencyKey: message.idempotencyKey,
|
|
379
|
+
suppressedRecipients: unique(dropped),
|
|
380
|
+
createdAt: now,
|
|
381
|
+
updatedAt: now,
|
|
382
|
+
});
|
|
383
|
+
for (const att of attachmentDocs) {
|
|
384
|
+
await ctx.db.patch(att._id, { messageId });
|
|
385
|
+
}
|
|
386
|
+
if (status === "queued") await enqueueDelivery(ctx, messageId, stream);
|
|
387
|
+
return { messageId, status, deduplicated: false };
|
|
388
|
+
},
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Queue a `failed` outbound message again, on its own stream's pool. Any
|
|
393
|
+
* other status is refused, and so is a failure the provider reported after
|
|
394
|
+
* accepting the message (it has a provider id): send that one anew. A
|
|
395
|
+
* message whose delivery was ambiguous (an attempt got no provider answer)
|
|
396
|
+
* may already have arrived, so it is refused unless `force` is set. The
|
|
397
|
+
* suppression and unsubscribe checks run again, as at enqueue: recipients
|
|
398
|
+
* suppressed or unsubscribed since move to `suppressedRecipients`, and a
|
|
399
|
+
* message left with no To is `suppressed` rather than queued. Returns the
|
|
400
|
+
* resulting status.
|
|
401
|
+
*/
|
|
402
|
+
export const retry = mutation({
|
|
403
|
+
args: { messageId: v.id("messages"), force: v.optional(v.boolean()) },
|
|
404
|
+
returns: v.union(v.literal("queued"), v.literal("suppressed")),
|
|
405
|
+
handler: async (ctx, { messageId, force }) => {
|
|
406
|
+
const message = await ctx.db.get(messageId);
|
|
407
|
+
if (!message) throw new Error("no such message");
|
|
408
|
+
if (message.direction !== "outbound" || message.status !== "failed") {
|
|
409
|
+
throw new Error(
|
|
410
|
+
`only a failed message can be retried; this one is ${message.direction} and ${message.status}`,
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
if (message.providerId !== undefined) {
|
|
414
|
+
throw new Error(
|
|
415
|
+
"the provider accepted this message and reported the failure later; send it again as a new message",
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
if (message.deliveryAmbiguous && force !== true) {
|
|
419
|
+
throw new Error(
|
|
420
|
+
"this message may already have been delivered: an attempt got no answer from the provider (a network error or timeout). Pass { force: true } to send it again anyway",
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
const dropped: string[] = [];
|
|
424
|
+
const keep = async (list: string[]) => {
|
|
425
|
+
const kept: string[] = [];
|
|
426
|
+
for (const address of list) {
|
|
427
|
+
const out =
|
|
428
|
+
(await isSuppressed(ctx, message.tenant, address)) ||
|
|
429
|
+
(message.category !== undefined &&
|
|
430
|
+
(await isUnsubscribed(
|
|
431
|
+
ctx,
|
|
432
|
+
message.tenant,
|
|
433
|
+
address,
|
|
434
|
+
message.category,
|
|
435
|
+
)));
|
|
436
|
+
(out ? dropped : kept).push(address);
|
|
437
|
+
}
|
|
438
|
+
return kept;
|
|
439
|
+
};
|
|
440
|
+
const to = await keep(message.to);
|
|
441
|
+
const cc = await keep(message.cc);
|
|
442
|
+
const bcc = await keep(message.bcc);
|
|
443
|
+
const suppressedRecipients = unique([
|
|
444
|
+
...message.suppressedRecipients,
|
|
445
|
+
...dropped,
|
|
446
|
+
]);
|
|
447
|
+
// Same rule as enqueue: no To left means the rest are not sent.
|
|
448
|
+
const status =
|
|
449
|
+
(message.to.length > 0 && to.length === 0) ||
|
|
450
|
+
to.length + cc.length + bcc.length === 0
|
|
451
|
+
? "suppressed"
|
|
452
|
+
: "queued";
|
|
453
|
+
await ctx.db.patch(messageId, {
|
|
454
|
+
status,
|
|
455
|
+
to,
|
|
456
|
+
cc,
|
|
457
|
+
bcc,
|
|
458
|
+
suppressedRecipients,
|
|
459
|
+
error: undefined,
|
|
460
|
+
updatedAt: Date.now(),
|
|
461
|
+
});
|
|
462
|
+
if (status === "queued") {
|
|
463
|
+
await enqueueDelivery(ctx, messageId, message.stream);
|
|
464
|
+
}
|
|
465
|
+
return status;
|
|
466
|
+
},
|
|
467
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { paginationOptsValidator } from "convex/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
import { normalizeAddress } from "../shared/address.js";
|
|
4
|
+
import { mutation, type QueryCtx, query } from "./_generated/server.js";
|
|
5
|
+
import { vSuppressionReason } from "./schema.js";
|
|
6
|
+
|
|
7
|
+
export async function isSuppressed(
|
|
8
|
+
ctx: Pick<QueryCtx, "db">,
|
|
9
|
+
tenant: string | undefined,
|
|
10
|
+
address: string,
|
|
11
|
+
): Promise<boolean> {
|
|
12
|
+
const row = await ctx.db
|
|
13
|
+
.query("suppressions")
|
|
14
|
+
.withIndex("by_tenant_address", (q) =>
|
|
15
|
+
q.eq("tenant", tenant).eq("address", normalizeAddress(address)),
|
|
16
|
+
)
|
|
17
|
+
.first();
|
|
18
|
+
return row !== null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function isUnsubscribed(
|
|
22
|
+
ctx: Pick<QueryCtx, "db">,
|
|
23
|
+
tenant: string | undefined,
|
|
24
|
+
address: string,
|
|
25
|
+
category: string,
|
|
26
|
+
): Promise<boolean> {
|
|
27
|
+
const row = await ctx.db
|
|
28
|
+
.query("unsubscribes")
|
|
29
|
+
.withIndex("by_tenant_address_category", (q) =>
|
|
30
|
+
q
|
|
31
|
+
.eq("tenant", tenant)
|
|
32
|
+
.eq("address", normalizeAddress(address))
|
|
33
|
+
.eq("category", category),
|
|
34
|
+
)
|
|
35
|
+
.first();
|
|
36
|
+
return row !== null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const list = query({
|
|
40
|
+
args: {
|
|
41
|
+
tenant: v.optional(v.string()),
|
|
42
|
+
paginationOpts: paginationOptsValidator,
|
|
43
|
+
},
|
|
44
|
+
returns: v.object({
|
|
45
|
+
page: v.array(
|
|
46
|
+
v.object({
|
|
47
|
+
tenant: v.optional(v.string()),
|
|
48
|
+
address: v.string(),
|
|
49
|
+
reason: vSuppressionReason,
|
|
50
|
+
createdAt: v.number(),
|
|
51
|
+
}),
|
|
52
|
+
),
|
|
53
|
+
isDone: v.boolean(),
|
|
54
|
+
continueCursor: v.string(),
|
|
55
|
+
splitCursor: v.optional(v.union(v.string(), v.null())),
|
|
56
|
+
pageStatus: v.optional(
|
|
57
|
+
v.union(
|
|
58
|
+
v.literal("SplitRecommended"),
|
|
59
|
+
v.literal("SplitRequired"),
|
|
60
|
+
v.null(),
|
|
61
|
+
),
|
|
62
|
+
),
|
|
63
|
+
}),
|
|
64
|
+
handler: async (ctx, { tenant, paginationOpts }) => {
|
|
65
|
+
const result = await ctx.db
|
|
66
|
+
.query("suppressions")
|
|
67
|
+
.withIndex("by_tenant_address", (q) => q.eq("tenant", tenant))
|
|
68
|
+
.paginate(paginationOpts);
|
|
69
|
+
return {
|
|
70
|
+
...result,
|
|
71
|
+
page: result.page.map((r) => ({
|
|
72
|
+
tenant: r.tenant,
|
|
73
|
+
address: r.address,
|
|
74
|
+
reason: r.reason,
|
|
75
|
+
createdAt: r.createdAt,
|
|
76
|
+
})),
|
|
77
|
+
};
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
/** Idempotent: an existing row (any reason) is left as it is. */
|
|
82
|
+
export const add = mutation({
|
|
83
|
+
args: {
|
|
84
|
+
tenant: v.optional(v.string()),
|
|
85
|
+
address: v.string(),
|
|
86
|
+
reason: v.literal("manual"),
|
|
87
|
+
},
|
|
88
|
+
returns: v.null(),
|
|
89
|
+
handler: async (ctx, { tenant, address, reason }) => {
|
|
90
|
+
if (await isSuppressed(ctx, tenant, address)) return null;
|
|
91
|
+
await ctx.db.insert("suppressions", {
|
|
92
|
+
tenant,
|
|
93
|
+
address: normalizeAddress(address),
|
|
94
|
+
reason,
|
|
95
|
+
createdAt: Date.now(),
|
|
96
|
+
});
|
|
97
|
+
return null;
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
export const remove = mutation({
|
|
102
|
+
args: { tenant: v.optional(v.string()), address: v.string() },
|
|
103
|
+
returns: v.null(),
|
|
104
|
+
handler: async (ctx, { tenant, address }) => {
|
|
105
|
+
const rows = await ctx.db
|
|
106
|
+
.query("suppressions")
|
|
107
|
+
.withIndex("by_tenant_address", (q) =>
|
|
108
|
+
q.eq("tenant", tenant).eq("address", normalizeAddress(address)),
|
|
109
|
+
)
|
|
110
|
+
.collect();
|
|
111
|
+
for (const row of rows) await ctx.db.delete(row._id);
|
|
112
|
+
return null;
|
|
113
|
+
},
|
|
114
|
+
});
|