-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.go
More file actions
1197 lines (1043 loc) · 40.1 KB
/
engine.go
File metadata and controls
1197 lines (1043 loc) · 40.1 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package authsome provides a composable authentication engine for the Forge ecosystem.
//
// AuthSome v0.5.0 is an interface-driven, store-abstracted authentication engine
// with a type-cached plugin registry, global hook bus, strategy-based authentication,
// and optional bridges to forgery extensions (Chronicle, Warden, Keysmith, Relay).
package authsome
import (
"context"
"errors"
"fmt"
"strings"
log "github.com/xraph/go-utils/log"
"github.com/xraph/forge"
"github.com/xraph/forge/extensions/auth"
"github.com/xraph/authsome/account"
"github.com/xraph/authsome/apikey"
"github.com/xraph/authsome/app"
"github.com/xraph/authsome/appclientconfig"
"github.com/xraph/authsome/appsessionconfig"
"github.com/xraph/authsome/authprovider"
"github.com/xraph/authsome/authz"
"github.com/xraph/authsome/bridge"
"github.com/xraph/authsome/ceremony"
"github.com/xraph/authsome/formconfig"
"github.com/xraph/authsome/hook"
"github.com/xraph/authsome/id"
"github.com/xraph/authsome/lockout"
"github.com/xraph/authsome/middleware"
"github.com/xraph/authsome/plugin"
"github.com/xraph/authsome/ratelimit"
"github.com/xraph/authsome/rbac"
"github.com/xraph/authsome/securityevent"
"github.com/xraph/authsome/session"
"github.com/xraph/authsome/settings"
"github.com/xraph/authsome/store"
"github.com/xraph/authsome/strategy"
"github.com/xraph/authsome/tokenformat"
"github.com/xraph/authsome/user"
"github.com/xraph/grove"
"github.com/xraph/keysmith"
xledger "github.com/xraph/ledger"
ledgerstore "github.com/xraph/ledger/store"
"github.com/xraph/warden"
wardenid "github.com/xraph/warden/id"
"github.com/xraph/warden/resourcetype"
)
// Engine is the core AuthSome orchestrator. It holds only interfaces —
// no concrete implementations — for maximum pluggability.
type Engine struct {
config Config
store store.Store
logger log.Logger
// Plugin system
plugins *plugin.Registry
hooks *hook.Bus
strategies *strategy.Registry
pendingPlugins []plugin.Plugin
pendingStrategies []pendingStrategy
pendingAppSessCfgs []*appsessionconfig.Config
// First-class authorization engine (optional, replaces bridge for RBAC)
wardenEng *warden.Engine
// First-class key management engine (optional, replaces bridge for API keys)
keysmithEng *keysmith.Engine
// First-class billing engine (optional, provides store access for subscription plugin)
ledgerEng *xledger.Ledger
// Optional forgery bridges (injected, not required)
chronicle bridge.Chronicle
authorizer bridge.Authorizer
keyManager bridge.KeyManager
relay bridge.EventRelay
mailer bridge.Mailer
sms bridge.SMSSender
heraldBridge bridge.Herald
vault bridge.Vault
dispatcher bridge.Dispatcher
ledger bridge.Ledger
metrics bridge.MetricsCollector
// Ceremony state store for multi-instance auth ceremonies
ceremonyStore ceremony.Store
// Token format (default: opaque; per-app overrides via AppSessionConfig.TokenFormat)
defaultTokenFormat tokenformat.Format
jwtFormats map[string]*tokenformat.JWT // keyed by app ID
// Security
rateLimiter ratelimit.Limiter
lockout lockout.Tracker
passwordHistory account.PasswordHistoryStore
securityEvents securityevent.Store
// Dynamic settings manager (optional).
settingsMgr *settings.Manager
// Bootstrap configuration (nil = disabled).
bootstrapCfg *BootstrapConfig
platformAppID id.AppID
// Database reference for plugins that need direct database access
// to create their own persistent stores.
db *grove.DB
// Cached auth middleware — built once during InitPlugins() with full
// capability detection (JWT + strategies + cookie bridge).
authMiddleware forge.Middleware
// Forge auth provider registry — plugins register their providers here.
authRegistry auth.Registry
pluginsInitialized bool
started bool
}
// NewEngine creates a new AuthSome engine with the given options.
func NewEngine(opts ...Option) (*Engine, error) {
e := &Engine{
config: DefaultConfig(),
logger: log.NewNoopLogger(),
}
for _, opt := range opts {
opt(e)
}
if e.store == nil {
return nil, errors.New("authsome: store is required")
}
if e.wardenEng == nil {
return nil, errors.New("authsome: warden engine is required (use WithWarden option)")
}
// Initialize subsystems
e.plugins = plugin.NewRegistry(e.logger)
e.hooks = hook.NewBus(e.logger)
e.strategies = strategy.NewRegistry(e.logger)
// Initialize the dynamic settings manager.
e.settingsMgr = settings.NewManager(e.store, e.logger)
// Register core session settings.
if err := registerCoreSessionSettings(e.settingsMgr); err != nil {
return nil, fmt.Errorf("authsome: failed to register core session settings: %w", err)
}
// Register pending plugins
for _, p := range e.pendingPlugins {
e.plugins.Register(p)
}
e.pendingPlugins = nil
// Register pending strategies
for _, ps := range e.pendingStrategies {
e.strategies.Register(ps.strategy, ps.priority)
}
e.pendingStrategies = nil
return e, nil
}
// ErrNotStarted is returned when a service method is called before Start().
var ErrNotStarted = errors.New("authsome: engine not started, please wait for initialization to complete")
// EnsureMigrated runs store migrations (core + plugin groups) if not disabled.
// This is idempotent — safe to call multiple times. Use this to ensure tables
// exist before the engine is fully started (e.g. during extension init).
func (e *Engine) EnsureMigrated(ctx context.Context) error {
if e.config.DisableMigrate {
return nil
}
extraGroups := e.plugins.CollectMigrationGroups(e.config.DriverName)
return e.store.Migrate(ctx, extraGroups...)
}
// requireStarted returns ErrNotStarted if the engine has not been started.
func (e *Engine) requireStarted() error {
if !e.started {
return ErrNotStarted
}
return nil
}
// buildAuthMiddleware constructs the fully-configured auth middleware with
// capability detection (JWT, strategies) and the cookie-to-header bridge.
// Called once during InitPlugins so both the extension and plugins share
// the same middleware instance.
func (e *Engine) buildAuthMiddleware() {
var inner forge.Middleware
bindCfg := middleware.SessionBindingConfig{
CookieNameResolver: e.resolveSessionCookieName,
JWTSessionChecker: e.jwtSessionChecker,
}
switch {
case e.HasJWT():
inner = middleware.AuthMiddlewareWithJWT(
e.ResolveSessionByToken,
e.ResolveUser,
e.Strategies(),
e,
e.Logger(),
bindCfg,
)
case e.HasStrategies():
inner = middleware.AuthMiddlewareWithStrategies(
e.ResolveSessionByToken,
e.ResolveUser,
e.Strategies(),
e.Logger(),
bindCfg,
)
default:
inner = middleware.AuthMiddleware(
e.ResolveSessionByToken,
e.ResolveUser,
e.Logger(),
bindCfg,
)
}
// Wrap with cookie-to-header bridge: when no Authorization header is
// present, read the auth_token cookie (set during browser login) or
// the dynamic session cookie and inject it as a Bearer token.
e.authMiddleware = func(next forge.Handler) forge.Handler {
return func(ctx forge.Context) error {
r := ctx.Request()
if r.Header.Get("Authorization") == "" {
if cookie, err := r.Cookie("auth_token"); err == nil && cookie.Value != "" {
r.Header.Set("Authorization", "Bearer "+cookie.Value)
} else {
// Fall back to the dynamic session cookie name from settings.
cookieName := e.resolveSessionCookieName(ctx.Context())
if cookie, err := r.Cookie(cookieName); err == nil && cookie.Value != "" {
r.Header.Set("Authorization", "Bearer "+cookie.Value)
}
}
}
return inner(next)(ctx)
}
}
}
// AuthMiddleware returns the engine's fully-configured non-blocking
// authentication middleware (cookie bridge + JWT + strategies). Populates
// user context when a valid token is present, passes through otherwise.
// Applied globally by the extension.
func (e *Engine) AuthMiddleware() forge.Middleware { return e.authMiddleware }
// AuthRegistry returns the forge auth provider registry. Plugins can register
// their own auth providers and create middleware via registry.Middleware().
func (e *Engine) AuthRegistry() auth.Registry { return e.authRegistry }
// SetAuthRegistry sets the forge auth provider registry. Called by the
// extension after obtaining the registry from the DI container.
func (e *Engine) SetAuthRegistry(r auth.Registry) { e.authRegistry = r }
// registerSessionAuthProvider registers the core "session" auth provider
// with the forge auth registry. This must be called before plugin OnInit
// so plugins can reference "session" in their auth declarations.
func (e *Engine) registerSessionAuthProvider() {
if e.authRegistry == nil {
e.logger.Debug("authsome: no auth registry available, skipping session provider registration")
return
}
provider := authprovider.NewSessionProvider(e.ResolveSessionByToken, e.ResolveUser, e.logger, e.resolveSessionCookieName)
if err := e.authRegistry.Register(provider); err != nil {
e.logger.Warn("authsome: failed to register session auth provider",
log.String("error", err.Error()),
)
} else {
e.logger.Info("authsome: registered 'session' auth provider with forge auth registry")
}
}
// resolveSessionCookieName returns the session cookie name for the given
// context by reading from dynamic settings. Falls back to the default
// "authsome_session_token" when settings are unavailable or unset.
func (e *Engine) resolveSessionCookieName(ctx context.Context) string {
mgr := e.Settings()
if mgr == nil {
return "authsome_session_token"
}
opts := settings.ResolveOpts{}
if appID, ok := middleware.AppIDFrom(ctx); ok {
opts.AppID = appID.String()
}
name, err := settings.Get(ctx, mgr, SettingCookieName, opts)
if err != nil || name == "" {
return "authsome_session_token"
}
return name
}
// jwtSessionChecker checks whether a JWT's session ID still exists in the
// store. This enables JWT revocation — revoked sessions are rejected even if
// the JWT signature is valid. The SettingJWTRequireActiveSession setting
// controls whether this check is active; when disabled, a non-nil sentinel
// session is returned to skip binding checks.
func (e *Engine) jwtSessionChecker(sessionIDStr string) (*session.Session, error) {
ctx := context.Background()
// Check if the feature is enabled via dynamic settings.
mgr := e.Settings()
if mgr != nil {
enabled, _ := settings.Get(ctx, mgr, SettingJWTRequireActiveSession, settings.ResolveOpts{}) //nolint:errcheck // best-effort
if !enabled {
return nil, nil //nolint:nilnil // nil,nil signals "feature disabled, skip check"
}
}
sessID, err := id.ParseSessionID(sessionIDStr)
if err != nil {
return nil, fmt.Errorf("authsome: invalid session ID in JWT: %w", err)
}
return e.store.GetSession(ctx, sessID)
}
// ensureAuthRegistry creates a local in-memory auth registry if no external
// one was provided (e.g. forge auth extension not registered in the app).
// This ensures AuthRegistry() never returns nil and plugins can always
// register providers and create middleware.
func (e *Engine) ensureAuthRegistry() {
if e.authRegistry != nil {
return
}
e.authRegistry = auth.NewRegistry(nil, e.logger)
e.logger.Debug("authsome: created local auth registry (forge auth extension not available)")
}
// InitPlugins builds the auth middleware, registers the session auth provider,
// and calls OnInit on all registered plugins. Idempotent — safe to call
// multiple times. The extension calls this before route registration so
// plugins can set up dependencies that RegisterRoutes relies on.
func (e *Engine) InitPlugins(ctx context.Context) {
if e.pluginsInitialized {
return
}
e.buildAuthMiddleware()
e.ensureAuthRegistry()
e.registerSessionAuthProvider()
e.plugins.EmitOnInit(ctx, e)
e.pluginsInitialized = true
}
// Start initializes the engine, runs migrations, and starts plugins.
func (e *Engine) Start(ctx context.Context) error {
if e.started {
return nil
}
// Run store migrations (idempotent — may have been called earlier via EnsureMigrated).
if err := e.EnsureMigrated(ctx); err != nil {
return err
}
// Register webhook event catalog with relay (before bootstrap so
// events emitted during bootstrap are recognized).
if e.relay != nil {
if err := e.relay.RegisterEventTypes(ctx, bridge.WebhookEventCatalog()); err != nil {
e.logger.Warn("authsome: failed to register webhook event catalog",
log.String("error", err.Error()),
)
}
}
// Initialize plugins (idempotent — may have been called earlier by
// the extension before route registration).
e.InitPlugins(ctx)
// Seed per-app session configs (from code options or YAML config).
for _, cfg := range e.pendingAppSessCfgs {
if err := e.store.SetAppSessionConfig(ctx, cfg); err != nil {
e.logger.Warn("authsome: failed to seed app session config",
log.String("app_id", cfg.AppID.String()),
log.String("error", err.Error()),
)
}
}
e.pendingAppSessCfgs = nil
// Bootstrap platform app (if configured).
if e.bootstrapCfg != nil {
if err := e.bootstrap(ctx); err != nil {
return err
}
}
// Register authsome resource types with Warden (idempotent).
// This must run AFTER bootstrap so that platformAppID is set and
// resource types are created with the correct tenant ID.
if e.wardenEng != nil {
e.registerWardenResourceTypes(ctx)
}
// Distribute the resolved app ID to plugins that need it.
// This must happen after bootstrap (which may create the platform app).
if appID := e.config.AppID; appID != "" {
for _, p := range e.plugins.Plugins() {
type appIDSetter interface {
SetAppID(string)
}
if s, ok := p.(appIDSetter); ok {
s.SetAppID(appID)
}
}
}
// Auto-register strategies from plugins implementing StrategyProvider.
for _, p := range e.plugins.Plugins() {
if sp, ok := p.(plugin.StrategyProvider); ok {
e.strategies.Register(sp.Strategy(), sp.StrategyPriority())
e.logger.Info("authsome: auto-registered strategy from plugin",
log.String("plugin", p.Name()),
log.String("strategy", sp.Strategy().Name()),
)
}
}
// Auto-register settings from plugins implementing SettingsProvider.
for _, p := range e.plugins.Plugins() {
if sp, ok := p.(plugin.SettingsProvider); ok {
if err := sp.DeclareSettings(e.settingsMgr); err != nil {
e.logger.Warn("authsome: failed to register plugin settings",
log.String("plugin", p.Name()),
log.String("error", err.Error()),
)
}
}
}
// Register metrics collector as a hook handler
if e.metrics != nil {
e.hooks.On("metrics", func(_ context.Context, event *hook.Event) error {
outcome := "success"
if event.Err != nil {
outcome = "failure"
}
e.metrics.RecordEvent(event.Action, event.Resource, outcome, event.Tenant, 0)
return nil
})
}
// Register security event recorder as a hook handler
if e.securityEvents != nil {
e.hooks.On("security_events", func(ctx context.Context, event *hook.Event) error {
outcome := "success"
if event.Err != nil {
outcome = "failure"
}
return e.securityEvents.RecordSecurityEvent(ctx, &securityevent.Event{
Action: event.Action,
Outcome: outcome,
Metadata: event.Metadata,
CreatedAt: event.Timestamp,
})
})
}
e.started = true
return nil
}
// Health checks the health of the engine by pinging its store.
func (e *Engine) Health(ctx context.Context) error {
return e.store.Ping(ctx)
}
// Stop gracefully shuts down the engine and all plugins.
func (e *Engine) Stop(ctx context.Context) error {
if !e.started {
return nil
}
e.plugins.EmitOnShutdown(ctx)
e.started = false
return nil
}
// registerWardenResourceTypes registers authsome's default resource type
// schemas with the Warden store. The operation is idempotent — duplicate
// errors are silently ignored.
func (e *Engine) registerWardenResourceTypes(ctx context.Context) {
tenantID := e.config.AppID
if !e.platformAppID.IsNil() {
tenantID = e.platformAppID.String()
}
for _, schema := range authz.DefaultSchemas() {
rt := &resourcetype.ResourceType{
ID: wardenid.NewResourceTypeID(),
TenantID: tenantID,
AppID: tenantID,
Name: schema.Name,
Description: schema.Description,
Relations: schema.Relations,
Permissions: schema.Permissions,
}
if err := e.wardenEng.Store().CreateResourceType(ctx, rt); err != nil {
// Idempotent — ignore duplicate/already-exists errors.
e.logger.Debug("authsome: resource type may already exist",
log.String("name", schema.Name),
log.String("error", err.Error()),
)
}
}
e.logger.Info("authsome: warden resource types registered",
log.Int("count", len(authz.DefaultSchemas())),
)
}
// ──────────────────────────────────────────────────
// Accessors
// ──────────────────────────────────────────────────
// Compile-time check: *Engine must satisfy plugin.Engine.
var _ plugin.Engine = (*Engine)(nil)
// Store returns the persistence backend.
func (e *Engine) Store() store.Store { return e.store }
// GetUser returns a user by ID. This method allows the Engine to satisfy
// narrow interfaces (e.g. notification plugin's userLookup) without
// exposing the full store.
func (e *Engine) GetUser(ctx context.Context, userID id.UserID) (*user.User, error) {
return e.store.GetUser(ctx, userID)
}
// Plugins returns the plugin registry.
func (e *Engine) Plugins() *plugin.Registry { return e.plugins }
// Plugin returns a registered plugin by name, or nil if not found.
func (e *Engine) Plugin(name string) plugin.Plugin { return e.plugins.Plugin(name) }
// Hooks returns the global event bus.
func (e *Engine) Hooks() *hook.Bus { return e.hooks }
// DefaultAppID returns the configured app ID string.
func (e *Engine) DefaultAppID() string { return e.config.AppID }
// BasePath returns the URL prefix for auth routes.
func (e *Engine) BasePath() string { return e.config.BasePath }
// Strategies returns the strategy registry.
func (e *Engine) Strategies() *strategy.Registry { return e.strategies }
// HasStrategies returns true if any authentication strategies are registered.
func (e *Engine) HasStrategies() bool { return len(e.strategies.Strategies()) > 0 }
// Logger returns the engine logger.
func (e *Engine) Logger() log.Logger { return e.logger }
// Config returns the engine configuration.
func (e *Engine) Config() Config { return e.config }
// SessionConfigForApp returns the resolved session config for an app,
// applying per-app and optional per-environment overrides on top of the
// global defaults. Plugins should use this instead of hardcoding their
// own session config.
func (e *Engine) SessionConfigForApp(ctx context.Context, appID id.AppID, envIDs ...id.EnvironmentID) account.SessionConfig {
return e.sessionConfigForApp(ctx, appID, envIDs...)
}
// Chronicle returns the audit trail bridge (may be nil).
func (e *Engine) Chronicle() bridge.Chronicle { return e.chronicle }
// Authorizer returns the authorization bridge (may be nil).
func (e *Engine) Authorizer() bridge.Authorizer { return e.authorizer }
// KeyManager returns the key management bridge (may be nil).
func (e *Engine) KeyManager() bridge.KeyManager { return e.keyManager }
// Relay returns the event relay bridge (may be nil).
func (e *Engine) Relay() bridge.EventRelay { return e.relay }
// Mailer returns the email bridge (may be nil).
func (e *Engine) Mailer() bridge.Mailer { return e.mailer }
// SMSSender returns the SMS bridge (may be nil).
func (e *Engine) SMSSender() bridge.SMSSender { return e.sms }
// Herald returns the Herald notification bridge (may be nil).
func (e *Engine) Herald() bridge.Herald { return e.heraldBridge }
// Vault returns the secrets/feature-flag/config bridge (may be nil).
func (e *Engine) Vault() bridge.Vault { return e.vault }
// Dispatcher returns the job queue bridge (may be nil).
func (e *Engine) Dispatcher() bridge.Dispatcher { return e.dispatcher }
// Ledger returns the billing/metering bridge (may be nil).
func (e *Engine) Ledger() bridge.Ledger { return e.ledger }
// LedgerEngine returns the first-class ledger billing engine (may be nil).
func (e *Engine) LedgerEngine() *xledger.Ledger { return e.ledgerEng }
// LedgerStore returns the underlying ledger store for direct query access
// (e.g. plan/feature/subscription listing). Returns nil if no ledger engine
// was provided via WithLedgerEngine.
func (e *Engine) LedgerStore() ledgerstore.Store {
if e.ledgerEng != nil {
return e.ledgerEng.Store()
}
return nil
}
// MetricsCollector returns the metrics collector bridge (may be nil).
func (e *Engine) MetricsCollector() bridge.MetricsCollector { return e.metrics }
// CeremonyStore returns the ceremony state store for short-lived auth
// ceremony sessions. Returns an in-memory store if none was configured.
func (e *Engine) CeremonyStore() ceremony.Store {
if e.ceremonyStore != nil {
return e.ceremonyStore
}
return ceremony.NewMemory()
}
// RateLimiter returns the rate limiter (may be nil).
func (e *Engine) RateLimiter() ratelimit.Limiter { return e.rateLimiter }
// Lockout returns the account lockout tracker (may be nil).
func (e *Engine) Lockout() lockout.Tracker { return e.lockout }
// PasswordHistory returns the password history store (may be nil).
func (e *Engine) PasswordHistory() account.PasswordHistoryStore { return e.passwordHistory }
// SecurityEvents returns the security event store (may be nil).
func (e *Engine) SecurityEvents() securityevent.Store { return e.securityEvents }
// Warden returns the first-class authorization engine (may be nil).
func (e *Engine) Warden() *warden.Engine { return e.wardenEng }
// Keysmith returns the first-class key management engine (may be nil).
func (e *Engine) Keysmith() *keysmith.Engine { return e.keysmithEng }
// Settings returns the dynamic settings manager (may be nil).
func (e *Engine) Settings() *settings.Manager { return e.settingsMgr }
// DB returns the database handle so plugins can create their own persistent
// stores. Returns nil if not set.
func (e *Engine) DB() *grove.DB { return e.db }
// ──────────────────────────────────────────────────
// Client configuration types
// ──────────────────────────────────────────────────
// ClientConfigResponse is the public client-facing configuration returned
// by the /client-config endpoint. It tells the frontend SDK which auth
// methods are enabled, available providers, branding, etc.
type ClientConfigResponse struct {
Version string `json:"version"`
AppID string `json:"app_id"`
Branding *ClientConfigBranding `json:"branding,omitempty"`
Password *ClientConfigToggle `json:"password,omitempty"`
Social *ClientConfigSocial `json:"social,omitempty"`
Passkey *ClientConfigToggle `json:"passkey,omitempty"`
MFA *ClientConfigMFA `json:"mfa,omitempty"`
MagicLink *ClientConfigToggle `json:"magiclink,omitempty"`
SSO *ClientConfigSSO `json:"sso,omitempty"`
EmailVerification *ClientConfigEmailVerification `json:"email_verification,omitempty"`
DeviceAuthorization *ClientConfigToggle `json:"device_authorization,omitempty"`
Waitlist *ClientConfigToggle `json:"waitlist,omitempty"`
SupportedPlugins []string `json:"supported_plugins"`
SignupFields []ClientConfigSignupField `json:"signup_fields,omitempty"`
}
// ClientConfigEmailVerification represents email verification settings.
type ClientConfigEmailVerification struct {
Enabled bool `json:"enabled"`
Required bool `json:"required"`
}
// ClientConfigBranding holds app branding information.
type ClientConfigBranding struct {
AppName string `json:"app_name,omitempty"`
LogoURL string `json:"logo_url,omitempty"`
}
// ClientConfigToggle represents a simple enabled/disabled auth method.
type ClientConfigToggle struct {
Enabled bool `json:"enabled"`
}
// ClientConfigSocial represents the social auth configuration.
type ClientConfigSocial struct {
Enabled bool `json:"enabled"`
Providers []ClientConfigSocialProvider `json:"providers"`
}
// ClientConfigSocialProvider represents a social login provider.
type ClientConfigSocialProvider struct {
ID string `json:"id"`
Name string `json:"name"`
}
// ClientConfigMFA represents the MFA configuration.
type ClientConfigMFA struct {
Enabled bool `json:"enabled"`
Methods []string `json:"methods"`
}
// ClientConfigSSO represents the SSO configuration.
type ClientConfigSSO struct {
Enabled bool `json:"enabled"`
Connections []ClientConfigSSOConnection `json:"connections"`
}
// ClientConfigSSOConnection represents an SSO connection/provider.
type ClientConfigSSOConnection struct {
ID string `json:"id"`
Name string `json:"name"`
}
// ClientConfigSignupField describes a custom signup form field.
type ClientConfigSignupField struct {
Key string `json:"key"`
Label string `json:"label"`
Type string `json:"type"`
Placeholder string `json:"placeholder,omitempty"`
Description string `json:"description,omitempty"`
Options []ClientConfigSelectOption `json:"options,omitempty"`
Default string `json:"default,omitempty"`
Validation *ClientConfigFieldValidation `json:"validation,omitempty"`
Order int `json:"order"`
}
// ClientConfigSelectOption represents a select/radio option.
type ClientConfigSelectOption struct {
Label string `json:"label"`
Value string `json:"value"`
}
// ClientConfigFieldValidation defines validation rules for a signup field.
type ClientConfigFieldValidation struct {
Required bool `json:"required,omitempty"`
MinLen int `json:"min_len,omitempty"`
MaxLen int `json:"max_len,omitempty"`
Pattern string `json:"pattern,omitempty"`
Min *int `json:"min,omitempty"`
Max *int `json:"max,omitempty"`
}
// socialProviderLister is implemented by the social plugin to expose providers.
type socialProviderLister interface {
Providers() []string
}
// ssoConnectionLister is implemented by the SSO plugin to expose connections.
type ssoConnectionLister interface {
Connections() []string
}
// providerDisplayNames maps lowercase provider IDs to proper display names
// for the client-config response. The frontend renders these as button labels.
var providerDisplayNames = map[string]string{
"google": "Google", "github": "GitHub", "apple": "Apple",
"microsoft": "Microsoft", "facebook": "Facebook", "twitter": "Twitter",
"discord": "Discord", "slack": "Slack", "linkedin": "LinkedIn",
"gitlab": "GitLab", "bitbucket": "Bitbucket", "spotify": "Spotify",
"twitch": "Twitch", "dropbox": "Dropbox", "amazon": "Amazon",
"yahoo": "Yahoo", "line": "Line", "instagram": "Instagram",
"pinterest": "Pinterest", "patreon": "Patreon", "strava": "Strava",
"zoom": "Zoom", "okta": "Okta", "azure-ad": "Azure AD",
"auth0": "Auth0", "onelogin": "OneLogin", "ping": "Ping Identity",
}
func providerDisplayName(providerID string) string {
if name, ok := providerDisplayNames[providerID]; ok {
return name
}
if providerID == "" {
return providerID
}
return strings.ToUpper(providerID[:1]) + providerID[1:]
}
// ClientConfig returns the merged client-facing configuration for an app.
// This aggregates plugin-level defaults with per-app overrides.
func (e *Engine) ClientConfig(ctx context.Context, appID id.AppID) *ClientConfigResponse {
resp := &ClientConfigResponse{
Version: "1",
AppID: appID.String(),
}
// Load app record for branding defaults.
if a, err := e.store.GetApp(ctx, appID); err == nil {
resp.Branding = &ClientConfigBranding{
AppName: a.Name,
LogoURL: a.Logo,
}
}
// Detect enabled auth methods from registered plugins.
allPlugins := e.plugins.Plugins()
var (
passwordEnabled bool
socialEnabled bool
passkeyEnabled bool
mfaEnabled bool
magicLinkEnabled bool
ssoEnabled bool
waitlistEnabled bool
socialProviders []ClientConfigSocialProvider
ssoConnections []ClientConfigSSOConnection
mfaMethods []string
pluginNames = make([]string, 0, len(allPlugins))
)
for _, p := range allPlugins {
name := p.Name()
pluginNames = append(pluginNames, name)
switch name {
case "password":
passwordEnabled = true
case "social":
socialEnabled = true
if lister, ok := p.(socialProviderLister); ok {
for _, prov := range lister.Providers() {
socialProviders = append(socialProviders, ClientConfigSocialProvider{
ID: prov,
Name: providerDisplayName(prov),
})
}
}
case "passkey":
passkeyEnabled = true
case "mfa":
mfaEnabled = true
mfaMethods = []string{"totp"}
case "magiclink":
magicLinkEnabled = true
case "sso":
ssoEnabled = true
if lister, ok := p.(ssoConnectionLister); ok {
for _, name := range lister.Connections() {
ssoConnections = append(ssoConnections, ClientConfigSSOConnection{
ID: name,
Name: providerDisplayName(name),
})
}
}
case "waitlist":
waitlistEnabled = true
}
}
// Load per-app overrides and apply on top of plugin defaults.
if overrides, err := e.store.GetAppClientConfig(ctx, appID); err == nil {
applyClientConfigOverrides(resp, overrides,
&passwordEnabled, &socialEnabled, &passkeyEnabled,
&mfaEnabled, &magicLinkEnabled, &ssoEnabled,
&waitlistEnabled,
&socialProviders, &ssoConnections, &mfaMethods,
)
}
// Build response sections.
resp.Password = &ClientConfigToggle{Enabled: passwordEnabled}
resp.Passkey = &ClientConfigToggle{Enabled: passkeyEnabled}
resp.MagicLink = &ClientConfigToggle{Enabled: magicLinkEnabled}
if socialProviders == nil {
socialProviders = []ClientConfigSocialProvider{}
}
resp.Social = &ClientConfigSocial{
Enabled: socialEnabled,
Providers: socialProviders,
}
if mfaMethods == nil {
mfaMethods = []string{}
}
resp.MFA = &ClientConfigMFA{
Enabled: mfaEnabled,
Methods: mfaMethods,
}
if ssoConnections == nil {
ssoConnections = []ClientConfigSSOConnection{}
}
resp.SSO = &ClientConfigSSO{
Enabled: ssoEnabled,
Connections: ssoConnections,
}
resp.Waitlist = &ClientConfigToggle{Enabled: waitlistEnabled}
if pluginNames == nil {
pluginNames = []string{}
}
resp.SupportedPlugins = pluginNames
// Load active signup form config and expose fields.
if fc, err := e.store.GetFormConfig(ctx, appID, formconfig.FormTypeSignup); err == nil && fc != nil && fc.Active && len(fc.Fields) > 0 {
fields := make([]ClientConfigSignupField, 0, len(fc.Fields))
for _, f := range fc.Fields {
sf := ClientConfigSignupField{
Key: f.Key,
Label: f.Label,
Type: string(f.Type),
Placeholder: f.Placeholder,
Description: f.Description,
Default: f.Default,
Order: f.Order,
}
if len(f.Options) > 0 {
opts := make([]ClientConfigSelectOption, 0, len(f.Options))
for _, o := range f.Options {
opts = append(opts, ClientConfigSelectOption{Label: o.Label, Value: o.Value})
}
sf.Options = opts
}
if f.Validation != (formconfig.Validation{}) {
sf.Validation = &ClientConfigFieldValidation{
Required: f.Validation.Required,
MinLen: f.Validation.MinLen,
MaxLen: f.Validation.MaxLen,
Pattern: f.Validation.Pattern,
Min: f.Validation.Min,
Max: f.Validation.Max,
}
}
fields = append(fields, sf)
}
resp.SignupFields = fields
}
// Email verification: enabled when password plugin is registered,
// required based on environment settings (default: required in production).
if passwordEnabled {
emailVerifRequired := true
if env, _ := e.GetDefaultEnvironment(ctx, appID); env != nil && env.Settings != nil { //nolint:errcheck // best-effort env lookup
if env.Settings.SkipEmailVerification != nil && *env.Settings.SkipEmailVerification {
emailVerifRequired = false
}
}
resp.EmailVerification = &ClientConfigEmailVerification{
Enabled: true,
Required: emailVerifRequired,
}
}
// Device authorization: enabled when oauth2provider plugin is registered.
for _, name := range pluginNames {
if name == "oauth2provider" {
resp.DeviceAuthorization = &ClientConfigToggle{Enabled: true}
break
}
}
return resp
}
// applyClientConfigOverrides applies per-app overrides to the client config.
func applyClientConfigOverrides(
resp *ClientConfigResponse,
cfg *appclientconfig.Config,
passwordEnabled, socialEnabled, passkeyEnabled *bool,
mfaEnabled, magicLinkEnabled, ssoEnabled *bool,
waitlistEnabled *bool,
socialProviders *[]ClientConfigSocialProvider,
_ *[]ClientConfigSSOConnection,
mfaMethods *[]string,
) {
if cfg.PasswordEnabled != nil {
*passwordEnabled = *cfg.PasswordEnabled
}
if cfg.SocialEnabled != nil {
*socialEnabled = *cfg.SocialEnabled
}
if cfg.PasskeyEnabled != nil {
*passkeyEnabled = *cfg.PasskeyEnabled
}
if cfg.MFAEnabled != nil {
*mfaEnabled = *cfg.MFAEnabled
}
if cfg.MagicLinkEnabled != nil {
*magicLinkEnabled = *cfg.MagicLinkEnabled
}
if cfg.SSOEnabled != nil {
*ssoEnabled = *cfg.SSOEnabled
}
if cfg.WaitlistEnabled != nil {
*waitlistEnabled = *cfg.WaitlistEnabled
}
// Filter social providers to per-app whitelist.
if len(cfg.SocialProviders) > 0 {
allowed := make(map[string]bool, len(cfg.SocialProviders))