@stream-io/node-sdk 0.7.56 → 0.7.58

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.
@@ -0,0 +1,206 @@
1
+ import crypto from 'crypto';
2
+ import zlib from 'zlib';
3
+ import type { WHEvent } from '../gen/models';
4
+
5
+ /**
6
+ * Canonical failure-mode messages for {@link InvalidWebhookError}.
7
+ *
8
+ * Callers that prefer exact-match filtering (security logging, retry
9
+ * policy) over substring matches can compare `err.message` to these
10
+ * constants instead of pattern-matching free-form text.
11
+ */
12
+ export const InvalidWebhookErrorMessages = {
13
+ signatureMismatch: 'signature mismatch',
14
+ invalidBase64: 'invalid base64 encoding',
15
+ gzipFailed: 'gzip decompression failed',
16
+ invalidJson: 'invalid JSON payload',
17
+ } as const;
18
+
19
+ /**
20
+ * Thrown by {@link verifyAndParseWebhook} when the supplied `x-signature`
21
+ * does not match the HMAC of the uncompressed payload, and by all webhook
22
+ * helpers (including {@link parseSqs} / {@link parseSns}) when a
23
+ * gzip / base64 / JSON envelope is malformed.
24
+ *
25
+ * The message identifies which failure mode fired. See
26
+ * {@link InvalidWebhookErrorMessages} for the canonical strings.
27
+ */
28
+ export class InvalidWebhookError extends Error {
29
+ public name = 'InvalidWebhookError';
30
+
31
+ constructor(message: string = InvalidWebhookErrorMessages.signatureMismatch) {
32
+ super(message);
33
+ }
34
+ }
35
+
36
+ const GZIP_MAGIC = Buffer.from([0x1f, 0x8b]);
37
+
38
+ /**
39
+ * Returns `body` as a `Buffer`, gzip-decompressed when its first two
40
+ * bytes match the gzip magic (`1f 8b`, per RFC 1952). When the body is
41
+ * plain JSON (no compression, or middleware already decompressed), the
42
+ * bytes are returned unchanged.
43
+ *
44
+ * Magic-byte detection (rather than relying on a header) keeps the same
45
+ * handler correct when middleware - Express, Next.js, AWS Lambda -
46
+ * auto-decompresses the request before your code sees it.
47
+ */
48
+ export function gunzipPayload(rawBody: string | Buffer): Buffer {
49
+ const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody);
50
+ if (body.length >= 2 && body.subarray(0, 2).equals(GZIP_MAGIC)) {
51
+ try {
52
+ return zlib.gunzipSync(body);
53
+ } catch {
54
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.gzipFailed);
55
+ }
56
+ }
57
+ return body;
58
+ }
59
+
60
+ /**
61
+ * Reverses the SQS firehose envelope: the message `Body` is
62
+ * base64-decoded, then the result is gzip-decompressed when it begins
63
+ * with the gzip magic. Returns the raw JSON `Buffer` Stream signed.
64
+ *
65
+ * SQS bodies are always base64-encoded so they remain valid UTF-8 over
66
+ * the queue. The same call works whether or not Stream is currently
67
+ * compressing payloads for this app.
68
+ */
69
+ export function decodeSqsPayload(body: string): Buffer {
70
+ // Reject anything that isn't canonical base64 up front. Node's base64
71
+ // decoder is permissive (silently strips characters outside the
72
+ // alphabet, accepts both standard and URL-safe variants), so we have
73
+ // to be strict here to avoid silently corrupting the body before the
74
+ // signature check runs.
75
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(body) || body.length % 4 !== 0) {
76
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidBase64);
77
+ }
78
+ const decoded = Buffer.from(body, 'base64');
79
+ if (decoded.toString('base64').length !== body.length) {
80
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidBase64);
81
+ }
82
+ return gunzipPayload(decoded);
83
+ }
84
+
85
+ /**
86
+ * Reverses an SNS HTTP notification envelope. When `notificationBody`
87
+ * is a JSON envelope (`{"Type":"Notification","Message":"..."}`), the
88
+ * inner `Message` field is extracted and run through the SQS pipeline
89
+ * (base64-decode, then gzip-if-magic). When the input is not a JSON
90
+ * envelope it is treated as the already-extracted `Message` string,
91
+ * so call sites that pre-unwrap continue to work.
92
+ */
93
+ export function decodeSnsPayload(notificationBody: string): Buffer {
94
+ const inner = extractSnsMessage(notificationBody);
95
+ return decodeSqsPayload(inner ?? notificationBody);
96
+ }
97
+
98
+ function extractSnsMessage(notificationBody: string): string | null {
99
+ const trimmed = notificationBody.replace(/^[\s\uFEFF]+/, '');
100
+ if (!trimmed.startsWith('{')) {
101
+ return null;
102
+ }
103
+ let parsed: unknown;
104
+ try {
105
+ parsed = JSON.parse(trimmed);
106
+ } catch {
107
+ return null;
108
+ }
109
+ if (
110
+ parsed === null ||
111
+ typeof parsed !== 'object' ||
112
+ Array.isArray(parsed) ||
113
+ typeof (parsed as { Message?: unknown }).Message !== 'string'
114
+ ) {
115
+ return null;
116
+ }
117
+ return (parsed as { Message: string }).Message;
118
+ }
119
+
120
+ /**
121
+ * Constant-time HMAC-SHA256 verification of `signature` against the
122
+ * digest of `body` using `secret` as the key. The signature is always
123
+ * computed over the **uncompressed** JSON bytes, so callers that
124
+ * decoded a gzipped or base64-wrapped payload must pass the inflated
125
+ * bytes here.
126
+ *
127
+ * The legacy `client.verifyWebhook` helper wraps this function, so
128
+ * callers that have already migrated to `verifyAndParseWebhook`,
129
+ * `parseSqs`, or `parseSns` rarely need to invoke this directly.
130
+ */
131
+ export function verifySignature(
132
+ body: string | Buffer,
133
+ signature: string,
134
+ secret: string,
135
+ ): boolean {
136
+ const key = Buffer.from(secret, 'utf8');
137
+ const hash = crypto.createHmac('sha256', key).update(body).digest('hex');
138
+ try {
139
+ return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(signature));
140
+ } catch {
141
+ return false;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Parse a JSON-encoded webhook event into a typed {@link WHEvent}. New
147
+ * event types Stream introduces still parse successfully — the runtime
148
+ * shape is the JSON Stream sent and the `type` field stays preserved.
149
+ */
150
+ export function parseEvent(payload: Buffer | string): WHEvent {
151
+ const text = Buffer.isBuffer(payload) ? payload.toString('utf8') : payload;
152
+ try {
153
+ return JSON.parse(text) as WHEvent;
154
+ } catch {
155
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidJson);
156
+ }
157
+ }
158
+
159
+ function verifyAndParse(
160
+ payload: Buffer,
161
+ signature: string,
162
+ secret: string,
163
+ ): WHEvent {
164
+ if (!verifySignature(payload, signature, secret)) {
165
+ throw new InvalidWebhookError(
166
+ InvalidWebhookErrorMessages.signatureMismatch,
167
+ );
168
+ }
169
+ return parseEvent(payload);
170
+ }
171
+
172
+ /**
173
+ * Decompress (when gzipped), verify the HMAC `signature`, and return
174
+ * the parsed {@link WHEvent}.
175
+ *
176
+ * @param rawBody Raw HTTP request body bytes Stream signed
177
+ * @param signature Value of the `X-Signature` header
178
+ * @param secret Your app's API secret
179
+ * @throws {InvalidWebhookError} When the signature does not match or
180
+ * the gzip / base64 / JSON envelope is malformed.
181
+ */
182
+ export function verifyAndParseWebhook(
183
+ rawBody: string | Buffer,
184
+ signature: string,
185
+ secret: string,
186
+ ): WHEvent {
187
+ return verifyAndParse(gunzipPayload(rawBody), signature, secret);
188
+ }
189
+
190
+ /**
191
+ * Decode the SQS message `Body` (base64, then gzip-if-magic) and return
192
+ * the parsed {@link WHEvent}. Stream does not attach an application-level
193
+ * HMAC to SQS deliveries — use {@link verifyAndParseWebhook} for HTTP
194
+ * webhooks.
195
+ */
196
+ export function parseSqs(messageBody: string): WHEvent {
197
+ return parseEvent(decodeSqsPayload(messageBody));
198
+ }
199
+
200
+ /**
201
+ * Decode an SNS notification (unwrap the JSON envelope when needed; same
202
+ * inner format as SQS). No application-level HMAC verification.
203
+ */
204
+ export function parseSns(notificationBody: string): WHEvent {
205
+ return parseEvent(decodeSnsPayload(notificationBody));
206
+ }