// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "crypto/rand" "encoding/hex" "fmt" "net/url" "strings" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/store/pocketbase" "docwell/server/internal/webhooks" ) // ---- Webhooks -------------------------------------------------------------- // // Workspace admins register URLs that hear about the workspace's pages, // comments and spaces (see package webhooks for delivery). // WebhookSender is the part of webhooks.Dispatcher this package uses. type WebhookSender interface { Emit(workspace, event string, data any) Test(ctx context.Context, id string) (webhooks.Delivery, error) Deliveries(ctx context.Context, id string) ([]webhooks.Delivery, error) } // UseWebhooks enables webhooks. func (s *Service) UseWebhooks(w WebhookSender) { s.hooks = w } type Webhook struct { ID string `json:"id"` Name string `json:"name"` URL string `json:"url"` Events []string `json:"events"` Active bool `json:"active"` // Secret signs deliveries; it is only returned when the webhook is created. Secret string `json:"secret,omitempty"` Created string `json:"created"` } type webhookRecord struct { ID string `json:"id"` Workspace string `json:"workspace"` Name string `json:"name"` URL string `json:"url"` Secret string `json:"secret"` Events []string `json:"events"` Active bool `json:"active"` Created string `json:"created"` } func (r webhookRecord) view() Webhook { events := r.Events if events == nil { events = []string{} } return Webhook{ID: r.ID, Name: r.Name, URL: r.URL, Events: events, Active: r.Active, Created: r.Created} } // WebhookInput changes only the fields that are set. type WebhookInput struct { Name *string `json:"name"` URL *string `json:"url"` Events *[]string `json:"events"` Active *bool `json:"active"` } func (in WebhookInput) patch(creating bool) (map[string]any, error) { patch := map[string]any{} fields := map[string]string{} if in.Name != nil { name := strings.TrimSpace(*in.Name) if len(name) > 100 { fields["name"] = "Name is too long (max 100)." } patch["name"] = name } if in.URL != nil || creating { raw := "" if in.URL != nil { raw = strings.TrimSpace(*in.URL) } u, err := url.Parse(raw) if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || u.User != nil { fields["url"] = "Enter an http:// or https:// address." } patch["url"] = raw } if in.Events != nil || creating { events := []string{"*"} if in.Events != nil { events = *in.Events } if len(events) == 0 { fields["events"] = "Pick at least one event." } for _, e := range events { if !webhooks.ValidEvent(e) { fields["events"] = "Unknown event: " + e } } patch["events"] = events } if in.Active != nil { patch["active"] = *in.Active } else if creating { patch["active"] = true } if len(fields) > 0 { return nil, apperr.InvalidFields(fields) } return patch, nil } func (s *Service) webhookFor(ctx context.Context, c access.Caller, id string) (webhookRecord, error) { if !validID(id) { return webhookRecord{}, apperr.NotFound("webhook not found") } h, err := pocketbase.Get[webhookRecord](ctx, s.pb, "webhooks", id) if err != nil { return h, mapPB(err, "webhook not found") } _, role, err := s.workspaceFor(ctx, c, h.Workspace) if err != nil { return h, apperr.NotFound("webhook not found") } if err := access.ManageWebhooks(role); err != nil { return h, err } return h, nil } // ListWebhooks lists a workspace's webhooks (workspace admin). func (s *Service) ListWebhooks(ctx context.Context, c access.Caller, wsID string) ([]Webhook, error) { ws, role, err := s.workspaceFor(ctx, c, wsID) if err != nil { return nil, err } if err := access.ManageWebhooks(role); err != nil { return nil, err } recs, err := listAll[webhookRecord](ctx, s, "webhooks", pocketbase.ListOptions{ Filter: fmt.Sprintf("workspace = '%s'", ws.ID), Sort: "created", }) if err != nil { return nil, err } out := make([]Webhook, 0, len(recs)) for _, r := range recs { out = append(out, r.view()) } return out, nil } // CreateWebhook adds a webhook (workspace admin); the result carries its secret. func (s *Service) CreateWebhook(ctx context.Context, c access.Caller, wsID string, in WebhookInput) (Webhook, error) { ws, role, err := s.workspaceFor(ctx, c, wsID) if err != nil { return Webhook{}, err } if err := access.ManageWebhooks(role); err != nil { return Webhook{}, err } n, err := s.count(ctx, "webhooks", fmt.Sprintf("workspace = '%s'", ws.ID)) if err != nil { return Webhook{}, err } if n >= 20 { return Webhook{}, apperr.Invalid("a workspace can have up to 20 webhooks") } patch, err := in.patch(true) if err != nil { return Webhook{}, err } secret := make([]byte, 24) _, _ = rand.Read(secret) patch["workspace"], patch["secret"], patch["created_by"] = ws.ID, "whsec_"+hex.EncodeToString(secret), c.ID rec, err := pocketbase.Create[webhookRecord](ctx, s.pb, "webhooks", patch) if err != nil { return Webhook{}, mapPB(err, "webhook not found") } out := rec.view() out.Secret = rec.Secret return out, nil } // UpdateWebhook changes a webhook (workspace admin). func (s *Service) UpdateWebhook(ctx context.Context, c access.Caller, id string, in WebhookInput) (Webhook, error) { h, err := s.webhookFor(ctx, c, id) if err != nil { return Webhook{}, err } patch, err := in.patch(false) if err != nil { return Webhook{}, err } if len(patch) == 0 { return h.view(), nil } rec, err := pocketbase.Update[webhookRecord](ctx, s.pb, "webhooks", h.ID, patch) if err != nil { return Webhook{}, mapPB(err, "webhook not found") } return rec.view(), nil } // DeleteWebhook removes a webhook and its delivery log (workspace admin). func (s *Service) DeleteWebhook(ctx context.Context, c access.Caller, id string) error { h, err := s.webhookFor(ctx, c, id) if err != nil { return err } return mapPB(s.pb.Delete(ctx, "webhooks", h.ID), "webhook not found") } // WebhookDeliveries lists a webhook's latest deliveries (workspace admin). func (s *Service) WebhookDeliveries(ctx context.Context, c access.Caller, id string) ([]webhooks.Delivery, error) { h, err := s.webhookFor(ctx, c, id) if err != nil { return nil, err } if s.hooks == nil { return []webhooks.Delivery{}, nil } return s.hooks.Deliveries(ctx, h.ID) } // TestWebhook sends a "ping" right away and returns the delivery (workspace admin). func (s *Service) TestWebhook(ctx context.Context, c access.Caller, id string) (webhooks.Delivery, error) { h, err := s.webhookFor(ctx, c, id) if err != nil { return webhooks.Delivery{}, err } if s.hooks == nil { return webhooks.Delivery{}, apperr.Invalid("webhooks are turned off on this server") } return s.hooks.Test(ctx, h.ID) } // ---- Events ---------------------------------------------------------------- type eventPage struct { ID string `json:"id"` Title string `json:"title"` Icon string `json:"icon"` Space string `json:"space"` Workspace string `json:"workspace"` Parent string `json:"parent"` URL string `json:"url"` } func (s *Service) eventPage(p pageRecord) eventPage { return eventPage{ ID: p.ID, Title: p.Title, Icon: p.Icon, Space: p.Space, Workspace: p.Workspace, Parent: p.Parent, URL: strings.TrimRight(s.mailer.WebURL, "/") + "/p/" + p.ID, } } // actorRef names who did something in an event. func (s *Service) actorRef(ctx context.Context, userID string) any { if userID == "" { return nil } if u, err := s.getUser(ctx, userID); err == nil { return map[string]string{"id": u.ID, "name": u.Name, "email": u.Email} } return map[string]string{"id": userID} } // emitPage sends a page event to the workspace's webhooks. func (s *Service) emitPage(ctx context.Context, event string, p pageRecord, actor string, extra map[string]any) { if s.hooks == nil { return } data := map[string]any{"page": s.eventPage(p), "actor": s.actorRef(ctx, actor)} for k, v := range extra { data[k] = v } s.hooks.Emit(p.Workspace, event, data) } // emitSpace sends a space event to the workspace's webhooks. func (s *Service) emitSpace(ctx context.Context, event string, sp spaceRecord, actor string) { if s.hooks == nil { return } s.hooks.Emit(sp.Workspace, event, map[string]any{ "space": map[string]string{"id": sp.ID, "name": sp.Name, "slug": sp.Slug, "workspace": sp.Workspace}, "actor": s.actorRef(ctx, actor), }) }