@distilled.cloud/resend 1.0.0-rc.19 → 1.0.0-rc.21
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 +73 -3
- package/lib/_bundle/sdk.js +1 -1
- package/lib/_bundle/sdk.js.map +1 -1
- package/lib/credentials.d.ts +9 -4
- package/lib/credentials.d.ts.map +1 -1
- package/lib/errors.d.ts +164 -6
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -1
- package/lib/index.d.ts +2 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.lazy.js +1 -1
- package/lib/index.lazy.js.map +1 -1
- package/lib/pagination.d.ts.map +1 -1
- package/lib/protocol.d.ts +11 -12
- package/lib/protocol.d.ts.map +1 -1
- package/lib/protocol.js +1 -1
- package/lib/retry.d.ts.map +1 -1
- package/lib/services/index.d.ts +1 -0
- package/lib/services/index.d.ts.map +1 -1
- package/lib/services/index.js +1 -0
- package/lib/services/resend.d.ts +3313 -579
- package/lib/services/resend.d.ts.map +1 -1
- package/lib/services/resend.js +226 -102
- package/lib/services/resend.js.map +1 -1
- package/lib/services/webhook_events.d.ts +1011 -0
- package/lib/services/webhook_events.d.ts.map +1 -0
- package/lib/services/webhook_events.js +1 -0
- package/lib/services.lazy/index.js +2 -2
- package/lib/services.lazy/resend.js +3 -2
- package/lib/services.lazy/webhook_events.js +1 -0
- package/lib/traits.d.ts +1 -1
- package/lib/traits.d.ts.map +1 -1
- package/lib/traits.js +1 -1
- package/lib/webhooks.d.ts +42 -0
- package/lib/webhooks.d.ts.map +1 -0
- package/lib/webhooks.js +2 -0
- package/lib/webhooks.js.map +1 -0
- package/package.json +5 -5
- package/src/credentials.ts +24 -16
- package/src/errors.ts +172 -5
- package/src/index.ts +5 -6
- package/src/protocol.ts +21 -30
- package/src/services/index.ts +1 -0
- package/src/services/resend.ts +7881 -1893
- package/src/services/webhook_events.ts +1069 -0
- package/src/traits.ts +3 -0
- package/src/webhooks.ts +245 -0
package/src/traits.ts
CHANGED
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
export {
|
|
10
10
|
Body,
|
|
11
11
|
Header,
|
|
12
|
+
IdempotencyToken,
|
|
12
13
|
Query,
|
|
14
|
+
CommaDelimited,
|
|
13
15
|
Label,
|
|
14
16
|
Http,
|
|
15
17
|
ResponseCode,
|
|
@@ -24,6 +26,7 @@ export {
|
|
|
24
26
|
bodySymbol,
|
|
25
27
|
headerSymbol,
|
|
26
28
|
querySymbol,
|
|
29
|
+
commaDelimitedSymbol,
|
|
27
30
|
labelSymbol,
|
|
28
31
|
httpSymbol,
|
|
29
32
|
responseCodeSymbol,
|
package/src/webhooks.ts
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resend webhook verification -- hand-written.
|
|
3
|
+
*
|
|
4
|
+
* Resend signs deliveries with Standard Webhooks (Svix): the `svix-id`,
|
|
5
|
+
* `svix-timestamp` and `svix-signature` headers (the `webhook-*` names are
|
|
6
|
+
* accepted too), an HMAC-SHA256 over `${id}.${timestamp}.${body}` keyed by
|
|
7
|
+
* the base64 part of the endpoint's `whsec_...` signing secret, and a
|
|
8
|
+
* space-separated `v1,<base64>` signature list. The HMAC runs on core's
|
|
9
|
+
* `Crypto` service (`node:crypto` where the runtime has it, WebCrypto
|
|
10
|
+
* elsewhere), so it runs on Node, Bun and workerd alike.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import * as Resend from "@distilled.cloud/resend";
|
|
15
|
+
*
|
|
16
|
+
* const event = yield* Resend.Webhooks.constructEvent({
|
|
17
|
+
* payload: yield* request.text,
|
|
18
|
+
* headers: request.headers,
|
|
19
|
+
* secret: signingSecret,
|
|
20
|
+
* });
|
|
21
|
+
* if (event.type === "email.bounced") event.data.bounce.type;
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
import * as CoreCrypto from "@distilled.cloud/core/crypto";
|
|
25
|
+
import * as Effect from "effect/Effect";
|
|
26
|
+
import * as Redacted from "effect/Redacted";
|
|
27
|
+
import { ResendWebhookPayloadParseError, ResendWebhookSignatureError } from "./errors.ts";
|
|
28
|
+
import type { WebhookEvent } from "./services/webhook_events.ts";
|
|
29
|
+
|
|
30
|
+
export type { WebhookEvent, WebhookEvents, WebhookEventType } from "./services/webhook_events.ts";
|
|
31
|
+
|
|
32
|
+
/** Standard Webhooks' default: deliveries older or newer than this are refused. */
|
|
33
|
+
export const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
34
|
+
|
|
35
|
+
export type WebhookPayload = string | Uint8Array | ArrayBuffer;
|
|
36
|
+
export type WebhookSecret = string | Redacted.Redacted<string>;
|
|
37
|
+
|
|
38
|
+
/** The three signature headers, already read off the request. */
|
|
39
|
+
export interface WebhookHeaders {
|
|
40
|
+
readonly id: string | null | undefined;
|
|
41
|
+
readonly timestamp: string | null | undefined;
|
|
42
|
+
readonly signature: string | null | undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A fetch `Headers` or a plain header record, read case-insensitively. */
|
|
46
|
+
export type WebhookHeaderSource =
|
|
47
|
+
| WebhookHeaders
|
|
48
|
+
| { readonly get: (name: string) => string | null }
|
|
49
|
+
| Readonly<Record<string, string | ReadonlyArray<string> | undefined>>;
|
|
50
|
+
|
|
51
|
+
export interface VerifySignatureOptions {
|
|
52
|
+
/** Raw request body exactly as Resend sent it. Do not pass parsed or reserialized JSON. */
|
|
53
|
+
readonly payload: WebhookPayload;
|
|
54
|
+
readonly headers: WebhookHeaderSource;
|
|
55
|
+
/** The endpoint's signing secret (`whsec_...`), as createWebhook or getWebhook return it. */
|
|
56
|
+
readonly secret: WebhookSecret;
|
|
57
|
+
/**
|
|
58
|
+
* Maximum allowed distance from now, in seconds, of `svix-timestamp`. Pass
|
|
59
|
+
* `0` to skip the check for tests or offline reprocessing.
|
|
60
|
+
*/
|
|
61
|
+
readonly toleranceSeconds?: number | undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface ConstructEventOptions extends VerifySignatureOptions {}
|
|
65
|
+
|
|
66
|
+
const textEncoder = /*@__PURE__*/ new TextEncoder();
|
|
67
|
+
const textDecoder = /*@__PURE__*/ new TextDecoder("utf-8", { fatal: true });
|
|
68
|
+
|
|
69
|
+
const signatureError = (message: string, cause?: unknown) =>
|
|
70
|
+
new ResendWebhookSignatureError({ message, cause });
|
|
71
|
+
|
|
72
|
+
const payloadToBytes = (payload: WebhookPayload): Uint8Array =>
|
|
73
|
+
typeof payload === "string"
|
|
74
|
+
? textEncoder.encode(payload)
|
|
75
|
+
: payload instanceof ArrayBuffer
|
|
76
|
+
? new Uint8Array(payload)
|
|
77
|
+
: payload;
|
|
78
|
+
|
|
79
|
+
const payloadToString = (payload: WebhookPayload): string =>
|
|
80
|
+
typeof payload === "string" ? payload : textDecoder.decode(payloadToBytes(payload));
|
|
81
|
+
|
|
82
|
+
const isWebhookHeaders = (source: WebhookHeaderSource): source is WebhookHeaders =>
|
|
83
|
+
"id" in source && "timestamp" in source && "signature" in source;
|
|
84
|
+
|
|
85
|
+
const readHeaders = (source: WebhookHeaderSource): WebhookHeaders => {
|
|
86
|
+
if (isWebhookHeaders(source)) return source;
|
|
87
|
+
const get = (name: string): string | undefined => {
|
|
88
|
+
if (typeof source.get === "function") return source.get(name) ?? undefined;
|
|
89
|
+
const record = source as Readonly<Record<string, string | ReadonlyArray<string> | undefined>>;
|
|
90
|
+
const key = Object.keys(record).find((k) => k.toLowerCase() === name);
|
|
91
|
+
const value = key === undefined ? undefined : record[key];
|
|
92
|
+
return typeof value === "string" ? value : value?.join(" ");
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
id: get("svix-id") ?? get("webhook-id"),
|
|
96
|
+
timestamp: get("svix-timestamp") ?? get("webhook-timestamp"),
|
|
97
|
+
signature: get("svix-signature") ?? get("webhook-signature"),
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const base64ToBytes = (base64: string): Uint8Array<ArrayBuffer> | undefined => {
|
|
102
|
+
try {
|
|
103
|
+
const binary = atob(base64);
|
|
104
|
+
const bytes = new Uint8Array(binary.length);
|
|
105
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
106
|
+
return bytes;
|
|
107
|
+
} catch {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const secretKeyBytes = (secret: WebhookSecret): Uint8Array<ArrayBuffer> | undefined => {
|
|
113
|
+
const value = Redacted.isRedacted(secret) ? Redacted.value(secret) : secret;
|
|
114
|
+
const key = base64ToBytes(value.startsWith("whsec_") ? value.slice("whsec_".length) : value);
|
|
115
|
+
return key === undefined || key.byteLength === 0 ? undefined : key;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const hmacSha256 = (
|
|
119
|
+
key: Uint8Array,
|
|
120
|
+
content: Uint8Array,
|
|
121
|
+
): Effect.Effect<Uint8Array, ResendWebhookSignatureError> =>
|
|
122
|
+
Effect.flatMap(CoreCrypto.Crypto, (c) =>
|
|
123
|
+
c.importHmacKey(key).pipe(
|
|
124
|
+
Effect.flatMap((hmacKey) => c.hmacSha256(hmacKey, content)),
|
|
125
|
+
Effect.mapError((cause) =>
|
|
126
|
+
signatureError("Unable to compute the Resend webhook signature", cause),
|
|
127
|
+
),
|
|
128
|
+
),
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
const signedContent = (
|
|
132
|
+
id: string,
|
|
133
|
+
timestamp: string,
|
|
134
|
+
payload: WebhookPayload,
|
|
135
|
+
): Uint8Array<ArrayBuffer> => {
|
|
136
|
+
const prefix = textEncoder.encode(`${id}.${timestamp}.`);
|
|
137
|
+
const body = payloadToBytes(payload);
|
|
138
|
+
const content = new Uint8Array(prefix.byteLength + body.byteLength);
|
|
139
|
+
content.set(prefix, 0);
|
|
140
|
+
content.set(body, prefix.byteLength);
|
|
141
|
+
return content;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const constantTimeEqual = (expected: Uint8Array, candidate: Uint8Array): boolean => {
|
|
145
|
+
// JavaScript cannot guarantee CPU-level constant time, but length mismatches
|
|
146
|
+
// are folded into the accumulator so a matching prefix can never succeed.
|
|
147
|
+
let difference = expected.byteLength ^ candidate.byteLength;
|
|
148
|
+
const byteLength = Math.max(expected.byteLength, candidate.byteLength);
|
|
149
|
+
for (let index = 0; index < byteLength; index += 1) {
|
|
150
|
+
difference |= (expected[index] ?? 0) ^ (candidate[index] ?? 0);
|
|
151
|
+
}
|
|
152
|
+
return difference === 0;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/** `v1,<base64>` entries of the space-separated signature header. */
|
|
156
|
+
const v1Signatures = (header: string): ReadonlyArray<Uint8Array> =>
|
|
157
|
+
header
|
|
158
|
+
.split(" ")
|
|
159
|
+
.map((entry) => entry.trim())
|
|
160
|
+
.filter((entry) => entry.startsWith("v1,"))
|
|
161
|
+
.map((entry) => base64ToBytes(entry.slice("v1,".length)) ?? new Uint8Array(0));
|
|
162
|
+
|
|
163
|
+
/** Fails with {@link ResendWebhookSignatureError} unless the delivery is signed with `secret`. */
|
|
164
|
+
export const verifySignature = ({
|
|
165
|
+
payload,
|
|
166
|
+
headers,
|
|
167
|
+
secret,
|
|
168
|
+
toleranceSeconds = DEFAULT_WEBHOOK_TOLERANCE_SECONDS,
|
|
169
|
+
}: VerifySignatureOptions): Effect.Effect<void, ResendWebhookSignatureError> =>
|
|
170
|
+
Effect.gen(function* () {
|
|
171
|
+
const { id, timestamp, signature } = readHeaders(headers);
|
|
172
|
+
if (!id || !timestamp || !signature) {
|
|
173
|
+
return yield* signatureError(
|
|
174
|
+
"svix-id, svix-timestamp and svix-signature headers are required",
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const timestampSeconds = Number(timestamp);
|
|
179
|
+
if (!Number.isSafeInteger(timestampSeconds) || String(timestampSeconds) !== timestamp) {
|
|
180
|
+
return yield* signatureError("svix-timestamp header is invalid");
|
|
181
|
+
}
|
|
182
|
+
if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) {
|
|
183
|
+
return yield* signatureError("Resend webhook tolerance must be a non-negative number");
|
|
184
|
+
}
|
|
185
|
+
if (
|
|
186
|
+
toleranceSeconds > 0 &&
|
|
187
|
+
Math.abs(Math.floor(Date.now() / 1000) - timestampSeconds) > toleranceSeconds
|
|
188
|
+
) {
|
|
189
|
+
return yield* signatureError(
|
|
190
|
+
`Resend webhook timestamp is outside the tolerance window of ${toleranceSeconds} seconds`,
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const key = secretKeyBytes(secret);
|
|
195
|
+
if (key === undefined) {
|
|
196
|
+
return yield* signatureError("Resend webhook secret is not a whsec_ base64 secret");
|
|
197
|
+
}
|
|
198
|
+
const candidates = v1Signatures(signature);
|
|
199
|
+
if (candidates.length === 0) {
|
|
200
|
+
return yield* signatureError("svix-signature header has no v1 signature");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const expected = yield* hmacSha256(key, signedContent(id, timestamp, payload));
|
|
204
|
+
let matched = false;
|
|
205
|
+
for (const candidate of candidates) matched = constantTimeEqual(expected, candidate) || matched;
|
|
206
|
+
if (!matched) {
|
|
207
|
+
return yield* signatureError("No v1 signature matches the expected Resend webhook signature");
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The envelope check: a JSON object with a string `type`. The payload is
|
|
213
|
+
* typed from the spec, not decoded, so this is the only runtime check.
|
|
214
|
+
*/
|
|
215
|
+
const isWebhookEvent = (value: unknown): value is WebhookEvent =>
|
|
216
|
+
typeof value === "object" &&
|
|
217
|
+
value !== null &&
|
|
218
|
+
!Array.isArray(value) &&
|
|
219
|
+
typeof (value as { readonly type?: unknown }).type === "string";
|
|
220
|
+
|
|
221
|
+
const payloadParseError = (message: string, cause?: unknown) =>
|
|
222
|
+
new ResendWebhookPayloadParseError({ message, cause });
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Verifies the signature, then parses the body as a {@link WebhookEvent}.
|
|
226
|
+
* The payload is typed from the spec, not decoded: an event type newer than
|
|
227
|
+
* this SDK still arrives, with a `type` outside the union.
|
|
228
|
+
*/
|
|
229
|
+
export const constructEvent = (
|
|
230
|
+
options: ConstructEventOptions,
|
|
231
|
+
): Effect.Effect<WebhookEvent, ResendWebhookSignatureError | ResendWebhookPayloadParseError> =>
|
|
232
|
+
Effect.gen(function* () {
|
|
233
|
+
yield* verifySignature(options);
|
|
234
|
+
const parsed: unknown = yield* Effect.try({
|
|
235
|
+
try: () => JSON.parse(payloadToString(options.payload)),
|
|
236
|
+
catch: (cause) =>
|
|
237
|
+
payloadParseError("Unable to parse the Resend webhook payload as JSON", cause),
|
|
238
|
+
});
|
|
239
|
+
if (!isWebhookEvent(parsed)) {
|
|
240
|
+
return yield* payloadParseError(
|
|
241
|
+
"Resend webhook payload must be a JSON object with a string `type`",
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
return parsed;
|
|
245
|
+
});
|