@stream-io/node-sdk 0.7.56 → 0.7.57

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/dist/index.cjs.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var jwt = require('jsonwebtoken');
4
4
  var crypto = require('crypto');
5
+ var zlib = require('zlib');
5
6
  var uuid = require('uuid');
6
7
 
7
8
  function _interopNamespaceDefault(e) {
@@ -43,6 +44,184 @@ function JWTServerToken(apiSecret, jwtOptions = {}) {
43
44
  return jwt.sign(payload, apiSecret, opts);
44
45
  }
45
46
 
47
+ /**
48
+ * Canonical failure-mode messages for {@link InvalidWebhookError}.
49
+ *
50
+ * Callers that prefer exact-match filtering (security logging, retry
51
+ * policy) over substring matches can compare `err.message` to these
52
+ * constants instead of pattern-matching free-form text.
53
+ */
54
+ const InvalidWebhookErrorMessages = {
55
+ signatureMismatch: 'signature mismatch',
56
+ invalidBase64: 'invalid base64 encoding',
57
+ gzipFailed: 'gzip decompression failed',
58
+ invalidJson: 'invalid JSON payload',
59
+ };
60
+ /**
61
+ * Thrown by {@link verifyAndParseWebhook} when the supplied `x-signature`
62
+ * does not match the HMAC of the uncompressed payload, and by all webhook
63
+ * helpers (including {@link parseSqs} / {@link parseSns}) when a
64
+ * gzip / base64 / JSON envelope is malformed.
65
+ *
66
+ * The message identifies which failure mode fired. See
67
+ * {@link InvalidWebhookErrorMessages} for the canonical strings.
68
+ */
69
+ class InvalidWebhookError extends Error {
70
+ constructor(message = InvalidWebhookErrorMessages.signatureMismatch) {
71
+ super(message);
72
+ this.name = 'InvalidWebhookError';
73
+ }
74
+ }
75
+ const GZIP_MAGIC = Buffer.from([0x1f, 0x8b]);
76
+ /**
77
+ * Returns `body` as a `Buffer`, gzip-decompressed when its first two
78
+ * bytes match the gzip magic (`1f 8b`, per RFC 1952). When the body is
79
+ * plain JSON (no compression, or middleware already decompressed), the
80
+ * bytes are returned unchanged.
81
+ *
82
+ * Magic-byte detection (rather than relying on a header) keeps the same
83
+ * handler correct when middleware - Express, Next.js, AWS Lambda -
84
+ * auto-decompresses the request before your code sees it.
85
+ */
86
+ function gunzipPayload(rawBody) {
87
+ const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody);
88
+ if (body.length >= 2 && body.subarray(0, 2).equals(GZIP_MAGIC)) {
89
+ try {
90
+ return zlib.gunzipSync(body);
91
+ }
92
+ catch {
93
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.gzipFailed);
94
+ }
95
+ }
96
+ return body;
97
+ }
98
+ /**
99
+ * Reverses the SQS firehose envelope: the message `Body` is
100
+ * base64-decoded, then the result is gzip-decompressed when it begins
101
+ * with the gzip magic. Returns the raw JSON `Buffer` Stream signed.
102
+ *
103
+ * SQS bodies are always base64-encoded so they remain valid UTF-8 over
104
+ * the queue. The same call works whether or not Stream is currently
105
+ * compressing payloads for this app.
106
+ */
107
+ function decodeSqsPayload(body) {
108
+ // Reject anything that isn't canonical base64 up front. Node's base64
109
+ // decoder is permissive (silently strips characters outside the
110
+ // alphabet, accepts both standard and URL-safe variants), so we have
111
+ // to be strict here to avoid silently corrupting the body before the
112
+ // signature check runs.
113
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(body) || body.length % 4 !== 0) {
114
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidBase64);
115
+ }
116
+ const decoded = Buffer.from(body, 'base64');
117
+ if (decoded.toString('base64').length !== body.length) {
118
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidBase64);
119
+ }
120
+ return gunzipPayload(decoded);
121
+ }
122
+ /**
123
+ * Reverses an SNS HTTP notification envelope. When `notificationBody`
124
+ * is a JSON envelope (`{"Type":"Notification","Message":"..."}`), the
125
+ * inner `Message` field is extracted and run through the SQS pipeline
126
+ * (base64-decode, then gzip-if-magic). When the input is not a JSON
127
+ * envelope it is treated as the already-extracted `Message` string,
128
+ * so call sites that pre-unwrap continue to work.
129
+ */
130
+ function decodeSnsPayload(notificationBody) {
131
+ const inner = extractSnsMessage(notificationBody);
132
+ return decodeSqsPayload(inner ?? notificationBody);
133
+ }
134
+ function extractSnsMessage(notificationBody) {
135
+ const trimmed = notificationBody.replace(/^[\s\uFEFF]+/, '');
136
+ if (!trimmed.startsWith('{')) {
137
+ return null;
138
+ }
139
+ let parsed;
140
+ try {
141
+ parsed = JSON.parse(trimmed);
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ if (parsed === null ||
147
+ typeof parsed !== 'object' ||
148
+ Array.isArray(parsed) ||
149
+ typeof parsed.Message !== 'string') {
150
+ return null;
151
+ }
152
+ return parsed.Message;
153
+ }
154
+ /**
155
+ * Constant-time HMAC-SHA256 verification of `signature` against the
156
+ * digest of `body` using `secret` as the key. The signature is always
157
+ * computed over the **uncompressed** JSON bytes, so callers that
158
+ * decoded a gzipped or base64-wrapped payload must pass the inflated
159
+ * bytes here.
160
+ *
161
+ * The legacy `client.verifyWebhook` helper wraps this function, so
162
+ * callers that have already migrated to `verifyAndParseWebhook`,
163
+ * `parseSqs`, or `parseSns` rarely need to invoke this directly.
164
+ */
165
+ function verifySignature(body, signature, secret) {
166
+ const key = Buffer.from(secret, 'utf8');
167
+ const hash = crypto.createHmac('sha256', key).update(body).digest('hex');
168
+ try {
169
+ return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(signature));
170
+ }
171
+ catch {
172
+ return false;
173
+ }
174
+ }
175
+ /**
176
+ * Parse a JSON-encoded webhook event into a typed {@link WHEvent}. New
177
+ * event types Stream introduces still parse successfully — the runtime
178
+ * shape is the JSON Stream sent and the `type` field stays preserved.
179
+ */
180
+ function parseEvent(payload) {
181
+ const text = Buffer.isBuffer(payload) ? payload.toString('utf8') : payload;
182
+ try {
183
+ return JSON.parse(text);
184
+ }
185
+ catch {
186
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidJson);
187
+ }
188
+ }
189
+ function verifyAndParse(payload, signature, secret) {
190
+ if (!verifySignature(payload, signature, secret)) {
191
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.signatureMismatch);
192
+ }
193
+ return parseEvent(payload);
194
+ }
195
+ /**
196
+ * Decompress (when gzipped), verify the HMAC `signature`, and return
197
+ * the parsed {@link WHEvent}.
198
+ *
199
+ * @param rawBody Raw HTTP request body bytes Stream signed
200
+ * @param signature Value of the `X-Signature` header
201
+ * @param secret Your app's API secret
202
+ * @throws {InvalidWebhookError} When the signature does not match or
203
+ * the gzip / base64 / JSON envelope is malformed.
204
+ */
205
+ function verifyAndParseWebhook(rawBody, signature, secret) {
206
+ return verifyAndParse(gunzipPayload(rawBody), signature, secret);
207
+ }
208
+ /**
209
+ * Decode the SQS message `Body` (base64, then gzip-if-magic) and return
210
+ * the parsed {@link WHEvent}. Stream does not attach an application-level
211
+ * HMAC to SQS deliveries — use {@link verifyAndParseWebhook} for HTTP
212
+ * webhooks.
213
+ */
214
+ function parseSqs(messageBody) {
215
+ return parseEvent(decodeSqsPayload(messageBody));
216
+ }
217
+ /**
218
+ * Decode an SNS notification (unwrap the JSON envelope when needed; same
219
+ * inner format as SQS). No application-level HMAC verification.
220
+ */
221
+ function parseSns(notificationBody) {
222
+ return parseEvent(decodeSnsPayload(notificationBody));
223
+ }
224
+
46
225
  const decoders = {};
