wire.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package payment
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "log/slog"
  6. "strings"
  7. dbent "github.com/Wei-Shaw/sub2api/ent"
  8. "github.com/Wei-Shaw/sub2api/internal/config"
  9. "github.com/google/wire"
  10. )
  11. // EncryptionKey is a named type for the payment encryption key (AES-256, 32 bytes).
  12. // Using a named type avoids Wire ambiguity with other []byte parameters.
  13. type EncryptionKey []byte
  14. // ProvideEncryptionKey derives the payment encryption key from the TOTP encryption key in config.
  15. // When the key is empty, nil is returned (payment features that need encryption will be disabled).
  16. // When the key is non-empty but invalid (bad hex or wrong length), an error is returned
  17. // to prevent startup with a misconfigured encryption key.
  18. func ProvideEncryptionKey(cfg *config.Config) (EncryptionKey, error) {
  19. if cfg == nil {
  20. slog.Warn("payment encryption key not configured — encrypted payment config and resume signing will be unavailable")
  21. return nil, nil
  22. }
  23. keyHex := strings.TrimSpace(cfg.Totp.EncryptionKey)
  24. if keyHex == "" {
  25. slog.Warn("payment encryption key not configured — encrypted payment config will be unavailable")
  26. return nil, nil
  27. }
  28. // Reject auto-generated TOTP keys for payment signing.
  29. // They change across restarts/instances and can silently break resume-token flows.
  30. if !cfg.Totp.EncryptionKeyConfigured {
  31. slog.Warn("payment encryption/signing key is not explicitly configured; set TOTP_ENCRYPTION_KEY to enable payment resume tokens")
  32. return nil, nil
  33. }
  34. key, err := hex.DecodeString(keyHex)
  35. if err != nil {
  36. return nil, fmt.Errorf("invalid payment encryption key (hex decode): %w", err)
  37. }
  38. if len(key) != 32 {
  39. return nil, fmt.Errorf("payment encryption key must be 32 bytes, got %d", len(key))
  40. }
  41. return EncryptionKey(key), nil
  42. }
  43. // ProvideRegistry creates an empty payment provider registry.
  44. // Providers are registered at runtime after application startup.
  45. func ProvideRegistry() *Registry {
  46. return NewRegistry()
  47. }
  48. // ProvideDefaultLoadBalancer creates a DefaultLoadBalancer backed by the ent client.
  49. func ProvideDefaultLoadBalancer(client *dbent.Client, key EncryptionKey) *DefaultLoadBalancer {
  50. return NewDefaultLoadBalancer(client, []byte(key))
  51. }
  52. // ProviderSet is the Wire provider set for the payment package.
  53. var ProviderSet = wire.NewSet(
  54. ProvideEncryptionKey,
  55. ProvideRegistry,
  56. ProvideDefaultLoadBalancer,
  57. wire.Bind(new(LoadBalancer), new(*DefaultLoadBalancer)),
  58. )