commit c1c65cac4f7f9b81fefe343e7e9c371eb2e2986b Author: Jeremy Karst Date: Tue Jan 14 13:17:55 2025 -0500 A fresh start before publishing diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eb10d1b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +signatures.db +__pycache__/ +*.pyc +server.log \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..ff726e8 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,27 @@ +# Custom MIT-Based License with Additional Terms + +This software is licensed under the MIT License with Additional Terms. +This is NOT the standard MIT License. + +## MIT License + +Copyright (c) 2025 Jeremy Karst + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## Additional Terms + +In addition to the terms and conditions of the MIT License above, the following terms apply: + +1. Project Identity Protection + Any redistribution, fork, or modified version of this software must not use the name "Open Signature Generator", either alone or as part of another name, except to indicate that the work is derived from or based on this software. This restriction includes, but is not limited to, public hosting of modified versions and derivative works. + +2. Scope of Additional Terms + These Additional Terms are intended to supplement, not replace, the permissions and restrictions specified in the MIT License above. In the event of any conflict between these Additional Terms and the MIT License, these Additional Terms shall take precedence. + +3. Severability + If any portion of these Additional Terms is found to be invalid or unenforceable, the remaining portions shall remain in effect. \ No newline at end of file diff --git a/benchmark.py b/benchmark.py new file mode 100644 index 0000000..eced928 --- /dev/null +++ b/benchmark.py @@ -0,0 +1,160 @@ +import time +import requests +import statistics +from concurrent.futures import ThreadPoolExecutor +import argparse +from rich.console import Console +from rich.table import Table +from rich.progress import Progress +import random + +def make_request(base_url, session): + """Make requests to test the full signature flow""" + start_time = time.time() + try: + # Fetch fonts + fonts_response = session.get(f"{base_url}/fonts") + fonts_response.raise_for_status() + available_fonts = list(fonts_response.json().keys()) + + # 1. Register a new signature + name = f"Test User {random.randint(100000000, 999999999)}" + register_data = { + 'name': name, + 'font': random.choice(available_fonts), + 'timezone': '0', + 'invert': 'false' + } + register_response = session.get(f"{base_url}/register", params=register_data) + register_response.raise_for_status() + signature_hash = register_response.text + register_time = time.time() + + # 2. Verify the signature + verify_response = session.get(f"{base_url}/verify/{signature_hash}") + verify_response.raise_for_status() + verify_time = time.time() + + # 3. Get the signature image + image_response = session.get(f"{base_url}/images/{signature_hash}.png") + image_response.raise_for_status() + image_time = time.time() + + return { + 'register_time': register_time - start_time, + 'register_status': register_response.status_code, + 'verify_time': verify_time - register_time, + 'verify_status': verify_response.status_code, + 'image_time': image_time - verify_time, + 'image_status': image_response.status_code + } + except requests.RequestException as e: + print(f"Request failed: {e}") + return None + +def run_benchmark(base_url, num_threads, requests_per_thread, progress=None): + """Run benchmark with specified number of threads""" + session = requests.Session() + register_times = [] + verify_times = [] + image_times = [] + errors = 0 + + def worker(): + for _ in range(requests_per_thread): + result = make_request(base_url, session) + if result is None: + nonlocal errors + errors += 1 + else: + register_times.append(result['register_time']) + verify_times.append(result['verify_time']) + image_times.append(result['image_time']) + if progress: + progress.update(task, advance=1) + + # Create and start threads + with Progress() as progress: + task = progress.add_task(f"[cyan]Running {num_threads} threads...", total=num_threads * requests_per_thread) + with ThreadPoolExecutor(max_workers=num_threads) as executor: + futures = [executor.submit(worker) for _ in range(num_threads)] + for future in futures: + future.result() + + if not image_times: + return None + + return { + 'successful_register_requests': len(register_times), + 'successful_verify_requests': len(verify_times), + 'successful_image_requests': len(image_times), + 'failed_requests': errors, + 'median_register_response_time': statistics.median(register_times), + 'median_verify_response_time': statistics.median(verify_times), + 'median_image_response_time': statistics.median(image_times), + 'min_response_time': min(register_times + verify_times + image_times), + 'max_response_time': max(register_times + verify_times + image_times), + 'total_time': sum(register_times + verify_times + image_times) + } + +def main(): + parser = argparse.ArgumentParser(description='Benchmark web server performance') + parser.add_argument('--url', default='http://localhost:8080', help='Base URL of the server') + parser.add_argument('--start-threads', type=int, default=1, help='Starting number of threads') + parser.add_argument('--max-threads', type=int, default=100, help='Maximum number of threads') + parser.add_argument('--requests-per-thread', type=int, default=20, help='Number of requests per thread') + + args = parser.parse_args() + + console = Console() + results_table = Table(show_header=True, header_style="bold cyan") + results_table.add_column("Threads") + results_table.add_column("Total Requests") + results_table.add_column("Success Rate") + results_table.add_column("Median Response (s)") + results_table.add_column("Req/sec") + + console.print(f"\n[bold green]Starting benchmark against {args.url}[/bold green]") + console.print("[yellow]Note: Each request includes register, verify, and image generation[/yellow]\n") + + # Test thread counts from start to max, doubling every step + assert args.start_threads > 0, "Starting threads must be greater than 0" + thread_counts = [args.start_threads] + while thread_counts[-1] < args.max_threads: + thread_counts.append(thread_counts[-1] * 2) + if thread_counts[-1] > args.max_threads: + thread_counts[-1] = args.max_threads + + for num_threads in thread_counts: + console.print(f"[yellow]Testing with {num_threads} threads...[/yellow]") + + start_time = time.time() + result = run_benchmark(args.url, num_threads, args.requests_per_thread) + end_time = time.time() + + if result: + register_success_rate = (result['successful_register_requests'] / (num_threads * args.requests_per_thread)) * 100 + verify_success_rate = (result['successful_verify_requests'] / (num_threads * args.requests_per_thread)) * 100 + image_success_rate = (result['successful_image_requests'] / (num_threads * args.requests_per_thread)) * 100 + requests_per_second = (result['successful_register_requests'] + result['successful_verify_requests'] + result['successful_image_requests']) / (end_time - start_time) + results_table.add_row( + str(num_threads), + str(num_threads * args.requests_per_thread * 3), + f"{register_success_rate:.1f}% / {verify_success_rate:.1f}% / {image_success_rate:.1f}%", + f"{result['median_register_response_time']:.3f} / {result['median_verify_response_time']:.3f} / {result['median_image_response_time']:.3f}", + f"{requests_per_second:.1f}" + ) + else: + results_table.add_row( + str(num_threads), + str(num_threads * args.requests_per_thread), + "0%", + "N/A", + "N/A" + ) + + console.print("\n[bold]Benchmark Results:[/bold]") + console.print(results_table) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..4db781f --- /dev/null +++ b/compose.yaml @@ -0,0 +1,21 @@ +name: open-signature-generator +services: + osg: + build: + context: . + dockerfile: osg.dockerfile + + image: osg:20 # <--automate this number change to trigger stack redeploy. + + environment: + DOCKER: "true" + HOSTPREFIX: "osg.jkdev.org" + + ports: + - "8312:8080" + + volumes: + - sqlite-database:/data + +volumes: + sqlite-database: \ No newline at end of file diff --git a/create_docker_image.bat b/create_docker_image.bat new file mode 100644 index 0000000..a629913 --- /dev/null +++ b/create_docker_image.bat @@ -0,0 +1,2 @@ +docker build -f ./osg.dockerfile -t python-osg . +pause \ No newline at end of file diff --git a/osg.dockerfile b/osg.dockerfile new file mode 100644 index 0000000..48c561d --- /dev/null +++ b/osg.dockerfile @@ -0,0 +1,8 @@ +FROM python:3.12-slim +ADD server.py . +ADD sha_sign.py . +COPY web_content/ /web_content/ +COPY requirements.txt /requirements.txt +RUN pip install -r requirements.txt +CMD ["python", "server.py"] +EXPOSE 8080 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1539323 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +CherryPy==18.9.0 +cryptography==42.0.5 +fonttools==4.50.0 +geocoder==1.38.1 +pillow==10.2.0 +qrcode==8.0 \ No newline at end of file diff --git a/server.py b/server.py new file mode 100644 index 0000000..1271b3f --- /dev/null +++ b/server.py @@ -0,0 +1,410 @@ +import os +import sqlite3 +import time +import threading +import datetime +import io +import json +import logging +from logging.handlers import RotatingFileHandler +from collections import deque +from threading import Timer +import multiprocessing +from multiprocessing import Pool + +import cherrypy +from cherrypy.lib import file_generator +from fontTools import ttLib +import geocoder + +from sha_sign import hash_text, generate_signature_image + + +def open_db(path): + db_lock = threading.Lock() + if not os.path.exists(path): + conn = sqlite3.connect(path, check_same_thread=False, cached_statements=0, autocommit = False) + conn.execute("CREATE TABLE signatures (hash TEXT PRIMARY KEY, name TEXT, time INTEGER, timezone INTEGER, font TEXT, invert BOOLEAN, identity TEXT)") + conn.commit() + else: + conn = sqlite3.connect(path, check_same_thread=False, cached_statements=0) + return conn, db_lock + + +def run_server(host_ip, host_port, host_prefix, static_dir, database_connection, db_lock, font_data, production=False): + logger = logging.getLogger(__name__) + static_dir = os.path.abspath(static_dir) + + # Create process pool for signature generation + process_pool = Pool(processes=multiprocessing.cpu_count() // 2) + + # Define web server + root_server_config= { + '/': { + 'tools.staticdir.on': True, + 'tools.staticdir.dir': static_dir, + 'tools.staticdir.index': 'index.html', + }, + '/images': { + 'tools.caching.on': True, + 'tools.caching.delay': 60, + } + } + + global_server_config = { + 'server.socket_host': host_ip, + 'server.socket_port': host_port, + 'server.max_request_body_size': 10*1024, + 'server.socket_timeout': 10, + 'response.timeout': 30, + 'tools.gzip.on': True, + 'tools.gzip.mime_types': ['text/*', 'application/*'], + 'tools.encode.text_only': False + } + + if production: + global_server_config['environment'] = 'production' + + cherrypy.config.update(global_server_config) + + def error_page_404(status, message, traceback, version): + return "Error 404: Page Not Found!" + cherrypy.config.update({'error_page.404': error_page_404}) + + class RateLimiter: + def __init__(self, requests_per_interval=20, limit_interval = 120, cleanup_interval=300): + assert cleanup_interval > limit_interval, "Cleanup interval must be greater than limit interval" + self.requests_per_minute = requests_per_interval + self.window = limit_interval # seconds + self.cleanup_interval = cleanup_interval # cleanup every 5 minutes + self.requests = {} # ip -> deque of timestamps + self.start_cleanup_timer() + + def start_cleanup_timer(self): + """Start periodic cleanup of old IP records""" + Timer(self.cleanup_interval, self._cleanup_old_records).start() + + def _cleanup_old_records(self): + """Remove IPs that haven't made requests in the last window""" + current_time = time.time() + # Create list of IPs to remove to avoid runtime dictionary modification + to_remove = [ + ip for ip, timestamps in self.requests.items() + if not timestamps or current_time - timestamps[-1] > self.window + ] + for ip in to_remove: + del self.requests[ip] + + # Restart cleanup timer + self.start_cleanup_timer() + + def is_rate_limited(self, ip): + if ip == '127.0.0.1': + return False + + current_time = time.time() + + # Initialize or get request deque for this IP + if ip not in self.requests: + self.requests[ip] = deque(maxlen=self.requests_per_minute) + + timestamps = self.requests[ip] + + # Remove timestamps outside the current window + while timestamps and current_time - timestamps[0] > self.window: + timestamps.popleft() + + # Check if rate limited + if len(timestamps) >= self.requests_per_minute: + return True + + # Add new request timestamp + timestamps.append(current_time) + return False + + class RootServer(object): + rate_limiter = RateLimiter() + + with open(os.path.join(static_dir, "verification.html"), "r") as f: + verification_html = f.read() + with open(os.path.join(static_dir, "howto.html"), "r") as f: + howto_html = f.read() + with open(os.path.join(static_dir, "privacy.html"), "r") as f: + privacy_html = f.read() + + @staticmethod + def _get_ip(request): + if 'Cf-Connecting-Ip' in request.headers: + logger.debug("Using Cloudflare IP: %s", request.headers['Cf-Connecting-Ip']) + ip = request.headers['CF-Connecting-IP'] + elif 'X-Forwarded-For' in request.headers: + logger.debug("Using X-Forwarded-For IP: %s", request.headers['X-Forwarded-For']) + ip = request.headers['X-Forwarded-For'] + else: + logger.debug("Using Remote IP: %s", request.remote.ip) + ip = request.remote.ip + return ip + + @cherrypy.expose + def register(self, name: str, font: str, timezone: str = '0', invert: str = 'false'): + request = cherrypy.request + ip = self._get_ip(request) + + if self.rate_limiter.is_rate_limited(ip): + raise cherrypy.HTTPError(429, "Too Many Requests, try again later.") + + # Validate inputs + if len(name) <= 0 or len(name) > 255: + raise cherrypy.HTTPError(400, "Bad Request, invalid signature name") + # Ensure name can be utf-8 encoded + try: + name.encode('utf-8') + except UnicodeEncodeError: + raise cherrypy.HTTPError(400, "Bad Request, invalid signature name") + if font not in font_data: + raise cherrypy.HTTPError(400, "Bad Request, invalid font name") + try: + timezone = int(timezone) + except ValueError: + raise cherrypy.HTTPError(400, "Bad Request, invalid timezone") + if timezone < -12*60 or timezone > 14*60: + raise cherrypy.HTTPError(400, "Bad Request, invalid timezone") + if invert.lower() not in ['true', 'false']: + raise cherrypy.HTTPError(400, "Bad Request, invalid invert value") + else: + try: + invert = invert.lower() == 'true' + except ValueError: + raise cherrypy.HTTPError(400, "Bad Request, invalid invert value") + + # CamelCase the name if it's not already + name_parts = name.split(' ') + for i, part in enumerate(name_parts): + if part[0].islower(): + name_parts[i] = part[0].upper() + part[1:] + name = ' '.join(name_parts) + + # Get user agent and ip for later signature verification + user_agent = request.headers['User-Agent'] + + # Try to get user location + try: + if ip == '127.0.0.1': + raise Exception("Localhost IP detected, skipping location lookup") + location = geocoder.ip(ip) + if location.lat is None or location.lng is None: + latlon = [0.0, 0.0] + else: + latlon = [location.lat, location.lng] + if location.org is None: + provider = 'None Found' + else: + provider = location.org + if location.address == "": + address = 'None Found' + else: + address = location.address + except Exception as e: + latlon = [0.0, 0.0] + address = 'None Found' + provider = 'None Found' + + # Get current unix time for signature timestamp + unix_time = int(time.time()) + + # Generate signature hash + hash_id = hash_text(f"{name}{unix_time}") + + # Sanity check hash length, in theory there is a small chance the hash will be short since we prune '=' padding + if len(hash_id) < 8: + raise cherrypy.HTTPError(500, "Internal Server Error, hash generation failed") + + identity = json.dumps({ # This shouldn't be able to fail since geocoder's api is stable and returns stringifyable data + 'ip': ip, + 'useragent': user_agent, + 'latlon': latlon, + 'address': address, + 'provider': provider + }) + # Insert signature into database + with db_lock: + try: + database_connection.execute("INSERT INTO signatures (hash, name, time, timezone, font, invert, identity) VALUES (?, ?, ?, ?, ?, ?, ?)", (hash_id, name, unix_time, timezone, font, invert, identity)) + database_connection.commit() + except Exception as e: + logger.error("Error inserting signature into database: %s", e) + raise cherrypy.HTTPError(500, "Internal Server Error, failed to insert signature into database") + + return hash_id + + @cherrypy.expose + def verify(self, *args): + request = cherrypy.request + ip = self._get_ip(request) + + if self.rate_limiter.is_rate_limited(ip): + raise cherrypy.HTTPError(429, "Too Many Requests, try again later.") + + if len(args) == 1: + id = args[0] + if len(id) == 0 or len(id) > 64: + raise cherrypy.HTTPError(400, "Bad Request, invalid signature id") + try: + id.encode('utf-8') + except UnicodeEncodeError: + raise cherrypy.HTTPError(400, "Bad Request, invalid signature id") + + # Get signature data from database + cursor = database_connection.cursor() + cursor.execute("SELECT name, time, timezone, font, invert, identity FROM signatures WHERE hash = ?", (id,)) + result = cursor.fetchone() + if result is None: + raise cherrypy.HTTPError(404, "Not Found") + name, time, timezone, font, invert, identity = result + + return json.dumps({ + "name": name, + "time": time, + "timezone": timezone, + "font": font, + "invert": invert, + "identity": json.loads(identity) + }) + + else: # Redirect to verification page + raise cherrypy.HTTPRedirect(f"{host_prefix}/verify/{id}") + + @cherrypy.expose + def v(self, *args): + request = cherrypy.request + ip = self._get_ip(request) + + if self.rate_limiter.is_rate_limited(ip): + raise cherrypy.HTTPError(429, "Too Many Requests, try again later.") + + if len(args) == 1: + id = args[0] + if len(id) == 0 or len(id) > 64: + raise cherrypy.HTTPError(400, "Bad Request, invalid signature id") + try: + id.encode('utf-8') + except UnicodeEncodeError: + raise cherrypy.HTTPError(400, "Bad Request, invalid signature id") + + if 'environment' in global_server_config and global_server_config['environment'] == 'production': + return self.verification_html + else: # If we are debugging, read the newest verification.html file from disk + with open(os.path.join(static_dir, "verification.html"), "r") as f: + verification_html = f.read() + return verification_html + else: + raise cherrypy.HTTPRedirect(f"{host_prefix}") + + @cherrypy.expose + def fonts(self): + return json.dumps(font_data) + + + @cherrypy.expose + def images(self, *args): + request = cherrypy.request + ip = self._get_ip(request) + + if self.rate_limiter.is_rate_limited(ip): + raise cherrypy.HTTPError(429, "Too Many Requests, try again later.") + + if len(args) == 1: + hash_id = args[0] + if hash_id.endswith('.png'): + hash_id = hash_id[:-4] + try: + hash_id.encode('utf-8') + except UnicodeEncodeError: + raise cherrypy.HTTPError(400, "Bad Request, invalid signature id") + qr_url = f"{host_prefix}/v/{hash_id}" + cursor = database_connection.cursor() + cursor.execute("SELECT name, time, timezone, font, invert FROM signatures WHERE hash = ?", (hash_id,)) + result = cursor.fetchone() + if result is None: + raise cherrypy.HTTPError(404, "Not Found") + name, time, timezone, font, invert = result + + timezone = datetime.timezone(datetime.timedelta(minutes=timezone)) + sig_font_path = os.path.join(static_dir, "fonts", font_data[font]) + note_font_path = os.path.join(static_dir, "fonts", "Steelfish.ttf") + + # Offload image generation to process pool + try: + sig_image = process_pool.apply( + generate_signature_image, + (name, time, timezone, qr_url, sig_font_path, note_font_path, invert) + ) + buffer = io.BytesIO() + sig_image.save(buffer, format="PNG") + buffer.seek(0) + return file_generator(buffer) + except Exception as e: + logger.error("Error generating signature image: %s", e) + raise cherrypy.HTTPError(500, "Internal Server Error") + else: + raise cherrypy.HTTPError(404, "Not Found") + + @cherrypy.expose + def howto(self): + if 'environment' in global_server_config and global_server_config['environment'] == 'production': + return self.howto_html + else: # If we are debugging, read the newest file from disk + with open(os.path.join(static_dir, "howto.html"), "r") as f: + howto_html = f.read() + return howto_html + + @cherrypy.expose + def privacy(self): + if 'environment' in global_server_config and global_server_config['environment'] == 'production': + return self.privacy_html + else: # If we are debugging, read the newest file from disk + with open(os.path.join(static_dir, "privacy.html"), "r") as f: + privacy_html = f.read() + return privacy_html + + logger.info("Starting server on %s:%s", host_ip, host_port) + cherrypy.quickstart(RootServer(), config=root_server_config) + + +if __name__ == "__main__": + socket_host = '0.0.0.0' + socket_port = 8080 + static_dir = "./web_content/" + db_path = "./data/signatures.db" + host_prefix = "osg.jkdev.org" + production = True + + if os.environ.get("DOCKER"): + host_prefix = os.environ.get("HOSTPREFIX") + production = True + + os.makedirs(os.path.dirname(db_path), exist_ok=True) + database_connection, db_lock = open_db(db_path) + + font_data = {} + for file in os.listdir(os.path.join(static_dir, "fonts")): + if file.endswith(".ttf"): + font = ttLib.TTFont(os.path.join(static_dir, "fonts", file)) + font_name = font['name'].getDebugName(4) + if font_name.endswith(' Regular'): + font_name = font_name[:-8] + font_data[font_name] = file + # Remove Steelfish from font data, we only use it for the note font + font_data.pop('Steelfish') + logger = logging.getLogger(__name__) + logger.debug("Font data: %s", font_data) + + handler = RotatingFileHandler('server.log', maxBytes=10*1024*1024, backupCount=5) + + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers = [handler] + ) + + run_server(socket_host, socket_port, host_prefix, static_dir, database_connection, db_lock, font_data, production) \ No newline at end of file diff --git a/sha_sign.py b/sha_sign.py new file mode 100644 index 0000000..284dd7f --- /dev/null +++ b/sha_sign.py @@ -0,0 +1,132 @@ +import base64 +import time +import datetime + +try: + import cryptography + import qrcode + import PIL + import pytz +except ImportError: + import pip + pip.main(['install', 'cryptography', 'qrcode', 'Pillow']) + +from cryptography.hazmat.primitives import hashes +import qrcode +from qrcode.image.styledpil import StyledPilImage +from qrcode.image.styles.moduledrawers.pil import CircleModuleDrawer +from qrcode.image.styles.colormasks import RadialGradiantColorMask +from PIL import Image, ImageDraw, ImageFont + +def hash_text(text: str) -> str: + message = text.encode('utf-8') + + hash_class = hashes.Hash(hashes.SHA256()) + + hash_class.update(message) + signature = hash_class.finalize() + + first_half = signature[:len(signature)//2] + second_half = signature[len(signature)//2:] + + xored = bytes(a ^ b for a, b in zip(first_half, second_half)) + + b64bytes = base64.b64encode(xored).replace(b'+', b'-').replace(b'/', b'_').replace(b'=', b'') + b64str = b64bytes.decode('utf-8') + + return b64str + +def generate_signature_image(sig_name: str, sig_time: int, sig_timezone: datetime.timezone, signature_url: str, sig_font_path: str, note_font_path: str, padding: int = 100, interspacing: int = 60, invert_colors: bool = False, gradient: bool = True): + start_time = time.perf_counter() + + # Create a datetime object from the sig_time and sig_timezone + sig_time = datetime.datetime.fromtimestamp(sig_time, sig_timezone) + datetime_time = time.perf_counter() + + note_text = f"Digitally Signed by\n{sig_name}\n{sig_time.strftime('%Y-%m-%d %I:%M %p')}" + + # QR code generation timing + # qr_start = time.perf_counter() + qr = qrcode.QRCode( + version=1, + error_correction=qrcode.constants.ERROR_CORRECT_L, + box_size=8, + border=0, + ) + qr.add_data(signature_url) + if invert_colors: + if gradient: + qr_img = qr.make_image(fit=True, image_factory=StyledPilImage, module_drawer=CircleModuleDrawer(), color_mask=RadialGradiantColorMask(back_color=(0, 0, 0, 128), center_color=(245, 245, 245, 255), edge_color=(250, 250, 250, 255))) + else: + qr_img = qr.make_image(fit=True, image_factory=StyledPilImage, module_drawer=CircleModuleDrawer()) + else: + if gradient: + qr_img = qr.make_image(fit=True, image_factory=StyledPilImage, module_drawer=CircleModuleDrawer(), color_mask=RadialGradiantColorMask(back_color=(255, 255, 255, 128), center_color=(10, 10, 150, 255), edge_color=(5, 5, 20, 255))) + else: + qr_img = qr.make_image(fit=True, image_factory=StyledPilImage, module_drawer=CircleModuleDrawer()) + qr_size = qr_img.pixel_size + # qr_time = time.perf_counter() + + # Text measurement timing + # text_start = time.perf_counter() + test_image = Image.new("RGBA", (2000, 1000), (0, 0, 0, 0)) + sig_font = ImageFont.truetype(sig_font_path, 350) + sans_font = ImageFont.truetype(note_font_path, 80) + draw = ImageDraw.Draw(test_image) + sig_bbox = draw.textbbox((0, 0), sig_name, font=sig_font, anchor="ls") # (left, top, right, bottom) + note_bbox = draw.multiline_textbbox((0, 0), note_text, font=sans_font, anchor="ls") # (left, top, right, bottom) + # text_measure_time = time.perf_counter() + + sig_width = sig_bbox[2] - sig_bbox[0] + sig_height = sig_bbox[3] - sig_bbox[1] + note_width = note_bbox[2] - note_bbox[0] + note_height = note_bbox[3] - note_bbox[1] + + total_image_width = padding + sig_width + interspacing + note_width + interspacing + qr_size + padding + total_image_height = padding + max(sig_height, note_height) + padding + v_anchor = total_image_height - sig_bbox[3] - padding + + if invert_colors: + sig_color = "white" + note_color = "white" + background_color = (255, 255, 255, 0) + else: + sig_color = "black" + note_color = "black" + background_color = (0, 0, 0, 0) + + image = Image.new("RGBA", (total_image_width, total_image_height), background_color) + draw = ImageDraw.Draw(image) + draw.text((padding - sig_bbox[0], v_anchor), sig_name, font=sig_font, fill=sig_color, anchor="ls") + draw.text((padding + sig_width + interspacing - note_bbox[0], v_anchor - note_bbox[3]), note_text, font=sans_font, fill=note_color, anchor="ls") + image.paste(qr_img, (padding + sig_width + interspacing + note_width + interspacing, v_anchor - qr_size)) + + # final_time = time.perf_counter() + + # # Print timing information + # print(f"Signature Image Generation Timing:") + # print(f" DateTime processing: {(datetime_time - start_time)*1000:.2f}ms") + # print(f" QR code generation: {(qr_time - qr_start)*1000:.2f}ms") + # print(f" Text measurement: {(text_measure_time - text_start)*1000:.2f}ms") + # print(f" Final image composition: {(final_time - text_measure_time)*1000:.2f}ms") + # print(f" Total time: {(final_time - start_time)*1000:.2f}ms") + + return image + + +if __name__ == "__main__": + sig_name = "Yöùr Ñamé Herê" + sig_font_path = "./web_content/fonts/HerrVonMuellerhoff.ttf" + note_font_path = "./web_content/fonts/Steelfish.ttf" + + timestamp = int(time.time()) + timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo + sig_text = f"{sig_name}{timestamp}" + + hash_id = hash_text(sig_text) + + signature_data = f"osg.jkdev.org/v/{hash_id}" + + image = generate_signature_image(sig_name, timestamp, timezone, signature_data, sig_font_path, note_font_path, invert_colors=False, gradient=True) + + image.save(f"Signature {hash_id} {timestamp}.png", optimize=True, compress_level=9) \ No newline at end of file diff --git a/web_content/example-signature-inverted.png b/web_content/example-signature-inverted.png new file mode 100644 index 0000000..e112bf8 Binary files /dev/null and b/web_content/example-signature-inverted.png differ diff --git a/web_content/example-signature.png b/web_content/example-signature.png new file mode 100644 index 0000000..b91fc7f Binary files /dev/null and b/web_content/example-signature.png differ diff --git a/web_content/favicon.ico b/web_content/favicon.ico new file mode 100644 index 0000000..757cddd Binary files /dev/null and b/web_content/favicon.ico differ diff --git a/web_content/fonts/AguafinaScript.ttf b/web_content/fonts/AguafinaScript.ttf new file mode 100644 index 0000000..8f18537 Binary files /dev/null and b/web_content/fonts/AguafinaScript.ttf differ diff --git a/web_content/fonts/Browse Fonts - Google Fonts.url b/web_content/fonts/Browse Fonts - Google Fonts.url new file mode 100644 index 0000000..6a8f7bb --- /dev/null +++ b/web_content/fonts/Browse Fonts - Google Fonts.url @@ -0,0 +1,6 @@ +[InternetShortcut] +URL=https://fonts.google.com/ +IDList= +HotKey=0 +IconFile=C:\Users\Jeremy\AppData\Local\Mozilla\Firefox\Profiles\6t1edzxq.default-release\shortcutCache\P1203vbMVqfejXjLF2mJYsLidUWdlROn4HMsI3cW9bI=.ico +IconIndex=0 diff --git a/web_content/fonts/Charm.ttf b/web_content/fonts/Charm.ttf new file mode 100644 index 0000000..02013a4 Binary files /dev/null and b/web_content/fonts/Charm.ttf differ diff --git a/web_content/fonts/DancingScript.ttf b/web_content/fonts/DancingScript.ttf new file mode 100644 index 0000000..af175f9 Binary files /dev/null and b/web_content/fonts/DancingScript.ttf differ diff --git a/web_content/fonts/HerrVonMuellerhoff.ttf b/web_content/fonts/HerrVonMuellerhoff.ttf new file mode 100644 index 0000000..3951337 Binary files /dev/null and b/web_content/fonts/HerrVonMuellerhoff.ttf differ diff --git a/web_content/fonts/LeagueScript.ttf b/web_content/fonts/LeagueScript.ttf new file mode 100644 index 0000000..15d4ef0 Binary files /dev/null and b/web_content/fonts/LeagueScript.ttf differ diff --git a/web_content/fonts/MeowScript.ttf b/web_content/fonts/MeowScript.ttf new file mode 100644 index 0000000..009b6e2 Binary files /dev/null and b/web_content/fonts/MeowScript.ttf differ diff --git a/web_content/fonts/OFL.txt b/web_content/fonts/OFL.txt new file mode 100644 index 0000000..26be973 --- /dev/null +++ b/web_content/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2010, Haley Fiege (haley@kingdomofawesome.com) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/web_content/fonts/PinyonScript.ttf b/web_content/fonts/PinyonScript.ttf new file mode 100644 index 0000000..be73d98 Binary files /dev/null and b/web_content/fonts/PinyonScript.ttf differ diff --git a/web_content/fonts/Qwigley.ttf b/web_content/fonts/Qwigley.ttf new file mode 100644 index 0000000..e4e5890 Binary files /dev/null and b/web_content/fonts/Qwigley.ttf differ diff --git a/web_content/fonts/Roboto.ttf b/web_content/fonts/Roboto.ttf new file mode 100644 index 0000000..2d116d9 Binary files /dev/null and b/web_content/fonts/Roboto.ttf differ diff --git a/web_content/fonts/Steelfish.ttf b/web_content/fonts/Steelfish.ttf new file mode 100644 index 0000000..4bf298b Binary files /dev/null and b/web_content/fonts/Steelfish.ttf differ diff --git a/web_content/fonts/StyleScript.ttf b/web_content/fonts/StyleScript.ttf new file mode 100644 index 0000000..ec4c6fa Binary files /dev/null and b/web_content/fonts/StyleScript.ttf differ diff --git a/web_content/fonts/Waterfall.ttf b/web_content/fonts/Waterfall.ttf new file mode 100644 index 0000000..99104a5 Binary files /dev/null and b/web_content/fonts/Waterfall.ttf differ diff --git a/web_content/fonts/steelfish.zip b/web_content/fonts/steelfish.zip new file mode 100644 index 0000000..17719e2 Binary files /dev/null and b/web_content/fonts/steelfish.zip differ diff --git a/web_content/howto.html b/web_content/howto.html new file mode 100644 index 0000000..a879777 --- /dev/null +++ b/web_content/howto.html @@ -0,0 +1,192 @@ + + + + How To Use - Open Signature Generator + + + + + + +
+

