-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathparser.go
More file actions
249 lines (204 loc) · 5.99 KB
/
parser.go
File metadata and controls
249 lines (204 loc) · 5.99 KB
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
package siwe
import (
"net/url"
"regexp"
"strings"
"time"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
// SIWEMessage is the final structured form of a parsed SIWE message.
// REF: https://eips.ethereum.org/EIPS/eip-4361
type SIWEMessage struct {
Raw string
Domain string
Address string
Statement *string
URI url.URL
Version string
ChainID string
Nonce string
IssuedAt time.Time
ExpirationTime *time.Time
NotBefore *time.Time
RequestID *string
Resources []*url.URL
}
const headerSuffix = " wants you to sign in with your Ethereum account:"
var addressPattern = regexp.MustCompile("^0x[a-fA-F0-9]{40}$")
func ParseMessage(raw string) (*SIWEMessage, error) {
lines := strings.Split(raw, "\n")
if len(lines) < 6 {
return nil, ErrMessageTooShort
}
// Parse first line exactly
header := lines[0]
if !strings.HasSuffix(header, headerSuffix) {
return nil, ErrInvalidHeader
}
domain := strings.TrimSpace(strings.TrimSuffix(header, headerSuffix))
if !IsValidDomain(domain) {
return nil, ErrInvalidDomain
}
address := strings.TrimSpace(lines[1])
if !addressPattern.MatchString(address) {
return nil, ErrInvalidAddress
}
// Ethereum addresses are protocol-level case-insensitive: 0xABC... and
// 0xabc... are the same wallet. EIP-55 mixed-case is a visual checksum,
// not a distinct identifier. We normalize to lowercase here so callers
// (notably web3GrantEthereum, which uses Address as part of the
// identity provider_id) see a single canonical form and the same
// wallet cannot create duplicate auth.identities rows by signing in
// with different case variants. See issue #2264. This mirrors the
// existing email lowercase-normalization in models.Identity.BeforeUpdate.
address = strings.ToLower(address)
msg := &SIWEMessage{
Raw: raw,
Domain: domain,
Address: address,
}
if lines[2] != "" {
return nil, ErrThirdLineNotEmpty
}
startIndex := 3
if lines[3] != "" && lines[4] == "" {
statement := lines[3]
msg.Statement = &statement
startIndex = 5
}
inResources := false
for i := startIndex; i < len(lines); i++ {
line := strings.TrimSpace(lines[i])
if inResources {
if after, ok := strings.CutPrefix(line, "- "); ok {
resource := strings.TrimSpace(after)
resourceURL, err := url.ParseRequestURI(resource)
if err != nil {
return nil, errInvalidResource(len(msg.Resources))
}
msg.Resources = append(msg.Resources, resourceURL)
continue
} else {
inResources = false
}
}
if line == "Resources:" {
inResources = true
continue
}
if line == "" {
continue
}
key, value, found := strings.Cut(line, ":")
if !found {
return nil, errUnparsableLine(i)
}
value = strings.TrimSpace(value)
switch key {
case "URI":
uri, err := url.ParseRequestURI(value)
if err != nil {
return nil, ErrInvalidURI
}
msg.URI = *uri
case "Version":
msg.Version = value
case "Chain ID":
if value == "" || !isValidEthereumNetwork(value) {
return nil, ErrInvalidChainID
}
msg.ChainID = value
case "Nonce":
// this is supposed to be REQUIRED >8 chr alphanum but we'll leave it for now for gotrue's nonce impl
msg.Nonce = value
case "Issued At":
ts, err := time.Parse(time.RFC3339, value)
if err != nil {
ts, err = time.Parse(time.RFC3339Nano, value)
if err != nil {
return nil, ErrInvalidIssuedAt
}
}
if ts.IsZero() {
return nil, ErrMissingIssuedAt
}
msg.IssuedAt = ts
case "Expiration Time":
ts, err := time.Parse(time.RFC3339, value)
if err != nil {
ts, err = time.Parse(time.RFC3339Nano, value)
if err != nil {
return nil, ErrInvalidExpirationTime
}
}
msg.ExpirationTime = &ts
case "Not Before":
ts, err := time.Parse(time.RFC3339, value)
if err != nil {
ts, err = time.Parse(time.RFC3339Nano, value)
if err != nil {
return nil, ErrInvalidNotBefore
}
}
msg.NotBefore = &ts
case "Request ID":
// This is supposed to be a pchar (RFC 3986) but generally we'll keep it as any str for now
msg.RequestID = &value
}
}
if msg.Version != "1" {
return nil, errUnsupportedVersion(msg.Version)
}
if msg.IssuedAt.IsZero() {
return nil, ErrMissingIssuedAt
}
if msg.URI.String() == "" {
return nil, ErrMissingURI
}
if msg.ExpirationTime != nil && !msg.IssuedAt.IsZero() {
if msg.IssuedAt.After(*msg.ExpirationTime) {
return nil, ErrIssuedAfterExpiration
}
}
if msg.NotBefore != nil && msg.ExpirationTime != nil {
if msg.NotBefore.After(*msg.ExpirationTime) {
return nil, ErrNotBeforeAfterExpiration
}
}
return msg, nil
}
// VerifySignature validates that the signature was created by the private key
// corresponding to the address in the message. This performs ECDSA recovery
// which is computationally expensive, so it should be called only after
// ParseMessage has validated the message structure.
//
// The signature must be a 65-byte hex string in the format: 0x{R}{S}{V}
// where R and S are 32 bytes each and V is 1 byte.
//
// Returns true if the recovered address matches the message address (case-insensitive).
func (m *SIWEMessage) VerifySignature(signatureHex string) bool {
sig, err := hexutil.Decode(signatureHex)
if err != nil || len(sig) != 65 {
panic("siwe: signature must be a 65-byte hex string")
}
// Create signature in [R || S || V] format
signature := make([]byte, 65)
copy(signature, sig)
// Normalize V if needed
// #nosec G602
if signature[64] >= 27 {
signature[64] -= 27 // #nosec G602
}
hash := accounts.TextHash([]byte(m.Raw))
// Recover public key
pubKey, err := crypto.Ecrecover(hash, signature)
if err != nil {
panic("siwe: failed to recover public key: " + err.Error())
}
// Convert to address
recoveredAddr := common.BytesToAddress(crypto.Keccak256(pubKey[1:])[12:])
return strings.EqualFold(recoveredAddr.Hex(), m.Address)
}