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>
375 lines
11 KiB
Go
375 lines
11 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package webhooks delivers workspace events to the URLs workspace admins
|
|
// register. Each delivery is a JSON POST signed with the webhook's secret
|
|
// (X-Docwell-Signature: sha256=<hex HMAC of the body>), retried a few times
|
|
// with growing pauses, and logged in webhook_deliveries.
|
|
package webhooks
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// Events a webhook can subscribe to ("*" means all of them).
|
|
var Events = []string{
|
|
"page.created", "page.updated", "page.moved", "page.trashed", "page.restored", "page.deleted",
|
|
"page.archived", "page.unarchived",
|
|
"comment.created", "comment.resolved",
|
|
"space.created", "space.deleted",
|
|
}
|
|
|
|
// ValidEvent reports whether e is an event or "*".
|
|
func ValidEvent(e string) bool {
|
|
if e == "*" {
|
|
return true
|
|
}
|
|
for _, v := range Events {
|
|
if v == e {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Payload is the body of every delivery.
|
|
type Payload struct {
|
|
ID string `json:"id"`
|
|
Event string `json:"event"`
|
|
Workspace string `json:"workspace"`
|
|
Created string `json:"created"`
|
|
Data any `json:"data"`
|
|
}
|
|
|
|
type Options struct {
|
|
// AllowLocal lets webhooks reach loopback and link-local addresses
|
|
// (development only: otherwise anyone who can add a webhook could probe
|
|
// the server's own machine or a cloud metadata endpoint).
|
|
AllowLocal bool
|
|
// Retries are the pauses before the 2nd, 3rd, … attempt.
|
|
Retries []time.Duration
|
|
Timeout time.Duration
|
|
}
|
|
|
|
type Dispatcher struct {
|
|
pb *pocketbase.Client
|
|
log *slog.Logger
|
|
opts Options
|
|
client *http.Client
|
|
queue chan job
|
|
// listeners see every event too (the Slack integration); set before Run.
|
|
listeners []func(Payload)
|
|
}
|
|
|
|
// Listen calls fn, on its own goroutine, for every event emitted from now on.
|
|
// Call it while setting up, before events flow.
|
|
func (d *Dispatcher) Listen(fn func(Payload)) {
|
|
if d != nil {
|
|
d.listeners = append(d.listeners, fn)
|
|
}
|
|
}
|
|
|
|
type job struct {
|
|
workspace string
|
|
payload Payload
|
|
}
|
|
|
|
type hookRecord struct {
|
|
ID string `json:"id"`
|
|
Workspace string `json:"workspace"`
|
|
URL string `json:"url"`
|
|
Secret string `json:"secret"`
|
|
Events []string `json:"events"`
|
|
Active bool `json:"active"`
|
|
}
|
|
|
|
func New(pb *pocketbase.Client, log *slog.Logger, opts Options) *Dispatcher {
|
|
if opts.Retries == nil {
|
|
opts.Retries = []time.Duration{10 * time.Second, time.Minute, 5 * time.Minute}
|
|
}
|
|
if opts.Timeout == 0 {
|
|
opts.Timeout = 10 * time.Second
|
|
}
|
|
dialer := &net.Dialer{Timeout: opts.Timeout, Control: guard(opts.AllowLocal)}
|
|
d := &Dispatcher{
|
|
pb: pb, log: log, opts: opts, queue: make(chan job, 1000),
|
|
client: &http.Client{
|
|
Timeout: opts.Timeout,
|
|
Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: nil},
|
|
// A redirect could point anywhere; deliveries do not follow them.
|
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
},
|
|
}
|
|
return d
|
|
}
|
|
|
|
// errBlocked is a webhook address that resolves somewhere it may not go.
|
|
var errBlocked = errors.New("address not allowed for webhooks")
|
|
|
|
// guard refuses connections to loopback, link-local (cloud metadata),
|
|
// unspecified and multicast addresses, after DNS resolution, so a hostname
|
|
// cannot sneak past it. Private networks stay reachable: self-hosted
|
|
// integrations usually live there.
|
|
func guard(allowLocal bool) func(network, address string, _ syscall.RawConn) error {
|
|
return func(network, address string, _ syscall.RawConn) error {
|
|
if allowLocal {
|
|
return nil
|
|
}
|
|
host, _, err := net.SplitHostPort(address)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ip := net.ParseIP(host)
|
|
if ip == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||
|
|
ip.IsUnspecified() || ip.IsMulticast() || ip.IsInterfaceLocalMulticast() {
|
|
return errBlocked
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// Guard is the same address check for other outgoing requests to
|
|
// user-given addresses (push endpoints).
|
|
func Guard(allowLocal bool) func(network, address string, _ syscall.RawConn) error {
|
|
return guard(allowLocal)
|
|
}
|
|
|
|
// Run delivers queued events until ctx ends.
|
|
func (d *Dispatcher) Run(ctx context.Context) {
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case j := <-d.queue:
|
|
d.fanOut(ctx, j)
|
|
}
|
|
}
|
|
}
|
|
|
|
func newID() string {
|
|
b := make([]byte, 12)
|
|
_, _ = rand.Read(b)
|
|
return hex.EncodeToString(b)
|
|
}
|
|
|
|
// Emit queues event for workspace's webhooks (never blocks).
|
|
func (d *Dispatcher) Emit(workspace, event string, data any) {
|
|
if d == nil || workspace == "" {
|
|
return
|
|
}
|
|
p := Payload{ID: newID(), Event: event, Workspace: workspace, Created: time.Now().UTC().Format(time.RFC3339), Data: data}
|
|
for _, fn := range d.listeners {
|
|
go fn(p)
|
|
}
|
|
select {
|
|
case d.queue <- job{workspace: workspace, payload: p}:
|
|
default:
|
|
d.log.Warn("webhooks: queue full, event dropped", "event", event, "workspace", workspace)
|
|
}
|
|
}
|
|
|
|
func subscribed(events []string, event string) bool {
|
|
for _, e := range events {
|
|
if e == "*" || e == event {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (d *Dispatcher) fanOut(ctx context.Context, j job) {
|
|
hooks, err := pocketbase.List[hookRecord](ctx, d.pb, "webhooks", pocketbase.ListOptions{
|
|
PerPage: 100, Filter: fmt.Sprintf("workspace = '%s' && active = true", j.workspace),
|
|
})
|
|
if err != nil {
|
|
d.log.Error("webhooks: list", "workspace", j.workspace, "err", err)
|
|
return
|
|
}
|
|
for _, h := range hooks.Items {
|
|
if subscribed(h.Events, j.payload.Event) {
|
|
go d.deliver(context.WithoutCancel(ctx), h, j.payload)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Delivery is one attempt series as the workspace settings show it.
|
|
type Delivery struct {
|
|
ID string `json:"id"`
|
|
Event string `json:"event"`
|
|
DeliveryID string `json:"deliveryId"`
|
|
Status string `json:"status"`
|
|
Attempts int `json:"attempts"`
|
|
ResponseCode int `json:"responseCode"`
|
|
Error string `json:"error"`
|
|
DurationMs int `json:"durationMs"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
type deliveryRecord struct {
|
|
ID string `json:"id"`
|
|
Webhook string `json:"webhook"`
|
|
Event string `json:"event"`
|
|
DeliveryID string `json:"delivery_id"`
|
|
Status string `json:"status"`
|
|
Attempts int `json:"attempts"`
|
|
ResponseCode int `json:"response_code"`
|
|
Error string `json:"error"`
|
|
DurationMs int `json:"duration_ms"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
func (r deliveryRecord) view() Delivery {
|
|
return Delivery{
|
|
ID: r.ID, Event: r.Event, DeliveryID: r.DeliveryID, Status: r.Status, Attempts: r.Attempts,
|
|
ResponseCode: r.ResponseCode, Error: r.Error, DurationMs: r.DurationMs, Created: r.Created,
|
|
}
|
|
}
|
|
|
|
// Sign is the X-Docwell-Signature value for body.
|
|
func Sign(secret string, body []byte) string {
|
|
m := hmac.New(sha256.New, []byte(secret))
|
|
m.Write(body)
|
|
return "sha256=" + hex.EncodeToString(m.Sum(nil))
|
|
}
|
|
|
|
// deliver posts p to h, retrying failures, and logs the outcome.
|
|
func (d *Dispatcher) deliver(ctx context.Context, h hookRecord, p Payload) Delivery {
|
|
body, _ := json.Marshal(p)
|
|
rec, err := pocketbase.Create[deliveryRecord](ctx, d.pb, "webhook_deliveries", map[string]any{
|
|
"webhook": h.ID, "event": p.Event, "delivery_id": p.ID, "status": "pending", "attempts": 0,
|
|
})
|
|
if err != nil {
|
|
d.log.Error("webhooks: log delivery", "webhook", h.ID, "err", err)
|
|
}
|
|
var code int
|
|
var lastErr string
|
|
var dur time.Duration
|
|
attempts := 0
|
|
for attempt := 0; attempt <= len(d.opts.Retries); attempt++ {
|
|
if attempt > 0 {
|
|
select {
|
|
case <-ctx.Done():
|
|
return rec.view()
|
|
case <-time.After(d.opts.Retries[attempt-1]):
|
|
}
|
|
}
|
|
attempts++
|
|
code, dur, err = d.post(ctx, h, p, body)
|
|
if err == nil && code >= 200 && code < 300 {
|
|
lastErr = ""
|
|
break
|
|
}
|
|
if err != nil {
|
|
lastErr = err.Error()
|
|
} else {
|
|
lastErr = fmt.Sprintf("the endpoint answered %d", code)
|
|
}
|
|
// 4xx other than 408/429 will not get better by retrying.
|
|
if err == nil && code >= 400 && code < 500 && code != 408 && code != 429 {
|
|
break
|
|
}
|
|
}
|
|
status := "success"
|
|
if lastErr != "" {
|
|
status = "failed"
|
|
}
|
|
if len(lastErr) > 500 {
|
|
lastErr = lastErr[:500]
|
|
}
|
|
if rec.ID != "" {
|
|
if updated, err := pocketbase.Update[deliveryRecord](ctx, d.pb, "webhook_deliveries", rec.ID, map[string]any{
|
|
"status": status, "attempts": attempts, "response_code": code, "error": lastErr, "duration_ms": dur.Milliseconds(),
|
|
}); err == nil {
|
|
rec = updated
|
|
}
|
|
}
|
|
return rec.view()
|
|
}
|
|
|
|
func (d *Dispatcher) post(ctx context.Context, h hookRecord, p Payload, body []byte) (int, time.Duration, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, h.URL, bytes.NewReader(body))
|
|
if err != nil {
|
|
return 0, 0, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("User-Agent", "Docwell-Webhooks/1")
|
|
req.Header.Set("X-Docwell-Event", p.Event)
|
|
req.Header.Set("X-Docwell-Delivery", p.ID)
|
|
req.Header.Set("X-Docwell-Signature", Sign(h.Secret, body))
|
|
start := time.Now()
|
|
res, err := d.client.Do(req)
|
|
dur := time.Since(start)
|
|
if err != nil {
|
|
if errors.Is(err, errBlocked) || strings.Contains(err.Error(), errBlocked.Error()) {
|
|
return 0, dur, errBlocked
|
|
}
|
|
return 0, dur, err
|
|
}
|
|
_, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 64<<10))
|
|
res.Body.Close()
|
|
return res.StatusCode, dur, nil
|
|
}
|
|
|
|
// Test sends a "ping" to webhook id right away (no retries) and returns the
|
|
// logged delivery.
|
|
func (d *Dispatcher) Test(ctx context.Context, id string) (Delivery, error) {
|
|
h, err := pocketbase.Get[hookRecord](ctx, d.pb, "webhooks", id)
|
|
if err != nil {
|
|
return Delivery{}, err
|
|
}
|
|
one := *d
|
|
one.opts.Retries = []time.Duration{}
|
|
p := Payload{ID: newID(), Event: "ping", Workspace: h.Workspace, Created: time.Now().UTC().Format(time.RFC3339),
|
|
Data: map[string]string{"message": "Hello from Docwell"}}
|
|
return one.deliver(ctx, h, p), nil
|
|
}
|
|
|
|
// Deliveries lists a webhook's latest deliveries, newest first.
|
|
func (d *Dispatcher) Deliveries(ctx context.Context, id string) ([]Delivery, error) {
|
|
res, err := pocketbase.List[deliveryRecord](ctx, d.pb, "webhook_deliveries", pocketbase.ListOptions{
|
|
PerPage: 50, Filter: fmt.Sprintf("webhook = '%s'", id), Sort: "-created,-id",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]Delivery, 0, len(res.Items))
|
|
for _, r := range res.Items {
|
|
out = append(out, r.view())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Prune deletes deliveries older than 30 days. It is a background job.
|
|
func (d *Dispatcher) Prune(ctx context.Context) error {
|
|
cutoff := time.Now().Add(-30 * 24 * time.Hour).UTC().Format("2006-01-02 15:04:05.000Z")
|
|
for {
|
|
res, err := pocketbase.List[deliveryRecord](ctx, d.pb, "webhook_deliveries", pocketbase.ListOptions{
|
|
PerPage: 500, Filter: fmt.Sprintf("created < '%s'", cutoff), Fields: "id",
|
|
})
|
|
if err != nil || len(res.Items) == 0 {
|
|
return err
|
|
}
|
|
for _, r := range res.Items {
|
|
if err := d.pb.Delete(ctx, "webhook_deliveries", r.ID); err != nil && !pocketbase.IsNotFound(err) {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|