Debian Codegraph @

pkg/services/chat/xmpp/xmpp_config.go

raw
1 package xmpp
2
3 import (
4 "fmt"
5 "net"
6 "net/url"
7 "slices"
8 "strconv"
9 "strings"
10
11 "github.com/nicholas-fedor/shoutrrr/pkg/format"
12 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
13 "github.com/nicholas-fedor/shoutrrr/pkg/types"
14 "github.com/nicholas-fedor/shoutrrr/pkg/util"
15 )
16
17 // Config holds settings for the XMPP notification service.
18 type Config struct {
19 standard.EnumlessConfig
20
21 // Host is the XMPP server hostname used for the TCP dial.
22 Host string `desc:"XMPP server hostname" url:"Host"`
23 // Port is the XMPP server port.
24 Port uint16 `desc:"XMPP server port" url:"Port"`
25 // User is the auth JID localpart or a full JID (local@domain).
26 User string `desc:"Auth JID localpart or full JID" url:"User"`
27 // Password is the SASL password.
28 Password string `desc:"Auth password" sensitive:"true" url:"Pass"`
29 // To is the list of 1:1 chat recipient JIDs.
30 To []string `desc:"Chat recipient JIDs" key:"to" optional:""`
31 // Rooms is the list of MUC room JIDs.
32 Rooms []string `desc:"MUC room JIDs" key:"rooms" optional:""`
33 // Nick is the MUC nickname. Empty uses the auth JID localpart.
34 Nick string `desc:"MUC nickname" key:"nick" optional:""`
35 // RoomPassword is sent when joining password-protected rooms.
36 RoomPassword string `desc:"Password for protected MUC rooms" key:"roompassword" optional:"" sensitive:"true"`
37 // Title is prepended to the message body when set.
38 Title string `desc:"Optional title prepended to the message body" key:"title" optional:""`
39 // DisableTLS disables encryption. Allowed only on xmpp://.
40 DisableTLS bool `default:"No" desc:"Disable TLS (xmpp:// only)" key:"disabletls"`
41 // SkipTLSVerify skips TLS certificate verification.
42 SkipTLSVerify bool `default:"No" desc:"Skip TLS certificate verification" key:"skiptlsverify"`
43
44 // scheme is the URL scheme used to build GetURL, either [Scheme] or [SchemeTLS].
45 scheme string
46 }
47
48 const (
49 // Scheme identifies STARTTLS XMPP URLs.
50 Scheme = "xmpp"
51 // SchemeTLS identifies implicit-TLS XMPP URLs.
52 SchemeTLS = "xmpps"
53 // DefaultPort is the standard XMPP c2s port.
54 DefaultPort uint16 = 5222
55 // DefaultTLSPort is the standard XMPP implicit-TLS c2s port.
56 DefaultTLSPort uint16 = 5223
57 // Resource is the resource bound on the XMPP session.
58 Resource = "shoutrrr"
59 )
60
61 // Clone returns a copy of the config with independent target lists.
62 //
63 // Returns:
64 // - A copy of the configuration.
65 func (c *Config) Clone() Config {
66 clone := *c
67 clone.To = slices.Clone(c.To)
68 clone.Rooms = slices.Clone(c.Rooms)
69
70 return clone
71 }
72
73 // GetURL returns a URL representation of the current field values.
74 //
75 // Returns:
76 // - A configuration URL using the stored scheme.
77 func (c *Config) GetURL() *url.URL {
78 resolver := format.NewPropKeyResolver(c)
79
80 return c.getURL(&resolver)
81 }
82
83 // SetURL updates the configuration from a URL representation.
84 //
85 // Parameters:
86 // - serviceURL: The XMPP configuration URL to parse.
87 //
88 // Returns:
89 // - An error if the URL is invalid or required fields are missing.
90 func (c *Config) SetURL(serviceURL *url.URL) error {
91 next := Config{}
92 resolver := format.NewPropKeyResolver(&next)
93
94 if err := resolver.SetDefaultProps(&next); err != nil {
95 return fmt.Errorf("setting default props: %w", err)
96 }
97
98 if err := next.setURL(&resolver, serviceURL); err != nil {
99 return err
100 }
101
102 *c = next
103
104 return nil
105 }
106
107 // authJIDString returns the SASL auth JID.
108 //
109 // A userinfo value that already contains @ is used as-is. Otherwise the JID is
110 // localpart@host.
111 //
112 // Returns:
113 // - The auth JID string.
114 func (c *Config) authJIDString() string {
115 if strings.Contains(c.User, "@") {
116 return c.User
117 }
118
119 return c.User + "@" + c.Host
120 }
121
122 // getURL constructs a URL from the Config fields using the provided resolver.
123 //
124 // Parameters:
125 // - resolver: Resolver used to serialize configuration query keys.
126 //
127 // Returns:
128 // - A configuration URL using the stored scheme and default port when unset.
129 func (c *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
130 scheme := c.scheme
131 if scheme == "" {
132 scheme = Scheme
133 }
134
135 port := c.Port
136 if port == 0 {
137 port = defaultPort(scheme)
138 }
139
140 result := &url.URL{
141 Scheme: scheme,
142 Host: net.JoinHostPort(c.Host, strconv.FormatUint(uint64(port), 10)),
143 ForceQuery: true,
144 RawQuery: format.BuildQuery(resolver),
145 }
146
147 if c.User != "" {
148 result.User = util.URLUserPassword(c.User, c.Password)
149 }
150
151 return result
152 }
153
154 // implicitTLS reports whether the URL uses xmpps:// implicit TLS.
155 //
156 // Returns:
157 // - true when the stored scheme is [SchemeTLS].
158 func (c *Config) implicitTLS() bool {
159 return c.scheme == SchemeTLS
160 }
161
162 // mucNick returns the nickname used when joining MUC rooms.
163 //
164 // An explicit [Config.Nick] wins. Otherwise the auth JID localpart is used,
165 // falling back to [Resource] if the JID cannot be split.
166 //
167 // Returns:
168 // - The MUC nickname.
169 func (c *Config) mucNick() string {
170 if c.Nick != "" {
171 return c.Nick
172 }
173
174 local, _, err := splitJID(c.authJIDString())
175 if err != nil {
176 return Resource
177 }
178
179 return local
180 }
181
182 // setURL updates the configuration from a URL representation.
183 //
184 // Dummy docs URLs (host dummy.com) skip credential and target validation so
185 // generated documentation can initialize the service.
186 //
187 // Parameters:
188 // - resolver: Resolver used to apply query keys onto the config.
189 // - serviceURL: The XMPP configuration URL to parse.
190 //
191 // Returns:
192 // - An error if the URL is invalid or required fields are missing.
193 func (c *Config) setURL(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
194 dummy := isDummyURL(serviceURL)
195
196 c.scheme = serviceURL.Scheme
197 if c.scheme == "" {
198 c.scheme = Scheme
199 }
200
201 if c.scheme != Scheme && c.scheme != SchemeTLS {
202 return fmt.Errorf("%w: %s", ErrUnsupportedScheme, c.scheme)
203 }
204
205 if serviceURL.User != nil {
206 c.User = serviceURL.User.Username()
207 if password, ok := serviceURL.User.Password(); ok {
208 c.Password = password
209 }
210 }
211
212 c.Host = serviceURL.Hostname()
213
214 if port := serviceURL.Port(); port != "" {
215 parsed, err := strconv.ParseUint(port, 10, 16)
216 if err != nil {
217 return fmt.Errorf("parsing port: %w", err)
218 }
219
220 c.Port = uint16(parsed)
221 } else {
222 c.Port = defaultPort(c.scheme)
223 }
224
225 for key, vals := range serviceURL.Query() {
226 if err := resolver.Set(key, vals[0]); err != nil {
227 return fmt.Errorf("setting query parameter %q to %q: %w", key, vals[0], err)
228 }
229 }
230
231 c.To = compactStrings(c.To)
232 c.Rooms = compactStrings(c.Rooms)
233
234 if dummy {
235 return nil
236 }
237
238 return c.validate()
239 }
240
241 // useTLS reports whether the session should encrypt the stream.
242 //
243 // Returns:
244 // - false only when [Config.DisableTLS] is set.
245 func (c *Config) useTLS() bool {
246 return !c.DisableTLS
247 }
248
249 // validate checks that required fields and JIDs are present and consistent.
250 //
251 // Returns:
252 // - An error describing the first invalid field.
253 func (c *Config) validate() error {
254 if c.Host == "" {
255 return ErrMissingHost
256 }
257
258 if c.User == "" {
259 return ErrMissingUser
260 }
261
262 if c.Password == "" {
263 return ErrMissingPassword
264 }
265
266 if c.DisableTLS && c.scheme == SchemeTLS {
267 return ErrDisableTLSOnXMPPS
268 }
269
270 if len(c.To) == 0 && len(c.Rooms) == 0 {
271 return ErrMissingTargets
272 }
273
274 if strings.Contains(c.User, "@") {
275 if err := validateJID(c.User); err != nil {
276 return fmt.Errorf("%w: %s", ErrInvalidUserJID, c.User)
277 }
278 }
279
280 for _, to := range c.To {
281 if err := validateJID(to); err != nil {
282 return fmt.Errorf("%w: %s", ErrInvalidRecipientJID, to)
283 }
284 }
285
286 for _, room := range c.Rooms {
287 if err := validateJID(room); err != nil {
288 return fmt.Errorf("%w: %s", ErrInvalidRoomJID, room)
289 }
290 }
291
292 return nil
293 }
294
295 // compactStrings removes empty entries from values.
296 //
297 // Parameters:
298 // - values: The slice to compact.
299 //
300 // Returns:
301 // - A slice with empty strings removed, or nil when none remain.
302 func compactStrings(values []string) []string {
303 values = slices.DeleteFunc(values, isEmpty)
304 if len(values) == 0 {
305 return nil
306 }
307
308 return values
309 }
310
311 // composeMessage prepends title to message when title is set.
312 //
313 // Parameters:
314 // - title: Optional heading prepended to the body.
315 // - message: The notification body.
316 //
317 // Returns:
318 // - The combined text sent as the XMPP body.
319 func composeMessage(title, message string) string {
320 if title == "" {
321 return message
322 }
323
324 if message == "" {
325 return title
326 }
327
328 return title + "\n" + message
329 }
330
331 // defaultPort returns the default c2s port for scheme.
332 //
333 // Parameters:
334 // - scheme: [Scheme] or [SchemeTLS].
335 //
336 // Returns:
337 // - [DefaultTLSPort] for xmpps, otherwise [DefaultPort].
338 func defaultPort(scheme string) uint16 {
339 if scheme == SchemeTLS {
340 return DefaultTLSPort
341 }
342
343 return DefaultPort
344 }
345
346 // isDummyURL reports whether serviceURL is the docs-generator placeholder.
347 //
348 // Parameters:
349 // - serviceURL: The URL to inspect.
350 //
351 // Returns:
352 // - true when the hostname is dummy.com.
353 func isDummyURL(serviceURL *url.URL) bool {
354 return serviceURL.Hostname() == "dummy.com"
355 }
356
357 // isEmpty reports whether value is the empty string.
358 //
359 // Parameters:
360 // - value: The string to inspect.
361 //
362 // Returns:
363 // - true if value has length zero.
364 func isEmpty(value string) bool {
365 return value == ""
366 }
367
368 // splitJID splits value into localpart and domainpart.
369 //
370 // A resource, if present, is discarded. The domain must not contain another @.
371 //
372 // Parameters:
373 // - value: A bare or full JID string.
374 //
375 // Returns:
376 // - The localpart.
377 // - The domainpart.
378 // - An error if value is not a valid JID.
379 func splitJID(value string) (string, string, error) {
380 local, rest, ok := strings.Cut(value, "@")
381 if !ok || local == "" || rest == "" {
382 return "", "", fmt.Errorf("%w: %s", ErrInvalidUserJID, value)
383 }
384
385 domain, _, _ := strings.Cut(rest, "/")
386 if domain == "" || strings.Contains(domain, "@") {
387 return "", "", fmt.Errorf("%w: %s", ErrInvalidUserJID, value)
388 }
389
390 return local, domain, nil
391 }
392
393 // validateJID reports whether value is a usable JID.
394 //
395 // Parameters:
396 // - value: A candidate JID string.
397 //
398 // Returns:
399 // - An error if value cannot be split into localpart and domainpart.
400 func validateJID(value string) error {
401 _, _, err := splitJID(value)
402
403 return err
404 }