-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwebhook.go
More file actions
889 lines (861 loc) · 36.8 KB
/
Copy pathwebhook.go
File metadata and controls
889 lines (861 loc) · 36.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
// Code generated by GetStream internal OpenAPI code generator. DO NOT EDIT.
package getstream
import (
"bytes"
"compress/gzip"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
// WebhookEvent is implemented by all webhook event types.
type WebhookEvent interface {
GetEventType() string
}
// Webhook event type constants
const (
EventTypeWildcard = "*"
EventTypeAppealAccepted = "appeal.accepted"
EventTypeAppealCreated = "appeal.created"
EventTypeAppealRejected = "appeal.rejected"
EventTypeCallAccepted = "call.accepted"
EventTypeCallBlockedUser = "call.blocked_user"
EventTypeCallClosedCaption = "call.closed_caption"
EventTypeCallClosedCaptionsFailed = "call.closed_captions_failed"
EventTypeCallClosedCaptionsStarted = "call.closed_captions_started"
EventTypeCallClosedCaptionsStopped = "call.closed_captions_stopped"
EventTypeCallCreated = "call.created"
EventTypeCallDeleted = "call.deleted"
EventTypeCallDtmf = "call.dtmf"
EventTypeCallEnded = "call.ended"
EventTypeCallFrameRecordingFailed = "call.frame_recording_failed"
EventTypeCallFrameRecordingReady = "call.frame_recording_ready"
EventTypeCallFrameRecordingStarted = "call.frame_recording_started"
EventTypeCallFrameRecordingStopped = "call.frame_recording_stopped"
EventTypeCallHLSBroadcastingFailed = "call.hls_broadcasting_failed"
EventTypeCallHLSBroadcastingStarted = "call.hls_broadcasting_started"
EventTypeCallHLSBroadcastingStopped = "call.hls_broadcasting_stopped"
EventTypeCallKickedUser = "call.kicked_user"
EventTypeCallLiveStarted = "call.live_started"
EventTypeCallMemberAdded = "call.member_added"
EventTypeCallMemberRemoved = "call.member_removed"
EventTypeCallMemberUpdated = "call.member_updated"
EventTypeCallMemberUpdatedPermission = "call.member_updated_permission"
EventTypeCallMissed = "call.missed"
EventTypeCallModerationBlur = "call.moderation_blur"
EventTypeCallModerationWarning = "call.moderation_warning"
EventTypeCallNotification = "call.notification"
EventTypeCallPermissionRequest = "call.permission_request"
EventTypeCallPermissionsUpdated = "call.permissions_updated"
EventTypeCallReactionNew = "call.reaction_new"
EventTypeCallRecordingFailed = "call.recording_failed"
EventTypeCallRecordingReady = "call.recording_ready"
EventTypeCallRecordingStarted = "call.recording_started"
EventTypeCallRecordingStopped = "call.recording_stopped"
EventTypeCallRejected = "call.rejected"
EventTypeCallRing = "call.ring"
EventTypeCallRTMPBroadcastFailed = "call.rtmp_broadcast_failed"
EventTypeCallRTMPBroadcastStarted = "call.rtmp_broadcast_started"
EventTypeCallRTMPBroadcastStopped = "call.rtmp_broadcast_stopped"
EventTypeCallSessionEnded = "call.session_ended"
EventTypeCallSessionParticipantCountUpdated = "call.session_participant_count_updated"
EventTypeCallSessionParticipantJoined = "call.session_participant_joined"
EventTypeCallSessionParticipantLeft = "call.session_participant_left"
EventTypeCallSessionStarted = "call.session_started"
EventTypeCallStatsReportReady = "call.stats_report_ready"
EventTypeCallTranscriptionFailed = "call.transcription_failed"
EventTypeCallTranscriptionReady = "call.transcription_ready"
EventTypeCallTranscriptionStarted = "call.transcription_started"
EventTypeCallTranscriptionStopped = "call.transcription_stopped"
EventTypeCallUnblockedUser = "call.unblocked_user"
EventTypeCallUpdated = "call.updated"
EventTypeCallUserFeedbackSubmitted = "call.user_feedback_submitted"
EventTypeCallUserMuted = "call.user_muted"
EventTypeCampaignCompleted = "campaign.completed"
EventTypeCampaignStarted = "campaign.started"
EventTypeChannelCreated = "channel.created"
EventTypeChannelDeleted = "channel.deleted"
EventTypeChannelFrozen = "channel.frozen"
EventTypeChannelHidden = "channel.hidden"
EventTypeChannelMaxStreakChanged = "channel.max_streak_changed"
EventTypeChannelMuted = "channel.muted"
EventTypeChannelTruncated = "channel.truncated"
EventTypeChannelUnfrozen = "channel.unfrozen"
EventTypeChannelUnmuted = "channel.unmuted"
EventTypeChannelUpdated = "channel.updated"
EventTypeChannelVisible = "channel.visible"
EventTypeChannelBatchUpdateCompleted = "channel_batch_update.completed"
EventTypeChannelBatchUpdateStarted = "channel_batch_update.started"
EventTypeCustom = "custom"
EventTypeExportBulkImageModerationError = "export.bulk_image_moderation.error"
EventTypeExportBulkImageModerationSuccess = "export.bulk_image_moderation.success"
EventTypeExportChannelsError = "export.channels.error"
EventTypeExportChannelsSuccess = "export.channels.success"
EventTypeExportModerationLogsError = "export.moderation_logs.error"
EventTypeExportModerationLogsSuccess = "export.moderation_logs.success"
EventTypeExportReviewQueueError = "export.review_queue.error"
EventTypeExportReviewQueueSuccess = "export.review_queue.success"
EventTypeExportUsersError = "export.users.error"
EventTypeExportUsersSuccess = "export.users.success"
EventTypeFeedsActivityAdded = "feeds.activity.added"
EventTypeFeedsActivityDeleted = "feeds.activity.deleted"
EventTypeFeedsActivityFeedback = "feeds.activity.feedback"
EventTypeFeedsActivityMarked = "feeds.activity.marked"
EventTypeFeedsActivityPinned = "feeds.activity.pinned"
EventTypeFeedsActivityReactionAdded = "feeds.activity.reaction.added"
EventTypeFeedsActivityReactionDeleted = "feeds.activity.reaction.deleted"
EventTypeFeedsActivityReactionUpdated = "feeds.activity.reaction.updated"
EventTypeFeedsActivityRemovedFromFeed = "feeds.activity.removed_from_feed"
EventTypeFeedsActivityRestored = "feeds.activity.restored"
EventTypeFeedsActivityUnpinned = "feeds.activity.unpinned"
EventTypeFeedsActivityUpdated = "feeds.activity.updated"
EventTypeFeedsBookmarkAdded = "feeds.bookmark.added"
EventTypeFeedsBookmarkDeleted = "feeds.bookmark.deleted"
EventTypeFeedsBookmarkUpdated = "feeds.bookmark.updated"
EventTypeFeedsBookmarkFolderDeleted = "feeds.bookmark_folder.deleted"
EventTypeFeedsBookmarkFolderUpdated = "feeds.bookmark_folder.updated"
EventTypeFeedsCommentAdded = "feeds.comment.added"
EventTypeFeedsCommentDeleted = "feeds.comment.deleted"
EventTypeFeedsCommentReactionAdded = "feeds.comment.reaction.added"
EventTypeFeedsCommentReactionDeleted = "feeds.comment.reaction.deleted"
EventTypeFeedsCommentReactionUpdated = "feeds.comment.reaction.updated"
EventTypeFeedsCommentRestored = "feeds.comment.restored"
EventTypeFeedsCommentUpdated = "feeds.comment.updated"
EventTypeFeedsFeedCreated = "feeds.feed.created"
EventTypeFeedsFeedDeleted = "feeds.feed.deleted"
EventTypeFeedsFeedUpdated = "feeds.feed.updated"
EventTypeFeedsFeedGroupChanged = "feeds.feed_group.changed"
EventTypeFeedsFeedGroupDeleted = "feeds.feed_group.deleted"
EventTypeFeedsFeedGroupRestored = "feeds.feed_group.restored"
EventTypeFeedsFeedMemberAdded = "feeds.feed_member.added"
EventTypeFeedsFeedMemberRemoved = "feeds.feed_member.removed"
EventTypeFeedsFeedMemberUpdated = "feeds.feed_member.updated"
EventTypeFeedsFollowCreated = "feeds.follow.created"
EventTypeFeedsFollowDeleted = "feeds.follow.deleted"
EventTypeFeedsFollowUpdated = "feeds.follow.updated"
EventTypeFeedsNotificationFeedUpdated = "feeds.notification_feed.updated"
EventTypeFeedsStoriesFeedUpdated = "feeds.stories_feed.updated"
EventTypeFlagUpdated = "flag.updated"
EventTypeIngressError = "ingress.error"
EventTypeIngressStarted = "ingress.started"
EventTypeIngressStopped = "ingress.stopped"
EventTypeMemberAdded = "member.added"
EventTypeMemberRemoved = "member.removed"
EventTypeMemberUpdated = "member.updated"
EventTypeMessageDeleted = "message.deleted"
EventTypeMessageFlagged = "message.flagged"
EventTypeMessageNew = "message.new"
EventTypeMessagePending = "message.pending"
EventTypeMessageRead = "message.read"
EventTypeMessageUnblocked = "message.unblocked"
EventTypeMessageUndeleted = "message.undeleted"
EventTypeMessageUpdated = "message.updated"
EventTypeModerationCustomAction = "moderation.custom_action"
EventTypeModerationFlagged = "moderation.flagged"
EventTypeModerationImageAnalysisComplete = "moderation.image_analysis.complete"
EventTypeModerationMarkReviewed = "moderation.mark_reviewed"
EventTypeModerationTextAnalysisComplete = "moderation.text_analysis.complete"
EventTypeModerationCheckCompleted = "moderation_check.completed"
EventTypeModerationRuleTriggered = "moderation_rule.triggered"
EventTypeNotificationMarkUnread = "notification.mark_unread"
EventTypeNotificationReminderDue = "notification.reminder_due"
EventTypeNotificationThreadMessageNew = "notification.thread_message_new"
EventTypeReactionDeleted = "reaction.deleted"
EventTypeReactionNew = "reaction.new"
EventTypeReactionUpdated = "reaction.updated"
EventTypeReminderCreated = "reminder.created"
EventTypeReminderDeleted = "reminder.deleted"
EventTypeReminderUpdated = "reminder.updated"
EventTypeReviewQueueItemNew = "review_queue_item.new"
EventTypeReviewQueueItemUpdated = "review_queue_item.updated"
EventTypeThreadUpdated = "thread.updated"
EventTypeUserBanned = "user.banned"
EventTypeUserDeactivated = "user.deactivated"
EventTypeUserDeleted = "user.deleted"
EventTypeUserFlagged = "user.flagged"
EventTypeUserMessagesDeleted = "user.messages.deleted"
EventTypeUserMuted = "user.muted"
EventTypeUserReactivated = "user.reactivated"
EventTypeUserUnbanned = "user.unbanned"
EventTypeUserUnmuted = "user.unmuted"
EventTypeUserUnreadMessageReminder = "user.unread_message_reminder"
EventTypeUserUpdated = "user.updated"
EventTypeUserGroupCreated = "user_group.created"
EventTypeUserGroupDeleted = "user_group.deleted"
EventTypeUserGroupMemberAdded = "user_group.member_added"
EventTypeUserGroupMemberRemoved = "user_group.member_removed"
EventTypeUserGroupUpdated = "user_group.updated"
)
// UnknownEvent is returned by ParseEvent when the type discriminator is well-formed
// but unknown to this SDK version. Forward-compat surface for new event types.
//
// To handle unknown events, switch on the returned event's concrete type and
// include *UnknownEvent in your default case.
type UnknownEvent struct {
Type string `json:"type"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
Raw map[string]any `json:"-"`
}
// GetEventType returns the unrecognized discriminator value.
func (u *UnknownEvent) GetEventType() string { return u.Type }
// ErrInvalidWebhook is the sentinel for every webhook handling failure.
// Use errors.Is(err, ErrInvalidWebhook). The wrapped message (err.Error())
// identifies the failure mode: "signature mismatch", "invalid base64 encoding",
// "gzip decompression failed", or "invalid JSON payload".
var ErrInvalidWebhook = errors.New("stream: invalid webhook")
// ErrUnknownEventType is returned by ParseWebhookEvent when the type discriminator
// is well-formed but not in the codegen-known set. ParseEvent uses this signal to
// route to UnknownEvent.
var ErrUnknownEventType = errors.New("stream: unknown webhook event type")
// gzipMagic is the two-byte gzip magic prefix (RFC 1952 §2.3.1).
// JSON cannot start with these bytes, so this gives unambiguous detection
// for Stream's always-JSON payloads.
var gzipMagic = []byte{0x1F, 0x8B}
// GetEventType extracts the event type from a raw webhook payload.
// This is useful for routing webhooks before full deserialization.
//
// Example:
//
// eventType := getstream.GetEventType(body)
// switch eventType {
// case "message.new":
// // handle message.new
// }
func GetEventType(rawEvent []byte) string {
var result struct {
Type string `json:"type"`
}
if err := json.Unmarshal(rawEvent, &result); err != nil {
return ""
}
return result.Type
}
// ParseWebhookEvent deserializes a raw webhook payload into a typed event.
// It uses the "type" field to determine which event struct to deserialize into.
//
// Returns WebhookEvent - the concrete event type (e.g., *MessageNewEvent, *ChannelCreatedEvent).
// All webhook events implement the WebhookEvent interface with a GetEventType() method.
//
// Returns an error if the event type is unknown or if deserialization fails.
//
// Example usage:
//
// func webhookHandler(w http.ResponseWriter, r *http.Request) {
// body, _ := io.ReadAll(r.Body)
// signature := r.Header.Get("X-Signature")
// secret := os.Getenv("STREAM_WEBHOOK_SECRET")
//
// if !getstream.VerifyWebhookSignature(body, signature, secret) {
// http.Error(w, "Invalid signature", http.StatusForbidden)
// return
// }
//
// event, err := getstream.ParseWebhookEvent(body)
// if err != nil {
// http.Error(w, err.Error(), http.StatusBadRequest)
// return
// }
//
// switch e := event.(type) {
// case *getstream.MessageNewEvent:
// fmt.Printf("New message: %s\n", e.Message.Text)
// case *getstream.ChannelCreatedEvent:
// fmt.Printf("Channel created: %s\n", e.Channel.Cid)
// default:
// fmt.Printf("Unknown event type: %s\n", e.GetEventType())
// }
// w.WriteHeader(200)
// }
func ParseWebhookEvent(rawEvent []byte) (WebhookEvent, error) {
eventType := GetEventType(rawEvent)
if eventType == "" {
return nil, fmt.Errorf("missing 'type' field in webhook payload")
}
var event WebhookEvent
switch eventType {
case "*":
event = new(CustomEvent)
case "appeal.accepted":
event = new(AppealAcceptedEvent)
case "appeal.created":
event = new(AppealCreatedEvent)
case "appeal.rejected":
event = new(AppealRejectedEvent)
case "call.accepted":
event = new(CallAcceptedEvent)
case "call.blocked_user":
event = new(BlockedUserEvent)
case "call.closed_caption":
event = new(ClosedCaptionEvent)
case "call.closed_captions_failed":
event = new(CallClosedCaptionsFailedEvent)
case "call.closed_captions_started":
event = new(CallClosedCaptionsStartedEvent)
case "call.closed_captions_stopped":
event = new(CallClosedCaptionsStoppedEvent)
case "call.created":
event = new(CallCreatedEvent)
case "call.deleted":
event = new(CallDeletedEvent)
case "call.dtmf":
event = new(CallDTMFEvent)
case "call.ended":
event = new(CallEndedEvent)
case "call.frame_recording_failed":
event = new(CallFrameRecordingFailedEvent)
case "call.frame_recording_ready":
event = new(CallFrameRecordingFrameReadyEvent)
case "call.frame_recording_started":
event = new(CallFrameRecordingStartedEvent)
case "call.frame_recording_stopped":
event = new(CallFrameRecordingStoppedEvent)
case "call.hls_broadcasting_failed":
event = new(CallHLSBroadcastingFailedEvent)
case "call.hls_broadcasting_started":
event = new(CallHLSBroadcastingStartedEvent)
case "call.hls_broadcasting_stopped":
event = new(CallHLSBroadcastingStoppedEvent)
case "call.kicked_user":
event = new(KickedUserEvent)
case "call.live_started":
event = new(CallLiveStartedEvent)
case "call.member_added":
event = new(CallMemberAddedEvent)
case "call.member_removed":
event = new(CallMemberRemovedEvent)
case "call.member_updated":
event = new(CallMemberUpdatedEvent)
case "call.member_updated_permission":
event = new(CallMemberUpdatedPermissionEvent)
case "call.missed":
event = new(CallMissedEvent)
case "call.moderation_blur":
event = new(CallModerationBlurEvent)
case "call.moderation_warning":
event = new(CallModerationWarningEvent)
case "call.notification":
event = new(CallNotificationEvent)
case "call.permission_request":
event = new(PermissionRequestEvent)
case "call.permissions_updated":
event = new(UpdatedCallPermissionsEvent)
case "call.reaction_new":
event = new(CallReactionEvent)
case "call.recording_failed":
event = new(CallRecordingFailedEvent)
case "call.recording_ready":
event = new(CallRecordingReadyEvent)
case "call.recording_started":
event = new(CallRecordingStartedEvent)
case "call.recording_stopped":
event = new(CallRecordingStoppedEvent)
case "call.rejected":
event = new(CallRejectedEvent)
case "call.ring":
event = new(CallRingEvent)
case "call.rtmp_broadcast_failed":
event = new(CallRtmpBroadcastFailedEvent)
case "call.rtmp_broadcast_started":
event = new(CallRtmpBroadcastStartedEvent)
case "call.rtmp_broadcast_stopped":
event = new(CallRtmpBroadcastStoppedEvent)
case "call.session_ended":
event = new(CallSessionEndedEvent)
case "call.session_participant_count_updated":
event = new(CallSessionParticipantCountsUpdatedEvent)
case "call.session_participant_joined":
event = new(CallSessionParticipantJoinedEvent)
case "call.session_participant_left":
event = new(CallSessionParticipantLeftEvent)
case "call.session_started":
event = new(CallSessionStartedEvent)
case "call.stats_report_ready":
event = new(CallStatsReportReadyEvent)
case "call.transcription_failed":
event = new(CallTranscriptionFailedEvent)
case "call.transcription_ready":
event = new(CallTranscriptionReadyEvent)
case "call.transcription_started":
event = new(CallTranscriptionStartedEvent)
case "call.transcription_stopped":
event = new(CallTranscriptionStoppedEvent)
case "call.unblocked_user":
event = new(UnblockedUserEvent)
case "call.updated":
event = new(CallUpdatedEvent)
case "call.user_feedback_submitted":
event = new(CallUserFeedbackSubmittedEvent)
case "call.user_muted":
event = new(CallUserMutedEvent)
case "campaign.completed":
event = new(CampaignCompletedEvent)
case "campaign.started":
event = new(CampaignStartedEvent)
case "channel.created":
event = new(ChannelCreatedEvent)
case "channel.deleted":
event = new(ChannelDeletedEvent)
case "channel.frozen":
event = new(ChannelFrozenEvent)
case "channel.hidden":
event = new(ChannelHiddenEvent)
case "channel.max_streak_changed":
event = new(MaxStreakChangedEvent)
case "channel.muted":
event = new(ChannelMutedEvent)
case "channel.truncated":
event = new(ChannelTruncatedEvent)
case "channel.unfrozen":
event = new(ChannelUnFrozenEvent)
case "channel.unmuted":
event = new(ChannelUnmutedEvent)
case "channel.updated":
event = new(ChannelUpdatedEvent)
case "channel.visible":
event = new(ChannelVisibleEvent)
case "channel_batch_update.completed":
event = new(ChannelBatchCompletedEvent)
case "channel_batch_update.started":
event = new(ChannelBatchStartedEvent)
case "custom":
event = new(CustomVideoEvent)
case "export.bulk_image_moderation.error":
event = new(AsyncExportErrorEvent)
case "export.bulk_image_moderation.success":
event = new(AsyncBulkImageModerationEvent)
case "export.channels.error":
event = new(AsyncExportErrorEvent)
case "export.channels.success":
event = new(AsyncExportChannelsEvent)
case "export.moderation_logs.error":
event = new(AsyncExportErrorEvent)
case "export.moderation_logs.success":
event = new(AsyncExportModerationLogsEvent)
case "export.review_queue.error":
event = new(AsyncExportErrorEvent)
case "export.review_queue.success":
event = new(AsyncExportReviewQueueEvent)
case "export.users.error":
event = new(AsyncExportErrorEvent)
case "export.users.success":
event = new(AsyncExportUsersEvent)
case "feeds.activity.added":
event = new(ActivityAddedEvent)
case "feeds.activity.deleted":
event = new(ActivityDeletedEvent)
case "feeds.activity.feedback":
event = new(ActivityFeedbackEvent)
case "feeds.activity.marked":
event = new(ActivityMarkEvent)
case "feeds.activity.pinned":
event = new(ActivityPinnedEvent)
case "feeds.activity.reaction.added":
event = new(ActivityReactionAddedEvent)
case "feeds.activity.reaction.deleted":
event = new(ActivityReactionDeletedEvent)
case "feeds.activity.reaction.updated":
event = new(ActivityReactionUpdatedEvent)
case "feeds.activity.removed_from_feed":
event = new(ActivityRemovedFromFeedEvent)
case "feeds.activity.restored":
event = new(ActivityRestoredEvent)
case "feeds.activity.unpinned":
event = new(ActivityUnpinnedEvent)
case "feeds.activity.updated":
event = new(ActivityUpdatedEvent)
case "feeds.bookmark.added":
event = new(BookmarkAddedEvent)
case "feeds.bookmark.deleted":
event = new(BookmarkDeletedEvent)
case "feeds.bookmark.updated":
event = new(BookmarkUpdatedEvent)
case "feeds.bookmark_folder.deleted":
event = new(BookmarkFolderDeletedEvent)
case "feeds.bookmark_folder.updated":
event = new(BookmarkFolderUpdatedEvent)
case "feeds.comment.added":
event = new(CommentAddedEvent)
case "feeds.comment.deleted":
event = new(CommentDeletedEvent)
case "feeds.comment.reaction.added":
event = new(CommentReactionAddedEvent)
case "feeds.comment.reaction.deleted":
event = new(CommentReactionDeletedEvent)
case "feeds.comment.reaction.updated":
event = new(CommentReactionUpdatedEvent)
case "feeds.comment.restored":
event = new(CommentRestoredEvent)
case "feeds.comment.updated":
event = new(CommentUpdatedEvent)
case "feeds.feed.created":
event = new(FeedCreatedEvent)
case "feeds.feed.deleted":
event = new(FeedDeletedEvent)
case "feeds.feed.updated":
event = new(FeedUpdatedEvent)
case "feeds.feed_group.changed":
event = new(FeedGroupChangedEvent)
case "feeds.feed_group.deleted":
event = new(FeedGroupDeletedEvent)
case "feeds.feed_group.restored":
event = new(FeedGroupRestoredEvent)
case "feeds.feed_member.added":
event = new(FeedMemberAddedEvent)
case "feeds.feed_member.removed":
event = new(FeedMemberRemovedEvent)
case "feeds.feed_member.updated":
event = new(FeedMemberUpdatedEvent)
case "feeds.follow.created":
event = new(FollowCreatedEvent)
case "feeds.follow.deleted":
event = new(FollowDeletedEvent)
case "feeds.follow.updated":
event = new(FollowUpdatedEvent)
case "feeds.notification_feed.updated":
event = new(NotificationFeedUpdatedEvent)
case "feeds.stories_feed.updated":
event = new(StoriesFeedUpdatedEvent)
case "flag.updated":
event = new(FlagUpdatedEvent)
case "ingress.error":
event = new(IngressErrorEvent)
case "ingress.started":
event = new(IngressStartedEvent)
case "ingress.stopped":
event = new(IngressStoppedEvent)
case "member.added":
event = new(MemberAddedEvent)
case "member.removed":
event = new(MemberRemovedEvent)
case "member.updated":
event = new(MemberUpdatedEvent)
case "message.deleted":
event = new(MessageDeletedEvent)
case "message.flagged":
event = new(MessageFlaggedEvent)
case "message.new":
event = new(MessageNewEvent)
case "message.pending":
event = new(PendingMessageEvent)
case "message.read":
event = new(MessageReadEvent)
case "message.unblocked":
event = new(MessageUnblockedEvent)
case "message.undeleted":
event = new(MessageUndeletedEvent)
case "message.updated":
event = new(MessageUpdatedEvent)
case "moderation.custom_action":
event = new(ModerationCustomActionEvent)
case "moderation.flagged":
event = new(ModerationFlaggedEvent)
case "moderation.image_analysis.complete":
event = new(ModerationImageAnalysisCompleteEvent)
case "moderation.mark_reviewed":
event = new(ModerationMarkReviewedEvent)
case "moderation.text_analysis.complete":
event = new(ModerationTextAnalysisCompleteEvent)
case "moderation_check.completed":
event = new(ModerationCheckCompletedEvent)
case "moderation_rule.triggered":
event = new(ModerationRulesTriggeredEvent)
case "notification.mark_unread":
event = new(NotificationMarkUnreadEvent)
case "notification.reminder_due":
event = new(ReminderNotificationEvent)
case "notification.thread_message_new":
event = new(NotificationThreadMessageNewEvent)
case "reaction.deleted":
event = new(ReactionDeletedEvent)
case "reaction.new":
event = new(ReactionNewEvent)
case "reaction.updated":
event = new(ReactionUpdatedEvent)
case "reminder.created":
event = new(ReminderCreatedEvent)
case "reminder.deleted":
event = new(ReminderDeletedEvent)
case "reminder.updated":
event = new(ReminderUpdatedEvent)
case "review_queue_item.new":
event = new(ReviewQueueItemNewEvent)
case "review_queue_item.updated":
event = new(ReviewQueueItemUpdatedEvent)
case "thread.updated":
event = new(ThreadUpdatedEvent)
case "user.banned":
event = new(UserBannedEvent)
case "user.deactivated":
event = new(UserDeactivatedEvent)
case "user.deleted":
event = new(UserDeletedEvent)
case "user.flagged":
event = new(UserFlaggedEvent)
case "user.messages.deleted":
event = new(UserMessagesDeletedEvent)
case "user.muted":
event = new(UserMutedEvent)
case "user.reactivated":
event = new(UserReactivatedEvent)
case "user.unbanned":
event = new(UserUnbannedEvent)
case "user.unmuted":
event = new(UserUnmutedEvent)
case "user.unread_message_reminder":
event = new(UserUnreadReminderEvent)
case "user.updated":
event = new(UserUpdatedEvent)
case "user_group.created":
event = new(UserGroupCreatedEvent)
case "user_group.deleted":
event = new(UserGroupDeletedEvent)
case "user_group.member_added":
event = new(UserGroupMemberAddedEvent)
case "user_group.member_removed":
event = new(UserGroupMemberRemovedEvent)
case "user_group.updated":
event = new(UserGroupUpdatedEvent)
default:
return nil, fmt.Errorf("%w: %s", ErrUnknownEventType, eventType)
}
if err := json.Unmarshal(rawEvent, event); err != nil {
return nil, fmt.Errorf("failed to unmarshal webhook event: %w", err)
}
return event, nil
}
// VerifyWebhookSignature verifies the HMAC-SHA256 signature of a webhook payload.
// This function should be used to verify that webhook requests are authentically from Stream.
//
// Parameters:
// - body: The raw request body bytes
// - signature: The signature from the X-Signature header
// - secret: Your webhook secret (found in the Stream Dashboard)
//
// Returns true if the signature is valid, false otherwise.
//
// Example usage:
//
// func webhookHandler(w http.ResponseWriter, r *http.Request) {
// body, _ := io.ReadAll(r.Body)
// signature := r.Header.Get("X-Signature")
// secret := os.Getenv("STREAM_WEBHOOK_SECRET")
//
// if !getstream.VerifyWebhookSignature(body, signature, secret) {
// http.Error(w, "Invalid signature", http.StatusForbidden)
// return
// }
// // Process webhook...
// }
func VerifyWebhookSignature(body []byte, signature string, secret string) bool {
h := hmac.New(sha256.New, []byte(secret))
h.Write(body)
expected := hex.EncodeToString(h.Sum(nil))
return hmac.Equal([]byte(signature), []byte(expected))
}
// VerifySignature is the canonical name for HMAC-SHA256 signature verification.
// It aliases the existing VerifyWebhookSignature for backward compatibility.
//
// Prefer this name in new code.
func VerifySignature(body []byte, signature, secret string) bool {
return VerifyWebhookSignature(body, signature, secret)
}
// GunzipPayload decompresses body if gzip-prefixed, else returns body as-is.
//
// Detection is by the first two bytes (0x1F 0x8B). This is reliable because
// Stream webhook bodies are always JSON, and JSON's first byte is always
// '{', '[', '"', a digit, '-', or one of t/f/n/whitespace; never 0x1F.
//
// Returns ErrInvalidWebhook (wrapped) if body has the gzip magic prefix
// but isn't a valid gzip stream.
func GunzipPayload(body []byte) ([]byte, error) {
if len(body) < 2 || !bytes.Equal(body[:2], gzipMagic) {
return body, nil
}
r, err := gzip.NewReader(bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("%w: gzip decompression failed: %v", ErrInvalidWebhook, err)
}
defer r.Close()
out, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("%w: gzip decompression failed: %v", ErrInvalidWebhook, err)
}
return out, nil
}
// DecodeSqsPayload decodes the SQS Message Body: try base64 first, fall back
// to raw bytes if base64 fails, then gunzip if gzip-prefixed.
//
// Wire format (per CHA-3071): SQS bodies are raw JSON when
// enable_hook_payload_compression is off (today's default for all existing
// apps), and base64(gzip(json)) when it's on. This helper handles both:
// raw JSON starts with '{' which is not valid base64, so the base64 decode
// fails and we fall through to raw bytes, then GunzipPayload's magic-byte
// detection decides whether to decompress.
//
// ParseSqs sits on top of this and works transparently for both wire formats:
// no caller code change, no flag, no header.
func DecodeSqsPayload(messageBody string) ([]byte, error) {
decoded, err := base64.StdEncoding.DecodeString(messageBody)
if err != nil {
// Not base64, so treat input as raw bytes (uncompressed wire format).
decoded = []byte(messageBody)
}
return GunzipPayload(decoded)
}
// unwrapSNSNotificationBody returns the inner Message field when body is a
// standard SNS notification envelope JSON; otherwise returns body unchanged so
// a pre-extracted Message string flows through.
//
// Heuristic: try to JSON-parse the input. If it yields an object with a string
// Message field, that's the envelope shape; return the Message. Otherwise the
// input is presumed to BE the pre-extracted Message (base64-encoded bytes are
// not valid JSON, so this falls through cleanly).
func unwrapSNSNotificationBody(body string) string {
var env struct{ Message string }
if err := json.Unmarshal([]byte(body), &env); err != nil {
return body
}
if env.Message == "" {
return body
}
return env.Message
}
// DecodeSnsPayload accepts either a full SNS HTTP notification envelope JSON
// ({"Type":"Notification","Message":"<base64>",...}) or a pre-extracted Message
// string (forwarded-through-SQS path). It then base64-decodes and gunzips the
// inner payload.
func DecodeSnsPayload(notificationBody string) ([]byte, error) {
return DecodeSqsPayload(unwrapSNSNotificationBody(notificationBody))
}
// ParseEvent parses a webhook payload and returns the typed event for known
// discriminators or *UnknownEvent for well-formed-but-unknown ones.
//
// Returns an error wrapping ErrInvalidWebhook for invalid JSON, missing/non-string
// type field, or any deserialization failure on a known type. The wrapped
// message identifies the failure mode (e.g., "invalid JSON payload").
//
// Distinct from ParseWebhookEvent: ParseEvent returns *UnknownEvent on unknown
// discriminators (forward-compat); ParseWebhookEvent returns an error.
func ParseEvent(payload []byte) (WebhookEvent, error) {
if len(payload) == 0 {
return nil, fmt.Errorf("%w: invalid JSON payload: empty body", ErrInvalidWebhook)
}
var probe struct {
Type string `json:"type"`
CreatedAt *Timestamp `json:"created_at"`
Raw json.RawMessage `json:"-"`
}
if err := json.Unmarshal(payload, &probe); err != nil {
return nil, fmt.Errorf("%w: invalid JSON payload: %v", ErrInvalidWebhook, err)
}
if probe.Type == "" {
return nil, fmt.Errorf("%w: invalid JSON payload: missing 'type' field", ErrInvalidWebhook)
}
event, err := ParseWebhookEvent(payload)
if err == nil {
return event, nil
}
// ParseWebhookEvent returns ErrUnknownEventType for unrecognized discriminators.
// Treat that case as UnknownEvent; everything else stays an invalid-webhook error.
if !errors.Is(err, ErrUnknownEventType) {
return nil, fmt.Errorf("%w: invalid JSON payload: %v", ErrInvalidWebhook, err)
}
var raw map[string]any
_ = json.Unmarshal(payload, &raw)
return &UnknownEvent{Type: probe.Type, CreatedAt: probe.CreatedAt, Raw: raw}, nil
}
// VerifyAndParseWebhookBytes is the spec-canonical HTTP composite. It takes
// the raw HTTP body (which may be gzip-compressed), the X-Signature header
// value, and the webhook secret. Steps: gunzip if gzip-prefixed → verify
// HMAC-SHA256 over the uncompressed bytes → parse into a typed event.
//
// Returns an error wrapping ErrInvalidWebhook for every failure mode. The
// wrapped message identifies which mode fired ("signature mismatch",
// "invalid base64 encoding", "gzip decompression failed", or "invalid JSON
// payload"). Callers that want a single arm use errors.Is(err, ErrInvalidWebhook);
// callers that need to differentiate (security logging, retry policy) filter
// on err.Error().
//
// Example:
//
// func webhookHandler(w http.ResponseWriter, r *http.Request) {
// body, _ := io.ReadAll(r.Body)
// sig := r.Header.Get("X-Signature")
// event, err := getstream.VerifyAndParseWebhookBytes(body, sig, secret)
// if err != nil {
// http.Error(w, err.Error(), http.StatusBadRequest)
// return
// }
// // Handle event...
// w.WriteHeader(http.StatusOK)
// }
func VerifyAndParseWebhookBytes(body []byte, signature, secret string) (WebhookEvent, error) {
payload, err := GunzipPayload(body)
if err != nil {
return nil, err
}
if !VerifySignature(payload, signature, secret) {
return nil, fmt.Errorf("%w: signature mismatch", ErrInvalidWebhook)
}
return ParseEvent(payload)
}
// VerifyAndParseWebhook reads the request body and the X-Signature header,
// then delegates to VerifyAndParseWebhookBytes. The request body is restored
// so downstream handlers can read it again.
func VerifyAndParseWebhook(r *http.Request, secret string) (WebhookEvent, error) {
if r == nil {
return nil, fmt.Errorf("%w: nil request", ErrInvalidWebhook)
}
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("%w: read body: %v", ErrInvalidWebhook, err)
}
r.Body = io.NopCloser(bytes.NewReader(body))
return VerifyAndParseWebhookBytes(body, r.Header.Get("X-Signature"), secret)
}
// WebhookEventKey is the context key under which WebhookMiddleware stores the
// parsed webhook event for downstream handlers.
type webhookEventKeyType struct{}
var WebhookEventKey = webhookEventKeyType{}
// WebhookMiddleware verifies + parses Stream webhook requests using the given
// secret and stores the parsed event in the request context under WebhookEventKey.
// On signature mismatch or parse failure, responds with 401 and aborts the chain.
func WebhookMiddleware(secret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
event, err := VerifyAndParseWebhook(r, secret)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), WebhookEventKey, event)))
})
}
}
// ParseSqs decodes (base64 + gzip pass-through) and parses an SQS Message Body.
//
// Backend emits no signature attribute on SQS messages today, so this helper
// performs no signature verification. If a signed variant is added later,
// it'll be a separate function rather than retrofitting this signature.
func ParseSqs(messageBody string) (WebhookEvent, error) {
payload, err := DecodeSqsPayload(messageBody)
if err != nil {
return nil, err
}
return ParseEvent(payload)
}
// ParseSns unwraps the standard AWS SNS notification envelope and parses
// the inner payload. Same no-signature posture as ParseSqs.
func ParseSns(notificationBody string) (WebhookEvent, error) {
payload, err := DecodeSnsPayload(notificationBody)
if err != nil {
return nil, err
}
return ParseEvent(payload)
}