@primitivedotdev/sdk 1.26.0 → 1.27.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/README.md +58 -1
- package/dist/api/index.d.ts +3 -3
- package/dist/api/index.js +4 -4
- package/dist/{api-BXlPoOdE.js → api-D4xf448r.js} +506 -3
- package/dist/contract/index.d.ts +1 -1
- package/dist/contract/index.js +2 -1
- package/dist/{errors-BgI9FKHK.d.ts → errors-CCJX3I_T.d.ts} +11 -5
- package/dist/{index-fS1gVNuX.d.ts → index-DCLGz6IH.d.ts} +5 -37
- package/dist/{index-BGyYkqRn.d.ts → index-DwP3ul-y.d.ts} +175 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/openapi/index.js +1 -1
- package/dist/{operations.generated-CPcHOHgd.js → operations.generated-CoVn-Rb6.js} +236 -4
- package/dist/parser/address.js +1 -1
- package/dist/parser/index.js +1 -1
- package/dist/payloads/index.js +1 -1
- package/dist/{webhook-BtyuJtUF.js → trust-DBOnyTHV.js} +671 -2147
- package/dist/webhook/index.d.ts +2 -2
- package/dist/webhook/index.js +2 -2
- package/dist/webhook-B72YFapb.js +2132 -0
- package/package.json +3 -3
- package/dist/errors-Bo0f7eId.js +0 -673
- /package/dist/{address-parser-C2JJzLdA.js → address-parser-BxXv4vx0.js} +0 -0
- /package/dist/{payloads-BfJAtqW9.js → payloads-BMngnJlE.js} +0 -0
|
@@ -0,0 +1,2132 @@
|
|
|
1
|
+
import { F as WebhookPayloadError, L as WebhookVerificationError, N as RawEmailDecodeError, _ as parseWebhookEvent, h as normalizeReceivedEmail, k as validateEmailReceivedEvent } from "./trust-DBOnyTHV.js";
|
|
2
|
+
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
3
|
+
//#region src/webhook/download-tokens.ts
|
|
4
|
+
/**
|
|
5
|
+
* Signed download tokens.
|
|
6
|
+
*
|
|
7
|
+
* A download token is a self-describing bearer credential for fetching a
|
|
8
|
+
* specific email's raw bytes or attachment bundle from a per-deployment
|
|
9
|
+
* download endpoint. It binds:
|
|
10
|
+
*
|
|
11
|
+
* - `email_id`: the specific email the token authorizes.
|
|
12
|
+
* - `aud`: a caller-chosen audience label (e.g. the resource kind being
|
|
13
|
+
* downloaded). Tokens minted for one audience will not verify under another.
|
|
14
|
+
* - `exp`: an absolute expiration time (unix seconds).
|
|
15
|
+
*
|
|
16
|
+
* Format: `<base64url(payload)>.<base64url(signature)>` where `signature`
|
|
17
|
+
* is HMAC-SHA256 over the base64url-encoded payload using the shared secret.
|
|
18
|
+
*
|
|
19
|
+
* The audience is an opaque caller-chosen string. Both the issuer and the
|
|
20
|
+
* verifier must agree on the exact bytes; the SDK does not prescribe a
|
|
21
|
+
* convention. New integrations are encouraged to namespace audiences
|
|
22
|
+
* (e.g. `primitive:raw-download`).
|
|
23
|
+
*
|
|
24
|
+
* Tokens are stateless: verification needs only the shared secret. Keep
|
|
25
|
+
* expirations as short as operationally tolerable.
|
|
26
|
+
*/
|
|
27
|
+
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
28
|
+
/**
|
|
29
|
+
* Issue a signed download token.
|
|
30
|
+
*
|
|
31
|
+
* The resulting token is `<base64url-payload>.<base64url-signature>`, where
|
|
32
|
+
* the payload is `{"email_id":"...","exp":...,"aud":"..."}` (snake_case,
|
|
33
|
+
* field order fixed) and the signature is HMAC-SHA256 of the base64url
|
|
34
|
+
* payload string using `secret`.
|
|
35
|
+
*
|
|
36
|
+
* @param params - Token inputs.
|
|
37
|
+
* @returns The signed token string.
|
|
38
|
+
*/
|
|
39
|
+
function generateDownloadToken(params) {
|
|
40
|
+
const { emailId, expiresAt, audience, secret } = params;
|
|
41
|
+
const payloadJson = JSON.stringify({
|
|
42
|
+
email_id: emailId,
|
|
43
|
+
exp: expiresAt,
|
|
44
|
+
aud: audience
|
|
45
|
+
});
|
|
46
|
+
const payloadStr = Buffer.from(payloadJson, "utf8").toString("base64url");
|
|
47
|
+
return `${payloadStr}.${createHmac("sha256", secret).update(payloadStr).digest("base64url")}`;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Verify a signed download token.
|
|
51
|
+
*
|
|
52
|
+
* Returns a discriminated-union result. The function never throws for
|
|
53
|
+
* verification failures. Only malformed inputs at the crypto layer would
|
|
54
|
+
* surface. Callers should check `result.valid` and log `result.error`.
|
|
55
|
+
*
|
|
56
|
+
* @param params - Verification inputs.
|
|
57
|
+
* @returns Whether the token is valid, plus a reason on failure.
|
|
58
|
+
*/
|
|
59
|
+
function verifyDownloadToken(params) {
|
|
60
|
+
const { token, emailId, audience, secret, nowSeconds } = params;
|
|
61
|
+
if (typeof token !== "string" || token.length === 0) return {
|
|
62
|
+
valid: false,
|
|
63
|
+
error: "Token is empty"
|
|
64
|
+
};
|
|
65
|
+
const firstDot = token.indexOf(".");
|
|
66
|
+
const lastDot = token.lastIndexOf(".");
|
|
67
|
+
if (firstDot === -1 || firstDot !== lastDot) return {
|
|
68
|
+
valid: false,
|
|
69
|
+
error: "Token is malformed: expected one '.'"
|
|
70
|
+
};
|
|
71
|
+
const payloadStr = token.slice(0, firstDot);
|
|
72
|
+
const providedSignature = token.slice(firstDot + 1);
|
|
73
|
+
if (payloadStr.length === 0 || providedSignature.length === 0) return {
|
|
74
|
+
valid: false,
|
|
75
|
+
error: "Token is malformed: empty part"
|
|
76
|
+
};
|
|
77
|
+
const expectedSignature = createHmac("sha256", secret).update(payloadStr).digest("base64url");
|
|
78
|
+
const providedBytes = Buffer.from(providedSignature, "base64url");
|
|
79
|
+
const expectedBytes = Buffer.from(expectedSignature, "base64url");
|
|
80
|
+
if (providedBytes.length !== expectedBytes.length || !timingSafeEqual(providedBytes, expectedBytes)) return {
|
|
81
|
+
valid: false,
|
|
82
|
+
error: "Invalid signature"
|
|
83
|
+
};
|
|
84
|
+
if (!BASE64URL_PATTERN.test(payloadStr)) return {
|
|
85
|
+
valid: false,
|
|
86
|
+
error: "Token payload is not valid base64url"
|
|
87
|
+
};
|
|
88
|
+
const decodedJson = Buffer.from(payloadStr, "base64url").toString("utf8");
|
|
89
|
+
let payload;
|
|
90
|
+
try {
|
|
91
|
+
payload = JSON.parse(decodedJson);
|
|
92
|
+
} catch {
|
|
93
|
+
return {
|
|
94
|
+
valid: false,
|
|
95
|
+
error: "Token payload is not valid JSON"
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.email_id !== "string" || typeof payload.aud !== "string" || typeof payload.exp !== "number") return {
|
|
99
|
+
valid: false,
|
|
100
|
+
error: "Token payload has wrong shape"
|
|
101
|
+
};
|
|
102
|
+
const { email_id, aud, exp } = payload;
|
|
103
|
+
if (aud !== audience) return {
|
|
104
|
+
valid: false,
|
|
105
|
+
error: "Audience mismatch"
|
|
106
|
+
};
|
|
107
|
+
if (email_id !== emailId) return {
|
|
108
|
+
valid: false,
|
|
109
|
+
error: "Email ID mismatch"
|
|
110
|
+
};
|
|
111
|
+
if (exp <= (nowSeconds ?? Math.floor(Date.now() / 1e3))) return {
|
|
112
|
+
valid: false,
|
|
113
|
+
error: "Token is expired"
|
|
114
|
+
};
|
|
115
|
+
return { valid: true };
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/webhook/encoding.ts
|
|
119
|
+
/**
|
|
120
|
+
* Buffer encoding utilities
|
|
121
|
+
*/
|
|
122
|
+
const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
|
|
123
|
+
/**
|
|
124
|
+
* Convert a Buffer to string with strict UTF-8 validation.
|
|
125
|
+
* Throws if the buffer contains invalid UTF-8 sequences.
|
|
126
|
+
*
|
|
127
|
+
* Uses TextDecoder with `fatal: true` for robust validation that catches
|
|
128
|
+
* all invalid UTF-8 sequences, not just those that produce replacement characters.
|
|
129
|
+
*
|
|
130
|
+
* @param buffer - The buffer to convert
|
|
131
|
+
* @param label - Label for error messages (e.g., "request body")
|
|
132
|
+
* @returns The UTF-8 decoded string
|
|
133
|
+
* @throws WebhookPayloadError if the buffer contains invalid UTF-8
|
|
134
|
+
*/
|
|
135
|
+
function bufferToString(buffer, label) {
|
|
136
|
+
try {
|
|
137
|
+
return utf8Decoder.decode(buffer);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
throw new WebhookPayloadError("INVALID_ENCODING", `${label} contains invalid UTF-8 bytes`, `Ensure the ${label} is valid UTF-8 encoded text. If the data is binary, it should be base64 encoded first.`, err instanceof Error ? err : void 0);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/webhook/signing.ts
|
|
144
|
+
/**
|
|
145
|
+
* Webhook HMAC Signing (Stripe-style format)
|
|
146
|
+
*
|
|
147
|
+
* Implements HMAC-SHA256 signature for webhook security with timestamp validation.
|
|
148
|
+
* Prevents replay attacks by including timestamp in signature.
|
|
149
|
+
*
|
|
150
|
+
* Header format:
|
|
151
|
+
* Primitive-Signature: t=<unix_seconds>,v1=<hex_hmac_sha256>
|
|
152
|
+
*
|
|
153
|
+
* Signed payload format: "{timestamp}.{raw_body}"
|
|
154
|
+
*
|
|
155
|
+
* This format matches Stripe's webhook signature scheme, which is widely understood
|
|
156
|
+
* and easy to implement in any language with ~15 lines of code.
|
|
157
|
+
*/
|
|
158
|
+
/**
|
|
159
|
+
* WeakMap cache for computed signatures.
|
|
160
|
+
* Only works for Buffer bodies (strings cannot be WeakMap keys).
|
|
161
|
+
* Automatically garbage collected when Buffer is no longer referenced.
|
|
162
|
+
*/
|
|
163
|
+
const signatureCache = /* @__PURE__ */ new WeakMap();
|
|
164
|
+
/**
|
|
165
|
+
* Hash a secret for cache key comparison.
|
|
166
|
+
* @internal
|
|
167
|
+
*/
|
|
168
|
+
function hashSecret(secret) {
|
|
169
|
+
return createHash("sha256").update(secret).digest("hex");
|
|
170
|
+
}
|
|
171
|
+
/** Header name for incoming webhook signature */
|
|
172
|
+
const PRIMITIVE_SIGNATURE_HEADER = "Primitive-Signature";
|
|
173
|
+
/** Legacy header name kept for backward compatibility with older servers */
|
|
174
|
+
const LEGACY_SIGNATURE_HEADER = "MyMX-Signature";
|
|
175
|
+
/** Header name to confirm webhook was processed (prevents retries) */
|
|
176
|
+
const PRIMITIVE_CONFIRMED_HEADER = "X-Primitive-Confirmed";
|
|
177
|
+
/** Legacy confirmed header name kept for backward compatibility */
|
|
178
|
+
const LEGACY_CONFIRMED_HEADER = "X-MyMX-Confirmed";
|
|
179
|
+
/** Default max age for webhook requests (5 minutes) */
|
|
180
|
+
const DEFAULT_TOLERANCE_SECONDS$1 = 300;
|
|
181
|
+
/** Future clock skew tolerance (1 minute) */
|
|
182
|
+
const FUTURE_TOLERANCE_SECONDS$1 = 60;
|
|
183
|
+
/** Valid hex pattern for signature verification */
|
|
184
|
+
const HEX_PATTERN = /^[0-9a-f]+$/i;
|
|
185
|
+
/** Strict unix-seconds pattern for the timestamp component */
|
|
186
|
+
const UNIX_SECONDS_PATTERN = /^\d+$/;
|
|
187
|
+
/**
|
|
188
|
+
* Sign a webhook payload using HMAC-SHA256.
|
|
189
|
+
*
|
|
190
|
+
* Useful for:
|
|
191
|
+
* - Internal testing and dogfooding
|
|
192
|
+
* - Generating test vectors
|
|
193
|
+
* - Integration tests
|
|
194
|
+
*
|
|
195
|
+
* @param rawBody - The raw JSON body string to sign
|
|
196
|
+
* @param secret - The webhook secret key
|
|
197
|
+
* @param timestamp - Unix timestamp in seconds (defaults to current time)
|
|
198
|
+
*/
|
|
199
|
+
function signWebhookPayload(rawBody, secret, timestamp) {
|
|
200
|
+
const ts = timestamp ?? Math.floor(Date.now() / 1e3);
|
|
201
|
+
const signedPayloadString = `${ts}.${typeof rawBody === "string" ? rawBody : bufferToString(rawBody, "rawBody")}`;
|
|
202
|
+
const hmac = createHmac("sha256", secret);
|
|
203
|
+
hmac.update(signedPayloadString);
|
|
204
|
+
const v1 = hmac.digest("hex");
|
|
205
|
+
return {
|
|
206
|
+
header: `t=${ts},v1=${v1}`,
|
|
207
|
+
timestamp: ts,
|
|
208
|
+
v1
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Parse the Primitive-Signature header into its components.
|
|
213
|
+
* Tolerant of whitespace around keys/values.
|
|
214
|
+
*
|
|
215
|
+
* @internal
|
|
216
|
+
*/
|
|
217
|
+
function parseSignatureHeader(signatureHeader) {
|
|
218
|
+
if (!signatureHeader || typeof signatureHeader !== "string") return null;
|
|
219
|
+
const parts = signatureHeader.split(",");
|
|
220
|
+
let timestamp = null;
|
|
221
|
+
const signatures = [];
|
|
222
|
+
for (const part of parts) {
|
|
223
|
+
const idx = part.indexOf("=");
|
|
224
|
+
if (idx === -1) continue;
|
|
225
|
+
const key = part.slice(0, idx).trim();
|
|
226
|
+
const value = part.slice(idx + 1).trim();
|
|
227
|
+
if (!key || !value) continue;
|
|
228
|
+
if (key === "t") {
|
|
229
|
+
if (!UNIX_SECONDS_PATTERN.test(value)) continue;
|
|
230
|
+
const parsed = Number(value);
|
|
231
|
+
if (Number.isSafeInteger(parsed)) timestamp = parsed;
|
|
232
|
+
} else if (key === "v1") signatures.push(value);
|
|
233
|
+
}
|
|
234
|
+
if (timestamp === null || signatures.length === 0) return null;
|
|
235
|
+
return {
|
|
236
|
+
timestamp,
|
|
237
|
+
signatures
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Check if a string is valid lowercase hex of expected length
|
|
242
|
+
*/
|
|
243
|
+
function isValidHex(str, expectedLength) {
|
|
244
|
+
return str.length === expectedLength && HEX_PATTERN.test(str);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Verify a webhook signature.
|
|
248
|
+
*
|
|
249
|
+
* Throws `WebhookVerificationError` on failure with a specific error code.
|
|
250
|
+
*
|
|
251
|
+
* @example
|
|
252
|
+
* ```typescript
|
|
253
|
+
* import { verifyWebhookSignature, WebhookVerificationError } from '@primitivedotdev/sdk';
|
|
254
|
+
*
|
|
255
|
+
* try {
|
|
256
|
+
* const signatureHeader = req.headers['primitive-signature'];
|
|
257
|
+
* if (typeof signatureHeader !== 'string') {
|
|
258
|
+
* throw new Error('Missing Primitive-Signature header');
|
|
259
|
+
* }
|
|
260
|
+
* verifyWebhookSignature({
|
|
261
|
+
* rawBody: req.body, // raw string, NOT parsed JSON
|
|
262
|
+
* signatureHeader,
|
|
263
|
+
* secret: process.env.PRIMITIVE_WEBHOOK_SECRET!,
|
|
264
|
+
* });
|
|
265
|
+
* // Signature is valid, process the webhook
|
|
266
|
+
* } catch (err) {
|
|
267
|
+
* if (err instanceof WebhookVerificationError) {
|
|
268
|
+
* console.error('Invalid webhook:', err.code, err.message);
|
|
269
|
+
* }
|
|
270
|
+
* return res.status(400).send('Invalid signature');
|
|
271
|
+
* }
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
274
|
+
function verifyWebhookSignature(opts) {
|
|
275
|
+
const { rawBody, signatureHeader, secret, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS$1, nowSeconds } = opts;
|
|
276
|
+
if (!secret || typeof secret === "string" && secret.length === 0 || Buffer.isBuffer(secret) && secret.length === 0) throw new WebhookVerificationError("MISSING_SECRET", "Webhook secret is required but was empty or not provided");
|
|
277
|
+
const parsed = parseSignatureHeader(signatureHeader);
|
|
278
|
+
if (!parsed) throw new WebhookVerificationError("INVALID_SIGNATURE_HEADER", "Invalid Primitive-Signature header format. Expected: t={timestamp},v1={signature}");
|
|
279
|
+
const { timestamp, signatures } = parsed;
|
|
280
|
+
const age = (nowSeconds ?? Math.floor(Date.now() / 1e3)) - timestamp;
|
|
281
|
+
if (age > toleranceSeconds) throw new WebhookVerificationError("TIMESTAMP_OUT_OF_RANGE", `Webhook timestamp too old (${age}s). Max age is ${toleranceSeconds}s.`);
|
|
282
|
+
if (age < -FUTURE_TOLERANCE_SECONDS$1) throw new WebhookVerificationError("TIMESTAMP_OUT_OF_RANGE", "Webhook timestamp is too far in the future. Check server clock sync.");
|
|
283
|
+
const body = typeof rawBody === "string" ? rawBody : bufferToString(rawBody, "request body");
|
|
284
|
+
let expectedHex;
|
|
285
|
+
if (Buffer.isBuffer(rawBody)) {
|
|
286
|
+
const cached = signatureCache.get(rawBody);
|
|
287
|
+
const currentSecretHash = hashSecret(secret);
|
|
288
|
+
if (cached && cached.body === body && cached.timestamp === timestamp && cached.secretHash === currentSecretHash) expectedHex = cached.computed;
|
|
289
|
+
else {
|
|
290
|
+
const signedPayloadString = `${timestamp}.${body}`;
|
|
291
|
+
const hmac = createHmac("sha256", secret);
|
|
292
|
+
hmac.update(signedPayloadString);
|
|
293
|
+
expectedHex = hmac.digest("hex");
|
|
294
|
+
signatureCache.set(rawBody, {
|
|
295
|
+
secretHash: currentSecretHash,
|
|
296
|
+
timestamp,
|
|
297
|
+
body,
|
|
298
|
+
computed: expectedHex
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
} else {
|
|
302
|
+
const signedPayloadString = `${timestamp}.${body}`;
|
|
303
|
+
const hmac = createHmac("sha256", secret);
|
|
304
|
+
hmac.update(signedPayloadString);
|
|
305
|
+
expectedHex = hmac.digest("hex");
|
|
306
|
+
}
|
|
307
|
+
for (const receivedHex of signatures) {
|
|
308
|
+
if (!isValidHex(receivedHex, 64)) continue;
|
|
309
|
+
if (timingSafeEqual(Buffer.from(receivedHex, "hex"), Buffer.from(expectedHex, "hex"))) return true;
|
|
310
|
+
}
|
|
311
|
+
const reserializationHint = detectReserializedBody(body);
|
|
312
|
+
throw new WebhookVerificationError("SIGNATURE_MISMATCH", reserializationHint ? `No valid signature found. ${reserializationHint}` : "No valid signature found. Verify the webhook secret matches and you're using the raw request body (not re-serialized JSON).");
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Detect if a body looks like it was re-serialized by a framework.
|
|
316
|
+
* Returns a helpful message if detected, null otherwise.
|
|
317
|
+
* @internal
|
|
318
|
+
*/
|
|
319
|
+
function detectReserializedBody(body) {
|
|
320
|
+
if (/^\s*\{[\s\S]*\n\s{2,}/.test(body)) return "Request body appears re-serialized (pretty-printed). Use the raw request body before any JSON.parse() or JSON.stringify() calls.";
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
//#endregion
|
|
324
|
+
//#region src/webhook/standard-webhooks.ts
|
|
325
|
+
/**
|
|
326
|
+
* Standard Webhooks Verification & Signing
|
|
327
|
+
*
|
|
328
|
+
* Implements the Standard Webhooks spec (standardwebhooks.com) for webhook
|
|
329
|
+
* signature verification and payload signing.
|
|
330
|
+
*
|
|
331
|
+
* Header format:
|
|
332
|
+
* webhook-id: <msg_id>
|
|
333
|
+
* webhook-timestamp: <unix_seconds>
|
|
334
|
+
* webhook-signature: v1,<base64_hmac_sha256> [v1,<base64_2> ...]
|
|
335
|
+
*
|
|
336
|
+
* Signed payload format: "{msg_id}.{timestamp}.{raw_body}"
|
|
337
|
+
*
|
|
338
|
+
* Secrets are base64-encoded, optionally prefixed with "whsec_".
|
|
339
|
+
*/
|
|
340
|
+
const WHSEC_PREFIX = "whsec_";
|
|
341
|
+
const BASE64_PATTERN$1 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
342
|
+
/** Default max age for webhook requests (5 minutes) */
|
|
343
|
+
const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
344
|
+
/** Future clock skew tolerance (1 minute) */
|
|
345
|
+
const FUTURE_TOLERANCE_SECONDS = 60;
|
|
346
|
+
/** Standard Webhooks header names */
|
|
347
|
+
const STANDARD_WEBHOOK_ID_HEADER = "webhook-id";
|
|
348
|
+
const STANDARD_WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp";
|
|
349
|
+
const STANDARD_WEBHOOK_SIGNATURE_HEADER = "webhook-signature";
|
|
350
|
+
/**
|
|
351
|
+
* Prepare a Standard Webhooks secret for HMAC computation.
|
|
352
|
+
*
|
|
353
|
+
* Strips the "whsec_" prefix if present, then base64-decodes the remainder
|
|
354
|
+
* to produce the raw HMAC key bytes.
|
|
355
|
+
*
|
|
356
|
+
* @internal
|
|
357
|
+
*/
|
|
358
|
+
function prepareStandardWebhooksSecret(secret) {
|
|
359
|
+
if (Buffer.isBuffer(secret)) {
|
|
360
|
+
if (secret.length === 0) throw new WebhookVerificationError("MISSING_SECRET", "Webhook secret is required but was empty or not provided");
|
|
361
|
+
return secret;
|
|
362
|
+
}
|
|
363
|
+
let keyStr = secret;
|
|
364
|
+
if (keyStr.startsWith(WHSEC_PREFIX)) keyStr = keyStr.slice(6);
|
|
365
|
+
if (!keyStr || !BASE64_PATTERN$1.test(keyStr)) throw new WebhookVerificationError("MISSING_SECRET", "Standard Webhooks secret must be base64-encoded (optionally with whsec_ prefix)");
|
|
366
|
+
const decoded = Buffer.from(keyStr, "base64");
|
|
367
|
+
if (decoded.length === 0) throw new WebhookVerificationError("MISSING_SECRET", "Webhook secret is required but was empty or not provided");
|
|
368
|
+
return decoded;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Parse the webhook-signature header into base64 signature strings.
|
|
372
|
+
*
|
|
373
|
+
* The header format is space-delimited entries like "v1,<base64>".
|
|
374
|
+
* Only v1 entries are returned.
|
|
375
|
+
*
|
|
376
|
+
* @internal
|
|
377
|
+
*/
|
|
378
|
+
function parseStandardWebhooksSignatures(header) {
|
|
379
|
+
if (!header) return [];
|
|
380
|
+
const signatures = [];
|
|
381
|
+
for (const entry of header.split(" ")) {
|
|
382
|
+
const trimmed = entry.trim();
|
|
383
|
+
if (!trimmed) continue;
|
|
384
|
+
const commaIdx = trimmed.indexOf(",");
|
|
385
|
+
if (commaIdx === -1) continue;
|
|
386
|
+
const version = trimmed.slice(0, commaIdx);
|
|
387
|
+
const sig = trimmed.slice(commaIdx + 1);
|
|
388
|
+
if (version === "v1" && sig) signatures.push(sig);
|
|
389
|
+
}
|
|
390
|
+
return signatures;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Sign a webhook payload using the Standard Webhooks format.
|
|
394
|
+
*
|
|
395
|
+
* @param rawBody - The raw JSON body string to sign
|
|
396
|
+
* @param secret - The webhook secret (with or without whsec_ prefix)
|
|
397
|
+
* @param msgId - The message ID (used in webhook-id header)
|
|
398
|
+
* @param timestamp - Unix timestamp in seconds (defaults to current time)
|
|
399
|
+
*/
|
|
400
|
+
function signStandardWebhooksPayload(rawBody, secret, msgId, timestamp) {
|
|
401
|
+
const ts = timestamp ?? Math.floor(Date.now() / 1e3);
|
|
402
|
+
const body = typeof rawBody === "string" ? rawBody : bufferToString(rawBody, "rawBody");
|
|
403
|
+
const key = prepareStandardWebhooksSecret(secret);
|
|
404
|
+
if (key.length === 0) throw new WebhookVerificationError("MISSING_SECRET", "Webhook secret is required but was empty or not provided");
|
|
405
|
+
const signedPayload = `${msgId}.${ts}.${body}`;
|
|
406
|
+
return {
|
|
407
|
+
signature: `v1,${createHmac("sha256", key).update(signedPayload).digest("base64")}`,
|
|
408
|
+
msgId,
|
|
409
|
+
timestamp: ts
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Verify a Standard Webhooks signature.
|
|
414
|
+
*
|
|
415
|
+
* Throws `WebhookVerificationError` on failure with a specific error code.
|
|
416
|
+
*/
|
|
417
|
+
function verifyStandardWebhooksSignature(opts) {
|
|
418
|
+
const { rawBody, msgId, timestamp: timestampStr, signatureHeader, secret, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS, nowSeconds } = opts;
|
|
419
|
+
const key = prepareStandardWebhooksSecret(secret);
|
|
420
|
+
if (key.length === 0) throw new WebhookVerificationError("MISSING_SECRET", "Webhook secret is required but was empty or not provided");
|
|
421
|
+
if (!timestampStr || !/^\d+$/.test(timestampStr)) throw new WebhookVerificationError("INVALID_SIGNATURE_HEADER", `Invalid webhook-timestamp header: "${timestampStr}". Expected a unix timestamp in seconds`);
|
|
422
|
+
const timestamp = Number(timestampStr);
|
|
423
|
+
if (!Number.isInteger(timestamp) || timestamp < 0) throw new WebhookVerificationError("INVALID_SIGNATURE_HEADER", `Invalid webhook-timestamp header: "${timestampStr}". Expected a unix timestamp in seconds`);
|
|
424
|
+
const age = (nowSeconds ?? Math.floor(Date.now() / 1e3)) - timestamp;
|
|
425
|
+
if (age > toleranceSeconds) throw new WebhookVerificationError("TIMESTAMP_OUT_OF_RANGE", `Webhook timestamp too old (${age}s). Max age is ${toleranceSeconds}s.`);
|
|
426
|
+
if (age < -FUTURE_TOLERANCE_SECONDS) throw new WebhookVerificationError("TIMESTAMP_OUT_OF_RANGE", "Webhook timestamp is too far in the future. Check server clock sync.");
|
|
427
|
+
const signedPayload = `${msgId}.${timestamp}.${typeof rawBody === "string" ? rawBody : bufferToString(rawBody, "request body")}`;
|
|
428
|
+
const expectedSig = createHmac("sha256", key).update(signedPayload).digest("base64");
|
|
429
|
+
const signatures = parseStandardWebhooksSignatures(signatureHeader);
|
|
430
|
+
if (signatures.length === 0) throw new WebhookVerificationError("INVALID_SIGNATURE_HEADER", "Invalid webhook-signature header format. Expected: \"v1,<base64>\"");
|
|
431
|
+
const expectedBytes = Buffer.from(expectedSig, "base64");
|
|
432
|
+
for (const sig of signatures) {
|
|
433
|
+
if (!BASE64_PATTERN$1.test(sig)) continue;
|
|
434
|
+
const sigBytes = Buffer.from(sig, "base64");
|
|
435
|
+
if (sigBytes.length === expectedBytes.length && timingSafeEqual(sigBytes, expectedBytes)) return true;
|
|
436
|
+
}
|
|
437
|
+
throw new WebhookVerificationError("SIGNATURE_MISMATCH", "No valid signature found. Verify the webhook secret matches and you're using the raw request body (not re-serialized JSON).");
|
|
438
|
+
}
|
|
439
|
+
//#endregion
|
|
440
|
+
//#region src/schema.generated.ts
|
|
441
|
+
const emailReceivedEventJsonSchema = {
|
|
442
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
443
|
+
"$ref": "#/definitions/EmailReceivedEvent",
|
|
444
|
+
"definitions": {
|
|
445
|
+
"EmailReceivedEvent": {
|
|
446
|
+
"type": "object",
|
|
447
|
+
"properties": {
|
|
448
|
+
"id": {
|
|
449
|
+
"type": "string",
|
|
450
|
+
"pattern": "^evt_[a-f0-9]{64}$",
|
|
451
|
+
"description": "Unique delivery event ID.\n\nThis ID is stable across retries to the same endpoint - use it as your idempotency/dedupe key. Note that the same email delivered to different endpoints will have different event IDs.\n\nFormat: `evt_` prefix followed by a SHA-256 hash (64 hex characters). Example: `evt_a1b2c3d4e5f6...` (68 characters total)"
|
|
452
|
+
},
|
|
453
|
+
"event": {
|
|
454
|
+
"type": "string",
|
|
455
|
+
"enum": [
|
|
456
|
+
"email.received",
|
|
457
|
+
"email.bounced",
|
|
458
|
+
"email.tls_report",
|
|
459
|
+
"email.dmarc_report",
|
|
460
|
+
"email.dmarc_failure"
|
|
461
|
+
],
|
|
462
|
+
"description": "Event type identifier.\n\n- `email.received` - A normal inbound email.\n- `email.bounced` - A delivery status notification (DSN) reporting that a message delivery failed. Carries `email.analysis.bounce`.\n- `email.tls_report` - An SMTP TLS report (RFC 8460). Carries `email.analysis.tls_report`.\n- `email.dmarc_report` - A DMARC aggregate report (RFC 7489). Carries `email.analysis.dmarc_report`.\n- `email.dmarc_failure` - A DMARC failure (forensic) report.\n\nMachine-generated mail (bounces and the report types above) is delivered under its own event type rather than `email.received`, so an endpoint subscribed only to `email.received` receives just normal inbound mail. The payload shape is otherwise identical across event types; the type-specific details live under `email.analysis`."
|
|
463
|
+
},
|
|
464
|
+
"version": {
|
|
465
|
+
"$ref": "#/definitions/WebhookVersion",
|
|
466
|
+
"description": "API version in date format (YYYY-MM-DD). Use this to detect version mismatches between webhook and SDK."
|
|
467
|
+
},
|
|
468
|
+
"routing": {
|
|
469
|
+
"$ref": "#/definitions/RoutingDecision",
|
|
470
|
+
"description": "The recipient-routing decision for this email: where it was delivered and why. Present only when recipient routing ran for the organization; omitted otherwise. This is the compact decision also recorded on the email's routing metadata."
|
|
471
|
+
},
|
|
472
|
+
"delivery": {
|
|
473
|
+
"type": "object",
|
|
474
|
+
"properties": {
|
|
475
|
+
"endpoint_id": {
|
|
476
|
+
"type": "string",
|
|
477
|
+
"description": "ID of the webhook endpoint receiving this event. Matches the endpoint ID from your Primitive dashboard."
|
|
478
|
+
},
|
|
479
|
+
"attempt": {
|
|
480
|
+
"type": "integer",
|
|
481
|
+
"minimum": 1,
|
|
482
|
+
"description": "Delivery attempt number, starting at 1. Increments with each retry if previous attempts failed."
|
|
483
|
+
},
|
|
484
|
+
"attempted_at": {
|
|
485
|
+
"type": "string",
|
|
486
|
+
"format": "date-time",
|
|
487
|
+
"description": "ISO 8601 timestamp (UTC) when this delivery was attempted.",
|
|
488
|
+
"examples": ["2025-01-15T10:30:00.000Z"]
|
|
489
|
+
}
|
|
490
|
+
},
|
|
491
|
+
"required": [
|
|
492
|
+
"endpoint_id",
|
|
493
|
+
"attempt",
|
|
494
|
+
"attempted_at"
|
|
495
|
+
],
|
|
496
|
+
"description": "Metadata about this webhook delivery."
|
|
497
|
+
},
|
|
498
|
+
"email": {
|
|
499
|
+
"type": "object",
|
|
500
|
+
"properties": {
|
|
501
|
+
"id": {
|
|
502
|
+
"type": "string",
|
|
503
|
+
"description": "Unique email ID in Primitive. Use this ID when calling Primitive APIs to reference this email."
|
|
504
|
+
},
|
|
505
|
+
"thread_id": {
|
|
506
|
+
"type": ["string", "null"],
|
|
507
|
+
"description": "Conversation thread this email belongs to. Inbound and outbound messages in the same conversation share a thread_id; fetch GET /v1/threads/{thread_id} for the full thread. Null on messages received before threading was enabled."
|
|
508
|
+
},
|
|
509
|
+
"received_at": {
|
|
510
|
+
"type": "string",
|
|
511
|
+
"format": "date-time",
|
|
512
|
+
"description": "ISO 8601 timestamp (UTC) when Primitive received the email.",
|
|
513
|
+
"examples": ["2025-01-15T10:29:55.123Z"]
|
|
514
|
+
},
|
|
515
|
+
"smtp": {
|
|
516
|
+
"type": "object",
|
|
517
|
+
"properties": {
|
|
518
|
+
"helo": {
|
|
519
|
+
"type": ["string", "null"],
|
|
520
|
+
"description": "HELO/EHLO hostname from the sending server. Null if not provided during SMTP transaction."
|
|
521
|
+
},
|
|
522
|
+
"mail_from": {
|
|
523
|
+
"type": "string",
|
|
524
|
+
"description": "SMTP envelope sender (MAIL FROM command). This is the bounce address, which may differ from the From header."
|
|
525
|
+
},
|
|
526
|
+
"rcpt_to": {
|
|
527
|
+
"type": "array",
|
|
528
|
+
"items": { "type": "string" },
|
|
529
|
+
"minItems": 1,
|
|
530
|
+
"description": "SMTP envelope recipients (RCPT TO commands). All addresses that received this email in a single delivery."
|
|
531
|
+
}
|
|
532
|
+
},
|
|
533
|
+
"required": [
|
|
534
|
+
"helo",
|
|
535
|
+
"mail_from",
|
|
536
|
+
"rcpt_to"
|
|
537
|
+
],
|
|
538
|
+
"description": "SMTP envelope information. This is the \"real\" sender/recipient info from the SMTP transaction, which may differ from the headers (e.g., BCC recipients)."
|
|
539
|
+
},
|
|
540
|
+
"headers": {
|
|
541
|
+
"type": "object",
|
|
542
|
+
"properties": {
|
|
543
|
+
"message_id": {
|
|
544
|
+
"type": ["string", "null"],
|
|
545
|
+
"description": "Message-ID header value. Null if the email had no Message-ID header."
|
|
546
|
+
},
|
|
547
|
+
"subject": {
|
|
548
|
+
"type": ["string", "null"],
|
|
549
|
+
"description": "Subject header value. Null if the email had no Subject header."
|
|
550
|
+
},
|
|
551
|
+
"from": {
|
|
552
|
+
"type": "string",
|
|
553
|
+
"minLength": 1,
|
|
554
|
+
"description": "From header value. May include display name: `\"John Doe\" <john@example.com>`"
|
|
555
|
+
},
|
|
556
|
+
"to": {
|
|
557
|
+
"type": "string",
|
|
558
|
+
"minLength": 1,
|
|
559
|
+
"description": "To header value. May include multiple addresses or display names."
|
|
560
|
+
},
|
|
561
|
+
"date": {
|
|
562
|
+
"type": ["string", "null"],
|
|
563
|
+
"description": "Date header value as it appeared in the email. Null if the email had no Date header."
|
|
564
|
+
}
|
|
565
|
+
},
|
|
566
|
+
"required": [
|
|
567
|
+
"message_id",
|
|
568
|
+
"subject",
|
|
569
|
+
"from",
|
|
570
|
+
"to",
|
|
571
|
+
"date"
|
|
572
|
+
],
|
|
573
|
+
"description": "Parsed email headers. These are extracted from the email content, not the SMTP envelope."
|
|
574
|
+
},
|
|
575
|
+
"content": {
|
|
576
|
+
"type": "object",
|
|
577
|
+
"properties": {
|
|
578
|
+
"raw": {
|
|
579
|
+
"$ref": "#/definitions/RawContent",
|
|
580
|
+
"description": "Raw email in RFC 5322 format. May be inline (base64) or download-only depending on size."
|
|
581
|
+
},
|
|
582
|
+
"download": {
|
|
583
|
+
"type": "object",
|
|
584
|
+
"properties": {
|
|
585
|
+
"url": {
|
|
586
|
+
"type": "string",
|
|
587
|
+
"format": "uri",
|
|
588
|
+
"pattern": "^https?://",
|
|
589
|
+
"description": "URL to download the raw email as-is in RFC 5322 format. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network (e.g. `http://localhost:4001/...`). Receivers that want to refuse plaintext downloads should check the scheme explicitly."
|
|
590
|
+
},
|
|
591
|
+
"expires_at": {
|
|
592
|
+
"type": "string",
|
|
593
|
+
"format": "date-time",
|
|
594
|
+
"description": "ISO 8601 timestamp (UTC) when this URL expires. Download before this time or the URL will return 403."
|
|
595
|
+
}
|
|
596
|
+
},
|
|
597
|
+
"required": ["url", "expires_at"],
|
|
598
|
+
"description": "Download information for the raw email. Always present, even if raw content is inline."
|
|
599
|
+
}
|
|
600
|
+
},
|
|
601
|
+
"required": ["raw", "download"],
|
|
602
|
+
"description": "Raw email content and download information."
|
|
603
|
+
},
|
|
604
|
+
"parsed": {
|
|
605
|
+
"$ref": "#/definitions/ParsedData",
|
|
606
|
+
"description": "Parsed email content (body text, HTML, attachments). Check `status` to determine if parsing succeeded."
|
|
607
|
+
},
|
|
608
|
+
"analysis": {
|
|
609
|
+
"$ref": "#/definitions/EmailAnalysis",
|
|
610
|
+
"description": "Email analysis and classification results."
|
|
611
|
+
},
|
|
612
|
+
"auth": {
|
|
613
|
+
"$ref": "#/definitions/EmailAuth",
|
|
614
|
+
"description": "Email authentication results (SPF, DKIM, DMARC)."
|
|
615
|
+
}
|
|
616
|
+
},
|
|
617
|
+
"required": [
|
|
618
|
+
"id",
|
|
619
|
+
"received_at",
|
|
620
|
+
"smtp",
|
|
621
|
+
"headers",
|
|
622
|
+
"content",
|
|
623
|
+
"parsed",
|
|
624
|
+
"analysis",
|
|
625
|
+
"auth"
|
|
626
|
+
],
|
|
627
|
+
"description": "The email that triggered this event."
|
|
628
|
+
}
|
|
629
|
+
},
|
|
630
|
+
"required": [
|
|
631
|
+
"id",
|
|
632
|
+
"event",
|
|
633
|
+
"version",
|
|
634
|
+
"delivery",
|
|
635
|
+
"email"
|
|
636
|
+
],
|
|
637
|
+
"description": "Webhook payload for the `email.received` event.\n\nThis is delivered to your webhook endpoint when Primitive receives an email matching your domain configuration."
|
|
638
|
+
},
|
|
639
|
+
"RoutingDecision": {
|
|
640
|
+
"type": "object",
|
|
641
|
+
"description": "The recipient-routing decision for an inbound email: which endpoint it resolved to and why. Present on the event only when recipient routing ran for the organization.",
|
|
642
|
+
"properties": {
|
|
643
|
+
"version": {
|
|
644
|
+
"type": "integer",
|
|
645
|
+
"description": "Decision schema version, so consumers can detect shape changes."
|
|
646
|
+
},
|
|
647
|
+
"outcome": {
|
|
648
|
+
"type": "string",
|
|
649
|
+
"enum": [
|
|
650
|
+
"matched",
|
|
651
|
+
"defaulted",
|
|
652
|
+
"none"
|
|
653
|
+
],
|
|
654
|
+
"description": "How the destination was chosen: `matched` a recipient route, fell back to a `defaulted` destination (domain or org), or `none` (no destination resolved)."
|
|
655
|
+
},
|
|
656
|
+
"endpoint_id": {
|
|
657
|
+
"type": ["string", "null"],
|
|
658
|
+
"description": "The endpoint the email was delivered to, or null when no destination resolved."
|
|
659
|
+
},
|
|
660
|
+
"matched_route_id": {
|
|
661
|
+
"type": ["string", "null"],
|
|
662
|
+
"description": "The recipient route that matched, or null when the outcome was not `matched`."
|
|
663
|
+
},
|
|
664
|
+
"matched_tier": {
|
|
665
|
+
"type": ["string", "null"],
|
|
666
|
+
"enum": [
|
|
667
|
+
"exact",
|
|
668
|
+
"wildcard",
|
|
669
|
+
"regex",
|
|
670
|
+
null
|
|
671
|
+
],
|
|
672
|
+
"description": "The match tier of the route that matched, or null when the outcome was not `matched`."
|
|
673
|
+
},
|
|
674
|
+
"default_scope": {
|
|
675
|
+
"type": ["string", "null"],
|
|
676
|
+
"enum": [
|
|
677
|
+
"domain",
|
|
678
|
+
"org",
|
|
679
|
+
null
|
|
680
|
+
],
|
|
681
|
+
"description": "When the outcome was `defaulted`, whether the default came from the domain or the organization; null otherwise."
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
"required": ["outcome"]
|
|
685
|
+
},
|
|
686
|
+
"WebhookVersion": {
|
|
687
|
+
"type": "string",
|
|
688
|
+
"pattern": "^(?:(?:\\d{4}-(?:(?:01|03|05|07|08|10|12)-(?:0[1-9]|[12]\\d|3[01])|(?:04|06|09|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8])))|(?:(?:[02468][048]00|[13579][26]00|\\d{2}(?:0[48]|[2468][048]|[13579][26]))-02-29))$",
|
|
689
|
+
"description": "Valid webhook version format (YYYY-MM-DD date string). The SDK accepts any valid date-formatted version, not just the current one, for forward and backward compatibility."
|
|
690
|
+
},
|
|
691
|
+
"RawContent": {
|
|
692
|
+
"anyOf": [{ "$ref": "#/definitions/RawContentInline" }, { "$ref": "#/definitions/RawContentDownloadOnly" }],
|
|
693
|
+
"description": "Raw email content - a discriminated union on `included`."
|
|
694
|
+
},
|
|
695
|
+
"RawContentInline": {
|
|
696
|
+
"type": "object",
|
|
697
|
+
"properties": {
|
|
698
|
+
"included": {
|
|
699
|
+
"type": "boolean",
|
|
700
|
+
"const": true,
|
|
701
|
+
"description": "Discriminant indicating raw content is included inline."
|
|
702
|
+
},
|
|
703
|
+
"encoding": {
|
|
704
|
+
"type": "string",
|
|
705
|
+
"const": "base64",
|
|
706
|
+
"description": "Encoding used for the data field. Always \"base64\"."
|
|
707
|
+
},
|
|
708
|
+
"max_inline_bytes": {
|
|
709
|
+
"type": "integer",
|
|
710
|
+
"minimum": 1,
|
|
711
|
+
"description": "Maximum size in bytes for inline inclusion. Emails larger than this threshold require download."
|
|
712
|
+
},
|
|
713
|
+
"size_bytes": {
|
|
714
|
+
"type": "integer",
|
|
715
|
+
"minimum": 0,
|
|
716
|
+
"description": "Actual size of the raw email in bytes."
|
|
717
|
+
},
|
|
718
|
+
"sha256": {
|
|
719
|
+
"type": "string",
|
|
720
|
+
"pattern": "^[a-fA-F0-9]{64}$",
|
|
721
|
+
"description": "SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after base64 decoding."
|
|
722
|
+
},
|
|
723
|
+
"data": {
|
|
724
|
+
"type": "string",
|
|
725
|
+
"description": "Base64-encoded raw email (RFC 5322 format). Decode with `Buffer.from(data, 'base64')` in Node.js."
|
|
726
|
+
}
|
|
727
|
+
},
|
|
728
|
+
"required": [
|
|
729
|
+
"included",
|
|
730
|
+
"encoding",
|
|
731
|
+
"max_inline_bytes",
|
|
732
|
+
"size_bytes",
|
|
733
|
+
"sha256",
|
|
734
|
+
"data"
|
|
735
|
+
],
|
|
736
|
+
"description": "Raw email content included inline (base64 encoded).\n\nWhen the raw email is small enough (under {@link max_inline_bytes } ), it's included directly in the webhook payload for convenience."
|
|
737
|
+
},
|
|
738
|
+
"RawContentDownloadOnly": {
|
|
739
|
+
"type": "object",
|
|
740
|
+
"properties": {
|
|
741
|
+
"included": {
|
|
742
|
+
"type": "boolean",
|
|
743
|
+
"const": false,
|
|
744
|
+
"description": "Discriminant indicating raw content must be downloaded."
|
|
745
|
+
},
|
|
746
|
+
"reason_code": {
|
|
747
|
+
"type": "string",
|
|
748
|
+
"const": "size_exceeded",
|
|
749
|
+
"description": "Reason the content wasn't included inline."
|
|
750
|
+
},
|
|
751
|
+
"max_inline_bytes": {
|
|
752
|
+
"type": "integer",
|
|
753
|
+
"minimum": 1,
|
|
754
|
+
"description": "Maximum size in bytes for inline inclusion. The email exceeded this threshold."
|
|
755
|
+
},
|
|
756
|
+
"size_bytes": {
|
|
757
|
+
"type": "integer",
|
|
758
|
+
"minimum": 0,
|
|
759
|
+
"description": "Actual size of the raw email in bytes."
|
|
760
|
+
},
|
|
761
|
+
"sha256": {
|
|
762
|
+
"type": "string",
|
|
763
|
+
"pattern": "^[a-fA-F0-9]{64}$",
|
|
764
|
+
"description": "SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after download."
|
|
765
|
+
}
|
|
766
|
+
},
|
|
767
|
+
"required": [
|
|
768
|
+
"included",
|
|
769
|
+
"reason_code",
|
|
770
|
+
"max_inline_bytes",
|
|
771
|
+
"size_bytes",
|
|
772
|
+
"sha256"
|
|
773
|
+
],
|
|
774
|
+
"description": "Raw email content not included (must be downloaded).\n\nWhen the raw email exceeds {@link max_inline_bytes } , it's not included in the webhook payload. Use the download URL from {@link EmailReceivedEvent.email.content.download } to fetch it."
|
|
775
|
+
},
|
|
776
|
+
"ParsedData": {
|
|
777
|
+
"anyOf": [{ "$ref": "#/definitions/ParsedDataComplete" }, { "$ref": "#/definitions/ParsedDataFailed" }],
|
|
778
|
+
"description": "Parsed email content - a discriminated union on `status`."
|
|
779
|
+
},
|
|
780
|
+
"ParsedDataComplete": {
|
|
781
|
+
"type": "object",
|
|
782
|
+
"properties": {
|
|
783
|
+
"status": {
|
|
784
|
+
"type": "string",
|
|
785
|
+
"const": "complete",
|
|
786
|
+
"description": "Discriminant indicating successful parsing."
|
|
787
|
+
},
|
|
788
|
+
"error": {
|
|
789
|
+
"type": "null",
|
|
790
|
+
"description": "Always null when parsing succeeds."
|
|
791
|
+
},
|
|
792
|
+
"body_text": {
|
|
793
|
+
"type": ["string", "null"],
|
|
794
|
+
"description": "Plain text body of the email. Null if the email had no text/plain part."
|
|
795
|
+
},
|
|
796
|
+
"body_html": {
|
|
797
|
+
"type": ["string", "null"],
|
|
798
|
+
"description": "HTML body of the email. Null if the email had no text/html part."
|
|
799
|
+
},
|
|
800
|
+
"reply_to": {
|
|
801
|
+
"anyOf": [{
|
|
802
|
+
"type": "array",
|
|
803
|
+
"items": { "$ref": "#/definitions/EmailAddress" }
|
|
804
|
+
}, { "type": "null" }],
|
|
805
|
+
"description": "Parsed Reply-To header addresses. Null if the email had no Reply-To header."
|
|
806
|
+
},
|
|
807
|
+
"cc": {
|
|
808
|
+
"anyOf": [{
|
|
809
|
+
"type": "array",
|
|
810
|
+
"items": { "$ref": "#/definitions/EmailAddress" }
|
|
811
|
+
}, { "type": "null" }],
|
|
812
|
+
"description": "Parsed CC header addresses. Null if the email had no CC header."
|
|
813
|
+
},
|
|
814
|
+
"bcc": {
|
|
815
|
+
"anyOf": [{
|
|
816
|
+
"type": "array",
|
|
817
|
+
"items": { "$ref": "#/definitions/EmailAddress" }
|
|
818
|
+
}, { "type": "null" }],
|
|
819
|
+
"description": "Parsed BCC header addresses. Null if the email had no BCC header. Note: BCC is only available for outgoing emails or when explicitly provided."
|
|
820
|
+
},
|
|
821
|
+
"to_addresses": {
|
|
822
|
+
"anyOf": [{
|
|
823
|
+
"type": "array",
|
|
824
|
+
"items": { "$ref": "#/definitions/EmailAddress" }
|
|
825
|
+
}, { "type": "null" }],
|
|
826
|
+
"description": "Parsed To header addresses. Null if the email had no To header."
|
|
827
|
+
},
|
|
828
|
+
"in_reply_to": {
|
|
829
|
+
"anyOf": [{
|
|
830
|
+
"type": "array",
|
|
831
|
+
"items": { "type": "string" }
|
|
832
|
+
}, { "type": "null" }],
|
|
833
|
+
"description": "In-Reply-To header values (Message-IDs of the email(s) being replied to). Null if the email had no In-Reply-To header. Per RFC 5322, this can contain multiple Message-IDs, though typically just one.",
|
|
834
|
+
"examples": [["<original-message-id@example.com>"]]
|
|
835
|
+
},
|
|
836
|
+
"references": {
|
|
837
|
+
"anyOf": [{
|
|
838
|
+
"type": "array",
|
|
839
|
+
"items": { "type": "string" }
|
|
840
|
+
}, { "type": "null" }],
|
|
841
|
+
"description": "References header values (Message-IDs of the email thread). Null if the email had no References header.",
|
|
842
|
+
"examples": [["<msg1@example.com>", "<msg2@example.com>"]]
|
|
843
|
+
},
|
|
844
|
+
"attachments": {
|
|
845
|
+
"type": "array",
|
|
846
|
+
"items": { "$ref": "#/definitions/WebhookAttachment" },
|
|
847
|
+
"description": "List of attachments with metadata. Use {@link attachments_download_url } to download the actual files."
|
|
848
|
+
},
|
|
849
|
+
"attachments_download_url": {
|
|
850
|
+
"type": ["string", "null"],
|
|
851
|
+
"format": "uri",
|
|
852
|
+
"pattern": "^https?://",
|
|
853
|
+
"description": "URL to download all attachments as a tar.gz archive. Null if the email had no attachments. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network. URL expires - check the expiration before downloading."
|
|
854
|
+
}
|
|
855
|
+
},
|
|
856
|
+
"required": [
|
|
857
|
+
"status",
|
|
858
|
+
"error",
|
|
859
|
+
"body_text",
|
|
860
|
+
"body_html",
|
|
861
|
+
"reply_to",
|
|
862
|
+
"cc",
|
|
863
|
+
"bcc",
|
|
864
|
+
"to_addresses",
|
|
865
|
+
"in_reply_to",
|
|
866
|
+
"references",
|
|
867
|
+
"attachments",
|
|
868
|
+
"attachments_download_url"
|
|
869
|
+
],
|
|
870
|
+
"description": "Parsed email content when parsing succeeded.\n\nUse the discriminant `status: \"complete\"` to narrow from {@link ParsedData } ."
|
|
871
|
+
},
|
|
872
|
+
"EmailAddress": {
|
|
873
|
+
"type": "object",
|
|
874
|
+
"properties": {
|
|
875
|
+
"address": {
|
|
876
|
+
"type": "string",
|
|
877
|
+
"description": "The email address portion (e.g., \"john@example.com\").\n\nThis is the raw value from the email header with no validation applied. May contain unusual but valid formats like quoted local parts."
|
|
878
|
+
},
|
|
879
|
+
"name": {
|
|
880
|
+
"type": ["string", "null"],
|
|
881
|
+
"description": "The display name portion, if present. Null if the address had no display name.\n\nMay contain any characters including unicode, emoji, or special characters as they appeared in the original email header."
|
|
882
|
+
}
|
|
883
|
+
},
|
|
884
|
+
"required": ["address", "name"],
|
|
885
|
+
"description": "A parsed email address with optional display name.\n\nThis structure is used in the `parsed` section of the webhook payload (e.g., `reply_to`, `cc`, `bcc`). For unparsed header strings, see the `headers` section (e.g., `event.email.headers.from`)."
|
|
886
|
+
},
|
|
887
|
+
"WebhookAttachment": {
|
|
888
|
+
"type": "object",
|
|
889
|
+
"properties": {
|
|
890
|
+
"filename": {
|
|
891
|
+
"type": ["string", "null"],
|
|
892
|
+
"description": "Original filename from the email. May be null if the attachment had no filename specified."
|
|
893
|
+
},
|
|
894
|
+
"content_type": {
|
|
895
|
+
"type": "string",
|
|
896
|
+
"description": "MIME content type (e.g., \"application/pdf\", \"image/png\")."
|
|
897
|
+
},
|
|
898
|
+
"size_bytes": {
|
|
899
|
+
"type": "integer",
|
|
900
|
+
"minimum": 0,
|
|
901
|
+
"description": "Size of the attachment in bytes."
|
|
902
|
+
},
|
|
903
|
+
"sha256": {
|
|
904
|
+
"type": "string",
|
|
905
|
+
"pattern": "^[a-fA-F0-9]{64}$",
|
|
906
|
+
"description": "SHA-256 hash of the attachment content (hex-encoded). Use this to verify attachment integrity after download."
|
|
907
|
+
},
|
|
908
|
+
"part_index": {
|
|
909
|
+
"type": "integer",
|
|
910
|
+
"minimum": 0,
|
|
911
|
+
"description": "Zero-based index of this part in the MIME structure."
|
|
912
|
+
},
|
|
913
|
+
"tar_path": {
|
|
914
|
+
"type": "string",
|
|
915
|
+
"description": "Path to this attachment within the downloaded tar.gz archive."
|
|
916
|
+
}
|
|
917
|
+
},
|
|
918
|
+
"required": [
|
|
919
|
+
"filename",
|
|
920
|
+
"content_type",
|
|
921
|
+
"size_bytes",
|
|
922
|
+
"sha256",
|
|
923
|
+
"part_index",
|
|
924
|
+
"tar_path"
|
|
925
|
+
],
|
|
926
|
+
"description": "Metadata for an email attachment.\n\nAttachment content is not included directly in the webhook payload. Use the `attachments_download_url` from {@link ParsedDataComplete } to download all attachments as a tar.gz archive."
|
|
927
|
+
},
|
|
928
|
+
"ParsedDataFailed": {
|
|
929
|
+
"type": "object",
|
|
930
|
+
"properties": {
|
|
931
|
+
"status": {
|
|
932
|
+
"type": "string",
|
|
933
|
+
"const": "failed",
|
|
934
|
+
"description": "Discriminant indicating parsing failed."
|
|
935
|
+
},
|
|
936
|
+
"error": {
|
|
937
|
+
"$ref": "#/definitions/ParsedError",
|
|
938
|
+
"description": "Details about why parsing failed."
|
|
939
|
+
},
|
|
940
|
+
"body_text": {
|
|
941
|
+
"type": "null",
|
|
942
|
+
"description": "Always null when parsing fails."
|
|
943
|
+
},
|
|
944
|
+
"body_html": {
|
|
945
|
+
"type": "null",
|
|
946
|
+
"description": "Always null when parsing fails."
|
|
947
|
+
},
|
|
948
|
+
"reply_to": {
|
|
949
|
+
"type": "null",
|
|
950
|
+
"description": "Always null when parsing fails."
|
|
951
|
+
},
|
|
952
|
+
"cc": {
|
|
953
|
+
"type": "null",
|
|
954
|
+
"description": "Always null when parsing fails."
|
|
955
|
+
},
|
|
956
|
+
"bcc": {
|
|
957
|
+
"type": "null",
|
|
958
|
+
"description": "Always null when parsing fails."
|
|
959
|
+
},
|
|
960
|
+
"to_addresses": {
|
|
961
|
+
"type": "null",
|
|
962
|
+
"description": "Always null when parsing fails."
|
|
963
|
+
},
|
|
964
|
+
"in_reply_to": {
|
|
965
|
+
"type": "null",
|
|
966
|
+
"description": "Always null when parsing fails."
|
|
967
|
+
},
|
|
968
|
+
"references": {
|
|
969
|
+
"type": "null",
|
|
970
|
+
"description": "Always null when parsing fails."
|
|
971
|
+
},
|
|
972
|
+
"attachments": {
|
|
973
|
+
"type": "array",
|
|
974
|
+
"items": { "$ref": "#/definitions/WebhookAttachment" },
|
|
975
|
+
"description": "May contain partial attachment metadata even when parsing failed. Useful for debugging or recovering partial data."
|
|
976
|
+
},
|
|
977
|
+
"attachments_download_url": {
|
|
978
|
+
"type": "null",
|
|
979
|
+
"description": "Always null when parsing fails."
|
|
980
|
+
}
|
|
981
|
+
},
|
|
982
|
+
"required": [
|
|
983
|
+
"status",
|
|
984
|
+
"error",
|
|
985
|
+
"body_text",
|
|
986
|
+
"body_html",
|
|
987
|
+
"reply_to",
|
|
988
|
+
"cc",
|
|
989
|
+
"bcc",
|
|
990
|
+
"to_addresses",
|
|
991
|
+
"in_reply_to",
|
|
992
|
+
"references",
|
|
993
|
+
"attachments",
|
|
994
|
+
"attachments_download_url"
|
|
995
|
+
],
|
|
996
|
+
"description": "Parsed email content when parsing failed.\n\nUse the discriminant `status: \"failed\"` to narrow from {@link ParsedData } ."
|
|
997
|
+
},
|
|
998
|
+
"ParsedError": {
|
|
999
|
+
"type": "object",
|
|
1000
|
+
"properties": {
|
|
1001
|
+
"code": {
|
|
1002
|
+
"type": "string",
|
|
1003
|
+
"enum": ["PARSE_FAILED", "ATTACHMENT_EXTRACTION_FAILED"],
|
|
1004
|
+
"description": "Error code indicating the type of failure.\n- `PARSE_FAILED`: The email could not be parsed (e.g., malformed MIME)\n- `ATTACHMENT_EXTRACTION_FAILED`: Email parsed but attachments couldn't be extracted"
|
|
1005
|
+
},
|
|
1006
|
+
"message": {
|
|
1007
|
+
"type": "string",
|
|
1008
|
+
"description": "Human-readable error message describing what went wrong."
|
|
1009
|
+
},
|
|
1010
|
+
"retryable": {
|
|
1011
|
+
"type": "boolean",
|
|
1012
|
+
"description": "Whether retrying might succeed. If true, the error was transient (e.g., timeout). If false, the email itself is problematic."
|
|
1013
|
+
}
|
|
1014
|
+
},
|
|
1015
|
+
"required": [
|
|
1016
|
+
"code",
|
|
1017
|
+
"message",
|
|
1018
|
+
"retryable"
|
|
1019
|
+
],
|
|
1020
|
+
"description": "Error details when email parsing fails."
|
|
1021
|
+
},
|
|
1022
|
+
"EmailAnalysis": {
|
|
1023
|
+
"type": "object",
|
|
1024
|
+
"properties": {
|
|
1025
|
+
"spamassassin": {
|
|
1026
|
+
"type": "object",
|
|
1027
|
+
"properties": { "score": {
|
|
1028
|
+
"type": "number",
|
|
1029
|
+
"description": "Overall spam score (sum of all rule scores). Higher scores indicate higher likelihood of spam. Unbounded - can be negative (ham) or very high (spam)."
|
|
1030
|
+
} },
|
|
1031
|
+
"required": ["score"],
|
|
1032
|
+
"description": "SpamAssassin analysis results.\n\nOptional. Present when the email was processed by a SpamAssassin-equipped pipeline (always present in Primitive's managed service). When absent, spam scoring was not performed on this email."
|
|
1033
|
+
},
|
|
1034
|
+
"forward": {
|
|
1035
|
+
"$ref": "#/definitions/ForwardAnalysis",
|
|
1036
|
+
"description": "Forward detection and analysis results.\n\nOptional. In Primitive's managed service this object is included only when forwarded content is detected; when absent, no forward was detected or forward detection was not performed."
|
|
1037
|
+
},
|
|
1038
|
+
"bounce": {
|
|
1039
|
+
"$ref": "#/definitions/BounceAnalysis",
|
|
1040
|
+
"description": "Bounce (delivery status notification) analysis.\n\nPresent on `email.bounced` events: the parsed DSN reporting that a message you sent could not be delivered. Absent on all other event types."
|
|
1041
|
+
},
|
|
1042
|
+
"tls_report": {
|
|
1043
|
+
"$ref": "#/definitions/TlsReportAnalysis",
|
|
1044
|
+
"description": "SMTP TLS report analysis (RFC 8460).\n\nPresent on `email.tls_report` events: a remote MTA's report of TLS negotiation results for mail sent to your domain. Absent on all other event types."
|
|
1045
|
+
},
|
|
1046
|
+
"dmarc_report": {
|
|
1047
|
+
"$ref": "#/definitions/DmarcReportAnalysis",
|
|
1048
|
+
"description": "DMARC aggregate report analysis (RFC 7489).\n\nPresent on `email.dmarc_report` events: a receiver's periodic aggregate report of DMARC authentication results for your domain. Absent on all other event types."
|
|
1049
|
+
}
|
|
1050
|
+
},
|
|
1051
|
+
"description": "Email analysis and classification results.\n\nAll properties in this object are optional. Which fields are present depends on the analysis pipeline processing the email. Primitive's managed service populates all fields. Self-hosted or third-party deployments may include some, all, or none of these fields depending on their pipeline configuration.\n\nWhen a field is absent, it means that particular analysis was not performed, not that the analysis produced no results. For example, a missing `spamassassin` field means SpamAssassin was not run, not that the email scored 0.\n\nThese fields may be omitted from the payload entirely but must not be set to null."
|
|
1052
|
+
},
|
|
1053
|
+
"BounceAnalysis": {
|
|
1054
|
+
"type": "object",
|
|
1055
|
+
"properties": {
|
|
1056
|
+
"is_bounce": {
|
|
1057
|
+
"type": "boolean",
|
|
1058
|
+
"const": true,
|
|
1059
|
+
"description": "Always `true` on a parsed bounce."
|
|
1060
|
+
},
|
|
1061
|
+
"kind": {
|
|
1062
|
+
"type": "string",
|
|
1063
|
+
"const": "dsn",
|
|
1064
|
+
"description": "The machine-mail kind. Always `dsn` for a bounce."
|
|
1065
|
+
},
|
|
1066
|
+
"type": {
|
|
1067
|
+
"type": "string",
|
|
1068
|
+
"enum": [
|
|
1069
|
+
"permanent",
|
|
1070
|
+
"transient",
|
|
1071
|
+
"undetermined"
|
|
1072
|
+
],
|
|
1073
|
+
"description": "Whether the failure is permanent (hard bounce), transient (soft bounce, may be retried), or undetermined."
|
|
1074
|
+
},
|
|
1075
|
+
"category": {
|
|
1076
|
+
"type": "string",
|
|
1077
|
+
"enum": [
|
|
1078
|
+
"mailbox_does_not_exist",
|
|
1079
|
+
"domain_does_not_exist",
|
|
1080
|
+
"domain_not_accepting_mail",
|
|
1081
|
+
"mailbox_full",
|
|
1082
|
+
"mailbox_inactive",
|
|
1083
|
+
"message_too_large",
|
|
1084
|
+
"content_rejected",
|
|
1085
|
+
"policy_blocked",
|
|
1086
|
+
"auth_failure",
|
|
1087
|
+
"relay_denied",
|
|
1088
|
+
"rate_limited",
|
|
1089
|
+
"network_error",
|
|
1090
|
+
"recipient_moved",
|
|
1091
|
+
"expired",
|
|
1092
|
+
"undetermined"
|
|
1093
|
+
],
|
|
1094
|
+
"description": "Best-effort reason category for the failure."
|
|
1095
|
+
},
|
|
1096
|
+
"classified_by": {
|
|
1097
|
+
"type": "string",
|
|
1098
|
+
"enum": [
|
|
1099
|
+
"status_code",
|
|
1100
|
+
"smtp_code",
|
|
1101
|
+
"pattern",
|
|
1102
|
+
"provider",
|
|
1103
|
+
"none"
|
|
1104
|
+
],
|
|
1105
|
+
"description": "Which signal produced `category` (for transparency and debugging)."
|
|
1106
|
+
},
|
|
1107
|
+
"failed_recipient": {
|
|
1108
|
+
"type": ["string", "null"],
|
|
1109
|
+
"description": "The recipient address that failed, if the report identifies one."
|
|
1110
|
+
},
|
|
1111
|
+
"smtp_code": {
|
|
1112
|
+
"type": ["integer", "null"],
|
|
1113
|
+
"description": "SMTP reply code (e.g. `550`), if reported."
|
|
1114
|
+
},
|
|
1115
|
+
"status_code": {
|
|
1116
|
+
"type": ["string", "null"],
|
|
1117
|
+
"description": "Enhanced mail system status code (RFC 3463, e.g. `5.1.1`), if reported."
|
|
1118
|
+
},
|
|
1119
|
+
"diagnostic_code": {
|
|
1120
|
+
"type": ["string", "null"],
|
|
1121
|
+
"description": "Raw diagnostic text from the reporting MTA, if present."
|
|
1122
|
+
},
|
|
1123
|
+
"reported_by_mta": {
|
|
1124
|
+
"type": ["string", "null"],
|
|
1125
|
+
"description": "The MTA that generated the report, if identifiable."
|
|
1126
|
+
},
|
|
1127
|
+
"original_message_id": {
|
|
1128
|
+
"type": ["string", "null"],
|
|
1129
|
+
"description": "Message-ID of the original message that bounced, if recoverable. Match this against the `message_id` of a message you sent to correlate the bounce."
|
|
1130
|
+
},
|
|
1131
|
+
"reasons": {
|
|
1132
|
+
"type": "array",
|
|
1133
|
+
"items": { "type": "string" },
|
|
1134
|
+
"description": "Human-readable reason strings extracted from the report."
|
|
1135
|
+
}
|
|
1136
|
+
},
|
|
1137
|
+
"required": [
|
|
1138
|
+
"is_bounce",
|
|
1139
|
+
"kind",
|
|
1140
|
+
"type",
|
|
1141
|
+
"category",
|
|
1142
|
+
"classified_by",
|
|
1143
|
+
"failed_recipient",
|
|
1144
|
+
"smtp_code",
|
|
1145
|
+
"status_code",
|
|
1146
|
+
"diagnostic_code",
|
|
1147
|
+
"reported_by_mta",
|
|
1148
|
+
"original_message_id",
|
|
1149
|
+
"reasons"
|
|
1150
|
+
],
|
|
1151
|
+
"description": "Parsed delivery status notification (bounce). Present as `email.analysis.bounce` on `email.bounced` events."
|
|
1152
|
+
},
|
|
1153
|
+
"TlsReportFailure": {
|
|
1154
|
+
"type": "object",
|
|
1155
|
+
"properties": {
|
|
1156
|
+
"result_type": {
|
|
1157
|
+
"type": ["string", "null"],
|
|
1158
|
+
"description": "Failure result type (e.g. `certificate-expired`, `starttls-not-supported`)."
|
|
1159
|
+
},
|
|
1160
|
+
"count": {
|
|
1161
|
+
"type": "integer",
|
|
1162
|
+
"description": "Number of sessions that hit this failure."
|
|
1163
|
+
},
|
|
1164
|
+
"sending_mta_ip": { "type": ["string", "null"] },
|
|
1165
|
+
"receiving_mx_hostname": { "type": ["string", "null"] }
|
|
1166
|
+
},
|
|
1167
|
+
"required": [
|
|
1168
|
+
"result_type",
|
|
1169
|
+
"count",
|
|
1170
|
+
"sending_mta_ip",
|
|
1171
|
+
"receiving_mx_hostname"
|
|
1172
|
+
]
|
|
1173
|
+
},
|
|
1174
|
+
"TlsReportPolicy": {
|
|
1175
|
+
"type": "object",
|
|
1176
|
+
"properties": {
|
|
1177
|
+
"policy_domain": { "type": ["string", "null"] },
|
|
1178
|
+
"policy_type": {
|
|
1179
|
+
"type": ["string", "null"],
|
|
1180
|
+
"description": "Policy type the sessions were evaluated against (e.g. `sts`, `tlsa`, `no-policy-found`)."
|
|
1181
|
+
},
|
|
1182
|
+
"successful_sessions": { "type": "integer" },
|
|
1183
|
+
"failed_sessions": { "type": "integer" },
|
|
1184
|
+
"failures": {
|
|
1185
|
+
"type": "array",
|
|
1186
|
+
"items": { "$ref": "#/definitions/TlsReportFailure" }
|
|
1187
|
+
}
|
|
1188
|
+
},
|
|
1189
|
+
"required": [
|
|
1190
|
+
"policy_domain",
|
|
1191
|
+
"policy_type",
|
|
1192
|
+
"successful_sessions",
|
|
1193
|
+
"failed_sessions",
|
|
1194
|
+
"failures"
|
|
1195
|
+
]
|
|
1196
|
+
},
|
|
1197
|
+
"TlsReportAnalysis": {
|
|
1198
|
+
"type": "object",
|
|
1199
|
+
"properties": {
|
|
1200
|
+
"kind": {
|
|
1201
|
+
"type": "string",
|
|
1202
|
+
"const": "tls_report"
|
|
1203
|
+
},
|
|
1204
|
+
"organization": {
|
|
1205
|
+
"type": ["string", "null"],
|
|
1206
|
+
"description": "Reporting organization name."
|
|
1207
|
+
},
|
|
1208
|
+
"report_id": { "type": ["string", "null"] },
|
|
1209
|
+
"contact": {
|
|
1210
|
+
"type": ["string", "null"],
|
|
1211
|
+
"description": "Reporter contact, if provided."
|
|
1212
|
+
},
|
|
1213
|
+
"date_range": {
|
|
1214
|
+
"type": "object",
|
|
1215
|
+
"properties": {
|
|
1216
|
+
"start": {
|
|
1217
|
+
"type": ["string", "null"],
|
|
1218
|
+
"description": "ISO 8601 start of the reporting window."
|
|
1219
|
+
},
|
|
1220
|
+
"end": {
|
|
1221
|
+
"type": ["string", "null"],
|
|
1222
|
+
"description": "ISO 8601 end of the reporting window."
|
|
1223
|
+
}
|
|
1224
|
+
},
|
|
1225
|
+
"required": ["start", "end"]
|
|
1226
|
+
},
|
|
1227
|
+
"total_successful_sessions": { "type": "integer" },
|
|
1228
|
+
"total_failed_sessions": { "type": "integer" },
|
|
1229
|
+
"policies": {
|
|
1230
|
+
"type": "array",
|
|
1231
|
+
"items": { "$ref": "#/definitions/TlsReportPolicy" }
|
|
1232
|
+
}
|
|
1233
|
+
},
|
|
1234
|
+
"required": [
|
|
1235
|
+
"kind",
|
|
1236
|
+
"organization",
|
|
1237
|
+
"report_id",
|
|
1238
|
+
"contact",
|
|
1239
|
+
"date_range",
|
|
1240
|
+
"total_successful_sessions",
|
|
1241
|
+
"total_failed_sessions",
|
|
1242
|
+
"policies"
|
|
1243
|
+
],
|
|
1244
|
+
"description": "Parsed SMTP TLS report (RFC 8460). Present as `email.analysis.tls_report` on `email.tls_report` events."
|
|
1245
|
+
},
|
|
1246
|
+
"DmarcRecord": {
|
|
1247
|
+
"type": "object",
|
|
1248
|
+
"properties": {
|
|
1249
|
+
"source_ip": { "type": ["string", "null"] },
|
|
1250
|
+
"count": { "type": "integer" },
|
|
1251
|
+
"disposition": {
|
|
1252
|
+
"type": ["string", "null"],
|
|
1253
|
+
"description": "Disposition applied by the receiver: `none`, `quarantine`, or `reject`."
|
|
1254
|
+
},
|
|
1255
|
+
"dkim": {
|
|
1256
|
+
"type": ["string", "null"],
|
|
1257
|
+
"description": "DKIM alignment result: `pass` or `fail`."
|
|
1258
|
+
},
|
|
1259
|
+
"spf": {
|
|
1260
|
+
"type": ["string", "null"],
|
|
1261
|
+
"description": "SPF alignment result: `pass` or `fail`."
|
|
1262
|
+
},
|
|
1263
|
+
"header_from": { "type": ["string", "null"] }
|
|
1264
|
+
},
|
|
1265
|
+
"required": [
|
|
1266
|
+
"source_ip",
|
|
1267
|
+
"count",
|
|
1268
|
+
"disposition",
|
|
1269
|
+
"dkim",
|
|
1270
|
+
"spf",
|
|
1271
|
+
"header_from"
|
|
1272
|
+
]
|
|
1273
|
+
},
|
|
1274
|
+
"DmarcReportAnalysis": {
|
|
1275
|
+
"type": "object",
|
|
1276
|
+
"properties": {
|
|
1277
|
+
"kind": {
|
|
1278
|
+
"type": "string",
|
|
1279
|
+
"const": "dmarc_report"
|
|
1280
|
+
},
|
|
1281
|
+
"organization": { "type": ["string", "null"] },
|
|
1282
|
+
"report_id": { "type": ["string", "null"] },
|
|
1283
|
+
"date_range": {
|
|
1284
|
+
"type": "object",
|
|
1285
|
+
"properties": {
|
|
1286
|
+
"start": {
|
|
1287
|
+
"type": ["string", "null"],
|
|
1288
|
+
"description": "ISO 8601 start of the reporting window."
|
|
1289
|
+
},
|
|
1290
|
+
"end": {
|
|
1291
|
+
"type": ["string", "null"],
|
|
1292
|
+
"description": "ISO 8601 end of the reporting window."
|
|
1293
|
+
}
|
|
1294
|
+
},
|
|
1295
|
+
"required": ["start", "end"]
|
|
1296
|
+
},
|
|
1297
|
+
"policy_published": {
|
|
1298
|
+
"type": "object",
|
|
1299
|
+
"properties": {
|
|
1300
|
+
"domain": { "type": ["string", "null"] },
|
|
1301
|
+
"p": {
|
|
1302
|
+
"type": ["string", "null"],
|
|
1303
|
+
"description": "Published domain policy: `none`, `quarantine`, or `reject`."
|
|
1304
|
+
},
|
|
1305
|
+
"sp": {
|
|
1306
|
+
"type": ["string", "null"],
|
|
1307
|
+
"description": "Published subdomain policy."
|
|
1308
|
+
},
|
|
1309
|
+
"pct": {
|
|
1310
|
+
"type": ["integer", "null"],
|
|
1311
|
+
"description": "Percentage of messages the policy is applied to."
|
|
1312
|
+
},
|
|
1313
|
+
"adkim": {
|
|
1314
|
+
"type": ["string", "null"],
|
|
1315
|
+
"description": "DKIM alignment mode: `r` (relaxed) or `s` (strict)."
|
|
1316
|
+
},
|
|
1317
|
+
"aspf": {
|
|
1318
|
+
"type": ["string", "null"],
|
|
1319
|
+
"description": "SPF alignment mode: `r` (relaxed) or `s` (strict)."
|
|
1320
|
+
}
|
|
1321
|
+
},
|
|
1322
|
+
"required": [
|
|
1323
|
+
"domain",
|
|
1324
|
+
"p",
|
|
1325
|
+
"sp",
|
|
1326
|
+
"pct",
|
|
1327
|
+
"adkim",
|
|
1328
|
+
"aspf"
|
|
1329
|
+
]
|
|
1330
|
+
},
|
|
1331
|
+
"total_count": {
|
|
1332
|
+
"type": "integer",
|
|
1333
|
+
"description": "Total messages covered by the report."
|
|
1334
|
+
},
|
|
1335
|
+
"dkim_pass_count": { "type": "integer" },
|
|
1336
|
+
"spf_pass_count": { "type": "integer" },
|
|
1337
|
+
"records": {
|
|
1338
|
+
"type": "array",
|
|
1339
|
+
"items": { "$ref": "#/definitions/DmarcRecord" }
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
"required": [
|
|
1343
|
+
"kind",
|
|
1344
|
+
"organization",
|
|
1345
|
+
"report_id",
|
|
1346
|
+
"date_range",
|
|
1347
|
+
"policy_published",
|
|
1348
|
+
"total_count",
|
|
1349
|
+
"dkim_pass_count",
|
|
1350
|
+
"spf_pass_count",
|
|
1351
|
+
"records"
|
|
1352
|
+
],
|
|
1353
|
+
"description": "Parsed DMARC aggregate report (RFC 7489). Present as `email.analysis.dmarc_report` on `email.dmarc_report` events."
|
|
1354
|
+
},
|
|
1355
|
+
"ForwardAnalysis": {
|
|
1356
|
+
"type": "object",
|
|
1357
|
+
"properties": {
|
|
1358
|
+
"detected": {
|
|
1359
|
+
"type": "boolean",
|
|
1360
|
+
"description": "Whether any forwards were detected in the email."
|
|
1361
|
+
},
|
|
1362
|
+
"results": {
|
|
1363
|
+
"type": "array",
|
|
1364
|
+
"items": { "$ref": "#/definitions/ForwardResult" },
|
|
1365
|
+
"description": "Analysis results for each detected forward."
|
|
1366
|
+
},
|
|
1367
|
+
"attachments_found": {
|
|
1368
|
+
"type": "integer",
|
|
1369
|
+
"minimum": 0,
|
|
1370
|
+
"description": "Total number of .eml attachments found."
|
|
1371
|
+
},
|
|
1372
|
+
"attachments_analyzed": {
|
|
1373
|
+
"type": "integer",
|
|
1374
|
+
"minimum": 0,
|
|
1375
|
+
"description": "Number of .eml attachments that were analyzed."
|
|
1376
|
+
},
|
|
1377
|
+
"attachments_limit": {
|
|
1378
|
+
"type": ["integer", "null"],
|
|
1379
|
+
"minimum": 1,
|
|
1380
|
+
"description": "Maximum number of attachments that will be analyzed, or null if unlimited."
|
|
1381
|
+
}
|
|
1382
|
+
},
|
|
1383
|
+
"required": [
|
|
1384
|
+
"detected",
|
|
1385
|
+
"results",
|
|
1386
|
+
"attachments_found",
|
|
1387
|
+
"attachments_analyzed",
|
|
1388
|
+
"attachments_limit"
|
|
1389
|
+
],
|
|
1390
|
+
"description": "Forward detection and analysis results."
|
|
1391
|
+
},
|
|
1392
|
+
"ForwardResult": {
|
|
1393
|
+
"anyOf": [
|
|
1394
|
+
{ "$ref": "#/definitions/ForwardResultInline" },
|
|
1395
|
+
{ "$ref": "#/definitions/ForwardResultAttachmentAnalyzed" },
|
|
1396
|
+
{ "$ref": "#/definitions/ForwardResultAttachmentSkipped" }
|
|
1397
|
+
],
|
|
1398
|
+
"description": "Result for a single forwarded email detected in the message.\n\nUse the `type` and `analyzed` fields to narrow the type:\n- `type: 'inline'` - Inline forward, always analyzed\n- `type: 'attachment'` + `analyzed: true` - Analyzed attachment\n- `type: 'attachment'` + `analyzed: false` - Skipped attachment"
|
|
1399
|
+
},
|
|
1400
|
+
"ForwardResultInline": {
|
|
1401
|
+
"type": "object",
|
|
1402
|
+
"properties": {
|
|
1403
|
+
"type": {
|
|
1404
|
+
"type": "string",
|
|
1405
|
+
"const": "inline"
|
|
1406
|
+
},
|
|
1407
|
+
"original_sender": {
|
|
1408
|
+
"anyOf": [{ "$ref": "#/definitions/ForwardOriginalSender" }, { "type": "null" }],
|
|
1409
|
+
"description": "Original sender of the forwarded email, if extractable."
|
|
1410
|
+
},
|
|
1411
|
+
"verification": {
|
|
1412
|
+
"$ref": "#/definitions/ForwardVerification",
|
|
1413
|
+
"description": "Verification result for the forwarded email."
|
|
1414
|
+
},
|
|
1415
|
+
"summary": {
|
|
1416
|
+
"type": "string",
|
|
1417
|
+
"description": "Human-readable summary of the forward analysis."
|
|
1418
|
+
}
|
|
1419
|
+
},
|
|
1420
|
+
"required": [
|
|
1421
|
+
"type",
|
|
1422
|
+
"original_sender",
|
|
1423
|
+
"verification",
|
|
1424
|
+
"summary"
|
|
1425
|
+
],
|
|
1426
|
+
"description": "Result for an inline forward that was detected and analyzed. Inline forwards are always analyzed when forward detection is enabled."
|
|
1427
|
+
},
|
|
1428
|
+
"ForwardOriginalSender": {
|
|
1429
|
+
"type": "object",
|
|
1430
|
+
"properties": {
|
|
1431
|
+
"email": {
|
|
1432
|
+
"type": "string",
|
|
1433
|
+
"description": "Email address of the original sender."
|
|
1434
|
+
},
|
|
1435
|
+
"domain": {
|
|
1436
|
+
"type": "string",
|
|
1437
|
+
"description": "Domain of the original sender."
|
|
1438
|
+
}
|
|
1439
|
+
},
|
|
1440
|
+
"required": ["email", "domain"],
|
|
1441
|
+
"description": "Original sender information extracted from the forwarded email."
|
|
1442
|
+
},
|
|
1443
|
+
"ForwardVerification": {
|
|
1444
|
+
"type": "object",
|
|
1445
|
+
"properties": {
|
|
1446
|
+
"verdict": {
|
|
1447
|
+
"$ref": "#/definitions/ForwardVerdict",
|
|
1448
|
+
"description": "Overall verdict on whether the forward is authentic."
|
|
1449
|
+
},
|
|
1450
|
+
"confidence": {
|
|
1451
|
+
"$ref": "#/definitions/AuthConfidence",
|
|
1452
|
+
"description": "Confidence level for this verdict."
|
|
1453
|
+
},
|
|
1454
|
+
"dkim_verified": {
|
|
1455
|
+
"type": "boolean",
|
|
1456
|
+
"description": "Whether a valid DKIM signature was found that verifies the original sender."
|
|
1457
|
+
},
|
|
1458
|
+
"dkim_domain": {
|
|
1459
|
+
"type": ["string", "null"],
|
|
1460
|
+
"description": "Domain of the DKIM signature that verified the forward, if any."
|
|
1461
|
+
},
|
|
1462
|
+
"dmarc_policy": {
|
|
1463
|
+
"$ref": "#/definitions/DmarcPolicy",
|
|
1464
|
+
"description": "DMARC policy of the original sender's domain."
|
|
1465
|
+
}
|
|
1466
|
+
},
|
|
1467
|
+
"required": [
|
|
1468
|
+
"verdict",
|
|
1469
|
+
"confidence",
|
|
1470
|
+
"dkim_verified",
|
|
1471
|
+
"dkim_domain",
|
|
1472
|
+
"dmarc_policy"
|
|
1473
|
+
],
|
|
1474
|
+
"description": "Verification result for a forwarded email."
|
|
1475
|
+
},
|
|
1476
|
+
"ForwardVerdict": {
|
|
1477
|
+
"type": "string",
|
|
1478
|
+
"enum": ["legit", "unknown"],
|
|
1479
|
+
"description": "Verdict for forwarded email verification.\n\n- `legit`: DKIM signature verified the original sender\n- `unknown`: Could not verify the forwarded email's authenticity"
|
|
1480
|
+
},
|
|
1481
|
+
"AuthConfidence": {
|
|
1482
|
+
"type": "string",
|
|
1483
|
+
"enum": [
|
|
1484
|
+
"high",
|
|
1485
|
+
"medium",
|
|
1486
|
+
"low"
|
|
1487
|
+
],
|
|
1488
|
+
"description": "Confidence level for the authentication verdict.\n\n- `high`: Strong cryptographic evidence (DKIM aligned + DMARC pass)\n- `medium`: Good evidence but with caveats (SPF-only alignment)\n- `low`: Weak evidence (missing authentication or unclear results)"
|
|
1489
|
+
},
|
|
1490
|
+
"DmarcPolicy": {
|
|
1491
|
+
"type": ["string", "null"],
|
|
1492
|
+
"enum": [
|
|
1493
|
+
"reject",
|
|
1494
|
+
"quarantine",
|
|
1495
|
+
"none",
|
|
1496
|
+
null
|
|
1497
|
+
],
|
|
1498
|
+
"description": "DMARC policy action specified in the domain's DMARC record.\n\n- `reject`: The domain owner requests that receivers reject failing emails\n- `quarantine`: The domain owner requests that failing emails be treated as suspicious\n- `none`: The domain owner is only monitoring (no action requested)\n- `null`: No DMARC policy was found for the domain"
|
|
1499
|
+
},
|
|
1500
|
+
"ForwardResultAttachmentAnalyzed": {
|
|
1501
|
+
"type": "object",
|
|
1502
|
+
"properties": {
|
|
1503
|
+
"type": {
|
|
1504
|
+
"type": "string",
|
|
1505
|
+
"const": "attachment"
|
|
1506
|
+
},
|
|
1507
|
+
"attachment_tar_path": {
|
|
1508
|
+
"type": "string",
|
|
1509
|
+
"description": "Path to the attachment in the attachments tar archive."
|
|
1510
|
+
},
|
|
1511
|
+
"attachment_filename": {
|
|
1512
|
+
"type": ["string", "null"],
|
|
1513
|
+
"description": "Original filename of the attachment, if available."
|
|
1514
|
+
},
|
|
1515
|
+
"analyzed": {
|
|
1516
|
+
"type": "boolean",
|
|
1517
|
+
"const": true,
|
|
1518
|
+
"description": "Whether this attachment was analyzed."
|
|
1519
|
+
},
|
|
1520
|
+
"original_sender": {
|
|
1521
|
+
"anyOf": [{ "$ref": "#/definitions/ForwardOriginalSender" }, { "type": "null" }],
|
|
1522
|
+
"description": "Original sender of the forwarded email, if extractable."
|
|
1523
|
+
},
|
|
1524
|
+
"verification": {
|
|
1525
|
+
"$ref": "#/definitions/ForwardVerification",
|
|
1526
|
+
"description": "Verification result for the forwarded email."
|
|
1527
|
+
},
|
|
1528
|
+
"summary": {
|
|
1529
|
+
"type": "string",
|
|
1530
|
+
"description": "Human-readable summary of the forward analysis."
|
|
1531
|
+
}
|
|
1532
|
+
},
|
|
1533
|
+
"required": [
|
|
1534
|
+
"type",
|
|
1535
|
+
"attachment_tar_path",
|
|
1536
|
+
"attachment_filename",
|
|
1537
|
+
"analyzed",
|
|
1538
|
+
"original_sender",
|
|
1539
|
+
"verification",
|
|
1540
|
+
"summary"
|
|
1541
|
+
],
|
|
1542
|
+
"description": "Result for an attachment forward that was analyzed."
|
|
1543
|
+
},
|
|
1544
|
+
"ForwardResultAttachmentSkipped": {
|
|
1545
|
+
"type": "object",
|
|
1546
|
+
"properties": {
|
|
1547
|
+
"type": {
|
|
1548
|
+
"type": "string",
|
|
1549
|
+
"const": "attachment"
|
|
1550
|
+
},
|
|
1551
|
+
"attachment_tar_path": {
|
|
1552
|
+
"type": "string",
|
|
1553
|
+
"description": "Path to the attachment in the attachments tar archive."
|
|
1554
|
+
},
|
|
1555
|
+
"attachment_filename": {
|
|
1556
|
+
"type": ["string", "null"],
|
|
1557
|
+
"description": "Original filename of the attachment, if available."
|
|
1558
|
+
},
|
|
1559
|
+
"analyzed": {
|
|
1560
|
+
"type": "boolean",
|
|
1561
|
+
"const": false,
|
|
1562
|
+
"description": "Whether this attachment was analyzed."
|
|
1563
|
+
},
|
|
1564
|
+
"original_sender": {
|
|
1565
|
+
"type": "null",
|
|
1566
|
+
"description": "Always null when not analyzed."
|
|
1567
|
+
},
|
|
1568
|
+
"verification": {
|
|
1569
|
+
"type": "null",
|
|
1570
|
+
"description": "Always null when not analyzed."
|
|
1571
|
+
},
|
|
1572
|
+
"summary": {
|
|
1573
|
+
"type": "string",
|
|
1574
|
+
"description": "Human-readable summary explaining why analysis was skipped."
|
|
1575
|
+
}
|
|
1576
|
+
},
|
|
1577
|
+
"required": [
|
|
1578
|
+
"type",
|
|
1579
|
+
"attachment_tar_path",
|
|
1580
|
+
"attachment_filename",
|
|
1581
|
+
"analyzed",
|
|
1582
|
+
"original_sender",
|
|
1583
|
+
"verification",
|
|
1584
|
+
"summary"
|
|
1585
|
+
],
|
|
1586
|
+
"description": "Result for an attachment forward that was detected but not analyzed. This occurs when attachment analysis is disabled or the limit was reached."
|
|
1587
|
+
},
|
|
1588
|
+
"EmailAuth": {
|
|
1589
|
+
"type": "object",
|
|
1590
|
+
"properties": {
|
|
1591
|
+
"spf": {
|
|
1592
|
+
"$ref": "#/definitions/SpfResult",
|
|
1593
|
+
"description": "SPF verification result.\n\nSPF checks if the sending IP is authorized by the envelope sender's domain. \"pass\" means the IP is authorized; \"fail\" means it's explicitly not allowed."
|
|
1594
|
+
},
|
|
1595
|
+
"dmarc": {
|
|
1596
|
+
"$ref": "#/definitions/DmarcResult",
|
|
1597
|
+
"description": "DMARC verification result.\n\nDMARC passes if either SPF or DKIM passes AND aligns with the From: domain. \"pass\" means the email is authenticated according to the sender's policy."
|
|
1598
|
+
},
|
|
1599
|
+
"dmarcPolicy": {
|
|
1600
|
+
"$ref": "#/definitions/DmarcPolicy",
|
|
1601
|
+
"description": "DMARC policy from the sender's DNS record.\n\n- `reject`: Domain wants receivers to reject failing emails\n- `quarantine`: Domain wants failing emails marked as suspicious\n- `none`: Domain is monitoring only (no action requested)\n- `null`: No DMARC record found for this domain"
|
|
1602
|
+
},
|
|
1603
|
+
"dmarcFromDomain": {
|
|
1604
|
+
"type": ["string", "null"],
|
|
1605
|
+
"description": "The organizational domain used for DMARC lookups.\n\nFor example, if the From: address is `user@mail.example.com`, the DMARC lookup checks `_dmarc.mail.example.com`, then falls back to `_dmarc.example.com`. This field shows which domain's policy was used."
|
|
1606
|
+
},
|
|
1607
|
+
"dmarcSpfAligned": {
|
|
1608
|
+
"type": "boolean",
|
|
1609
|
+
"description": "Whether SPF aligned with the From: domain for DMARC purposes.\n\nTrue if the envelope sender domain matches the From: domain (per alignment mode)."
|
|
1610
|
+
},
|
|
1611
|
+
"dmarcDkimAligned": {
|
|
1612
|
+
"type": "boolean",
|
|
1613
|
+
"description": "Whether DKIM aligned with the From: domain for DMARC purposes.\n\nTrue if at least one DKIM signature's domain matches the From: domain."
|
|
1614
|
+
},
|
|
1615
|
+
"dmarcSpfStrict": {
|
|
1616
|
+
"type": ["boolean", "null"],
|
|
1617
|
+
"description": "Whether DMARC SPF alignment mode is strict.\n\n- `true`: Strict alignment required (exact domain match)\n- `false`: Relaxed alignment allowed (organizational domain match)\n- `null`: No DMARC record found"
|
|
1618
|
+
},
|
|
1619
|
+
"dmarcDkimStrict": {
|
|
1620
|
+
"type": ["boolean", "null"],
|
|
1621
|
+
"description": "Whether DMARC DKIM alignment mode is strict.\n\n- `true`: Strict alignment required (exact domain match)\n- `false`: Relaxed alignment allowed (organizational domain match)\n- `null`: No DMARC record found"
|
|
1622
|
+
},
|
|
1623
|
+
"dkimSignatures": {
|
|
1624
|
+
"type": "array",
|
|
1625
|
+
"items": { "$ref": "#/definitions/DkimSignature" },
|
|
1626
|
+
"description": "All DKIM signatures found in the email with their verification results.\n\nMay be empty if no DKIM signatures were present."
|
|
1627
|
+
}
|
|
1628
|
+
},
|
|
1629
|
+
"required": [
|
|
1630
|
+
"spf",
|
|
1631
|
+
"dmarc",
|
|
1632
|
+
"dmarcPolicy",
|
|
1633
|
+
"dmarcFromDomain",
|
|
1634
|
+
"dmarcSpfAligned",
|
|
1635
|
+
"dmarcDkimAligned",
|
|
1636
|
+
"dmarcSpfStrict",
|
|
1637
|
+
"dmarcDkimStrict",
|
|
1638
|
+
"dkimSignatures"
|
|
1639
|
+
],
|
|
1640
|
+
"description": "Email authentication results for SPF, DKIM, and DMARC.\n\nUse `validateEmailAuth()` to compute a verdict based on these results."
|
|
1641
|
+
},
|
|
1642
|
+
"SpfResult": {
|
|
1643
|
+
"type": "string",
|
|
1644
|
+
"enum": [
|
|
1645
|
+
"pass",
|
|
1646
|
+
"fail",
|
|
1647
|
+
"softfail",
|
|
1648
|
+
"neutral",
|
|
1649
|
+
"none",
|
|
1650
|
+
"temperror",
|
|
1651
|
+
"permerror"
|
|
1652
|
+
],
|
|
1653
|
+
"description": "SPF verification result."
|
|
1654
|
+
},
|
|
1655
|
+
"DmarcResult": {
|
|
1656
|
+
"type": "string",
|
|
1657
|
+
"enum": [
|
|
1658
|
+
"pass",
|
|
1659
|
+
"fail",
|
|
1660
|
+
"none",
|
|
1661
|
+
"temperror",
|
|
1662
|
+
"permerror"
|
|
1663
|
+
],
|
|
1664
|
+
"description": "DMARC verification result."
|
|
1665
|
+
},
|
|
1666
|
+
"DkimSignature": {
|
|
1667
|
+
"type": "object",
|
|
1668
|
+
"properties": {
|
|
1669
|
+
"domain": {
|
|
1670
|
+
"type": "string",
|
|
1671
|
+
"description": "The domain that signed this DKIM signature (d= tag). This may differ from the From: domain (that's what alignment checks)."
|
|
1672
|
+
},
|
|
1673
|
+
"selector": {
|
|
1674
|
+
"type": ["string", "null"],
|
|
1675
|
+
"description": "The DKIM selector used to locate the public key (s= tag). Combined with the domain to form the DNS lookup: `selector._domainkey.domain`\n\nOptional in self-hosted environments where the milter may not provide selector info."
|
|
1676
|
+
},
|
|
1677
|
+
"result": {
|
|
1678
|
+
"$ref": "#/definitions/DkimResult",
|
|
1679
|
+
"description": "Verification result for this specific signature."
|
|
1680
|
+
},
|
|
1681
|
+
"aligned": {
|
|
1682
|
+
"type": "boolean",
|
|
1683
|
+
"description": "Whether this signature's domain aligns with the From: domain (for DMARC).\n\nAlignment can be \"strict\" (exact match) or \"relaxed\" (organizational domain match). For example, if From: is `user@sub.example.com` and DKIM is signed by `example.com`:\n- Relaxed alignment: true (same organizational domain)\n- Strict alignment: false (not exact match)"
|
|
1684
|
+
},
|
|
1685
|
+
"keyBits": {
|
|
1686
|
+
"type": ["integer", "null"],
|
|
1687
|
+
"minimum": 1,
|
|
1688
|
+
"maximum": 16384,
|
|
1689
|
+
"description": "Key size in bits (e.g., 1024, 2048). Null if the key size couldn't be determined.\n\nOptional in self-hosted environments."
|
|
1690
|
+
},
|
|
1691
|
+
"algo": {
|
|
1692
|
+
"type": ["string", "null"],
|
|
1693
|
+
"description": "Signing algorithm (e.g., \"rsa-sha256\", \"ed25519-sha256\").\n\nOptional in self-hosted environments."
|
|
1694
|
+
}
|
|
1695
|
+
},
|
|
1696
|
+
"required": [
|
|
1697
|
+
"domain",
|
|
1698
|
+
"selector",
|
|
1699
|
+
"result",
|
|
1700
|
+
"aligned",
|
|
1701
|
+
"keyBits",
|
|
1702
|
+
"algo"
|
|
1703
|
+
],
|
|
1704
|
+
"description": "Details about a single DKIM signature found in the email.\n\nAn email may have multiple DKIM signatures (e.g., one from the sending domain and one from the ESP). Each signature is verified independently."
|
|
1705
|
+
},
|
|
1706
|
+
"DkimResult": {
|
|
1707
|
+
"type": "string",
|
|
1708
|
+
"enum": [
|
|
1709
|
+
"pass",
|
|
1710
|
+
"fail",
|
|
1711
|
+
"temperror",
|
|
1712
|
+
"permerror"
|
|
1713
|
+
],
|
|
1714
|
+
"description": "DKIM signature verification result for a single signature."
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
};
|
|
1718
|
+
//#endregion
|
|
1719
|
+
//#region src/webhook/version.ts
|
|
1720
|
+
/**
|
|
1721
|
+
* Webhook API Version
|
|
1722
|
+
*
|
|
1723
|
+
* Single source of truth for the webhook version.
|
|
1724
|
+
* Update this file when bumping the API version.
|
|
1725
|
+
*/
|
|
1726
|
+
/**
|
|
1727
|
+
* The current webhook API version this SDK is built for.
|
|
1728
|
+
* Webhooks may be sent with different versions - the SDK accepts any valid
|
|
1729
|
+
* YYYY-MM-DD formatted version string. Compare against this constant if you
|
|
1730
|
+
* need to handle version-specific behavior.
|
|
1731
|
+
*/
|
|
1732
|
+
const WEBHOOK_VERSION = "2025-12-14";
|
|
1733
|
+
//#endregion
|
|
1734
|
+
//#region src/webhook/parsing.ts
|
|
1735
|
+
/**
|
|
1736
|
+
* JSON parsing utilities with helpful error messages.
|
|
1737
|
+
* @internal
|
|
1738
|
+
*/
|
|
1739
|
+
/**
|
|
1740
|
+
* Parse a raw body string/Buffer into JSON with helpful error messages.
|
|
1741
|
+
*
|
|
1742
|
+
* Handles:
|
|
1743
|
+
* - Empty/whitespace bodies
|
|
1744
|
+
* - BOM (byte order mark) prefix stripping
|
|
1745
|
+
* - Detailed JSON syntax error messages with position
|
|
1746
|
+
*
|
|
1747
|
+
* @param rawBody - The raw request body (string or Buffer)
|
|
1748
|
+
* @returns The parsed JSON value
|
|
1749
|
+
* @throws WebhookPayloadError with helpful message on failure
|
|
1750
|
+
* @internal
|
|
1751
|
+
*/
|
|
1752
|
+
function parseJsonBody(rawBody) {
|
|
1753
|
+
const bodyStr = typeof rawBody === "string" ? rawBody : bufferToString(rawBody, "request body");
|
|
1754
|
+
if (!bodyStr || bodyStr.trim() === "") throw new WebhookPayloadError("PAYLOAD_EMPTY_BODY", "Received empty request body", "The request body is empty. Check your web framework is correctly passing the request body.");
|
|
1755
|
+
try {
|
|
1756
|
+
const cleanBody = bodyStr.charCodeAt(0) === 65279 ? bodyStr.slice(1) : bodyStr;
|
|
1757
|
+
return JSON.parse(cleanBody);
|
|
1758
|
+
} catch (e) {
|
|
1759
|
+
const jsonError = e;
|
|
1760
|
+
const position = jsonError.message.match(/position\s*(\d+)/i)?.[1];
|
|
1761
|
+
throw new WebhookPayloadError("JSON_PARSE_FAILED", "Failed to parse webhook body as JSON", position ? `Invalid JSON at position ${position}. Check your web framework isn't truncating the request body.` : `Invalid JSON: ${jsonError.message}. Check the raw request body is valid JSON.`, jsonError);
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
//#endregion
|
|
1765
|
+
//#region src/webhook/index.ts
|
|
1766
|
+
const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
1767
|
+
/**
|
|
1768
|
+
* The header that names the webhook event for ALL event families
|
|
1769
|
+
* (`email.*`, `payment.*`, `interaction.*`). It is the primary discriminator
|
|
1770
|
+
* the parser keys on, because the stored body is sent verbatim with no envelope.
|
|
1771
|
+
*/
|
|
1772
|
+
const WEBHOOK_EVENT_HEADER = "X-Webhook-Event";
|
|
1773
|
+
const SIGNATURE_HEADER_NAMES = ["primitive-signature", "mymx-signature"];
|
|
1774
|
+
/**
|
|
1775
|
+
* Read the `X-Webhook-Event` header value (case-insensitive). Returns null when
|
|
1776
|
+
* the header is absent.
|
|
1777
|
+
*/
|
|
1778
|
+
function getEventHeader(headers) {
|
|
1779
|
+
if (headers instanceof Headers) return headers.get("x-webhook-event");
|
|
1780
|
+
const obj = headers;
|
|
1781
|
+
const key = Object.keys(obj).find((k) => k.toLowerCase() === "x-webhook-event");
|
|
1782
|
+
if (!key) return null;
|
|
1783
|
+
const value = obj[key];
|
|
1784
|
+
if (Array.isArray(value)) return value[0] ?? null;
|
|
1785
|
+
return value ?? null;
|
|
1786
|
+
}
|
|
1787
|
+
const STANDARD_WEBHOOKS_HEADER_NAMES = [
|
|
1788
|
+
"webhook-signature",
|
|
1789
|
+
"webhook-id",
|
|
1790
|
+
"webhook-timestamp"
|
|
1791
|
+
];
|
|
1792
|
+
/**
|
|
1793
|
+
* Extract signature header from various header formats.
|
|
1794
|
+
* Checks for Primitive-Signature first, then falls back to the legacy
|
|
1795
|
+
* MyMX-Signature for backward compatibility with older servers.
|
|
1796
|
+
*/
|
|
1797
|
+
function getSignatureHeader(headers) {
|
|
1798
|
+
if (headers instanceof Headers) {
|
|
1799
|
+
for (const name of SIGNATURE_HEADER_NAMES) {
|
|
1800
|
+
const value = headers.get(name);
|
|
1801
|
+
if (value) return value;
|
|
1802
|
+
}
|
|
1803
|
+
return "";
|
|
1804
|
+
}
|
|
1805
|
+
const obj = headers;
|
|
1806
|
+
const keys = Object.keys(obj);
|
|
1807
|
+
for (const name of SIGNATURE_HEADER_NAMES) {
|
|
1808
|
+
const key = keys.find((k) => k.toLowerCase() === name);
|
|
1809
|
+
if (!key) continue;
|
|
1810
|
+
const value = obj[key];
|
|
1811
|
+
if (Array.isArray(value)) return value[0] ?? "";
|
|
1812
|
+
if (value) return value;
|
|
1813
|
+
}
|
|
1814
|
+
return "";
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* Extract Standard Webhooks headers from various header formats.
|
|
1818
|
+
*
|
|
1819
|
+
* Returns all three required headers if `webhook-signature` is present.
|
|
1820
|
+
* If `webhook-signature` is found but `webhook-id` or `webhook-timestamp`
|
|
1821
|
+
* is missing, throws an error (partial Standard Webhooks headers indicate
|
|
1822
|
+
* a misconfiguration, not a Primitive-format webhook).
|
|
1823
|
+
*
|
|
1824
|
+
* Returns null if `webhook-signature` is not present (fall through to Primitive).
|
|
1825
|
+
*/
|
|
1826
|
+
function getStandardWebhooksHeaders(headers) {
|
|
1827
|
+
let signature = "";
|
|
1828
|
+
let msgId = "";
|
|
1829
|
+
let timestamp = "";
|
|
1830
|
+
let hasSignatureKey = false;
|
|
1831
|
+
if (headers instanceof Headers) {
|
|
1832
|
+
hasSignatureKey = headers.has("webhook-signature");
|
|
1833
|
+
if (!hasSignatureKey) return null;
|
|
1834
|
+
signature = headers.get("webhook-signature") ?? "";
|
|
1835
|
+
msgId = headers.get("webhook-id") ?? "";
|
|
1836
|
+
timestamp = headers.get("webhook-timestamp") ?? "";
|
|
1837
|
+
} else {
|
|
1838
|
+
const obj = headers;
|
|
1839
|
+
const keys = Object.keys(obj);
|
|
1840
|
+
for (const name of STANDARD_WEBHOOKS_HEADER_NAMES) {
|
|
1841
|
+
const key = keys.find((k) => k.toLowerCase() === name);
|
|
1842
|
+
const raw = key ? obj[key] : void 0;
|
|
1843
|
+
const value = Array.isArray(raw) ? raw[0] ?? "" : raw ?? "";
|
|
1844
|
+
if (name === "webhook-signature") {
|
|
1845
|
+
hasSignatureKey = key !== void 0;
|
|
1846
|
+
signature = value;
|
|
1847
|
+
} else if (name === "webhook-id") msgId = value;
|
|
1848
|
+
else if (name === "webhook-timestamp") timestamp = value;
|
|
1849
|
+
}
|
|
1850
|
+
if (!hasSignatureKey) return null;
|
|
1851
|
+
}
|
|
1852
|
+
if (!signature) throw new WebhookVerificationError("INVALID_SIGNATURE_HEADER", "Empty webhook-signature header. Expected: \"v1,<base64>\"");
|
|
1853
|
+
if (!msgId || !timestamp) throw new WebhookVerificationError("INVALID_SIGNATURE_HEADER", `Found webhook-signature header but missing ${!msgId ? "webhook-id" : "webhook-timestamp"} header. Standard Webhooks requires all three headers: webhook-id, webhook-timestamp, webhook-signature.`);
|
|
1854
|
+
return {
|
|
1855
|
+
msgId,
|
|
1856
|
+
timestamp,
|
|
1857
|
+
signature
|
|
1858
|
+
};
|
|
1859
|
+
}
|
|
1860
|
+
/**
|
|
1861
|
+
* Verify, parse, and validate a webhook in one call.
|
|
1862
|
+
*
|
|
1863
|
+
* This is the recommended way to handle Primitive webhooks. It:
|
|
1864
|
+
* 1. Verifies the signature to ensure the webhook is authentic
|
|
1865
|
+
* 2. Parses the JSON body
|
|
1866
|
+
* 3. Validates the payload against the canonical JSON schema
|
|
1867
|
+
* 4. Returns a fully typed EmailReceivedEvent
|
|
1868
|
+
*
|
|
1869
|
+
* @param options - The webhook data and secret
|
|
1870
|
+
* @returns A validated EmailReceivedEvent
|
|
1871
|
+
* @throws {WebhookVerificationError} If signature verification fails
|
|
1872
|
+
* @throws {WebhookPayloadError} If JSON parsing fails
|
|
1873
|
+
* @throws {WebhookValidationError} If schema validation fails
|
|
1874
|
+
*
|
|
1875
|
+
* @example
|
|
1876
|
+
* ```typescript
|
|
1877
|
+
* import { handleWebhook, PrimitiveWebhookError } from '@primitivedotdev/sdk';
|
|
1878
|
+
*
|
|
1879
|
+
* app.post('/webhooks/email', express.raw({ type: 'application/json' }), (req, res) => {
|
|
1880
|
+
* try {
|
|
1881
|
+
* const event = handleWebhook({
|
|
1882
|
+
* body: req.body,
|
|
1883
|
+
* headers: req.headers,
|
|
1884
|
+
* secret: process.env.PRIMITIVE_WEBHOOK_SECRET,
|
|
1885
|
+
* });
|
|
1886
|
+
*
|
|
1887
|
+
* console.log('Email from:', event.email.headers.from);
|
|
1888
|
+
* res.json({ received: true });
|
|
1889
|
+
* } catch (err) {
|
|
1890
|
+
* if (err instanceof PrimitiveWebhookError) {
|
|
1891
|
+
* console.error(`[${err.code}] ${err.message}`);
|
|
1892
|
+
* return res.status(400).json({ error: err.code });
|
|
1893
|
+
* }
|
|
1894
|
+
* throw err;
|
|
1895
|
+
* }
|
|
1896
|
+
* });
|
|
1897
|
+
* ```
|
|
1898
|
+
*/
|
|
1899
|
+
function verifyWebhookRequest(options) {
|
|
1900
|
+
const { body, headers, secret, toleranceSeconds } = options;
|
|
1901
|
+
const swHeaders = getStandardWebhooksHeaders(headers);
|
|
1902
|
+
if (swHeaders) verifyStandardWebhooksSignature({
|
|
1903
|
+
rawBody: body,
|
|
1904
|
+
msgId: swHeaders.msgId,
|
|
1905
|
+
timestamp: swHeaders.timestamp,
|
|
1906
|
+
signatureHeader: swHeaders.signature,
|
|
1907
|
+
secret,
|
|
1908
|
+
toleranceSeconds
|
|
1909
|
+
});
|
|
1910
|
+
else verifyWebhookSignature({
|
|
1911
|
+
rawBody: body,
|
|
1912
|
+
signatureHeader: getSignatureHeader(headers),
|
|
1913
|
+
secret,
|
|
1914
|
+
toleranceSeconds
|
|
1915
|
+
});
|
|
1916
|
+
}
|
|
1917
|
+
/**
|
|
1918
|
+
* Verify, then parse any webhook event into a typed value.
|
|
1919
|
+
*
|
|
1920
|
+
* Unlike {@link handleWebhook}, this returns the full {@link WebhookEvent}
|
|
1921
|
+
* union, so it handles `payment.*` and `interaction.x402.*` events in addition
|
|
1922
|
+
* to `email.*`. The flow is:
|
|
1923
|
+
*
|
|
1924
|
+
* 1. Verify the signature over the RAW body (works for every event family).
|
|
1925
|
+
* 2. Parse the JSON body.
|
|
1926
|
+
* 3. Classify on the `X-Webhook-Event` HEADER (the primary discriminator),
|
|
1927
|
+
* returning a typed event for known types and an UnknownEvent for the rest.
|
|
1928
|
+
*
|
|
1929
|
+
* @example
|
|
1930
|
+
* ```typescript
|
|
1931
|
+
* const event = handleWebhookEvent({ body, headers, secret });
|
|
1932
|
+
* if (isPaymentSettledEvent(event)) {
|
|
1933
|
+
* // typed PaymentSettledEvent
|
|
1934
|
+
* } else if (isInteractionX402Event(event)) {
|
|
1935
|
+
* // typed interaction.x402.* event
|
|
1936
|
+
* }
|
|
1937
|
+
* ```
|
|
1938
|
+
*/
|
|
1939
|
+
function handleWebhookEvent(options) {
|
|
1940
|
+
verifyWebhookRequest(options);
|
|
1941
|
+
return parseWebhookEvent(parseJsonBody(options.body), getEventHeader(options.headers));
|
|
1942
|
+
}
|
|
1943
|
+
function handleWebhook(options) {
|
|
1944
|
+
verifyWebhookRequest(options);
|
|
1945
|
+
return validateEmailReceivedEvent(parseJsonBody(options.body));
|
|
1946
|
+
}
|
|
1947
|
+
function receive(input, options) {
|
|
1948
|
+
if (input instanceof Request) return receiveFromRequest(input, options);
|
|
1949
|
+
return normalizeReceivedEmail(handleWebhook(input));
|
|
1950
|
+
}
|
|
1951
|
+
async function receiveFromRequest(request, options) {
|
|
1952
|
+
if (!options?.secret) throw new WebhookVerificationError("MISSING_SECRET", "Webhook secret is required but was empty or not provided");
|
|
1953
|
+
return normalizeReceivedEmail(handleWebhook({
|
|
1954
|
+
body: Buffer.from(await request.arrayBuffer()),
|
|
1955
|
+
headers: request.headers,
|
|
1956
|
+
secret: options.secret,
|
|
1957
|
+
toleranceSeconds: options.toleranceSeconds
|
|
1958
|
+
}));
|
|
1959
|
+
}
|
|
1960
|
+
/**
|
|
1961
|
+
* Returns headers for the optional "content discard" feature.
|
|
1962
|
+
*
|
|
1963
|
+
* If you have the "content discard" setting enabled in your Primitive dashboard,
|
|
1964
|
+
* returning this header tells Primitive to permanently delete the email content
|
|
1965
|
+
* after successful delivery. Requires BOTH the dashboard setting AND this header.
|
|
1966
|
+
*
|
|
1967
|
+
* **Warning:** Only use this if you can durably guarantee you've processed the email.
|
|
1968
|
+
* Once discarded, the email content is gone forever.
|
|
1969
|
+
*
|
|
1970
|
+
* @returns Headers object to spread into your response
|
|
1971
|
+
*
|
|
1972
|
+
* @example Express (only if using content discard)
|
|
1973
|
+
* ```typescript
|
|
1974
|
+
* app.post('/webhook', async (req, res) => {
|
|
1975
|
+
* const event = handleWebhook({ ... });
|
|
1976
|
+
* // Durably save the email first!
|
|
1977
|
+
* await db.saveEmail(event);
|
|
1978
|
+
* res.set(confirmedHeaders()).json({ received: true });
|
|
1979
|
+
* });
|
|
1980
|
+
* ```
|
|
1981
|
+
*
|
|
1982
|
+
* @example Fetch API / Next.js (only if using content discard)
|
|
1983
|
+
* ```typescript
|
|
1984
|
+
* return new Response(JSON.stringify({ received: true }), {
|
|
1985
|
+
* status: 200,
|
|
1986
|
+
* headers: {
|
|
1987
|
+
* 'Content-Type': 'application/json',
|
|
1988
|
+
* ...confirmedHeaders(),
|
|
1989
|
+
* },
|
|
1990
|
+
* });
|
|
1991
|
+
* ```
|
|
1992
|
+
*/
|
|
1993
|
+
function confirmedHeaders() {
|
|
1994
|
+
return {
|
|
1995
|
+
[PRIMITIVE_CONFIRMED_HEADER]: "true",
|
|
1996
|
+
[LEGACY_CONFIRMED_HEADER]: "true"
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
/**
|
|
2000
|
+
* Check if the download URL for a webhook event has expired.
|
|
2001
|
+
*
|
|
2002
|
+
* @param event - The webhook event
|
|
2003
|
+
* @param now - Optional current time for testing (defaults to Date.now())
|
|
2004
|
+
* @returns true if the download URL has expired
|
|
2005
|
+
*
|
|
2006
|
+
* @example
|
|
2007
|
+
* ```typescript
|
|
2008
|
+
* if (isDownloadExpired(event)) {
|
|
2009
|
+
* console.log("Download URL has expired, cannot fetch raw email");
|
|
2010
|
+
* } else {
|
|
2011
|
+
* const response = await fetch(event.email.content.download.url);
|
|
2012
|
+
* }
|
|
2013
|
+
* ```
|
|
2014
|
+
*/
|
|
2015
|
+
function isDownloadExpired(event, now = Date.now()) {
|
|
2016
|
+
return now >= new Date(event.email.content.download.expires_at).getTime();
|
|
2017
|
+
}
|
|
2018
|
+
/**
|
|
2019
|
+
* Get the time remaining (in milliseconds) before the download URL expires.
|
|
2020
|
+
* Returns 0 if already expired.
|
|
2021
|
+
*
|
|
2022
|
+
* @param event - The webhook event
|
|
2023
|
+
* @param now - Optional current time for testing (defaults to Date.now())
|
|
2024
|
+
* @returns Milliseconds until expiration, or 0 if expired
|
|
2025
|
+
*
|
|
2026
|
+
* @example
|
|
2027
|
+
* ```typescript
|
|
2028
|
+
* const remaining = getDownloadTimeRemaining(event);
|
|
2029
|
+
* if (remaining > 60000) {
|
|
2030
|
+
* // More than 1 minute left, safe to download
|
|
2031
|
+
* }
|
|
2032
|
+
* ```
|
|
2033
|
+
*/
|
|
2034
|
+
function getDownloadTimeRemaining(event, now = Date.now()) {
|
|
2035
|
+
const expiresAt = new Date(event.email.content.download.expires_at).getTime();
|
|
2036
|
+
return Math.max(0, expiresAt - now);
|
|
2037
|
+
}
|
|
2038
|
+
/**
|
|
2039
|
+
* Check if the raw email content is included inline in the event.
|
|
2040
|
+
*
|
|
2041
|
+
* Use this to check before calling `decodeRawEmail()` to avoid try/catch.
|
|
2042
|
+
*
|
|
2043
|
+
* @param event - The webhook event
|
|
2044
|
+
* @returns true if raw content is included inline, false if download required
|
|
2045
|
+
*
|
|
2046
|
+
* @example
|
|
2047
|
+
* ```typescript
|
|
2048
|
+
* if (isRawIncluded(event)) {
|
|
2049
|
+
* const rawEmail = decodeRawEmail(event);
|
|
2050
|
+
* } else {
|
|
2051
|
+
* const response = await fetch(event.email.content.download.url);
|
|
2052
|
+
* }
|
|
2053
|
+
* ```
|
|
2054
|
+
*/
|
|
2055
|
+
function isRawIncluded(event) {
|
|
2056
|
+
return event.email.content.raw.included;
|
|
2057
|
+
}
|
|
2058
|
+
/**
|
|
2059
|
+
* Decode the raw email content from an EmailReceivedEvent.
|
|
2060
|
+
*
|
|
2061
|
+
* Throws if the raw content is not included inline (i.e., must be downloaded).
|
|
2062
|
+
* By default, verifies the SHA-256 hash matches after decoding.
|
|
2063
|
+
*
|
|
2064
|
+
* NOTE: This function assumes a well-formed event from `handleWebhook()`.
|
|
2065
|
+
* Passing a manually constructed event with missing fields (e.g., `raw.data`
|
|
2066
|
+
* undefined when `raw.included` is true) will result in undefined behavior.
|
|
2067
|
+
*
|
|
2068
|
+
* @param event - The webhook event containing the raw email
|
|
2069
|
+
* @param options - Decoding options
|
|
2070
|
+
* @returns The decoded raw email as a Buffer
|
|
2071
|
+
* @throws {RawEmailDecodeError} If content not included or hash mismatch
|
|
2072
|
+
*
|
|
2073
|
+
* @example
|
|
2074
|
+
* ```typescript
|
|
2075
|
+
* import { handleWebhook, decodeRawEmail, isRawIncluded } from '@primitivedotdev/sdk';
|
|
2076
|
+
*
|
|
2077
|
+
* const event = handleWebhook({ body, headers, secret });
|
|
2078
|
+
*
|
|
2079
|
+
* if (isRawIncluded(event)) {
|
|
2080
|
+
* const rawEmail = decodeRawEmail(event);
|
|
2081
|
+
* // rawEmail is a Buffer containing the RFC 5322 email
|
|
2082
|
+
* } else {
|
|
2083
|
+
* // Must download from event.email.content.download.url
|
|
2084
|
+
* }
|
|
2085
|
+
* ```
|
|
2086
|
+
*/
|
|
2087
|
+
function decodeRawEmail(event, options = {}) {
|
|
2088
|
+
const { verify = true } = options;
|
|
2089
|
+
const raw = event.email.content.raw;
|
|
2090
|
+
if (!raw.included) throw new RawEmailDecodeError("NOT_INCLUDED", `Raw email not included inline (size: ${raw.size_bytes} bytes, threshold: ${raw.max_inline_bytes} bytes). Download from: ${event.email.content.download.url}`);
|
|
2091
|
+
if (!BASE64_PATTERN.test(raw.data)) throw new RawEmailDecodeError("INVALID_BASE64", "Raw email data is not valid base64. The raw email data may be malformed.");
|
|
2092
|
+
const decoded = Buffer.from(raw.data, "base64");
|
|
2093
|
+
if (verify) {
|
|
2094
|
+
const hash = createHash("sha256").update(decoded).digest("hex");
|
|
2095
|
+
if (hash !== raw.sha256.toLowerCase()) throw new RawEmailDecodeError("HASH_MISMATCH", `SHA-256 hash mismatch. Expected: ${raw.sha256}, got: ${hash}. The raw email data may be corrupted.`);
|
|
2096
|
+
}
|
|
2097
|
+
return decoded;
|
|
2098
|
+
}
|
|
2099
|
+
/**
|
|
2100
|
+
* Verify downloaded raw email content against the SHA-256 hash in the event.
|
|
2101
|
+
*
|
|
2102
|
+
* Use this after fetching from `event.email.content.download.url` to ensure
|
|
2103
|
+
* the downloaded content matches what Primitive received.
|
|
2104
|
+
*
|
|
2105
|
+
* @param downloaded - The downloaded raw email content (Buffer, ArrayBuffer, or Uint8Array)
|
|
2106
|
+
* @param event - The webhook event containing the expected hash
|
|
2107
|
+
* @returns The verified content as a Buffer
|
|
2108
|
+
* @throws {RawEmailDecodeError} If hash doesn't match
|
|
2109
|
+
*
|
|
2110
|
+
* @example
|
|
2111
|
+
* ```typescript
|
|
2112
|
+
* import { handleWebhook, verifyRawEmailDownload, isRawIncluded } from '@primitivedotdev/sdk';
|
|
2113
|
+
*
|
|
2114
|
+
* const event = handleWebhook({ body, headers, secret });
|
|
2115
|
+
*
|
|
2116
|
+
* if (!isRawIncluded(event)) {
|
|
2117
|
+
* const response = await fetch(event.email.content.download.url);
|
|
2118
|
+
* const arrayBuffer = await response.arrayBuffer();
|
|
2119
|
+
* const verified = verifyRawEmailDownload(arrayBuffer, event);
|
|
2120
|
+
* // verified is a Buffer containing the RFC 5322 email
|
|
2121
|
+
* }
|
|
2122
|
+
* ```
|
|
2123
|
+
*/
|
|
2124
|
+
function verifyRawEmailDownload(downloaded, event) {
|
|
2125
|
+
const buffer = Buffer.isBuffer(downloaded) ? downloaded : Buffer.from(downloaded);
|
|
2126
|
+
const hash = createHash("sha256").update(buffer).digest("hex");
|
|
2127
|
+
const expected = event.email.content.raw.sha256;
|
|
2128
|
+
if (hash !== expected.toLowerCase()) throw new RawEmailDecodeError("HASH_MISMATCH", `SHA-256 hash mismatch. Expected: ${expected}, got: ${hash}. The downloaded content may be corrupted.`);
|
|
2129
|
+
return buffer;
|
|
2130
|
+
}
|
|
2131
|
+
//#endregion
|
|
2132
|
+
export { signWebhookPayload as C, verifyDownloadToken as E, PRIMITIVE_SIGNATURE_HEADER as S, generateDownloadToken as T, signStandardWebhooksPayload as _, getEventHeader as a, LEGACY_SIGNATURE_HEADER as b, isDownloadExpired as c, verifyRawEmailDownload as d, WEBHOOK_VERSION as f, STANDARD_WEBHOOK_TIMESTAMP_HEADER as g, STANDARD_WEBHOOK_SIGNATURE_HEADER as h, getDownloadTimeRemaining as i, isRawIncluded as l, STANDARD_WEBHOOK_ID_HEADER as m, confirmedHeaders as n, handleWebhook as o, emailReceivedEventJsonSchema as p, decodeRawEmail as r, handleWebhookEvent as s, WEBHOOK_EVENT_HEADER as t, receive as u, verifyStandardWebhooksSignature as v, verifyWebhookSignature as w, PRIMITIVE_CONFIRMED_HEADER as x, LEGACY_CONFIRMED_HEADER as y };
|