Repository navigation
Expand file tree
/
Copy pathauth_pair.go
More file actions
302 lines (259 loc) · 7.67 KB
/
Copy pathauth_pair.go
File metadata and controls
302 lines (259 loc) · 7.67 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
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
package api
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/RealityLink-Tech/MoonHub/pkg/devices"
"github.com/google/uuid"
)
const (
maxPairAttempts = 5
pairLockoutDuration = 5 * time.Minute
)
const maxAuthBodyBytes = 64 * 1024
// AuthHandler handles device pairing and authentication API requests.
type AuthHandler struct {
pairingManager *devices.PairingManager
deviceStore *devices.DeviceStore
// Rate limiting
mu sync.Mutex
attempts int
lastAttempt time.Time
lockedUntil time.Time
}
// NewAuthHandler creates a new auth API handler.
func NewAuthHandler(pairingManager *devices.PairingManager, deviceStore *devices.DeviceStore) *AuthHandler {
return &AuthHandler{
pairingManager: pairingManager,
deviceStore: deviceStore,
}
}
// RegisterRoutes registers auth routes with the mux.
func (h *AuthHandler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/auth/status", h.handleAuthStatus)
mux.HandleFunc("POST /api/auth/pair", h.handleAuthPair)
mux.HandleFunc("POST /api/auth/verify", h.handleAuthVerify)
}
// AuthStatusResponse represents the auth status response.
type AuthStatusResponse struct {
Success bool `json:"success"`
Data struct {
Code string `json:"code"`
Paired bool `json:"paired"`
} `json:"data"`
}
// PairRequest represents a pairing request.
type PairRequest struct {
Code string `json:"code"`
DeviceID string `json:"deviceId,omitempty"`
DeviceName string `json:"deviceName,omitempty"`
}
// UnmarshalJSON accepts camelCase fields and snake_case aliases (device_id, device_name).
func (p *PairRequest) UnmarshalJSON(data []byte) error {
type wire struct {
Code string `json:"code"`
DeviceID string `json:"deviceId"`
DeviceName string `json:"deviceName"`
DeviceIDSnake string `json:"device_id"`
DeviceNameSnk string `json:"device_name"`
}
var w wire
if err := json.Unmarshal(data, &w); err != nil {
return err
}
p.Code = w.Code
p.DeviceID = w.DeviceID
if p.DeviceID == "" {
p.DeviceID = w.DeviceIDSnake
}
p.DeviceName = w.DeviceName
if p.DeviceName == "" {
p.DeviceName = w.DeviceNameSnk
}
return nil
}
// PairResponse represents a pairing response.
type PairResponse struct {
Success bool `json:"success"`
Data struct {
Token string `json:"token,omitempty"`
TokenExpiresAt time.Time `json:"tokenExpiresAt,omitempty"`
Device *devices.PairedDevice `json:"device,omitempty"`
} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
// VerifyResponse represents a token verification response.
type VerifyResponse struct {
Success bool `json:"success"`
Data struct {
Valid bool `json:"valid"`
DeviceID string `json:"deviceId,omitempty"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
} `json:"data"`
}
// handleAuthStatus handles GET /api/auth/status - returns current pairing code status.
func (h *AuthHandler) handleAuthStatus(w http.ResponseWriter, r *http.Request) {
if !requireLANClient(w, r) {
return
}
code := h.pairingManager.GetCurrentCode()
paired := h.pairingManager.IsPaired()
// If already paired, don't show the code
if paired {
code = ""
}
response := AuthStatusResponse{
Success: true,
}
response.Data.Code = code
response.Data.Paired = paired
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
// handleAuthPair handles POST /api/auth/pair - pairs a device with authorization code.
func (h *AuthHandler) handleAuthPair(w http.ResponseWriter, r *http.Request) {
if !requireLANClient(w, r) {
return
}
// Rate limit check
h.mu.Lock()
if !h.lockedUntil.IsZero() && time.Now().Before(h.lockedUntil) {
h.mu.Unlock()
writeAuthError(w, http.StatusTooManyRequests, "too many failed attempts, code regenerated")
return
}
h.mu.Unlock()
// Parse request
var req PairRequest
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxAuthBodyBytes))
if err := dec.Decode(&req); err != nil {
writeAuthError(w, http.StatusBadRequest, "invalid request body")
return
}
// Validate code
req.Code = strings.TrimSpace(strings.ToUpper(req.Code))
if req.Code == "" {
writeAuthError(w, http.StatusBadRequest, "pairing code is required")
return
}
// Generate device ID if not provided
if req.DeviceID == "" {
req.DeviceID = uuid.New().String()
}
// Generate device name if not provided
deviceName := req.DeviceName
if deviceName == "" {
deviceName = "PWA Client"
}
// Get client IP
ipAddr := getClientIP(r)
// Create device info
deviceInfo := &devices.PairedDevice{
ID: req.DeviceID,
Name: deviceName,
IPAddress: ipAddr,
UserAgent: r.UserAgent(),
}
// Validate pairing code
result, err := h.pairingManager.ValidateCode(req.Code, deviceInfo)
if err != nil {
log.Printf("pairing error: %v", err)
writeAuthError(w, http.StatusInternalServerError, "pairing failed")
return
}
if !result.Success {
h.mu.Lock()
h.attempts++
h.lastAttempt = time.Now()
if h.attempts >= maxPairAttempts {
h.lockedUntil = time.Now().Add(pairLockoutDuration)
h.attempts = 0
// Auto-regenerate code after lockout
if h.pairingManager != nil {
if _, regenErr := h.pairingManager.RegenerateCode(); regenErr != nil {
log.Printf("failed to regenerate pairing code after lockout: %v", regenErr)
}
}
}
h.mu.Unlock()
writeAuthError(w, http.StatusBadRequest, result.Error)
return
}
// Reset attempts on successful pairing
h.mu.Lock()
h.attempts = 0
h.mu.Unlock()
// Return success with token
response := PairResponse{
Success: true,
}
response.Data.Token = result.Token
response.Data.TokenExpiresAt = result.TokenExpiresAt
response.Data.Device = result.Device
log.Printf("device paired: %s (%s)", deviceInfo.ID, deviceInfo.Name)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
// handleAuthVerify handles POST /api/auth/verify - verifies a Bearer token.
func (h *AuthHandler) handleAuthVerify(w http.ResponseWriter, r *http.Request) {
if !requireLANClient(w, r) {
return
}
token := ""
if authHeader := r.Header.Get("Authorization"); authHeader != "" {
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) == 2 && strings.ToLower(parts[0]) == "bearer" {
token = strings.TrimSpace(parts[1])
}
}
if token == "" {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxAuthBodyBytes))
if err == nil && len(strings.TrimSpace(string(body))) > 0 {
var payload struct {
Token string `json:"token"`
}
if json.Unmarshal(body, &payload) == nil {
token = strings.TrimSpace(payload.Token)
}
}
}
if token == "" {
writeAuthError(w, http.StatusUnauthorized, "token required (Authorization: Bearer or JSON {\"token\"})")
return
}
// Validate token
validation := h.deviceStore.ValidateToken(token)
response := VerifyResponse{
Success: true,
}
response.Data.Valid = validation.Valid
if validation.Valid {
response.Data.DeviceID = validation.DeviceID
response.Data.ExpiresAt = validation.ExpiresAt
// Update last seen
_ = h.deviceStore.UpdateLastSeen(validation.DeviceID, getClientIP(r))
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
// writeAuthError writes an error response.
func writeAuthError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]interface{}{
"success": false,
"error": message,
})
}
// getClientIP extracts the client IP string for persistence (paired device last-seen).
func getClientIP(r *http.Request) string {
ip := ClientIPFromRequest(r)
if ip == nil {
return ""
}
return ip.String()
}