// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "crypto/rand" "encoding/base64" "fmt" "log/slog" "net/url" "strings" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/auth" "docwell/server/internal/push" "docwell/server/internal/store/pocketbase" ) // ---- Invite links ---------------------------------------------------------- // // A workspace can have one invite link (ADR-17). Unlike an email invite it is // not tied to a person: whoever opens it signs in (or signs up, where signup // is open) and joins with the link's role. With approval on, opening it only // asks to join: the workspace's admins hear about the request and approve or // decline it, and the person hears back. Accounts without an organization // join the workspace's organization; accounts of other organizations and // superadmins cannot use a link, as with email invites. // JoinLink is a workspace's invite link, as its admins see it. type JoinLink struct { Token string `json:"token"` URL string `json:"url"` Role string `json:"role"` Approval bool `json:"approval"` // Expires is empty for a link that does not expire. Expires string `json:"expires"` Created string `json:"created"` // Pending counts the requests waiting for a decision. Pending int `json:"pending"` } type joinLinkRecord struct { ID string `json:"id"` Workspace string `json:"workspace"` Token string `json:"token"` Role string `json:"role"` Approval bool `json:"approval"` CreatedBy string `json:"created_by"` Expires string `json:"expires"` Created string `json:"created"` } func (r joinLinkRecord) expired(now time.Time) bool { if r.Expires == "" { return false } t, err := parsePBTime(r.Expires) return err == nil && now.After(t) } func (s *Service) joinLinkView(r joinLinkRecord, pending int) JoinLink { return JoinLink{ Token: r.Token, URL: strings.TrimRight(s.mailer.WebURL, "/") + "/join?token=" + url.QueryEscape(r.Token), Role: r.Role, Approval: r.Approval, Expires: r.Expires, Created: r.Created, Pending: pending, } } func (s *Service) joinLinkOf(ctx context.Context, wsID string) (joinLinkRecord, error) { res, err := pocketbase.List[joinLinkRecord](ctx, s.pb, "invite_links", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("workspace = '%s'", wsID), }) if err != nil || len(res.Items) == 0 { return joinLinkRecord{}, err } return res.Items[0], nil } // adminWorkspace loads a workspace c administers. func (s *Service) adminWorkspace(ctx context.Context, c access.Caller, wsID string) (workspaceRecord, string, error) { ws, role, err := s.workspaceFor(ctx, c, wsID) if err != nil { return ws, role, err } if !access.AtLeast(role, access.WorkspaceAdmin) { return ws, role, apperr.Forbidden("workspace admin role required") } return ws, role, nil } func (s *Service) pendingRequests(ctx context.Context, wsID string) (int, error) { return s.count(ctx, "invite_requests", fmt.Sprintf("workspace = '%s' && status = 'pending'", wsID)) } // GetJoinLink returns a workspace's invite link; ok is false when it has none // (workspace admin). func (s *Service) GetJoinLink(ctx context.Context, c access.Caller, wsID string) (JoinLink, bool, error) { ws, _, err := s.adminWorkspace(ctx, c, wsID) if err != nil { return JoinLink{}, false, err } rec, err := s.joinLinkOf(ctx, ws.ID) if err != nil || rec.ID == "" { return JoinLink{}, false, err } n, err := s.pendingRequests(ctx, ws.ID) return s.joinLinkView(rec, n), err == nil, err } type SetJoinLinkInput struct { // Role is member (default) or guest. Role string `json:"role"` Approval bool `json:"approval"` // ExpiresInDays is 1 to 365; 0 means the link does not expire. A change // counts from now. ExpiresInDays int `json:"expiresInDays"` // Reset makes a new URL; the old one stops working. Reset bool `json:"reset"` } // SetJoinLink creates or changes a workspace's invite link (workspace admin). // An existing link keeps its URL unless Reset is set. func (s *Service) SetJoinLink(ctx context.Context, c access.Caller, wsID string, in SetJoinLinkInput) (JoinLink, error) { ws, actorRole, err := s.adminWorkspace(ctx, c, wsID) if err != nil { return JoinLink{}, err } role := in.Role if role == "" { role = access.WorkspaceMember } if role != access.WorkspaceMember && role != access.WorkspaceGuest { return JoinLink{}, apperr.InvalidFields(map[string]string{"role": "Role must be member or guest."}) } if err := access.InviteToWorkspace(actorRole, role); err != nil { return JoinLink{}, err } if in.ExpiresInDays < 0 || in.ExpiresInDays > 365 { return JoinLink{}, apperr.InvalidFields(map[string]string{"expiresInDays": "Pick 1 to 365 days, or 0 for no end."}) } body := map[string]any{"role": role, "approval": in.Approval, "expires": ""} if in.ExpiresInDays > 0 { body["expires"] = pbTime(time.Now().Add(time.Duration(in.ExpiresInDays) * 24 * time.Hour)) } rec, err := s.joinLinkOf(ctx, ws.ID) if err != nil { return JoinLink{}, err } if rec.ID == "" || in.Reset { token, err := newJoinToken() if err != nil { return JoinLink{}, err } body["token"] = token } if rec.ID != "" { rec, err = pocketbase.Update[joinLinkRecord](ctx, s.pb, "invite_links", rec.ID, body) } else { body["workspace"], body["created_by"] = ws.ID, c.ID rec, err = pocketbase.Create[joinLinkRecord](ctx, s.pb, "invite_links", body) } if err != nil { return JoinLink{}, mapPB(err, "workspace not found") } n, err := s.pendingRequests(ctx, ws.ID) return s.joinLinkView(rec, n), err } func newJoinToken() (string, error) { b := make([]byte, 24) if _, err := rand.Read(b); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(b), nil } // DeleteJoinLink turns a workspace's invite link off; its URL stops working. // Requests already made stay for the admins to decide (workspace admin). func (s *Service) DeleteJoinLink(ctx context.Context, c access.Caller, wsID string) error { ws, _, err := s.adminWorkspace(ctx, c, wsID) if err != nil { return err } rec, err := s.joinLinkOf(ctx, ws.ID) if err != nil || rec.ID == "" { return err } return mapPB(s.pb.Delete(ctx, "invite_links", rec.ID), "workspace not found") } // openJoinLink finds a working link; unknown and expired tokens are both // auth.ErrInvalidToken. func (s *Service) openJoinLink(ctx context.Context, token string) (joinLinkRecord, workspaceRecord, error) { token = strings.TrimSpace(token) if len(token) < 24 || len(token) > 64 || !validID(token) { return joinLinkRecord{}, workspaceRecord{}, auth.ErrInvalidToken } res, err := pocketbase.List[joinLinkRecord](ctx, s.pb, "invite_links", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("token = '%s'", token), }) if err != nil { return joinLinkRecord{}, workspaceRecord{}, err } if len(res.Items) == 0 || res.Items[0].expired(time.Now()) { return joinLinkRecord{}, workspaceRecord{}, auth.ErrInvalidToken } ws, err := s.getWorkspace(ctx, res.Items[0].Workspace) if err != nil { return joinLinkRecord{}, workspaceRecord{}, auth.ErrInvalidToken } return res.Items[0], ws, nil } // JoinInfo is what the /join page shows. Status is the caller's standing: // "" (signed out or not asked yet), member, pending or declined. type JoinInfo struct { Workspace string `json:"workspace"` WorkspaceName string `json:"workspaceName"` OrganizationName string `json:"organizationName"` Role string `json:"role"` Approval bool `json:"approval"` Status string `json:"status"` } type joinRequestRecord struct { ID string `json:"id"` Workspace string `json:"workspace"` User string `json:"user"` Role string `json:"role"` Status string `json:"status"` ReviewedBy string `json:"reviewed_by"` ReviewedAt string `json:"reviewed_at"` Created string `json:"created"` } func (s *Service) joinRequestOf(ctx context.Context, wsID, userID string) (joinRequestRecord, error) { res, err := pocketbase.List[joinRequestRecord](ctx, s.pb, "invite_requests", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && user = '%s'", wsID, userID), }) if err != nil || len(res.Items) == 0 { return joinRequestRecord{}, err } return res.Items[0], nil } // GetJoinInfo describes a working invite link; me may be nil. func (s *Service) GetJoinInfo(ctx context.Context, me *auth.User, token string) (JoinInfo, error) { link, ws, err := s.openJoinLink(ctx, token) if err != nil { return JoinInfo{}, err } info := JoinInfo{Workspace: ws.ID, WorkspaceName: ws.Name, Role: link.Role, Approval: link.Approval} if ws.Expand.Organization != nil { info.OrganizationName = ws.Expand.Organization.Name } if me != nil { if info.Status, err = s.joinStatus(ctx, me.Caller(), ws); err != nil { return JoinInfo{}, err } } return info, nil } func (s *Service) joinStatus(ctx context.Context, c access.Caller, ws workspaceRecord) (string, error) { if role, err := s.effective(ctx, c, ws); err != nil { return "", err } else if role != "" { return "member", nil } req, err := s.joinRequestOf(ctx, ws.ID, c.ID) if err != nil { return "", err } switch req.Status { case "pending", "declined": return req.Status, nil } return "", nil } // JoinResult says what using a link did: "member" (joined, or was already // in) or "pending" (asked; an admin decides). type JoinResult struct { Status string `json:"status"` Workspace string `json:"workspace"` } // Join uses an invite link for the signed-in person. func (s *Service) Join(ctx context.Context, me auth.User, token string) (JoinResult, error) { link, ws, err := s.openJoinLink(ctx, token) if err != nil { return JoinResult{}, err } out := JoinResult{Workspace: ws.ID} status, err := s.joinStatus(ctx, me.Caller(), ws) if err != nil { return out, err } switch status { case "member", "pending": out.Status = status return out, nil } if err := access.AcceptInvite(me.Role, me.Organization, ws.Organization); err != nil { return out, err } if !link.Approval { if err := s.addJoiner(ctx, ws, me.ID, link.Role); err != nil { return out, err } out.Status = "member" return out, nil } // Asking again after a decline starts a new request. prev, err := s.joinRequestOf(ctx, ws.ID, me.ID) if err != nil { return out, err } body := map[string]any{"role": link.Role, "status": "pending", "reviewed_by": "", "reviewed_at": ""} if prev.ID != "" { _, err = pocketbase.Update[joinRequestRecord](ctx, s.pb, "invite_requests", prev.ID, body) } else { body["workspace"], body["user"] = ws.ID, me.ID _, err = pocketbase.Create[joinRequestRecord](ctx, s.pb, "invite_requests", body) } if err != nil { return out, mapPB(err, "workspace not found") } s.notifyWorkspace(ctx, ws, me.ID, s.workspaceAdmins(ctx, ws), NotifyJoinRequest) out.Status = "pending" return out, nil } // addJoiner moves an account without an organization into the workspace's // and makes it a member with role. func (s *Service) addJoiner(ctx context.Context, ws workspaceRecord, userID, role string) error { u, err := s.getUser(ctx, userID) if err != nil { return err } if err := access.AcceptInvite(u.Role, u.Organization, ws.Organization); err != nil { return err } if u.Organization != ws.Organization { if _, err := pocketbase.Update[auth.UserRecord](ctx, s.pb, "users", u.ID, map[string]any{ "organization": ws.Organization, "role": access.RoleUser, }); err != nil { return mapPB(err, "user not found") } } current, err := s.membership(ctx, ws.ID, u.ID) if err != nil { return err } if current.ID == "" { if _, err := pocketbase.Create[memberRecord](ctx, s.pb, "workspace_members", map[string]any{ "workspace": ws.ID, "user": u.ID, "role": role, }); err != nil { return mapPB(err, "workspace not found") } } s.forget(u.ID) return nil } // JoinRequest is a request to join, as admins see it. type JoinRequest struct { ID string `json:"id"` User MemberUser `json:"user"` Role string `json:"role"` Created string `json:"created"` } // ListJoinRequests lists the requests waiting for a decision, oldest first // (workspace admin). func (s *Service) ListJoinRequests(ctx context.Context, c access.Caller, wsID string) ([]JoinRequest, error) { ws, _, err := s.adminWorkspace(ctx, c, wsID) if err != nil { return nil, err } recs, err := listAll[joinRequestRecord](ctx, s, "invite_requests", pocketbase.ListOptions{ Filter: fmt.Sprintf("workspace = '%s' && status = 'pending'", ws.ID), Sort: "created", }) if err != nil { return nil, err } who := s.people() out := make([]JoinRequest, 0, len(recs)) for _, r := range recs { u := who.get(ctx, r.User) if u == nil { continue } out = append(out, JoinRequest{ID: r.ID, User: *u, Role: r.Role, Created: r.Created}) } return out, nil } // ReviewJoinRequest approves or declines a pending request (workspace admin) // and tells the person. role, when set, overrides the requested role on // approval. func (s *Service) ReviewJoinRequest(ctx context.Context, c access.Caller, wsID, id string, approve bool, role string) error { ws, actorRole, err := s.adminWorkspace(ctx, c, wsID) if err != nil { return err } if !validID(id) { return apperr.NotFound("request not found") } req, err := pocketbase.Get[joinRequestRecord](ctx, s.pb, "invite_requests", id) if err != nil || req.Workspace != ws.ID || req.Status != "pending" { return apperr.NotFound("request not found") } status := "declined" if approve { if role == "" { role = req.Role } if err := access.InviteToWorkspace(actorRole, role); err != nil { return err } if err := s.addJoiner(ctx, ws, req.User, role); err != nil { return err } status = "approved" } if _, err := pocketbase.Update[joinRequestRecord](ctx, s.pb, "invite_requests", req.ID, map[string]any{ "status": status, "reviewed_by": c.ID, "reviewed_at": pbTime(time.Now()), }); err != nil { return mapPB(err, "request not found") } kind := NotifyJoinDeclined if approve { kind = NotifyJoinApproved } s.notifyWorkspace(ctx, ws, c.ID, []string{req.User}, kind) return nil } // workspaceAdmins lists who hears about join requests: the workspace's // explicit admins and owners; when it has none, its organization's admins; // when the organization has none either, the superadmins. func (s *Service) workspaceAdmins(ctx context.Context, ws workspaceRecord) []string { members, err := listAll[memberRecord](ctx, s, "workspace_members", pocketbase.ListOptions{ Filter: fmt.Sprintf("workspace = '%s' && (role = 'admin' || role = 'owner')", ws.ID), }) if err != nil { slog.Default().Warn("join: list admins", "workspace", ws.ID, "err", err) return nil } var out []string for _, m := range members { out = append(out, m.User) } if len(out) > 0 { return out } for _, filter := range []string{ fmt.Sprintf("organization = '%s' && role = 'admin' && status != 'disabled'", ws.Organization), "role = 'superadmin' && status != 'disabled'", } { admins, err := listAll[auth.UserRecord](ctx, s, "users", pocketbase.ListOptions{Filter: filter, Fields: "id"}) if err != nil { slog.Default().Warn("join: list admins", "workspace", ws.ID, "err", err) return nil } for _, u := range admins { out = append(out, u.ID) } if len(out) > 0 { break } } return out } // notifyWorkspace stores a workspace notification (one without a page) for // each recipient and pushes it to their phones (best effort). func (s *Service) notifyWorkspace(ctx context.Context, ws workspaceRecord, actor string, to []string, kind string) { who := "Someone" if u, err := s.getUser(ctx, actor); err == nil { who = u.Name if who == "" { who = u.Email } } var body, route string switch kind { case NotifyJoinRequest: body, route = who+" asks to join", "/w/"+ws.ID+"/settings" case NotifyJoinApproved: body, route = "You can now open this workspace", "/" case NotifyJoinDeclined: body, route = "Your request to join was declined", "/" } for _, userID := range to { if userID == "" || userID == actor || !validID(userID) { continue } if _, err := pocketbase.Create[struct{}](ctx, s.pb, "notifications", map[string]any{ "user": userID, "workspace": ws.ID, "type": kind, "actor": actor, "excerpt": excerpt(ws.Name), }); err != nil { slog.Default().Warn("notify: create", "user", userID, "err", err) continue } if s.push != nil { s.push.Notify(userID, push.Message{Title: ws.Name, Body: body, Route: route}) } } }