File size: 15,378 Bytes
1aff627
 
 
 
 
 
 
 
 
 
 
126657d
 
 
 
 
 
 
 
 
 
 
 
1aff627
 
0de9042
4a51730
 
0de9042
 
 
1aff627
0de9042
 
c4bfa25
1aff627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51730
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1aff627
 
 
 
 
 
 
126657d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1aff627
126657d
 
 
 
 
26aea6a
126657d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1aff627
 
 
 
126657d
1aff627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23afbae
1aff627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126657d
 
362bce4
1aff627
 
759a4cb
1aff627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126657d
 
 
fae00cd
13115cd
126657d
 
 
 
 
 
 
 
 
 
1aff627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126657d
 
1aff627
 
 
 
 
759a4cb
 
 
d36fd84
759a4cb
 
 
4a51730
126657d
 
759a4cb
 
23afbae
1aff627
4a51730
 
8b6c2c8
4a51730
 
 
 
 
 
 
 
362bce4
 
c01b33e
362bce4
 
 
0de9042
1aff627
 
126657d
0de9042
 
 
 
 
 
 
 
 
 
 
 
759a4cb
1aff627
 
 
5936a59
1aff627
 
 
0de9042
1aff627
 
 
 
b9f287e
1aff627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de9042
 
 
 
 
 
 
 
1aff627
 
 
126657d
 
 
 
 
 
1aff627
126657d
 
 
 
 
 
1aff627
 
 
 
 
 
 
 
 
 
126657d
 
 
1aff627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
from fastapi import Request 
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError
import hashlib
import secrets
import base58
import requests
import json
import httpx
import jwt
from jwt.exceptions import (
    ExpiredSignatureError, 
    InvalidAudienceError, 
    InvalidSignatureError, 
    DecodeError
)


import datetime
import time

from geopy.geocoders import Nominatim
from geopy.exc import GeocoderServiceError
from .mongodbconnection import provideClient
from eth_account import Account
from eth_account.messages import encode_defunct



geolocator = Nominatim(user_agent="velocity")
dbclient=provideClient()
db=dbclient["sdklogs_db"]
coll=db["sdklogs_col"]




def GEOCODER(coords):
    try:
        lat = coords.get("latitude")
        lon = coords.get("longitude")

        if lat is None or lon is None:
            return {
                "status": "error",
                "message": "Missing latitude or longitude.",
                "data": None
            }

        location = geolocator.reverse(f"{lat}, {lon}", exactly_one=True)

        if location and "address" in location.raw:
            country_name = location.raw["address"].get("country")
            country_code = location.raw["address"].get("country_code")

            return {
                "status": "success",
                "message": "Location resolved successfully.",
                "data": {
                    "country": country_name,
                    "code": country_code.upper() if country_code else None
                }
            }

        return {
            "status": "not_found",
            "message": "Location could not be resolved.",
            "data": None
        }

    except GeocoderServiceError as e:
        return {
            "status": "error",
            "message": f"Geocoding service error: {str(e)}",
            "data": None
        }

    except Exception as e:
        return {
            "status": "error",
            "message": f"Unexpected error: {str(e)}",
            "data": None
        }




def SignatureVerification(X_401_Addr,X_401_Nonce,X_401_Sign,challange):

    
            if X_401_Addr and X_401_Nonce and X_401_Sign:

                try:

                    signature_bytes = base58.b58decode(X_401_Sign)
                    verify_key = VerifyKey(base58.b58decode(X_401_Addr))
                    payload_bytes = challange.encode("utf-8")
    
                    verify_key.verify(payload_bytes, signature_bytes)
                    return True
                         
                except BadSignatureError:
                    
                    return False








def verify_ethereum_signature(address, signature, original_payload):
  
    try:
     
        message = encode_defunct(text=original_payload)

        recovered_address = Account.recover_message(message, signature=signature)

        return recovered_address.lower() == address.lower()
    except Exception as e:
        print(f"Verification failed: {e}")
        return False




def SecretNonceGenerator():
        random_bytes = secrets.token_bytes(32)
        return hashlib.sha256(random_bytes).hexdigest()




