Files
Docwell/Server/internal/unfurl/unfurl.go
T
tajniak81andClaude Opus 5.5 f1963f1391 Add Confluence import, a Slack app per workspace, and GitHub, Linear and Figma link previews
Link previews: link cards for GitHub issues, pull requests and
repositories, Linear issues and Figma files are read through the
services' APIs and show a status pill (Open, Merged, In Progress…) and a
line of details. Public items need nothing; a workspace's tokens, set by
its admins under Workspace settings → Integrations and checked with each
service before being sealed, reach private ones and Linear.
GET /link-preview takes the workspace; the link card stores kind,
status, state and meta.

Slack: each workspace connects its own Slack app, made from a manifest
the settings page fills in. Docwell posts chosen page and comment events
to a channel (edits at most every 30 minutes per page), previews links
to Docwell pages posted in Slack, and answers /docwell with a search as
the member whose email matches the Slack user, shown only to them. Only
pages every member can open are posted or previewed. Requests from Slack
are signature-checked; the webhook dispatcher gained listeners so Slack
follows the same events.

Confluence: a space's HTML export imports with its page tree (from
index.html, else breadcrumbs), links between pages, pictures and
attachments. Panels become callouts, code macros code blocks with their
language, expand macros toggles, task lists to-dos.

New collection workspace_integrations (schema snapshot regenerated),
OpenAPI and generated Go, TypeScript and Dart types, strings in all five
languages, the user guide, and a rebuilt mobile editor bundle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:42:11 +01:00

