-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
232 lines (207 loc) · 5.85 KB
/
client.go
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package harmonyos
import (
"context"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/pem"
"fmt"
"strings"
"time"
"github.com/duke-git/lancet/v2/cryptor"
"github.com/duke-git/lancet/v2/slice"
"github.com/go-resty/resty/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/pkg/errors"
"github.com/caiknife/mp3lister/lib/fjson"
"github.com/caiknife/mp3lister/lib/types"
)
type Client struct {
PrivateKey string `json:"private_key"`
KeyID string `json:"key_id"`
IssuerID string `json:"issuer_id"`
AppID string `json:"app_id"`
Header *Header
Payload *Payload
token *jwt.Token
}
func NewClient(privateKey, keyID, issuerID, appID string) *Client {
c := &Client{
PrivateKey: privateKey,
KeyID: keyID,
IssuerID: issuerID,
AppID: appID,
}
c.token = jwt.New(jwt.SigningMethodES256)
return c
}
func (c *Client) GetToken(body any) (s string, err error) {
c.token.Header["kid"] = c.KeyID
now := time.Now().Unix()
hash, err := c.Hash(body)
if err != nil {
return "", errors.WithMessage(err, "hash failed")
}
c.token.Claims = jwt.MapClaims{
"iss": c.IssuerID,
"aud": "iap-v1",
"iat": now,
"exp": now + 60*60,
"aid": c.AppID,
"digest": hash,
}
pem, err := jwt.ParseECPrivateKeyFromPEM([]byte(c.PrivateKey))
if err != nil {
return "", errors.WithMessage(err, "parse private key failed")
}
s, err = c.token.SignedString(pem)
if err != nil {
return "", errors.WithMessage(err, "sign token failed")
}
return s, nil
}
func (c *Client) Hash(body any) (s string, err error) {
toString, err := fjson.MarshalToString(body)
if err != nil {
return "", errors.WithMessage(err, "json marshal failed")
}
s = cryptor.Sha256(toString)
return s, nil
}
func (c *Client) Verify(token string) (err error) {
split := strings.Split(token, ".")
if len(split) != 3 {
return errors.New("invalid purchase order token")
}
// 解析header
header, err := GetHeader(split[0])
if err != nil {
return errors.WithMessage(err, "get header failed")
}
c.Header = header
if len(header.X5C) != 3 {
return errors.New("invalid x5c header")
}
// 解析payload
payload, err := GetPayload(split[1])
if err != nil {
return errors.WithMessage(err, "get payload failed")
}
c.Payload = payload
// 证书链验证
leafCert, err := LoadCertificate(header.X5C[0])
if err != nil {
return errors.WithMessage(err, "load leaf certificate failed")
}
caCert, err := LoadCertificate(header.X5C[1])
if err != nil {
return errors.WithMessage(err, "load ca certificate failed")
}
rootCert, err := LoadCertificate(header.X5C[2])
if err != nil {
return errors.WithMessage(err, "load root certificate failed")
}
err = leafCert.CheckSignatureFrom(caCert)
if err != nil {
return errors.WithMessage(err, "check leaf from ca signature failed")
}
err = caCert.CheckSignatureFrom(rootCert)
if err != nil {
return errors.WithMessage(err, "check ca from root certificate failed")
}
// 子证书oid验证
extensions := types.Slice[*pkix.Extension](slice.Map[pkix.Extension, *pkix.Extension](leafCert.Extensions, func(index int, item pkix.Extension) *pkix.Extension {
return &item
}))
_, find := extensions.Find(func(extension *pkix.Extension) bool {
return extension.Id.String() == oID
})
if !find {
return errors.New("leaf certificate oid not found in extensions")
}
// 完整验证
_, err = jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return leafCert.PublicKey, nil
})
if err != nil {
return errors.WithMessage(err, "parse order failed")
}
return nil
}
func (c *Client) QueryOrder(purchaseToken, purchaseOrderID string) (r *Response, err error) {
body := types.Map[string]{
"purchaseOrderId": purchaseOrderID,
"purchaseToken": purchaseToken,
}
token, err := c.GetToken(body)
if err != nil {
return nil, errors.WithMessage(err, "get token failed")
}
client := resty.New()
timeout, cancelFunc := context.WithTimeout(context.Background(), time.Second*10)
defer cancelFunc()
post, err := client.R().SetBody(body).SetContext(timeout).SetHeaders(types.Map[string]{
"Authorization": fmt.Sprintf("Bearer %s", token),
"Content-Type": "application/json;charset=UTF-8",
}).Post(QueryOrder)
if err != nil {
return nil, errors.WithMessage(err, "http client query failed")
}
r = &Response{}
err = fjson.UnmarshalFromString(post.String(), r)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal failed")
}
return r, nil
}
func (c *Client) Check(purchaseToken, purchaseOrderID string) (err error) {
order, err := c.QueryOrder(purchaseToken, purchaseOrderID)
if err != nil {
return errors.WithMessage(err, "query order failed")
}
if !order.ResponseOK() {
return errors.New("query order response is not ok")
}
return c.Verify(order.JWSPurchaseOrder)
}
func GetHeader(s string) (*Header, error) {
s = Base64RawStdDecode(s)
h := &Header{}
err := fjson.UnmarshalFromString(s, h)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal failed")
}
return h, nil
}
func GetPayload(s string) (*Payload, error) {
s = Base64RawStdDecode(s)
h := &Payload{}
err := fjson.UnmarshalFromString(s, h)
if err != nil {
return nil, errors.WithMessage(err, "json unmarshal failed")
}
return h, nil
}
func Base64RawStdDecode(s string) string {
decodeString, _ := base64.RawStdEncoding.DecodeString(s)
return string(decodeString)
}
func Base64RawStdEncode(s string) string {
return base64.RawStdEncoding.EncodeToString([]byte(s))
}
func LoadCertificate(key string) (*x509.Certificate, error) {
if !strings.HasPrefix(key, "-----BEGIN") {
key = fmt.Sprintf(`-----BEGIN CERTIFICATE-----
%s
-----END CERTIFICATE-----`, key)
}
pemBlock, _ := pem.Decode([]byte(key))
if pemBlock == nil {
return nil, errors.New("pem decode failed")
}
cert, err := x509.ParseCertificate(pemBlock.Bytes)
if err != nil {
return nil, errors.New("failed to parse certificate")
}
return cert, nil
}