def generateJWT(wallet,aud):

    EXPIRY_DURATION = datetime.timedelta(days=3)
    try:
    
        payload = {
            
            "sub": wallet,
            "aud":aud,
            "issuer":"velocity401",
            "exp": datetime.datetime.utcnow() + EXPIRY_DURATION, 
            "iat": datetime.datetime.utcnow()
            
        }

        token = jwt.encode(payload, "jwttoken", algorithm="HS256")

        return token
    except Exception as e:
         
        return None




def verifyJWT(token_string,aud):

    try:
        payload = jwt.decode(
            token_string, 
            "jwttoken", 
            algorithms=["HS256"],
            audience=aud,
            issuer="velocity401" 
        )
        
        wallet_address = payload.get("sub")
        print(f"βœ… Token valid for wallet: {wallet_address}")
        return wallet_address
        
    except ExpiredSignatureError:
        print("🚨 Token rejected: Signature has expired.")
        return None
    except InvalidAudienceError:
        print(f"🚨 Token rejected: Invalid audience. Expected '{EXPECTED_AUDIENCE}'.")
        return None
    except InvalidSignatureError:
        print("🚨 Token rejected: Invalid signature (key mismatch).")
        return None
    except DecodeError as e:
        print(f"🚨 Token rejected: Malformed JWT structure. Error: {e}")
        return None
    except Exception as e:
        print(f"⚠️ An unexpected error occurred during verification: {e}")
        return None




        


def TokenCheck(walletPublicKey,required_mint,mint_amount):
    
        url = f"https://mainnet.helius-rpc.com/?api-key=4e833ada-d32c-48c5-b020-c11b2253f25b"
        payload = {
            "jsonrpc": "2.0",
            "id": "1",
            "method": "getTokenAccountsByOwner",
            "params": [
                walletPublicKey,
                {"mint":required_mint},
                {"encoding": "jsonParsed"}
            ]
        }
    
        headers = {"Content-Type": "application/json"}
    
        try:
            
            response = requests.post(url, json=payload, headers=headers)
            response.raise_for_status()
            data = response.json()
            
        except requests.exceptions.RequestException as e:
            
            return {"status": False, "message": f"API Request Failed: {e}"}

    
        token_accounts = data.get("result", {}).get("value")

        if not token_accounts:
        
            return False
    
        try:
            
            account_info = token_accounts[0]["account"]["data"]["parsed"]["info"]
            token_amount = account_info["tokenAmount"]
            ui_amount = float(token_amount.get("uiAmount"))
            
        except (TypeError, KeyError, IndexError):

            return {"status": False, "message": "Could not parse token account data"}

        if ui_amount >= mint_amount:
            
            print(ui_amount)
            print(True)
            return True
            
        else:
            print(ui_amount)
            return False