How To Use

+
+ +
+

Creating Your Signature

+ + +

Using Your Signature

+ + +

Verification

+ +
+ +
+ Back to Generator +
+ +
+ +
+ + + + + + \ No newline at end of file diff --git a/web_content/index.html b/web_content/index.html new file mode 100644 index 0000000..69318da --- /dev/null +++ b/web_content/index.html @@ -0,0 +1,689 @@ + + + Open Signature Generator + + + + + + +
+

+ Open Signature Generator +

+
+ +
+
+

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

+
+ +
+ Signature + +
+ + +
+
+ + + +
+ +
+
Select Font
+ +
+ + + +
+ +
+ How To Use OSG + Privacy Policy +
+ +
+ +
+ + + + + \ No newline at end of file diff --git a/web_content/privacy.html b/web_content/privacy.html new file mode 100644 index 0000000..1ca510f --- /dev/null +++ b/web_content/privacy.html @@ -0,0 +1,193 @@ + + + + Privacy Policy - Open Signature Generator + + + + + + +
+

Privacy Policy

+
+ +
+

Data Collection and Usage

+

The Open Signature Generator is designed with transparency and privacy in mind. We collect the minimum possible data necessary for operation:

+ + + +

Information Sharing

+

We do not sell, trade, transfer, or share your information with any third parties under any circumstances. Your information remains strictly confidential.

+ +

Data Security

+

We implement reasonable security measures to protect your information from unauthorized access, disclosure, alteration, or destruction. These measures include:

+ +
+ +
+ Back to Generator +
+ +
+ +
+ + + + + + \ No newline at end of file diff --git a/web_content/verification.html b/web_content/verification.html new file mode 100644 index 0000000..2177ab3 --- /dev/null +++ b/web_content/verification.html @@ -0,0 +1,280 @@ + + + Open Signature Generator + + + + + + +
+

+ Open Signature Generator +

+
+ +
+
Loading...
+ +
+
+ +
+ Go to Open Signature Generator! + + +
+ +
+ + + + + \ No newline at end of file