Sign-in:
- Google, GitHub, Microsoft and any OpenID Connect provider, set up in the
admin panel (secrets are write-only). PocketBase talks to the provider,
and docwell-server keeps the state and PKCE verifier. Accounts a
provider creates follow the sign-up switch and the domain list; refused
ones are removed again.
- Two-step sign-in with an authenticator app (TOTP), set up under "Your
account", with ten single-use recovery codes. After any first factor
(password, email code, provider) the session is held behind a
five-minute challenge: five tries, each code works once. Turning it off
needs a code. Managers can reset it for someone who lost their phone.
Both the web app and the admin panel ask for the code.
Integrations:
- Personal API tokens ("dw_…") that act as their owner, read-only or
read-write, with optional expiry. Only a hash is stored, and the token is
shown once. Tokens cannot manage tokens or two-step sign-in. Admins see
and can revoke their organization's tokens.
- Workspace webhooks for page, comment and space events. Deliveries are
HMAC-SHA256 signed and retried (10 s, 1 min, 5 min), with a 30-day log
and a test button. Loopback and link-local addresses are refused
(DOCWELL_WEBHOOKS_ALLOW_LOCAL is for development).
Audit log: sign-ins (including failures and second steps, filed under the
account's organization) and every successful change request, by route and
path ids, never bodies. Superadmins see everything and org admins their
organization. It is searchable and exportable as CSV in the admin panel's
new Security page, and kept for DOCWELL_AUDIT_RETENTION_DAYS (365).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
355 lines
10 KiB
Go
355 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",
|
|
"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
|
|
}
|
|
}
|
|
}
|
|
}
|