cryptologin 2.0__tar.gz → 2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. cryptologin-2.1/PKG-INFO +915 -0
  2. cryptologin-2.1/README.md +862 -0
  3. cryptologin-2.1/cryptologin/__init__.py +147 -0
  4. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/api/dependencies.py +54 -22
  5. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/api/models.py +41 -1
  6. cryptologin-2.1/cryptologin/api/routes/auth.py +376 -0
  7. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/core/user_manager_v2.py +30 -17
  8. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/main.py +1 -0
  9. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/storage/sqlite_v2.py +31 -18
  10. cryptologin-2.1/cryptologin.egg-info/PKG-INFO +915 -0
  11. {cryptologin-2.0 → cryptologin-2.1}/pyproject.toml +2 -2
  12. cryptologin-2.0/PKG-INFO +0 -590
  13. cryptologin-2.0/README.md +0 -537
  14. cryptologin-2.0/cryptologin/__init__.py +0 -104
  15. cryptologin-2.0/cryptologin/api/routes/auth.py +0 -199
  16. cryptologin-2.0/cryptologin.egg-info/PKG-INFO +0 -590
  17. {cryptologin-2.0 → cryptologin-2.1}/LICENSE +0 -0
  18. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/api/__init__.py +0 -0
  19. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/api/routes/__init__.py +0 -0
  20. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/api/routes/health.py +0 -0
  21. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/api/routes/user.py +0 -0
  22. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/api/routes/vault.py +0 -0
  23. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/cli.py +0 -0
  24. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/client/__init__.py +0 -0
  25. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/client/crypto_client.py +0 -0
  26. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/config.py +0 -0
  27. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/core/__init__.py +0 -0
  28. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/core/constants.py +0 -0
  29. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/core/crypto_engine.py +0 -0
  30. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/core/data_vault.py +0 -0
  31. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/core/exceptions.py +0 -0
  32. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/core/user_manager.py +0 -0
  33. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/storage/__init__.py +0 -0
  34. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/storage/base.py +0 -0
  35. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/storage/memory.py +0 -0
  36. {cryptologin-2.0 → cryptologin-2.1}/cryptologin/storage/sqlite.py +0 -0
  37. {cryptologin-2.0 → cryptologin-2.1}/cryptologin.egg-info/SOURCES.txt +0 -0
  38. {cryptologin-2.0 → cryptologin-2.1}/cryptologin.egg-info/dependency_links.txt +0 -0
  39. {cryptologin-2.0 → cryptologin-2.1}/cryptologin.egg-info/entry_points.txt +0 -0
  40. {cryptologin-2.0 → cryptologin-2.1}/cryptologin.egg-info/requires.txt +0 -0
  41. {cryptologin-2.0 → cryptologin-2.1}/cryptologin.egg-info/top_level.txt +0 -0
  42. {cryptologin-2.0 → cryptologin-2.1}/setup.cfg +0 -0
  43. {cryptologin-2.0 → cryptologin-2.1}/setup.py +0 -0