class x401Kit(BaseHTTPMiddleware):


    def __init__(self, app,protected_paths:list):
        super().__init__(app)
        self.protected_paths = protected_paths
     
        


    async def dispatch(self, request: Request, call_next):
            


            if request.method == "OPTIONS":
                return await call_next(request)
            
            if not any(request.url.path.startswith(p) for p in self.protected_paths):
                return await call_next(request)
        


            NONCE=SecretNonceGenerator()
            
            X_401_Nonce=request.headers.get("X-401-Nonce")
            X_401_Sign=request.headers.get("X-401-Signature")
            X_401_Addr=request.headers.get("X-401-Addr")
            lat=request.headers.get("X-Lat")
            long=request.headers.get("X-Long")
            client_jwt=request.headers.get("x-jwt")
            aud=request.headers.get("origin")
            

        
          


        
            coords={
                                 
                "latitude":lat,
                "longitude":long
                
                }

            
        
           
            REQUIRED_SERVICE=None
            

            if client_jwt:
                        decoded=verifyJWT(client_jwt,aud)
                        return JSONResponse(
                                content={"status":"identified","token":X_401_Addr,"message":"identified already"},
                                status_code=200,
                                headers={
    
                                     "Access-Control-Allow-Origin": "*",
                                    "Access-Control-Allow-Credentials": "true"                        
                            
                                }
                                )


            
                
            if not X_401_Addr and not X_401_Nonce and not X_401_Sign :

                payload401={
                            
                        "X-401-Status":"Authrequired",
                        "x-401-Mechanism":"SOLANA",
                        "X-401-Nonce":NONCE,
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Credentials": "true",
                        "Access-Control-Expose-Headers": "x-401-Nonce, x-401-Mechanism, x-401-Status"
                }
    
                return JSONResponse(content={
                    
                    
                        "message":"401 Auth Required",
                        "information":"Non persistant stateless auth",
                        "issuer":"velocityinfra"
                
                },headers=payload401,status_code=401)
        



            required_mint = request.headers.get("required_mint")
            mint_amount=float(request.headers.get("mint_amount"))
            print(mint_amount)
            helius_api_key = request.headers.get("helius_api_key")
            geo_code=request.headers.get("geo_code")
            geo_code_locs=[request.headers.get("geo_code_locs")]
            eth=request.headers.get("eth")            

           
        

            challange=f"CHALLENGE::{X_401_Nonce}::{request.url.path}::VELOCITY401"

        
            signverify=None
            if eth=='true':
                
                signverify=verify_ethereum_signature(X_401_Addr,X_401_Sign,challange)

            else:
                signverify=SignatureVerification(X_401_Addr,X_401_Nonce,X_401_Sign,challange)
            
            

        
            tokenverify=None
            if required_mint =="no":
                tokenverify=True
            else:
                tokenverify=TokenCheck(X_401_Addr,required_mint,mint_amount)
            
            print(tokenverify)


            sdkpayload={
                
                "signer":X_401_Addr,
                 "challange":challange,
                "token_amount":mint_amount,
                "required_mint":required_mint,
                "sign_verification":signverify,
                "token_verification":tokenverify,
                "geo_code":geo_code,
                "restricted_loc":geo_code_locs
                
            }

            if signverify == True and tokenverify == True:


                        if geo_code=="true":
                            
                            country=GEOCODER(coords)
                            print(country)
                            sdkpayload["geography"]=country
                            
                            if country["data"] is None:
                                 return JSONResponse(
                                      
                                        content={"status": "locerror", "message": f"Auth error"},
                                        headers= {
                                                "Access-Control-Allow-Origin": "*",
                                                "Access-Control-Allow-Credentials": "true"
                                            },
                                            status_code=500
                                            )
                                    
                                 
                            if country["data"]["code"] in geo_code_locs:
                                
                                 return JSONResponse(
                                            content={"status": "locdeny", "message":f"access denied for {country['data']['country']}"},
                                            headers= {
                                                "Access-Control-Allow-Origin": "*",
                                                "Access-Control-Allow-Credentials": "true"
                                            },
                                            status_code=401
                                            )

                        coll.find_one_and_update(
                            {"owner":"system"},
                            {
                                "$push":{
                                    "logs":sdkpayload
                                }
                            })    
                    
                        response = await call_next(request)



                       


                
                        if response.headers.get("content-type") == "application/json":



                           

                            
                            
                            body_bytes = b""
                            async for chunk in response.body_iterator:
                                body_bytes += chunk

                            try:
                                data = json.loads(body_bytes.decode())
                            except json.JSONDecodeError:
                                return response


                            JWTTOKEN=generateJWT(X_401_Addr,aud)
                            data["token"] = JWTTOKEN
        
                            response_headers = dict(response.headers)
                            response_headers.pop("content-length", None)
                            print(data) 

                            return JSONResponse(
                                    content=data,
                                    status_code=response.status_code,
                                    headers=response_headers
                                    )


                        return response
                                                    

            elif tokenverify==False:
                        return JSONResponse(
                            content={"status": "error", "message": "Missing required token"},
                            status_code=500,
                            headers={
                                   "Access-Control-Allow-Origin": "*",
                                "Access-Control-Allow-Credentials": "true"
                            }
                            
                            )
                            
            elif signverify==False:
                        print("failed")
                        return JSONResponse(
                            content={"status": "error", "message": "bad signature"},
                            status_code=500,
                              headers={
                                   "Access-Control-Allow-Origin": "*",
                                    "Access-Control-Allow-Credentials": "true"
                            })
            


            else:
                        return JSONResponse(
                            content={"status": "error", "message": "Authentication failed"},
                            status_code=500,
                            headers={
                                "Access-Control-Allow-Origin": "*",
                                "Access-Control-Allow-Credentials": "true"
                        })