Files
Docwell/Server/internal/webhooks/webhooks.go
T
tajniak81andClaude Opus 5.5 1f580ca6f8 Add Mobile 1.0 and UnifiedPush notifications
Mobile app (Android):
- Sign-in to any server, with authenticator codes. The server address and
  token are kept in secure storage; a dropped connection never signs out.
- Workspaces, recent pages, spaces and a foldable page tree; search; the
  inbox with mark-read.
- Pages open read-only in the shared editor from their saved content and
  join the live document to edit (with the native toolbar). Page links in
  the text open in the app (new "navigate" bridge message).
- Comments: threads, replies, resolve.
- "Save to Docwell" in the Android share sheet makes a page from shared
  text, with web addresses as links.
- Offline reading: every answer the app reads is kept on the phone, and
  used when the server can't be reached.
- Push through UnifiedPush (ntfy, NextPush, ...). The app uses the Android
  connector directly; the umbrella package pulls in a native crypto build
  for Linux that breaks `dart run` and tests.

Server:
- /me/devices registers a phone's UnifiedPush endpoint and Web Push keys
  (new push_devices collection). Each notification is also pushed,
  encrypted with RFC 8291 aes128gcm so the distributor can't read it; the
  app drops messages that don't decrypt. Endpoints answering 404/410 are
  forgotten. Endpoints follow the webhook address rules.
- /collab accepts the apps' own origins ("null" for the mobile editor page,
  wails:// for the desktop app). Sign-in is a token in the first message,
  not a cookie, so this opens no cross-site hijacking.

Tried on an Android 15 emulator: sign-in, browsing, reading, live editing,
sharing and offline reading. Not covered: push end to end (no distributor
on the emulator), iOS, and YouTube embeds, which refuse to play from the
app's local editor page (error 153).

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

362 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
}
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}
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
}
}
}
}