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
|
package control
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
)
const porkbunAPIHost = "https://api.porkbun.com/api/json/v3"
var porkbunAPIHostOverride string
type DNSProvider interface {
EnsureRandomARecord(ctx context.Context, zone, prefix, ip string, ttl int) (string, error)
DeleteARecord(ctx context.Context, zone, name string) error
}
type PorkbunClient struct {
APIKey string
SecretAPIKey string
HTTPClient *http.Client
}
type porkbunResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Records []map[string]any `json:"records"`
ID string `json:"id"`
}
func (c PorkbunClient) EnsureRandomARecord(ctx context.Context, zone, prefix, ip string, ttl int) (string, error) {
if err := c.validate(); err != nil {
return "", err
}
if ttl == 0 {
ttl = 600
}
for range 10 {
name := randomSubdomain(prefix)
records, err := c.retrieveRecordsByNameType(ctx, zone, "A", name)
if err != nil {
return "", err
}
if len(records) > 0 {
continue
}
if err := c.createRecord(ctx, zone, name, "A", ip, ttl); err != nil {
return "", err
}
return name + "." + zone, nil
}
return "", errors.New("failed to allocate unique subdomain")
}
func (c PorkbunClient) DeleteARecord(ctx context.Context, zone, name string) error {
if err := c.validate(); err != nil {
return err
}
return c.deleteByNameType(ctx, zone, "A", name)
}
func (c PorkbunClient) validate() error {
if strings.TrimSpace(c.APIKey) == "" || strings.TrimSpace(c.SecretAPIKey) == "" {
return errors.New("porkbun api keys are not configured")
}
return nil
}
func (c PorkbunClient) createRecord(ctx context.Context, zone, name, recordType, content string, ttl int) error {
payload := map[string]string{
"secretapikey": c.SecretAPIKey,
"apikey": c.APIKey,
"name": name,
"type": recordType,
"content": content,
"ttl": fmt.Sprintf("%d", ttl),
}
_, err := c.post(ctx, "/dns/create/"+zone, payload)
return err
}
func (c PorkbunClient) deleteByNameType(ctx context.Context, zone, recordType, name string) error {
payload := map[string]string{
"secretapikey": c.SecretAPIKey,
"apikey": c.APIKey,
}
_, err := c.post(ctx, "/dns/deleteByNameType/"+zone+"/"+recordType+"/"+name, payload)
return err
}
func (c PorkbunClient) retrieveRecordsByNameType(ctx context.Context, zone, recordType, name string) ([]map[string]any, error) {
payload := map[string]string{
"secretapikey": c.SecretAPIKey,
"apikey": c.APIKey,
}
resp, err := c.post(ctx, "/dns/retrieveByNameType/"+zone+"/"+recordType+"/"+name, payload)
if err != nil {
return nil, err
}
return resp.Records, nil
}
func (c PorkbunClient) post(ctx context.Context, path string, payload map[string]string) (*porkbunResponse, error) {
data, err := json.Marshal(payload)
if err != nil {
return nil, err
}
client := c.HTTPClient
if client == nil {
client = &http.Client{Timeout: 15 * time.Second}
}
baseURL := porkbunAPIHost
if porkbunAPIHostOverride != "" {
baseURL = porkbunAPIHostOverride
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+path, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var out porkbunResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("porkbun http %d: %s", resp.StatusCode, out.Message)
}
if strings.ToUpper(out.Status) != "SUCCESS" {
return nil, fmt.Errorf("porkbun api error: %s", out.Message)
}
return &out, nil
}
func randomSubdomain(prefix string) string {
if prefix == "" {
prefix = "vpn"
}
var buf [4]byte
if _, err := rand.Read(buf[:]); err != nil {
now := time.Now().UTC().UnixNano()
return fmt.Sprintf("%s-%x", prefix, now)
}
return prefix + "-" + hex.EncodeToString(buf[:])
}
|