@@ -0,0 +1,915 @@
1
+ Metadata-Version: 2.4
2
+ Name: cryptologin
3
+ Version: 2.1
4
+ Summary: Zero-Knowledge-Inspired · Passwordless without Password Storage Authentication System - No Email, No Password, Just Your Secret
5
+ Author-email: erabytse <contact@fbfconsulting.org>
6
+ Maintainer-email: erabytse <contact@fbfconsulting.org>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://erabytse.github.io/cryptologin-website/
9
+ Project-URL: Documentation, https://docs.cryptologin.io
10
+ Project-URL: Repository, https://github.com/erabytse/CryptoLogin
11
+ Project-URL: Issues, https://github.com/erabytse/CryptoLogin.git/issues
12
+ Project-URL: Changelog, https://github.com/erabytse/CryptoLogin.git/releases
13
+ Keywords: authentication,security,cryptography,Storage,passwordless,aes-256-gcm,argon2id,fastapi
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Information Technology
17
+ Classifier: Intended Audience :: System Administrators
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Security
25
+ Classifier: Topic :: Security :: Cryptography
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
28
+ Requires-Python: >=3.10
29
+ Description-Content-Type: text/markdown; charset=UTF-8
30
+ License-File: LICENSE
31
+ Requires-Dist: flash512-vanguard>=2.1.1
32
+ Requires-Dist: fastapi>=0.104.0
33
+ Requires-Dist: uvicorn[standard]>=0.24.0
34
+ Requires-Dist: pydantic>=2.5.0
35
+ Requires-Dist: pydantic-settings>=2.1.0
36
+ Requires-Dist: python-multipart>=0.0.6
37
+ Requires-Dist: slowapi>=0.1.9
38
+ Provides-Extra: postgres
39
+ Requires-Dist: psycopg2-binary>=2.9.9; extra == "postgres"
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
42
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
43
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
44
+ Requires-Dist: httpx>=0.25.0; extra == "dev"
45
+ Requires-Dist: httpx2>=2.0.0; extra == "dev"
46
+ Requires-Dist: black>=23.11.0; extra == "dev"
47
+ Requires-Dist: flake8>=6.1.0; extra == "dev"
48
+ Requires-Dist: mypy>=1.6.1; extra == "dev"
49
+ Requires-Dist: isort>=5.12.0; extra == "dev"
50
+ Provides-Extra: full
51
+ Requires-Dist: cryptologin[postgres]; extra == "full"
52
+ Dynamic: license-file
53
+
54
+ <div align="center">
55
+
56
+ # ![Passwordless Authentication without Password Storage](https://raw.githubusercontent.com/erabytse/CryptoLogin/main/images/logo.png)
57
+
58
+ ## _Zero-Knowledge-Inspired · Passwordless Authentication · Military-Grade Encryption_
59
+
60
+ **The Future of Authentication is Here. No Email. No Password. Just Your Secret.**
61
+
62
+ [![Python](https://img.shields.io/badge/Python-3.10+-blue.svg)](https://www.python.org/)
63
+ [![License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](LICENSE)
64
+ [![PyPI](https://img.shields.io/pypi/v/cryptologin.svg)](https://pypi.org/project/cryptologin/)
65
+ [![CI Status](https://img.shields.io/badge/CI-Pending-yellow.svg)](https://github.com/erabytse/CryptoLogin)
66
+ [![Security](https://img.shields.io/badge/Security-Military%20Grade-red.svg)](SECURITY.md)
67
+ [![Stars](https://img.shields.io/github/stars/erabytse/CryptoLogin.svg)](https://github.com/yourusername/cryptologin)
68
+
69
+ ## The time is now ripe for it
70
+
71
+ **Stop storing password hashes. With CryptoLogin, the server only stores encrypted challenges. The master secret is used once at registration, then forgotten. At login, no secret ever crosses the network.**
72
+
73
+ <img src="https://raw.githubusercontent.com/erabytse/CryptoLogin/main/images/CryptoLogin.gif" width="320" height="170" alt="CryptoLogin"/>
74
+
75
+ CryptoLogin uses a challenge-response mechanism inspired by Zero-Knowledge principles.
76
+ The server never stores your secret. Your secret never leaves your device.
77
+
78
+ </div>
79
+
80
+ ---
81
+
82
+ ## 🚀 What is CryptoLogin?
83
+
84
+ **CryptoLogin** is a revolutionary **Passwordless Authentication without Password Storage** with a **Zero-Knowledge-Inspired architecture** that eliminates the need for emails, passwords, or social logins.
85
+
86
+ ---
87
+
88
+ ## What CryptoLogin REALLY is (and isn't)
89
+
90
+ ### ❌ It is NOT "Zero-Knowledge" in the strict cryptographic sense
91
+
92
+ - In true Zero-Knowledge (like zk-SNARKs or Passkeys), the server never sees the secret, even during registration.
93
+ - Here, the `master_secret` is used to encrypt the challenge during registration.
94
+
95
+ ### ✅ What it actually is
96
+
97
+ - A **Passwordless Authentication System with Encrypted Challenges**.
98
+ - The `master_secret` is **never stored** in the database.
99
+ - During login, no secret travels over the network.
100
+ - Security relies on the fact that **only the client can decrypt the `challenge_token`**.
101
+
102
+ ### 🔐 Real-world security
103
+
104
+ If the database leaks, the attacker gets:
105
+
106
+ - `challenge_en_clair` (the "salt")
107
+ - `challenge_token` (the "hash")
108
+
109
+ To crack it, they must perform offline brute-force:
110
+
111
+ 1. Guess a `master_secret`.
112
+ 2. Derive the key with Argon2id.
113
+ 3. Decrypt the `challenge_token` with AES-GCM.
114
+ 4. Compare with `challenge_en_clair`.
115
+
116
+ **This is equivalent to cracking a password hash with a salt (like bcrypt/Argon2), but using our own elegant and secure mechanism powered by Flash512.**
117
+
118
+ ---
119
+
120
+ ## 🛡️ Powered by Flash512-Vanguard
121
+
122
+ CryptoLogin is built on top of [Flash512-Vanguard](https://github.com/erabytse/Flash512-vanguard), a military-grade encryption engine:
123
+
124
+ - **AES-256-GCM** - NIST standard encryption
125
+ - **Argon2id** - Memory-hard key derivation (GPU/ASIC resistant)
126
+ - **SecureBuffer** - Automatic memory wiping of sensitive data
127
+
128
+ Flash512 handles all cryptographic operations, ensuring that CryptoLogin inherits battle-tested security from one of the most robust encryption libraries available.
129
+
130
+ ---
131
+
132
+ ### 🚀 Why it's still revolutionary
133
+
134
+ - **One secret** for your entire digital life.
135
+ - **No email** required.
136
+ - **No OAuth** or social login.
137
+ - **Military-grade encryption**: AES-256-GCM + Argon2id + SecureBuffer.
138
+ - **Data Vault**: Your data is encrypted with your secret.
139
+
140
+ #
141
+
142
+ ### The Problem
143
+
144
+ - 🔓 Passwords are **stolen** daily
145
+ - 📧 Email verification is **slow** and **annoying**
146
+ - 🕵️‍♂️ Social logins **track** your users
147
+ - 💰 Authentication services are **expensive**
148
+
149
+ ### The Solution
150
+
151
+ - 🔐 **One Master Secret** - All you need to remember
152
+ - 🛡️ **Military-Grade Encryption** - AES-256-GCM + Argon2id
153
+ - 🚫 **Passwordless without password storage** - Your secret never leaves your device
154
+ - ⚡ **Lightning Fast** - Register in seconds
155
+
156
+ ---
157
+
158
+ ## ✨ Key Features
159
+
160
+ | Feature | Description | Security |
161
+ | :------------------------------ | :----------------------------- | :---------------- |
162
+ | **Passwordless Authentication** | Server never knows your secret | 🔒 **Military** |
163
+ | **No Email Required** | Register without email | 🔒 **Privacy** |
164
+ | **No Password Required** | Single master secret | 🔒 **Simple** |
165
+ | **AES-256-GCM** | NIST standard encryption | 🔒 **FIPS** |
166
+ | **Argon2id** | Memory-hard KDF | 🔒 **OWASP** |
167
+ | **SecureBuffer** | Automatic memory wiping | 🔒 **Military** |
168
+ | **Data Vault** | Encrypted user data | 🔒 **Zero-Trust** |
169
+ | **REST API** | FastAPI + OpenAPI | 🔒 **Modern** |
170
+ | **Rate Limiting** | Brute-force protection | 🔒 **Production** |
171
+
172
+ ---
173
+
174
+ ## 📦 Installation
175
+
176
+ ```bash
177
+ # Install from PyPI
178
+ pip install cryptologin
179
+
180
+ # Or install from source
181
+ git clone https://github.com/erabytse/CryptoLogin.git
182
+ cd cryptologin
183
+ pip install -e .
184
+ ```
185
+
186
+ ## 🔒 Security Model
187
+
188
+ **CryptoLogin** uses a challenge-response mechanism with symmetric encryption (Flash512).
189
+
190
+ **Registration:**
191
+
192
+ 1. User creates a `master_secret` (never leaves the client).
193
+ 2. Client derives a `user_id` from the `master_secret` using Web Crypto API (PBKDF2-SHA512, 100k iterations).
194
+ 3. Server generates a random `challenge` and encrypts it using Flash512 with the `user_id`.
195
+ 4. Server stores the encrypted challenge (`challenge_token`) in the database.
196
+
197
+ **Login:**
198
+
199
+ 1. User sends `user_id` to the server.
200
+ 2. Server retrieves the `challenge_token` and sends it to the client.
201
+ 3. Client decrypts the `challenge_token` with the `master_secret` to get the plaintext `challenge`.
202
+ 4. Client sends the plaintext `challenge` back to the server.
203
+ 5. Server verifies that the plaintext `challenge` matches the original challenge.
204
+
205
+ **The `master_secret` is never transmitted over the network.** Only the encrypted challenge and the derived `user_id` are exchanged.
206
+
207
+ ### Why This Is Secure
208
+
209
+ - **Passwordless without password storage**: The server never sees the `master_secret`.
210
+ - **Military-Grade Encryption**: AES-256-GCM + Argon2id via Flash512.
211
+ - **Challenge-Response**: Each login uses a unique challenge (nonce).
212
+ - **Data Vault**: All user data is encrypted with the `master_secret`.
213
+
214
+ ## 🏗️ Architecture
215
+
216
+ ```mermaid
217
+ sequenceDiagram
218
+ participant User
219
+ participant Browser
220
+ participant Server
221
+
222
+ Note over User,Server: REGISTRATION
223
+ User->>Browser: Enter master_secret
224
+ Browser->>Server: POST /register {user_id}
225
+ Server->>Server: Generate random challenge
226
+ Server->>Server: Encrypt challenge with user_id (Flash512)
227
+ Server->>Server: Store (user_id, challenge, encrypted_token)
228
+ Server->>Browser: Return success
229
+
230
+ Note over User,Server: LOGIN
231
+ User->>Browser: Enter master_secret
232
+ Browser->>Server: POST /login/init {user_id}
233
+ Server->>Server: Retrieve encrypted_token
234
+ Server->>Browser: Return encrypted_token
235
+ Browser->>Browser: Decrypt token with master_secret
236
+ Browser->>Server: POST /login/verify {user_id, decrypted_challenge}
237
+ Server->>Server: Compare with stored challenge
238
+ Server->>Browser: Return session_token
239
+ ```
240
+
241
+ ```text
242
+ ┌─────────────────────────────────────────────────────────────────┐
243
+ │ CRYPTOLOGIN │
244
+ ├─────────────────────────────────────────────────────────────────┤
245
+ │ │
246
+ │ [USER] → [API] → [UserManager] → [Data Vault] → [Storage] │
247
+ │ │
248
+ │ 🔐 AES-256-GCM + Argon2id + SecureBuffer |
249
+ │ 🚫 Passwordless Authentication Architecture |
250
+ │ ⚡ FastAPI + SQLite/PostgreSQL |
251
+ │ │
252
+ └─────────────────────────────────────────────────────────────────┘
253
+ ```
254
+
255
+ ✅ No Password Storage
256
+
257
+ The server never stores the master secret. Only encrypted challenges are stored.
258
+
259
+ ✅ No Secret at Login
260
+
261
+ During login, the master secret never leaves the browser. Only the decrypted challenge is sent.
262
+
263
+ ✅ Simple Architecture
264
+
265
+ No asymmetric keys, no WebAuthn complexity, no email verification. Just Flash512 encryption.
266
+
267
+ ✅ Breach-Resistant
268
+
269
+ If the database is compromised, attackers only get encrypted challenges. They must brute-force each user individually.
270
+
271
+ # Powered by Flash512-Vanguard
272
+
273
+ Flash512-Vanguard is the cryptographic engine behind CryptoLogin. It provides:
274
+
275
+ - AES-256-GCM: NIST-standard authenticated encryption
276
+
277
+ - Argon2id: Memory-hard key derivation
278
+
279
+ - SecureBuffer: Automatic memory wiping
280
+
281
+ - Polymorphic encryption: Same data, different ciphertext each time
282
+
283
+ - Integrity verification: GCM authentication tags
284
+
285
+ By building on Flash512, CryptoLogin inherits enterprise-grade security without implementing cryptographic primitives from scratch.
286
+
287
+ ## 🚀 Quick Start (V2 - Zero-Knowledge)
288
+
289
+ ### Deployment Example (Web Application)
290
+
291
+ **Frontend (JavaScript):**
292
+
293
+ ```javascript
294
+ import { deriveUserId } from "cryptologin-client";
295
+
296
+ async function login(masterSecret) {
297
+ // 1. Derive user_id (CLIENT-SIDE)
298
+ const userId = await deriveUserId(masterSecret);
299
+
300
+ // 2. Get encrypted challenge from server
301
+ const initResponse = await fetch("/auth/login/init_v2", {
302
+ method: "POST",
303
+ body: JSON.stringify({ user_id: userId }),
304
+ });
305
+ const { challenge } = await initResponse.json();
306
+
307
+ // 3. Send the encrypted challenge back (DO NOT DECRYPT)
308
+ const verifyResponse = await fetch("/auth/login/verify_v2", {
309
+ method: "POST",
310
+ body: JSON.stringify({
311
+ user_id: userId,
312
+ challenge_response: challenge,
313
+ }),
314
+ });
315
+
316
+ return verifyResponse.json();
317
+ }
318
+ ```
319
+
320
+ **Backend 🚀 EXAMPLE 1: FastAPI (Recommended)**
321
+
322
+ ### Structure du projet
323
+
324
+ ```text
325
+ myapp/
326
+ ├── app.py # Application FastAPI
327
+ ├── cryptologin.db # SQLite database (created automatically)
328
+ ├── .env # Environment variables
329
+ └── requirements.txt
330
+ ```
331
+
332
+ ### requirements.txt
333
+
334
+ ```text
335
+ fastapi==0.104.0
336
+ uvicorn[standard]==0.24.0
337
+ cryptologin>=2.1.0
338
+ python-dotenv==1.0.0
339
+ ```
340
+
341
+ ### .env
342
+
343
+ ```env
344
+ CRYPTOLOGIN_SECRET_KEY=your-super-secret-key-change-in-production-32-chars-min
345
+ FLASH512_VANGUARD_CORE=your-flash512-core-secret-64-chars-min
346
+ DATABASE_URL=sqlite:///cryptologin.db
347
+ ```
348
+
349
+ ### app.py
350
+
351
+ ```python
352
+ """
353
+ CryptoLogin – Example of integration with FastAPI
354
+ """
355
+
356
+ import os
357
+ import logging
358
+ from datetime import datetime
359
+ from typing import Optional
360
+ from contextlib import asynccontextmanager
361
+
362
+ from fastapi import FastAPI, HTTPException, status, Depends
363
+ from fastapi.middleware.cors import CORSMiddleware
364
+ from pydantic import BaseModel, Field
365
+ from dotenv import load_dotenv
366
+
367
+ # Import CryptoLogin
368
+ from cryptologin import CryptoLogin
369
+ from cryptologin.core.user_manager_v2 import UserManagerV2
370
+ from cryptologin.storage.sqlite_v2 import SQLiteStorageV2
371
+ from cryptologin.client.crypto_client import CryptoClient
372
+
373
+ # Load environment variables
374
+ load_dotenv()
375
+
376
+ # Logging configuration
377
+ logging.basicConfig(
378
+ level=logging.INFO,
379
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
380
+ )
381
+ logger = logging.getLogger(__name__)
382
+
383
+
384
+ # ============================================================
385
+ # PYDANTIC MODELS
386
+ # ============================================================
387
+
388
+ class RegisterRequest(BaseModel):
389
+ """Application for registration V2."""
390
+ user_id: str = Field(..., description="User ID derived from the master_secret (64 hex characters)")
391
+ user_data: Optional[dict] = Field(default=None, description="User data")
392
+
393
+
394
+ class LoginInitRequest(BaseModel):
395
+ """Request to initiate login."""
396
+ user_id: str = Field(..., description="User ID")
397
+
398
+
399
+ class LoginVerifyRequest(BaseModel):
400
+ """Request for login verification."""
401
+ user_id: str = Field(..., description="User ID")
402
+ challenge_response: str = Field(..., description="Numerical challenge (reposted as is)")
403
+
404
+
405
+ class AuthResponse(BaseModel):
406
+ """Authentication response."""
407
+ authenticated: bool
408
+ user_id: str
409
+ session_id: str
410
+ expires_at: datetime
411
+ message: str
412
+
413
+
414
+ class MessageResponse(BaseModel):
415
+ """Replying to a simple message."""
416
+ message: str
417
+ success: bool
418
+ data: Optional[dict] = None
419
+
420
+
421
+ # ============================================================
422
+ # LIFESPAN
423
+ # ============================================================
424
+
425
+ @asynccontextmanager
426
+ async def lifespan(app: FastAPI):
427
+ """Application lifecycle management."""
428
+ logger.info("🚀 Starting CryptoLogin FastAPI example...")
429
+
430
+ # Initialise the database
431
+ db_path = os.getenv("DATABASE_URL", "sqlite:///cryptologin.db").replace("sqlite:///", "")
432
+ storage = SQLiteStorageV2(db_path=db_path, auto_migrate=True)
433
+ app.state.storage = storage
434
+
435
+ # Initialise UserManager V2
436
+ app.state.user_manager = UserManagerV2(storage=storage, session_duration_hours=24)
437
+
438
+ logger.info(f"✅ Database initialized at: {db_path}")
439
+ logger.info("✅ CryptoLogin ready!")
440
+
441
+ yield
442
+
443
+ logger.info("👋 Shutting down CryptoLogin FastAPI example...")
444
+
445
+
446
+ # ============================================================
447
+ # APPLICATION FASTAPI
448
+ # ============================================================
449
+
450
+ app = FastAPI(
451
+ title="CryptoLogin Example API",
452
+ description="Passwordless Authentication with Zero-Knowledge-Inspired Architecture",
453
+ version="2.1.0",
454
+ lifespan=lifespan
455
+ )
456
+
457
+ # CORS (for development)
458
+ app.add_middleware(
459
+ CORSMiddleware,
460
+ allow_origins=["*"],
461
+ allow_credentials=True,
462
+ allow_methods=["*"],
463
+ allow_headers=["*"],
464
+ )
465
+
466
+
467
+ # ============================================================
468
+ # ROUTES
469
+ # ============================================================
470
+
471
+ @app.get("/")
472
+ async def root():
473
+ """Root of the API."""
474
+ return {
475
+ "name": "CryptoLogin Example API",
476
+ "version": "2.1.0",
477
+ "docs": "/docs",
478
+ "status": "running"
479
+ }
480
+
481
+
482
+ @app.post("/auth/register", response_model=MessageResponse)
483
+ async def register(request: RegisterRequest):
484
+ """
485
+ Register a new user.
486
+
487
+ The client must derive the `user_id` from the `master_secret` before calling this route.
488
+ The server NEVER sees the `master_secret`.
489
+ """
490
+ try:
491
+ user_manager: UserManagerV2 = app.state.user_manager
492
+
493
+ user_id = user_manager.register_user_v2(
494
+ request.user_id,
495
+ request.user_data or {}
496
+ )
497
+
498
+ return MessageResponse(
499
+ message="User registered successfully",
500
+ success=True,
501
+ data={"user_id": user_id}
502
+ )
503
+
504
+ except ValueError as e:
505
+ raise HTTPException(status_code=400, detail=str(e))
506
+ except Exception as e:
507
+ logger.error(f"Registration failed: {e}")
508
+ raise HTTPException(status_code=500, detail=f"Registration failed: {str(e)}")
509
+
510
+
511
+ @app.post("/auth/login/init")
512
+ async def login_init(request: LoginInitRequest):
513
+ """
514
+ Initiate login – returns an encrypted challenge.
515
+
516
+ The client must send this challenge back exactly as it is for verification.
517
+ """
518
+ try:
519
+ user_manager: UserManagerV2 = app.state.user_manager
520
+
521
+ challenge_token = user_manager.initiate_login_v2(request.user_id)
522
+
523
+ return {
524
+ "challenge": challenge_token,
525
+ "message": "Please send this challenge back to /auth/login/verify"
526
+ }
527
+
528
+ except Exception as e:
529
+ logger.error(f"Login init failed: {e}")
530
+ raise HTTPException(status_code=500, detail=f"Login initiation failed: {str(e)}")
531
+
532
+
533
+ @app.post("/auth/login/verify", response_model=AuthResponse)
534
+ async def login_verify(request: LoginVerifyRequest):
535
+ """
536
+ Verify the login – the server decrypts the challenge using Flash512.
537
+
538
+ The client sends back the encrypted challenge. The server decrypts it and verifies it.
539
+ """
540
+ try:
541
+ user_manager: UserManagerV2 = app.state.user_manager
542
+
543
+ session = user_manager.complete_login_v2(
544
+ request.user_id,
545
+ request.challenge_response # Quantified challenge returned as is
546
+ )
547
+
548
+ return AuthResponse(
549
+ authenticated=True,
550
+ user_id=session.user_id,
551
+ session_id=session.user_id,
552
+ expires_at=session.expires_at,
553
+ message="Authentication successful"
554
+ )
555
+
556
+ except Exception as e:
557
+ logger.error(f"Login verify failed: {e}")
558
+ raise HTTPException(status_code=401, detail=f"Authentication failed: {str(e)}")
559
+
560
+
561
+ @app.post("/auth/logout")
562
+ async def logout(user_id: str):
563
+ """log a user out."""
564
+ try:
565
+ user_manager: UserManagerV2 = app.state.user_manager
566
+ user_manager.logout(user_id)
567
+ return {"message": "Logged out successfully"}
568
+ except Exception as e:
569
+ raise HTTPException(status_code=500, detail=f"Logout failed: {str(e)}")
570
+
571
+
572
+ # ============================================================
573
+ # ENTRY POINT
574
+ # ============================================================
575
+
576
+ if __name__ == "__main__":
577
+ import uvicorn
578
+ uvicorn.run(
579
+ "app:app",
580
+ host="0.0.0.0",
581
+ port=8000,
582
+ reload=True,
583
+ log_level="info"
584
+ )
585
+ ```
586
+
587
+ ### Start the application
588
+
589
+ ```bash
590
+ # Install the dependencies
591
+ pip install fastapi uvicorn cryptologin python-dotenv
592
+
593
+ # run the app
594
+ python app.py
595
+ ```
596
+
597
+ ## **Backend 🚀🚀 EXAMPLE 2: Flask (Alternative)**
598
+
599
+ ### app_flask.py
600
+
601
+ ```python
602
+ """
603
+ CryptoLogin - Example of integration with Flask
604
+ """
605
+
606
+ import os
607
+ import logging
608
+ from flask import Flask, request, jsonify, render_template
609
+ from dotenv import load_dotenv
610
+
611
+ # Import CryptoLogin
612
+ from cryptologin import CryptoLogin
613
+ from cryptologin.core.user_manager_v2 import UserManagerV2
614
+ from cryptologin.storage.sqlite_v2 import SQLiteStorageV2
615
+
616
+ # Load environment variables
617
+ load_dotenv()
618
+
619
+ # Logging configuration
620
+ logging.basicConfig(level=logging.INFO)
621
+ logger = logging.getLogger(__name__)
622
+
623
+ # ============================================================
624
+ # APPLICATION FLASK
625
+ # ============================================================
626
+
627
+ app = Flask(__name__)
628
+ app.secret_key = os.getenv("CRYPTOLOGIN_SECRET_KEY", "dev-secret-key")
629
+
630
+ # Set CryptoLogin to start at boot
631
+ db_path = os.getenv("DATABASE_URL", "sqlite:///cryptologin.db").replace("sqlite:///", "")
632
+ storage = SQLiteStorageV2(db_path=db_path, auto_migrate=True)
633
+ user_manager = UserManagerV2(storage=storage, session_duration_hours=24)
634
+
635
+ logger.info(f"✅ CryptoLogin initialized with database: {db_path}")
636
+
637
+
638
+ # ============================================================
639
+ # ROUTES
640
+ # ============================================================
641
+
642
+ @app.route("/")
643
+ def index():
644
+ """Home page."""
645
+ return jsonify({
646
+ "name": "CryptoLogin Example API (Flask)",
647
+ "version": "2.1.0",
648
+ "status": "running",
649
+ "endpoints": {
650
+ "register": "POST /auth/register",
651
+ "login_init": "POST /auth/login/init",
652
+ "login_verify": "POST /auth/login/verify",
653
+ "logout": "POST /auth/logout"
654
+ }
655
+ })
656
+
657
+
658
+ @app.route("/auth/register", methods=["POST"])
659
+ def register():
660
+ """
661
+ Register a new user.
662
+
663
+ Body: {"user_id": "64-hex-chars", "user_data": {...}}
664
+ """
665
+ try:
666
+ data = request.get_json()
667
+ user_id = data.get("user_id")
668
+ user_data = data.get("user_data", {})
669
+
670
+ if not user_id:
671
+ return jsonify({"error": "user_id is required"}), 400
672
+
673
+ result = user_manager.register_user_v2(user_id, user_data)
674
+
675
+ return jsonify({
676
+ "message": "User registered successfully",
677
+ "success": True,
678
+ "data": {"user_id": result}
679
+ }), 200
680
+
681
+ except ValueError as e:
682
+ return jsonify({"error": str(e)}), 400
683
+ except Exception as e:
684
+ logger.error(f"Registration failed: {e}")
685
+ return jsonify({"error": f"Registration failed: {str(e)}"}), 500
686
+
687
+
688
+ @app.route("/auth/login/init", methods=["POST"])
689
+ def login_init():
690
+ """
691
+ Start the login process.
692
+
693
+ Body: {"user_id": "64-hex-chars"}
694
+ """
695
+ try:
696
+ data = request.get_json()
697
+ user_id = data.get("user_id")
698
+
699
+ if not user_id:
700
+ return jsonify({"error": "user_id is required"}), 400
701
+
702
+ challenge_token = user_manager.initiate_login_v2(user_id)
703
+
704
+ return jsonify({
705
+ "challenge": challenge_token,
706
+ "message": "Please send this challenge back to /auth/login/verify"
707
+ }), 200
708
+
709
+ except Exception as e:
710
+ logger.error(f"Login init failed: {e}")
711
+ return jsonify({"error": f"Login initiation failed: {str(e)}"}), 500
712
+
713
+
714
+ @app.route("/auth/login/verify", methods=["POST"])
715
+ def login_verify():
716
+ """
717
+ Check the login.
718
+
719
+ Body: {"user_id": "64-hex-chars", "challenge_response": "encrypted-challenge"}
720
+ """
721
+ try:
722
+ data = request.get_json()
723
+ user_id = data.get("user_id")
724
+ challenge_response = data.get("challenge_response")
725
+
726
+ if not user_id or not challenge_response:
727
+ return jsonify({"error": "user_id and challenge_response are required"}), 400
728
+
729
+ session = user_manager.complete_login_v2(user_id, challenge_response)
730
+
731
+ return jsonify({
732
+ "authenticated": True,
733
+ "user_id": session.user_id,
734
+ "session_id": session.user_id,
735
+ "expires_at": session.expires_at.isoformat(),
736
+ "message": "Authentication successful"
737
+ }), 200
738
+
739
+ except Exception as e:
740
+ logger.error(f"Login verify failed: {e}")
741
+ return jsonify({"error": f"Authentication failed: {str(e)}"}), 401
742
+
743
+
744
+ @app.route("/auth/logout", methods=["POST"])
745
+ def logout():
746
+ """Log a user out."""
747
+ try:
748
+ data = request.get_json()
749
+ user_id = data.get("user_id")
750
+
751
+ if not user_id:
752
+ return jsonify({"error": "user_id is required"}), 400
753
+
754
+ user_manager.logout(user_id)
755
+ return jsonify({"message": "Logged out successfully"}), 200
756
+
757
+ except Exception as e:
758
+ return jsonify({"error": f"Logout failed: {str(e)}"}), 500
759
+
760
+
761
+ # ============================================================
762
+ # ENTRY POINT
763
+ # ============================================================
764
+
765
+ if __name__ == "__main__":
766
+ app.run(host="0.0.0.0", port=5000, debug=True)
767
+ ```
768
+
769
+ ### Start the Flask application
770
+
771
+ ```bash
772
+ # Install the dependencies
773
+ pip install flask cryptologin python-dotenv
774
+
775
+ # run the app
776
+ python app_flask.py
777
+ ```
778
+
779
+ 🔑 Key Points to Remember
780
+
781
+ 1. The customer never deciphers the challenge → They send it back exactly as it is.
782
+
783
+ 2. The server uses Flash512 for all → encryption, decryption and verification.
784
+
785
+ 3. The master_secret NEVER leaves the client → Only the user_id is sent.
786
+
787
+ ### The master_secret is never exposed to the server. This is true Passwordless without password storage.
788
+
789
+ #
790
+
791
+ ### Security Certifications
792
+
793
+ | Standard | Compliance |
794
+ | ------------- | ---------------------------------------- |
795
+ | NIST FIPS 197 | ✅ AES-256 |
796
+ | OWASP ASVS | ✅ Argon2id |
797
+ | GDPR | ✅ Passwordless without password storage |
798
+ | SOC2 | ✅ Audit Logs (in process!) |
799
+ | |
800
+
801
+ 📊 Comparison
802
+
803
+ | Feature | CryptoLogin | Auth0 | Firebase | Clerk |
804
+ | --------------------------- | ----------- | ------ | -------- | ------ |
805
+ | Passwordless Authentication | ✅ | ❌ | ❌ | ❌ |
806
+ | No Email Required | ✅ | ❌ | ❌ | ❌ |
807
+ | No Password Required | ✅ | ❌ | ❌ | ❌ |
808
+ | Open Source | ✅ | ❌ | ❌ | ❌ |
809
+ | Self-Hosted | ✅ | ❌ | ❌ | ❌ |
810
+ | Military Encryption | ✅ | ⚠️ | ⚠️ | ⚠️ |
811
+ | Price | 💰Free | 💰💰💰 | 💰💰 | 💰💰💰 |
812
+
813
+ 🎯 Use Cases
814
+
815
+ - 🌐 Web Applications - Authentication without email/password
816
+
817
+ - 📱 Mobile Apps - Simple, secure login
818
+
819
+ - 🔒 Enterprise Apps - Zero-trust authentication
820
+
821
+ - 🏥 Healthcare - GDPR compliant authentication
822
+
823
+ - 💳 Fintech - High-security authentication
824
+
825
+ #
826
+
827
+ # 🧪 DEMO
828
+
829
+ Try it now
830
+
831
+ The interactive demo
832
+
833
+ Create an account in 2 seconds. One master secret. No personal data.
834
+
835
+ <b>[ONLINE DEMO](https://erabytse.github.io/cryptologin-website/)</b>
836
+
837
+ #
838
+
839
+ 📚 Documentation
840
+
841
+ - API Reference
842
+
843
+ - Getting Started Guide
844
+
845
+ - Security Whitepaper
846
+
847
+ - Architecture Overview
848
+
849
+ #
850
+
851
+ 🤝 Contributing
852
+
853
+ We welcome contributions! Please see our Contributing Guide.
854
+
855
+ Development Setup
856
+
857
+ ```bash
858
+ # Clone the repository
859
+ git clone https://github.com/erabytse/CryptoLogin.git
860
+ cd cryptologin
861
+
862
+ # Install dev dependencies
863
+ pip install -e .[dev]
864
+
865
+ # Run tests
866
+ pytest tests/ -v
867
+
868
+ # Run the API
869
+ python run.py
870
+ ```
871
+
872
+ #
873
+
874
+ 📄 License
875
+
876
+ - Open Source: Apache 2.0
877
+
878
+ - Commercial: Available for enterprise use
879
+
880
+ #
881
+
882
+ 🌟 Support the Project
883
+
884
+ - ⭐ Star the repository
885
+
886
+ - 🐛 Report issues
887
+
888
+ - 📝 Improve documentation
889
+
890
+ - 💰 Sponsor the project
891
+
892
+ - 🗣️ Spread the word
893
+
894
+ #
895
+
896
+ 📞 Contact
897
+
898
+ - 📧 Email: contact@fbfconsulting.org
899
+
900
+ - 🐦 Twitter: @cryptologin (coming soon)
901
+
902
+ - 💬 Discord: Join our community (coming soon)
903
+
904
+ [©erabytse](https://erabytse.github.io/)
905
+
906
+ #
907
+
908
+ <div align="center">
909
+ Built with ❤️ by erabytse
910
+
911
+ Reinventing Authentication. One Secret at a Time.
912
+
913
+ A quiet rebellion against digital waste.
914
+
915
+ </div>