@stream-io/node-sdk 0.7.55 → 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.d.ts CHANGED
@@ -6,3 +6,4 @@ export * from './src/StreamVideoClient';
6
6
  export * from './src/gen/models';
7
7
  export * from './src/StreamFeedsClient';
8
8
  export * from './src/StreamFeed';
9
+ export { InvalidWebhookError, InvalidWebhookErrorMessages, } from './src/utils/webhook';
package/dist/index.es.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import jwt from 'jsonwebtoken';
2
2
  import crypto from 'crypto';
3
+ import zlib from 'zlib';
3
4
  import { v4 } from 'uuid';
4
5
 
5
6
  function JWTUserToken(apiSecret, payload) {
@@ -24,6 +25,184 @@ function JWTServerToken(apiSecret, jwtOptions = {}) {
24
25
  return jwt.sign(payload, apiSecret, opts);
25
26
  }
26
27
 
28
+ /**
29
+ * Canonical failure-mode messages for {@link InvalidWebhookError}.
30
+ *
31
+ * Callers that prefer exact-match filtering (security logging, retry
32
+ * policy) over substring matches can compare `err.message` to these
33
+ * constants instead of pattern-matching free-form text.
34
+ */
35
+ const InvalidWebhookErrorMessages = {
36
+ signatureMismatch: 'signature mismatch',
37
+ invalidBase64: 'invalid base64 encoding',
38
+ gzipFailed: 'gzip decompression failed',
39
+ invalidJson: 'invalid JSON payload',
40
+ };
41
+ /**
42
+ * Thrown by {@link verifyAndParseWebhook} when the supplied `x-signature`
43
+ * does not match the HMAC of the uncompressed payload, and by all webhook
44
+ * helpers (including {@link parseSqs} / {@link parseSns}) when a
45
+ * gzip / base64 / JSON envelope is malformed.
46
+ *
47
+ * The message identifies which failure mode fired. See
48
+ * {@link InvalidWebhookErrorMessages} for the canonical strings.
49
+ */
50
+ class InvalidWebhookError extends Error {
51
+ constructor(message = InvalidWebhookErrorMessages.signatureMismatch) {
52
+ super(message);
53
+ this.name = 'InvalidWebhookError';
54
+ }
55
+ }
56
+ const GZIP_MAGIC = Buffer.from([0x1f, 0x8b]);
57
+ /**
58
+ * Returns `body` as a `Buffer`, gzip-decompressed when its first two
59
+ * bytes match the gzip magic (`1f 8b`, per RFC 1952). When the body is
60
+ * plain JSON (no compression, or middleware already decompressed), the
61
+ * bytes are returned unchanged.
62
+ *
63
+ * Magic-byte detection (rather than relying on a header) keeps the same
64
+ * handler correct when middleware - Express, Next.js, AWS Lambda -
65
+ * auto-decompresses the request before your code sees it.
66
+ */
67
+ function gunzipPayload(rawBody) {
68
+ const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody);
69
+ if (body.length >= 2 && body.subarray(0, 2).equals(GZIP_MAGIC)) {
70
+ try {
71
+ return zlib.gunzipSync(body);
72
+ }
73
+ catch {
74
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.gzipFailed);
75
+ }
76
+ }
77
+ return body;
78
+ }
79
+ /**
80
+ * Reverses the SQS firehose envelope: the message `Body` is
81
+ * base64-decoded, then the result is gzip-decompressed when it begins
82
+ * with the gzip magic. Returns the raw JSON `Buffer` Stream signed.
83
+ *
84
+ * SQS bodies are always base64-encoded so they remain valid UTF-8 over
85
+ * the queue. The same call works whether or not Stream is currently
86
+ * compressing payloads for this app.
87
+ */
88
+ function decodeSqsPayload(body) {
89
+ // Reject anything that isn't canonical base64 up front. Node's base64
90
+ // decoder is permissive (silently strips characters outside the
91
+ // alphabet, accepts both standard and URL-safe variants), so we have
92
+ // to be strict here to avoid silently corrupting the body before the
93
+ // signature check runs.
94
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(body) || body.length % 4 !== 0) {
95
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidBase64);
96
+ }
97
+ const decoded = Buffer.from(body, 'base64');
98
+ if (decoded.toString('base64').length !== body.length) {
99
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidBase64);
100
+ }
101
+ return gunzipPayload(decoded);
102
+ }
103
+ /**
104
+ * Reverses an SNS HTTP notification envelope. When `notificationBody`
105
+ * is a JSON envelope (`{"Type":"Notification","Message":"..."}`), the
106
+ * inner `Message` field is extracted and run through the SQS pipeline
107
+ * (base64-decode, then gzip-if-magic). When the input is not a JSON
108
+ * envelope it is treated as the already-extracted `Message` string,
109
+ * so call sites that pre-unwrap continue to work.
110
+ */
111
+ function decodeSnsPayload(notificationBody) {
112
+ const inner = extractSnsMessage(notificationBody);
113
+ return decodeSqsPayload(inner ?? notificationBody);
114
+ }
115
+ function extractSnsMessage(notificationBody) {
116
+ const trimmed = notificationBody.replace(/^[\s\uFEFF]+/, '');
117
+ if (!trimmed.startsWith('{')) {
118
+ return null;
119
+ }
120
+ let parsed;
121
+ try {
122
+ parsed = JSON.parse(trimmed);
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ if (parsed === null ||
128
+ typeof parsed !== 'object' ||
129
+ Array.isArray(parsed) ||
130
+ typeof parsed.Message !== 'string') {
131
+ return null;
132
+ }
133
+ return parsed.Message;
134
+ }
135
+ /**
136
+ * Constant-time HMAC-SHA256 verification of `signature` against the
137
+ * digest of `body` using `secret` as the key. The signature is always
138
+ * computed over the **uncompressed** JSON bytes, so callers that
139
+ * decoded a gzipped or base64-wrapped payload must pass the inflated
140
+ * bytes here.
141
+ *
142
+ * The legacy `client.verifyWebhook` helper wraps this function, so
143
+ * callers that have already migrated to `verifyAndParseWebhook`,
144
+ * `parseSqs`, or `parseSns` rarely need to invoke this directly.
145
+ */
146
+ function verifySignature(body, signature, secret) {
147
+ const key = Buffer.from(secret, 'utf8');
148
+ const hash = crypto.createHmac('sha256', key).update(body).digest('hex');
149
+ try {
150
+ return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(signature));
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
156
+ /**
157
+ * Parse a JSON-encoded webhook event into a typed {@link WHEvent}. New
158
+ * event types Stream introduces still parse successfully — the runtime
159
+ * shape is the JSON Stream sent and the `type` field stays preserved.
160
+ */
161
+ function parseEvent(payload) {
162
+ const text = Buffer.isBuffer(payload) ? payload.toString('utf8') : payload;
163
+ try {
164
+ return JSON.parse(text);
165
+ }
166
+ catch {
167
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.invalidJson);
168
+ }
169
+ }
170
+ function verifyAndParse(payload, signature, secret) {
171
+ if (!verifySignature(payload, signature, secret)) {
172
+ throw new InvalidWebhookError(InvalidWebhookErrorMessages.signatureMismatch);
173
+ }
174
+ return parseEvent(payload);
175
+ }
176
+ /**
177
+ * Decompress (when gzipped), verify the HMAC `signature`, and return
178
+ * the parsed {@link WHEvent}.
179
+ *
180
+ * @param rawBody Raw HTTP request body bytes Stream signed
181
+ * @param signature Value of the `X-Signature` header
182
+ * @param secret Your app's API secret
183
+ * @throws {InvalidWebhookError} When the signature does not match or
184
+ * the gzip / base64 / JSON envelope is malformed.
185
+ */
186
+ function verifyAndParseWebhook(rawBody, signature, secret) {
187
+ return verifyAndParse(gunzipPayload(rawBody), signature, secret);
188
+ }
189
+ /**
190
+ * Decode the SQS message `Body` (base64, then gzip-if-magic) and return
191
+ * the parsed {@link WHEvent}. Stream does not attach an application-level
192
+ * HMAC to SQS deliveries — use {@link verifyAndParseWebhook} for HTTP
193
+ * webhooks.
194
+ */
195
+ function parseSqs(messageBody) {
196
+ return parseEvent(decodeSqsPayload(messageBody));
197
+ }
198
+ /**
199
+ * Decode an SNS notification (unwrap the JSON envelope when needed; same
200
+ * inner format as SQS). No application-level HMAC verification.
201
+ */
202
+ function parseSns(notificationBody) {
203
+ return parseEvent(decodeSnsPayload(notificationBody));
204
+ }
205
+
27
206
  const decoders = {};
28
207
  const decodeDatetimeType = (input) => typeof input === 'number'
29
208
  ? new Date(Math.floor(input / 1000000))
@@ -3034,6 +3213,12 @@ decoders.QueryReviewQueueResponse = (input) => {
3034
3213
  };
3035
3214
  return decode(typeMappings, input);
3036
3215
  };
