diff --git a/PLAN-4.1.0.md b/PLAN-4.1.0.md index 0ecaf41..5ed57d4 100644 --- a/PLAN-4.1.0.md +++ b/PLAN-4.1.0.md @@ -429,20 +429,55 @@ Or simpler: detect on startup, update schema automatically (current pattern). - [x] Channel Key QR (Web UI) - added QR generator on About page - [x] CLI Channel Commands - [x] Saved Channel Keys (Web UI) - users can save/manage channel keys -- [ ] Advanced Tools (in progress) +- [x] Advanced Tools - Image Security Toolkit + - [x] CLI: `stegasoo tools capacity/strip/peek/exif` + - [x] API: `/api/tools/capacity`, `/api/tools/peek`, `/api/tools/exif/*` + - [x] WebUI: Tools page with tabbed interface + - [x] EXIF Editor with inline editing, clear all, save/download --- -## Action Item: Architectural Review +## Architectural Improvements (4.1.0) -Review other modules for consistency with the Library → CLI → API → WebUI pattern: +### Consolidated Channel Key Resolution -| Module | Library | CLI | API | WebUI | Notes | -|--------|---------|-----|-----|-------|-------| -| encode | ✓ | ✓ | ✓ | ✓ | Review for consistency | -| decode | ✓ | ✓ | ✓ | ✓ | Review for consistency | -| channel | ✓ | ✓ | - | ✓ | Needs API layer? | -| tools | ✓ | WIP | ✓ | WIP | Building now | -| generate | ✓ | ? | - | ✓ | CLI for credential gen? | +Moved `resolve_channel_key()` from 3 duplicate implementations to single source of truth in `src/stegasoo/channel.py`: + +```python +# Library: src/stegasoo/channel.py +def resolve_channel_key(value, *, file_path=None, no_channel=False) -> str | None: + """Unified channel key resolution - returns None (auto), "" (public), or key.""" + +def get_channel_response_info(channel_key) -> dict: + """Get channel info dict for API/WebUI responses.""" +``` + +Frontends now use thin wrappers that translate exceptions to their context (Click/HTTP). + +### DCT Payload Pre-Check + +Added `will_fit_by_mode()` pre-check to WebUI encode to fail fast with helpful error message instead of cryptic exception deep in DCT processing. + +### EXIF Tools (Library Layer) + +Added to `src/stegasoo/utils.py`: +- `read_image_exif(image_data)` - Read EXIF metadata as dict +- `write_image_exif(image_data, updates)` - Update EXIF fields (JPEG only) + +Dependencies added: `piexif>=1.1.0` + +--- + +## Action Item: Architectural Review ✅ DONE + +Reviewed modules for consistency with Library → CLI → API → WebUI pattern: + +| Module | Library | CLI | API | WebUI | Status | +|--------|---------|-----|-----|-------|--------| +| encode | ✓ | ✓ | ✓ | ✓ | Consistent | +| decode | ✓ | ✓ | ✓ | ✓ | Consistent | +| channel | ✓ | ✓ | ✓ | ✓ | Consolidated resolve_channel_key | +| tools | ✓ | ✓ | ✓ | ✓ | Complete | +| generate | ✓ | ✓ | - | ✓ | CLI has `stegasoo generate` | Priority order: Developer/CLI → API integrator → WebUI end-user diff --git a/frontends/api/main.py b/frontends/api/main.py index c2a3b63..8965671 100644 --- a/frontends/api/main.py +++ b/frontends/api/main.py @@ -49,7 +49,6 @@ from stegasoo import ( generate_credentials, get_channel_status, has_argon2, - has_channel_key, has_dct_support, set_channel_key, validate_channel_key, @@ -406,11 +405,7 @@ def _resolve_channel_key(channel_key: str | None) -> str | None: """ Resolve channel key from API parameter. - Args: - channel_key: API parameter value - - None: Use server-configured key (auto mode) - - "": Public mode (no channel key) - - "XXXX-...": Explicit key + Wrapper around library's resolve_channel_key with HTTP exception handling. Returns: Resolved channel key to pass to encode/decode @@ -418,44 +413,27 @@ def _resolve_channel_key(channel_key: str | None) -> str | None: Raises: HTTPException: If key format is invalid """ - if channel_key is None: - # Auto mode - use server config - return None + from stegasoo.channel import resolve_channel_key - if channel_key == "": - # Public mode - return "" - - # Explicit key - validate format - if not validate_channel_key(channel_key): - raise HTTPException( - 400, "Invalid channel key format. Expected: XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX" - ) - - return channel_key + try: + return resolve_channel_key(channel_key) + except (ValueError, FileNotFoundError) as e: + raise HTTPException(400, str(e)) def _get_channel_info(channel_key: str | None) -> tuple[str, str | None]: """ Get channel mode and fingerprint for response. + Uses library's get_channel_response_info for consistent formatting. + Returns: (mode, fingerprint) tuple """ - if channel_key == "": - return "public", None + from stegasoo.channel import get_channel_response_info - if channel_key is not None: - # Explicit key - fingerprint = f"{channel_key[:4]}-••••-••••-••••-••••-••••-••••-{channel_key[-4:]}" - return "private", fingerprint - - # Auto mode - check server config - if has_channel_key(): - status = get_channel_status() - return "private", status.get("fingerprint") - - return "public", None + info = get_channel_response_info(channel_key) + return info["mode"], info.get("fingerprint") # ============================================================================ diff --git a/frontends/cli/main.py b/frontends/cli/main.py index b877e9f..a153405 100644 --- a/frontends/cli/main.py +++ b/frontends/cli/main.py @@ -168,37 +168,25 @@ def resolve_channel_key_option( """ Resolve channel key from CLI options. + Wrapper around library's resolve_channel_key with Click exception handling. + Returns: None: Use server-configured key (auto mode) "": Public mode (no channel key) str: Explicit channel key """ - if no_channel: - return "" # Public mode + from stegasoo.channel import resolve_channel_key - if channel_file: - # Load from file - path = Path(channel_file) - if not path.exists(): - raise click.ClickException(f"Channel key file not found: {channel_file}") - key = path.read_text().strip() - if not validate_channel_key(key): - raise click.ClickException(f"Invalid channel key format in file: {channel_file}") - return key - - if channel: - if channel.lower() == "auto": - return None # Use server config - # Explicit key provided - if not validate_channel_key(channel): - raise click.ClickException( - "Invalid channel key format. Expected: XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX\n" - "Generate a new key with: stegasoo channel generate" - ) - return channel - - # Default: use server-configured key (auto mode) - return None + try: + return resolve_channel_key( + value=channel, + file_path=channel_file, + no_channel=no_channel, + ) + except FileNotFoundError as e: + raise click.ClickException(str(e)) + except ValueError as e: + raise click.ClickException(str(e)) def format_channel_status_line(quiet: bool = False) -> str | None: diff --git a/frontends/web/app.py b/frontends/web/app.py index 7b18261..6ec0647 100644 --- a/frontends/web/app.py +++ b/frontends/web/app.py @@ -277,23 +277,22 @@ def resolve_channel_key_form(channel_key_value: str) -> str: """ Resolve channel key from form input. - Args: - channel_key_value: Form value ('auto', 'none', or explicit key) - - Returns: - Value to pass to subprocess_stego ('auto', 'none', or explicit key) + Wrapper around library's resolve_channel_key for subprocess compatibility. + Returns string values for subprocess_stego ('auto', 'none', or explicit key). """ - if not channel_key_value or channel_key_value == "auto": - return "auto" - elif channel_key_value == "none": - return "none" - else: - # Explicit key - validate format - if validate_channel_key(channel_key_value): - return channel_key_value - else: - # Invalid format, fall back to auto + from stegasoo.channel import resolve_channel_key + + try: + result = resolve_channel_key(channel_key_value) + if result is None: return "auto" + elif result == "": + return "none" + else: + return result + except (ValueError, FileNotFoundError): + # Invalid format, fall back to auto + return "auto" def generate_thumbnail(image_data: bytes, size: tuple = THUMBNAIL_SIZE) -> bytes: @@ -928,6 +927,25 @@ def encode_page(): flash(result.error_message, "error") return render_template("encode.html", has_qrcode_read=HAS_QRCODE_READ) + # Pre-check payload capacity BEFORE encode (fail fast) + from stegasoo.steganography import will_fit_by_mode + + payload_size = len(payload.data) if hasattr(payload, "data") else len(payload.encode("utf-8")) + fit_check = will_fit_by_mode(payload_size, carrier_data, embed_mode=embed_mode) + if not fit_check.get("fits", True): + error_msg = ( + f"Payload too large for {embed_mode.upper()} mode. " + f"Payload: {payload_size:,} bytes, " + f"Capacity: {fit_check.get('capacity', 0):,} bytes" + ) + # Suggest alternative mode + if embed_mode == "dct": + alt_check = will_fit_by_mode(payload_size, carrier_data, embed_mode="lsb") + if alt_check.get("fits"): + error_msg += " - Try LSB mode instead." + flash(error_msg, "error") + return render_template("encode.html", has_qrcode_read=HAS_QRCODE_READ) + # v4.0.0: Include channel_key parameter # Use subprocess-isolated encode to prevent crashes if payload_type == "file" and payload_file and payload_file.filename: @@ -1370,6 +1388,109 @@ def api_tools_peek(): return jsonify({"success": False, "error": str(e)}), 400 +@app.route("/api/tools/exif", methods=["POST"]) +@login_required +def api_tools_exif(): + """Read EXIF metadata from image.""" + from stegasoo.utils import read_image_exif + + image_file = request.files.get("image") + if not image_file: + return jsonify({"success": False, "error": "No image provided"}), 400 + + try: + image_data = image_file.read() + exif = read_image_exif(image_data) + + # Check if it's a JPEG (editable) or not + is_jpeg = image_data[:2] == b"\xff\xd8" + + return jsonify({ + "success": True, + "filename": image_file.filename, + "exif": exif, + "editable": is_jpeg, + "field_count": len(exif), + }) + except Exception as e: + return jsonify({"success": False, "error": str(e)}), 400 + + +@app.route("/api/tools/exif/update", methods=["POST"]) +@login_required +def api_tools_exif_update(): + """Update EXIF fields in image.""" + from stegasoo.utils import write_image_exif + + image_file = request.files.get("image") + if not image_file: + return jsonify({"success": False, "error": "No image provided"}), 400 + + # Get updates from form data + updates_json = request.form.get("updates", "{}") + try: + import json + updates = json.loads(updates_json) + except json.JSONDecodeError: + return jsonify({"success": False, "error": "Invalid updates JSON"}), 400 + + if not updates: + return jsonify({"success": False, "error": "No updates provided"}), 400 + + try: + image_data = image_file.read() + updated_data = write_image_exif(image_data, updates) + + # Return as downloadable file + buffer = io.BytesIO(updated_data) + return send_file( + buffer, + mimetype="image/jpeg", + as_attachment=True, + download_name=f"exif_{image_file.filename}", + ) + except ValueError as e: + return jsonify({"success": False, "error": str(e)}), 400 + except Exception as e: + return jsonify({"success": False, "error": str(e)}), 500 + + +@app.route("/api/tools/exif/clear", methods=["POST"]) +@login_required +def api_tools_exif_clear(): + """Remove all EXIF metadata from image.""" + from stegasoo.utils import strip_image_metadata + + image_file = request.files.get("image") + if not image_file: + return jsonify({"success": False, "error": "No image provided"}), 400 + + # Get desired output format (default to PNG for lossless) + output_format = request.form.get("format", "PNG").upper() + if output_format not in ("PNG", "JPEG", "BMP"): + output_format = "PNG" + + try: + image_data = image_file.read() + clean_data = strip_image_metadata(image_data, output_format=output_format) + + # Determine extension and mimetype + ext_map = {"PNG": ("png", "image/png"), "JPEG": ("jpg", "image/jpeg"), "BMP": ("bmp", "image/bmp")} + ext, mimetype = ext_map.get(output_format, ("png", "image/png")) + + # Return as downloadable file + stem = image_file.filename.rsplit(".", 1)[0] if "." in image_file.filename else image_file.filename + buffer = io.BytesIO(clean_data) + return send_file( + buffer, + mimetype=mimetype, + as_attachment=True, + download_name=f"{stem}_clean.{ext}", + ) + except Exception as e: + return jsonify({"success": False, "error": str(e)}), 500 + + # Add these two test routes anywhere in app.py after the app = Flask(...) line: diff --git a/frontends/web/templates/tools.html b/frontends/web/templates/tools.html index 0944b19..6f0383d 100644 --- a/frontends/web/templates/tools.html +++ b/frontends/web/templates/tools.html @@ -4,7 +4,7 @@ {% block content %}
Remove metadata (camera info, GPS, timestamps) from images.
+View, edit, or remove image metadata (EXIF, GPS, camera info).
-