Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): add admin api for config, signups, email, branding

Hampus9d0a11e3d338
diff --git a/fluxer_rexctl/internal/adminapi/config.go b/fluxer_rexctl/internal/adminapi/config.go
new file mode 100644
index 000000000..8cb5a1638
--- /dev/null
+++ b/fluxer_rexctl/internal/adminapi/config.go
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package adminapi
+
+import (
+ "context"
+ _ "embed"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+)
+
+//go:embed configschema.json
+var configSchemaJSON []byte
+
+type ConfigKey struct {
+ Key string `json:"key"`
+ Type string `json:"type"`
+ Value any `json:"value"`
+ Default any `json:"default,omitempty"`
+ Help string `json:"help"`
+ Options []string `json:"options,omitempty"`
+ SecretSet string `json:"-"`
+ Nullable bool `json:"-"`
+}
+
+func ConfigSchema() ([]ConfigKey, error) {
+ var raw []struct {
+ Key string `json:"key"`
+ Type string `json:"type"`
+ Help string `json:"help"`
+ Default any `json:"default"`
+ Options []string `json:"options"`
+ SecretSet string `json:"secret_set"`
+ Nullable bool `json:"nullable"`
+ }
+ if err := json.Unmarshal(configSchemaJSON, &raw); err != nil {
+ return nil, fmt.Errorf("adminapi: config schema: %w", err)
+ }
+ keys := make([]ConfigKey, len(raw))
+ for i, r := range raw {
+ keys[i] = ConfigKey{Key: r.Key, Type: r.Type, Help: r.Help, Default: r.Default, Options: r.Options, SecretSet: r.SecretSet, Nullable: r.Nullable}
+ switch r.Key {
+ case RegistrationModeKey:
+ keys[i].Options = RegistrationModes
+ keys[i].Help = "Who can create an account. It works like rexctl registration set"
+ case registrationLinksKey:
+ keys[i].Help = "Whether invite links from admins still create accounts. rexctl registration set changes it for you"
+ }
+ }
+ return keys, nil
+}
+
+const (
+ RegistrationModeKey = "registration.mode"
+ registrationLinksKey = "registration.admin_registration_urls_enabled"
+)
+
+type UnknownKeyError struct {
+ Key string
+ Similar []string
+}
+
+func (e *UnknownKeyError) Error() string { return fmt.Sprintf("adminapi: no setting %q", e.Key) }
+
+func FindConfigKey(keys []ConfigKey, name string) (ConfigKey, error) {
+ name = strings.TrimSpace(name)
+ for _, k := range keys {
+ if k.Key == name {
+ return k, nil
+ }
+ }
+ e := &UnknownKeyError{Key: name}
+ last := name[strings.LastIndex(name, ".")+1:]
+ for _, k := range keys {
+ if last != "" && (strings.HasSuffix(k.Key, "."+last) || strings.Contains(k.Key, name)) {
+ e.Similar = append(e.Similar, k.Key)
+ }
+ }
+ return ConfigKey{}, e
+}
+
+func lookup(m map[string]any, path string) (any, bool) {
+ var cur any = m
+ for _, p := range strings.Split(path, ".") {
+ obj, ok := cur.(map[string]any)
+ if !ok {
+ return nil, false
+ }
+ cur, ok = obj[p]
+ if !ok {
+ return nil, false
+ }
+ }
+ return cur, true
+}
+
+func FillValues(keys []ConfigKey, cfg map[string]any) []ConfigKey {
+ out := make([]ConfigKey, len(keys))
+ for i, k := range keys {
+ if k.Type == "secret" {
+ v, _ := lookup(cfg, k.SecretSet)
+ set, _ := v.(bool)
+ k.Value = set
+ } else if v, ok := lookup(cfg, k.Key); ok {
+ k.Value = v
+ }
+ if links, _ := lookup(cfg, registrationLinksKey); k.Key == RegistrationModeKey && k.Value == "closed" && links == true {
+ k.Value = "invite"
+ }
+ out[i] = k
+ }
+ return out
+}
+
+func (c *Client) ConfigValues(ctx context.Context) ([]ConfigKey, error) {
+ keys, err := ConfigSchema()
+ if err != nil {
+ return nil, err
+ }
+ cfg, err := c.RawConfig(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return FillValues(keys, cfg), nil
+}
+
+type InvalidValueError struct {
+ Key ConfigKey
+ Want string
+}
+
+func (e *InvalidValueError) Error() string {
+ return fmt.Sprintf("adminapi: %s needs %s", e.Key.Key, e.Want)
+}
+
+func ParseConfigValue(k ConfigKey, value string) (any, error) {
+ switch k.Type {
+ case "integer":
+ n, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
+ if err != nil {
+ return nil, &InvalidValueError{Key: k, Want: "a whole number"}
+ }
+ return n, nil
+ case "number":
+ f, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
+ if err != nil {
+ return nil, &InvalidValueError{Key: k, Want: "a number"}
+ }
+ return f, nil
+ case "boolean":
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "true", "on", "yes", "1":
+ return true, nil
+ case "false", "off", "no", "0":
+ return false, nil
+ }
+ return nil, &InvalidValueError{Key: k, Want: "true or false"}
+ case "list":
+ items := []string{}
+ for _, part := range strings.Split(value, ",") {
+ if part = strings.TrimSpace(part); part != "" {
+ items = append(items, part)
+ }
+ }
+ return items, nil
+ case "json":
+ var v any
+ if err := json.Unmarshal([]byte(value), &v); err != nil {
+ return nil, &InvalidValueError{Key: k, Want: "JSON"}
+ }
+ return v, nil
+ }
+ if len(k.Options) > 0 && !slices.Contains(k.Options, value) {
+ return nil, &InvalidValueError{Key: k, Want: "one of " + JoinOr(k.Options)}
+ }
+ return value, nil
+}
+
+func ConfigPatch(key string, value any) map[string]any {
+ parts := strings.Split(key, ".")
+ root := map[string]any{}
+ cur := root
+ for _, p := range parts[:len(parts)-1] {
+ next := map[string]any{}
+ cur[p] = next
+ cur = next
+ }
+ cur[parts[len(parts)-1]] = value
+ return root
+}
+
+func MergePatch(dst, src map[string]any) {
+ for k, v := range src {
+ sub, ok := v.(map[string]any)
+ if have, exists := dst[k].(map[string]any); ok && exists {
+ MergePatch(have, sub)
+ continue
+ }
+ dst[k] = v
+ }
+}
+
+func FormatValue(k ConfigKey) string {
+ if k.Type == "secret" {
+ if set, _ := k.Value.(bool); set {
+ return "set"
+ }
+ return "not set"
+ }
+ switch v := k.Value.(type) {
+ case nil:
+ return ""
+ case string:
+ return v
+ case bool:
+ return strconv.FormatBool(v)
+ case float64:
+ return strconv.FormatFloat(v, 'f', -1, 64)
+ case []string:
+ return strings.Join(v, ", ")
+ case []any:
+ if all := scalarList(v); all != nil {
+ return strings.Join(all, ", ")
+ }
+ }
+ data, err := json.Marshal(k.Value)
+ if err != nil {
+ return fmt.Sprint(k.Value)
+ }
+ return string(data)
+}
+
+func scalarList(v []any) []string {
+ out := make([]string, 0, len(v))
+ for _, item := range v {
+ s, ok := item.(string)
+ if !ok {
+ return nil
+ }
+ out = append(out, s)
+ }
+ return out
+}
diff --git a/fluxer_rexctl/internal/adminapi/instance.go b/fluxer_rexctl/internal/adminapi/instance.go
new file mode 100644
index 000000000..de3ccb792
--- /dev/null
+++ b/fluxer_rexctl/internal/adminapi/instance.go
@@ -0,0 +1,341 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package adminapi
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+const configPath = "/admin/instance/config"
+
+func (c *Client) Config(ctx context.Context) (*InstanceConfigResponse, error) {
+ var resp InstanceConfigResponse
+ if err := c.Call(ctx, http.MethodGet, configPath, nil, nil, &resp); err != nil {
+ return nil, err
+ }
+ return &resp, nil
+}
+
+func (c *Client) RawConfig(ctx context.Context) (map[string]any, error) {
+ var resp map[string]any
+ if err := c.Call(ctx, http.MethodGet, configPath, nil, nil, &resp); err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+func (c *Client) PatchConfig(ctx context.Context, patch any) error {
+ return c.Call(ctx, http.MethodPatch, configPath, nil, patch, nil)
+}
+
+var RegistrationModes = []string{"open", "approval", "invite", "closed"}
+
+func RegistrationPatch(mode string) (map[string]any, error) {
+ var apiMode string
+ links := true
+ switch mode {
+ case "open", "approval":
+ apiMode = mode
+ case "invite":
+ apiMode = "closed"
+ case "closed":
+ apiMode = "closed"
+ links = false
+ default:
+ return nil, fmt.Errorf("adminapi: unknown registration mode %q", mode)
+ }
+ return map[string]any{"registration": map[string]any{
+ "mode": apiMode,
+ "admin_registration_urls_enabled": links,
+ }}, nil
+}
+
+type Invite struct {
+ ID string `json:"id"`
+ URL string `json:"url"`
+ Label string `json:"label,omitempty"`
+ Uses int `json:"uses"`
+ MaxUses *int `json:"max_uses"`
+ ExpiresAt *string `json:"expires_at"`
+ CreatedAt string `json:"created_at"`
+}
+
+func InviteURL(origin, id string) string {
+ return strings.TrimRight(origin, "/") + "/register?registration_url=" + url.QueryEscape(id)
+}
+
+func rfc3339(t *time.Time) *string {
+ if t == nil {
+ return nil
+ }
+ s := t.UTC().Format(time.RFC3339)
+ return &s
+}
+
+func (c *Client) ListInvites(ctx context.Context, origin string) ([]Invite, error) {
+ cfg, err := c.Config(ctx)
+ if err != nil {
+ return nil, err
+ }
+ out := []Invite{}
+ now := time.Now()
+ for _, u := range cfg.Registration.Urls {
+ if u.RevokedAt != nil {
+ continue
+ }
+ if u.ExpiresAt != nil && u.ExpiresAt.Before(now) {
+ continue
+ }
+ inv := Invite{
+ ID: u.Id,
+ URL: InviteURL(origin, u.Id),
+ Uses: u.UseCount,
+ MaxUses: u.MaxUses,
+ ExpiresAt: rfc3339(u.ExpiresAt),
+ CreatedAt: u.CreatedAt.UTC().Format(time.RFC3339),
+ }
+ if u.Label != nil {
+ inv.Label = *u.Label
+ }
+ out = append(out, inv)
+ }
+ return out, nil
+}
+
+type InviteOptions struct {
+ Uses int
+ Expires time.Duration
+ Label string
+}
+
+func (c *Client) CreateInvite(ctx context.Context, opts InviteOptions) (*Invite, error) {
+ req := CreateRegistrationUrlRequest{}
+ if opts.Uses > 0 {
+ uses := opts.Uses
+ req.MaxUses = &uses
+ }
+ if opts.Expires > 0 {
+ at := time.Now().Add(opts.Expires).UTC().Truncate(time.Second)
+ req.ExpiresAt = &at
+ }
+ if opts.Label != "" {
+ label := opts.Label
+ req.Label = &label
+ }
+ var resp CreateRegistrationUrlResponse
+ if err := c.Call(ctx, http.MethodPost, "/admin/instance/registration-urls", nil, req, &resp); err != nil {
+ return nil, err
+ }
+ u := resp.RegistrationUrl
+ inv := &Invite{
+ ID: u.Id,
+ URL: resp.Url,
+ Uses: u.UseCount,
+ MaxUses: u.MaxUses,
+ ExpiresAt: rfc3339(u.ExpiresAt),
+ CreatedAt: u.CreatedAt.UTC().Format(time.RFC3339),
+ }
+ if u.Label != nil {
+ inv.Label = *u.Label
+ }
+ return inv, nil
+}
+
+type InviteNotFoundError struct{ ID string }
+
+func (e *InviteNotFoundError) Error() string { return fmt.Sprintf("adminapi: no invite %q", e.ID) }
+
+func (c *Client) RevokeInvite(ctx context.Context, id string) error {
+ cfg, err := c.Config(ctx)
+ if err != nil {
+ return err
+ }
+ for _, u := range cfg.Registration.Urls {
+ if u.Id != id {
+ continue
+ }
+ if u.RevokedAt != nil {
+ return nil
+ }
+ return c.Call(ctx, http.MethodDelete, "/admin/instance/registration-urls/"+url.PathEscape(id), nil, nil, nil)
+ }
+ return &InviteNotFoundError{ID: id}
+}
+
+type PendingRegistration struct {
+ ID string `json:"id"`
+ Username string `json:"username"`
+ Email string `json:"email,omitempty"`
+ RequestedAt string `json:"requested_at"`
+}
+
+func (c *Client) PendingRegistrations(ctx context.Context) ([]PendingRegistration, error) {
+ var resp PendingRegistrationListResponse
+ if err := c.Call(ctx, http.MethodGet, "/admin/instance/pending-registrations", nil, nil, &resp); err != nil {
+ return nil, err
+ }
+ out := []PendingRegistration{}
+ for _, p := range resp.PendingRegistrations {
+ pr := PendingRegistration{ID: p.UserId, Username: p.Username, RequestedAt: p.RequestedAt.UTC().Format(time.RFC3339)}
+ if p.Email != nil {
+ pr.Email = *p.Email
+ }
+ out = append(out, pr)
+ }
+ return out, nil
+}
+
+type PendingNotFoundError struct{ ID string }
+
+func (e *PendingNotFoundError) Error() string {
+ return fmt.Sprintf("adminapi: no pending registration %q", e.ID)
+}
+
+func (c *Client) ReviewRegistration(ctx context.Context, id string, approve bool) (*PendingRegistration, error) {
+ pending, err := c.PendingRegistrations(ctx)
+ if err != nil {
+ return nil, err
+ }
+ var found *PendingRegistration
+ for i := range pending {
+ if pending[i].ID == id || strings.EqualFold(pending[i].Username, id) {
+ found = &pending[i]
+ break
+ }
+ }
+ if found == nil {
+ return nil, &PendingNotFoundError{ID: id}
+ }
+ status := Rejected
+ if approve {
+ status = Approved
+ }
+ req := PendingRegistrationActionRequest{Status: status}
+ if err := c.Call(ctx, http.MethodPatch, "/admin/instance/pending-registrations/"+url.PathEscape(found.ID), nil, req, nil); err != nil {
+ return nil, err
+ }
+ return found, nil
+}
+
+type SMTPSettings struct {
+ Host string
+ Port int
+ TLS string
+ Username string
+ Password string
+ FromName string
+ FromAddr string
+}
+
+var TLSModes = []string{"starttls", "implicit", "opportunistic", "none"}
+
+func TLSModeFor(port int) string {
+ if port == 465 {
+ return "implicit"
+ }
+ return "starttls"
+}
+
+func StartTLSFailed(message string) bool {
+ return strings.Contains(strings.ToLower(message), "starttls")
+}
+
+func (c *Client) SavedTLSMode(ctx context.Context, host string, port int) (string, error) {
+ cfg, err := c.RawConfig(ctx)
+ if err != nil {
+ return "", err
+ }
+ savedHost, _ := lookup(cfg, "integrations.email.smtp.host")
+ savedPort, _ := lookup(cfg, "integrations.email.smtp.port")
+ mode, _ := lookup(cfg, "integrations.email.smtp.tls_mode")
+ h, _ := savedHost.(string)
+ n, _ := savedPort.(float64)
+ m, _ := mode.(string)
+ if !strings.EqualFold(h, host) || int(n) != port {
+ return "", nil
+ }
+ return m, nil
+}
+
+func (c *Client) SetSMTP(ctx context.Context, s SMTPSettings) error {
+ tls := s.TLS
+ if tls == "" {
+ tls = TLSModeFor(s.Port)
+ }
+ smtp := map[string]any{
+ "host": s.Host,
+ "port": s.Port,
+ "tls_mode": tls,
+ "username": s.Username,
+ }
+ if s.Password != "" {
+ smtp["password"] = s.Password
+ }
+ email := map[string]any{
+ "delivery": "smtp",
+ "from_email": s.FromAddr,
+ "smtp": smtp,
+ }
+ if s.FromName != "" {
+ email["from_name"] = s.FromName
+ }
+ return c.PatchConfig(ctx, map[string]any{"integrations": map[string]any{"email": email}})
+}
+
+func (c *Client) EmailOff(ctx context.Context) error {
+ return c.PatchConfig(ctx, map[string]any{"integrations": map[string]any{"email": map[string]any{"delivery": "off"}}})
+}
+
+type SMTPTestResult struct {
+ OK bool
+ Error string
+ ServerResponse string
+}
+
+func (c *Client) TestSMTP(ctx context.Context, sendTo string) (*SMTPTestResult, error) {
+ req := InstanceEmailSmtpTestRequest{}
+ if sendTo != "" {
+ to := EmailType(sendTo)
+ req.SendTo = &to
+ }
+ var resp InstanceEmailSmtpTestResponse
+ if err := c.Call(ctx, http.MethodPost, "/admin/instance/config/smtp-tests", nil, req, &resp); err != nil {
+ return nil, err
+ }
+ out := &SMTPTestResult{OK: resp.Ok}
+ if resp.Error != nil {
+ out.Error = *resp.Error
+ }
+ if resp.ServerResponse != nil {
+ out.ServerResponse = *resp.ServerResponse
+ }
+ return out, nil
+}
+
+func (c *Client) UploadBranding(ctx context.Context, kind BrandingAssetUploadRequestKind, image []byte) error {
+ data := base64.StdEncoding.EncodeToString(image)
+ req := BrandingAssetUploadRequest{Kind: kind, Image: &data}
+ var resp json.RawMessage
+ return c.Call(ctx, http.MethodPost, "/admin/instance/config/branding-assets", nil, req, &resp)
+}
+
+func (c *Client) SetBranding(ctx context.Context, name, colour string) error {
+ branding := map[string]any{}
+ if name != "" {
+ branding["product_name"] = name
+ }
+ if colour != "" {
+ branding["theme_color"] = colour
+ }
+ if len(branding) == 0 {
+ return nil
+ }
+ return c.PatchConfig(ctx, map[string]any{"app_public": map[string]any{"branding": branding}})
+}