Files
vHost/backend/internal/service/dns_discovery.go
T

89 lines
2.7 KiB
Go

package service
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sea-vhost/internal/dnsprovider"
"sea-vhost/internal/store"
"strings"
"time"
)
type DNSZoneChoice struct {
dnsprovider.Zone
VerificationToken string `json:"verificationToken"`
}
type dnsZoneProof struct {
Owner, Provider, Hash, ID, Zone string
Expires int64
}
func credentialHash(c dnsprovider.Credential) string {
c.ZoneID = ""
raw, _ := json.Marshal(c)
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
func (s *Projects) DiscoverDNSZones(ctx context.Context, u store.User, platform bool, input DNSCredentialInput) ([]DNSZoneChoice, error) {
owner, err := dnsCredentialOwner(u, platform)
if err != nil {
return nil, err
}
ownerKey := "platform"
if owner != nil {
ownerKey = fmt.Sprintf("tenant:%d", *owner)
}
hint := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(input.ZoneName), "."))
if hint != "" && !domainPattern.MatchString(hint) {
return nil, errors.New("指定域名格式无效")
}
zones, err := dnsprovider.DiscoverZones(ctx, input.Provider, input.Credential, hint)
if err != nil {
return nil, err
}
out := []DNSZoneChoice{}
for _, z := range zones {
if !domainPattern.MatchString(z.Name) {
continue
}
proof := dnsZoneProof{Owner: ownerKey, Provider: input.Provider, Hash: credentialHash(input.Credential), ID: z.ID, Zone: z.Name, Expires: time.Now().Add(15 * time.Minute).Unix()}
raw, _ := json.Marshal(proof)
token, e := s.credentials.Seal("dns-zone-choice", string(raw))
if e != nil {
return nil, e
}
out = append(out, DNSZoneChoice{Zone: z, VerificationToken: hex.EncodeToString(token)})
}
return out, nil
}
func (s *Projects) verifyDNSZoneChoice(u store.User, platform bool, input DNSCredentialInput) error {
owner, e := dnsCredentialOwner(u, platform)
if e != nil {
return e
}
ownerKey := "platform"
if owner != nil {
ownerKey = fmt.Sprintf("tenant:%d", *owner)
}
raw, e := hex.DecodeString(input.VerificationToken)
if e != nil || len(raw) > 4096 {
return errors.New("请先读取并选择 DNS 域名")
}
plain, e := s.credentials.Open("dns-zone-choice", raw)
if e != nil {
return errors.New("DNS 域名选择已失效,请重新读取")
}
var p dnsZoneProof
if json.Unmarshal([]byte(plain), &p) != nil || p.Owner != ownerKey || p.Provider != input.Provider || p.Hash != credentialHash(input.Credential) || p.Zone != input.ZoneName || p.Expires < time.Now().Unix() {
return errors.New("DNS 域名选择已失效或票据已变更,请重新读取")
}
if (input.Provider == "cloudflare" || input.Provider == "dnsmgr") && input.Credential.ZoneID != p.ID {
return errors.New("DNS 区域编号与已验证域名不一致")
}
return nil
}