Editor:
- Toggles (Tiptap Details). Open state is per reader, not saved.
- Embeds for YouTube, Vimeo, Loom, Figma, CodePen, Spotify, Google Docs
and Maps, in sandboxed frames. Other addresses become link cards.
- Link cards with title, description and picture read by docwell-server
(GET /link-preview). The fetcher refuses private, loopback, link-local
and CGNAT addresses after DNS resolution, redirects included.
- Block links: a margin button gives a block a short id and copies
/p/<id>#b-<block>. Opening one jumps to the block and flashes it.
- Markdown, HTML and PDF exports handle the new blocks; HTML import reads
<details> as a toggle.
Pages and spaces:
- History gets a Changes view: block and word diff against the previous
version or the page as it is now.
- Archive: archived pages leave the tree and become read-only but stay
readable; a space's Archive lists them with Unarchive. New migration
(pages.archived_at) and page.archived / page.unarchived webhook events.
- Full space export (GET /spaces/{id}/export): a zip of Markdown or HTML
files with subpages in folders, an index, and attachments under _files/.
Links between exported pages and to attachments become relative paths.
Desktop 1.0:
- Several servers, each with its own sign-in; old settings files carry over.
- Session tokens in the system keychain (go-keyring), moved out of
localStorage on first start.
- Native menu bar (File, Edit, View, Window, Help) with a Server submenu.
- docwell:// links may point at a block.
- Release workflow builds Windows NSIS, macOS DMG and Linux deb, rpm and
AppImage installers and attaches them to the release;
build/set-version.mjs stamps the version into their metadata.
Not yet run: the release workflow, the desktop menus by eye, and macOS or
Linux builds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
356 lines
10 KiB
Go
356 lines
10 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
|
|
}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
}
|
|
}
|
|
}
|