3216
+ decoders.QueryRevisionHistoryResponse = (input) => {
3217
+ const typeMappings = {
3218
+ revisions: { type: 'RevisionHistoryResponse', isSingle: false },
3219
+ };
3220
+ return decode(typeMappings, input);
3221
+ };
3037
3222
  decoders.QuerySegmentTargetsResponse = (input) => {
3038
3223
  const typeMappings = {
3039
3224
  targets: { type: 'SegmentTargetResponse', isSingle: false },
@@ -3286,6 +3471,12 @@ decoders.ReviewQueueItemUpdatedEvent = (input) => {
3286
3471
  };
3287
3472
  return decode(typeMappings, input);
3288
3473
  };
3474
+ decoders.RevisionHistoryResponse = (input) => {
3475
+ const typeMappings = {
3476
+ created_at: { type: 'DatetimeType', isSingle: true },
3477
+ };
3478
+ return decode(typeMappings, input);
3479
+ };
3289
3480
  decoders.Role = (input) => {
3290
3481
  const typeMappings = {
3291
3482
  created_at: { type: 'DatetimeType', isSingle: true },
@@ -7936,7 +8127,7 @@ class ApiClient {
7936
8127
  const headers = {
7937
8128
  Authorization: this.apiConfig.token,
7938
8129
  'stream-auth-type': 'jwt',
7939
- 'X-Stream-Client': 'stream-node-' + "0.7.55",
8130
+ 'X-Stream-Client': 'stream-node-' + "0.7.57",
7940
8131
  'Accept-Encoding': 'gzip',
7941
8132
  'x-client-request-id': clientRequestId,
7942
8133
  };
@@ -8721,6 +8912,7 @@ class FeedsApi {
8721
8912
  async deleteFeed(request) {
8722
8913
  const queryParams = {
8723
8914
  hard_delete: request?.hard_delete,
8915
+ purge_user_activities: request?.purge_user_activities,
8724
8916
  };
8725
8917
  const pathParams = {
8726
8918
  feed_group_id: request?.feed_group_id,
@@ -8990,7 +9182,6 @@ class FeedsApi {
8990
9182
  const body = {
8991
9183
  id: request?.id,
8992
9184
  activity_selectors: request?.activity_selectors,
8993
- activity_filter: request?.activity_filter,
8994
9185
  aggregation: request?.aggregation,
8995
9186
  ranking: request?.ranking,
8996
9187
  };
@@ -9020,7 +9211,6 @@ class FeedsApi {
9020
9211
  };
9021
9212
  const body = {
9022
9213
  activity_selectors: request?.activity_selectors,
9023
- activity_filter: request?.activity_filter,
9024
9214
  aggregation: request?.aggregation,
9025
9215
  ranking: request?.ranking,
9026
9216
  };
@@ -9034,7 +9224,6 @@ class FeedsApi {
9034
9224
  };
9035
9225
  const body = {
9036
9226
  activity_selectors: request?.activity_selectors,
9037
- activity_filter: request?.activity_filter,
9038
9227
  aggregation: request?.aggregation,
9039
9228
  ranking: request?.ranking,
9040
9229
  };
@@ -9079,6 +9268,7 @@ class FeedsApi {
9079
9268
  const body = {
9080
9269
  feeds: request?.feeds,
9081
9270
  hard_delete: request?.hard_delete,
9271
+ purge_user_activities: request?.purge_user_activities,
9082
9272
  };
9083
9273
  const response = await this.apiClient.sendRequest('POST', '/api/v2/feeds/feeds/delete', undefined, undefined, body, 'application/json');
9084
9274
  decoders.DeleteFeedsBatchResponse?.(response.body);
@@ -9271,6 +9461,18 @@ class FeedsApi {
9271
9461
  decoders.UpdateMembershipLevelResponse?.(response.body);
9272
9462
  return { ...response.body, metadata: response.metadata };
9273
9463
  }
9464
+ async queryRevisionHistory(request) {
9465
+ const body = {
9466
+ filter: request?.filter,
9467
+ limit: request?.limit,
9468
+ next: request?.next,
9469
+ prev: request?.prev,
9470
+ sort: request?.sort,
9471
+ };
9472
+ const response = await this.apiClient.sendRequest('POST', '/api/v2/feeds/revisions/query', undefined, undefined, body, 'application/json');
9473
+ decoders.QueryRevisionHistoryResponse?.(response.body);
9474
+ return { ...response.body, metadata: response.metadata };
9475
+ }
9274
9476
  async queryFeedsUsageStats(request) {
9275
9477
  const body = {
9276
9478
  from: request?.from,
@@ -9602,6 +9804,43 @@ class StreamClient extends CommonApi {
9602
9804
  return false;
9603
9805
  }
9604
9806
  };
9807
+ /**
9808
+ * Verify and parse an HTTP webhook event.
9809
+ *
9810
+ * Decompresses `rawBody` when gzipped (detected from the body bytes),
9811
+ * verifies the `X-Signature` header against the app's API secret, and
9812
+ * returns the parsed typed event. Works whether or not Stream is
9813
+ * currently compressing payloads for this app, and stays correct behind
9814
+ * middleware that auto-decompresses the request.
9815
+ *
9816
+ * @param rawBody Raw HTTP request body bytes Stream signed
9817
+ * @param signature Value of the `X-Signature` header
9818
+ * @throws {InvalidWebhookError} When the signature does not match or
9819
+ * the gzip / JSON envelope is malformed.
9820
+ */
9821
+ this.verifyAndParseWebhook = (rawBody, signature) => {
9822
+ if (!this.secret) {
9823
+ throw new InvalidWebhookError('cannot verify webhook signature without an API secret on the client');
9824
+ }
9825
+ return verifyAndParseWebhook(rawBody, signature, this.secret);
9826
+ };
9827
+ /**
9828
+ * Parse an SQS firehose event: decodes the message `Body` (base64 +
9829
+ * optional gzip) and returns the parsed typed event. No HMAC
9830
+ * verification (Stream does not sign SQS bodies).
9831
+ *
9832
+ * @param messageBody SQS message `Body` string
9833
+ * @throws {InvalidWebhookError} When the base64 / gzip envelope is malformed.
9834
+ */
9835
+ this.parseSqs = (messageBody) => parseSqs(messageBody);
9836
+ /**
9837
+ * Parse an SNS-delivered event (unwraps envelope JSON when needed, then
9838
+ * same decode path as SQS). No HMAC verification.
9839
+ *
9840
+ * @param notificationBody Raw SNS POST body or pre-extracted `Message` string
9841
+ * @throws {InvalidWebhookError} When the envelope cannot be decoded.
9842
+ */
9843
+ this.parseSns = (notificationBody) => parseSns(notificationBody);
9605
9844
  this.video = new StreamVideoClient({
9606
9845
  streamClient: this,
9607
9846
  apiClient: videoApiClient,
@@ -9722,5 +9961,5 @@ const OwnCapability = {
9722
9961
  UPDATE_CALL_SETTINGS: 'update-call-settings',
9723
9962
  };
9724
9963
 
9725
- export { ChannelOwnCapability, FeedOwnCapability, OwnCapability, StreamCall, StreamChannel, StreamChatClient, StreamClient, StreamFeed, StreamFeedsClient, StreamVideoClient };
9964
+ export { ChannelOwnCapability, FeedOwnCapability, InvalidWebhookError, InvalidWebhookErrorMessages, OwnCapability, StreamCall, StreamChannel, StreamChatClient, StreamClient, StreamFeed, StreamFeedsClient, StreamVideoClient };
9726
9965
  //# sourceMappingURL=index.es.mjs.map