service.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package passkey
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "time"
  10. "one-api/common"
  11. "one-api/setting/system_setting"
  12. "github.com/go-webauthn/webauthn/protocol"
  13. webauthn "github.com/go-webauthn/webauthn/webauthn"
  14. )
  15. const (
  16. RegistrationSessionKey = "passkey_registration_session"
  17. LoginSessionKey = "passkey_login_session"
  18. VerifySessionKey = "passkey_verify_session"
  19. )
  20. // BuildWebAuthn constructs a WebAuthn instance using the current passkey settings and request context.
  21. func BuildWebAuthn(r *http.Request) (*webauthn.WebAuthn, error) {
  22. settings := system_setting.GetPasskeySettings()
  23. if settings == nil {
  24. return nil, errors.New("未找到 Passkey 设置")
  25. }
  26. displayName := strings.TrimSpace(settings.RPDisplayName)
  27. if displayName == "" {
  28. displayName = common.SystemName
  29. }
  30. origins, err := resolveOrigins(r, settings)
  31. if err != nil {
  32. return nil, err
  33. }
  34. rpID, err := resolveRPID(r, settings, origins)
  35. if err != nil {
  36. return nil, err
  37. }
  38. selection := protocol.AuthenticatorSelection{
  39. ResidentKey: protocol.ResidentKeyRequirementRequired,
  40. RequireResidentKey: protocol.ResidentKeyRequired(),
  41. UserVerification: protocol.UserVerificationRequirement(settings.UserVerification),
  42. }
  43. if selection.UserVerification == "" {
  44. selection.UserVerification = protocol.VerificationPreferred
  45. }
  46. if attachment := strings.TrimSpace(settings.AttachmentPreference); attachment != "" {
  47. selection.AuthenticatorAttachment = protocol.AuthenticatorAttachment(attachment)
  48. }
  49. config := &webauthn.Config{
  50. RPID: rpID,
  51. RPDisplayName: displayName,
  52. RPOrigins: origins,
  53. AuthenticatorSelection: selection,
  54. Debug: common.DebugEnabled,
  55. Timeouts: webauthn.TimeoutsConfig{
  56. Login: webauthn.TimeoutConfig{
  57. Enforce: true,
  58. Timeout: 2 * time.Minute,
  59. TimeoutUVD: 2 * time.Minute,
  60. },
  61. Registration: webauthn.TimeoutConfig{
  62. Enforce: true,
  63. Timeout: 2 * time.Minute,
  64. TimeoutUVD: 2 * time.Minute,
  65. },
  66. },
  67. }
  68. return webauthn.New(config)
  69. }
  70. func resolveOrigins(r *http.Request, settings *system_setting.PasskeySettings) ([]string, error) {
  71. if len(settings.Origins) > 0 {
  72. origins := make([]string, 0, len(settings.Origins))
  73. for _, origin := range settings.Origins {
  74. trimmed := strings.TrimSpace(origin)
  75. if trimmed == "" {
  76. continue
  77. }
  78. if !settings.AllowInsecureOrigin && strings.HasPrefix(strings.ToLower(trimmed), "http://") {
  79. return nil, fmt.Errorf("Passkey 不允许使用不安全的 Origin: %s", trimmed)
  80. }
  81. origins = append(origins, trimmed)
  82. }
  83. if len(origins) == 0 {
  84. // 如果配置了Origins但过滤后为空,使用自动推导
  85. goto autoDetect
  86. }
  87. return origins, nil
  88. }
  89. autoDetect:
  90. scheme := detectScheme(r)
  91. if scheme == "http" && !settings.AllowInsecureOrigin && r.Host != "localhost" && r.Host != "127.0.0.1" && !strings.HasPrefix(r.Host, "127.0.0.1:") && !strings.HasPrefix(r.Host, "localhost:") {
  92. return nil, fmt.Errorf("Passkey 仅支持 HTTPS,当前访问: %s://%s,请在 Passkey 设置中允许不安全 Origin 或配置 HTTPS", scheme, r.Host)
  93. }
  94. // 优先使用请求的完整Host(包含端口)
  95. host := r.Host
  96. // 如果无法从请求获取Host,尝试从ServerAddress获取
  97. if host == "" && system_setting.ServerAddress != "" {
  98. if parsed, err := url.Parse(system_setting.ServerAddress); err == nil && parsed.Host != "" {
  99. host = parsed.Host
  100. if scheme == "" && parsed.Scheme != "" {
  101. scheme = parsed.Scheme
  102. }
  103. }
  104. }
  105. if host == "" {
  106. return nil, fmt.Errorf("无法确定 Passkey 的 Origin,请在系统设置或 Passkey 设置中指定。当前 Host: '%s', ServerAddress: '%s'", r.Host, system_setting.ServerAddress)
  107. }
  108. if scheme == "" {
  109. scheme = "https"
  110. }
  111. origin := fmt.Sprintf("%s://%s", scheme, host)
  112. return []string{origin}, nil
  113. }
  114. func resolveRPID(r *http.Request, settings *system_setting.PasskeySettings, origins []string) (string, error) {
  115. rpID := strings.TrimSpace(settings.RPID)
  116. if rpID != "" {
  117. return hostWithoutPort(rpID), nil
  118. }
  119. if len(origins) == 0 {
  120. return "", errors.New("Passkey 未配置 Origin,无法推导 RPID")
  121. }
  122. parsed, err := url.Parse(origins[0])
  123. if err != nil {
  124. return "", fmt.Errorf("无法解析 Passkey Origin: %w", err)
  125. }
  126. return hostWithoutPort(parsed.Host), nil
  127. }
  128. func hostWithoutPort(host string) string {
  129. host = strings.TrimSpace(host)
  130. if host == "" {
  131. return ""
  132. }
  133. if strings.Contains(host, ":") {
  134. if host, _, err := net.SplitHostPort(host); err == nil {
  135. return host
  136. }
  137. }
  138. return host
  139. }
  140. func detectScheme(r *http.Request) string {
  141. if r == nil {
  142. return ""
  143. }
  144. if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  145. parts := strings.Split(proto, ",")
  146. return strings.ToLower(strings.TrimSpace(parts[0]))
  147. }
  148. if r.TLS != nil {
  149. return "https"
  150. }
  151. if r.URL != nil && r.URL.Scheme != "" {
  152. return strings.ToLower(r.URL.Scheme)
  153. }
  154. if r.Header.Get("X-Forwarded-Protocol") != "" {
  155. return strings.ToLower(strings.TrimSpace(r.Header.Get("X-Forwarded-Protocol")))
  156. }
  157. return "http"
  158. }