service.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package passkey
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-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. originsStr := strings.TrimSpace(settings.Origins)
  72. if originsStr != "" {
  73. originList := strings.Split(originsStr, ",")
  74. origins := make([]string, 0, len(originList))
  75. for _, origin := range originList {
  76. trimmed := strings.TrimSpace(origin)
  77. if trimmed == "" {
  78. continue
  79. }
  80. if !settings.AllowInsecureOrigin && strings.HasPrefix(strings.ToLower(trimmed), "http://") {
  81. return nil, fmt.Errorf("Passkey 不允许使用不安全的 Origin: %s", trimmed)
  82. }
  83. origins = append(origins, trimmed)
  84. }
  85. if len(origins) == 0 {
  86. // 如果配置了Origins但过滤后为空,使用自动推导
  87. goto autoDetect
  88. }
  89. return origins, nil
  90. }
  91. autoDetect:
  92. scheme := detectScheme(r)
  93. 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:") {
  94. return nil, fmt.Errorf("Passkey 仅支持 HTTPS,当前访问: %s://%s,请在 Passkey 设置中允许不安全 Origin 或配置 HTTPS", scheme, r.Host)
  95. }
  96. // 优先使用请求的完整Host(包含端口)
  97. host := r.Host
  98. // 如果无法从请求获取Host,尝试从ServerAddress获取
  99. if host == "" && system_setting.ServerAddress != "" {
  100. if parsed, err := url.Parse(system_setting.ServerAddress); err == nil && parsed.Host != "" {
  101. host = parsed.Host
  102. if scheme == "" && parsed.Scheme != "" {
  103. scheme = parsed.Scheme
  104. }
  105. }
  106. }
  107. if host == "" {
  108. return nil, fmt.Errorf("无法确定 Passkey 的 Origin,请在系统设置或 Passkey 设置中指定。当前 Host: '%s', ServerAddress: '%s'", r.Host, system_setting.ServerAddress)
  109. }
  110. if scheme == "" {
  111. scheme = "https"
  112. }
  113. origin := fmt.Sprintf("%s://%s", scheme, host)
  114. return []string{origin}, nil
  115. }
  116. func resolveRPID(r *http.Request, settings *system_setting.PasskeySettings, origins []string) (string, error) {
  117. rpID := strings.TrimSpace(settings.RPID)
  118. if rpID != "" {
  119. return hostWithoutPort(rpID), nil
  120. }
  121. if len(origins) == 0 {
  122. return "", errors.New("Passkey 未配置 Origin,无法推导 RPID")
  123. }
  124. parsed, err := url.Parse(origins[0])
  125. if err != nil {
  126. return "", fmt.Errorf("无法解析 Passkey Origin: %w", err)
  127. }
  128. return hostWithoutPort(parsed.Host), nil
  129. }
  130. func hostWithoutPort(host string) string {
  131. host = strings.TrimSpace(host)
  132. if host == "" {
  133. return ""
  134. }
  135. if strings.Contains(host, ":") {
  136. if host, _, err := net.SplitHostPort(host); err == nil {
  137. return host
  138. }
  139. }
  140. return host
  141. }
  142. func detectScheme(r *http.Request) string {
  143. if r == nil {
  144. return ""
  145. }
  146. if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  147. parts := strings.Split(proto, ",")
  148. return strings.ToLower(strings.TrimSpace(parts[0]))
  149. }
  150. if r.TLS != nil {
  151. return "https"
  152. }
  153. if r.URL != nil && r.URL.Scheme != "" {
  154. return strings.ToLower(r.URL.Scheme)
  155. }
  156. if r.Header.Get("X-Forwarded-Protocol") != "" {
  157. return strings.ToLower(strings.TrimSpace(r.Header.Get("X-Forwarded-Protocol")))
  158. }
  159. return "http"
  160. }