47
226
  const decodeDatetimeType = (input) => typeof input === 'number'
48
227
  ? new Date(Math.floor(input / 1000000))
@@ -7967,7 +8146,7 @@ class ApiClient {
7967
8146
  const headers = {
7968
8147
  Authorization: this.apiConfig.token,
7969
8148
  'stream-auth-type': 'jwt',
7970
- 'X-Stream-Client': 'stream-node-' + "0.7.56",
8149
+ 'X-Stream-Client': 'stream-node-' + "0.7.57",
7971
8150
  'Accept-Encoding': 'gzip',
7972
8151
  'x-client-request-id': clientRequestId,
7973
8152
  };
@@ -8752,6 +8931,7 @@ class FeedsApi {
8752
8931
  async deleteFeed(request) {
8753
8932
  const queryParams = {
8754
8933
  hard_delete: request?.hard_delete,
8934
+ purge_user_activities: request?.purge_user_activities,
8755
8935
  };
8756
8936
  const pathParams = {
8757
8937
  feed_group_id: request?.feed_group_id,
@@ -9107,6 +9287,7 @@ class FeedsApi {
9107
9287
  const body = {
9108
9288
  feeds: request?.feeds,
9109
9289
  hard_delete: request?.hard_delete,
9290
+ purge_user_activities: request?.purge_user_activities,
9110
9291
  };
9111
9292
  const response = await this.apiClient.sendRequest('POST', '/api/v2/feeds/feeds/delete', undefined, undefined, body, 'application/json');
9112
9293
  decoders.DeleteFeedsBatchResponse?.(response.body);
@@ -9642,6 +9823,43 @@ class StreamClient extends CommonApi {
9642
9823
  return false;
9643
9824
  }
9644
9825
  };
9826
+ /**
9827
+ * Verify and parse an HTTP webhook event.
9828
+ *
9829
+ * Decompresses `rawBody` when gzipped (detected from the body bytes),
9830
+ * verifies the `X-Signature` header against the app's API secret, and
9831
+ * returns the parsed typed event. Works whether or not Stream is
9832
+ * currently compressing payloads for this app, and stays correct behind
9833
+ * middleware that auto-decompresses the request.
9834
+ *
9835
+ * @param rawBody Raw HTTP request body bytes Stream signed
9836
+ * @param signature Value of the `X-Signature` header
9837
+ * @throws {InvalidWebhookError} When the signature does not match or
9838
+ * the gzip / JSON envelope is malformed.
9839
+ */
9840
+ this.verifyAndParseWebhook = (rawBody, signature) => {
9841
+ if (!this.secret) {
9842
+ throw new InvalidWebhookError('cannot verify webhook signature without an API secret on the client');
9843
+ }
9844
+ return verifyAndParseWebhook(rawBody, signature, this.secret);
9845
+ };
9846
+ /**
9847
+ * Parse an SQS firehose event: decodes the message `Body` (base64 +
9848
+ * optional gzip) and returns the parsed typed event. No HMAC
9849
+ * verification (Stream does not sign SQS bodies).
9850
+ *
9851
+ * @param messageBody SQS message `Body` string
9852
+ * @throws {InvalidWebhookError} When the base64 / gzip envelope is malformed.
9853
+ */
9854
+ this.parseSqs = (messageBody) => parseSqs(messageBody);
9855
+ /**
9856
+ * Parse an SNS-delivered event (unwraps envelope JSON when needed, then
9857
+ * same decode path as SQS). No HMAC verification.
9858
+ *
9859
+ * @param notificationBody Raw SNS POST body or pre-extracted `Message` string
9860
+ * @throws {InvalidWebhookError} When the envelope cannot be decoded.
9861
+ */
9862
+ this.parseSns = (notificationBody) => parseSns(notificationBody);
9645
9863
  this.video = new StreamVideoClient({
9646
9864
  streamClient: this,
9647
9865
  apiClient: videoApiClient,
@@ -9764,6 +9982,8 @@ const OwnCapability = {
9764
9982
 
9765
9983
  exports.ChannelOwnCapability = ChannelOwnCapability;
9766
9984
  exports.FeedOwnCapability = FeedOwnCapability;
9985
+ exports.InvalidWebhookError = InvalidWebhookError;
9986
+ exports.InvalidWebhookErrorMessages = InvalidWebhookErrorMessages;
9767
9987
  exports.OwnCapability = OwnCapability;
9768
9988
  exports.StreamCall = StreamCall;
9769
9989
  exports.StreamChannel = StreamChannel;