@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.
- package/LICENSE +201 -0
- package/README.md +709 -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,1107 @@
|
|
|
1
|
+
import { vOnCompleteArgs, Workpool } from "@convex-dev/workpool";
|
|
2
|
+
import type { FunctionReference } from "convex/server";
|
|
3
|
+
import { v } from "convex/values";
|
|
4
|
+
import { getAdapter } from "../adapters/index.js";
|
|
5
|
+
import { normalizeAddress } from "../shared/address.js";
|
|
6
|
+
import type { Verdict } from "../shared/authResults.js";
|
|
7
|
+
import { parseAuthenticationResults } from "../shared/authResults.js";
|
|
8
|
+
import { htmlToText } from "../shared/htmlToText.js";
|
|
9
|
+
import { parseMime } from "../shared/mime.js";
|
|
10
|
+
import { sanitizeInboundHtml } from "../shared/sanitize.js";
|
|
11
|
+
import type {
|
|
12
|
+
Addr,
|
|
13
|
+
InboundForApp,
|
|
14
|
+
ParsedInbound,
|
|
15
|
+
ProviderName,
|
|
16
|
+
} from "../shared/types.js";
|
|
17
|
+
import {
|
|
18
|
+
vAddr,
|
|
19
|
+
vDisposition,
|
|
20
|
+
vInboundNotification,
|
|
21
|
+
vRuntimeConfig,
|
|
22
|
+
vVerdicts,
|
|
23
|
+
} from "../shared/validators.js";
|
|
24
|
+
import { components, internal } from "./_generated/api.js";
|
|
25
|
+
import type { Doc, Id } from "./_generated/dataModel.js";
|
|
26
|
+
import {
|
|
27
|
+
type ActionCtx,
|
|
28
|
+
action,
|
|
29
|
+
internalAction,
|
|
30
|
+
internalMutation,
|
|
31
|
+
internalQuery,
|
|
32
|
+
type MutationCtx,
|
|
33
|
+
query,
|
|
34
|
+
} from "./_generated/server.js";
|
|
35
|
+
import { getConfig } from "./config.js";
|
|
36
|
+
import { fetchCredentials, redact, secretStrings } from "./credentials.js";
|
|
37
|
+
import { vInboundProvider, vInboundState } from "./schema.js";
|
|
38
|
+
|
|
39
|
+
/** Its own lane: a slow or failing app handler never delays a send. */
|
|
40
|
+
const callbacks = new Workpool(components.callbacks, { maxParallelism: 5 });
|
|
41
|
+
|
|
42
|
+
/** Text and HTML together over this go by reference, not inline. */
|
|
43
|
+
const BODY_INLINE_LIMIT = 256 * 1024;
|
|
44
|
+
/** Text derived from HTML is cut to this many UTF-8 bytes (and `truncated` set). */
|
|
45
|
+
const MAX_DERIVED_TEXT = 1024 * 1024;
|
|
46
|
+
/** Never parse more HTML than this for derived text (UTF-16 units, then bytes). */
|
|
47
|
+
const MAX_DERIVED_HTML = 2 * 1024 * 1024;
|
|
48
|
+
/** A pathological header must not push the message row past 1 MiB. */
|
|
49
|
+
const MAX_HEADER_VALUE = 8 * 1024;
|
|
50
|
+
const MAX_HEADERS = 200;
|
|
51
|
+
const MAX_HEADER_BYTES = 64 * 1024;
|
|
52
|
+
const MAX_SUBJECT = 2000;
|
|
53
|
+
const MAX_ADDRS = 500;
|
|
54
|
+
const MAX_ADDRESS = 320;
|
|
55
|
+
const MAX_NAME = 256;
|
|
56
|
+
/** Addresses are stored twice (bare columns and `addrs`), so half of 128 KiB. */
|
|
57
|
+
const MAX_ADDR_BYTES = 64 * 1024;
|
|
58
|
+
const MAX_ATTACHMENTS = 100;
|
|
59
|
+
const MAX_FILENAME = 255;
|
|
60
|
+
/** Rows read when looking for earlier mail with the same Message-ID. */
|
|
61
|
+
const MAX_SAME_ID = 50;
|
|
62
|
+
const MAX_REFERENCES = 50;
|
|
63
|
+
const MAX_ID = 512;
|
|
64
|
+
/** Waits before the scheduled fetch re-attempts: 30 s, 2 min, 10 min. */
|
|
65
|
+
const FETCH_RETRY_MS = [30_000, 120_000, 600_000];
|
|
66
|
+
const REUSED_NOTE = "Message-ID reused by a different message";
|
|
67
|
+
const MAX_NOTE = 500;
|
|
68
|
+
const MAX_FAILURE = 1000;
|
|
69
|
+
const MAX_THREAD_CANDIDATES = 21;
|
|
70
|
+
|
|
71
|
+
const bytes = (s: string | undefined) =>
|
|
72
|
+
s === undefined ? 0 : new TextEncoder().encode(s).byteLength;
|
|
73
|
+
|
|
74
|
+
const truncate = (s: string, max: number) =>
|
|
75
|
+
s.length > max ? `${s.slice(0, max - 1)}…` : s;
|
|
76
|
+
|
|
77
|
+
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Cut to at most `max` UTF-8 bytes (Convex limits documents in bytes, and a
|
|
81
|
+
* CJK character is three), never in the middle of a character or surrogate pair.
|
|
82
|
+
*/
|
|
83
|
+
function cutBytes(s: string, max: number): string {
|
|
84
|
+
if (bytes(s) <= max) return s;
|
|
85
|
+
let used = 0;
|
|
86
|
+
let end = 0;
|
|
87
|
+
for (const ch of s) {
|
|
88
|
+
const n = bytes(ch);
|
|
89
|
+
if (used + n > max) break;
|
|
90
|
+
used += n;
|
|
91
|
+
end += ch.length;
|
|
92
|
+
}
|
|
93
|
+
return s.slice(0, end);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Sender-controlled input cut to what a message row can always hold. */
|
|
97
|
+
function bound(parsed: ParsedInbound) {
|
|
98
|
+
let truncated = false;
|
|
99
|
+
const cut = (s: string, max: number) => {
|
|
100
|
+
const out = cutBytes(s, max);
|
|
101
|
+
if (out.length !== s.length) truncated = true;
|
|
102
|
+
return out;
|
|
103
|
+
};
|
|
104
|
+
// One budget for every address list together (from, to, cc, replyTo).
|
|
105
|
+
let addrBudget = MAX_ADDR_BYTES;
|
|
106
|
+
const list = (xs: Addr[]) => {
|
|
107
|
+
if (xs.length > MAX_ADDRS) truncated = true;
|
|
108
|
+
const out: Addr[] = [];
|
|
109
|
+
for (const a of xs.slice(0, MAX_ADDRS)) {
|
|
110
|
+
const address = cut(a.address, MAX_ADDRESS);
|
|
111
|
+
const name = a.name === undefined ? undefined : cut(a.name, MAX_NAME);
|
|
112
|
+
const size = bytes(address) + bytes(name);
|
|
113
|
+
if (size > addrBudget) {
|
|
114
|
+
truncated = true;
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
addrBudget -= size;
|
|
118
|
+
out.push(name === undefined ? { address } : { address, name });
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
};
|
|
122
|
+
// Every msg-id is kept in `<…>` form, whatever the adapter (or raw MIME)
|
|
123
|
+
// handed over, so a bare id from one source still matches another's. The
|
|
124
|
+
// size cap comes first and the brackets go by index scans: no regex ever
|
|
125
|
+
// runs over a sender-controlled id.
|
|
126
|
+
const id = (s: string | undefined) => {
|
|
127
|
+
if (s === undefined) return undefined;
|
|
128
|
+
if (bytes(s) > MAX_ID + 2) {
|
|
129
|
+
truncated = true;
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
const t = s.trim();
|
|
133
|
+
let start = 0;
|
|
134
|
+
let end = t.length;
|
|
135
|
+
while (start < end && t[start] === "<") start++;
|
|
136
|
+
while (end > start && t[end - 1] === ">") end--;
|
|
137
|
+
const inner = t.slice(start, end).trim();
|
|
138
|
+
if (!inner) return undefined;
|
|
139
|
+
const out = `<${inner}>`;
|
|
140
|
+
if (bytes(out) > MAX_ID) {
|
|
141
|
+
truncated = true;
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
};
|
|
146
|
+
const headers: { name: string; value: string }[] = [];
|
|
147
|
+
let headerBytes = 0;
|
|
148
|
+
for (const h of parsed.headers) {
|
|
149
|
+
const value = cut(h.value, MAX_HEADER_VALUE);
|
|
150
|
+
const size = bytes(h.name) + bytes(value);
|
|
151
|
+
if (
|
|
152
|
+
headers.length >= MAX_HEADERS ||
|
|
153
|
+
bytes(h.name) > MAX_ID ||
|
|
154
|
+
headerBytes + size > MAX_HEADER_BYTES
|
|
155
|
+
) {
|
|
156
|
+
truncated = true;
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
headers.push({ name: h.name, value });
|
|
160
|
+
headerBytes += size;
|
|
161
|
+
}
|
|
162
|
+
// Only the last (nearest) references are kept; the rest are never read.
|
|
163
|
+
if (parsed.references.length > MAX_REFERENCES) truncated = true;
|
|
164
|
+
const refs = parsed.references.slice(-MAX_REFERENCES).flatMap((r) => {
|
|
165
|
+
const x = id(r);
|
|
166
|
+
return x === undefined ? [] : [x];
|
|
167
|
+
});
|
|
168
|
+
if (parsed.attachments.length > MAX_ATTACHMENTS) truncated = true;
|
|
169
|
+
if (parsed.truncated) truncated = true;
|
|
170
|
+
const attachments = parsed.attachments.slice(0, MAX_ATTACHMENTS).map((a) => ({
|
|
171
|
+
...a,
|
|
172
|
+
filename: cut(a.filename, MAX_FILENAME),
|
|
173
|
+
contentType: cut(a.contentType, MAX_FILENAME),
|
|
174
|
+
contentId:
|
|
175
|
+
a.contentId === undefined ? undefined : cut(a.contentId, MAX_FILENAME),
|
|
176
|
+
}));
|
|
177
|
+
const from = list([parsed.from])[0] ?? { address: "" };
|
|
178
|
+
const to = list(parsed.to);
|
|
179
|
+
const cc = list(parsed.cc);
|
|
180
|
+
const replyTo = list(parsed.replyTo);
|
|
181
|
+
const subject = cut(parsed.subject, MAX_SUBJECT);
|
|
182
|
+
const rfcMessageId = id(parsed.messageId);
|
|
183
|
+
const inReplyTo = id(parsed.inReplyTo);
|
|
184
|
+
// `truncated` is read last: every cut above has been counted by now.
|
|
185
|
+
return {
|
|
186
|
+
attachments,
|
|
187
|
+
truncated,
|
|
188
|
+
rfcMessageId,
|
|
189
|
+
inReplyTo,
|
|
190
|
+
references: refs,
|
|
191
|
+
from,
|
|
192
|
+
to,
|
|
193
|
+
cc,
|
|
194
|
+
replyTo,
|
|
195
|
+
subject,
|
|
196
|
+
headers,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Only the topmost Authentication-Results header counts, and only when the
|
|
202
|
+
* host that added it is trusted: a forged one deeper down is never read.
|
|
203
|
+
*/
|
|
204
|
+
function trustedAuthResults(
|
|
205
|
+
headers: { name: string; value: string }[],
|
|
206
|
+
trusted: string[] | undefined,
|
|
207
|
+
): string | undefined {
|
|
208
|
+
const ids = new Set(
|
|
209
|
+
(trusted ?? []).map((t) => t.trim().toLowerCase()).filter(Boolean),
|
|
210
|
+
);
|
|
211
|
+
if (ids.size === 0) return undefined;
|
|
212
|
+
const top = headers.find(
|
|
213
|
+
(h) => h.name.toLowerCase() === "authentication-results",
|
|
214
|
+
);
|
|
215
|
+
if (!top) return undefined;
|
|
216
|
+
const id = top.value.trim().split(/[\s;]/)[0]?.toLowerCase() ?? "";
|
|
217
|
+
return ids.has(id) ? top.value : undefined;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const hex = (buf: ArrayBuffer) =>
|
|
221
|
+
Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join(
|
|
222
|
+
"",
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
/** SHA-256 over subject, bodies and each attachment's name, size and bytes. */
|
|
226
|
+
async function contentHash(p: ParsedInbound): Promise<string> {
|
|
227
|
+
const parts = await Promise.all(
|
|
228
|
+
p.attachments.map(
|
|
229
|
+
async (a) =>
|
|
230
|
+
[
|
|
231
|
+
a.filename,
|
|
232
|
+
a.content.byteLength,
|
|
233
|
+
hex(await crypto.subtle.digest("SHA-256", a.content)),
|
|
234
|
+
] as const,
|
|
235
|
+
),
|
|
236
|
+
);
|
|
237
|
+
const data = new TextEncoder().encode(
|
|
238
|
+
JSON.stringify([p.subject, p.text ?? null, p.html ?? null, parts]),
|
|
239
|
+
);
|
|
240
|
+
return hex(await crypto.subtle.digest("SHA-256", data));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function enqueueProcess(
|
|
244
|
+
ctx: MutationCtx,
|
|
245
|
+
inboundId: Id<"inbound">,
|
|
246
|
+
runAfter?: number,
|
|
247
|
+
): Promise<unknown> {
|
|
248
|
+
return callbacks.enqueueAction(
|
|
249
|
+
ctx,
|
|
250
|
+
internal.inbound.process,
|
|
251
|
+
{ inboundId },
|
|
252
|
+
{
|
|
253
|
+
onComplete: internal.inbound.processed,
|
|
254
|
+
context: { inboundId },
|
|
255
|
+
...(runAfter === undefined ? {} : { runAfter }),
|
|
256
|
+
},
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Record an inbound notification and queue its processing. A second
|
|
262
|
+
* notification for the same `(tenant, provider, providerId)` is a no-op.
|
|
263
|
+
*/
|
|
264
|
+
export const accept = internalMutation({
|
|
265
|
+
args: {
|
|
266
|
+
provider: vInboundProvider,
|
|
267
|
+
tenant: v.optional(v.string()),
|
|
268
|
+
notification: vInboundNotification,
|
|
269
|
+
},
|
|
270
|
+
returns: v.object({ created: v.boolean() }),
|
|
271
|
+
handler: async (ctx, { provider, tenant, notification }) => {
|
|
272
|
+
const seen = await ctx.db
|
|
273
|
+
.query("inbound")
|
|
274
|
+
.withIndex("by_tenant_provider_providerId", (q) =>
|
|
275
|
+
q
|
|
276
|
+
.eq("tenant", tenant)
|
|
277
|
+
.eq("provider", provider)
|
|
278
|
+
.eq("providerId", notification.providerId),
|
|
279
|
+
)
|
|
280
|
+
.first();
|
|
281
|
+
if (seen) return { created: false };
|
|
282
|
+
const inboundId = await ctx.db.insert("inbound", {
|
|
283
|
+
provider,
|
|
284
|
+
providerId: notification.providerId,
|
|
285
|
+
tenant,
|
|
286
|
+
notification,
|
|
287
|
+
state: "received",
|
|
288
|
+
});
|
|
289
|
+
await enqueueProcess(ctx, inboundId);
|
|
290
|
+
return { created: true };
|
|
291
|
+
},
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
export const acceptRaw = internalMutation({
|
|
295
|
+
args: {
|
|
296
|
+
tenant: v.optional(v.string()),
|
|
297
|
+
source: v.string(),
|
|
298
|
+
rawStorageId: v.id("_storage"),
|
|
299
|
+
verdicts: v.optional(vVerdicts),
|
|
300
|
+
},
|
|
301
|
+
returns: v.id("inbound"),
|
|
302
|
+
handler: async (ctx, { tenant, source, rawStorageId, verdicts }) => {
|
|
303
|
+
const inboundId = await ctx.db.insert("inbound", {
|
|
304
|
+
provider: "raw",
|
|
305
|
+
tenant,
|
|
306
|
+
source,
|
|
307
|
+
rawStorageId,
|
|
308
|
+
verdicts,
|
|
309
|
+
state: "received",
|
|
310
|
+
});
|
|
311
|
+
await enqueueProcess(ctx, inboundId);
|
|
312
|
+
return inboundId;
|
|
313
|
+
},
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Hand in a raw RFC 822 message the app already holds. Runs the same pipeline
|
|
318
|
+
* as a provider notification; the bytes are stored first because processing
|
|
319
|
+
* reads them back, and deleted afterwards unless `keepRawMime`.
|
|
320
|
+
*/
|
|
321
|
+
export const receiveRaw = action({
|
|
322
|
+
args: {
|
|
323
|
+
config: vRuntimeConfig,
|
|
324
|
+
mime: v.bytes(),
|
|
325
|
+
tenant: v.optional(v.string()),
|
|
326
|
+
source: v.string(),
|
|
327
|
+
verdicts: v.optional(vVerdicts),
|
|
328
|
+
},
|
|
329
|
+
returns: v.id("inbound"),
|
|
330
|
+
handler: async (
|
|
331
|
+
ctx,
|
|
332
|
+
{ config, mime, tenant, source, verdicts },
|
|
333
|
+
): Promise<Id<"inbound">> => {
|
|
334
|
+
await ctx.runMutation(internal.config.upsert, { config });
|
|
335
|
+
const rawStorageId = await ctx.storage.store(
|
|
336
|
+
new Blob([mime], { type: "message/rfc822" }),
|
|
337
|
+
);
|
|
338
|
+
return await ctx.runMutation(internal.inbound.acceptRaw, {
|
|
339
|
+
tenant: tenant ?? config.defaultTenant,
|
|
340
|
+
source,
|
|
341
|
+
rawStorageId,
|
|
342
|
+
verdicts,
|
|
343
|
+
});
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
export const load = internalQuery({
|
|
348
|
+
args: { inboundId: v.id("inbound") },
|
|
349
|
+
handler: async (ctx, { inboundId }) => {
|
|
350
|
+
const row = await ctx.db.get(inboundId);
|
|
351
|
+
if (!row) return null;
|
|
352
|
+
return { row, config: await getConfig(ctx) };
|
|
353
|
+
},
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
async function obtain(
|
|
357
|
+
ctx: ActionCtx,
|
|
358
|
+
row: Doc<"inbound">,
|
|
359
|
+
config: Doc<"config">,
|
|
360
|
+
secrets: string[],
|
|
361
|
+
): Promise<ParsedInbound> {
|
|
362
|
+
if (row.provider === "raw") {
|
|
363
|
+
if (!row.rawStorageId) throw new Error("raw message is missing");
|
|
364
|
+
const blob = await ctx.storage.get(row.rawStorageId);
|
|
365
|
+
if (!blob) throw new Error("raw message is missing from storage");
|
|
366
|
+
return await parseMime(await blob.arrayBuffer());
|
|
367
|
+
}
|
|
368
|
+
const provider: ProviderName = row.provider;
|
|
369
|
+
if (!row.notification) throw new Error("inbound notification is missing");
|
|
370
|
+
const creds = await fetchCredentials(ctx, config, {
|
|
371
|
+
provider,
|
|
372
|
+
tenant: row.tenant,
|
|
373
|
+
purpose: "fetchInbound",
|
|
374
|
+
});
|
|
375
|
+
if ((creds as { provider?: unknown } | null)?.provider !== provider) {
|
|
376
|
+
throw new Error(`credentials provider mismatch: expected ${provider}`);
|
|
377
|
+
}
|
|
378
|
+
secrets.push(...secretStrings(creds));
|
|
379
|
+
return await getAdapter(provider).fetchInbound(creds, row.notification);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
type Stored = {
|
|
383
|
+
storageId: Id<"_storage">;
|
|
384
|
+
filename: string;
|
|
385
|
+
contentType: string;
|
|
386
|
+
size: number;
|
|
387
|
+
contentId?: string;
|
|
388
|
+
disposition: "attachment" | "inline";
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Fetch (or read) and parse the message, clean and store its parts, then hand
|
|
393
|
+
* it to `commit`. Any failure is recorded on the row, never thrown away.
|
|
394
|
+
*/
|
|
395
|
+
export const process = internalAction({
|
|
396
|
+
args: { inboundId: v.id("inbound") },
|
|
397
|
+
handler: async (ctx, { inboundId }): Promise<null> => {
|
|
398
|
+
const loaded = await ctx.runQuery(internal.inbound.load, { inboundId });
|
|
399
|
+
if (loaded?.row.state !== "received") return null;
|
|
400
|
+
const { row, config } = loaded;
|
|
401
|
+
const secrets: string[] = [];
|
|
402
|
+
const storedIds: Id<"_storage">[] = [];
|
|
403
|
+
let fetching = false;
|
|
404
|
+
try {
|
|
405
|
+
if (!config) throw new Error("inbound config missing");
|
|
406
|
+
if (row.provider !== "raw" && !row.notification) {
|
|
407
|
+
throw new Error("inbound notification is missing");
|
|
408
|
+
}
|
|
409
|
+
fetching = row.provider !== "raw";
|
|
410
|
+
const parsed = await obtain(ctx, row, config, secrets);
|
|
411
|
+
fetching = false;
|
|
412
|
+
|
|
413
|
+
// Notification (or caller) verdicts win, then verdicts the provider
|
|
414
|
+
// returned with the fetch; else a trusted host's header.
|
|
415
|
+
let verdicts: { spf?: Verdict; dkim?: Verdict; dmarc?: Verdict } = {};
|
|
416
|
+
let verdictsSource: string | undefined;
|
|
417
|
+
// Explicit verdicts, even `{}`, are authoritative: no header is read.
|
|
418
|
+
const given =
|
|
419
|
+
row.provider === "raw" ? row.verdicts : row.notification?.verdicts;
|
|
420
|
+
if (given !== undefined) {
|
|
421
|
+
verdicts = given;
|
|
422
|
+
verdictsSource = row.provider === "raw" ? row.source : "provider";
|
|
423
|
+
} else if (parsed.verdicts !== undefined) {
|
|
424
|
+
verdicts = parsed.verdicts;
|
|
425
|
+
verdictsSource = "provider";
|
|
426
|
+
} else {
|
|
427
|
+
const header = trustedAuthResults(
|
|
428
|
+
parsed.headers,
|
|
429
|
+
config.trustedAuthServIds,
|
|
430
|
+
);
|
|
431
|
+
const fromHeader = parseAuthenticationResults(header);
|
|
432
|
+
if (fromHeader.spf || fromHeader.dkim || fromHeader.dmarc) {
|
|
433
|
+
verdicts = fromHeader;
|
|
434
|
+
verdictsSource = "authentication-results";
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
const hash = await contentHash(parsed);
|
|
438
|
+
const b = bound(parsed);
|
|
439
|
+
|
|
440
|
+
let html: string | undefined;
|
|
441
|
+
let hasRemoteImages = false;
|
|
442
|
+
if (parsed.html !== undefined) {
|
|
443
|
+
const clean = sanitizeInboundHtml(parsed.html);
|
|
444
|
+
html = clean.html;
|
|
445
|
+
hasRemoteImages = clean.hasRemoteImages;
|
|
446
|
+
}
|
|
447
|
+
// HTML-only mail (no text part, or a blank one) gets its text from the
|
|
448
|
+
// RAW html: the sanitiser keeps the text of tags it drops (title) and
|
|
449
|
+
// strips the styles that hide a preheader. Plain text is never rendered.
|
|
450
|
+
let text = parsed.text;
|
|
451
|
+
let textFromHtml = false;
|
|
452
|
+
let derivedCut = false;
|
|
453
|
+
const raw = parsed.html;
|
|
454
|
+
if (raw !== undefined && (text === undefined || text.trim() === "")) {
|
|
455
|
+
const source =
|
|
456
|
+
raw.length > MAX_DERIVED_HTML
|
|
457
|
+
? cutBytes(raw.slice(0, MAX_DERIVED_HTML), MAX_DERIVED_HTML)
|
|
458
|
+
: raw;
|
|
459
|
+
const derived = htmlToText(source);
|
|
460
|
+
if (derived !== "") {
|
|
461
|
+
text = cutBytes(derived, MAX_DERIVED_TEXT);
|
|
462
|
+
derivedCut =
|
|
463
|
+
source.length !== raw.length || text.length !== derived.length;
|
|
464
|
+
textFromHtml = true;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const store = async (data: BlobPart, type: string) => {
|
|
469
|
+
const id = await ctx.storage.store(new Blob([data], { type }));
|
|
470
|
+
storedIds.push(id);
|
|
471
|
+
return id;
|
|
472
|
+
};
|
|
473
|
+
const textStorageId =
|
|
474
|
+
text === undefined ? undefined : await store(text, "text/plain");
|
|
475
|
+
const htmlStorageId =
|
|
476
|
+
html === undefined ? undefined : await store(html, "text/html");
|
|
477
|
+
const attachments: Stored[] = [];
|
|
478
|
+
for (const a of b.attachments) {
|
|
479
|
+
attachments.push({
|
|
480
|
+
storageId: await store(a.content, a.contentType),
|
|
481
|
+
filename: a.filename,
|
|
482
|
+
contentType: a.contentType,
|
|
483
|
+
size: a.content.byteLength,
|
|
484
|
+
contentId: a.contentId,
|
|
485
|
+
disposition: a.disposition,
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const bodyByReference = bytes(text) + bytes(html) > BODY_INLINE_LIMIT;
|
|
490
|
+
await ctx.runMutation(internal.inbound.commit, {
|
|
491
|
+
inboundId,
|
|
492
|
+
rfcMessageId: b.rfcMessageId,
|
|
493
|
+
inReplyTo: b.inReplyTo,
|
|
494
|
+
references: b.references,
|
|
495
|
+
from: b.from,
|
|
496
|
+
to: b.to,
|
|
497
|
+
cc: b.cc,
|
|
498
|
+
replyTo: b.replyTo,
|
|
499
|
+
subject: b.subject,
|
|
500
|
+
headers: b.headers,
|
|
501
|
+
contentHash: hash,
|
|
502
|
+
truncated: b.truncated || derivedCut,
|
|
503
|
+
...(textFromHtml ? { textFromHtml: true as const } : {}),
|
|
504
|
+
textStorageId,
|
|
505
|
+
htmlStorageId,
|
|
506
|
+
hasRemoteImages,
|
|
507
|
+
verdicts,
|
|
508
|
+
verdictsSource,
|
|
509
|
+
attachments,
|
|
510
|
+
inline: bodyByReference ? undefined : { text, html },
|
|
511
|
+
});
|
|
512
|
+
} catch (e) {
|
|
513
|
+
for (const id of storedIds) {
|
|
514
|
+
try {
|
|
515
|
+
await ctx.storage.delete(id);
|
|
516
|
+
} catch {
|
|
517
|
+
// Already gone.
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const failure = truncate(redact(errorText(e), secrets), MAX_FAILURE);
|
|
521
|
+
// A provider fetch may fail for a moment only: try again on a schedule.
|
|
522
|
+
await ctx.runMutation(
|
|
523
|
+
fetching ? internal.inbound.fetchFailed : internal.inbound.fail,
|
|
524
|
+
{ inboundId, failure },
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
return null;
|
|
528
|
+
},
|
|
529
|
+
});
|
|
530
|
+
|
|
531
|
+
export const fetchFailed = internalMutation({
|
|
532
|
+
args: { inboundId: v.id("inbound"), failure: v.string() },
|
|
533
|
+
handler: async (ctx, { inboundId, failure }): Promise<null> => {
|
|
534
|
+
const row = await ctx.db.get(inboundId);
|
|
535
|
+
if (row?.state !== "received") return null;
|
|
536
|
+
const attempts = row.attempts ?? 0;
|
|
537
|
+
const wait = FETCH_RETRY_MS[attempts];
|
|
538
|
+
if (wait === undefined) {
|
|
539
|
+
await ctx.db.patch(inboundId, { state: "failed", failure });
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
await ctx.db.patch(inboundId, { attempts: attempts + 1 });
|
|
543
|
+
// Through the pool, so its onComplete covers a run that dies outside try.
|
|
544
|
+
await enqueueProcess(ctx, inboundId, wait);
|
|
545
|
+
return null;
|
|
546
|
+
},
|
|
547
|
+
});
|
|
548
|
+
|
|
549
|
+
export const fail = internalMutation({
|
|
550
|
+
args: { inboundId: v.id("inbound"), failure: v.string() },
|
|
551
|
+
handler: async (ctx, { inboundId, failure }): Promise<null> => {
|
|
552
|
+
const row = await ctx.db.get(inboundId);
|
|
553
|
+
if (!row || (row.state !== "received" && row.state !== "fetched")) {
|
|
554
|
+
return null;
|
|
555
|
+
}
|
|
556
|
+
await ctx.db.patch(inboundId, { state: "failed", failure });
|
|
557
|
+
return null;
|
|
558
|
+
},
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
/** Terminal outcome of `process`: catches runs that ended by throwing. */
|
|
562
|
+
export const processed = internalMutation({
|
|
563
|
+
args: vOnCompleteArgs(v.object({ inboundId: v.id("inbound") })),
|
|
564
|
+
handler: async (ctx, { context, result }): Promise<null> => {
|
|
565
|
+
if (result.kind === "success") return null;
|
|
566
|
+
const row = await ctx.db.get(context.inboundId);
|
|
567
|
+
if (row?.state !== "received") return null;
|
|
568
|
+
const failure =
|
|
569
|
+
result.kind === "failed"
|
|
570
|
+
? truncate(result.error, MAX_FAILURE)
|
|
571
|
+
: "processing was canceled";
|
|
572
|
+
await ctx.db.patch(context.inboundId, { state: "failed", failure });
|
|
573
|
+
return null;
|
|
574
|
+
},
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
type Candidates = {
|
|
578
|
+
/** The nearest stored message of either direction, for the thread id. */
|
|
579
|
+
thread: Doc<"messages"> | null;
|
|
580
|
+
/** The nearest of OUR messages it answers, for the app. */
|
|
581
|
+
outbound: Doc<"messages"> | null;
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
/** Nearest first: In-Reply-To, then References from the last. */
|
|
585
|
+
const candidateIds = (inReplyTo: string | undefined, references: string[]) =>
|
|
586
|
+
[
|
|
587
|
+
...new Set([
|
|
588
|
+
...(inReplyTo ? [inReplyTo] : []),
|
|
589
|
+
...[...references].reverse(),
|
|
590
|
+
]),
|
|
591
|
+
].slice(0, MAX_THREAD_CANDIDATES);
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Mail that arrived with no tenant (an account-level route and no default)
|
|
595
|
+
* answering one of our messages takes that message's tenant, but only when
|
|
596
|
+
* its From is one of that message's recipients: anyone can quote one of our
|
|
597
|
+
* Message-IDs. Only the nearest cited id that matches our outbound mail
|
|
598
|
+
* counts, and only when exactly one outbound message carries it.
|
|
599
|
+
*/
|
|
600
|
+
async function adoptTenant(
|
|
601
|
+
ctx: Pick<MutationCtx, "db">,
|
|
602
|
+
from: string,
|
|
603
|
+
inReplyTo: string | undefined,
|
|
604
|
+
references: string[],
|
|
605
|
+
): Promise<string | undefined> {
|
|
606
|
+
for (const id of candidateIds(inReplyTo, references)) {
|
|
607
|
+
const outbound = (
|
|
608
|
+
await ctx.db
|
|
609
|
+
.query("messages")
|
|
610
|
+
.withIndex("by_rfcMessageId", (q) => q.eq("rfcMessageId", id))
|
|
611
|
+
.take(MAX_SAME_ID)
|
|
612
|
+
).filter((m) => m.direction === "outbound");
|
|
613
|
+
if (outbound.length === 0) continue;
|
|
614
|
+
const [parent] = outbound;
|
|
615
|
+
if (outbound.length !== 1 || !parent) return undefined;
|
|
616
|
+
const sender = normalizeAddress(from);
|
|
617
|
+
const recipients = [...parent.to, ...parent.cc, ...parent.bcc];
|
|
618
|
+
return recipients.some((r) => normalizeAddress(r) === sender)
|
|
619
|
+
? parent.tenant
|
|
620
|
+
: undefined;
|
|
621
|
+
}
|
|
622
|
+
return undefined;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
async function findParents(
|
|
626
|
+
ctx: Pick<MutationCtx, "db">,
|
|
627
|
+
tenant: string | undefined,
|
|
628
|
+
inReplyTo: string | undefined,
|
|
629
|
+
references: string[],
|
|
630
|
+
): Promise<Candidates> {
|
|
631
|
+
const ids = candidateIds(inReplyTo, references);
|
|
632
|
+
let thread: Doc<"messages"> | null = null;
|
|
633
|
+
let outbound: Doc<"messages"> | null = null;
|
|
634
|
+
for (const id of ids) {
|
|
635
|
+
const same = await ctx.db
|
|
636
|
+
.query("messages")
|
|
637
|
+
.withIndex("by_tenant_rfcMessageId", (q) =>
|
|
638
|
+
q.eq("tenant", tenant).eq("rfcMessageId", id),
|
|
639
|
+
)
|
|
640
|
+
.take(MAX_SAME_ID);
|
|
641
|
+
for (const m of same) {
|
|
642
|
+
thread ??= m;
|
|
643
|
+
if (m.direction === "outbound") outbound ??= m;
|
|
644
|
+
}
|
|
645
|
+
if (thread && outbound) break;
|
|
646
|
+
}
|
|
647
|
+
return { thread, outbound };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const vStored = v.object({
|
|
651
|
+
storageId: v.id("_storage"),
|
|
652
|
+
filename: v.string(),
|
|
653
|
+
contentType: v.string(),
|
|
654
|
+
size: v.number(),
|
|
655
|
+
contentId: v.optional(v.string()),
|
|
656
|
+
disposition: vDisposition,
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
async function buildForApp(
|
|
660
|
+
ctx: MutationCtx,
|
|
661
|
+
row: Doc<"inbound">,
|
|
662
|
+
message: Doc<"messages">,
|
|
663
|
+
body: { text?: string; html?: string; byReference: boolean },
|
|
664
|
+
): Promise<InboundForApp> {
|
|
665
|
+
const attachments = await ctx.db
|
|
666
|
+
.query("attachments")
|
|
667
|
+
.withIndex("by_message", (q) => q.eq("messageId", message._id))
|
|
668
|
+
.collect();
|
|
669
|
+
const { outbound } = await findParents(
|
|
670
|
+
ctx,
|
|
671
|
+
message.tenant,
|
|
672
|
+
message.inReplyTo,
|
|
673
|
+
message.references,
|
|
674
|
+
);
|
|
675
|
+
const bare = (address: string): Addr => ({ address });
|
|
676
|
+
const addrs = message.addrs ?? {
|
|
677
|
+
from: bare(message.from),
|
|
678
|
+
to: message.to.map(bare),
|
|
679
|
+
cc: message.cc.map(bare),
|
|
680
|
+
};
|
|
681
|
+
const recipients = outbound
|
|
682
|
+
? [...outbound.to, ...outbound.cc, ...outbound.bcc].map(normalizeAddress)
|
|
683
|
+
: [];
|
|
684
|
+
return {
|
|
685
|
+
messageId: message._id,
|
|
686
|
+
...(message.tenant === undefined ? {} : { tenant: message.tenant }),
|
|
687
|
+
provider: row.provider,
|
|
688
|
+
from: addrs.from,
|
|
689
|
+
to: addrs.to,
|
|
690
|
+
cc: addrs.cc,
|
|
691
|
+
subject: message.subject,
|
|
692
|
+
...(body.byReference || body.text === undefined ? {} : { text: body.text }),
|
|
693
|
+
...(message.textFromHtml ? { textFromHtml: true as const } : {}),
|
|
694
|
+
...(body.byReference || body.html === undefined ? {} : { html: body.html }),
|
|
695
|
+
bodyByReference: body.byReference,
|
|
696
|
+
hasRemoteImages: message.hasRemoteImages ?? false,
|
|
697
|
+
attachments: attachments.map((a) => ({
|
|
698
|
+
id: a._id,
|
|
699
|
+
filename: a.filename,
|
|
700
|
+
contentType: a.contentType,
|
|
701
|
+
size: a.size,
|
|
702
|
+
})),
|
|
703
|
+
verdicts: message.verdicts ?? {},
|
|
704
|
+
threadId: message.threadId,
|
|
705
|
+
...(message.truncated ? { truncated: true } : {}),
|
|
706
|
+
...(message.tenantAdopted ? { tenantAdopted: true as const } : {}),
|
|
707
|
+
...(outbound
|
|
708
|
+
? {
|
|
709
|
+
parent: {
|
|
710
|
+
messageId: outbound._id,
|
|
711
|
+
tags: outbound.tags,
|
|
712
|
+
senderWasRecipient: recipients.includes(
|
|
713
|
+
normalizeAddress(addrs.from.address),
|
|
714
|
+
),
|
|
715
|
+
},
|
|
716
|
+
}
|
|
717
|
+
: {}),
|
|
718
|
+
headers: message.headers,
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Hand the message to the app's handler, or keep it `unhandled`. */
|
|
723
|
+
async function route(
|
|
724
|
+
ctx: MutationCtx,
|
|
725
|
+
inboundId: Id<"inbound">,
|
|
726
|
+
forApp: InboundForApp,
|
|
727
|
+
config: Doc<"config"> | null,
|
|
728
|
+
note?: string,
|
|
729
|
+
): Promise<void> {
|
|
730
|
+
if (!config?.onInboundHandle) {
|
|
731
|
+
await ctx.db.patch(inboundId, {
|
|
732
|
+
state: "unhandled",
|
|
733
|
+
appNote: note
|
|
734
|
+
? `${note}; no onInbound handler configured`
|
|
735
|
+
: "no onInbound handler configured",
|
|
736
|
+
});
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
const handler = config.onInboundHandle as unknown as FunctionReference<
|
|
740
|
+
"mutation",
|
|
741
|
+
"internal",
|
|
742
|
+
InboundForApp,
|
|
743
|
+
unknown
|
|
744
|
+
>;
|
|
745
|
+
await ctx.db.patch(inboundId, { state: "fetched", appNote: note });
|
|
746
|
+
await callbacks.enqueueMutation(ctx, handler, forApp, {
|
|
747
|
+
onComplete: internal.inbound.handlerDone,
|
|
748
|
+
context: { inboundId },
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
export const commit = internalMutation({
|
|
753
|
+
args: {
|
|
754
|
+
inboundId: v.id("inbound"),
|
|
755
|
+
rfcMessageId: v.optional(v.string()),
|
|
756
|
+
inReplyTo: v.optional(v.string()),
|
|
757
|
+
references: v.array(v.string()),
|
|
758
|
+
from: vAddr,
|
|
759
|
+
to: v.array(vAddr),
|
|
760
|
+
cc: v.array(vAddr),
|
|
761
|
+
replyTo: v.array(vAddr),
|
|
762
|
+
subject: v.string(),
|
|
763
|
+
headers: v.array(v.object({ name: v.string(), value: v.string() })),
|
|
764
|
+
contentHash: v.string(),
|
|
765
|
+
truncated: v.boolean(),
|
|
766
|
+
textFromHtml: v.optional(v.literal(true)),
|
|
767
|
+
textStorageId: v.optional(v.id("_storage")),
|
|
768
|
+
htmlStorageId: v.optional(v.id("_storage")),
|
|
769
|
+
hasRemoteImages: v.boolean(),
|
|
770
|
+
verdicts: vVerdicts,
|
|
771
|
+
verdictsSource: v.optional(v.string()),
|
|
772
|
+
attachments: v.array(vStored),
|
|
773
|
+
/** Present only when the bodies are small enough to pass inline. */
|
|
774
|
+
inline: v.optional(
|
|
775
|
+
v.object({ text: v.optional(v.string()), html: v.optional(v.string()) }),
|
|
776
|
+
),
|
|
777
|
+
},
|
|
778
|
+
handler: async (ctx, args): Promise<null> => {
|
|
779
|
+
const row = await ctx.db.get(args.inboundId);
|
|
780
|
+
if (row?.state !== "received") return null;
|
|
781
|
+
const config = await getConfig(ctx);
|
|
782
|
+
const adopted =
|
|
783
|
+
row.tenant === undefined
|
|
784
|
+
? await adoptTenant(
|
|
785
|
+
ctx,
|
|
786
|
+
args.from.address,
|
|
787
|
+
args.inReplyTo,
|
|
788
|
+
args.references,
|
|
789
|
+
)
|
|
790
|
+
: undefined;
|
|
791
|
+
const tenant = row.tenant ?? adopted;
|
|
792
|
+
// No Message-ID of its own: a stable placeholder keyed by the row.
|
|
793
|
+
const rfcMessageId =
|
|
794
|
+
args.rfcMessageId ?? `<inbound-${row._id}@convex-email.invalid>`;
|
|
795
|
+
|
|
796
|
+
// The row's raw bytes are kept only when the app asked for them.
|
|
797
|
+
const rawKept = row.rawStorageId && config?.keepRawMime;
|
|
798
|
+
const dropRaw = async () => {
|
|
799
|
+
if (row.rawStorageId && !rawKept) {
|
|
800
|
+
await ctx.storage.delete(row.rawStorageId);
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
const rawPatch = rawKept ? {} : { rawStorageId: undefined };
|
|
804
|
+
|
|
805
|
+
// Only INBOUND mail can duplicate: our own outbound copy looping back is
|
|
806
|
+
// not one. A duplicate has the same sender and content as well; a reused
|
|
807
|
+
// Message-ID with either different is stored as its own message.
|
|
808
|
+
let reused = false;
|
|
809
|
+
const same = await ctx.db
|
|
810
|
+
.query("messages")
|
|
811
|
+
.withIndex("by_tenant_rfcMessageId", (q) =>
|
|
812
|
+
q.eq("tenant", tenant).eq("rfcMessageId", rfcMessageId),
|
|
813
|
+
)
|
|
814
|
+
.take(MAX_SAME_ID);
|
|
815
|
+
for (const m of same) {
|
|
816
|
+
if (m.direction !== "inbound") continue;
|
|
817
|
+
if (
|
|
818
|
+
normalizeAddress(m.from) !== normalizeAddress(args.from.address) ||
|
|
819
|
+
m.contentHash !== args.contentHash
|
|
820
|
+
) {
|
|
821
|
+
reused = true;
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
for (const id of [
|
|
825
|
+
args.textStorageId,
|
|
826
|
+
args.htmlStorageId,
|
|
827
|
+
...args.attachments.map((a) => a.storageId),
|
|
828
|
+
]) {
|
|
829
|
+
if (id) await ctx.storage.delete(id);
|
|
830
|
+
}
|
|
831
|
+
await dropRaw();
|
|
832
|
+
await ctx.db.patch(row._id, {
|
|
833
|
+
tenant,
|
|
834
|
+
state: "handled",
|
|
835
|
+
messageId: m._id,
|
|
836
|
+
failure: undefined,
|
|
837
|
+
appNote: "duplicate of a stored message with the same Message-ID",
|
|
838
|
+
...rawPatch,
|
|
839
|
+
});
|
|
840
|
+
return null;
|
|
841
|
+
}
|
|
842
|
+
const note = reused ? REUSED_NOTE : undefined;
|
|
843
|
+
|
|
844
|
+
const { thread } = await findParents(
|
|
845
|
+
ctx,
|
|
846
|
+
tenant,
|
|
847
|
+
args.inReplyTo,
|
|
848
|
+
args.references,
|
|
849
|
+
);
|
|
850
|
+
const threadId =
|
|
851
|
+
thread?.threadId ?? args.references[0] ?? args.inReplyTo ?? rfcMessageId;
|
|
852
|
+
|
|
853
|
+
const now = Date.now();
|
|
854
|
+
const messageId = await ctx.db.insert("messages", {
|
|
855
|
+
direction: "inbound",
|
|
856
|
+
provider: row.provider,
|
|
857
|
+
tenant,
|
|
858
|
+
inboundId: row._id,
|
|
859
|
+
// Streams are an outbound lane; this value is not meaningful here.
|
|
860
|
+
stream: "transactional",
|
|
861
|
+
from: args.from.address,
|
|
862
|
+
to: args.to.map((a) => a.address),
|
|
863
|
+
cc: args.cc.map((a) => a.address),
|
|
864
|
+
bcc: [],
|
|
865
|
+
replyTo: args.replyTo.map((a) => a.address),
|
|
866
|
+
addrs: { from: args.from, to: args.to, cc: args.cc },
|
|
867
|
+
contentHash: args.contentHash,
|
|
868
|
+
...(args.truncated ? { truncated: true } : {}),
|
|
869
|
+
...(args.textFromHtml ? { textFromHtml: true as const } : {}),
|
|
870
|
+
...(reused ? { messageIdReused: true } : {}),
|
|
871
|
+
...(adopted !== undefined ? { tenantAdopted: true as const } : {}),
|
|
872
|
+
subject: args.subject,
|
|
873
|
+
htmlStorageId: args.htmlStorageId,
|
|
874
|
+
textStorageId: args.textStorageId,
|
|
875
|
+
headers: args.headers,
|
|
876
|
+
rfcMessageId,
|
|
877
|
+
inReplyTo: args.inReplyTo,
|
|
878
|
+
references: args.references,
|
|
879
|
+
threadId,
|
|
880
|
+
status: "received",
|
|
881
|
+
tags: {},
|
|
882
|
+
suppressedRecipients: [],
|
|
883
|
+
verdicts: args.verdicts,
|
|
884
|
+
verdictsSource: args.verdictsSource,
|
|
885
|
+
hasRemoteImages: args.hasRemoteImages,
|
|
886
|
+
createdAt: now,
|
|
887
|
+
updatedAt: now,
|
|
888
|
+
});
|
|
889
|
+
for (const a of args.attachments) {
|
|
890
|
+
await ctx.db.insert("attachments", { ...a, messageId, tenant });
|
|
891
|
+
}
|
|
892
|
+
await dropRaw();
|
|
893
|
+
await ctx.db.patch(row._id, {
|
|
894
|
+
tenant,
|
|
895
|
+
messageId,
|
|
896
|
+
failure: undefined,
|
|
897
|
+
...rawPatch,
|
|
898
|
+
});
|
|
899
|
+
|
|
900
|
+
const message = await ctx.db.get(messageId);
|
|
901
|
+
if (!message) throw new Error("inbound message vanished");
|
|
902
|
+
const forApp = await buildForApp(ctx, row, message, {
|
|
903
|
+
text: args.inline?.text,
|
|
904
|
+
html: args.inline?.html,
|
|
905
|
+
byReference: args.inline === undefined,
|
|
906
|
+
});
|
|
907
|
+
await route(ctx, row._id, forApp, config, note);
|
|
908
|
+
return null;
|
|
909
|
+
},
|
|
910
|
+
});
|
|
911
|
+
|
|
912
|
+
/** The app handler's outcome: `{ handled: true }` or the message stays kept. */
|
|
913
|
+
export const handlerDone = internalMutation({
|
|
914
|
+
args: vOnCompleteArgs(v.object({ inboundId: v.id("inbound") })),
|
|
915
|
+
handler: async (ctx, { context, result }): Promise<null> => {
|
|
916
|
+
const row = await ctx.db.get(context.inboundId);
|
|
917
|
+
if (row?.state !== "fetched") return null;
|
|
918
|
+
if (result.kind === "success") {
|
|
919
|
+
const answer =
|
|
920
|
+
typeof result.returnValue === "object" && result.returnValue !== null
|
|
921
|
+
? (result.returnValue as { handled?: unknown; note?: unknown })
|
|
922
|
+
: {};
|
|
923
|
+
// The app's `note` is kept, after any note the component already made.
|
|
924
|
+
const appNote =
|
|
925
|
+
typeof answer.note === "string" && answer.note !== ""
|
|
926
|
+
? truncate(
|
|
927
|
+
row.appNote ? `${row.appNote}; ${answer.note}` : answer.note,
|
|
928
|
+
MAX_NOTE,
|
|
929
|
+
)
|
|
930
|
+
: row.appNote;
|
|
931
|
+
await ctx.db.patch(row._id, {
|
|
932
|
+
state: answer.handled === true ? "handled" : "unhandled",
|
|
933
|
+
appNote,
|
|
934
|
+
});
|
|
935
|
+
return null;
|
|
936
|
+
}
|
|
937
|
+
await ctx.db.patch(row._id, {
|
|
938
|
+
state: "unhandled",
|
|
939
|
+
appNote: truncate(
|
|
940
|
+
result.kind === "failed" ? result.error : "handler was canceled",
|
|
941
|
+
MAX_NOTE,
|
|
942
|
+
),
|
|
943
|
+
});
|
|
944
|
+
return null;
|
|
945
|
+
},
|
|
946
|
+
});
|
|
947
|
+
|
|
948
|
+
const vInboundView = v.object({
|
|
949
|
+
id: v.id("inbound"),
|
|
950
|
+
provider: vInboundProvider,
|
|
951
|
+
providerId: v.optional(v.string()),
|
|
952
|
+
tenant: v.optional(v.string()),
|
|
953
|
+
source: v.optional(v.string()),
|
|
954
|
+
state: vInboundState,
|
|
955
|
+
receivedAt: v.number(),
|
|
956
|
+
messageId: v.optional(v.id("messages")),
|
|
957
|
+
from: v.optional(v.string()),
|
|
958
|
+
subject: v.optional(v.string()),
|
|
959
|
+
failure: v.optional(v.string()),
|
|
960
|
+
appNote: v.optional(v.string()),
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
/** Inbound mail the app did not handle, or that could not be processed. */
|
|
964
|
+
export const listUnhandled = query({
|
|
965
|
+
args: { tenant: v.optional(v.string()), limit: v.number() },
|
|
966
|
+
returns: v.array(vInboundView),
|
|
967
|
+
handler: async (ctx, { tenant, limit }) => {
|
|
968
|
+
if (!Number.isInteger(limit) || limit < 1) {
|
|
969
|
+
throw new Error("limit must be a positive integer");
|
|
970
|
+
}
|
|
971
|
+
const scope = tenant ?? (await getConfig(ctx))?.defaultTenant;
|
|
972
|
+
const rows: Doc<"inbound">[] = [];
|
|
973
|
+
for (const state of ["unhandled", "failed"] as const) {
|
|
974
|
+
rows.push(
|
|
975
|
+
...(await ctx.db
|
|
976
|
+
.query("inbound")
|
|
977
|
+
.withIndex("by_tenant_state", (q) =>
|
|
978
|
+
q.eq("tenant", scope).eq("state", state),
|
|
979
|
+
)
|
|
980
|
+
.take(limit)),
|
|
981
|
+
);
|
|
982
|
+
}
|
|
983
|
+
rows.sort((a, b) => a._creationTime - b._creationTime);
|
|
984
|
+
return await Promise.all(
|
|
985
|
+
rows.slice(0, limit).map(async (row) => {
|
|
986
|
+
const message = row.messageId ? await ctx.db.get(row.messageId) : null;
|
|
987
|
+
return {
|
|
988
|
+
id: row._id,
|
|
989
|
+
provider: row.provider,
|
|
990
|
+
providerId: row.providerId,
|
|
991
|
+
tenant: row.tenant,
|
|
992
|
+
source: row.source,
|
|
993
|
+
state: row.state,
|
|
994
|
+
receivedAt: row._creationTime,
|
|
995
|
+
messageId: row.messageId,
|
|
996
|
+
from: message?.from,
|
|
997
|
+
subject: message?.subject,
|
|
998
|
+
failure: row.failure,
|
|
999
|
+
appNote: row.appNote,
|
|
1000
|
+
};
|
|
1001
|
+
}),
|
|
1002
|
+
);
|
|
1003
|
+
},
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
export const retryState = internalQuery({
|
|
1007
|
+
args: { id: v.id("inbound") },
|
|
1008
|
+
handler: async (ctx, { id }) => {
|
|
1009
|
+
const row = await ctx.db.get(id);
|
|
1010
|
+
if (!row) return null;
|
|
1011
|
+
const message = row.messageId ? await ctx.db.get(row.messageId) : null;
|
|
1012
|
+
const size = async (sid: Id<"_storage"> | undefined) =>
|
|
1013
|
+
sid === undefined
|
|
1014
|
+
? 0
|
|
1015
|
+
: ((await ctx.db.system.get("_storage", sid))?.size ?? 0);
|
|
1016
|
+
return {
|
|
1017
|
+
state: row.state,
|
|
1018
|
+
message,
|
|
1019
|
+
bodyBytes:
|
|
1020
|
+
(await size(message?.textStorageId)) +
|
|
1021
|
+
(await size(message?.htmlStorageId)),
|
|
1022
|
+
};
|
|
1023
|
+
},
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
export const requeue = internalMutation({
|
|
1027
|
+
args: { id: v.id("inbound") },
|
|
1028
|
+
handler: async (ctx, { id }): Promise<null> => {
|
|
1029
|
+
const row = await ctx.db.get(id);
|
|
1030
|
+
if (row?.state !== "failed" || row.messageId) return null;
|
|
1031
|
+
await ctx.db.patch(id, {
|
|
1032
|
+
state: "received",
|
|
1033
|
+
failure: undefined,
|
|
1034
|
+
attempts: 0,
|
|
1035
|
+
});
|
|
1036
|
+
await enqueueProcess(ctx, id);
|
|
1037
|
+
return null;
|
|
1038
|
+
},
|
|
1039
|
+
});
|
|
1040
|
+
|
|
1041
|
+
export const redeliver = internalMutation({
|
|
1042
|
+
args: {
|
|
1043
|
+
id: v.id("inbound"),
|
|
1044
|
+
byReference: v.boolean(),
|
|
1045
|
+
text: v.optional(v.string()),
|
|
1046
|
+
html: v.optional(v.string()),
|
|
1047
|
+
},
|
|
1048
|
+
handler: async (ctx, { id, byReference, text, html }): Promise<null> => {
|
|
1049
|
+
const row = await ctx.db.get(id);
|
|
1050
|
+
if (row?.state !== "unhandled" || !row.messageId) return null;
|
|
1051
|
+
const message = await ctx.db.get(row.messageId);
|
|
1052
|
+
if (!message) return null;
|
|
1053
|
+
const forApp = await buildForApp(ctx, row, message, {
|
|
1054
|
+
text,
|
|
1055
|
+
html,
|
|
1056
|
+
byReference,
|
|
1057
|
+
});
|
|
1058
|
+
await route(
|
|
1059
|
+
ctx,
|
|
1060
|
+
row._id,
|
|
1061
|
+
forApp,
|
|
1062
|
+
await getConfig(ctx),
|
|
1063
|
+
message.messageIdReused ? REUSED_NOTE : undefined,
|
|
1064
|
+
);
|
|
1065
|
+
return null;
|
|
1066
|
+
},
|
|
1067
|
+
});
|
|
1068
|
+
|
|
1069
|
+
/**
|
|
1070
|
+
* Try again. A `failed` row runs the whole pipeline again; an `unhandled` row
|
|
1071
|
+
* with a stored message calls the app's `onInbound` again and nothing else.
|
|
1072
|
+
* Any other state is left alone, and the result says so: `{ acted: false }`.
|
|
1073
|
+
*/
|
|
1074
|
+
export const retry = action({
|
|
1075
|
+
args: { id: v.id("inbound") },
|
|
1076
|
+
returns: v.object({ acted: v.boolean(), state: vInboundState }),
|
|
1077
|
+
handler: async (
|
|
1078
|
+
ctx,
|
|
1079
|
+
{ id },
|
|
1080
|
+
): Promise<{ acted: boolean; state: Doc<"inbound">["state"] }> => {
|
|
1081
|
+
const loaded = await ctx.runQuery(internal.inbound.retryState, { id });
|
|
1082
|
+
if (!loaded) throw new Error("no such inbound message");
|
|
1083
|
+
let acted = false;
|
|
1084
|
+
if (loaded.state === "failed") {
|
|
1085
|
+
await ctx.runMutation(internal.inbound.requeue, { id });
|
|
1086
|
+
acted = true;
|
|
1087
|
+
} else if (loaded.state === "unhandled" && loaded.message) {
|
|
1088
|
+
const { message } = loaded;
|
|
1089
|
+
const byReference = loaded.bodyBytes > BODY_INLINE_LIMIT;
|
|
1090
|
+
const read = async (sid: Id<"_storage"> | undefined) => {
|
|
1091
|
+
if (byReference || sid === undefined) return undefined;
|
|
1092
|
+
const blob = await ctx.storage.get(sid);
|
|
1093
|
+
return blob ? await blob.text() : undefined;
|
|
1094
|
+
};
|
|
1095
|
+
await ctx.runMutation(internal.inbound.redeliver, {
|
|
1096
|
+
id,
|
|
1097
|
+
byReference,
|
|
1098
|
+
text: await read(message.textStorageId),
|
|
1099
|
+
html: await read(message.htmlStorageId),
|
|
1100
|
+
});
|
|
1101
|
+
acted = true;
|
|
1102
|
+
}
|
|
1103
|
+
// `acted: false` means nothing was done; `state` is the row's state when
|
|
1104
|
+
// retry was called (a handled, received or fetched row is left alone).
|
|
1105
|
+
return { acted, state: loaded.state };
|
|
1106
|
+
},
|
|
1107
|
+
});
|