Update app.py
Browse files
app.py
CHANGED
|
@@ -1,162 +1,63 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# --- Backend Logic Class (Enhanced with more methods) ---
|
| 19 |
-
class AppServerLogic:
|
| 20 |
-
"""Contains all backend logic and mock data needed by the application."""
|
| 21 |
-
def __init__(self):
|
| 22 |
-
self.private_key_object = None
|
| 23 |
-
self.public_key_pem = ""
|
| 24 |
-
self.mock_user_db = {
|
| 25 |
-
"demo-user": {"api_key": "sk-12345-abcde", "password": "password123"},
|
| 26 |
-
"admin-user": {"api_key": "sk-67890-fghij", "password": "adminpass"}
|
| 27 |
-
}
|
| 28 |
-
self._initialize_keys()
|
| 29 |
-
|
| 30 |
-
def _initialize_keys(self):
|
| 31 |
-
key_pem = os.environ.get('KEYLOCK_PRIV_KEY')
|
| 32 |
-
if not key_pem:
|
| 33 |
-
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
| 34 |
-
key_pem = pk.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode('utf-8')
|
| 35 |
-
try:
|
| 36 |
-
self.private_key_object = serialization.load_pem_private_key(key_pem.encode(), password=None)
|
| 37 |
-
self.public_key_pem = self.private_key_object.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode('utf-8')
|
| 38 |
-
except Exception as e:
|
| 39 |
-
logging.error(f"Key initialization failed: {e}")
|
| 40 |
-
|
| 41 |
-
def decode_payload(self, image_input):
|
| 42 |
-
if not self.private_key_object:
|
| 43 |
-
return {"status": "Error", "message": "Server key not configured."}
|
| 44 |
-
try:
|
| 45 |
-
pixel_data = np.array(image_input.convert("RGB")).ravel()
|
| 46 |
-
header_binary = "".join(str(p & 1) for p in pixel_data[:32])
|
| 47 |
-
data_length = int(header_binary, 2)
|
| 48 |
-
required_pixels = 32 + data_length * 8
|
| 49 |
-
if required_pixels > len(pixel_data):
|
| 50 |
-
raise ValueError("Incomplete payload in image.")
|
| 51 |
-
data_binary = "".join(str(p & 1) for p in pixel_data[32:required_pixels])
|
| 52 |
-
crypto_payload = int(data_binary, 2).to_bytes(data_length, byteorder='big')
|
| 53 |
-
offset = 4
|
| 54 |
-
encrypted_aes_key_len = struct.unpack('>I', crypto_payload[:offset])[0]
|
| 55 |
-
encrypted_aes_key = crypto_payload[offset:offset + encrypted_aes_key_len]; offset += encrypted_aes_key_len
|
| 56 |
-
nonce = crypto_payload[offset:offset + 12]; offset += 12
|
| 57 |
-
ciphertext = crypto_payload[offset:]
|
| 58 |
-
recovered_aes_key = self.private_key_object.decrypt(encrypted_aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
| 59 |
-
payload = json.loads(AESGCM(recovered_aes_key).decrypt(nonce, ciphertext, None).decode())
|
| 60 |
-
return {"status": "Success", "payload": payload}
|
| 61 |
-
except Exception as e:
|
| 62 |
-
return {"status": "Error", "message": f"Decryption Failed: {e}"}
|
| 63 |
-
|
| 64 |
-
def generate_encrypted_image(self, payload_dict):
|
| 65 |
-
"""
|
| 66 |
-
Creates a KeyLock image and returns both a Pillow object for preview
|
| 67 |
-
and a filepath to a saved, uncorrupted PNG for download.
|
| 68 |
-
"""
|
| 69 |
-
try:
|
| 70 |
-
response = requests.get("https://images.unsplash.com/photo-1506318137071-a8e063b4bec0?q=80&w=1200", timeout=10)
|
| 71 |
-
img = ImageOps.fit(Image.open(io.BytesIO(response.content)).convert("RGB"), (600, 600))
|
| 72 |
-
except:
|
| 73 |
-
img = Image.new('RGB', (600, 600), color=(15, 23, 42))
|
| 74 |
-
|
| 75 |
-
json_bytes = json.dumps(payload_dict).encode('utf-8')
|
| 76 |
-
public_key = serialization.load_pem_public_key(self.public_key_pem.encode('utf-8'))
|
| 77 |
-
aes_key, nonce = os.urandom(32), os.urandom(12)
|
| 78 |
-
ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
| 79 |
-
rsa_key = public_key.encrypt(aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
| 80 |
-
payload = struct.pack('>I', len(rsa_key)) + rsa_key + nonce + ciphertext
|
| 81 |
-
|
| 82 |
-
pixel_data = np.array(img).ravel()
|
| 83 |
-
binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(payload)) + payload)
|
| 84 |
-
pixel_data[:len(binary_payload)] = (pixel_data[:len(binary_payload)] & 0xFE) | np.array(list(binary_payload), dtype=np.uint8)
|
| 85 |
-
final_image = Image.fromarray(pixel_data.reshape(img.size[1], img.size[0], 3), 'RGB')
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
class KeylockDecoderComponent(gr.components.Component):
|
| 102 |
-
"""A Gradio Component that decodes a KeyLock image and provides advanced tools."""
|
| 103 |
-
EVENTS = ["change"]
|
| 104 |
-
|
| 105 |
-
def __init__(self, server_logic, **kwargs):
|
| 106 |
-
self.server_logic = server_logic
|
| 107 |
-
self.value = None
|
| 108 |
-
super().__init__(**kwargs)
|
| 109 |
-
|
| 110 |
-
def _format_message(self, result: dict | None) -> str:
|
| 111 |
-
if not result or not result.get("status"): return "Upload a KeyLock image to auto-fill credentials."
|
| 112 |
-
status = result["status"]
|
| 113 |
-
if status == "Success":
|
| 114 |
-
user = result.get("payload", {}).get("USER", "N/A")
|
| 115 |
-
return f"<p style='color:green; font-weight:bold;'>✅ Success! Decoded credentials for '{user}'.</p>"
|
| 116 |
else:
|
| 117 |
-
|
| 118 |
-
return f"<p style='color:red;
|
| 119 |
-
|
| 120 |
-
def preprocess(self, payload): return payload
|
| 121 |
-
def postprocess(self, value): return value
|
| 122 |
-
def api_info(self): return {"type": "object", "example": {"status": "Success", "payload": {"USER": "demo-user"}}}
|
| 123 |
-
|
| 124 |
-
def render(self):
|
| 125 |
-
value_state = gr.State(value=self.value)
|
| 126 |
-
|
| 127 |
-
with gr.Column():
|
| 128 |
-
image_input = gr.Image(label="KeyLock Image", type="pil", show_label=False)
|
| 129 |
-
status_display = gr.Markdown(self._format_message(self.value))
|
| 130 |
-
|
| 131 |
-
with gr.Accordion("Generate Encrypted Image", open=False):
|
| 132 |
-
gr.Markdown("Create a test image using the site's public key.")
|
| 133 |
-
payload_input = gr.JSON(label="Payload to Encrypt", value={"API_KEY": "sk-12345-abcde", "USER": "demo-user"})
|
| 134 |
-
generate_img_button = gr.Button("Generate Image", variant="secondary")
|
| 135 |
-
# Use two components: an Image for preview and a File for download
|
| 136 |
-
generated_image_preview = gr.Image(label="Generated Image Preview", interactive=False)
|
| 137 |
-
generated_file_download = gr.File(label="Download Uncorrupted PNG", interactive=False)
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from keylock_component import KeylockDecoderComponent, AppServerLogic
|
| 3 |
+
|
| 4 |
+
# --- App Definition ---
|
| 5 |
+
shared_server_logic = AppServerLogic()
|
| 6 |
+
|
| 7 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky")) as demo:
|
| 8 |
+
gr.Markdown("# 🔑 KeyLock Application Login")
|
| 9 |
+
|
| 10 |
+
with gr.Row():
|
| 11 |
+
with gr.Column(scale=2):
|
| 12 |
+
gr.Markdown("### 1. Login with Credentials")
|
| 13 |
+
gr.Markdown("Enter your credentials manually, or use a KeyLock image to auto-fill them.")
|
| 14 |
+
username_input = gr.Textbox(label="Username", interactive=True)
|
| 15 |
+
password_input = gr.Textbox(label="Password", type="password", interactive=True)
|
| 16 |
+
login_button = gr.Button("Login", variant="primary")
|
| 17 |
+
login_status = gr.Markdown()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
with gr.Column(scale=3):
|
| 20 |
+
gr.Markdown("### 2. Use a KeyLock Image to Auto-Fill")
|
| 21 |
+
keylock_decoder = KeylockDecoderComponent(
|
| 22 |
+
server_logic=shared_server_logic
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# --- App-level Event Handlers ---
|
| 26 |
+
|
| 27 |
+
def handle_login(username, password):
|
| 28 |
+
"""The final verification step after fields are filled."""
|
| 29 |
+
user_data = shared_server_logic.mock_user_db.get(username)
|
| 30 |
+
if user_data and user_data["password"] == password:
|
| 31 |
+
gr.Info(f"Login Successful! Welcome, {username}.")
|
| 32 |
+
return f"<p style='color:green;font-weight:bold'>✅ Login successful for {username}.</p>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
else:
|
| 34 |
+
gr.Error("Login Failed: Invalid username or password.")
|
| 35 |
+
return f"<p style='color:red;font-weight:bold'>❌ Login failed.</p>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
def autofill_from_key(decoder_result):
|
| 38 |
+
"""
|
| 39 |
+
This listens to the component and updates the login form.
|
| 40 |
+
"""
|
| 41 |
+
if decoder_result and decoder_result.get("status") == "Success":
|
| 42 |
+
payload = decoder_result.get("payload", {})
|
| 43 |
+
user = payload.get("USER", "")
|
| 44 |
+
user_data = shared_server_logic.mock_user_db.get(user)
|
| 45 |
+
password = user_data.get("password", "") if user_data else ""
|
| 46 |
+
return user, password
|
| 47 |
+
return gr.update(), gr.update()
|
| 48 |
+
|
| 49 |
+
# --- Wire the event handlers to the UI components ---
|
| 50 |
+
keylock_decoder.change(
|
| 51 |
+
fn=autofill_from_key,
|
| 52 |
+
inputs=[keylock_decoder],
|
| 53 |
+
outputs=[username_input, password_input]
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
login_button.click(
|
| 57 |
+
fn=handle_login,
|
| 58 |
+
inputs=[username_input, password_input],
|
| 59 |
+
outputs=[login_status]
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
demo.launch()
|