// SPDX-License-Identifier: AGPL-3.0-or-later // Package integrations connects a workspace to outside services (ADR-18): // tokens that let link previews read private GitHub, Linear and Figma items, // and a Slack app that gets page and comment news in a channel, previews of // Docwell links, and a /docwell search command. One record per workspace // holds it all; tokens are sealed with the server secret, and only // workspace admins see or change them. package integrations import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "net/url" "strings" "sync" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/directory" "docwell/server/internal/store/pocketbase" "docwell/server/internal/unfurl" ) const collection = "workspace_integrations" // Directory is what the service needs from directory.Service. type Directory interface { WorkspaceRole(ctx context.Context, c access.Caller, wsID string) (string, error) OpenToMembers(ctx context.Context, wsID, pageID string) (directory.ChatPage, bool) MemberByEmail(ctx context.Context, wsID, email string) (access.Caller, error) Search(ctx context.Context, c access.Caller, wsID string, q directory.SearchQuery) (directory.SearchResult, error) } // Options configure the service. type Options struct { // Secret seals the tokens (the server secret). Secret string // WebURL is where people open Docwell; Slack links and request URLs use it. WebURL string // APIs and SlackAPI point at the real services unless set (tests). APIs *unfurl.APIs SlackAPI string // Client calls the services; nil makes one with a timeout. Client *http.Client Log *slog.Logger } type Service struct { pb *pocketbase.Client dir Directory previews *unfurl.Fetcher apis unfurl.APIs slackAPI string webURL string client *http.Client aead cipher.AEAD log *slog.Logger // recent remembers page.updated posts, so a page being edited is posted // once in a while rather than on every save. mu sync.Mutex recent map[string]time.Time } // New makes the service. previews reads link previews (unfurl.New()). func New(pb *pocketbase.Client, dir Directory, previews *unfurl.Fetcher, o Options) *Service { key := sha256.Sum256([]byte("docwell-integrations:" + o.Secret)) block, _ := aes.NewCipher(key[:]) aead, _ := cipher.NewGCM(block) s := &Service{ pb: pb, dir: dir, previews: previews, apis: unfurl.DefaultAPIs, slackAPI: "https://slack.com/api", webURL: strings.TrimRight(o.WebURL, "/"), client: o.Client, aead: aead, log: o.Log, recent: map[string]time.Time{}, } if o.APIs != nil { s.apis = *o.APIs if previews != nil { s.previews = previews.WithAPIs(*o.APIs) } } if o.SlackAPI != "" { s.slackAPI = strings.TrimRight(o.SlackAPI, "/") } if s.client == nil { s.client = &http.Client{Timeout: 10 * time.Second} } if s.log == nil { s.log = slog.Default() } return s } // ---- Sealing --------------------------------------------------------------- func (s *Service) seal(plain string) string { if plain == "" { return "" } nonce := make([]byte, s.aead.NonceSize()) _, _ = rand.Read(nonce) return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil)) } var errUnreadable = errors.New("a stored token cannot be decrypted (the server secret changed); enter it again") func (s *Service) open(sealed string) (string, error) { if sealed == "" { return "", nil } raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:")) n := s.aead.NonceSize() if err != nil || len(raw) < n { return "", errUnreadable } plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil) if err != nil { return "", errUnreadable } return string(plain), nil } // ---- The record ------------------------------------------------------------ type record struct { ID string `json:"id"` Workspace string `json:"workspace"` GitHub string `json:"github"` Linear string `json:"linear"` Figma string `json:"figma"` SlackBot string `json:"slack_bot"` SlackSigning string `json:"slack_signing"` SlackTeam string `json:"slack_team"` SlackTeamName string `json:"slack_team_name"` SlackChannel string `json:"slack_channel"` SlackChannelName string `json:"slack_channel_name"` SlackEvents []string `json:"slack_events"` SlackUnfurl bool `json:"slack_unfurl"` SlackSearch bool `json:"slack_search"` SlackError string `json:"slack_error"` } func (s *Service) find(ctx context.Context, wsID string) (*record, error) { res, err := pocketbase.List[record](ctx, s.pb, collection, pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("workspace = '%s'", wsID)}) if err != nil { return nil, err } if len(res.Items) == 0 { return nil, nil } return &res.Items[0], nil } // save writes fields into the workspace's record, making it when needed. func (s *Service) save(ctx context.Context, wsID string, r *record, body map[string]any) (*record, error) { if r == nil { body["workspace"] = wsID out, err := pocketbase.Create[record](ctx, s.pb, collection, body) return &out, err } out, err := pocketbase.Update[record](ctx, s.pb, collection, r.ID, body) return &out, err } func (s *Service) requireAdmin(ctx context.Context, c access.Caller, wsID string) error { if wsID == "" { return apperr.NotFound("workspace not found") } role, err := s.dir.WorkspaceRole(ctx, c, wsID) if err != nil { return err } if !access.AtLeast(role, access.WorkspaceAdmin) { return apperr.Forbidden("workspace admin role required") } return nil } // ---- What workspace settings show ----------------------------------------- // Token says whether a service's token is stored. type Token struct { Set bool `json:"set"` } // Slack is the workspace's Slack connection as its settings show it. type Slack struct { Connected bool `json:"connected"` HasSigning bool `json:"hasSigningSecret"` Team string `json:"team"` TeamName string `json:"teamName"` Channel string `json:"channel"` ChannelName string `json:"channelName"` Events []string `json:"events"` Unfurl bool `json:"unfurl"` Search bool `json:"search"` LastError string `json:"lastError"` // EventsURL and CommandsURL go into the Slack app's settings; Manifest // makes such an app in one step (api.slack.com/apps → From a manifest). EventsURL string `json:"eventsUrl"` CommandsURL string `json:"commandsUrl"` Manifest string `json:"manifest"` } // View is a workspace's integrations. type View struct { GitHub Token `json:"github"` Linear Token `json:"linear"` Figma Token `json:"figma"` Slack Slack `json:"slack"` } func (s *Service) view(wsID string, r *record) View { v := View{Slack: Slack{ EventsURL: s.webURL + "/api/v1/slack/" + wsID + "/events", CommandsURL: s.webURL + "/api/v1/slack/" + wsID + "/commands", Events: DefaultSlackEvents, }} v.Slack.Manifest = s.manifest(v.Slack.EventsURL, v.Slack.CommandsURL) if r == nil { return v } v.GitHub.Set, v.Linear.Set, v.Figma.Set = r.GitHub != "", r.Linear != "", r.Figma != "" v.Slack.Connected = r.SlackBot != "" v.Slack.HasSigning = r.SlackSigning != "" v.Slack.Team, v.Slack.TeamName = r.SlackTeam, r.SlackTeamName v.Slack.Channel, v.Slack.ChannelName = r.SlackChannel, r.SlackChannelName if r.SlackEvents != nil { v.Slack.Events = r.SlackEvents } v.Slack.Unfurl, v.Slack.Search, v.Slack.LastError = r.SlackUnfurl, r.SlackSearch, r.SlackError return v } // Get returns a workspace's integrations (workspace admins). func (s *Service) Get(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 { return View{}, err } return s.view(wsID, r), nil } // ---- Tokens for link previews ---------------------------------------------- // Services whose tokens SetToken takes. const ( GitHub = "github" Linear = "linear" Figma = "figma" ) // SetToken checks a token with its service and stores it; an empty token // removes the stored one. func (s *Service) SetToken(ctx context.Context, c access.Caller, wsID, service, token string) (View, error) { if service != GitHub && service != Linear && service != Figma { return View{}, apperr.NotFound("unknown service") } if err := s.requireAdmin(ctx, c, wsID); err != nil { return View{}, err } token = strings.TrimSpace(token) if len(token) > 500 { return View{}, apperr.InvalidFields(map[string]string{"token": "The token is too long."}) } if token != "" { if err := s.checkToken(ctx, service, token); err != nil { return View{}, apperr.InvalidFields(map[string]string{"token": err.Error()}) } } r, err := s.find(ctx, wsID) if err != nil { return View{}, err } r, err = s.save(ctx, wsID, r, map[string]any{service: s.seal(token)}) if err != nil { return View{}, err } return s.view(wsID, r), nil } // checkToken asks the service who the token belongs to. func (s *Service) checkToken(ctx context.Context, service, token string) error { var req *http.Request var err error switch service { case GitHub: req, err = http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(s.apis.GitHub, "/")+"/user", nil) if err == nil { req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("X-GitHub-Api-Version", "2022-11-28") } case Linear: body := strings.NewReader(`{"query":"{ viewer { id } }"}`) req, err = http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(s.apis.Linear, "/")+"/graphql", body) if err == nil { req.Header.Set("Authorization", token) req.Header.Set("Content-Type", "application/json") } case Figma: req, err = http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(s.apis.Figma, "/")+"/v1/me", nil) if err == nil { req.Header.Set("X-Figma-Token", token) } } if err != nil { return err } name := map[string]string{GitHub: "GitHub", Linear: "Linear", Figma: "Figma"}[service] res, err := s.client.Do(req) if err != nil { return fmt.Errorf("%s could not be reached", name) } defer func() { _ = res.Body.Close() }() data, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10)) if res.StatusCode != http.StatusOK || (service == Linear && bytes.Contains(data, []byte(`"errors"`))) { return fmt.Errorf("%s did not accept the token", name) } return nil } // Preview reads a link preview with the tokens of workspace wsID when the // caller is a member of it; without a workspace only public data is read. func (s *Service) Preview(ctx context.Context, c access.Caller, wsID, raw string) (unfurl.Preview, error) { t := unfurl.Tokens{} if wsID != "" { if _, err := s.dir.WorkspaceRole(ctx, c, wsID); err != nil { return unfurl.Preview{}, err } r, err := s.find(ctx, wsID) if err != nil { return unfurl.Preview{}, err } if r != nil { // A token that no longer opens is left out, not an error. t.GitHub, _ = s.open(r.GitHub) t.Linear, _ = s.open(r.Linear) t.Figma, _ = s.open(r.Figma) } } return s.previews.PreviewWith(ctx, raw, t) } // ---- Small helpers ---------------------------------------------------------- func postJSON(ctx context.Context, client *http.Client, u, bearer string, body, out any) error { data, err := json.Marshal(body) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data)) if err != nil { return err } req.Header.Set("Content-Type", "application/json; charset=utf-8") if bearer != "" { req.Header.Set("Authorization", "Bearer "+bearer) } return do(client, req, out) } func getForm(ctx context.Context, client *http.Client, u, bearer string, q url.Values, out any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, u+"?"+q.Encode(), nil) if err != nil { return err } if bearer != "" { req.Header.Set("Authorization", "Bearer "+bearer) } return do(client, req, out) } func do(client *http.Client, req *http.Request, out any) error { res, err := client.Do(req) if err != nil { return err } defer func() { _ = res.Body.Close() }() if res.StatusCode >= 300 { return fmt.Errorf("HTTP %d", res.StatusCode) } return json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(out) }