-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathsiwe.go
383 lines (311 loc) · 9.2 KB
/
siwe.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package siwe
import (
"crypto/ecdsa"
"fmt"
"net/url"
"strconv"
"strings"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func buildAuthority(uri *url.URL) string {
authority := uri.Host
if uri.User != nil {
authority = fmt.Sprintf("%s@%s", uri.User.String(), authority)
}
return authority
}
func validateDomain(domain *string) (bool, error) {
if isEmpty(domain) {
return false, &InvalidMessage{"`domain` must not be empty"}
}
validateDomain, err := url.Parse(fmt.Sprintf("https://%s", *domain))
if err != nil {
return false, &InvalidMessage{"Invalid format for field `domain`"}
}
authority := buildAuthority(validateDomain)
if authority != *domain {
return false, &InvalidMessage{"Invalid format for field `domain`"}
}
return true, nil
}
func validateURI(uri *string) (*url.URL, error) {
if isEmpty(uri) {
return nil, &InvalidMessage{"`uri` must not be empty"}
}
validateURI, err := url.Parse(*uri)
if err != nil {
return nil, &InvalidMessage{"Invalid format for field `uri`"}
}
return validateURI, nil
}
// InitMessage creates a Message object with the provided parameters
func InitMessage(domain, address, uri, nonce string, options map[string]interface{}) (*Message, error) {
if ok, err := validateDomain(&domain); !ok {
return nil, err
}
if isEmpty(&address) {
return nil, &InvalidMessage{"`address` must not be empty"}
}
validateURI, err := validateURI(&uri)
if err != nil {
return nil, err
}
if isEmpty(&nonce) {
return nil, &InvalidMessage{"`nonce` must not be empty"}
}
var statement *string
if val, ok := options["statement"]; ok {
value := val.(string)
statement = &value
}
var chainId int
if val, ok := options["chainId"]; ok {
switch val.(type) {
case float64:
chainId = int(val.(float64))
case int:
chainId = val.(int)
case string:
parsed, err := strconv.Atoi(val.(string))
if err != nil {
return nil, &InvalidMessage{"Invalid format for field `chainId`, must be an integer"}
}
chainId = parsed
default:
return nil, &InvalidMessage{"`chainId` must be a string or a integer"}
}
} else {
chainId = 1
}
var issuedAt string
timestamp, err := parseTimestamp(options, "issuedAt")
if err != nil {
return nil, err
}
if timestamp != nil {
issuedAt = *timestamp
} else {
issuedAt = time.Now().UTC().Format(time.RFC3339)
}
var expirationTime *string
timestamp, err = parseTimestamp(options, "expirationTime")
if err != nil {
return nil, err
}
if timestamp != nil {
expirationTime = timestamp
}
var notBefore *string
timestamp, err = parseTimestamp(options, "notBefore")
if err != nil {
return nil, err
}
if timestamp != nil {
notBefore = timestamp
}
var requestID *string
if val, ok := isStringAndNotEmpty(options, "requestId"); ok {
requestID = val
}
var resources []url.URL
if val, ok := options["resources"]; ok {
switch val.(type) {
case []url.URL:
resources = val.([]url.URL)
default:
return nil, &InvalidMessage{"`resources` must be a []url.URL"}
}
}
return &Message{
domain: domain,
address: common.HexToAddress(address),
uri: *validateURI,
version: "1",
statement: statement,
nonce: nonce,
chainID: chainId,
issuedAt: issuedAt,
expirationTime: expirationTime,
notBefore: notBefore,
requestID: requestID,
resources: resources,
}, nil
}
func parseMessage(message string) (map[string]interface{}, error) {
match := _SIWE_MESSAGE.FindStringSubmatch(message)
if match == nil {
return nil, &InvalidMessage{"Message could not be parsed"}
}
result := make(map[string]interface{})
for i, name := range _SIWE_MESSAGE.SubexpNames() {
if i != 0 && name != "" && match[i] != "" {
result[name] = match[i]
}
}
if _, ok := result["domain"]; !ok {
return nil, &InvalidMessage{"`domain` must not be empty"}
}
domain := result["domain"].(string)
if ok, err := validateDomain(&domain); !ok {
return nil, err
}
if _, ok := result["uri"]; !ok {
return nil, &InvalidMessage{"`domain` must not be empty"}
}
uri := result["uri"].(string)
if _, err := validateURI(&uri); err != nil {
return nil, err
}
originalAddress := result["address"].(string)
parsedAddress := common.HexToAddress(originalAddress)
if originalAddress != parsedAddress.String() {
return nil, &InvalidMessage{"Address must be in EIP-55 format"}
}
if val, ok := result["resources"]; ok {
resources := strings.Split(val.(string), "\n- ")[1:]
validateResources := make([]url.URL, len(resources))
for i, resource := range resources {
validateResource, err := url.Parse(resource)
if err != nil {
return nil, &InvalidMessage{fmt.Sprintf("Invalid format for field `resources` at position %d", i)}
}
validateResources[i] = *validateResource
}
result["resources"] = validateResources
}
return result, nil
}
// ParseMessage returns a Message object by parsing an EIP-4361 formatted string
func ParseMessage(message string) (*Message, error) {
result, err := parseMessage(message)
if err != nil {
return nil, err
}
parsed, err := InitMessage(
result["domain"].(string),
result["address"].(string),
result["uri"].(string),
result["nonce"].(string),
result,
)
if err != nil {
return nil, err
}
return parsed, nil
}
func (m *Message) eip191Hash() common.Hash {
// Ref: https://stackoverflow.com/questions/49085737/geth-ecrecover-invalid-signature-recovery-id
data := []byte(m.String())
msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
return crypto.Keccak256Hash([]byte(msg))
}
// ValidNow validates the time constraints of the message at current time.
func (m *Message) ValidNow() (bool, error) {
return m.ValidAt(time.Now().UTC())
}
// ValidAt validates the time constraints of the message at a specific point in time.
func (m *Message) ValidAt(when time.Time) (bool, error) {
if m.expirationTime != nil {
if when.After(*m.getExpirationTime()) {
return false, &ExpiredMessage{"Message expired"}
}
}
if m.notBefore != nil {
if when.Before(*m.getNotBefore()) {
return false, &InvalidMessage{"Message not yet valid"}
}
}
return true, nil
}
// VerifyEIP191 validates the integrity of the object by matching it's signature.
func (m *Message) VerifyEIP191(signature string) (*ecdsa.PublicKey, error) {
if isEmpty(&signature) {
return nil, &InvalidSignature{"Signature cannot be empty"}
}
sigBytes, err := hexutil.Decode(signature)
if err != nil {
return nil, &InvalidSignature{"Failed to decode signature"}
}
// Ref:https://github.com/ethereum/go-ethereum/blob/55599ee95d4151a2502465e0afc7c47bd1acba77/internal/ethapi/api.go#L442
sigBytes[64] %= 27
if sigBytes[64] != 0 && sigBytes[64] != 1 {
return nil, &InvalidSignature{"Invalid signature recovery byte"}
}
pkey, err := crypto.SigToPub(m.eip191Hash().Bytes(), sigBytes)
if err != nil {
return nil, &InvalidSignature{"Failed to recover public key from signature"}
}
address := crypto.PubkeyToAddress(*pkey)
if address != m.address {
return nil, &InvalidSignature{"Signer address must match message address"}
}
return pkey, nil
}
// Verify validates time constraints and integrity of the object by matching it's signature.
func (m *Message) Verify(signature string, domain *string, nonce *string, timestamp *time.Time) (*ecdsa.PublicKey, error) {
var err error
if timestamp != nil {
_, err = m.ValidAt(*timestamp)
} else {
_, err = m.ValidNow()
}
if err != nil {
return nil, err
}
if domain != nil {
if m.GetDomain() != *domain {
return nil, &InvalidSignature{"Message domain doesn't match"}
}
}
if nonce != nil {
if m.GetNonce() != *nonce {
return nil, &InvalidSignature{"Message nonce doesn't match"}
}
}
return m.VerifyEIP191(signature)
}
func (m *Message) prepareMessage() string {
greeting := fmt.Sprintf("%s wants you to sign in with your Ethereum account:", m.domain)
headerArr := []string{greeting, m.address.String()}
if isEmpty(m.statement) {
headerArr = append(headerArr, "\n")
} else {
headerArr = append(headerArr, fmt.Sprintf("\n%s\n", *m.statement))
}
header := strings.Join(headerArr, "\n")
uri := fmt.Sprintf("URI: %s", m.uri.String())
version := fmt.Sprintf("Version: %s", m.version)
chainId := fmt.Sprintf("Chain ID: %d", m.chainID)
nonce := fmt.Sprintf("Nonce: %s", m.nonce)
issuedAt := fmt.Sprintf("Issued At: %s", m.issuedAt)
bodyArr := []string{uri, version, chainId, nonce, issuedAt}
if !isEmpty(m.expirationTime) {
value := fmt.Sprintf("Expiration Time: %s", *m.expirationTime)
bodyArr = append(bodyArr, value)
}
if !isEmpty(m.notBefore) {
value := fmt.Sprintf("Not Before: %s", *m.notBefore)
bodyArr = append(bodyArr, value)
}
if !isEmpty(m.requestID) {
value := fmt.Sprintf("Request ID: %s", *m.requestID)
bodyArr = append(bodyArr, value)
}
if len(m.resources) > 0 {
resourcesArr := make([]string, len(m.resources))
for i, v := range m.resources {
resourcesArr[i] = fmt.Sprintf("- %s", v.String())
}
resources := strings.Join(resourcesArr, "\n")
value := fmt.Sprintf("Resources:\n%s", resources)
bodyArr = append(bodyArr, value)
}
body := strings.Join(bodyArr, "\n")
return strings.Join([]string{header, body}, "\n")
}
func (m *Message) String() string {
return m.prepareMessage()
}