login512-server 1.0.0__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.
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: login512-server
3
+ Version: 1.0.0
4
+ Summary: Official Login512 Server SDK for Python (Post-Quantum Passwordless Face Authentication)
5
+ Home-page: https://login512.com
6
+ Author: login512.com
7
+ License: Apache-2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: requests>=2.28.0
15
+ Provides-Extra: offline
16
+ Requires-Dist: liboqs-python>=0.9.0; extra == "offline"
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: license
23
+ Dynamic: provides-extra
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # Login512 Python Server SDK
29
+
30
+ Official Python server-side SDK for **Login512** — Global Post-Quantum Passwordless Face Authentication API.
31
+
32
+ ## Requirements
33
+ - Python >= 3.9
34
+ - `requests >= 2.28.0`
35
+ - Optional: `liboqs-python` for offline post-quantum signature verification.
36
+
37
+ ## Installation
38
+ ```bash
39
+ pip install login512-server
40
+ ```
41
+
42
+ ---
43
+
44
+ ## 4-Step Integration Flow
45
+
46
+ ### Step 1: Generate Nonce for Session
47
+ Before displaying the Login512 biometric frame, generate a cryptographically secure 32-byte nonce on your server and store it in the user's session:
48
+
49
+ ```python
50
+ import login512_server
51
+
52
+ @app.route('/api/auth/start', methods=['GET'])
53
+ def start_auth():
54
+ nonce = login512_server.generate_nonce()
55
+ session['auth_nonce'] = nonce
56
+ return jsonify({'nonce': nonce})
57
+ ```
58
+
59
+ ### Step 2: Receive & Verify Token from Frontend
60
+ When the user finishes face authentication, receive the post-quantum L512 token and verify it against Login512 API:
61
+
62
+ ```python
63
+ import os
64
+ import login512_server
65
+
66
+ @app.route('/api/auth/login512-callback', methods=['POST'])
67
+ def auth_callback():
68
+ token = request.json.get('token')
69
+ expected_nonce = session.get('auth_nonce')
70
+
71
+ result = login512_server.verify_token(
72
+ secret_key=os.environ['LOGIN512_SECRET_KEY'], # e.g. l512_sk_...
73
+ token=token,
74
+ expected_nonce=expected_nonce,
75
+ )
76
+
77
+ if not result['valid']:
78
+ return jsonify({'error': result['error']}), 401
79
+
80
+ # Step 3: Handle Session Authorization vs Step-up
81
+ if result['session_allowed']:
82
+ # Normal passwordless login
83
+ session['user_id'] = result['claims']['sub']
84
+ return jsonify({'ok': True, 'user_id': result['claims']['sub']})
85
+
86
+ if result['step_up_required']:
87
+ # New device policy triggered step-up requirement
88
+ session['pending_device_ref'] = result['claims']['did']
89
+ return jsonify({
90
+ 'step_up_required': True,
91
+ 'message': 'Unrecognized device: please verify via Passkey/MFA'
92
+ })
93
+ ```
94
+
95
+ ### Step 3: Device Trusting after Step-up
96
+ If `result['step_up_required']` is true, perform step-up authentication (e.g. Passkey), then mark the device as trusted:
97
+
98
+ ```python
99
+ @app.route('/api/auth/step-up-complete', methods=['POST'])
100
+ def step_up_complete():
101
+ device_ref = session.pop('pending_device_ref', None)
102
+
103
+ login512_server.trust_device(
104
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
105
+ device_ref=device_ref,
106
+ )
107
+
108
+ return jsonify({'ok': True})
109
+ ```
110
+
111
+ ### Step 4: Enabling Face Login (Enrollment)
112
+ Enable Face Login for existing authenticated users:
113
+
114
+ ```python
115
+ @app.route('/api/profile/enable-face-login', methods=['POST'])
116
+ def enable_face():
117
+ user_id = session['user_id']
118
+
119
+ # 1. Create one-time enrollment token
120
+ data = login512_server.create_enrollment_token(
121
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
122
+ external_user_id=user_id,
123
+ display_name=current_user.name,
124
+ ttl_seconds=120,
125
+ )
126
+
127
+ return jsonify({'enrollment_token': data['token']})
128
+
129
+ # After frontend calls l512.enroll({ token: enrollment_token })
130
+ @app.route('/api/profile/confirm-face-enrollment', methods=['POST'])
131
+ def confirm_enrollment():
132
+ token = request.json.get('token')
133
+ result = login512_server.verify_token(
134
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
135
+ token=token,
136
+ )
137
+
138
+ if result['valid'] and result['claims'].get('act') == 'enroll':
139
+ return jsonify({'ok': True, 'message': 'Face login successfully enabled'})
140
+
141
+ return jsonify({'error': 'Enrollment verification failed'}), 400
142
+ ```
@@ -0,0 +1,115 @@
1
+ # Login512 Python Server SDK
2
+
3
+ Official Python server-side SDK for **Login512** — Global Post-Quantum Passwordless Face Authentication API.
4
+
5
+ ## Requirements
6
+ - Python >= 3.9
7
+ - `requests >= 2.28.0`
8
+ - Optional: `liboqs-python` for offline post-quantum signature verification.
9
+
10
+ ## Installation
11
+ ```bash
12
+ pip install login512-server
13
+ ```
14
+
15
+ ---
16
+
17
+ ## 4-Step Integration Flow
18
+
19
+ ### Step 1: Generate Nonce for Session
20
+ Before displaying the Login512 biometric frame, generate a cryptographically secure 32-byte nonce on your server and store it in the user's session:
21
+
22
+ ```python
23
+ import login512_server
24
+
25
+ @app.route('/api/auth/start', methods=['GET'])
26
+ def start_auth():
27
+ nonce = login512_server.generate_nonce()
28
+ session['auth_nonce'] = nonce
29
+ return jsonify({'nonce': nonce})
30
+ ```
31
+
32
+ ### Step 2: Receive & Verify Token from Frontend
33
+ When the user finishes face authentication, receive the post-quantum L512 token and verify it against Login512 API:
34
+
35
+ ```python
36
+ import os
37
+ import login512_server
38
+
39
+ @app.route('/api/auth/login512-callback', methods=['POST'])
40
+ def auth_callback():
41
+ token = request.json.get('token')
42
+ expected_nonce = session.get('auth_nonce')
43
+
44
+ result = login512_server.verify_token(
45
+ secret_key=os.environ['LOGIN512_SECRET_KEY'], # e.g. l512_sk_...
46
+ token=token,
47
+ expected_nonce=expected_nonce,
48
+ )
49
+
50
+ if not result['valid']:
51
+ return jsonify({'error': result['error']}), 401
52
+
53
+ # Step 3: Handle Session Authorization vs Step-up
54
+ if result['session_allowed']:
55
+ # Normal passwordless login
56
+ session['user_id'] = result['claims']['sub']
57
+ return jsonify({'ok': True, 'user_id': result['claims']['sub']})
58
+
59
+ if result['step_up_required']:
60
+ # New device policy triggered step-up requirement
61
+ session['pending_device_ref'] = result['claims']['did']
62
+ return jsonify({
63
+ 'step_up_required': True,
64
+ 'message': 'Unrecognized device: please verify via Passkey/MFA'
65
+ })
66
+ ```
67
+
68
+ ### Step 3: Device Trusting after Step-up
69
+ If `result['step_up_required']` is true, perform step-up authentication (e.g. Passkey), then mark the device as trusted:
70
+
71
+ ```python
72
+ @app.route('/api/auth/step-up-complete', methods=['POST'])
73
+ def step_up_complete():
74
+ device_ref = session.pop('pending_device_ref', None)
75
+
76
+ login512_server.trust_device(
77
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
78
+ device_ref=device_ref,
79
+ )
80
+
81
+ return jsonify({'ok': True})
82
+ ```
83
+
84
+ ### Step 4: Enabling Face Login (Enrollment)
85
+ Enable Face Login for existing authenticated users:
86
+
87
+ ```python
88
+ @app.route('/api/profile/enable-face-login', methods=['POST'])
89
+ def enable_face():
90
+ user_id = session['user_id']
91
+
92
+ # 1. Create one-time enrollment token
93
+ data = login512_server.create_enrollment_token(
94
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
95
+ external_user_id=user_id,
96
+ display_name=current_user.name,
97
+ ttl_seconds=120,
98
+ )
99
+
100
+ return jsonify({'enrollment_token': data['token']})
101
+
102
+ # After frontend calls l512.enroll({ token: enrollment_token })
103
+ @app.route('/api/profile/confirm-face-enrollment', methods=['POST'])
104
+ def confirm_enrollment():
105
+ token = request.json.get('token')
106
+ result = login512_server.verify_token(
107
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
108
+ token=token,
109
+ )
110
+
111
+ if result['valid'] and result['claims'].get('act') == 'enroll':
112
+ return jsonify({'ok': True, 'message': 'Face login successfully enabled'})
113
+
114
+ return jsonify({'error': 'Enrollment verification failed'}), 400
115
+ ```
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: login512-server
3
+ Version: 1.0.0
4
+ Summary: Official Login512 Server SDK for Python (Post-Quantum Passwordless Face Authentication)
5
+ Home-page: https://login512.com
6
+ Author: login512.com
7
+ License: Apache-2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: requests>=2.28.0
15
+ Provides-Extra: offline
16
+ Requires-Dist: liboqs-python>=0.9.0; extra == "offline"
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: license
23
+ Dynamic: provides-extra
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # Login512 Python Server SDK
29
+
30
+ Official Python server-side SDK for **Login512** — Global Post-Quantum Passwordless Face Authentication API.
31
+
32
+ ## Requirements
33
+ - Python >= 3.9
34
+ - `requests >= 2.28.0`
35
+ - Optional: `liboqs-python` for offline post-quantum signature verification.
36
+
37
+ ## Installation
38
+ ```bash
39
+ pip install login512-server
40
+ ```
41
+
42
+ ---
43
+
44
+ ## 4-Step Integration Flow
45
+
46
+ ### Step 1: Generate Nonce for Session
47
+ Before displaying the Login512 biometric frame, generate a cryptographically secure 32-byte nonce on your server and store it in the user's session:
48
+
49
+ ```python
50
+ import login512_server
51
+
52
+ @app.route('/api/auth/start', methods=['GET'])
53
+ def start_auth():
54
+ nonce = login512_server.generate_nonce()
55
+ session['auth_nonce'] = nonce
56
+ return jsonify({'nonce': nonce})
57
+ ```
58
+
59
+ ### Step 2: Receive & Verify Token from Frontend
60
+ When the user finishes face authentication, receive the post-quantum L512 token and verify it against Login512 API:
61
+
62
+ ```python
63
+ import os
64
+ import login512_server
65
+
66
+ @app.route('/api/auth/login512-callback', methods=['POST'])
67
+ def auth_callback():
68
+ token = request.json.get('token')
69
+ expected_nonce = session.get('auth_nonce')
70
+
71
+ result = login512_server.verify_token(
72
+ secret_key=os.environ['LOGIN512_SECRET_KEY'], # e.g. l512_sk_...
73
+ token=token,
74
+ expected_nonce=expected_nonce,
75
+ )
76
+
77
+ if not result['valid']:
78
+ return jsonify({'error': result['error']}), 401
79
+
80
+ # Step 3: Handle Session Authorization vs Step-up
81
+ if result['session_allowed']:
82
+ # Normal passwordless login
83
+ session['user_id'] = result['claims']['sub']
84
+ return jsonify({'ok': True, 'user_id': result['claims']['sub']})
85
+
86
+ if result['step_up_required']:
87
+ # New device policy triggered step-up requirement
88
+ session['pending_device_ref'] = result['claims']['did']
89
+ return jsonify({
90
+ 'step_up_required': True,
91
+ 'message': 'Unrecognized device: please verify via Passkey/MFA'
92
+ })
93
+ ```
94
+
95
+ ### Step 3: Device Trusting after Step-up
96
+ If `result['step_up_required']` is true, perform step-up authentication (e.g. Passkey), then mark the device as trusted:
97
+
98
+ ```python
99
+ @app.route('/api/auth/step-up-complete', methods=['POST'])
100
+ def step_up_complete():
101
+ device_ref = session.pop('pending_device_ref', None)
102
+
103
+ login512_server.trust_device(
104
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
105
+ device_ref=device_ref,
106
+ )
107
+
108
+ return jsonify({'ok': True})
109
+ ```
110
+
111
+ ### Step 4: Enabling Face Login (Enrollment)
112
+ Enable Face Login for existing authenticated users:
113
+
114
+ ```python
115
+ @app.route('/api/profile/enable-face-login', methods=['POST'])
116
+ def enable_face():
117
+ user_id = session['user_id']
118
+
119
+ # 1. Create one-time enrollment token
120
+ data = login512_server.create_enrollment_token(
121
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
122
+ external_user_id=user_id,
123
+ display_name=current_user.name,
124
+ ttl_seconds=120,
125
+ )
126
+
127
+ return jsonify({'enrollment_token': data['token']})
128
+
129
+ # After frontend calls l512.enroll({ token: enrollment_token })
130
+ @app.route('/api/profile/confirm-face-enrollment', methods=['POST'])
131
+ def confirm_enrollment():
132
+ token = request.json.get('token')
133
+ result = login512_server.verify_token(
134
+ secret_key=os.environ['LOGIN512_SECRET_KEY'],
135
+ token=token,
136
+ )
137
+
138
+ if result['valid'] and result['claims'].get('act') == 'enroll':
139
+ return jsonify({'ok': True, 'message': 'Face login successfully enabled'})
140
+
141
+ return jsonify({'error': 'Enrollment verification failed'}), 400
142
+ ```
@@ -0,0 +1,8 @@
1
+ README.md
2
+ login512_server.py
3
+ setup.py
4
+ login512_server.egg-info/PKG-INFO
5
+ login512_server.egg-info/SOURCES.txt
6
+ login512_server.egg-info/dependency_links.txt
7
+ login512_server.egg-info/requires.txt
8
+ login512_server.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ requests>=2.28.0
2
+
3
+ [offline]
4
+ liboqs-python>=0.9.0
@@ -0,0 +1 @@
1
+ login512_server
@@ -0,0 +1,276 @@
1
+ """
2
+ login512_server.py — Official Login512 Server-Side SDK for Python
3
+ Implements Section 22 of blueprint512.md.
4
+ Provides online token verification, enrollment token generation, device trusting, and ML-DSA-65 offline verification.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ import secrets
12
+ import time
13
+ from typing import Any, Dict, List, Optional, Union
14
+ import urllib.parse
15
+
16
+ import requests
17
+
18
+ DEFAULT_ENDPOINT = "https://api.login512.com"
19
+
20
+
21
+ def _b64url_decode(s: str) -> bytes:
22
+ """Decodes base64url string with missing padding restoration."""
23
+ padding = "=" * ((4 - len(s) % 4) % 4)
24
+ return base64.urlsafe_b64decode(s + padding)
25
+
26
+
27
+ def generate_nonce() -> str:
28
+ """
29
+ Generates a cryptographically secure 32-byte nonce encoded as base64url.
30
+ Store this nonce in the user's session before initiating authentication.
31
+ """
32
+ token_bytes = secrets.token_bytes(32)
33
+ return base64.urlsafe_b64encode(token_bytes).decode("ascii").rstrip("=")
34
+
35
+
36
+ def verify_token(
37
+ secret_key: str,
38
+ token: str,
39
+ expected_nonce: Optional[str] = None,
40
+ endpoint: str = DEFAULT_ENDPOINT,
41
+ ) -> Dict[str, Any]:
42
+ """
43
+ Verifies a post-quantum L512 authentication token online via Login512 API.
44
+
45
+ Returns:
46
+ {
47
+ "valid": bool,
48
+ "claims": dict | None,
49
+ "error": str | None,
50
+ "session_allowed": bool,
51
+ "step_up_required": bool,
52
+ }
53
+ """
54
+ if not secret_key or not secret_key.startswith("l512_sk_"):
55
+ return {
56
+ "valid": False,
57
+ "claims": None,
58
+ "error": "Invalid secret_key: must start with l512_sk_",
59
+ "session_allowed": False,
60
+ "step_up_required": False,
61
+ }
62
+
63
+ if not token or not isinstance(token, str):
64
+ return {
65
+ "valid": False,
66
+ "claims": None,
67
+ "error": "Missing or invalid token",
68
+ "session_allowed": False,
69
+ "step_up_required": False,
70
+ }
71
+
72
+ clean_endpoint = endpoint.rstrip("/")
73
+ url = f"{clean_endpoint}/v1/token/verify"
74
+
75
+ payload: Dict[str, Any] = {"token": token}
76
+ if expected_nonce:
77
+ payload["expected_nonce"] = expected_nonce
78
+
79
+ headers = {
80
+ "Content-Type": "application/json",
81
+ "x-api-key": secret_key,
82
+ }
83
+
84
+ try:
85
+ resp = requests.post(url, json=payload, headers=headers, timeout=10.0)
86
+ data = resp.json() if resp.content else {}
87
+
88
+ if not resp.ok:
89
+ err_msg = data.get("message") or data.get("error") or f"HTTP {resp.status_code}: Verification failed"
90
+ return {
91
+ "valid": False,
92
+ "claims": None,
93
+ "error": err_msg,
94
+ "session_allowed": False,
95
+ "step_up_required": False,
96
+ }
97
+
98
+ valid = bool(data.get("valid"))
99
+ step_up_required = bool(data.get("step_up_required"))
100
+ claims = data.get("claims")
101
+ session_allowed = valid and not step_up_required
102
+
103
+ return {
104
+ "valid": valid,
105
+ "claims": claims,
106
+ "error": data.get("error"),
107
+ "session_allowed": session_allowed,
108
+ "step_up_required": step_up_required,
109
+ }
110
+ except Exception as exc:
111
+ return {
112
+ "valid": False,
113
+ "claims": None,
114
+ "error": f"Network/HTTP error: {exc}",
115
+ "session_allowed": False,
116
+ "step_up_required": False,
117
+ }
118
+
119
+
120
+ def create_enrollment_token(
121
+ secret_key: str,
122
+ external_user_id: str,
123
+ display_name: Optional[str] = None,
124
+ ttl_seconds: int = 120,
125
+ endpoint: str = DEFAULT_ENDPOINT,
126
+ ) -> Dict[str, Any]:
127
+ """
128
+ Creates an authorized enrollment token for linking biometric login to an existing user account.
129
+ """
130
+ if not secret_key or not secret_key.startswith("l512_sk_"):
131
+ raise ValueError("Invalid secret_key: must start with l512_sk_")
132
+ if not external_user_id:
133
+ raise ValueError("external_user_id is required")
134
+
135
+ clean_endpoint = endpoint.rstrip("/")
136
+ url = f"{clean_endpoint}/v1/enrollment-tokens"
137
+
138
+ payload: Dict[str, Any] = {
139
+ "external_user_id": external_user_id,
140
+ "ttl_seconds": ttl_seconds,
141
+ }
142
+ if display_name:
143
+ payload["display_name"] = display_name
144
+
145
+ headers = {
146
+ "Content-Type": "application/json",
147
+ "x-api-key": secret_key,
148
+ }
149
+
150
+ resp = requests.post(url, json=payload, headers=headers, timeout=10.0)
151
+ data = resp.json() if resp.content else {}
152
+ if not resp.ok:
153
+ msg = data.get("message") or data.get("error") or f"HTTP {resp.status_code}"
154
+ raise RuntimeError(f"Failed to create enrollment token: {msg}")
155
+
156
+ return data
157
+
158
+
159
+ def trust_device(
160
+ secret_key: str,
161
+ device_ref: str,
162
+ endpoint: str = DEFAULT_ENDPOINT,
163
+ ) -> Dict[str, Any]:
164
+ """
165
+ Registers an unrecognized device as trusted after customer completes step-up verification.
166
+ """
167
+ if not secret_key or not secret_key.startswith("l512_sk_"):
168
+ raise ValueError("Invalid secret_key: must start with l512_sk_")
169
+ if not device_ref:
170
+ raise ValueError("device_ref is required")
171
+
172
+ clean_endpoint = endpoint.rstrip("/")
173
+ url = f"{clean_endpoint}/v1/devices/trust"
174
+
175
+ headers = {
176
+ "Content-Type": "application/json",
177
+ "x-api-key": secret_key,
178
+ }
179
+
180
+ resp = requests.post(url, json={"device_ref": device_ref}, headers=headers, timeout=10.0)
181
+ data = resp.json() if resp.content else {}
182
+ if not resp.ok:
183
+ msg = data.get("message") or data.get("error") or f"HTTP {resp.status_code}"
184
+ raise RuntimeError(f"Failed to trust device: {msg}")
185
+
186
+ return data
187
+
188
+
189
+ def verify_token_offline(
190
+ token: str,
191
+ keys: Union[List[Dict[str, Any]], Dict[str, Any]],
192
+ expected_audience: Optional[str] = None,
193
+ expected_nonce: Optional[str] = None,
194
+ replay_store: Any = None,
195
+ ) -> Dict[str, Any]:
196
+ """
197
+ Verifies an ML-DSA-65 post-quantum token offline using cached public keys and local replay store.
198
+ """
199
+ if not token or not isinstance(token, str):
200
+ return {"valid": False, "claims": None, "error": "Invalid token format", "session_allowed": False, "step_up_required": False}
201
+
202
+ parts = token.split(".")
203
+ if len(parts) != 3:
204
+ return {"valid": False, "claims": None, "error": "Malformed token: expected 3 segments", "session_allowed": False, "step_up_required": False}
205
+
206
+ try:
207
+ header = json.loads(_b64url_decode(parts[0]).decode("utf-8"))
208
+ claims = json.loads(_b64url_decode(parts[1]).decode("utf-8"))
209
+ sig_bytes = _b64url_decode(parts[2])
210
+ except Exception as exc:
211
+ return {"valid": False, "claims": None, "error": f"Failed to decode token segments: {exc}", "session_allowed": False, "step_up_required": False}
212
+
213
+ if header.get("typ") != "L512" or header.get("alg") != "ML-DSA-65":
214
+ return {"valid": False, "claims": None, "error": f"Unsupported token typ/alg: {header.get('typ')}/{header.get('alg')}", "session_allowed": False, "step_up_required": False}
215
+
216
+ now = int(time.time())
217
+ if "exp" in claims and now > claims["exp"]:
218
+ return {"valid": False, "claims": claims, "error": "Token expired", "session_allowed": False, "step_up_required": False}
219
+ if "nbf" in claims and now < claims["nbf"]:
220
+ return {"valid": False, "claims": claims, "error": "Token not yet valid", "session_allowed": False, "step_up_required": False}
221
+
222
+ if expected_audience and claims.get("aud") != expected_audience:
223
+ return {"valid": False, "claims": claims, "error": f"Audience mismatch: expected {expected_audience}, got {claims.get('aud')}", "session_allowed": False, "step_up_required": False}
224
+
225
+ if expected_nonce and claims.get("nonce") != expected_nonce:
226
+ return {"valid": False, "claims": claims, "error": f"Nonce mismatch: expected {expected_nonce}, got {claims.get('nonce')}", "session_allowed": False, "step_up_required": False}
227
+
228
+ # Replay protection check
229
+ if replay_store is not None:
230
+ jti = claims.get("jti")
231
+ if hasattr(replay_store, "has") and replay_store.has(jti):
232
+ return {"valid": False, "claims": claims, "error": "Token replay detected (JTI already used)", "session_allowed": False, "step_up_required": False}
233
+ if hasattr(replay_store, "add"):
234
+ replay_store.add(jti, claims.get("exp", now + 60))
235
+
236
+ # Cryptographic signature check via liboqs or oqs if available
237
+ key_list = keys if isinstance(keys, list) else keys.get("keys", [keys])
238
+ matching_key = next((k for k in key_list if k.get("kid") == header.get("kid")), None)
239
+ if not matching_key:
240
+ return {"valid": False, "claims": claims, "error": f"Unknown signing key kid: {header.get('kid')}", "session_allowed": False, "step_up_required": False}
241
+
242
+ pubkey_bytes = _b64url_decode(matching_key["public_key"])
243
+ message = f"{parts[0]}.{parts[1]}".encode("utf-8")
244
+
245
+ try:
246
+ import oqs
247
+ with oqs.Signature("ML-DSA-65") as verifier:
248
+ is_valid = verifier.verify(message, sig_bytes, pubkey_bytes)
249
+ if not is_valid:
250
+ return {"valid": False, "claims": claims, "error": "Invalid ML-DSA-65 signature", "session_allowed": False, "step_up_required": False}
251
+ except ImportError:
252
+ # Fallback to local app.core.pqc_crypto if installed in environment
253
+ try:
254
+ from app.core.pqc_crypto import verify_ml_dsa_65
255
+ is_valid = verify_ml_dsa_65(pubkey_bytes, message, sig_bytes)
256
+ if not is_valid:
257
+ return {"valid": False, "claims": claims, "error": "Invalid ML-DSA-65 signature", "session_allowed": False, "step_up_required": False}
258
+ except Exception:
259
+ return {
260
+ "valid": False,
261
+ "claims": claims,
262
+ "error": "Offline ML-DSA-65 verification requires liboqs-python (oqs). Please install it or use online verify_token.",
263
+ "session_allowed": False,
264
+ "step_up_required": False,
265
+ }
266
+
267
+ step_up_required = bool(claims.get("stp"))
268
+ session_allowed = not step_up_required
269
+
270
+ return {
271
+ "valid": True,
272
+ "claims": claims,
273
+ "error": None,
274
+ "session_allowed": session_allowed,
275
+ "step_up_required": step_up_required,
276
+ }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,26 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="login512-server",
5
+ version="1.0.0",
6
+ description="Official Login512 Server SDK for Python (Post-Quantum Passwordless Face Authentication)",
7
+ long_description=open("README.md", encoding="utf-8").read(),
8
+ long_description_content_type="text/markdown",
9
+ author="login512.com",
10
+ url="https://login512.com",
11
+ license="Apache-2.0",
12
+ py_modules=["login512_server"],
13
+ python_requires=">=3.9",
14
+ install_requires=[
15
+ "requests>=2.28.0",
16
+ ],
17
+ extras_require={
18
+ "offline": ["liboqs-python>=0.9.0"],
19
+ },
20
+ classifiers=[
21
+ "Programming Language :: Python :: 3",
22
+ "License :: OSI Approved :: Apache Software License",
23
+ "Operating System :: OS Independent",
24
+ "Topic :: Security :: Cryptography",
25
+ ],
26
+ )