224 lines
6.7 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package unfurl reads a web page's title, description and picture for link
// cards in the editor. Any signed-in user can make the server fetch an
// address and read the answer, so it only goes to public addresses.
package unfurl
import (
"context"
"errors"
"io"
"mime"
"net"
"net/http"
"net/url"
"strings"
"syscall"
"time"
"unicode/utf8"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"docwell/server/internal/apperr"
)
// Preview is what a link card shows.
type Preview struct {
URL string `json:"url"`
Title string `json:"title"`
Description string `json:"description"`
Image string `json:"image"`
Site string `json:"site"`
// Kind, Status, State and Meta come from a service's API (rich.go):
// Kind like "github.pull", Status the service's word for it ("Merged",
// "In Progress"), State one of open, started, draft, merged, done,
// closed, canceled (for its colour), and Meta a line of details.
Kind string `json:"kind,omitempty"`
Status string `json:"status,omitempty"`
State string `json:"state,omitempty"`
Meta string `json:"meta,omitempty"`
}
// maxBody caps how much of a page is read; the tags are in its head.
const maxBody = 1 << 20
type Fetcher struct {
client *http.Client
apis *APIs // nil: the real services
}
// New returns a fetcher that refuses private, loopback and link-local
// addresses after DNS resolution, redirects included.
func New() *Fetcher {
dialer := &net.Dialer{Timeout: 5 * time.Second, Control: guard}
return &Fetcher{client: &http.Client{
Timeout: 8 * time.Second,
Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: nil, MaxResponseHeaderBytes: 64 << 10},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 3 {
return errors.New("too many redirects")
}
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
return errors.New("redirect to a non-web address")
}
return nil
},
}}
}
// NewWithClient uses client as is (tests point it at a local server).
func NewWithClient(client *http.Client) *Fetcher { return &Fetcher{client: client} }
var errBlocked = errors.New("address not allowed")
// cgnat is the shared address space (100.64.0.0/10) carriers and some cloud
// networks use internally.
var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
func guard(_, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
ip := net.ParseIP(host)
if ip == nil || !Public(ip) {
return errBlocked
}
return nil
}
// Public reports whether ip is on the public internet.
func Public(ip net.IP) bool {
return !ip.IsLoopback() && !ip.IsPrivate() && !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() &&
!ip.IsUnspecified() && !ip.IsMulticast() && !ip.IsInterfaceLocalMulticast() && !cgnat.Contains(ip)
}
// Preview fetches raw and reads its preview. Pages that are not HTML, or
// can't be reached, still get a preview with the address and site name.
func (f *Fetcher) Preview(ctx context.Context, raw string) (Preview, error) {
return f.PreviewWith(ctx, raw, Tokens{})
}
// PreviewWith is Preview with a workspace's tokens for the services that
// rich.go reads through their APIs.
func (f *Fetcher) PreviewWith(ctx context.Context, raw string, t Tokens) (Preview, error) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || len(raw) > 2000 {
return Preview{}, apperr.InvalidFields(map[string]string{"url": "Enter a web address (http or https)."})
}
u.Fragment = ""
if p, ok := f.rich(ctx, u, t); ok {
return p, nil
}
out := Preview{URL: u.String(), Site: siteName(u)}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return out, nil
}
req.Header.Set("Accept", "text/html,application/xhtml+xml")
req.Header.Set("User-Agent", "DocwellLinkPreview/1.0 (+https://docwell.app)")
res, err := f.client.Do(req)
if err != nil {
return out, nil
}
defer func() { _ = res.Body.Close() }()
ct, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type"))
if res.StatusCode >= 300 || (ct != "text/html" && ct != "application/xhtml+xml") {
return out, nil
}
p := Parse(res.Request.URL, io.LimitReader(res.Body, maxBody))
p.URL = out.URL
if p.Site == "" {
p.Site = out.Site
}
return p, nil
}
func siteName(u *url.URL) string { return strings.TrimPrefix(u.Hostname(), "www.") }
// Parse reads the preview from a page's head; base resolves relative image
// addresses.
func Parse(base *url.URL, r io.Reader) Preview {
var p Preview
var title strings.Builder
meta := map[string]string{}
z := html.NewTokenizer(r)
inTitle := false
for {
switch z.Next() {
case html.ErrorToken:
return finish(base, p, title.String(), meta)
case html.StartTagToken, html.SelfClosingTagToken:
name, hasAttr := z.TagName()
switch atom.Lookup(name) {
case atom.Title:
inTitle = true
case atom.Meta:
var key, content string
for hasAttr {
var k, v []byte
k, v, hasAttr = z.TagAttr()
switch string(k) {
case "property", "name":
key = strings.ToLower(string(v))
case "content":
content = string(v)
}
}
if key != "" && meta[key] == "" {
meta[key] = content
}
case atom.Body:
// Everything a preview needs is in the head.
return finish(base, p, title.String(), meta)
}
case html.TextToken:
if inTitle {
title.Write(z.Text())
}
case html.EndTagToken:
name, _ := z.TagName()
switch atom.Lookup(name) {
case atom.Title:
inTitle = false
case atom.Head:
return finish(base, p, title.String(), meta)
}
}
}
}
func finish(base *url.URL, p Preview, title string, meta map[string]string) Preview {
first := func(keys ...string) string {
for _, k := range keys {
if v := strings.TrimSpace(meta[k]); v != "" {
return v
}
}
return ""
}
p.Title = clip(first("og:title", "twitter:title"), 300)
if p.Title == "" {
p.Title = clip(strings.TrimSpace(title), 300)
}
p.Description = clip(first("og:description", "twitter:description", "description"), 500)
p.Site = clip(first("og:site_name", "application-name"), 100)
if img := first("og:image:secure_url", "og:image", "twitter:image", "twitter:image:src"); img != "" && base != nil {
if u, err := base.Parse(img); err == nil && (u.Scheme == "https" || u.Scheme == "http") && len(u.String()) <= 2000 {
p.Image = u.String()
}
}
return p
}
// clip collapses whitespace and cuts s to n runes.
func clip(s string, n int) string {
s = strings.Join(strings.Fields(s), " ")
if utf8.RuneCountInString(s) <= n {
return s
}
return strings.TrimSpace(string([]rune(s)[:n-1])) + "…"
}