-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstreamlit_generator.py
More file actions
420 lines (365 loc) ยท 15.3 KB
/
streamlit_generator.py
File metadata and controls
420 lines (365 loc) ยท 15.3 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
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
"""
Streamlit OTP Generator Application
Generates time-based OTPs using recurrence relation with transparent math display
"""
import streamlit as st
import time
import requests
from datetime import datetime, timedelta
import config
# Page configuration
st.set_page_config(
page_title="OTP Generator",
page_icon="๐",
layout="wide",
initial_sidebar_state="collapsed"
)
# Custom CSS for styling
st.markdown("""
<style>
.big-font {
font-size: 48px !important;
font-weight: bold;
color: #1f77b4;
text-align: center;
font-family: monospace;
}
.countdown {
font-size: 20px !important;
color: #666;
text-align: center;
}
.formula-box {
background-color: #f0f2f6;
padding: 20px;
border-radius: 10px;
margin: 10px 0;
border-left: 4px solid #1f77b4;
}
.stMetricValue {
font-size: 48px !important;
font-family: monospace;
letter-spacing: 8px;
}
.otp-display {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 30px;
border-radius: 15px;
text-align: center;
margin: 20px 0;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}
.otp-number {
font-size: 56px;
color: white;
font-weight: bold;
letter-spacing: 12px;
font-family: 'Courier New', monospace;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}
.success-msg {
color: green;
font-weight: bold;
}
.error-msg {
color: red;
font-weight: bold;
}
</style>
""", unsafe_allow_html=True)
def calculate_otp(time_slice: int) -> tuple:
"""
Calculate OTP using recurrence relation with a TIME-DEPENDENT seed
Returns: (otp_string, x_next_value, calculation_details)
"""
# --- SOLUTION ---
# The seed for the calculation MUST change with the time_slice
# This introduces the non-linear t^2 term needed for security
time_dependent_seed = config.seed + time_slice
# --- END SOLUTION ---
# Recurrence relation: X_(n+1) = (a * X_n^2 + b * t + c) mod m
x_squared = time_dependent_seed ** 2 # Use the new time-dependent seed
x_next = (config.a * x_squared + config.b * time_slice + config.c) % config.m
# Generate 6-digit OTP
otp_value = x_next % config.otp_modulus
otp_string = str(otp_value).zfill(config.otp_digits)
# Return calculation details for display
calc_details = {
'seed': time_dependent_seed, # Report the seed that was actually used
'x_squared': x_squared,
'term1': config.a * x_squared,
'term2': config.b * time_slice,
'term3': config.c,
'sum': config.a * x_squared + config.b * time_slice + config.c,
'x_next': x_next,
'otp_value': otp_value
}
return otp_string, x_next, calc_details
def send_otp_to_api(otp: str, timestamp: int, time_slice: int, validity_duration: int) -> bool:
"""
Send generated OTP to FastAPI backend
Returns: Success status
"""
try:
response = requests.post(
f"{config.api_url}/otp/update",
json={
"otp": otp,
"timestamp": timestamp,
"time_slice": time_slice,
"validity_duration": validity_duration
},
headers={
"X-API-KEY": config.api_key,
"Content-Type": "application/json"
},
timeout=5
)
return response.status_code == 200
except requests.exceptions.RequestException as e:
st.error(f"Failed to send OTP to server: {str(e)}")
return False
def main():
"""Main application logic"""
# Title and description
st.title("๐ OTP Generator")
st.markdown("### Transparent Time-Based OTP Generation with Recurrence Relations")
# Initialize session state
if 'last_time_slice' not in st.session_state:
st.session_state.last_time_slice = None
if 'last_otp' not in st.session_state:
st.session_state.last_otp = None
if 'validity_duration' not in st.session_state:
st.session_state.validity_duration = config.time_slice_duration
if 'manual_regenerate' not in st.session_state:
st.session_state.manual_regenerate = False
if 'force_time_slice' not in st.session_state:
st.session_state.force_time_slice = None
# Validity duration slider in sidebar
with st.sidebar:
st.markdown("## โ๏ธ OTP Settings")
st.markdown("---")
# Custom validity slider
st.markdown("### โฑ๏ธ OTP Validity Duration")
validity = st.slider(
"Select validity window (seconds)",
min_value=config.min_validity,
max_value=config.max_validity,
value=st.session_state.validity_duration,
step=5,
help="OTP will remain valid for this duration"
)
st.session_state.validity_duration = validity
st.info(f"๐ Current validity: **{validity} seconds**")
st.markdown("---")
st.markdown("### ๐ System Info")
st.code(f"Default: {config.time_slice_duration}s")
st.code(f"Range: {config.min_validity}-{config.max_validity}s")
# Create two columns for layout
col1, col2 = st.columns([1, 1])
with col1:
st.markdown("## ๐ Current OTP")
# Calculate current time values using custom validity
current_time = int(time.time())
# Check for manual regeneration
if st.session_state.manual_regenerate:
# Use current timestamp as custom time slice for manual regeneration
st.session_state.force_time_slice = current_time
st.session_state.manual_regenerate = False
time_slice = current_time
elif st.session_state.force_time_slice is not None:
# Keep using forced time slice until validity expires
forced_elapsed = current_time - st.session_state.force_time_slice
if forced_elapsed >= st.session_state.validity_duration:
# Forced OTP expired, go back to normal
st.session_state.force_time_slice = None
time_slice = current_time // st.session_state.validity_duration
else:
time_slice = st.session_state.force_time_slice
else:
# Normal time-based calculation
time_slice = current_time // st.session_state.validity_duration
# Calculate time remaining based on time slice start
if st.session_state.force_time_slice is not None:
# For manual OTP
otp_start_time = st.session_state.force_time_slice
else:
# For auto OTP
otp_start_time = time_slice * st.session_state.validity_duration
time_in_slice = current_time - otp_start_time
time_remaining = st.session_state.validity_duration - time_in_slice
# Ensure time_remaining is never negative
if time_remaining < 0:
time_remaining = 0
time_in_slice = st.session_state.validity_duration
# Calculate OTP - ALWAYS uses config.seed (constant)
otp, x_next, calc_details = calculate_otp(time_slice)
# Display OTP with enhanced visual styling and copy button
st.markdown(
f'''
<div class="otp-display">
<div style="color: rgba(255,255,255,0.8); font-size: 18px; margin-bottom: 10px;">๐ ONE-TIME PASSWORD</div>
<div class="otp-number" id="otp-value">{otp}</div>
<div style="margin-top: 15px; font-size: 14px; color: rgba(255,255,255,0.7);">
๐ Click to copy: <code style="background: rgba(0,0,0,0.3); padding: 5px 10px; border-radius: 5px;">{otp}</code>
</div>
</div>
''',
unsafe_allow_html=True
)
# Copy button
if st.button("๐ Copy OTP to Clipboard", use_container_width=True, key="copy_otp"):
st.code(otp, language=None)
st.success(f"โ
OTP **{otp}** ready to copy!")
# Display countdown with correct progress calculation
progress = time_in_slice / st.session_state.validity_duration
st.progress(progress)
# Visual countdown with color coding
if time_remaining <= 10:
color = "#ff4444" # Red for last 10 seconds
elif time_remaining <= 20:
color = "#ff9900" # Orange for 11-20 seconds
else:
color = "#00cc66" # Green for more than 20 seconds
st.markdown(f'<p class="countdown" style="color: {color}; font-size: 24px; font-weight: bold;">โฑ๏ธ Expires in: {time_remaining} seconds</p>',
unsafe_allow_html=True)
# Auto-send to API if time slice changed
if time_slice != st.session_state.last_time_slice:
# Use otp_start_time for timestamp
if send_otp_to_api(otp, otp_start_time, time_slice, st.session_state.validity_duration):
st.success("โ
OTP sent to server successfully")
st.session_state.last_time_slice = time_slice
st.session_state.last_otp = otp
else:
st.error("โ Failed to send OTP to server")
# Action buttons
st.markdown("### ๐ฎ Actions")
btn_col1, btn_col2 = st.columns(2)
with btn_col1:
# Manual regenerate button
if st.button("๐ Regenerate OTP", use_container_width=True, type="primary"):
st.session_state.manual_regenerate = True
st.rerun()
with btn_col2:
# Manual send button
if st.button("๐ค Send to Server", use_container_width=True):
if send_otp_to_api(otp, otp_start_time, time_slice, st.session_state.validity_duration):
st.success("โ
OTP sent to server successfully")
st.session_state.last_time_slice = time_slice
else:
st.error("โ Failed to send OTP to server")
# Display current time info with visual chart
st.markdown("### โฐ Time Information")
time_info_col1, time_info_col2 = st.columns(2)
with time_info_col1:
st.info(f"Current Timestamp: {current_time}")
with time_info_col2:
st.info(f"Time Slice Index: {time_slice}")
# Visual representation of time progress
st.markdown("### ๐ Time Progress Visualization")
import pandas as pd
import numpy as np
# Create a simple bar chart showing time progress
chart_data = pd.DataFrame({
'Time': ['Elapsed', 'Remaining'],
'Seconds': [time_in_slice, time_remaining]
})
st.bar_chart(chart_data.set_index('Time'))
with col2:
st.markdown("## ๐งฎ Mathematical Transparency")
# Display the recurrence formula
st.markdown('<div class="formula-box">', unsafe_allow_html=True)
st.latex(r"X_{n+1} = (a \cdot X_n^2 + b \cdot t + c) \bmod m")
st.markdown('</div>', unsafe_allow_html=True)
# Display constants
st.markdown("### ๐ Constants")
const_col1, const_col2 = st.columns(2)
with const_col1:
st.code(f"a = {config.a}")
st.code(f"b = {config.b}")
st.code(f"c = {config.c}")
with const_col2:
st.code(f"m = {config.m:,}")
st.code(f"seed = {config.seed:,}")
st.code(f"OTP mod = {config.otp_modulus:,}")
# Show calculation steps using calc_details
st.markdown("### ๐ Calculation Steps")
with st.expander("View Detailed Calculation", expanded=True):
# Display using calculation details
st.write(f"**Step 1:** Square the seed (constant)")
st.code(f"X_nยฒ = {calc_details['seed']:,}ยฒ = {calc_details['x_squared']:,}")
# Step 2: Apply recurrence relation
st.write(f"**Step 2:** Apply recurrence relation")
st.code(f"""
a ร X_nยฒ = {config.a} ร {calc_details['x_squared']:,} = {calc_details['term1']:,}
b ร t = {config.b} ร {time_slice} = {calc_details['term2']:,}
c = {calc_details['term3']}
Sum = {calc_details['term1']:,} + {calc_details['term2']:,} + {calc_details['term3']} = {calc_details['sum']:,}
""")
# Step 3: Apply modulus m
st.write(f"**Step 3:** Apply modulus m")
st.code(f"X_n+1 = {calc_details['sum']:,} mod {config.m:,} = {calc_details['x_next']:,}")
# Step 4: Generate OTP
st.write(f"**Step 4:** Generate 6-digit OTP")
st.code(f"OTP = {calc_details['x_next']:,} mod {config.otp_modulus:,} = {calc_details['otp_value']:06d}")
# Add more graphs
st.markdown("### ๐ Additional Visualizations")
# OTP History chart (simulated)
import pandas as pd
import numpy as np
# Generate sample OTPs for past few time slices
history_slices = []
history_otps = []
for i in range(max(0, time_slice - 5), time_slice + 1):
temp_otp, _, _ = calculate_otp(i)
history_slices.append(f"Slice {i}")
history_otps.append(int(temp_otp))
df_history = pd.DataFrame({
'Time Slice': history_slices,
'OTP Value': history_otps
})
st.line_chart(df_history.set_index('Time Slice'))
st.caption("๐ OTP values for recent time slices")
# Constants visualization
st.markdown("#### ๐ข Constants Distribution")
const_df = pd.DataFrame({
'Constant': ['a', 'b', 'c'],
'Value': [config.a, config.b, config.c]
})
st.bar_chart(const_df.set_index('Constant'))
# Server status
st.markdown("### ๐ฅ๏ธ Server Status")
try:
response = requests.get(f"{config.api_url}/health", timeout=2)
if response.status_code == 200:
st.success("โ
Server is running")
# Show current OTP on server
try:
otp_response = requests.get(f"{config.api_url}/otp/current", timeout=2)
if otp_response.status_code == 200:
server_otp_data = otp_response.json()
if server_otp_data.get('otp'):
st.info(f"๐ Server OTP: **{server_otp_data['otp']}**")
if server_otp_data.get('expired'):
st.warning("โ ๏ธ Server OTP has expired")
except:
pass
else:
st.warning("โ ๏ธ Server responding with issues")
except:
st.error("โ Cannot connect to server")
# Footer
st.markdown("---")
st.markdown(
"""
<div style='text-align: center; color: #666;'>
๐ Recurrence-Based OTP System | Auto-refreshes every second
</div>
""",
unsafe_allow_html=True
)
# Auto-refresh every second
time.sleep(1)
st.rerun()
if __name__ == "__main__":
main()