// SPDX-License-Identifier: AGPL-3.0-or-later package integrations // Slack: each workspace connects its own Slack app (made from the manifest // its settings show). Docwell posts chosen page and comment events to one // channel, answers Slack's link_shared events with a preview of Docwell // pages, and runs /docwell as a search for the person who typed it (found // by their Slack email). Only pages every member of the workspace can open // are ever posted or previewed (directory.OpenToMembers); search results // are what that one person can open, and only they see them. import ( "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "net/url" "regexp" "slices" "strconv" "strings" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/directory" "docwell/server/internal/webhooks" ) // SlackEvents are the events a workspace can have posted to Slack. var SlackEvents = []string{ "page.created", "page.updated", "page.moved", "page.archived", "page.unarchived", "page.restored", "comment.created", "comment.resolved", } // DefaultSlackEvents are posted until an admin picks others. var DefaultSlackEvents = []string{"page.created", "comment.created"} // updateQuiet is how long a page's edits stay quiet after one was posted. const updateQuiet = 30 * time.Minute // SlackInput changes the Slack connection; nil fields stay as they are. type SlackInput struct { BotToken *string `json:"botToken"` SigningSecret *string `json:"signingSecret"` Channel *string `json:"channel"` Events *[]string `json:"events"` Unfurl *bool `json:"unfurl"` Search *bool `json:"search"` } // slackOK is the envelope of every Slack Web API answer. type slackOK struct { OK bool `json:"ok"` Error string `json:"error"` } func (s *Service) slack(ctx context.Context, method, token string, body, out any) error { var env struct { slackOK Raw json.RawMessage `json:"-"` } var raw json.RawMessage if err := postJSON(ctx, s.client, s.slackAPI+"/"+method, token, body, &raw); err != nil { return fmt.Errorf("Slack could not be reached (%w)", err) //nolint:staticcheck // shown to admins as is } if err := json.Unmarshal(raw, &env); err != nil { return fmt.Errorf("Slack sent an answer Docwell could not read") //nolint:staticcheck } if !env.OK { return fmt.Errorf("Slack said: %s", env.Error) //nolint:staticcheck } if out != nil { return json.Unmarshal(raw, out) } return nil } func (s *Service) slackGet(ctx context.Context, method, token string, q url.Values, out any) error { var raw json.RawMessage if err := getForm(ctx, s.client, s.slackAPI+"/"+method, token, q, &raw); err != nil { return fmt.Errorf("Slack could not be reached (%w)", err) //nolint:staticcheck } var env slackOK if err := json.Unmarshal(raw, &env); err != nil || !env.OK { return fmt.Errorf("Slack said: %s", env.Error) //nolint:staticcheck } return json.Unmarshal(raw, out) } var channelID = regexp.MustCompile(`^[CG][A-Z0-9]{6,}$`) // resolveChannel finds a public channel by id or name ("#general"). func (s *Service) resolveChannel(ctx context.Context, token, ch string) (id, name string, err error) { ch = strings.TrimSpace(ch) if channelID.MatchString(ch) { var out struct { Channel struct { ID string `json:"id"` Name string `json:"name"` } `json:"channel"` } if err := s.slackGet(ctx, "conversations.info", token, url.Values{"channel": {ch}}, &out); err != nil { return "", "", err } return out.Channel.ID, out.Channel.Name, nil } want := strings.ToLower(strings.TrimPrefix(ch, "#")) cursor := "" for range 20 { var out struct { Channels []struct { ID string `json:"id"` Name string `json:"name"` } `json:"channels"` Meta struct { Next string `json:"next_cursor"` } `json:"response_metadata"` } q := url.Values{"types": {"public_channel"}, "exclude_archived": {"true"}, "limit": {"1000"}} if cursor != "" { q.Set("cursor", cursor) } if err := s.slackGet(ctx, "conversations.list", token, q, &out); err != nil { return "", "", err } for _, c := range out.Channels { if strings.ToLower(c.Name) == want { return c.ID, c.Name, nil } } if cursor = out.Meta.Next; cursor == "" { break } } return "", "", fmt.Errorf("no public channel named #%s", want) } // SetSlack connects or changes the workspace's Slack app. func (s *Service) SetSlack(ctx context.Context, c access.Caller, wsID string, in SlackInput) (View, error) { if err := s.requireAdmin(ctx, c, wsID); err != nil { return View{}, err } r, err := s.find(ctx, wsID) if err != nil { return View{}, err } body := map[string]any{"slack_error": ""} token := "" if r != nil { token, _ = s.open(r.SlackBot) } if in.BotToken != nil { t := strings.TrimSpace(*in.BotToken) if !strings.HasPrefix(t, "xoxb-") || len(t) > 300 { return View{}, apperr.InvalidFields(map[string]string{"botToken": "Paste the app's Bot User OAuth Token (it starts with xoxb-)."}) //nolint:gosec // a message, not a credential } var who struct { TeamID string `json:"team_id"` Team string `json:"team"` } if err := s.slack(ctx, "auth.test", t, map[string]any{}, &who); err != nil { return View{}, apperr.InvalidFields(map[string]string{"botToken": err.Error()}) } token = t body["slack_bot"], body["slack_team"], body["slack_team_name"] = s.seal(t), who.TeamID, who.Team if r == nil || r.SlackBot == "" { // A first connection previews links and searches unless turned off. body["slack_unfurl"], body["slack_search"] = true, true body["slack_events"] = DefaultSlackEvents } } if in.SigningSecret != nil { sec := strings.TrimSpace(*in.SigningSecret) if len(sec) < 16 || len(sec) > 200 { return View{}, apperr.InvalidFields(map[string]string{"signingSecret": "Paste the app's Signing Secret (Basic Information โ†’ App Credentials)."}) //nolint:gosec // a message, not a credential } body["slack_signing"] = s.seal(sec) } if in.Channel != nil { if strings.TrimSpace(*in.Channel) == "" { body["slack_channel"], body["slack_channel_name"] = "", "" } else { if token == "" { return View{}, apperr.InvalidFields(map[string]string{"channel": "Connect the bot token first."}) } id, name, err := s.resolveChannel(ctx, token, *in.Channel) if err != nil { return View{}, apperr.InvalidFields(map[string]string{"channel": err.Error()}) } body["slack_channel"], body["slack_channel_name"] = id, name } } if in.Events != nil { events := []string{} for _, e := range *in.Events { if !slices.Contains(SlackEvents, e) { return View{}, apperr.InvalidFields(map[string]string{"events": "Unknown event: " + e}) } if !slices.Contains(events, e) { events = append(events, e) } } body["slack_events"] = events } if in.Unfurl != nil { body["slack_unfurl"] = *in.Unfurl } if in.Search != nil { body["slack_search"] = *in.Search } r, err = s.save(ctx, wsID, r, body) if err != nil { return View{}, err } return s.view(wsID, r), nil } // DeleteSlack disconnects Slack (the app itself stays in Slack). func (s *Service) DeleteSlack(ctx context.Context, c access.Caller, wsID string) (View, error) { if err := s.requireAdmin(ctx, c, wsID); err != nil { return View{}, err } r, err := s.find(ctx, wsID) if err != nil || r == nil { return s.view(wsID, r), err } r, err = s.save(ctx, wsID, r, map[string]any{ "slack_bot": "", "slack_signing": "", "slack_team": "", "slack_team_name": "", "slack_channel": "", "slack_channel_name": "", "slack_events": nil, "slack_unfurl": false, "slack_search": false, "slack_error": "", }) if err != nil { return View{}, err } return s.view(wsID, r), nil } // TestSlack posts a hello to the channel. func (s *Service) TestSlack(ctx context.Context, c access.Caller, wsID string) error { if err := s.requireAdmin(ctx, c, wsID); err != nil { return err } r, err := s.find(ctx, wsID) if err != nil { return err } if r == nil || r.SlackBot == "" || r.SlackChannel == "" { return apperr.Invalid("Connect the bot token and choose a channel first.") } token, err := s.open(r.SlackBot) if err != nil { return apperr.Invalid(err.Error()) } err = s.slack(ctx, "chat.postMessage", token, map[string]any{ "channel": r.SlackChannel, "text": "๐Ÿ‘‹ Docwell is connected. Page and comment news will show up here.", "unfurl_links": false, }, nil) if err != nil { return apperr.Invalid(err.Error()) } return nil } func (s *Service) manifest(eventsURL, commandsURL string) string { host := "" if u, err := url.Parse(s.webURL); err == nil { host = u.Hostname() } m := map[string]any{ "display_information": map[string]any{"name": "Docwell", "description": "Docwell pages in Slack"}, "features": map[string]any{ "bot_user": map[string]any{"display_name": "Docwell", "always_online": false}, "slash_commands": []any{map[string]any{ "command": "/docwell", "url": commandsURL, "description": "Search Docwell", "usage_hint": "[words to find]", "should_escape": false, }}, "unfurl_domains": []string{host}, }, "oauth_config": map[string]any{"scopes": map[string]any{"bot": []string{ "chat:write", "chat:write.public", "channels:read", "commands", "links:read", "links:write", "users:read", "users:read.email", }}}, "settings": map[string]any{ "event_subscriptions": map[string]any{"request_url": eventsURL, "bot_events": []string{"link_shared"}}, "org_deploy_enabled": false, "socket_mode_enabled": false, "token_rotation_enabled": false, }, } data, _ := json.MarshalIndent(m, "", " ") return string(data) } // ---- Channel posts ----------------------------------------------------------- // Listen posts webhook events to Slack; give it to webhooks.Dispatcher.Listen. func (s *Service) Listen(p webhooks.Payload) { if !slices.Contains(SlackEvents, p.Event) { return } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() r, err := s.find(ctx, p.Workspace) if err != nil || r == nil || r.SlackBot == "" || r.SlackChannel == "" { return } events := r.SlackEvents if events == nil { events = DefaultSlackEvents } if !slices.Contains(events, p.Event) { return } // The event's data, read through JSON whatever its Go type. var data struct { Page struct { ID string `json:"id"` } `json:"page"` Actor *struct { Name string `json:"name"` } `json:"actor"` Comment *struct { Body string `json:"body"` } `json:"comment"` } raw, _ := json.Marshal(p.Data) if json.Unmarshal(raw, &data) != nil || data.Page.ID == "" { return } page, ok := s.dir.OpenToMembers(ctx, p.Workspace, data.Page.ID) if !ok { return } if p.Event == "page.updated" && !s.quietEnough(p.Workspace+"/"+page.ID) { return } who := "Someone" if data.Actor != nil && data.Actor.Name != "" { who = data.Actor.Name } text := fmt.Sprintf("*%s* %s %s", escape(who), verb(p.Event), pageLink(page)) if page.SpaceName != "" { text += " in _" + escape(page.SpaceName) + "_" } if data.Comment != nil && p.Event == "comment.created" { if body := commentText(data.Comment.Body); body != "" { text += "\n>" + escape(body) } } token, err := s.open(r.SlackBot) if err == nil { err = s.slack(ctx, "chat.postMessage", token, map[string]any{"channel": r.SlackChannel, "text": text, "unfurl_links": false}, nil) } s.noteError(ctx, r, err) } func (s *Service) quietEnough(key string) bool { s.mu.Lock() defer s.mu.Unlock() now := time.Now() if t, ok := s.recent[key]; ok && now.Sub(t) < updateQuiet { return false } s.recent[key] = now if len(s.recent) > 5000 { for k, t := range s.recent { if now.Sub(t) >= updateQuiet { delete(s.recent, k) } } } return true } // noteError keeps the last delivery error for the settings page (and clears it). func (s *Service) noteError(ctx context.Context, r *record, err error) { msg := "" if err != nil { msg = err.Error() s.log.Warn("slack: post", "workspace", r.Workspace, "err", err) } if msg != r.SlackError { _, _ = s.save(ctx, r.Workspace, r, map[string]any{"slack_error": msg}) } } func verb(event string) string { switch event { case "page.created": return "created" case "page.updated": return "edited" case "page.moved": return "moved" case "page.archived": return "archived" case "page.unarchived": return "brought back" case "page.restored": return "restored" case "comment.created": return "commented on" case "comment.resolved": return "resolved a comment on" } return event } func pageLink(p directory.ChatPage) string { title := p.Title if title == "" { title = "Untitled" } if p.Icon != "" && len([]rune(p.Icon)) <= 4 { title = p.Icon + " " + title } return "<" + p.URL + "|" + escape(title) + ">" } // escape keeps text from being read as Slack markup. func escape(s string) string { return strings.NewReplacer("&", "&", "<", "<", ">", ">").Replace(s) } // commentText is a comment body (Tiptap JSON or text) as one short line. func commentText(body string) string { text := body if strings.HasPrefix(strings.TrimSpace(body), "{") { var parts []string var walk func(any) walk = func(v any) { switch n := v.(type) { case map[string]any: if t, ok := n["text"].(string); ok { parts = append(parts, t) } if a, ok := n["attrs"].(map[string]any); ok { if l, ok := a["label"].(string); ok && n["type"] == "mention" { parts = append(parts, "@"+l) } } walk(n["content"]) case []any: for _, c := range n { walk(c) } } } var doc any if json.Unmarshal([]byte(body), &doc) == nil { walk(doc) text = strings.Join(parts, " ") } } text = strings.Join(strings.Fields(text), " ") if r := []rune(text); len(r) > 280 { text = string(r[:279]) + "โ€ฆ" } return text } // ---- Requests from Slack ------------------------------------------------------- // maxSlackBody caps what Slack sends. const maxSlackBody = 1 << 20 // verify checks Slack's signature on a request body (5 minutes of leeway). func verify(secret string, h http.Header, body []byte, now time.Time) bool { ts, err := strconv.ParseInt(h.Get("X-Slack-Request-Timestamp"), 10, 64) if err != nil || secret == "" { return false } if d := now.Unix() - ts; d > 300 || d < -300 { return false } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte("v0:" + strconv.FormatInt(ts, 10) + ":")) mac.Write(body) want := "v0=" + hex.EncodeToString(mac.Sum(nil)) return hmac.Equal([]byte(want), []byte(h.Get("X-Slack-Signature"))) } // signed reads a request from Slack for workspace wsID and checks its // signature; the record comes back for the caller to use. func (s *Service) signed(r *http.Request, wsID string) (*record, []byte, bool) { body, err := io.ReadAll(io.LimitReader(r.Body, maxSlackBody)) if err != nil || wsID == "" || strings.ContainsAny(wsID, "'\"\\ ") { return nil, nil, false } rec, err := s.find(r.Context(), wsID) if err != nil || rec == nil || rec.SlackBot == "" { return nil, nil, false } secret, err := s.open(rec.SlackSigning) if err != nil || !verify(secret, r.Header, body, time.Now()) { return nil, nil, false } return rec, body, true } // Events answers Slack's Events API for workspace wsID: the URL check, and // link_shared, which gets previews of Docwell pages. func (s *Service) Events(w http.ResponseWriter, r *http.Request, wsID string) { rec, body, ok := s.signed(r, wsID) if !ok { http.Error(w, "bad signature", http.StatusUnauthorized) return } var in struct { Type string `json:"type"` Challenge string `json:"challenge"` TeamID string `json:"team_id"` Event struct { Type string `json:"type"` Channel string `json:"channel"` MessageTS string `json:"message_ts"` UnfurlID string `json:"unfurl_id"` Source string `json:"source"` Links []struct { URL string `json:"url"` } `json:"links"` } `json:"event"` } if json.Unmarshal(body, &in) != nil { http.Error(w, "bad request", http.StatusBadRequest) return } if in.Type == "url_verification" { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]string{"challenge": in.Challenge}) return } w.WriteHeader(http.StatusOK) // Slack resends what it thinks was missed; the first try did the work. if r.Header.Get("X-Slack-Retry-Num") != "" || in.Type != "event_callback" || in.Event.Type != "link_shared" { return } if !rec.SlackUnfurl || (rec.SlackTeam != "" && in.TeamID != "" && in.TeamID != rec.SlackTeam) { return } var urls []string for _, l := range in.Event.Links { urls = append(urls, l.URL) } ev := in.Event go s.unfurl(rec, ev.Channel, ev.MessageTS, ev.UnfurlID, ev.Source, urls) } var pagePath = regexp.MustCompile(`^/p/([a-z0-9]{15})(?:[/?#]|$)`) // unfurl sends Slack previews of the Docwell pages among urls. func (s *Service) unfurl(rec *record, channel, ts, unfurlID, source string, urls []string) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() base, err := url.Parse(s.webURL) if err != nil { return } unfurls := map[string]any{} for _, raw := range urls { u, err := url.Parse(raw) if err != nil || !strings.EqualFold(u.Host, base.Host) { continue } m := pagePath.FindStringSubmatch(u.Path) if m == nil { continue } page, ok := s.dir.OpenToMembers(ctx, rec.Workspace, m[1]) if !ok { continue } title := page.Title if title == "" { title = "Untitled" } if page.Icon != "" && len([]rune(page.Icon)) <= 4 { title = page.Icon + " " + title } block := map[string]any{"title": title, "title_link": raw, "footer": "Docwell ยท " + page.SpaceName} if page.Excerpt != "" { block["text"] = page.Excerpt } unfurls[raw] = block } if len(unfurls) == 0 { return } token, err := s.open(rec.SlackBot) if err != nil { return } body := map[string]any{"unfurls": unfurls} if unfurlID != "" && source != "" { body["unfurl_id"], body["source"] = unfurlID, source } else { body["channel"], body["ts"] = channel, ts } if err := s.slack(ctx, "chat.unfurl", token, body, nil); err != nil { s.log.Warn("slack: unfurl", "workspace", rec.Workspace, "err", err) } } // Commands answers /docwell for workspace wsID: a search as the person who // typed it, shown only to them. func (s *Service) Commands(w http.ResponseWriter, r *http.Request, wsID string) { rec, body, ok := s.signed(r, wsID) if !ok { http.Error(w, "bad signature", http.StatusUnauthorized) return } form, err := url.ParseQuery(string(body)) if err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } if form.Get("ssl_check") == "1" { return } reply := func(text string) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"response_type": "ephemeral", "text": text}) } if !rec.SlackSearch { reply("Searching Docwell from Slack is turned off for this workspace.") return } if rec.SlackTeam != "" && form.Get("team_id") != "" && form.Get("team_id") != rec.SlackTeam { reply("This Slack workspace is not the one connected to Docwell.") return } q := strings.TrimSpace(form.Get("text")) if q == "" { reply("Type what to find, like `/docwell onboarding checklist`.") return } ctx, cancel := context.WithTimeout(r.Context(), 2500*time.Millisecond) defer cancel() c, err := s.slackCaller(ctx, rec, form.Get("user_id")) if err != nil { reply(err.Error()) return } res, err := s.dir.Search(ctx, c, rec.Workspace, directory.SearchQuery{Text: q, Limit: 5}) if err != nil { reply("The search did not work: " + err.Error()) return } if len(res.Items) == 0 { reply("Nothing in Docwell matches โ€œ" + escape(q) + "โ€.") return } var b strings.Builder fmt.Fprintf(&b, "Docwell pages for โ€œ%sโ€:", escape(q)) for _, h := range res.Items { title := h.Title if title == "" { title = "Untitled" } fmt.Fprintf(&b, "\nโ€ข <%s/p/%s|%s>", s.webURL, h.ID, escape(title)) if h.File != nil { b.WriteString(" ยท ๐Ÿ“Ž " + escape(h.File.Name)) } if h.SpaceName != "" { b.WriteString(" โ€” _" + escape(h.SpaceName) + "_") } if sn := strings.Join(strings.Fields(h.Snippet), " "); sn != "" { if r := []rune(sn); len(r) > 160 { sn = string(r[:159]) + "โ€ฆ" } b.WriteString("\n " + escape(sn)) } } if res.Total > len(res.Items) { fmt.Fprintf(&b, "\n<%s/search?q=%s|All %d results in Docwell>", s.webURL, url.QueryEscape(q), res.Total) } reply(b.String()) } // slackCaller is the Docwell member with the Slack user's email. func (s *Service) slackCaller(ctx context.Context, rec *record, slackUser string) (access.Caller, error) { token, err := s.open(rec.SlackBot) if err != nil || slackUser == "" { return access.Caller{}, fmt.Errorf("Docwell cannot reach Slack right now") //nolint:staticcheck } var out struct { User struct { Deleted bool `json:"deleted"` IsBot bool `json:"is_bot"` Profile struct { Email string `json:"email"` } `json:"profile"` } `json:"user"` } if err := s.slackGet(ctx, "users.info", token, url.Values{"user": {slackUser}}, &out); err != nil || out.User.Profile.Email == "" { return access.Caller{}, fmt.Errorf("Docwell could not read your Slack email; ask an admin to give the app the users:read.email scope") //nolint:staticcheck } if out.User.Deleted || out.User.IsBot { return access.Caller{}, fmt.Errorf("Only people can search Docwell") //nolint:staticcheck } c, err := s.dir.MemberByEmail(ctx, rec.Workspace, out.User.Profile.Email) if err != nil { return access.Caller{}, fmt.Errorf("Your Slack email is not a member of this Docwell workspace") //nolint:staticcheck } return c, nil }