@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.
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))
@@ -2078,6 +2257,18 @@ decoders.GetOrCreateFeedViewResponse = (input) => {
2078
2257
  };
2079
2258
  return decode(typeMappings, input);
2080
2259
  };
2260
+ decoders.GetOrCreateFollowResponse = (input) => {
2261
+ const typeMappings = {
2262
+ follow: { type: 'FollowResponse', isSingle: true },
2263
+ };
2264
+ return decode(typeMappings, input);
2265
+ };
2266
+ decoders.GetOrCreateUnfollowResponse = (input) => {
2267
+ const typeMappings = {
2268
+ follow: { type: 'FollowResponse', isSingle: true },
2269
+ };
2270
+ return decode(typeMappings, input);
2271
+ };
2081
2272
  decoders.GetPushTemplatesResponse = (input) => {
2082
2273
  const typeMappings = {
2083
2274
  templates: { type: 'PushTemplateResponse', isSingle: false },
@@ -7967,7 +8158,7 @@ class ApiClient {
7967
8158
  const headers = {
7968
8159
  Authorization: this.apiConfig.token,
7969
8160
  'stream-auth-type': 'jwt',
7970
- 'X-Stream-Client': 'stream-node-' + "0.7.56",
8161
+ 'X-Stream-Client': 'stream-node-' + "0.7.58",
7971
8162
  'Accept-Encoding': 'gzip',
7972
8163
  'x-client-request-id': clientRequestId,
7973
8164
  };
@@ -8752,6 +8943,7 @@ class FeedsApi {
8752
8943
  async deleteFeed(request) {
8753
8944
  const queryParams = {
8754
8945
  hard_delete: request?.hard_delete,
8946
+ purge_user_activities: request?.purge_user_activities,
8755
8947
  };
8756
8948
  const pathParams = {
8757
8949
  feed_group_id: request?.feed_group_id,
@@ -9107,6 +9299,7 @@ class FeedsApi {
9107
9299
  const body = {
9108
9300
  feeds: request?.feeds,
9109
9301
  hard_delete: request?.hard_delete,
9302
+ purge_user_activities: request?.purge_user_activities,
9110
9303
  };
9111
9304
  const response = await this.apiClient.sendRequest('POST', '/api/v2/feeds/feeds/delete', undefined, undefined, body, 'application/json');
9112
9305
  decoders.DeleteFeedsBatchResponse?.(response.body);
@@ -9237,6 +9430,24 @@ class FeedsApi {
9237
9430
  decoders.RejectFollowResponse?.(response.body);
9238
9431
  return { ...response.body, metadata: response.metadata };
9239
9432
  }
9433
+ async getOrCreateFollow(request) {
9434
+ const body = {
9435
+ source: request?.source,
9436
+ target: request?.target,
9437
+ activity_copy_limit: request?.activity_copy_limit,
9438
+ copy_custom_to_notification: request?.copy_custom_to_notification,
9439
+ create_notification_activity: request?.create_notification_activity,
9440
+ create_users: request?.create_users,
9441
+ enrich_own_fields: request?.enrich_own_fields,
9442
+ push_preference: request?.push_preference,
9443
+ skip_push: request?.skip_push,
9444
+ status: request?.status,
9445
+ custom: request?.custom,
9446
+ };
9447
+ const response = await this.apiClient.sendRequest('POST', '/api/v2/feeds/follows/upsert', undefined, undefined, body, 'application/json');
9448
+ decoders.GetOrCreateFollowResponse?.(response.body);
9449
+ return { ...response.body, metadata: response.metadata };
9450
+ }
9240
9451
  async unfollow(request) {
9241
9452
  const queryParams = {
9242
9453
  delete_notification_activity: request?.delete_notification_activity,
@@ -9340,6 +9551,18 @@ class FeedsApi {
9340
9551
  decoders.UnfollowBatchResponse?.(response.body);
9341
9552
  return { ...response.body, metadata: response.metadata };
9342
9553
  }
9554
+ async getOrCreateUnfollow(request) {
9555
+ const body = {
9556
+ source: request?.source,
9557
+ target: request?.target,
9558
+ delete_notification_activity: request?.delete_notification_activity,
9559
+ enrich_own_fields: request?.enrich_own_fields,
9560
+ keep_history: request?.keep_history,
9561
+ };
9562
+ const response = await this.apiClient.sendRequest('POST', '/api/v2/feeds/unfollow/upsert', undefined, undefined, body, 'application/json');
9563
+ decoders.GetOrCreateUnfollowResponse?.(response.body);
9564
+ return { ...response.body, metadata: response.metadata };
9565
+ }
9343
9566
  async deleteFeedUserData(request) {
9344
9567
  const pathParams = {
9345
9568
  user_id: request?.user_id,
@@ -9642,6 +9865,43 @@ class StreamClient extends CommonApi {
9642
9865
  return false;
9643
9866
  }
9644
9867
  };
9868
+ /**
9869
+ * Verify and parse an HTTP webhook event.
9870
+ *
9871
+ * Decompresses `rawBody` when gzipped (detected from the body bytes),
9872
+ * verifies the `X-Signature` header against the app's API secret, and
9873
+ * returns the parsed typed event. Works whether or not Stream is
9874
+ * currently compressing payloads for this app, and stays correct behind
9875
+ * middleware that auto-decompresses the request.
9876
+ *
9877
+ * @param rawBody Raw HTTP request body bytes Stream signed
9878
+ * @param signature Value of the `X-Signature` header
9879
+ * @throws {InvalidWebhookError} When the signature does not match or
9880
+ * the gzip / JSON envelope is malformed.
9881
+ */
9882
+ this.verifyAndParseWebhook = (rawBody, signature) => {
9883
+ if (!this.secret) {
9884
+ throw new InvalidWebhookError('cannot verify webhook signature without an API secret on the client');
9885
+ }
9886
+ return verifyAndParseWebhook(rawBody, signature, this.secret);
9887
+ };
9888
+ /**
9889
+ * Parse an SQS firehose event: decodes the message `Body` (base64 +
9890
+ * optional gzip) and returns the parsed typed event. No HMAC
9891
+ * verification (Stream does not sign SQS bodies).
9892
+ *
9893
+ * @param messageBody SQS message `Body` string
9894
+ * @throws {InvalidWebhookError} When the base64 / gzip envelope is malformed.
9895
+ */
9896
+ this.parseSqs = (messageBody) => parseSqs(messageBody);
9897
+ /**
9898
+ * Parse an SNS-delivered event (unwraps envelope JSON when needed, then
9899
+ * same decode path as SQS). No HMAC verification.
9900
+ *
9901
+ * @param notificationBody Raw SNS POST body or pre-extracted `Message` string
9902
+ * @throws {InvalidWebhookError} When the envelope cannot be decoded.
9903
+ */
9904
+ this.parseSns = (notificationBody) => parseSns(notificationBody);
9645
9905
  this.video = new StreamVideoClient({
9646
9906
  streamClient: this,
9647
9907
  apiClient: videoApiClient,
@@ -9764,6 +10024,8 @@ const OwnCapability = {
9764
10024
 
9765
10025
  exports.ChannelOwnCapability = ChannelOwnCapability;
9766
10026
  exports.FeedOwnCapability = FeedOwnCapability;
10027
+ exports.InvalidWebhookError = InvalidWebhookError;
10028
+ exports.InvalidWebhookErrorMessages = InvalidWebhookErrorMessages;
9767
10029
  exports.OwnCapability = OwnCapability;
9768
10030
  exports.StreamCall = StreamCall;
9769
10031
  exports.StreamChannel = StreamChannel;