@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,206 @@
|
|
|
1
|
+
import { readCapped } from "../../shared/readCapped.js";
|
|
2
|
+
import type {
|
|
3
|
+
OutboundPayload,
|
|
4
|
+
SendResult,
|
|
5
|
+
SesCredentials,
|
|
6
|
+
} from "../../shared/types.js";
|
|
7
|
+
import {
|
|
8
|
+
assertRegion,
|
|
9
|
+
awsClient,
|
|
10
|
+
awsDomain,
|
|
11
|
+
scrubCredentials,
|
|
12
|
+
} from "./sigv4.js";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 10 MiB raw (bodies plus attachments). SES itself takes 40 MB after base64
|
|
16
|
+
* (about 30 MiB raw), but a send reads every attachment and builds the base64
|
|
17
|
+
* body in memory, in Convex's default runtime: this is held well below that
|
|
18
|
+
* runtime's memory limit. The live probes (Task 14) measure the real ceiling.
|
|
19
|
+
*/
|
|
20
|
+
export const SES_MAX_BYTES = 10 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
const SEND_TIMEOUT_MS = 30_000;
|
|
23
|
+
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
const THROTTLED = new Set([
|
|
26
|
+
"TooManyRequestsException",
|
|
27
|
+
"ThrottlingException",
|
|
28
|
+
"Throttling",
|
|
29
|
+
"RequestLimitExceeded",
|
|
30
|
+
]);
|
|
31
|
+
|
|
32
|
+
function toBase64(bytes: ArrayBuffer): string {
|
|
33
|
+
const view = new Uint8Array(bytes);
|
|
34
|
+
const parts: string[] = [];
|
|
35
|
+
for (let i = 0; i < view.length; i += 0x8000) {
|
|
36
|
+
parts.push(String.fromCharCode(...view.subarray(i, i + 0x8000)));
|
|
37
|
+
}
|
|
38
|
+
return btoa(parts.join(""));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const utf8 = (Data: string) => ({ Data, Charset: "UTF-8" });
|
|
42
|
+
|
|
43
|
+
/** UTF-8 bytes per encoded word: 60 base64 chars + 12 of `=?UTF-8?B?…?=`. */
|
|
44
|
+
const WORD_BYTES = 45;
|
|
45
|
+
|
|
46
|
+
/** RFC 2047 `B` encoded words, never splitting a character between two. */
|
|
47
|
+
function encodeWords(text: string): string {
|
|
48
|
+
const enc = new TextEncoder();
|
|
49
|
+
const words: string[] = [];
|
|
50
|
+
let chunk: number[] = [];
|
|
51
|
+
const flush = () => {
|
|
52
|
+
if (chunk.length === 0) return;
|
|
53
|
+
words.push(`=?UTF-8?B?${btoa(String.fromCharCode(...chunk))}?=`);
|
|
54
|
+
chunk = [];
|
|
55
|
+
};
|
|
56
|
+
for (const ch of text) {
|
|
57
|
+
const b = enc.encode(ch);
|
|
58
|
+
if (chunk.length + b.length > WORD_BYTES) flush();
|
|
59
|
+
chunk.push(...b);
|
|
60
|
+
}
|
|
61
|
+
flush();
|
|
62
|
+
return words.join(" ");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* SESv2 takes `FromEmailAddress` as a header value, so a display name
|
|
67
|
+
* outside ASCII must be RFC 2047 encoded. An ASCII or bare From is sent as
|
|
68
|
+
* given. (To, Cc and Reply-To are bare addresses: nothing to encode.)
|
|
69
|
+
*/
|
|
70
|
+
function encodeFrom(from: string): string {
|
|
71
|
+
const text = from.trim();
|
|
72
|
+
const open = text.lastIndexOf("<");
|
|
73
|
+
const close = text.lastIndexOf(">");
|
|
74
|
+
if (open === -1 || close < open) return text;
|
|
75
|
+
let name = text.slice(0, open).trim();
|
|
76
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: ASCII range test
|
|
77
|
+
if (/^[\x00-\x7f]*$/.test(name)) return text;
|
|
78
|
+
if (name.length >= 2 && name.startsWith('"') && name.endsWith('"')) {
|
|
79
|
+
name = name.slice(1, -1).replace(/\\(.)/g, "$1");
|
|
80
|
+
}
|
|
81
|
+
return `${encodeWords(name)} ${text.slice(open, close + 1)}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The error type from `x-amzn-ErrorType` (`Name:http://…`) or the body. */
|
|
85
|
+
function errorType(res: Response, json: Record<string, unknown>): string {
|
|
86
|
+
const raw =
|
|
87
|
+
res.headers.get("x-amzn-errortype") ??
|
|
88
|
+
(typeof json.__type === "string" ? json.__type : "");
|
|
89
|
+
const name = raw.split(":")[0] ?? "";
|
|
90
|
+
return name.split("#").pop() ?? "";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function sendViaSes(
|
|
94
|
+
creds: SesCredentials,
|
|
95
|
+
msg: OutboundPayload,
|
|
96
|
+
): Promise<SendResult> {
|
|
97
|
+
const region = assertRegion(creds.region);
|
|
98
|
+
const destination: Record<string, string[]> = { ToAddresses: msg.to };
|
|
99
|
+
if (msg.cc.length > 0) destination.CcAddresses = msg.cc;
|
|
100
|
+
if (msg.bcc.length > 0) destination.BccAddresses = msg.bcc;
|
|
101
|
+
|
|
102
|
+
// SES replaces any Message-ID with its own, so none is sent.
|
|
103
|
+
const headers = msg.headers
|
|
104
|
+
.filter((h) => h.name.toLowerCase() !== "message-id")
|
|
105
|
+
.map((h) => ({ Name: h.name, Value: h.value }));
|
|
106
|
+
|
|
107
|
+
const body: Record<string, unknown> = {
|
|
108
|
+
FromEmailAddress: encodeFrom(msg.from),
|
|
109
|
+
Destination: destination,
|
|
110
|
+
Content: {
|
|
111
|
+
Simple: {
|
|
112
|
+
Subject: utf8(msg.subject),
|
|
113
|
+
Body: {
|
|
114
|
+
...(msg.html !== undefined ? { Html: utf8(msg.html) } : {}),
|
|
115
|
+
...(msg.text !== undefined ? { Text: utf8(msg.text) } : {}),
|
|
116
|
+
},
|
|
117
|
+
...(headers.length > 0 ? { Headers: headers } : {}),
|
|
118
|
+
...(msg.attachments.length > 0
|
|
119
|
+
? {
|
|
120
|
+
Attachments: msg.attachments.map((a) => ({
|
|
121
|
+
FileName: a.filename,
|
|
122
|
+
ContentType: a.contentType,
|
|
123
|
+
RawContent: toBase64(a.content),
|
|
124
|
+
ContentDisposition:
|
|
125
|
+
a.disposition === "inline" ? "INLINE" : "ATTACHMENT",
|
|
126
|
+
...(a.contentId ? { ContentId: a.contentId } : {}),
|
|
127
|
+
})),
|
|
128
|
+
}
|
|
129
|
+
: {}),
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
ConfigurationSetName:
|
|
133
|
+
(msg.stream === "bulk" ? creds.configurationSets.bulk : undefined) ??
|
|
134
|
+
creds.configurationSets.transactional,
|
|
135
|
+
};
|
|
136
|
+
if (msg.replyTo.length > 0) body.ReplyToAddresses = msg.replyTo;
|
|
137
|
+
if (msg.tenant) body.TenantName = msg.tenant;
|
|
138
|
+
const tags = Object.entries(msg.tags).map(([Name, Value]) => ({
|
|
139
|
+
Name,
|
|
140
|
+
Value,
|
|
141
|
+
}));
|
|
142
|
+
if (tags.length > 0) body.EmailTags = tags;
|
|
143
|
+
|
|
144
|
+
let res: Response;
|
|
145
|
+
try {
|
|
146
|
+
res = await awsClient(creds, "ses").fetch(
|
|
147
|
+
`https://email.${region}.${awsDomain(region)}/v2/email/outbound-emails`,
|
|
148
|
+
{
|
|
149
|
+
method: "POST",
|
|
150
|
+
headers: { "Content-Type": "application/json" },
|
|
151
|
+
body: JSON.stringify(body),
|
|
152
|
+
redirect: "manual",
|
|
153
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
154
|
+
},
|
|
155
|
+
);
|
|
156
|
+
} catch {
|
|
157
|
+
// Fixed text: a network error message must never carry request details.
|
|
158
|
+
return {
|
|
159
|
+
ok: false,
|
|
160
|
+
retryable: true,
|
|
161
|
+
ambiguous: true,
|
|
162
|
+
error: "SES request failed",
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
let json: Record<string, unknown> = {};
|
|
167
|
+
try {
|
|
168
|
+
const bytes = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
169
|
+
const parsed: unknown = bytes
|
|
170
|
+
? JSON.parse(new TextDecoder().decode(bytes))
|
|
171
|
+
: null;
|
|
172
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
173
|
+
json = parsed as Record<string, unknown>;
|
|
174
|
+
}
|
|
175
|
+
} catch {
|
|
176
|
+
// Non-JSON body: fall through to the status handling.
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (res.ok) {
|
|
180
|
+
if (typeof json.MessageId === "string" && json.MessageId) {
|
|
181
|
+
const host = region === "us-east-1" ? "email" : region;
|
|
182
|
+
return {
|
|
183
|
+
ok: true,
|
|
184
|
+
providerId: json.MessageId,
|
|
185
|
+
rfcMessageId: `<${json.MessageId}@${host}.amazonses.com>`,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
// Not retryable: SES has no idempotency key, so a retry could double-send.
|
|
189
|
+
return {
|
|
190
|
+
ok: false,
|
|
191
|
+
retryable: false,
|
|
192
|
+
ambiguous: true,
|
|
193
|
+
error: "SES accepted the request but returned no message id",
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const type = errorType(res, json);
|
|
198
|
+
const text = typeof json.message === "string" ? json.message : "";
|
|
199
|
+
const message = scrubCredentials(
|
|
200
|
+
[type || `SES responded ${res.status}`, text].filter(Boolean).join(": "),
|
|
201
|
+
creds,
|
|
202
|
+
).slice(0, 500);
|
|
203
|
+
const retryable =
|
|
204
|
+
res.status === 429 || res.status >= 500 || THROTTLED.has(type);
|
|
205
|
+
return { ok: false, retryable, error: message };
|
|
206
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AwsClient } from "aws4fetch";
|
|
2
|
+
import type { SesCredentials } from "../../shared/types.js";
|
|
3
|
+
|
|
4
|
+
const REGION = /^[a-z]{2}(-[a-z]+)+-\d+$/;
|
|
5
|
+
const BUCKET = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The region and bucket end up inside request URLs, so both are checked
|
|
9
|
+
* before any URL is built (a crafted value could otherwise redirect the
|
|
10
|
+
* signed request to another host).
|
|
11
|
+
*/
|
|
12
|
+
export function assertRegion(region: string): string {
|
|
13
|
+
if (!REGION.test(region)) throw new Error("invalid SES region");
|
|
14
|
+
return region;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function assertBucket(bucket: string): string {
|
|
18
|
+
if (!BUCKET.test(bucket)) throw new Error("invalid S3 bucket name");
|
|
19
|
+
return bucket;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** `amazonaws.com`, or `amazonaws.com.cn` for the China partition. */
|
|
23
|
+
export function awsDomain(region: string): string {
|
|
24
|
+
return region.startsWith("cn-") ? "amazonaws.com.cn" : "amazonaws.com";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* `retries: 0`: aws4fetch retries 10 times on 5xx/429 by default, but the
|
|
29
|
+
* Workpool owns retries (a hidden retry loop would also re-send mail).
|
|
30
|
+
*/
|
|
31
|
+
export function awsClient(
|
|
32
|
+
creds: SesCredentials,
|
|
33
|
+
service: "ses" | "s3",
|
|
34
|
+
): AwsClient {
|
|
35
|
+
return new AwsClient({
|
|
36
|
+
accessKeyId: creds.accessKeyId,
|
|
37
|
+
secretAccessKey: creds.secretAccessKey,
|
|
38
|
+
...(creds.sessionToken ? { sessionToken: creds.sessionToken } : {}),
|
|
39
|
+
service,
|
|
40
|
+
region: assertRegion(creds.region),
|
|
41
|
+
retries: 0,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Removes every credential value from text that may reach an error. */
|
|
46
|
+
export function scrubCredentials(text: string, creds: SesCredentials): string {
|
|
47
|
+
let out = text;
|
|
48
|
+
for (const secret of [
|
|
49
|
+
creds.secretAccessKey,
|
|
50
|
+
creds.accessKeyId,
|
|
51
|
+
creds.sessionToken,
|
|
52
|
+
]) {
|
|
53
|
+
if (secret) out = out.split(secret).join("[redacted]");
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { readCapped } from "../../shared/readCapped.js";
|
|
2
|
+
import type { VerifyResult, WebhookRequest } from "../../shared/types.js";
|
|
3
|
+
|
|
4
|
+
const SNS_HOST = /^sns\.([a-z]{2}(?:-[a-z]+)+-\d+)\.amazonaws\.com(?:\.cn)?$/;
|
|
5
|
+
const CERT_PATH = /^\/SimpleNotificationService-[A-Za-z0-9]+\.pem$/;
|
|
6
|
+
const TOPIC_ARN =
|
|
7
|
+
/^arn:aws(?:-cn)?:sns:([a-z]{2}(?:-[a-z]+)+-\d+):[0-9]+:[^:]+$/;
|
|
8
|
+
const FETCH_TIMEOUT_MS = 10_000;
|
|
9
|
+
const MAX_CERT_BYTES = 16 * 1024;
|
|
10
|
+
const MAX_CERTS = 16;
|
|
11
|
+
const CERT_TTL_MS = 60 * 60 * 1000;
|
|
12
|
+
|
|
13
|
+
type Json = Record<string, unknown>;
|
|
14
|
+
|
|
15
|
+
const reject = (status: 401 | 400, reason: string): VerifyResult => ({
|
|
16
|
+
ok: false,
|
|
17
|
+
status,
|
|
18
|
+
reason,
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const isObject = (x: unknown): x is Json =>
|
|
22
|
+
typeof x === "object" && x !== null && !Array.isArray(x);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Only an https URL on `sns.<region>.amazonaws.com` (never `sns.s3.…`, an S3
|
|
26
|
+
* bucket named "sns"), in the topic's own region, without credentials or port.
|
|
27
|
+
*/
|
|
28
|
+
export function isSnsUrl(
|
|
29
|
+
raw: unknown,
|
|
30
|
+
region: string,
|
|
31
|
+
pathPattern?: RegExp,
|
|
32
|
+
): raw is string {
|
|
33
|
+
if (typeof raw !== "string") return false;
|
|
34
|
+
let url: URL;
|
|
35
|
+
try {
|
|
36
|
+
url = new URL(raw);
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
return (
|
|
41
|
+
url.protocol === "https:" &&
|
|
42
|
+
SNS_HOST.exec(url.hostname)?.[1] === region &&
|
|
43
|
+
url.port === "" &&
|
|
44
|
+
url.username === "" &&
|
|
45
|
+
url.password === "" &&
|
|
46
|
+
(!pathPattern || pathPattern.test(url.pathname))
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Field order is part of the signature: AWS documents these exact lists.
|
|
51
|
+
const NOTIFICATION_FIELDS = [
|
|
52
|
+
"Message",
|
|
53
|
+
"MessageId",
|
|
54
|
+
"Subject",
|
|
55
|
+
"Timestamp",
|
|
56
|
+
"TopicArn",
|
|
57
|
+
"Type",
|
|
58
|
+
];
|
|
59
|
+
const CONFIRMATION_FIELDS = [
|
|
60
|
+
"Message",
|
|
61
|
+
"MessageId",
|
|
62
|
+
"SubscribeURL",
|
|
63
|
+
"Timestamp",
|
|
64
|
+
"Token",
|
|
65
|
+
"TopicArn",
|
|
66
|
+
"Type",
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
/** `Key\nValue\n` per field; `Subject` is only present on some notifications. */
|
|
70
|
+
export function canonicalString(msg: Json): string | null {
|
|
71
|
+
const fields =
|
|
72
|
+
msg.Type === "Notification" ? NOTIFICATION_FIELDS : CONFIRMATION_FIELDS;
|
|
73
|
+
let out = "";
|
|
74
|
+
for (const key of fields) {
|
|
75
|
+
const value = msg[key];
|
|
76
|
+
if (value === undefined || value === null) {
|
|
77
|
+
if (key === "Subject") continue;
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
if (typeof value !== "string") return null;
|
|
81
|
+
out += `${key}\n${value}\n`;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---- X.509: extract the SubjectPublicKeyInfo -------------------------------
|
|
87
|
+
|
|
88
|
+
type Tlv = { tag: number; start: number; end: number };
|
|
89
|
+
|
|
90
|
+
function readTlv(bytes: Uint8Array, at: number): Tlv {
|
|
91
|
+
const tag = bytes[at];
|
|
92
|
+
const first = bytes[at + 1];
|
|
93
|
+
if (tag === undefined || first === undefined) throw new Error("bad DER");
|
|
94
|
+
let length = first;
|
|
95
|
+
let start = at + 2;
|
|
96
|
+
if (first & 0x80) {
|
|
97
|
+
const count = first & 0x7f;
|
|
98
|
+
if (count < 1 || count > 4) throw new Error("bad DER");
|
|
99
|
+
length = 0;
|
|
100
|
+
for (let i = 0; i < count; i++) {
|
|
101
|
+
const b = bytes[start + i];
|
|
102
|
+
if (b === undefined) throw new Error("bad DER");
|
|
103
|
+
length = length * 256 + b;
|
|
104
|
+
}
|
|
105
|
+
start += count;
|
|
106
|
+
}
|
|
107
|
+
const end = start + length;
|
|
108
|
+
if (end > bytes.length) throw new Error("bad DER");
|
|
109
|
+
return { tag, start, end };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const SEQUENCE = 0x30;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Certificate -> tbsCertificate -> [0] version (optional), serial, signature
|
|
116
|
+
* algorithm, issuer, validity, subject -> the next SEQUENCE is the SPKI.
|
|
117
|
+
* WebCrypto cannot import an X.509 certificate, only the SPKI inside it.
|
|
118
|
+
*/
|
|
119
|
+
export function extractSpki(der: Uint8Array): Uint8Array<ArrayBuffer> {
|
|
120
|
+
const cert = readTlv(der, 0);
|
|
121
|
+
if (cert.tag !== SEQUENCE) throw new Error("bad certificate");
|
|
122
|
+
const tbs = readTlv(der, cert.start);
|
|
123
|
+
if (tbs.tag !== SEQUENCE) throw new Error("bad certificate");
|
|
124
|
+
let at = tbs.start;
|
|
125
|
+
let field = readTlv(der, at);
|
|
126
|
+
if (field.tag === 0xa0) {
|
|
127
|
+
at = field.end;
|
|
128
|
+
field = readTlv(der, at);
|
|
129
|
+
}
|
|
130
|
+
// serial, signature algorithm, issuer, validity, subject
|
|
131
|
+
for (const expected of [0x02, SEQUENCE, SEQUENCE, SEQUENCE, SEQUENCE]) {
|
|
132
|
+
if (field.tag !== expected) throw new Error("bad certificate");
|
|
133
|
+
at = field.end;
|
|
134
|
+
field = readTlv(der, at);
|
|
135
|
+
}
|
|
136
|
+
if (field.tag !== SEQUENCE) throw new Error("bad certificate");
|
|
137
|
+
return Uint8Array.from(der.subarray(at, field.end));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function pemToDer(pem: string): Uint8Array<ArrayBuffer> {
|
|
141
|
+
const match =
|
|
142
|
+
/-----BEGIN CERTIFICATE-----([^-]+)-----END CERTIFICATE-----/.exec(pem);
|
|
143
|
+
if (!match?.[1]) throw new Error("no certificate");
|
|
144
|
+
const bin = atob(match[1].replace(/\s+/g, ""));
|
|
145
|
+
const out = new Uint8Array(bin.length);
|
|
146
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function fromBase64(b64: string): Uint8Array<ArrayBuffer> {
|
|
151
|
+
const bin = atob(b64);
|
|
152
|
+
const out = new Uint8Array(bin.length);
|
|
153
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---- Certificate fetch + cache ---------------------------------------------
|
|
158
|
+
|
|
159
|
+
const certCache = new Map<
|
|
160
|
+
string,
|
|
161
|
+
{ spki: Uint8Array<ArrayBuffer>; at: number }
|
|
162
|
+
>();
|
|
163
|
+
|
|
164
|
+
export function resetSnsCertCacheForTesting(): void {
|
|
165
|
+
certCache.clear();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The certificate could not be fetched (network error, timeout, non-2xx):
|
|
170
|
+
* nothing was verified either way, so the caller throws and SNS retries.
|
|
171
|
+
*/
|
|
172
|
+
class CertFetchError extends Error {
|
|
173
|
+
constructor() {
|
|
174
|
+
super("certificate fetch failed");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function signingKeySpki(url: string): Promise<Uint8Array<ArrayBuffer>> {
|
|
179
|
+
const hit = certCache.get(url);
|
|
180
|
+
if (hit && Date.now() - hit.at < CERT_TTL_MS) return hit.spki;
|
|
181
|
+
// No redirects: the URL was checked, a redirect target would not be.
|
|
182
|
+
let res: Response;
|
|
183
|
+
try {
|
|
184
|
+
res = await fetch(url, {
|
|
185
|
+
redirect: "manual",
|
|
186
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
187
|
+
});
|
|
188
|
+
} catch {
|
|
189
|
+
throw new CertFetchError();
|
|
190
|
+
}
|
|
191
|
+
if (!res.ok || res.type === "opaqueredirect") {
|
|
192
|
+
await res.body?.cancel().catch(() => {});
|
|
193
|
+
throw new CertFetchError();
|
|
194
|
+
}
|
|
195
|
+
let body: ArrayBuffer | null;
|
|
196
|
+
try {
|
|
197
|
+
body = await readCapped(res, MAX_CERT_BYTES);
|
|
198
|
+
} catch {
|
|
199
|
+
throw new CertFetchError();
|
|
200
|
+
}
|
|
201
|
+
if (!body) throw new Error("certificate too large");
|
|
202
|
+
const spki = extractSpki(pemToDer(new TextDecoder().decode(body)));
|
|
203
|
+
// Cache only a usable RSA key: an EC key throws here and is never kept.
|
|
204
|
+
await crypto.subtle.importKey(
|
|
205
|
+
"spki",
|
|
206
|
+
spki,
|
|
207
|
+
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
|
|
208
|
+
false,
|
|
209
|
+
["verify"],
|
|
210
|
+
);
|
|
211
|
+
if (certCache.size >= MAX_CERTS) {
|
|
212
|
+
const oldest = certCache.keys().next().value;
|
|
213
|
+
if (oldest !== undefined) certCache.delete(oldest);
|
|
214
|
+
}
|
|
215
|
+
certCache.set(url, { spki, at: Date.now() });
|
|
216
|
+
return spki;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function signatureValid(msg: Json, certUrl: string): Promise<boolean> {
|
|
220
|
+
const version = msg.SignatureVersion;
|
|
221
|
+
const hash =
|
|
222
|
+
version === "1" ? "SHA-1" : version === "2" ? "SHA-256" : undefined;
|
|
223
|
+
const canonical = canonicalString(msg);
|
|
224
|
+
if (!hash || canonical === null || typeof msg.Signature !== "string") {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
const spki = await signingKeySpki(certUrl);
|
|
228
|
+
const key = await crypto.subtle.importKey(
|
|
229
|
+
"spki",
|
|
230
|
+
spki,
|
|
231
|
+
{ name: "RSASSA-PKCS1-v1_5", hash },
|
|
232
|
+
false,
|
|
233
|
+
["verify"],
|
|
234
|
+
);
|
|
235
|
+
return crypto.subtle.verify(
|
|
236
|
+
"RSASSA-PKCS1-v1_5",
|
|
237
|
+
key,
|
|
238
|
+
fromBase64(msg.Signature),
|
|
239
|
+
new TextEncoder().encode(canonical),
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ---- Public entry -----------------------------------------------------------
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Verifies an SNS HTTP(S) delivery. Every check that needs no network (topic,
|
|
247
|
+
* URL hosts) runs before the signing certificate is fetched.
|
|
248
|
+
*/
|
|
249
|
+
export async function verifySnsWebhook(
|
|
250
|
+
trustedTopicArns: string[],
|
|
251
|
+
req: WebhookRequest,
|
|
252
|
+
): Promise<VerifyResult> {
|
|
253
|
+
let msg: unknown;
|
|
254
|
+
try {
|
|
255
|
+
msg = JSON.parse(req.body);
|
|
256
|
+
} catch {
|
|
257
|
+
return reject(400, "body is not JSON");
|
|
258
|
+
}
|
|
259
|
+
if (!isObject(msg)) return reject(400, "body is not an SNS message");
|
|
260
|
+
|
|
261
|
+
const type = msg.Type;
|
|
262
|
+
if (
|
|
263
|
+
type !== "Notification" &&
|
|
264
|
+
type !== "SubscriptionConfirmation" &&
|
|
265
|
+
type !== "UnsubscribeConfirmation"
|
|
266
|
+
) {
|
|
267
|
+
return reject(400, "unsupported SNS message type");
|
|
268
|
+
}
|
|
269
|
+
if (
|
|
270
|
+
typeof msg.TopicArn !== "string" ||
|
|
271
|
+
!trustedTopicArns.includes(msg.TopicArn)
|
|
272
|
+
) {
|
|
273
|
+
return reject(401, "untrusted topic");
|
|
274
|
+
}
|
|
275
|
+
const topicRegion = TOPIC_ARN.exec(msg.TopicArn)?.[1];
|
|
276
|
+
if (!topicRegion) return reject(401, "untrusted topic");
|
|
277
|
+
const certUrl = msg.SigningCertURL;
|
|
278
|
+
if (!isSnsUrl(certUrl, topicRegion, CERT_PATH)) {
|
|
279
|
+
return reject(401, "invalid signing certificate url");
|
|
280
|
+
}
|
|
281
|
+
const subscribeUrl = msg.SubscribeURL;
|
|
282
|
+
if (type !== "Notification" && !isSnsUrl(subscribeUrl, topicRegion)) {
|
|
283
|
+
return reject(401, "invalid subscribe url");
|
|
284
|
+
}
|
|
285
|
+
if (typeof msg.MessageId !== "string" || !msg.MessageId) {
|
|
286
|
+
return reject(400, "missing message id");
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
try {
|
|
290
|
+
if (!(await signatureValid(msg, certUrl))) {
|
|
291
|
+
return reject(401, "invalid signature");
|
|
292
|
+
}
|
|
293
|
+
} catch (e) {
|
|
294
|
+
// No answer is not a verdict: throwing makes ingest answer 500, so SNS
|
|
295
|
+
// delivers again. A certificate that arrived but is unusable is a 401.
|
|
296
|
+
if (e instanceof CertFetchError) throw e;
|
|
297
|
+
return reject(401, "invalid signature");
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// The verified envelope: parseWebhook unwraps `Message` and keeps the
|
|
301
|
+
// envelope Timestamp as a fallback event time.
|
|
302
|
+
if (type === "Notification") {
|
|
303
|
+
return { ok: true, payload: msg, deliveryId: msg.MessageId };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (type === "SubscriptionConfirmation") {
|
|
307
|
+
try {
|
|
308
|
+
const res = await fetch(String(subscribeUrl), {
|
|
309
|
+
redirect: "manual",
|
|
310
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
311
|
+
});
|
|
312
|
+
await res.body?.cancel();
|
|
313
|
+
if (!res.ok) return reject(400, "subscription confirmation failed");
|
|
314
|
+
} catch {
|
|
315
|
+
return reject(400, "subscription confirmation failed");
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// An UnsubscribeConfirmation is acknowledged only: fetching its URL would
|
|
319
|
+
// re-subscribe the endpoint.
|
|
320
|
+
return { ok: true, handled: true, status: 200 };
|
|
321
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AdapterOptions,
|
|
3
|
+
Capabilities,
|
|
4
|
+
InboundNotification,
|
|
5
|
+
OutboundPayload,
|
|
6
|
+
ParsedInbound,
|
|
7
|
+
ParsedWebhook,
|
|
8
|
+
ProviderName,
|
|
9
|
+
SendResult,
|
|
10
|
+
VerifyResult,
|
|
11
|
+
WebhookRequest,
|
|
12
|
+
} from "../shared/types.js";
|
|
13
|
+
|
|
14
|
+
export type { AdapterOptions };
|
|
15
|
+
|
|
16
|
+
export interface ProviderAdapter<C> {
|
|
17
|
+
name: ProviderName;
|
|
18
|
+
capabilities: Capabilities;
|
|
19
|
+
send(creds: C, msg: OutboundPayload): Promise<SendResult>;
|
|
20
|
+
verifyWebhook(creds: C, req: WebhookRequest): Promise<VerifyResult>;
|
|
21
|
+
parseWebhook(
|
|
22
|
+
payload: unknown,
|
|
23
|
+
deliveryId: string,
|
|
24
|
+
options: AdapterOptions,
|
|
25
|
+
): ParsedWebhook;
|
|
26
|
+
fetchInbound(creds: C, n: InboundNotification): Promise<ParsedInbound>;
|
|
27
|
+
}
|