// SPDX-License-Identifier: AGPL-3.0-or-later package spa import ( "bytes" "context" "encoding/json" "html" "io" "net/http" "net/url" "regexp" "strings" "sync" "time" ) // Link previews for chat apps (ADR-17). When Slack, Teams, Discord and the // like fetch a page or share link, the app shell they get has no title, so // for their bots docwell-web asks docwell-server what to show and writes it // into the page's meta tags. People's browsers never wait for this. // Preview is what docwell-server's preview endpoints answer. type Preview struct { Title string `json:"title"` Description string `json:"description"` Site string `json:"site"` } // previewBots matches the user agents of chat apps' link-preview fetchers. // Search engines are left out on purpose: they must not learn the titles of // private pages. var previewBots = regexp.MustCompile(`(?i)slackbot|slack-imgproxy|twitterbot|facebookexternalhit|discordbot|telegrambot|whatsapp|linkedinbot|mattermost|skypeuripreview|microsoftpreview|embedly|iframely|redditbot|zulip|rocket\.chat|synapse|nextcloud server crawler|viber`) var ( pagePath = regexp.MustCompile(`^/p/([A-Za-z0-9_-]{1,64})$`) sharePath = regexp.MustCompile(`^/share/([A-Za-z0-9_-]{1,64})(?:/p/([A-Za-z0-9_-]{1,64}))?$`) ) // previewer looks previews up on docwell-server and remembers them briefly. type previewer struct { api *url.URL client *http.Client mu sync.Mutex cache map[string]cachedPreview } type cachedPreview struct { p *Preview exp time.Time } func newPreviewer(api *url.URL) *previewer { return &previewer{api: api, client: &http.Client{Timeout: 3 * time.Second}, cache: map[string]cachedPreview{}} } // endpoint maps an app path to its preview endpoint ("" when it has none). func endpoint(p string) string { if m := pagePath.FindStringSubmatch(p); m != nil { return "/api/v1/previews/pages/" + m[1] } if m := sharePath.FindStringSubmatch(p); m != nil { e := "/api/v1/previews/share/" + m[1] if m[2] != "" { e += "?page=" + url.QueryEscape(m[2]) } return e } return "" } // lookup returns the preview for an app path, or nil. func (v *previewer) lookup(ctx context.Context, p string) *Preview { e := endpoint(p) if e == "" { return nil } now := time.Now() v.mu.Lock() if c, ok := v.cache[e]; ok && now.Before(c.exp) { v.mu.Unlock() return c.p } v.mu.Unlock() var out *Preview // The host is docwell-server's from configuration; e only carries ids the // path patterns above allowed. u := strings.TrimRight(v.api.String(), "/") + e if req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil); err == nil { //nolint:gosec // see above if resp, err := v.client.Do(req); err == nil { //nolint:gosec // see above if resp.StatusCode == http.StatusOK { var p Preview if json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&p) == nil && p.Title != "" { out = &p } } resp.Body.Close() } } v.mu.Lock() if len(v.cache) > 1000 { v.cache = map[string]cachedPreview{} } v.cache[e] = cachedPreview{p: out, exp: now.Add(time.Minute)} v.mu.Unlock() return out } // withPreview writes p's title and meta tags into the app shell's head. func withPreview(index []byte, p *Preview) []byte { esc := html.EscapeString var b strings.Builder b.WriteString("