Repository navigation
Expand file tree
/
Copy pathplugin.go
More file actions
469 lines (417 loc) · 15.2 KB
/
Copy pathplugin.go
File metadata and controls
469 lines (417 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package notification
import (
"context"
"net/url"
"strings"
"time"
"github.com/xraph/authsome/internal/mask"
log "github.com/xraph/go-utils/log"
"github.com/xraph/authsome/bridge"
"github.com/xraph/authsome/hook"
"github.com/xraph/authsome/id"
"github.com/xraph/authsome/plugin"
"github.com/xraph/authsome/session"
"github.com/xraph/authsome/settings"
"github.com/xraph/authsome/user"
)
// Compile-time interface checks.
var (
_ plugin.Plugin = (*Plugin)(nil)
_ plugin.OnInit = (*Plugin)(nil)
_ plugin.AfterSignUp = (*Plugin)(nil)
_ plugin.AfterUserCreate = (*Plugin)(nil)
_ plugin.SettingsProvider = (*Plugin)(nil)
)
// ──────────────────────────────────────────────────
// Dynamic setting definitions
// ──────────────────────────────────────────────────
var (
// SettingAppName controls the application name used in notification templates.
SettingAppName = settings.Define("notification.app_name", "AuthSome",
settings.WithDisplayName("Application Name"),
settings.WithDescription("Application name used in notification templates"),
settings.WithCategory("Notifications"),
settings.WithScopes(settings.ScopeGlobal, settings.ScopeApp),
settings.WithPlaceholder("My App"),
settings.WithHelpText("Used in notification templates for branding"),
settings.WithOrder(10),
)
// SettingBaseURL controls the application root URL for notification links.
SettingBaseURL = settings.Define("notification.base_url", "",
settings.WithDisplayName("Base URL"),
settings.WithDescription("Application root URL for building links in notifications"),
settings.WithCategory("Notifications"),
settings.WithScopes(settings.ScopeGlobal, settings.ScopeApp),
settings.WithPlaceholder("https://example.com"),
settings.WithHelpText("Used to build action links in notifications"),
settings.WithOrder(20),
)
// SettingDefaultLocale controls the default locale for notifications.
SettingDefaultLocale = settings.Define("notification.default_locale", "en",
settings.WithDisplayName("Default Locale"),
settings.WithDescription("Default locale for notification templates"),
settings.WithCategory("Notifications"),
settings.WithScopes(settings.ScopeGlobal, settings.ScopeApp),
settings.WithPlaceholder("en"),
settings.WithHelpText("Language/locale for notification content. Default: en"),
settings.WithOrder(30),
)
// SettingAsync controls whether notifications are sent asynchronously.
SettingAsync = settings.Define("notification.async", false,
settings.WithDisplayName("Async Delivery"),
settings.WithDescription("Send notifications asynchronously via dispatch queue"),
settings.WithCategory("Notifications"),
settings.WithScopes(settings.ScopeGlobal),
settings.WithHelpText("When enabled, notifications are queued for async delivery"),
settings.WithOrder(40),
)
)
// Plugin is the Herald-backed notification plugin. It replaces the legacy
// email plugin with a unified multi-channel notification system.
type Plugin struct {
config Config
herald bridge.Herald
templates bridge.HeraldTemplateManager
hooks *hook.Bus
logger log.Logger
mappings map[string]*Mapping
engine plugin.Engine
// dispatcher is the engine's job queue when it has one; its presence
// is what decides that the welcome notification goes out asynchronously.
dispatcher bridge.Dispatcher
}
// welcomeSendTimeout bounds an inline welcome notification, so a slow
// provider cannot hold a sign-up open.
const welcomeSendTimeout = 10 * time.Second
// sendAsync decides how the welcome notification is sent: through the
// queue when the operator asked for it or the engine has a dispatcher to
// back it, inline under a deadline otherwise.
func sendAsync(configured bool, dispatcher bridge.Dispatcher) bool {
return configured || dispatcher != nil
}
// DeclareSettings implements plugin.SettingsProvider.
func (p *Plugin) DeclareSettings(m *settings.Manager) error {
if err := settings.RegisterTyped(m, "notification", SettingAppName); err != nil {
return err
}
if err := settings.RegisterTyped(m, "notification", SettingBaseURL); err != nil {
return err
}
if err := settings.RegisterTyped(m, "notification", SettingDefaultLocale); err != nil {
return err
}
return settings.RegisterTyped(m, "notification", SettingAsync)
}
// New creates a new notification plugin with optional configuration.
func New(cfg ...Config) *Plugin {
var c Config
if len(cfg) > 0 {
c = cfg[0]
}
if c.AppName == "" {
c.AppName = "AuthSome"
}
if c.DefaultLocale == "" {
c.DefaultLocale = "en"
}
if c.EmailVerifyPath == "" {
c.EmailVerifyPath = "/verify-email"
}
if c.PasswordResetPath == "" {
c.PasswordResetPath = "/reset-password"
}
if c.SignInPath == "" {
c.SignInPath = "/sign-in"
}
// Merge user-provided mappings with defaults.
mappings := DefaultMappings()
if c.Mappings != nil {
for action, m := range c.Mappings {
if m == nil {
// nil entry disables the mapping.
delete(mappings, action)
} else {
mappings[action] = m
}
}
}
return &Plugin{
config: c,
mappings: mappings,
}
}
// Name returns the plugin name.
func (p *Plugin) Name() string { return "notification" }
// OnInit extracts the Herald bridge and hook bus from the engine during
// initialization.
func (p *Plugin) OnInit(_ context.Context, engine plugin.Engine) error {
p.engine = engine
if dp, ok := engine.(plugin.DispatcherProvider); ok {
p.dispatcher = dp.Dispatcher()
}
// Discover Herald bridge (required).
p.herald = engine.Herald()
if p.herald == nil {
return bridge.ErrHeraldNotAvailable
}
// Discover template manager (optional, available when real Herald is configured).
if tm, ok := p.herald.(bridge.HeraldTemplateManager); ok {
p.templates = tm
}
// Discover hook bus.
p.hooks = engine.Hooks()
// Discover logger.
p.logger = engine.Logger()
if p.logger == nil {
p.logger = log.NewNoopLogger()
}
// Discover plugin-contributed notification mappings.
for _, pl := range engine.Plugins().Plugins() {
if contributor, ok := pl.(plugin.NotificationMappingContributor); ok {
for action, m := range contributor.NotificationMappings() {
// Plugin-contributed mappings don't override user-provided config mappings.
if _, exists := p.mappings[action]; !exists {
p.mappings[action] = &Mapping{
Template: m.Template,
Channels: m.Channels,
Enabled: m.Enabled,
}
}
}
}
}
// Seed default Herald templates so notifications don't fail with
// "template not found" on a fresh database.
if p.templates != nil {
appID := ""
if pid := engine.PlatformAppID(); !pid.IsNil() {
appID = pid.String()
}
if err := p.templates.SeedDefaultTemplates(context.Background(), appID); err != nil {
p.logger.Warn("notification plugin: failed to seed default templates",
log.String("error", err.Error()),
)
}
}
// Register a global hook handler that auto-sends notifications for
// all mapped actions that aren't handled by direct plugin hooks.
if p.hooks != nil && p.herald != nil {
p.hooks.On("herald-notification", func(ctx context.Context, event *hook.Event) error {
return p.handleHookEvent(ctx, event)
})
}
return nil
}
// OnAfterSignUp sends a welcome notification to the newly registered user.
func (p *Plugin) OnAfterSignUp(ctx context.Context, u *user.User, _ *session.Session) error {
if p.herald == nil {
return nil
}
m, ok := p.mappings[hook.ActionSignUp]
if !ok || !m.Enabled {
return nil
}
name := u.Name()
if name == "" {
name = u.Email
}
async := sendAsync(p.config.Async, p.dispatcher)
sendCtx := ctx
if !async {
var cancel context.CancelFunc
sendCtx, cancel = context.WithTimeout(ctx, welcomeSendTimeout)
defer cancel()
}
if err := p.herald.Notify(sendCtx, &bridge.HeraldNotifyRequest{
Template: m.Template,
Channels: m.Channels,
To: []string{u.Email},
UserID: u.ID.String(),
Locale: p.config.DefaultLocale,
Async: async,
Data: map[string]any{
"user_name": name,
"app_name": p.config.AppName,
"login_url": p.config.BaseURL + p.config.SignInPath,
},
}); err != nil {
p.logger.Warn("notification plugin: failed to send welcome notification",
log.String("email", mask.Email(u.Email)),
log.String("error", err.Error()),
)
}
return nil
}
// OnAfterUserCreate is intentionally a no-op for email verification.
//
// The engine now owns verification issuance: SignUp (and ResendEmailVerification)
// mint a 6-digit OTP and fire ActionEmailVerificationRequested carrying the code,
// which handleHookEvent delivers. Sending here as well would double-email the
// user (and the old payload had no token/code, so the link was unusable).
func (p *Plugin) OnAfterUserCreate(_ context.Context, _ *user.User) error {
return nil
}
// SendPasswordReset sends a password reset notification. This is typically
// called by the engine's password reset flow.
func (p *Plugin) SendPasswordReset(ctx context.Context, email, name, resetURL string) error {
if p.herald == nil {
return bridge.ErrHeraldNotAvailable
}
m, ok := p.mappings[hook.ActionPasswordReset]
if !ok || !m.Enabled {
return nil
}
if name == "" {
name = email
}
return p.herald.Notify(ctx, &bridge.HeraldNotifyRequest{
Template: m.Template,
Channels: m.Channels,
To: []string{email},
Locale: p.config.DefaultLocale,
Async: p.config.Async,
Data: map[string]any{
"user_name": name,
"app_name": p.config.AppName,
"reset_url": resetURL,
"expires_in": "1 hour",
},
})
}
// SendInvitation sends an organization invitation notification.
func (p *Plugin) SendInvitation(ctx context.Context, email, inviterName, orgName, acceptURL string) error {
if p.herald == nil {
return bridge.ErrHeraldNotAvailable
}
m, ok := p.mappings[hook.ActionInvitationAccept]
if !ok || !m.Enabled {
return nil
}
return p.herald.Notify(ctx, &bridge.HeraldNotifyRequest{
Template: m.Template,
Channels: m.Channels,
To: []string{email},
Locale: p.config.DefaultLocale,
Async: p.config.Async,
Data: map[string]any{
"inviter_name": inviterName,
"org_name": orgName,
"app_name": p.config.AppName,
"accept_url": acceptURL,
},
})
}
// handleHookEvent is the global hook handler that catches actions not handled
// by direct plugin hooks (e.g. password_change, account_locked).
func (p *Plugin) handleHookEvent(ctx context.Context, event *hook.Event) error {
// Skip actions that are handled by direct plugin hooks to avoid
// sending duplicate notifications.
switch event.Action {
case hook.ActionSignUp, hook.ActionUserCreate:
return nil
}
m, ok := p.mappings[event.Action]
if !ok || !m.Enabled {
return nil
}
// Build recipient list from the event's delivery data. Addresses live in
// Private so they never reach the audit trail; Metadata is checked for
// events emitted by code that predates that split.
var to []string
if email := event.Private["email"]; email != "" {
to = []string{email}
} else if email, ok := event.Metadata["email"]; ok && email != "" {
to = []string{email}
}
// Fallback: resolve email from ActorID via user store lookup.
if len(to) == 0 && event.ActorID != "" && p.engine != nil {
if uid, err := id.ParseUserID(event.ActorID); err == nil {
if u, err := p.engine.GetUser(ctx, uid); err == nil && u.Email != "" {
to = []string{u.Email}
}
}
}
if len(to) == 0 {
// No recipient — skip. Logged so a misconfigured hook (missing email
// metadata) is diagnosable rather than failing invisibly.
p.logger.Warn("notification: no recipient resolved for action, skipping",
log.String("action", event.Action))
return nil
}
// Build template data from event metadata plus the delivery-only values
// (address, name, token, code) that travel in Private.
data := make(map[string]any, len(event.Metadata)+len(event.Private)+2)
for k, v := range event.Metadata {
data[k] = v
}
for k, v := range event.Private {
data[k] = v
}
data["app_name"] = p.config.AppName
// app_url is the application root, available to every template for generic
// "open the app" call-to-action buttons (templates whose own variables don't
// include a specific link, e.g. email-verified, welcome, password-changed).
if p.config.BaseURL != "" {
data["app_url"] = strings.TrimRight(p.config.BaseURL, "/")
}
// The default Herald auth.email-verification template marks verify_url as a
// required variable — it predates the OTP flow, which delivers a 6-digit
// code (event.Metadata["code"]) rather than a click-through link. Without a
// verify_url the renderer fails validation and Notify silently drops the
// email. Synthesize a deep-link to the code-entry page so the template
// renders (the page can read ?email= to pre-fill) and validation passes.
if event.Action == hook.ActionEmailVerificationRequested {
if existing, ok := data["verify_url"].(string); !ok || existing == "" {
verifyURL := strings.TrimRight(p.config.BaseURL, "/") + p.config.EmailVerifyPath
if email := deliveryValue(event, "email"); email != "" {
verifyURL += "?email=" + url.QueryEscape(email)
}
data["verify_url"] = verifyURL
}
}
// Likewise the default auth.password-reset template requires reset_url.
// Synthesize it from the reset token so the email renders and the link
// lands on the reset-password page.
if event.Action == hook.ActionPasswordReset {
if existing, ok := data["reset_url"].(string); !ok || existing == "" {
resetURL := strings.TrimRight(p.config.BaseURL, "/") + p.config.PasswordResetPath
if token := deliveryValue(event, "token"); token != "" {
resetURL += "?token=" + url.QueryEscape(token)
}
data["reset_url"] = resetURL
}
}
// Deliver on a context detached from the caller's request context. Hook
// handlers run inline on the originating request (e.g. signup), which has
// often already spent most of its deadline on password hashing, user
// creation and role assignment by the time this fires. Sending on that
// near-exhausted context makes a perfectly healthy provider call fail with
// "context deadline exceeded" and silently drops the email. Detaching (and
// granting a fresh timeout) makes delivery independent of how much budget
// the originating request had left.
sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), notifyDeliveryTimeout)
defer cancel()
return p.herald.Notify(sendCtx, &bridge.HeraldNotifyRequest{
AppID: event.Tenant,
Template: m.Template,
Channels: m.Channels,
To: to,
UserID: event.ActorID,
Locale: p.config.DefaultLocale,
Async: p.config.Async,
Data: data,
})
}
// notifyDeliveryTimeout bounds a single hook-triggered notification delivery on
// its detached context. Generous enough to absorb a slow provider response
// without inheriting the originating request's (possibly tiny) remaining budget.
const notifyDeliveryTimeout = 30 * time.Second
// deliveryValue returns a delivery-only value (address, token, code) from the
// event's Private map, falling back to Metadata for events emitted by code
// that predates the split between audit data and delivery data.
func deliveryValue(event *hook.Event, key string) string {
if v := event.Private[key]; v != "" {
return v
}
return event.Metadata[key]
}