-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.go
More file actions
239 lines (225 loc) · 6.32 KB
/
Copy pathutils.go
File metadata and controls
239 lines (225 loc) · 6.32 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
package siwe
import (
"crypto/rand"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
const nonceAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
// GenerateNonce returns a cryptographically random 17-character alphanumeric
// nonce suitable for the EIP-4361 `nonce` field.
func GenerateNonce() string {
// 17 chars of 62-symbol alphabet ≈ 101 bits of entropy.
out := make([]byte, 17)
buf := make([]byte, 17)
if _, err := rand.Read(buf); err != nil {
// crypto/rand should not fail in practice; if it does, panic is the
// least worst option since returning a weak nonce would silently
// compromise replay resistance.
panic(fmt.Errorf("siwe: crypto/rand failed: %w", err))
}
for i, b := range buf {
out[i] = nonceAlphabet[int(b)%len(nonceAlphabet)]
}
return string(out)
}
// validateNonce enforces the EIP-4361 nonce rule: 8+ alphanumeric characters.
func validateNonce(n string) error {
if len(n) < 8 {
return newErrorWith(ErrInvalidNonce, "8+ alphanumeric characters", n)
}
for i := 0; i < len(n); i++ {
b := n[i]
if !isALPHA(b) && !isDIGIT(b) {
return newErrorWith(ErrInvalidNonce, "alphanumeric characters only", n)
}
}
return nil
}
// isValidScheme validates an RFC 3986 URI scheme per the ABNF.
func isValidScheme(s string) bool {
if s == "" {
return false
}
return pScheme(s, 0) == len(s)
}
// isValidStatement validates the EIP-4361 ABNF statement rule. Per the ABNF:
//
// statement = 1*( %d32-33 / %d35-36 / %d38-59 / %d61 / %d63-64 /
// %d65-90 / %d91 / %d93 / %d95 / %d97-122 / %d126)
//
// In effect: printable ASCII (0x20-0x7e) excluding backtick `, angle brackets,
// braces, and pipe. Line breaks are disallowed. The empty string is also
// permitted (see `empty-statement` in the grammar).
func isValidStatement(s string) bool {
for i := 0; i < len(s); i++ {
b := s[i]
if b == '<' || b == '>' || b == '{' || b == '}' || b == '|' || b == '`' {
return false
}
if b < 0x20 || b > 0x7e {
return false
}
}
return true
}
// isValidRequestID validates the EIP-4361 ABNF request-id rule (`*pchar`).
func isValidRequestID(s string) bool {
for i := 0; i < len(s); {
if j := pPctEncoded(s, i); j != -1 {
i = j
continue
}
if isPcharLiteral(s[i]) {
i++
continue
}
return false
}
return true
}
// isValidISO8601 validates a strict ISO 8601 / RFC 3339 datetime string using
// Go's time package. Rejects loose formats like "Wed Oct 05 2011".
func isValidISO8601(s string) bool {
_, err := parseISO8601(s)
return err == nil
}
// parseISO8601 parses a datetime per the EIP-4361 `date-time` rule (RFC 3339
// date-time). Accepts fractional seconds of any precision and timezone
// offsets including "Z".
func parseISO8601(s string) (time.Time, error) {
// Must match: full-date "T" full-time where full-time = partial-time time-offset.
// Validate structure with a regex-style scan, then let time.Parse enforce
// the semantic ranges (e.g. month 1-12, day in month range).
if !syntacticISO8601(s) {
return time.Time{}, fmt.Errorf("invalid ISO 8601 syntax: %q", s)
}
// RFC3339Nano covers fractional seconds and any offset including Z.
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
return t, nil
}
// Some RFC 3339 corners (e.g. upper-case T/Z omitted) fall through. Try a
// lower/upper-case normalized variant since the ABNF is case-insensitive
// on the T and Z literals but RFC3339Nano only accepts uppercase.
norm := strings.ReplaceAll(s, "t", "T")
norm = strings.ReplaceAll(norm, "z", "Z")
return time.Parse(time.RFC3339Nano, norm)
}
// syntacticISO8601 checks YYYY-MM-DDTHH:MM:SS[.frac][Z|±HH:MM] shape quickly
// before handing to time.Parse. Rejects garbage like "Wed Oct 05 ...".
func syntacticISO8601(s string) bool {
// Minimum: 2006-01-02T15:04:05Z → 20 chars
if len(s) < 20 {
return false
}
if !(isDIGIT(s[0]) && isDIGIT(s[1]) && isDIGIT(s[2]) && isDIGIT(s[3])) {
return false
}
if s[4] != '-' || !isDIGIT(s[5]) || !isDIGIT(s[6]) {
return false
}
if s[7] != '-' || !isDIGIT(s[8]) || !isDIGIT(s[9]) {
return false
}
if s[10] != 'T' && s[10] != 't' {
return false
}
if !isDIGIT(s[11]) || !isDIGIT(s[12]) || s[13] != ':' {
return false
}
if !isDIGIT(s[14]) || !isDIGIT(s[15]) || s[16] != ':' {
return false
}
if !isDIGIT(s[17]) || !isDIGIT(s[18]) {
return false
}
i := 19
if i < len(s) && s[i] == '.' {
i++
start := i
for i < len(s) && isDIGIT(s[i]) {
i++
}
if i == start {
return false
}
}
if i >= len(s) {
return false
}
if s[i] == 'Z' || s[i] == 'z' {
return i+1 == len(s)
}
if s[i] == '+' || s[i] == '-' {
if i+6 != len(s) {
return false
}
return isDIGIT(s[i+1]) && isDIGIT(s[i+2]) && s[i+3] == ':' && isDIGIT(s[i+4]) && isDIGIT(s[i+5])
}
return false
}
// eip55 returns the EIP-55 checksummed hex address (with `0x` prefix).
func eip55(addr common.Address) string {
raw := hex.EncodeToString(addr[:])
hash := crypto.Keccak256([]byte(raw))
out := make([]byte, 42)
out[0] = '0'
out[1] = 'x'
for i := 0; i < 40; i++ {
c := raw[i]
hv := hash[i/2]
if i%2 == 0 {
hv >>= 4
}
if (c >= 'a' && c <= 'f') && (hv&0x8) != 0 {
out[2+i] = c - 32 // to upper
} else {
out[2+i] = c
}
}
return string(out)
}
// isEIP55 reports whether a mixed-case address matches the EIP-55 checksum.
func isEIP55(addressWithPrefix string) bool {
if !strings.HasPrefix(addressWithPrefix, "0x") || len(addressWithPrefix) != 42 {
return false
}
// Reject if the hex contains any non-hex characters.
for i := 2; i < 42; i++ {
if !isHEXDIG(addressWithPrefix[i]) {
return false
}
}
var addr common.Address
_, err := hex.Decode(addr[:], []byte(addressWithPrefix[2:]))
if err != nil {
return false
}
return eip55(addr) == addressWithPrefix
}
// classifyAddressCase returns one of "upper", "lower", "mixed" for a 40-char
// hex string (no 0x prefix). Distinguishes between addresses where the checksum
// can be enforced ("mixed") and where it cannot ("upper"/"lower").
func classifyAddressCase(hexPart string) string {
hasLower := false
hasUpper := false
for i := 0; i < len(hexPart); i++ {
b := hexPart[i]
if b >= 'a' && b <= 'f' {
hasLower = true
}
if b >= 'A' && b <= 'F' {
hasUpper = true
}
}
if hasLower && hasUpper {
return "mixed"
}
if hasUpper {
return "upper"
}
return "lower"
}