Compare commits
50 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c88f53cd0 | ||
|
|
3f8c2a6957 | ||
|
|
22cf27d7f6 | ||
|
|
4d8575ce33 | ||
|
|
28b539bcd9 | ||
|
|
6b82069dc8 | ||
|
|
52e1a3dfbf | ||
|
|
4a27d0c182 | ||
|
|
36931518ce | ||
|
|
f79c63428b | ||
|
|
cc29de4200 | ||
|
|
c14f3f75cb | ||
|
|
aa99a258f4 | ||
|
|
93420704e8 | ||
|
|
6e4eb5464e | ||
|
|
d04670e352 | ||
|
|
fda1cdad51 | ||
|
|
b48ccc5d16 | ||
|
|
15ed63cafa | ||
|
|
869d7ee8e3 | ||
|
|
3ee8c1d22a | ||
|
|
b96564358a | ||
|
|
01afb3da66 | ||
|
|
a98df5f9a0 | ||
|
|
70da348bce | ||
|
|
90ba8543a7 | ||
|
|
da3aea992c | ||
|
|
ae47ff4932 | ||
|
|
eb16eb1db2 | ||
|
|
c65d9e6682 | ||
|
|
eeb44eae94 | ||
|
|
26d4b82c91 | ||
|
|
7efeaf02e8 | ||
|
|
925fb05cbd | ||
|
|
29a02265a1 | ||
|
|
d58f3c6fb6 | ||
|
|
cc46993d80 | ||
|
|
893a044eaa | ||
|
|
9f03b69408 | ||
|
|
cce2007c6e | ||
|
|
52f43d3a86 | ||
|
|
85a7092d55 | ||
|
|
4b37a81087 | ||
|
|
31941dc3f5 | ||
|
|
9a7e4ddce7 | ||
|
|
0424dd34d5 | ||
|
|
2127b916f3 | ||
|
|
f8e65890e5 | ||
|
|
5861ab0e1e | ||
|
|
5309a08aaf |
9
.gitignore
vendored
9
.gitignore
vendored
@@ -69,6 +69,7 @@ scripts/*
|
||||
!scripts/validate-release.sh
|
||||
|
||||
# Web UI auth database and SSL certs
|
||||
instance/
|
||||
frontends/web/instance/
|
||||
frontends/web/certs/
|
||||
|
||||
@@ -84,3 +85,11 @@ pishrink.sh
|
||||
|
||||
# Temp file storage
|
||||
frontends/web/temp_files/
|
||||
rpi/config.json
|
||||
|
||||
# Pre-built Pi tarballs and images (release assets, too large for git)
|
||||
rpi/*.tar.zst
|
||||
rpi/*.tar.zst.zip
|
||||
rpi/*.img
|
||||
rpi/*.img.zst
|
||||
rpi/*.img.zst.zip
|
||||
|
||||
22
CHANGELOG.md
22
CHANGELOG.md
@@ -5,6 +5,27 @@ All notable changes to Stegasoo will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org).
|
||||
|
||||
## [4.1.5] - 2026-01-07
|
||||
|
||||
### Added
|
||||
- **Developer Documentation**: Educational comments throughout core modules
|
||||
- DCT module: zig-zag diagrams, QIM explanation, Reed-Solomon deep dive
|
||||
- LSB module: visual bit embedding examples, ChaCha20 pixel selection
|
||||
- Crypto module: multi-factor KDF flow diagrams, Argon2id reasoning
|
||||
- CLI module: Click patterns (groups, JSON output, secure input)
|
||||
- Web UI module: Flask architecture, subprocess isolation, async jobs
|
||||
- **Pi Test Automation**: `rpi/kickoff-pi-test.sh` script
|
||||
- One command to flash, wait for boot, setup, and smoke test
|
||||
- Self-contained (no dotfile dependencies)
|
||||
- **v4.2 Wishlist**: `WISHLIST-4.2.md` for blue-sky ideas (GPU acceleration)
|
||||
|
||||
### Changed
|
||||
- **Pi MOTD Improvements**:
|
||||
- Dynamic temperature emoji (ice/cool/fire based on temp)
|
||||
- Rocket emoji for service status, globe emoji for URL
|
||||
- Shortened Debian boilerplate message
|
||||
- Fixed escaped variable syntax in heredoc
|
||||
|
||||
## [4.1.3] - 2026-01-05
|
||||
|
||||
### Added
|
||||
@@ -180,6 +201,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
|
||||
- CLI interface
|
||||
- Basic PIN authentication
|
||||
|
||||
[4.1.5]: https://github.com/adlee-was-taken/stegasoo/compare/v4.1.3...v4.1.5
|
||||
[4.1.3]: https://github.com/adlee-was-taken/stegasoo/compare/v4.1.0...v4.1.3
|
||||
[4.1.0]: https://github.com/adlee-was-taken/stegasoo/compare/v4.0.2...v4.1.0
|
||||
[4.0.2]: https://github.com/adlee-was-taken/stegasoo/compare/v4.0.1...v4.0.2
|
||||
|
||||
@@ -6,7 +6,7 @@ Thank you for your interest in contributing to Stegasoo! This document provides
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Python 3.10 or higher
|
||||
- Python 3.10 - 3.12
|
||||
- Git
|
||||
- Docker (optional, for container testing)
|
||||
|
||||
|
||||
538
PLAN-4.1.0.md
538
PLAN-4.1.0.md
@@ -1,538 +0,0 @@
|
||||
# Stegasoo 4.1.0 Plan
|
||||
|
||||
## Overview
|
||||
|
||||
Version 4.1.0 is a feature release focusing on small-group deployment improvements and new utilities.
|
||||
|
||||
## Goals
|
||||
|
||||
1. ~~**Multi-User Support** - Admin can create up to 16 users for shared deployments~~ ✅ DONE
|
||||
2. **Channel Key QR** - Easy visual sharing of channel keys via QR codes
|
||||
3. ~~**CLI Channel Commands** - Manage channel keys from command line~~ ✅ DONE
|
||||
4. **Advanced Tools** - Image/stego utilities (TBD)
|
||||
|
||||
---
|
||||
|
||||
## Feature 1: Multi-User Support ✅ COMPLETED
|
||||
|
||||
> Implemented in commit 7b33501. All requirements met.
|
||||
|
||||
### Requirements
|
||||
|
||||
- 16 users + 1 admin maximum (17 total)
|
||||
- First user created at setup is always admin
|
||||
- Admin can add/delete users, reset passwords
|
||||
- Regular users can only change their own password
|
||||
- No self-registration (admin-invite only)
|
||||
|
||||
### Database Changes
|
||||
|
||||
**Update User model in `frontends/web/models.py`:**
|
||||
|
||||
```python
|
||||
class User(db.Model):
|
||||
id = Column(Integer, primary_key=True)
|
||||
username = Column(String(80), unique=True, nullable=False)
|
||||
password_hash = Column(String(255), nullable=False)
|
||||
role = Column(String(20), default='user') # 'admin' or 'user'
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
```
|
||||
|
||||
**Migration:** Add `role` and `created_at` columns. Existing users get `role='admin'`.
|
||||
|
||||
### New Routes
|
||||
|
||||
| Route | Method | Access | Description |
|
||||
|-------|--------|--------|-------------|
|
||||
| `/admin/users` | GET | admin | List all users |
|
||||
| `/admin/users/new` | GET, POST | admin | Create user form |
|
||||
| `/admin/users/<id>/delete` | POST | admin | Delete user |
|
||||
| `/admin/users/<id>/reset-password` | POST | admin | Generate temp password |
|
||||
|
||||
### New Decorator
|
||||
|
||||
```python
|
||||
# auth.py
|
||||
def admin_required(f):
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
if not current_user.is_authenticated:
|
||||
return redirect(url_for('login'))
|
||||
if current_user.role != 'admin':
|
||||
flash('Admin access required', 'error')
|
||||
return redirect(url_for('index'))
|
||||
return f(*args, **kwargs)
|
||||
return decorated
|
||||
```
|
||||
|
||||
### UI Changes
|
||||
|
||||
**Navigation (for admin users):**
|
||||
- Add "Users" link in navbar (visible only to admin)
|
||||
|
||||
**Account page (`/account`):**
|
||||
- Admin sees link to user management
|
||||
- All users see their own password change form
|
||||
|
||||
**New template: `templates/admin/users.html`:**
|
||||
- Table: Username | Role | Created | Actions
|
||||
- Actions: Reset Password, Delete (disabled for self)
|
||||
- "Add User" button (disabled if at 16 user limit)
|
||||
- Show count: "3 of 16 users"
|
||||
|
||||
**New template: `templates/admin/user_new.html`:**
|
||||
- Username field (email-style allowed)
|
||||
- Password field (auto-populated with random 8-char, admin can override)
|
||||
- Submit → confirmation page shows password once with copy button
|
||||
|
||||
### Validation
|
||||
|
||||
- Username: 3-80 chars, alphanumeric + underscore/hyphen + @/. for email-style
|
||||
- Password: 8+ chars (same as current)
|
||||
- Can't delete yourself
|
||||
- Can't demote the last admin
|
||||
- Deleting user immediately invalidates their sessions
|
||||
|
||||
---
|
||||
|
||||
## Feature 2: Channel Key QR
|
||||
|
||||
### Web UI
|
||||
|
||||
**About page additions:**
|
||||
|
||||
If `STEGASOO_CHANNEL_KEY` environment variable is set:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Channel Key │
|
||||
│ │
|
||||
│ ██████████████ Your server uses a │
|
||||
│ ██ ██ private channel key. │
|
||||
│ ██ ██████ ██ Share this QR with │
|
||||
│ ██ ██████ ██ others to join. │
|
||||
│ ██ ██ │
|
||||
│ ██████████████ [Copy Key] [Download]│
|
||||
│ │
|
||||
│ Key: abc123...xyz │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- QR generated server-side using `qrcode` library
|
||||
- "Copy Key" copies text to clipboard
|
||||
- "Download QR" saves as PNG
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```python
|
||||
# about route addition
|
||||
@app.route('/about')
|
||||
def about():
|
||||
channel_key = os.environ.get('STEGASOO_CHANNEL_KEY', '')
|
||||
channel_qr_b64 = None
|
||||
if channel_key:
|
||||
# Generate QR as base64 PNG
|
||||
qr = qrcode.make(channel_key)
|
||||
buffer = BytesIO()
|
||||
qr.save(buffer, format='PNG')
|
||||
channel_qr_b64 = base64.b64encode(buffer.getvalue()).decode()
|
||||
return render_template('about.html',
|
||||
channel_key=channel_key,
|
||||
channel_qr=channel_qr_b64)
|
||||
```
|
||||
|
||||
### CLI Commands
|
||||
|
||||
**New command group: `stegasoo channel`**
|
||||
|
||||
```bash
|
||||
# Generate a new channel key
|
||||
stegasoo channel generate
|
||||
# Output:
|
||||
# Channel Key: stg_abc123...xyz789
|
||||
#
|
||||
# ██████████████████
|
||||
# ██ ██
|
||||
# ██ ██████████ ██
|
||||
# ...
|
||||
#
|
||||
# Set in environment: export STEGASOO_CHANNEL_KEY="stg_abc123..."
|
||||
|
||||
# Show current key (from env or argument)
|
||||
stegasoo channel show
|
||||
# Output:
|
||||
# Channel Key: stg_abc123...xyz789
|
||||
|
||||
# Display QR in terminal (ASCII)
|
||||
stegasoo channel qr
|
||||
# Output: ASCII QR code
|
||||
|
||||
# Save QR as PNG
|
||||
stegasoo channel qr -o channel-key.png
|
||||
# Output: Saved to channel-key.png
|
||||
|
||||
# Explicit format selection
|
||||
stegasoo channel qr --format ascii # Terminal (default)
|
||||
stegasoo channel qr --format png -o - # PNG to stdout
|
||||
```
|
||||
|
||||
**Implementation notes:**
|
||||
|
||||
- Use `qrcode[pil]` for PNG output
|
||||
- Use `qrcode` with `print_ascii()` for terminal
|
||||
- Read key from `--key` argument or `STEGASOO_CHANNEL_KEY` env var
|
||||
- `generate` uses existing `generate_channel_key()` from `stegasoo.channel`
|
||||
|
||||
---
|
||||
|
||||
## File Changes Summary
|
||||
|
||||
### New Files
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `frontends/web/templates/admin/users.html` | User management page |
|
||||
| `frontends/web/templates/admin/user_new.html` | Add user form |
|
||||
|
||||
### Modified Files
|
||||
|
||||
| File | Changes |
|
||||
|------|---------|
|
||||
| `frontends/web/models.py` | Add `role`, `created_at` to User |
|
||||
| `frontends/web/auth.py` | Add `@admin_required`, user management routes |
|
||||
| `frontends/web/templates/base.html` | Add Users link for admins |
|
||||
| `frontends/web/templates/account.html` | Add admin link |
|
||||
| `frontends/web/templates/about.html` | Add channel key QR section |
|
||||
| `src/stegasoo/cli.py` | Add `channel` command group |
|
||||
|
||||
---
|
||||
|
||||
## Testing Plan
|
||||
|
||||
### Multi-User
|
||||
|
||||
1. Fresh install → first user is admin
|
||||
2. Admin can create users up to limit (16)
|
||||
3. Admin can't create 17th user (shows error)
|
||||
4. Regular user can log in, encode/decode
|
||||
5. Regular user can't access `/admin/users`
|
||||
6. Admin can reset user password
|
||||
7. Admin can delete user
|
||||
8. Admin can't delete self
|
||||
9. Existing 4.0.2 databases upgrade correctly (single user becomes admin)
|
||||
|
||||
### Channel Key QR
|
||||
|
||||
1. About page shows nothing if no channel key
|
||||
2. About page shows QR + key if channel key set
|
||||
3. Copy button works
|
||||
4. Download gives valid PNG
|
||||
5. QR scans correctly to key value
|
||||
|
||||
### CLI
|
||||
|
||||
1. `channel generate` creates valid key + shows QR
|
||||
2. `channel show` displays current key
|
||||
3. `channel qr` outputs ASCII to terminal
|
||||
4. `channel qr -o file.png` saves PNG
|
||||
5. Commands work with `--key` override
|
||||
6. Commands read from env var
|
||||
|
||||
---
|
||||
|
||||
## Feature 3: Advanced Tools
|
||||
|
||||
### Included Tools
|
||||
|
||||
| Tool | Web | CLI | Description |
|
||||
|------|-----|-----|-------------|
|
||||
| **Capacity Calculator** | ✓ | ✓ | Upload image → show DCT/LSB capacity |
|
||||
| **Metadata Stripper** | ✓ | ✓ | Remove EXIF/metadata from image |
|
||||
| **Stego Detector** | ✓ | ✓ | Analyze image for signs of hidden data |
|
||||
| **Image Compare** | ✓ | - | Side-by-side before/after diff |
|
||||
| **Header Peek** | ✓ | ✓ | Check for Stegasoo header without decrypting |
|
||||
| **Batch Mode** | - | ✓ | Encode/decode multiple files |
|
||||
|
||||
### Web UI: `/tools` Page
|
||||
|
||||
New page with card-based layout:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 🛠️ Advanced Tools │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌─────────────────┐ ┌─────────────────┐ │
|
||||
│ │ 📏 Capacity │ │ 🧹 Metadata │ │
|
||||
│ │ Calculator │ │ Stripper │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ Check how much │ │ Remove EXIF │ │
|
||||
│ │ data fits │ │ before encoding │ │
|
||||
│ └─────────────────┘ └─────────────────┘ │
|
||||
│ │
|
||||
│ ┌─────────────────┐ ┌─────────────────┐ │
|
||||
│ │ 🔍 Stego │ │ 🔎 Header │ │
|
||||
│ │ Detector │ │ Peek │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ Analyze image │ │ Check for │ │
|
||||
│ │ for hidden data │ │ Stegasoo data │ │
|
||||
│ └─────────────────┘ └─────────────────┘ │
|
||||
│ │
|
||||
│ ┌─────────────────┐ │
|
||||
│ │ ⚖️ Image │ │
|
||||
│ │ Compare │ │
|
||||
│ │ │ │
|
||||
│ │ Before/after │ │
|
||||
│ │ diff view │ │
|
||||
│ └─────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Each card opens a modal or expands inline for the tool interface.
|
||||
|
||||
### CLI Structure
|
||||
|
||||
```bash
|
||||
# Capacity calculator
|
||||
stegasoo capacity image.jpg
|
||||
stegasoo capacity image.jpg --format json
|
||||
|
||||
# Metadata stripper
|
||||
stegasoo strip image.jpg # Output to image_stripped.jpg
|
||||
stegasoo strip image.jpg -o clean.jpg # Custom output
|
||||
stegasoo strip image.jpg --in-place # Overwrite original
|
||||
|
||||
# Stego detector
|
||||
stegasoo detect image.jpg
|
||||
stegasoo detect image.jpg --verbose # Detailed analysis
|
||||
|
||||
# Header peek
|
||||
stegasoo peek image.jpg
|
||||
# Output: "Stegasoo DCT header detected" or "No Stegasoo header found"
|
||||
|
||||
# Batch mode
|
||||
stegasoo encode --batch manifest.json # JSON with files + credentials
|
||||
stegasoo decode --batch input_dir/ --out output_dir/
|
||||
```
|
||||
|
||||
### Tool Details
|
||||
|
||||
#### Capacity Calculator
|
||||
- Input: Image file
|
||||
- Output: Dimensions, megapixels, DCT capacity, LSB capacity
|
||||
- Web: Upload zone + results panel
|
||||
- CLI: Table or JSON output
|
||||
|
||||
#### Metadata Stripper
|
||||
- Input: Image file
|
||||
- Output: Clean image (EXIF/metadata removed)
|
||||
- Show what was removed (camera model, GPS, etc.)
|
||||
- Preserve image quality
|
||||
|
||||
#### Stego Detector
|
||||
- Input: Image file
|
||||
- Analysis:
|
||||
- Chi-square analysis (LSB detection)
|
||||
- DCT coefficient histogram analysis
|
||||
- Visual inspection hints
|
||||
- Output: Likelihood score + findings
|
||||
- Note: Detection is probabilistic, not definitive
|
||||
|
||||
#### Image Compare
|
||||
- Input: Two images (original + stego)
|
||||
- Output:
|
||||
- Side-by-side view
|
||||
- Difference overlay (amplified)
|
||||
- Pixel-level stats (PSNR, SSIM)
|
||||
- Web only (visual tool)
|
||||
|
||||
#### Header Peek
|
||||
- Input: Image file
|
||||
- Output: Header found (yes/no), mode (DCT/LSB), embedded size estimate
|
||||
- Does NOT decrypt - just checks for valid header structure
|
||||
- Useful for "is this a stego image?" without credentials
|
||||
|
||||
#### Batch Mode
|
||||
- CLI only
|
||||
- Manifest file (JSON) or directory-based
|
||||
- Progress bar for multiple files
|
||||
- Error handling per-file (continue on failure)
|
||||
|
||||
---
|
||||
|
||||
## Migration Notes
|
||||
|
||||
### Database Migration
|
||||
|
||||
For existing 4.0.2 installations:
|
||||
|
||||
```python
|
||||
# migrations/add_user_role.py
|
||||
def upgrade():
|
||||
# Add columns with defaults
|
||||
op.add_column('user', sa.Column('role', sa.String(20), default='user'))
|
||||
op.add_column('user', sa.Column('created_at', sa.DateTime))
|
||||
|
||||
# Set existing users as admin (they were the first user)
|
||||
op.execute("UPDATE user SET role = 'admin' WHERE role IS NULL")
|
||||
op.execute("UPDATE user SET created_at = datetime('now') WHERE created_at IS NULL")
|
||||
```
|
||||
|
||||
Or simpler: detect on startup, update schema automatically (current pattern).
|
||||
|
||||
---
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Per-user channel keys
|
||||
- User groups/teams
|
||||
- API authentication tokens
|
||||
- User activity logging
|
||||
- Password complexity rules beyond length
|
||||
|
||||
---
|
||||
|
||||
## Estimated Effort
|
||||
|
||||
| Component | Complexity |
|
||||
|-----------|------------|
|
||||
| Database schema change | Low |
|
||||
| Admin routes + templates | Medium |
|
||||
| Access control decorator | Low |
|
||||
| About page QR | Low |
|
||||
| CLI channel commands | Medium |
|
||||
| Advanced Tools (TBD) | Medium-High |
|
||||
| Testing | Medium |
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **Temp password flow:** Password field auto-populates with random 8-char password. Admin can override if desired. Show password once on confirmation page.
|
||||
|
||||
2. **Session handling:** Yes - deleting a user immediately invalidates their active sessions (ban hammer).
|
||||
|
||||
3. **Username rules:** Sane requirements, email-style allowed. Validation: 3-80 chars, alphanumeric, underscore, hyphen, @ and . for email-style.
|
||||
|
||||
---
|
||||
|
||||
## Approval
|
||||
|
||||
- [x] Plan reviewed
|
||||
- [x] Questions resolved
|
||||
- [x] Ready to implement
|
||||
|
||||
## Progress
|
||||
|
||||
- [x] Multi-User Support (commit 7b33501)
|
||||
- [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
|
||||
- [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
|
||||
|
||||
---
|
||||
|
||||
## Architectural Improvements (4.1.0)
|
||||
|
||||
### Consolidated Channel Key Resolution
|
||||
|
||||
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
|
||||
|
||||
---
|
||||
|
||||
## Admin Recovery System (4.1.0) ✅ DONE
|
||||
|
||||
Password reset capability for locked-out admins with multiple backup options.
|
||||
|
||||
### Library Layer (`src/stegasoo/recovery.py`)
|
||||
|
||||
```python
|
||||
# Key generation and validation
|
||||
generate_recovery_key() -> str # XXXX-XXXX-XXXX-... (32 chars)
|
||||
hash_recovery_key(key) -> str # SHA-256 for storage
|
||||
verify_recovery_key(key, hash) -> bool
|
||||
|
||||
# QR code (obfuscated - scans as gibberish)
|
||||
obfuscate_key(key) -> str # XOR with RECOVERY_OBFUSCATION_KEY
|
||||
deobfuscate_key(data) -> str | None
|
||||
generate_recovery_qr(key) -> bytes # PNG with obfuscated data
|
||||
extract_key_from_qr(image) -> str | None
|
||||
|
||||
# Stego backup (hide key in an image)
|
||||
create_stego_backup(key, carrier_image) -> bytes
|
||||
extract_stego_backup(stego_image, reference) -> str | None
|
||||
```
|
||||
|
||||
### Database (`app_settings` table)
|
||||
|
||||
- `recovery_key_hash` - SHA-256 of recovery key (or null if disabled)
|
||||
|
||||
### Web Routes
|
||||
|
||||
| Route | Method | Description |
|
||||
|-------|--------|-------------|
|
||||
| `/setup/recovery` | GET, POST | Step 2 of initial setup |
|
||||
| `/recover` | GET, POST | Password reset page |
|
||||
| `/recover/stego` | POST | Extract key from stego backup |
|
||||
| `/account/recovery/regenerate` | GET, POST | Generate new key |
|
||||
| `/account/recovery/disable` | POST | Remove recovery option |
|
||||
| `/account/recovery/stego-backup` | POST | Create stego backup |
|
||||
|
||||
### CLI Commands
|
||||
|
||||
```bash
|
||||
stegasoo admin recover --db path/to/stegasoo.db # Reset password
|
||||
stegasoo admin generate-key [--qr] # Generate key (reference)
|
||||
```
|
||||
|
||||
### Security Model
|
||||
|
||||
1. Recovery key shown once during setup - only hash stored
|
||||
2. QR codes XOR'd with `RECOVERY_OBFUSCATION_KEY` (fixed in constants.py)
|
||||
3. Stego backups use fixed internal passphrase/PIN - security is obscurity
|
||||
4. Instance-bound: recovery key hash must match in target database
|
||||
5. Options: text file, QR image, stego image, or no recovery (most secure)
|
||||
250
PLAN-4.1.2.md
250
PLAN-4.1.2.md
@@ -1,250 +0,0 @@
|
||||
# Stegasoo 4.1.2 Plan
|
||||
|
||||
## Release Theme
|
||||
Polish and UX improvements after the 4.1.1 stability release.
|
||||
|
||||
---
|
||||
|
||||
## 1. Real Progress Bar for Encode/Decode
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** Users see elapsed time but no indication of how far along the operation is. Long DCT encodes on Pi can take 2-3 minutes with no feedback.
|
||||
|
||||
**Solution:** Polling + progress file approach
|
||||
|
||||
### Backend Changes
|
||||
|
||||
1. **dct_steganography.py** - Write progress during block loop:
|
||||
```python
|
||||
if progress_file and block_num % 50 == 0:
|
||||
with open(progress_file, 'w') as f:
|
||||
json.dump({"current": block_num, "total": total_blocks, "phase": "embedding"}, f)
|
||||
```
|
||||
|
||||
2. **app.py** - New endpoints:
|
||||
- `POST /encode` returns `job_id`, starts subprocess
|
||||
- `GET /encode/progress/<job_id>` returns progress JSON
|
||||
- `GET /encode/result/<job_id>` returns final result when done
|
||||
|
||||
3. **Subprocess wrapper** - Pass progress file path to encode/decode functions
|
||||
|
||||
### Frontend Changes
|
||||
|
||||
1. **stegasoo.js** - After form submit:
|
||||
- Show progress bar (Bootstrap progress component)
|
||||
- Poll `/encode/progress/{job_id}` every 500ms
|
||||
- Update bar width and percentage text
|
||||
- Show phase (hashing, embedding, encoding, etc.)
|
||||
|
||||
2. **Templates** - Add progress bar markup to encode.html and decode.html
|
||||
|
||||
### Files to Modify
|
||||
- `src/stegasoo/dct_steganography.py`
|
||||
- `frontends/web/app.py`
|
||||
- `frontends/web/static/js/stegasoo.js`
|
||||
- `frontends/web/templates/encode.html`
|
||||
- `frontends/web/templates/decode.html`
|
||||
|
||||
---
|
||||
|
||||
## 2. Granular Decode Error Messages
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** Decode failures show generic "Decryption failed" - users don't know if it's wrong photo, wrong passphrase, wrong PIN, corrupted image, or format mismatch.
|
||||
|
||||
**Solution:** Bubble up specific error types from library to UI
|
||||
|
||||
### Implementation
|
||||
- Added new exceptions: InvalidMagicBytesError, ReedSolomonError, NoDataFoundError, ModeMismatchError
|
||||
- DCT decode now raises InvalidMagicBytesError for wrong magic bytes
|
||||
- DCT decode now raises ReedSolomonError (renamed from reedsolo's) for corruption
|
||||
- app.py catches specific exceptions with user-friendly messages:
|
||||
- Invalid magic → "Try a different mode (LSB/DCT)"
|
||||
- RS error → "Image too corrupted, may have been re-saved"
|
||||
- Invalid header → "Image may have been modified"
|
||||
- Decryption error → "Wrong credentials"
|
||||
|
||||
### Files Modified
|
||||
- `src/stegasoo/exceptions.py` (new exceptions)
|
||||
- `src/stegasoo/__init__.py` (exports)
|
||||
- `src/stegasoo/dct_steganography.py` (raise specific exceptions)
|
||||
- `frontends/web/app.py` (catch and display)
|
||||
|
||||
---
|
||||
|
||||
## 3. Mobile-Responsive Polish
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** UI works on mobile but has rough edges - cramped buttons, hard-to-tap targets, awkward layouts on small screens.
|
||||
|
||||
**Solution:** Targeted CSS/layout fixes for mobile breakpoints
|
||||
|
||||
### Areas to Improve
|
||||
|
||||
1. **Encode/Decode Forms:**
|
||||
- Stack image drop zones vertically on mobile (currently side-by-side)
|
||||
- Larger touch targets for file inputs
|
||||
- Full-width buttons on small screens
|
||||
- Passphrase input readable at smaller sizes
|
||||
|
||||
2. **Navigation:**
|
||||
- Hamburger menu for mobile navbar (if not already)
|
||||
- Sticky header doesn't eat too much screen
|
||||
- Easy thumb reach for main actions
|
||||
|
||||
3. **Results/Output:**
|
||||
- Download buttons full-width on mobile
|
||||
- QR codes sized appropriately
|
||||
- Click-to-copy message box works well with touch
|
||||
|
||||
4. **Drop Zones:**
|
||||
- Larger tap targets
|
||||
- Visual feedback for touch (not just hover)
|
||||
- Camera integration hint on mobile ("Tap to take photo or choose file")
|
||||
|
||||
### Testing Targets
|
||||
- iPhone SE (small)
|
||||
- iPhone 14 (medium)
|
||||
- iPad (tablet)
|
||||
- Android Chrome
|
||||
|
||||
### Files to Modify
|
||||
- `frontends/web/static/css/style.css` (or new mobile.css)
|
||||
- `frontends/web/templates/encode.html`
|
||||
- `frontends/web/templates/decode.html`
|
||||
- `frontends/web/templates/base.html` (navbar)
|
||||
|
||||
---
|
||||
|
||||
## Testing Checklist
|
||||
|
||||
- [ ] Progress bar works on localhost
|
||||
- [ ] Progress bar works on Pi (slower, more visible)
|
||||
- [ ] Cancellation handling (what if user navigates away?)
|
||||
- [ ] Error states display correctly
|
||||
- [ ] Smoke test passes
|
||||
|
||||
---
|
||||
|
||||
## 4. Forced First-Login Setup
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** Users can navigate the app without creating an admin account first. Should force password setup before anything else.
|
||||
|
||||
**Solution:** Middleware/decorator that redirects to setup page if no users exist.
|
||||
|
||||
### Implementation
|
||||
- Added `@app.before_request` hook that redirects to /setup if no users exist
|
||||
- Skips redirect for static files and setup-related routes
|
||||
|
||||
### Files Modified
|
||||
- `frontends/web/app.py` (added require_setup before_request hook)
|
||||
|
||||
---
|
||||
|
||||
## 5. Dropzone UX Fixes
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** Dropzone has some interaction bugs:
|
||||
- Dropzone doesn't clear properly if first QR image fails
|
||||
- Can't click on image preview to replace file (have to click surrounding border)
|
||||
|
||||
**Solution:** Fix JS event handling and state management
|
||||
|
||||
### Implementation
|
||||
- Added click handler on preview images to trigger file input
|
||||
- Made entire drop zone clickable (not just label)
|
||||
- QR zone now resets after 2 seconds on error, allowing retry
|
||||
- Clear file input on QR error so same file can be re-selected
|
||||
|
||||
### Files Modified
|
||||
- `frontends/web/static/js/stegasoo.js`
|
||||
|
||||
---
|
||||
|
||||
## 6. Smoke Test Benchmarking
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** No way to measure encode/decode performance or track regressions.
|
||||
|
||||
**Solution:** Add timing to smoke tests using `hyperfine` or `time`.
|
||||
|
||||
### Implementation
|
||||
- Added `--benchmark` flag to run encode/decode benchmarks after tests
|
||||
- Added `--runs=N` flag to customize number of benchmark runs (default: 5)
|
||||
- Uses hyperfine if available for precise timing with warmup
|
||||
- Falls back to manual timing with bc if hyperfine not installed
|
||||
- Outputs min/max/avg stats for both encode and decode operations
|
||||
|
||||
### Files Modified
|
||||
- `tests/smoke-test.sh`
|
||||
|
||||
---
|
||||
|
||||
## 7. Docker Cleanup
|
||||
|
||||
**Status:** Done (4.1.1)
|
||||
|
||||
**Problem:** Docker build context is larger than needed (includes test images, rpi scripts, etc.)
|
||||
|
||||
**Solution:** Added `.dockerignore` and fixed volume permissions in Dockerfile
|
||||
|
||||
### Files Modified
|
||||
- `.dockerignore` (created)
|
||||
- `Dockerfile` (instance dir permissions)
|
||||
|
||||
---
|
||||
|
||||
## 8. Release Validation Script
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** Manual release checklist is error-prone. Need automated validation.
|
||||
|
||||
**Solution:** Script that runs through testable checklist items
|
||||
|
||||
### Features
|
||||
- Run pytest
|
||||
- Build and test Docker image
|
||||
- SSH to Pi and run smoke test (optional, if PI_IP provided)
|
||||
- Report pass/fail summary
|
||||
|
||||
### Files to Create
|
||||
- `scripts/validate-release.sh`
|
||||
|
||||
---
|
||||
|
||||
## 9. Smoke Test Docker Support
|
||||
|
||||
**Status:** Done
|
||||
|
||||
**Problem:** Smoke test expects systemd service, doesn't auto-create admin for Docker.
|
||||
|
||||
**Solution:** Make smoke test Docker-aware
|
||||
|
||||
### Features
|
||||
- Skip systemd checks if not on Pi/Linux with systemd
|
||||
- Auto-detect fresh Docker (no users) and create admin via /setup
|
||||
- Add `--docker` flag to skip Pi-specific checks
|
||||
|
||||
### Implementation
|
||||
- Added `--docker` flag that sets localhost and skips SSH/systemd checks
|
||||
- Docker health check verifies container responds with HTTP 200/302
|
||||
- Header shows "Docker Smoke Test" in Docker mode
|
||||
|
||||
### Files Modified
|
||||
- `rpi/smoke-test.sh`
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- Keep 4.1.2 focused - 9 features (9 done)
|
||||
- Don't break DCT compatibility (4.1.1 RS format is stable)
|
||||
- Test on Pi before release
|
||||
@@ -1,42 +0,0 @@
|
||||
# Stegasoo 4.1.3 Plan
|
||||
|
||||
## Release Theme
|
||||
Performance and admin features.
|
||||
|
||||
---
|
||||
|
||||
## 1. DCT Performance Optimizations
|
||||
|
||||
**Status:** Planned
|
||||
|
||||
**Problem:** DCT encode/decode can be slow on Pi, especially for large images.
|
||||
|
||||
**Ideas:**
|
||||
- Vectorize block processing with NumPy
|
||||
- Reduce Python loop overhead
|
||||
- Parallel block processing (multiprocessing?)
|
||||
- Profile and identify bottlenecks
|
||||
- Consider Cython for hot paths
|
||||
|
||||
---
|
||||
|
||||
## 2. User Management UI
|
||||
|
||||
**Status:** Planned
|
||||
|
||||
**Problem:** No way for admin to manage users via UI. Currently need direct DB access.
|
||||
|
||||
**Features:**
|
||||
- List all users
|
||||
- Create new user (admin only)
|
||||
- Delete user (admin only)
|
||||
- Reset user password
|
||||
- User activity/last login
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- These are heavier lifts than 4.1.2
|
||||
- Profile before optimizing
|
||||
- Consider security implications of user management
|
||||
97
PLAN-4.1.6.md
Normal file
97
PLAN-4.1.6.md
Normal file
@@ -0,0 +1,97 @@
|
||||
# Stegasoo v4.1.6 Planning
|
||||
|
||||
## UI Tweaks
|
||||
|
||||
### 1. Revamp Tron Lines Animation (Carrier/Stego Image)
|
||||
**Current state:**
|
||||
- 6-8 snake paths, each with 3-5 segments (~24-40 total lines)
|
||||
- 2px thick lines
|
||||
- 30-60px length per segment
|
||||
- Starting points spread across 80% of image area
|
||||
- Colors: yellow, cyan, purple, blue with glow
|
||||
|
||||
**Target improvements:**
|
||||
- [x] Thinner lines (1px instead of 2px)
|
||||
- [x] More numerous (20-40 paths via 5x4 grid, ~60-200 segments total)
|
||||
- [x] Better distribution across entire image (grid-based seeding)
|
||||
- [x] Shorter segments (12-30px) for denser "circuit board" look
|
||||
|
||||
**Files:**
|
||||
- `frontends/web/static/style.css` (~881-979) - `.embed-trace` styling
|
||||
- `frontends/web/static/js/stegasoo.js` (~333-390) - `generateEmbedTraces()`
|
||||
|
||||
---
|
||||
|
||||
## Tools Page Expansion
|
||||
|
||||
### Analysis Tools
|
||||
- [x] **JPEG Compression Tester** - Preview image at different quality levels (10-100%), show file size delta. Useful for understanding stego survivability.
|
||||
- [ ] **LSB Plane Viewer** - Visualize least significant bit plane(s) of RGB channels. Classic stego analysis tool.
|
||||
- [ ] **Histogram Viewer** - Color distribution graph per channel. Anomalies can indicate hidden data.
|
||||
- [ ] **Image Diff** - Compare two images side-by-side with pixel difference highlighting. Great for original vs stego comparison.
|
||||
- [ ] **Noise Analysis** - Chi-square or similar statistical analysis for detecting LSB embedding.
|
||||
|
||||
### Transform Tools
|
||||
- [x] **Rotate/Flip** - 90°/180°/270° rotation, horizontal/vertical flip
|
||||
- [ ] **Resize** - Scale with aspect ratio lock, common presets (50%, 25%, etc.)
|
||||
- [ ] **Crop** - Basic rectangular crop with preview
|
||||
- [x] **Format Convert** - PNG ↔ JPEG ↔ WebP with quality slider
|
||||
|
||||
### Existing Tools (already done)
|
||||
- [x] Capacity Calculator
|
||||
- [x] EXIF Viewer
|
||||
- [x] EXIF Strip
|
||||
- [x] Image Peek (header analysis)
|
||||
|
||||
### Tools UI/UX Overhaul
|
||||
|
||||
**Final Layout: Office-style Ribbon + Two-Panel**
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 📏 📋 👁️ 📊 ┃ ✂️ 🔄 📐 🔀 Image Tools │ ← Icon toolbar
|
||||
├────────────────────────────────────────┬────────────────────┤
|
||||
│ [Format: PNG ▼] [Quality: 85] │ │
|
||||
├────────────────────────────────────────┤ Capacity │
|
||||
│ │ Calculator │
|
||||
│ ┌────────────────────────────┐ │ ────────────── │
|
||||
│ │ │ │ │
|
||||
│ │ Drop image here │ │ Dimensions: │
|
||||
│ │ or click │ │ 1920 × 1080 │
|
||||
│ │ │ │ │
|
||||
│ └────────────────────────────┘ │ LSB Capacity: │
|
||||
│ │ 245 KB │
|
||||
│ [image.jpg] │ │
|
||||
│ │ ────────────── │
|
||||
│ │ [Clear] [Export] │
|
||||
└────────────────────────────────────────┴────────────────────┘
|
||||
Options + dropzone/preview Results sidebar
|
||||
```
|
||||
|
||||
- Top ribbon: Icon buttons grouped by category (Analyze | Transform)
|
||||
- Left panel: Tool options + dropzone/preview (INPUT)
|
||||
- Right panel: Tool name + results/metadata + actions (OUTPUT)
|
||||
- Flow: Left → Right (input → output)
|
||||
|
||||
**Implementation Tasks:**
|
||||
- [x] Move inline CSS to style.css
|
||||
- [x] Build icon toolbar ribbon
|
||||
- [x] Build two-panel layout structure
|
||||
- [x] Migrate existing tools (Capacity, EXIF, Strip)
|
||||
- [x] Add new tools (Rotate, Compress, Convert)
|
||||
- [ ] Loading spinner on all async operations
|
||||
- [ ] Toast notifications instead of alerts
|
||||
- [ ] Consistent color coding (green=analysis, amber=transform)
|
||||
- [ ] Mobile: stack panels vertically
|
||||
|
||||
---
|
||||
|
||||
## CLI Improvements
|
||||
|
||||
### (Add items here)
|
||||
|
||||
---
|
||||
|
||||
## Other UI Tweaks
|
||||
|
||||
### (Add items here)
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
# Stegasoo 4.1.1 Release Notes
|
||||
|
||||
**Release Date:** January 5, 2026
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Reed-Solomon Error Correction** - DCT steganography now includes RS error correction, making encoded images more resilient to minor corruption and compression artifacts
|
||||
- **Completely Rewritten Pi Setup** - Fresh install tested and validated, works reliably from scratch
|
||||
- **SSH Login Banner** - See your Stegasoo URL immediately on SSH login
|
||||
|
||||
## New Features
|
||||
|
||||
### Reed-Solomon Error Correction
|
||||
DCT-encoded images now include Reed-Solomon error correction codes, allowing recovery from minor image corruption. This significantly improves reliability when images are shared through platforms that may slightly modify them.
|
||||
|
||||
### SSH Login Banner (MOTD)
|
||||
When you SSH into your Stegasoo Pi, you'll now see:
|
||||
```
|
||||
___ _____ ___ ___ _ ___ ___ ___
|
||||
/ __||_ _|| __| / __| /_\ / __| / _ \ / _ \
|
||||
\__ \ | | | _| | (_ | / _ \ \__ \ | (_) || (_) |
|
||||
|___/ |_| |___| \___//_/ \_\|___/ \___/ \___/
|
||||
|
||||
● Stegasoo is running
|
||||
https://192.168.0.4
|
||||
```
|
||||
|
||||
### Elapsed Time Counter
|
||||
Encode/decode buttons now show elapsed time during operations.
|
||||
|
||||
### Click-to-Copy Decoded Message
|
||||
Click the decoded message box to copy to clipboard (no button needed).
|
||||
|
||||
### Overclock Wizard Option
|
||||
First-boot wizard now offers optional CPU overclocking for Pi 4/5 with active cooling.
|
||||
|
||||
## Improvements
|
||||
|
||||
### Setup Script (setup.sh)
|
||||
- Fixed pyenv Python path resolution (handles 3.12 → 3.12.12 mapping)
|
||||
- Changed default install location to `/opt/stegasoo`
|
||||
- Fixed jpegio build order (clone stegasoo first, then build jpegio into venv)
|
||||
- Added python3-dev to dependencies
|
||||
- Added btop for system monitoring
|
||||
- Shows `/setup` URL at completion for admin account creation
|
||||
|
||||
### Sanitize Script
|
||||
- Now clears port 443 iptables redirect (clean slate for wizard)
|
||||
- Removes overclock settings before imaging
|
||||
|
||||
### Documentation
|
||||
- Updated all docs to reference `/opt/stegasoo` path
|
||||
- Added pre-setup steps (chown /opt, install git)
|
||||
- Added Pi 4 performance baseline (~60s for 10MB JPEG)
|
||||
|
||||
### About Page
|
||||
- Redesigned "Limits & Specs" section with key stats cards and accordion
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
- Fixed DCT steganography for non-8-aligned images
|
||||
- Fixed MOTD port detection (was using iptables which requires root)
|
||||
- Fixed smoke test `--443` flag parsing
|
||||
|
||||
## Performance
|
||||
|
||||
On a Raspberry Pi 4 at 2GHz with USB 3.0 NVMe:
|
||||
- ~50 seconds to encode a 10MB JPEG
|
||||
- ~60 seconds to decode a 10MB JPEG
|
||||
- Full encryption: passphrase + PIN + reference photo
|
||||
|
||||
## Upgrade Notes
|
||||
|
||||
If upgrading from 4.1.0:
|
||||
```bash
|
||||
cd /opt/stegasoo # or ~/stegasoo
|
||||
git pull origin 4.1
|
||||
```
|
||||
|
||||
For fresh installs, see the [Pi README](rpi/README.md).
|
||||
|
||||
## Pre-built Images
|
||||
|
||||
- `stegasoo-rpi-4.1.1_20260105-2.img.zst` - Raspberry Pi 4/5 image
|
||||
|
||||
Flash with:
|
||||
```bash
|
||||
zstdcat stegasoo-rpi-4.1.1_20260105-2.img.zst | sudo dd of=/dev/sdX bs=4M status=progress
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Full changelog: [v4.1.0...v4.1.1](https://github.com/adlee-was-taken/stegasoo/compare/v4.1.0...v4.1.1)
|
||||
47
RELEASE_NOTES.md
Normal file
47
RELEASE_NOTES.md
Normal file
@@ -0,0 +1,47 @@
|
||||
## Stegasoo v4.1.5
|
||||
|
||||
### Developer Experience
|
||||
- **Educational Code Comments**: Core modules now include detailed explanations
|
||||
- DCT: zig-zag coefficient diagrams, QIM embedding math, Reed-Solomon "Voyager" reference
|
||||
- LSB: visual bit manipulation examples, ChaCha20 pixel selection
|
||||
- Crypto: multi-factor KDF flow diagrams, Argon2id memory-hardness reasoning
|
||||
- CLI/Web: architectural patterns for future contributors
|
||||
|
||||
### Raspberry Pi Improvements
|
||||
- **Streamlined Image Creation**: `pull-image.sh` now handles everything
|
||||
- Auto-resizes rootfs to exactly 16GB (consistent images from any SD card)
|
||||
- Disables Pi OS auto-expand
|
||||
- Compresses with zstd
|
||||
- Optional .zst.zip wrapper for GitHub releases
|
||||
- **16GB Minimum**: Pre-built images are now 16GB (was variable)
|
||||
- **Host Requirements**: `rpi/host-requirements.txt` documents all dependencies
|
||||
- **Test Automation**: `kickoff-pi-test.sh` for one-command flash+test cycles
|
||||
|
||||
### MOTD Polish
|
||||
- Dynamic temperature emoji (ice/cool/fire based on CPU temp)
|
||||
- Rocket emoji for service status
|
||||
- Cleaner formatting
|
||||
|
||||
### Raspberry Pi Image
|
||||
Download `stegasoo-rpi-4.1.5.img.zst.zip` from Releases.
|
||||
|
||||
```bash
|
||||
# Flash (auto-detects SD card)
|
||||
sudo ./rpi/flash-image.sh stegasoo-rpi-4.1.5.img.zst.zip
|
||||
|
||||
# Or manual
|
||||
zstdcat stegasoo-rpi-4.1.5.img.zst | sudo dd of=/dev/sdX bs=4M status=progress
|
||||
```
|
||||
|
||||
Default login: `admin` / `stegasoo`
|
||||
|
||||
First boot runs the setup wizard for WiFi, HTTPS, and channel key configuration.
|
||||
|
||||
### Docker
|
||||
```bash
|
||||
docker-compose up -d web # Web UI on :5000
|
||||
docker-compose up -d api # REST API on :8000
|
||||
```
|
||||
|
||||
### Full Changelog
|
||||
See [CHANGELOG.md](CHANGELOG.md) for complete version history.
|
||||
10
SECURITY.md
10
SECURITY.md
@@ -4,16 +4,16 @@
|
||||
|
||||
| Version | Supported | Notes |
|
||||
| ------- | ------------------ | ----- |
|
||||
| 4.x.x | ✅ Active | Current release |
|
||||
| 3.x.x | ⚠️ Security fixes only | Upgrade recommended |
|
||||
| 2.x.x | ❌ End of life | |
|
||||
| 1.x.x | ❌ End of life | |
|
||||
| 4.1.x | Current Version | What you SHOULD be using. |
|
||||
| 4.x.x | ⚠️ Security fixes only | Upgrade (EOL soon) |
|
||||
| <= 3.x.x | ❌ End of life | |
|
||||
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
**Please do not report security vulnerabilities through public GitHub issues.**
|
||||
|
||||
Instead, please email: **security@example.com** (replace with your email)
|
||||
Instead, please email: **adlee-was-taken@proton.me**
|
||||
|
||||
Include:
|
||||
- Description of the vulnerability
|
||||
|
||||
284
SECURITY_AUDIT_PLAN.md
Normal file
284
SECURITY_AUDIT_PLAN.md
Normal file
@@ -0,0 +1,284 @@
|
||||
# Stegasoo Security Audit Plan
|
||||
|
||||
> **Target Audience**: Developers, security reviewers, and deployment administrators
|
||||
> **Scope**: Web UI, REST API, CLI, and cryptographic core
|
||||
> **Deployment Model**: Air-gapped / private LAN (primary), Internet-facing (secondary)
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Stegasoo is a steganography tool designed for **air-gapped deployments** on private networks. While the primary threat model assumes a trusted local network, this audit plan covers security best practices for both isolated and potentially exposed deployments.
|
||||
|
||||
### Known Limitations (By Design)
|
||||
|
||||
- **Self-signed certificates**: HTTPS uses self-signed certs; users must add exceptions or deploy their own CA
|
||||
- **No rate limiting**: Assumes trusted users on private network
|
||||
- **Single-node**: No distributed session store; sessions are per-instance
|
||||
- **Air-gap focus**: External security (firewalls, network isolation) is user's responsibility
|
||||
|
||||
---
|
||||
|
||||
## 1. Authentication & Authorization
|
||||
|
||||
### 1.1 Password Security
|
||||
- [ ] Passwords hashed with Argon2id (preferred) or PBKDF2 fallback
|
||||
- [ ] Minimum password length enforced (8+ characters)
|
||||
- [ ] Password not logged or exposed in error messages
|
||||
- [ ] Password change requires current password verification
|
||||
- [ ] Admin re-authentication required for sensitive operations (channel key export)
|
||||
|
||||
### 1.2 Session Management
|
||||
- [ ] Session tokens are cryptographically random
|
||||
- [ ] Session cookies have `HttpOnly` flag
|
||||
- [ ] Session cookies have `Secure` flag (when HTTPS enabled)
|
||||
- [ ] Session cookies have `SameSite` attribute
|
||||
- [ ] Sessions invalidated on logout
|
||||
- [ ] Sessions invalidated on password change
|
||||
- [ ] Session timeout configured appropriately
|
||||
|
||||
### 1.3 Authorization
|
||||
- [ ] Admin-only routes protected by `@admin_required` decorator
|
||||
- [ ] User-only routes protected by `@login_required` decorator
|
||||
- [ ] Users cannot access other users' saved channel keys
|
||||
- [ ] Users cannot modify other users' accounts
|
||||
- [ ] Role escalation not possible through API manipulation
|
||||
|
||||
---
|
||||
|
||||
## 2. Cryptographic Implementation
|
||||
|
||||
### 2.1 Key Derivation
|
||||
- [ ] KDF uses Argon2id with appropriate parameters (memory, iterations, parallelism)
|
||||
- [ ] PBKDF2 fallback uses sufficient iterations (600,000+)
|
||||
- [ ] Salt is cryptographically random and unique per operation
|
||||
- [ ] PIN/passphrase combined securely before KDF
|
||||
|
||||
### 2.2 Encryption
|
||||
- [ ] AES-256-GCM used for payload encryption
|
||||
- [ ] Nonce/IV is unique per encryption operation
|
||||
- [ ] Authentication tag verified before decryption
|
||||
- [ ] No padding oracle vulnerabilities
|
||||
|
||||
### 2.3 Channel Keys
|
||||
- [ ] Channel keys are 128-bit (32 hex chars)
|
||||
- [ ] Channel key derivation uses HKDF or similar
|
||||
- [ ] Channel isolation prevents cross-channel decryption
|
||||
- [ ] Fingerprint reveals no information about full key
|
||||
|
||||
### 2.4 Random Number Generation
|
||||
- [ ] All random values use `secrets` module or OS CSPRNG
|
||||
- [ ] No use of `random` module for security-sensitive operations
|
||||
|
||||
---
|
||||
|
||||
## 3. Input Validation & Injection Prevention
|
||||
|
||||
### 3.1 Web UI
|
||||
- [ ] All user input sanitized before rendering (XSS prevention)
|
||||
- [ ] Jinja2 auto-escaping enabled
|
||||
- [ ] No `| safe` filter on user-controlled content
|
||||
- [ ] Content-Security-Policy header configured
|
||||
- [ ] X-Content-Type-Options: nosniff
|
||||
|
||||
### 3.2 File Uploads
|
||||
- [ ] File size limits enforced server-side
|
||||
- [ ] File type validation (magic bytes, not just extension)
|
||||
- [ ] Uploaded files not executed
|
||||
- [ ] Filenames sanitized (path traversal prevention)
|
||||
- [ ] Temporary files cleaned up after processing
|
||||
|
||||
### 3.3 API Inputs
|
||||
- [ ] JSON schema validation on API endpoints
|
||||
- [ ] Integer overflow checks on size parameters
|
||||
- [ ] No SQL injection (parameterized queries only)
|
||||
- [ ] No command injection (no shell=True with user input)
|
||||
|
||||
---
|
||||
|
||||
## 4. Steganography-Specific Security
|
||||
|
||||
### 4.1 Carrier Image Handling
|
||||
- [ ] Malformed images don't crash the server (PIL/jpegio hardening)
|
||||
- [ ] DCT mode subprocess isolation for crash protection
|
||||
- [ ] Memory limits on image processing
|
||||
- [ ] No arbitrary code execution from image metadata
|
||||
|
||||
### 4.2 Payload Security
|
||||
- [ ] Payload size limits enforced
|
||||
- [ ] Encrypted payload indistinguishable from random noise
|
||||
- [ ] No metadata leakage in output images
|
||||
- [ ] Reference photo required (prevents dictionary attacks)
|
||||
|
||||
### 4.3 Capacity Reporting
|
||||
- [ ] Capacity calculation doesn't leak information about encoding method
|
||||
- [ ] Failed decodes don't reveal why (wrong key vs no data vs corrupted)
|
||||
|
||||
---
|
||||
|
||||
## 5. Network & Transport Security
|
||||
|
||||
### 5.1 HTTPS Configuration
|
||||
- [ ] TLS 1.2+ only (no SSLv3, TLS 1.0/1.1)
|
||||
- [ ] Strong cipher suites configured
|
||||
- [ ] Certificate generation uses 2048+ bit RSA or P-256 EC
|
||||
- [ ] Private key file permissions restricted (600)
|
||||
|
||||
### 5.2 Headers
|
||||
- [ ] X-Frame-Options: DENY (clickjacking prevention)
|
||||
- [ ] X-Content-Type-Options: nosniff
|
||||
- [ ] Referrer-Policy: same-origin
|
||||
- [ ] Permissions-Policy configured
|
||||
|
||||
### 5.3 CORS (if applicable)
|
||||
- [ ] CORS not enabled (or restricted to specific origins)
|
||||
- [ ] Credentials not allowed cross-origin
|
||||
|
||||
---
|
||||
|
||||
## 6. Error Handling & Logging
|
||||
|
||||
### 6.1 Error Messages
|
||||
- [ ] Stack traces not exposed to users in production
|
||||
- [ ] Error messages don't reveal sensitive paths or config
|
||||
- [ ] Failed login doesn't reveal if username exists
|
||||
|
||||
### 6.2 Logging
|
||||
- [ ] Passwords never logged
|
||||
- [ ] Channel keys never logged
|
||||
- [ ] Passphrases never logged
|
||||
- [ ] Log files have appropriate permissions
|
||||
- [ ] Sensitive operations logged for audit trail (optional)
|
||||
|
||||
---
|
||||
|
||||
## 7. Dependency Security
|
||||
|
||||
### 7.1 Python Dependencies
|
||||
- [ ] All dependencies pinned to specific versions
|
||||
- [ ] No known vulnerabilities in dependencies (run `pip-audit` or `safety`)
|
||||
- [ ] Dependencies from trusted sources only (PyPI)
|
||||
|
||||
### 7.2 Frontend Dependencies
|
||||
- [ ] All JS/CSS served locally (air-gap ready)
|
||||
- [ ] No CDN dependencies
|
||||
- [ ] Bootstrap and libraries are official releases
|
||||
- [ ] Subresource integrity considered for any external loads
|
||||
|
||||
---
|
||||
|
||||
## 8. Deployment Security
|
||||
|
||||
### 8.1 File Permissions
|
||||
- [ ] Database file not world-readable (600 or 640)
|
||||
- [ ] SSL certificates/keys not world-readable
|
||||
- [ ] Config files with secrets protected
|
||||
- [ ] Instance directory not in web root
|
||||
|
||||
### 8.2 Docker Deployment
|
||||
- [ ] Container runs as non-root user
|
||||
- [ ] No unnecessary capabilities
|
||||
- [ ] Resource limits configured
|
||||
- [ ] Health checks don't expose sensitive info
|
||||
|
||||
### 8.3 Raspberry Pi Deployment
|
||||
- [ ] Default passwords changed
|
||||
- [ ] SSH key-only authentication (recommended)
|
||||
- [ ] Unnecessary services disabled
|
||||
- [ ] Firewall configured (UFW/iptables)
|
||||
|
||||
---
|
||||
|
||||
## 9. Air-Gap Specific Considerations
|
||||
|
||||
### 9.1 Network Isolation
|
||||
- [ ] Document expected network topology
|
||||
- [ ] No phone-home or telemetry
|
||||
- [ ] No external API calls
|
||||
- [ ] Works fully offline after deployment
|
||||
|
||||
### 9.2 Key Distribution
|
||||
- [ ] QR code export for channel keys (offline transfer)
|
||||
- [ ] Print sheet for physical key backup
|
||||
- [ ] No cloud sync or external key servers
|
||||
|
||||
### 9.3 Updates
|
||||
- [ ] Document offline update procedure
|
||||
- [ ] Signed releases (future consideration)
|
||||
- [ ] Checksum verification for downloads
|
||||
|
||||
---
|
||||
|
||||
## 10. Penetration Testing Checklist
|
||||
|
||||
### 10.1 Authentication Attacks
|
||||
- [ ] Brute force login (note: no rate limiting by design)
|
||||
- [ ] Session fixation
|
||||
- [ ] Session hijacking
|
||||
- [ ] Password reset flow abuse
|
||||
|
||||
### 10.2 Injection Attacks
|
||||
- [ ] SQL injection on all inputs
|
||||
- [ ] XSS (stored, reflected, DOM-based)
|
||||
- [ ] Command injection
|
||||
- [ ] Path traversal
|
||||
- [ ] SSTI (Server-Side Template Injection)
|
||||
|
||||
### 10.3 Business Logic
|
||||
- [ ] Access control bypass
|
||||
- [ ] IDOR (Insecure Direct Object Reference)
|
||||
- [ ] Race conditions
|
||||
- [ ] Integer overflow in capacity calculations
|
||||
|
||||
### 10.4 Cryptographic Attacks
|
||||
- [ ] Known-plaintext attacks on stego output
|
||||
- [ ] Timing attacks on password verification
|
||||
- [ ] Padding oracle attacks
|
||||
- [ ] Key reuse vulnerabilities
|
||||
|
||||
---
|
||||
|
||||
## Tools for Automated Testing
|
||||
|
||||
```bash
|
||||
# Dependency vulnerability scan
|
||||
pip-audit
|
||||
safety check
|
||||
|
||||
# Static analysis
|
||||
bandit -r stegasoo/ frontends/
|
||||
|
||||
# Web security scan (if exposed)
|
||||
nikto -h https://localhost:5000
|
||||
OWASP ZAP (manual)
|
||||
|
||||
# SSL/TLS configuration
|
||||
testssl.sh https://localhost:5000
|
||||
|
||||
# Python code quality
|
||||
ruff check .
|
||||
mypy stegasoo/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Audit Schedule
|
||||
|
||||
| Phase | Focus Area | Priority |
|
||||
|-------|-----------|----------|
|
||||
| Pre-release | Crypto implementation, auth flow | Critical |
|
||||
| Post-release | Dependency scan, static analysis | High |
|
||||
| Quarterly | Full penetration test | Medium |
|
||||
| Ongoing | CVE monitoring for dependencies | High |
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- This plan assumes **trusted users on a private network** as the primary deployment model
|
||||
- Internet-facing deployments should add rate limiting, fail2ban, and reverse proxy hardening
|
||||
- For high-security deployments, consider external security audit by professionals
|
||||
|
||||
---
|
||||
|
||||
*Last updated: 2026-01-07*
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
A detailed breakdown of how Stegasoo's LSB and DCT steganography modes work under the hood.
|
||||
|
||||
**Version 4.0** - Updated for simplified authentication (no date dependency)
|
||||
**Version 4.1** - Updated for channel keys and deployment isolation
|
||||
|
||||
---
|
||||
|
||||
@@ -22,20 +22,20 @@ A detailed breakdown of how Stegasoo's LSB and DCT steganography modes work unde
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────────┐
|
||||
│ STEGASOO ARCHITECTURE (v4.0) │
|
||||
│ STEGASOO ARCHITECTURE (v4.1) │
|
||||
├─────────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ INPUTS PROCESSING OUTPUT │
|
||||
│ ─────── ────────── ────── │
|
||||
│ │
|
||||
│ Reference Photo ─┐ │
|
||||
│ Passphrase ──────┼──► Argon2id KDF ──► AES-256 Key │
|
||||
│ PIN/RSA Key ─────┘ │ │
|
||||
│ ▼ │
|
||||
│ Message/File ────────────────────────► AES-256-GCM ──► Ciphertext │
|
||||
│ Passphrase ──────┼──► Argon2id KDF ──► AES-256 Key │
|
||||
│ PIN/RSA Key ─────┤ │ │
|
||||
│ Channel Key ─────┘ (v4.1) ▼ │
|
||||
│ Message/File ────────────────────────► AES-256-GCM ──► Ciphertext │
|
||||
│ Encryption │ │
|
||||
│ ▼ │
|
||||
│ Carrier Image ───────────────────────────────────────► Embedding ──► Stego│
|
||||
│ Carrier Image ───────────────────────────────────────► Embedding ─► Stego │
|
||||
│ (LSB/DCT) Image │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────────┘
|
||||
@@ -50,11 +50,24 @@ A detailed breakdown of how Stegasoo's LSB and DCT steganography modes work unde
|
||||
| Header size | 75 bytes | 65 bytes (no date field) |
|
||||
| Python support | 3.10+ | 3.10-3.12 only |
|
||||
|
||||
### v4.1 Changes
|
||||
|
||||
| Change | v4.0 | v4.1 |
|
||||
|--------|------|------|
|
||||
| Channel keys | None | 32-byte deployment isolation |
|
||||
| Key derivation | passphrase + ref + pin | passphrase + ref + pin + channel |
|
||||
| Web auth | Session-based | Session + admin/user roles |
|
||||
| Raspberry Pi | Manual setup | First-boot wizard with gum |
|
||||
| Docker | Basic | Production-ready compose |
|
||||
|
||||
**Channel Keys** provide deployment isolation - messages encoded on one Stegasoo instance cannot be decoded by another instance with a different channel key, even with the same passphrase/PIN/reference photo.
|
||||
|
||||
### Module Responsibilities
|
||||
|
||||
| Module | File | Purpose |
|
||||
|--------|------|---------|
|
||||
| **Crypto** | `crypto.py` | Key derivation (Argon2id), AES-256-GCM encryption/decryption |
|
||||
| **Channel** | `channel.py` | Channel key management, deployment isolation (v4.1) |
|
||||
| **Steganography** | `steganography.py` | LSB pixel manipulation, capacity calculation |
|
||||
| **DCT Steganography** | `dct_steganography.py` | Frequency-domain embedding, jpegio integration |
|
||||
| **Compression** | `compression.py` | Optional LZ4 compression of payload |
|
||||
@@ -626,7 +639,7 @@ Factor 1: Reference Photo ─┐
|
||||
• 80-256 bits entropy │
|
||||
• "Something you have" │
|
||||
├──► Combined entropy: 133-400+ bits
|
||||
Factor 2: Passphrase │ (Beyond brute force)
|
||||
Factor 2: Passphrase │ (Beyond brute force)
|
||||
• 43-132 bits entropy │
|
||||
• "Something you know" │
|
||||
• 4 words default (v4.0) │
|
||||
@@ -688,7 +701,7 @@ AUTHENTICATED ENCRYPTION (AES-256-GCM)
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
│ ENCODE FLOW (v4.0) │
|
||||
│ ENCODE FLOW (v4.0) │
|
||||
└──────────────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
User Inputs Processing Output
|
||||
@@ -714,14 +727,14 @@ Carrier Image ──────────────────────
|
||||
│ │
|
||||
┌───────────┴─────┴────────────┐
|
||||
│ │
|
||||
LSB Mode DCT Mode
|
||||
LSB Mode DCT Mode
|
||||
│ │
|
||||
▼ ▼
|
||||
embed_lsb() embed_in_dct()
|
||||
(pixel LSBs) (DCT coefficients)
|
||||
embed_lsb() embed_in_dct()
|
||||
(pixel LSBs) (DCT coefficients)
|
||||
│ │
|
||||
▼ ▼
|
||||
PNG Output PNG or JPEG
|
||||
PNG Output PNG or JPEG
|
||||
│ │
|
||||
└──────────┬───────────────────┘
|
||||
│
|
||||
@@ -793,8 +806,8 @@ Stego Image ──────────► detect_mode() ──────
|
||||
Both modes share the same cryptographic foundation (Argon2id + AES-256-GCM) and multi-factor authentication, ensuring security regardless of embedding method.
|
||||
|
||||
The choice comes down to your use case:
|
||||
- **Private channel?** → LSB (maximum capacity)
|
||||
- **Public platform?** → DCT (maximum compatibility)
|
||||
- **Private channel?** → LSB (maximum capacity)
|
||||
|
||||
### v4.0 Simplifications
|
||||
|
||||
|
||||
42
WISHLIST-4.2.md
Normal file
42
WISHLIST-4.2.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# Stegasoo v4.2 Wishlist
|
||||
|
||||
Blue sky ideas for future development. No timeline - just capturing thoughts.
|
||||
|
||||
---
|
||||
|
||||
## Performance
|
||||
|
||||
### GPU-Accelerated DCT Encoding/Decoding
|
||||
- **Idea**: Leverage GPU for JPEG DCT coefficient manipulation
|
||||
- **Potential Approaches**:
|
||||
- OpenCL/CUDA for parallel DCT operations
|
||||
- Raspberry Pi VideoCore IV/VI GPU compute
|
||||
- WebGPU for browser-based acceleration
|
||||
- **Challenges**:
|
||||
- jpegio library is CPU-bound (C extension)
|
||||
- Would need custom DCT implementation
|
||||
- Memory transfer overhead may negate gains for small images
|
||||
- **Research**:
|
||||
- libjpeg-turbo uses SIMD but not GPU
|
||||
- nvJPEG (NVIDIA) does GPU-accelerated JPEG
|
||||
- Could potentially use GPU for the embedding math, not JPEG decode
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
(Add ideas here)
|
||||
|
||||
---
|
||||
|
||||
## Infrastructure
|
||||
|
||||
(Add ideas here)
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- This is a living document - add ideas anytime
|
||||
- Not all ideas will be implemented
|
||||
- Feasibility research needed before committing to roadmap
|
||||
@@ -2,23 +2,76 @@
|
||||
"""
|
||||
Stegasoo Web Frontend (v4.0.0)
|
||||
|
||||
Flask-based web UI for steganography operations.
|
||||
Supports both text messages and file embedding.
|
||||
A production Flask application demonstrating proper web architecture patterns.
|
||||
This isn't just a quick demo - it's built to run on a Raspberry Pi 24/7.
|
||||
|
||||
ARCHITECTURE OVERVIEW
|
||||
=====================
|
||||
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ FLASK APPLICATION │
|
||||
├─────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ Routes (/encode, /decode, /api/*) │
|
||||
│ │ │
|
||||
│ ├── auth.py # Session management, user accounts │
|
||||
│ ├── temp_storage.py # File-based temp storage with expiry │
|
||||
│ ├── subprocess_stego.py # Isolated encode/decode workers │
|
||||
│ └── ssl_utils.py # Self-signed cert generation │
|
||||
│ │
|
||||
│ Templates (Jinja2) │
|
||||
│ └── base.html → encode.html, decode.html, etc. │
|
||||
│ │
|
||||
│ Static assets (CSS, JS) │
|
||||
│ └── Vanilla JS, no framework (keeps it simple) │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
KEY PATTERNS
|
||||
============
|
||||
|
||||
1. SUBPROCESS ISOLATION
|
||||
Stegasoo's DCT mode uses scipy/jpegio which can crash on malformed input.
|
||||
We run encode/decode in subprocesses so crashes don't take down the server:
|
||||
|
||||
subprocess_stego = SubprocessStego(timeout=180)
|
||||
result = subprocess_stego.encode(carrier, ref, message, ...)
|
||||
|
||||
If the subprocess crashes, we catch it and return an error gracefully.
|
||||
|
||||
2. ASYNC JOBS WITH PROGRESS
|
||||
Encoding large images can take 30+ seconds. We use ThreadPoolExecutor
|
||||
to run jobs in background threads with progress reporting:
|
||||
|
||||
job_id = generate_job_id()
|
||||
_executor.submit(_run_encode_job, job_id, params)
|
||||
# Client polls /api/encode/progress/<job_id> for updates
|
||||
|
||||
3. CONTEXT PROCESSORS
|
||||
@app.context_processor injects variables into ALL templates:
|
||||
|
||||
return {"version": __version__, "has_dct": has_dct_support()}
|
||||
|
||||
Now every template can use {{ version }} without passing it explicitly.
|
||||
|
||||
4. BEFORE_REQUEST HOOKS
|
||||
@app.before_request runs before every request. We use it for:
|
||||
- First-run setup redirect (no users → /setup)
|
||||
- Session validation
|
||||
- Cleanup of old temp files
|
||||
|
||||
5. SECURE SECRET KEY
|
||||
Flask sessions need a secret key. We persist it to a file so sessions
|
||||
survive server restarts (otherwise everyone gets logged out).
|
||||
|
||||
CHANGES in v4.0.0:
|
||||
- Added channel key support for deployment/group isolation
|
||||
- New /api/channel/status endpoint
|
||||
- Channel key selector on encode/decode pages
|
||||
- Messages encoded with channel key require same key to decode
|
||||
|
||||
CHANGES in v3.2.0:
|
||||
- Removed date dependency from all operations
|
||||
- Renamed day_phrase → passphrase
|
||||
- No date selection or tracking needed
|
||||
- Simplified user experience for asynchronous communications
|
||||
|
||||
NEW in v3.0: LSB and DCT embedding modes with advanced options.
|
||||
NEW in v3.0.1: DCT output format selection (PNG or JPEG) and color mode (grayscale or color).
|
||||
"""
|
||||
|
||||
import io
|
||||
@@ -31,6 +84,7 @@ import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import temp_storage
|
||||
from auth import (
|
||||
MAX_CHANNEL_KEYS,
|
||||
MAX_USERS,
|
||||
@@ -83,7 +137,6 @@ from flask import (
|
||||
)
|
||||
from PIL import Image
|
||||
from ssl_utils import ensure_certs
|
||||
import temp_storage
|
||||
|
||||
os.environ["NUMPY_MADVISE_HUGEPAGE"] = "0"
|
||||
os.environ["OMP_NUM_THREADS"] = "1"
|
||||
@@ -157,8 +210,35 @@ except ImportError:
|
||||
# ============================================================================
|
||||
# SUBPROCESS ISOLATION FOR STEGASOO OPERATIONS
|
||||
# ============================================================================
|
||||
# Runs encode/decode/compare in subprocesses to prevent jpegio/scipy crashes
|
||||
# from taking down the Flask server.
|
||||
#
|
||||
# This is a critical reliability pattern. Here's the problem:
|
||||
#
|
||||
# scipy's DCT and jpegio can crash (segfault) on:
|
||||
# - Malformed JPEG files
|
||||
# - Very large images that exhaust memory
|
||||
# - Certain edge cases in coefficient manipulation
|
||||
#
|
||||
# If these crash in the main Flask process, your whole server dies.
|
||||
# Users get a connection reset, and the service goes down.
|
||||
#
|
||||
# The solution: Run stegasoo operations in separate Python processes.
|
||||
#
|
||||
# Main Flask process Worker subprocess
|
||||
# ┌─────────────────┐ ┌─────────────────┐
|
||||
# │ │ spawn │ │
|
||||
# │ /api/encode │──────────────>│ encode() │
|
||||
# │ │ │ │
|
||||
# │ wait for │<──────────────│ return result │
|
||||
# │ result │ or crash │ (or crash) │
|
||||
# │ │ │ │
|
||||
# │ handle error │ │ (process dies) │
|
||||
# └─────────────────┘ └─────────────────┘
|
||||
#
|
||||
# If the subprocess crashes, we catch the error and return a friendly message.
|
||||
# The main server keeps running. Users can try again with different input.
|
||||
#
|
||||
# The subprocess_stego module handles all the pickling/unpickling of data.
|
||||
|
||||
from subprocess_stego import (
|
||||
SubprocessStego,
|
||||
cleanup_progress_file,
|
||||
@@ -169,6 +249,7 @@ from subprocess_stego import (
|
||||
|
||||
from stegasoo.qr_utils import (
|
||||
can_fit_in_qr,
|
||||
decompress_data,
|
||||
detect_and_crop_qr,
|
||||
extract_key_from_qr,
|
||||
generate_qr_code,
|
||||
@@ -181,38 +262,89 @@ subprocess_stego = SubprocessStego(timeout=180) # 3 minute timeout for large im
|
||||
# ============================================================================
|
||||
# FLASK APP CONFIGURATION
|
||||
# ============================================================================
|
||||
#
|
||||
# Flask configuration demonstrates several production patterns:
|
||||
#
|
||||
# 1. SECRET KEY PERSISTENCE
|
||||
# Flask uses secret_key to sign session cookies. If it changes, all users
|
||||
# get logged out. We save it to a file so it survives restarts.
|
||||
#
|
||||
# 2. CONTENT LENGTH LIMITS
|
||||
# MAX_CONTENT_LENGTH prevents DoS via huge uploads. Flask will reject
|
||||
# requests that exceed this before loading them into memory.
|
||||
#
|
||||
# 3. ENVIRONMENT-BASED CONFIG
|
||||
# Settings come from environment variables, allowing:
|
||||
# - Different settings per deployment (dev/staging/prod)
|
||||
# - Docker/systemd to inject config without code changes
|
||||
# - 12-factor app compliance
|
||||
#
|
||||
# 4. INSTANCE FOLDER
|
||||
# Flask's instance_path is for per-deployment data (databases, keys).
|
||||
# It's .gitignored by default - perfect for secrets.
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Persist secret key so sessions survive restarts
|
||||
# Without this, every restart = everyone gets logged out
|
||||
_instance_path = Path(app.instance_path)
|
||||
_instance_path.mkdir(parents=True, exist_ok=True)
|
||||
_secret_key_file = _instance_path / ".secret_key"
|
||||
if _secret_key_file.exists():
|
||||
app.secret_key = _secret_key_file.read_text().strip()
|
||||
else:
|
||||
app.secret_key = secrets.token_hex(32)
|
||||
# First run: generate a new key and save it
|
||||
app.secret_key = secrets.token_hex(32) # 256 bits of randomness
|
||||
_secret_key_file.write_text(app.secret_key)
|
||||
_secret_key_file.chmod(0o600)
|
||||
_secret_key_file.chmod(0o600) # Only owner can read
|
||||
|
||||
# Reject uploads larger than this (prevents memory exhaustion)
|
||||
app.config["MAX_CONTENT_LENGTH"] = MAX_FILE_SIZE
|
||||
|
||||
# Auth configuration from environment
|
||||
# STEGASOO_AUTH_ENABLED=false disables login (for local/dev use)
|
||||
app.config["AUTH_ENABLED"] = os.environ.get("STEGASOO_AUTH_ENABLED", "true").lower() == "true"
|
||||
app.config["HTTPS_ENABLED"] = os.environ.get("STEGASOO_HTTPS_ENABLED", "false").lower() == "true"
|
||||
|
||||
# Initialize auth module
|
||||
# Initialize auth module (sets up session handling, user DB)
|
||||
init_auth(app)
|
||||
|
||||
# ============================================================================
|
||||
# ASYNC JOB MANAGEMENT (v4.1.2)
|
||||
# ============================================================================
|
||||
# Encode operations can run in background threads with progress reporting
|
||||
#
|
||||
# Problem: DCT encoding a large image can take 30-60 seconds.
|
||||
# Solution: Run it in a background thread, let the client poll for progress.
|
||||
#
|
||||
# The flow:
|
||||
#
|
||||
# Client Server
|
||||
# ────── ──────
|
||||
# POST /api/encode/async ──────> Start background job
|
||||
# <────── Return job_id
|
||||
#
|
||||
# GET /api/encode/progress/123 ─> Check job status
|
||||
# <────── {"progress": 45, "phase": "embedding"}
|
||||
#
|
||||
# GET /api/encode/progress/123 ─> Check again
|
||||
# <────── {"status": "complete", "file_id": "abc"}
|
||||
#
|
||||
# GET /api/download/abc ────────> Download result
|
||||
# <────── Encoded image
|
||||
#
|
||||
# Why ThreadPoolExecutor instead of Celery/Redis?
|
||||
# - This runs on a Raspberry Pi with 1GB RAM
|
||||
# - We don't need distributed workers
|
||||
# - Keep it simple - threads are fine for 2 concurrent jobs
|
||||
#
|
||||
# The thread pool is limited to 2 workers because:
|
||||
# - Each encode loads the full image into memory
|
||||
# - Too many concurrent jobs = OOM on the Pi
|
||||
|
||||
# Thread pool for background encode/decode operations
|
||||
_executor = ThreadPoolExecutor(max_workers=2)
|
||||
|
||||
# Job storage: job_id -> {status, result, error, file_id, ...}
|
||||
# Job storage: job_id -> {status, result, error, file_id, created, ...}
|
||||
# We use a dict with a lock because threads access it concurrently
|
||||
_jobs = {}
|
||||
_jobs_lock = threading.Lock()
|
||||
|
||||
@@ -267,6 +399,27 @@ THUMBNAIL_FILES: dict[str, bytes] = {} # Not used - see temp_storage.py
|
||||
# ============================================================================
|
||||
# TEMPLATE CONTEXT PROCESSOR
|
||||
# ============================================================================
|
||||
#
|
||||
# Context processors inject variables into EVERY template automatically.
|
||||
# Instead of passing the same data to every render_template() call:
|
||||
#
|
||||
# # Bad: repetitive and error-prone
|
||||
# return render_template("page.html", version=__version__, has_dct=...)
|
||||
#
|
||||
# We define it once here and it's available everywhere:
|
||||
#
|
||||
# # In any template:
|
||||
# <p>Version: {{ version }}</p>
|
||||
# {% if has_dct %}DCT mode available{% endif %}
|
||||
#
|
||||
# This is great for:
|
||||
# - Version numbers (show in footer)
|
||||
# - Feature flags (has_dct, auth_enabled)
|
||||
# - User info (username, is_admin)
|
||||
# - Global config (max sizes, limits)
|
||||
#
|
||||
# The function runs on EVERY request, so keep it fast.
|
||||
# Don't do expensive database queries here.
|
||||
|
||||
|
||||
@app.context_processor
|
||||
@@ -1049,12 +1202,19 @@ def encode_page():
|
||||
ref_data = ref_photo.read()
|
||||
carrier_data = carrier.read()
|
||||
|
||||
# Handle RSA key - can come from .pem file or QR code image
|
||||
# Handle RSA key - can come from .pem file, QR code image, or webcam-scanned PEM (v4.1.5)
|
||||
rsa_key_data = None
|
||||
rsa_key_pem = request.form.get("rsa_key_pem", "").strip()
|
||||
rsa_key_qr = request.files.get("rsa_key_qr")
|
||||
rsa_key_from_qr = False
|
||||
|
||||
if rsa_key_file and rsa_key_file.filename:
|
||||
if rsa_key_pem:
|
||||
# Webcam-scanned PEM key (v4.1.5) - may be compressed
|
||||
if rsa_key_pem.startswith("STEGASOO-Z:"):
|
||||
rsa_key_pem = decompress_data(rsa_key_pem)
|
||||
rsa_key_data = rsa_key_pem.encode("utf-8")
|
||||
rsa_key_from_qr = True
|
||||
elif rsa_key_file and rsa_key_file.filename:
|
||||
rsa_key_data = rsa_key_file.read()
|
||||
elif rsa_key_qr and rsa_key_qr.filename and HAS_QRCODE_READ:
|
||||
qr_image_data = rsa_key_qr.read()
|
||||
@@ -1371,6 +1531,82 @@ def encode_cleanup(file_id):
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def _run_decode_job(job_id: str, decode_params: dict) -> None:
|
||||
"""Background thread function for async decode."""
|
||||
progress_file = get_progress_file_path(job_id)
|
||||
|
||||
try:
|
||||
_store_job(job_id, {"status": "running", "created": time.time()})
|
||||
|
||||
# Run decode with progress file
|
||||
decode_result = subprocess_stego.decode(
|
||||
stego_data=decode_params["stego_data"],
|
||||
reference_data=decode_params["ref_data"],
|
||||
passphrase=decode_params["passphrase"],
|
||||
pin=decode_params.get("pin"),
|
||||
rsa_key_data=decode_params.get("rsa_key_data"),
|
||||
rsa_password=decode_params.get("rsa_password"),
|
||||
embed_mode=decode_params.get("embed_mode", "auto"),
|
||||
channel_key=decode_params.get("channel_key"),
|
||||
progress_file=progress_file,
|
||||
)
|
||||
|
||||
if not decode_result.success:
|
||||
_store_job(
|
||||
job_id,
|
||||
{
|
||||
"status": "error",
|
||||
"error": decode_result.error or "Decoding failed",
|
||||
"error_type": decode_result.error_type,
|
||||
"created": time.time(),
|
||||
},
|
||||
)
|
||||
return
|
||||
|
||||
# Store result based on type
|
||||
if decode_result.is_file:
|
||||
file_id = secrets.token_urlsafe(16)
|
||||
filename = decode_result.filename or "decoded_file"
|
||||
temp_storage.save_temp_file(file_id, decode_result.file_data, {
|
||||
"filename": filename,
|
||||
"mime_type": decode_result.mime_type,
|
||||
})
|
||||
_store_job(
|
||||
job_id,
|
||||
{
|
||||
"status": "complete",
|
||||
"file_id": file_id,
|
||||
"is_file": True,
|
||||
"filename": filename,
|
||||
"file_size": len(decode_result.file_data),
|
||||
"mime_type": decode_result.mime_type,
|
||||
"created": time.time(),
|
||||
},
|
||||
)
|
||||
else:
|
||||
_store_job(
|
||||
job_id,
|
||||
{
|
||||
"status": "complete",
|
||||
"is_file": False,
|
||||
"message": decode_result.message,
|
||||
"created": time.time(),
|
||||
},
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
_store_job(
|
||||
job_id,
|
||||
{
|
||||
"status": "error",
|
||||
"error": str(e),
|
||||
"created": time.time(),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
cleanup_progress_file(job_id)
|
||||
|
||||
|
||||
@app.route("/decode", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def decode_page():
|
||||
@@ -1414,12 +1650,19 @@ def decode_page():
|
||||
ref_data = ref_photo.read()
|
||||
stego_data = stego_image.read()
|
||||
|
||||
# Handle RSA key - can come from .pem file or QR code image
|
||||
# Handle RSA key - can come from .pem file, QR code image, or webcam-scanned PEM (v4.1.5)
|
||||
rsa_key_data = None
|
||||
rsa_key_pem = request.form.get("rsa_key_pem", "").strip()
|
||||
rsa_key_qr = request.files.get("rsa_key_qr")
|
||||
rsa_key_from_qr = False
|
||||
|
||||
if rsa_key_file and rsa_key_file.filename:
|
||||
if rsa_key_pem:
|
||||
# Webcam-scanned PEM key (v4.1.5) - may be compressed
|
||||
if rsa_key_pem.startswith("STEGASOO-Z:"):
|
||||
rsa_key_pem = decompress_data(rsa_key_pem)
|
||||
rsa_key_data = rsa_key_pem.encode("utf-8")
|
||||
rsa_key_from_qr = True
|
||||
elif rsa_key_file and rsa_key_file.filename:
|
||||
rsa_key_data = rsa_key_file.read()
|
||||
elif rsa_key_qr and rsa_key_qr.filename and HAS_QRCODE_READ:
|
||||
qr_image_data = rsa_key_qr.read()
|
||||
@@ -1454,6 +1697,29 @@ def decode_page():
|
||||
flash(result.error_message, "error")
|
||||
return render_template("decode.html", has_qrcode_read=HAS_QRCODE_READ)
|
||||
|
||||
# Check for async mode (v4.1.5)
|
||||
is_async = request.form.get("async") == "true" or request.headers.get("X-Async") == "true"
|
||||
|
||||
# Build decode params
|
||||
decode_params = {
|
||||
"stego_data": stego_data,
|
||||
"ref_data": ref_data,
|
||||
"passphrase": passphrase,
|
||||
"pin": pin if pin else None,
|
||||
"rsa_key_data": rsa_key_data,
|
||||
"rsa_password": key_password,
|
||||
"embed_mode": embed_mode,
|
||||
"channel_key": channel_key,
|
||||
}
|
||||
|
||||
# ASYNC MODE: Start background job and return JSON
|
||||
if is_async:
|
||||
job_id = generate_job_id()
|
||||
_store_job(job_id, {"status": "pending", "created": time.time()})
|
||||
_executor.submit(_run_decode_job, job_id, decode_params)
|
||||
return jsonify({"job_id": job_id, "status": "pending"})
|
||||
|
||||
# SYNC MODE: Run inline (original behavior)
|
||||
# v4.0.0: Include channel_key parameter
|
||||
# Use subprocess-isolated decode to prevent crashes
|
||||
decode_result = subprocess_stego.decode(
|
||||
@@ -1559,9 +1825,113 @@ def decode_download(file_id):
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# DECODE PROGRESS ENDPOINTS (v4.1.5)
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@app.route("/decode/status/<job_id>")
|
||||
@login_required
|
||||
def decode_status(job_id):
|
||||
"""Get the status of an async decode job."""
|
||||
job = _get_job(job_id)
|
||||
if not job:
|
||||
return jsonify({"error": "Job not found"}), 404
|
||||
|
||||
response = {"status": job.get("status", "unknown")}
|
||||
|
||||
if job["status"] == "complete":
|
||||
response["is_file"] = job.get("is_file", False)
|
||||
if job.get("is_file"):
|
||||
response["file_id"] = job.get("file_id")
|
||||
response["filename"] = job.get("filename")
|
||||
response["file_size"] = job.get("file_size")
|
||||
response["mime_type"] = job.get("mime_type")
|
||||
else:
|
||||
response["message"] = job.get("message")
|
||||
elif job["status"] == "error":
|
||||
response["error"] = job.get("error", "Unknown error")
|
||||
response["error_type"] = job.get("error_type")
|
||||
|
||||
return jsonify(response)
|
||||
|
||||
|
||||
@app.route("/decode/progress/<job_id>")
|
||||
@login_required
|
||||
def decode_progress(job_id):
|
||||
"""Get the progress of an async decode job."""
|
||||
progress = read_progress(job_id)
|
||||
if progress:
|
||||
return jsonify(progress)
|
||||
|
||||
# No progress file yet - check job status
|
||||
job = _get_job(job_id)
|
||||
if not job:
|
||||
return jsonify({"error": "Job not found"}), 404
|
||||
|
||||
if job["status"] == "complete":
|
||||
return jsonify({"percent": 100, "phase": "complete"})
|
||||
elif job["status"] == "error":
|
||||
return jsonify({"percent": 0, "phase": "error", "error": job.get("error")})
|
||||
elif job["status"] == "pending":
|
||||
return jsonify({"percent": 0, "phase": "starting"})
|
||||
|
||||
# Running but no progress file yet
|
||||
return jsonify({"percent": 5, "phase": "reading"})
|
||||
|
||||
|
||||
@app.route("/decode/result/<job_id>")
|
||||
@login_required
|
||||
def decode_result(job_id):
|
||||
"""Get the result page for an async decode job."""
|
||||
job = _get_job(job_id)
|
||||
if not job:
|
||||
flash("Job not found or expired.", "error")
|
||||
return redirect(url_for("decode_page"))
|
||||
|
||||
if job["status"] != "complete":
|
||||
flash("Decode not complete.", "error")
|
||||
return redirect(url_for("decode_page"))
|
||||
|
||||
if job.get("is_file"):
|
||||
return render_template(
|
||||
"decode.html",
|
||||
decoded_file=True,
|
||||
file_id=job.get("file_id"),
|
||||
filename=job.get("filename"),
|
||||
file_size=format_size(job.get("file_size", 0)),
|
||||
mime_type=job.get("mime_type"),
|
||||
has_qrcode_read=HAS_QRCODE_READ,
|
||||
)
|
||||
else:
|
||||
return render_template(
|
||||
"decode.html",
|
||||
decoded_message=job.get("message"),
|
||||
has_qrcode_read=HAS_QRCODE_READ,
|
||||
)
|
||||
|
||||
|
||||
@app.route("/about")
|
||||
def about():
|
||||
return render_template("about.html", has_argon2=has_argon2(), has_qrcode_read=HAS_QRCODE_READ)
|
||||
from stegasoo.channel import get_channel_status
|
||||
|
||||
channel_status = get_channel_status()
|
||||
|
||||
# Check if user is admin (for QR sharing)
|
||||
current_user = get_current_user()
|
||||
is_admin = current_user.is_admin if current_user else False
|
||||
|
||||
return render_template(
|
||||
"about.html",
|
||||
has_argon2=has_argon2(),
|
||||
has_qrcode_read=HAS_QRCODE_READ,
|
||||
# Channel info (bugfix - was not being passed)
|
||||
channel_configured=channel_status["configured"],
|
||||
channel_fingerprint=channel_status.get("fingerprint"),
|
||||
channel_source=channel_status.get("source"),
|
||||
# Admin check for QR sharing
|
||||
is_admin=is_admin,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -1735,6 +2105,145 @@ def api_tools_exif_clear():
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/tools/rotate", methods=["POST"])
|
||||
@login_required
|
||||
def api_tools_rotate():
|
||||
"""Rotate and/or flip an image."""
|
||||
from PIL import Image
|
||||
|
||||
image_file = request.files.get("image")
|
||||
if not image_file:
|
||||
return jsonify({"success": False, "error": "No image provided"}), 400
|
||||
|
||||
rotation = int(request.form.get("rotation", 0))
|
||||
flip_h = request.form.get("flip_h", "false").lower() == "true"
|
||||
flip_v = request.form.get("flip_v", "false").lower() == "true"
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(image_file.read()))
|
||||
|
||||
# Apply rotation (PIL rotates counter-clockwise, so negate)
|
||||
if rotation:
|
||||
img = img.rotate(-rotation, expand=True)
|
||||
|
||||
# Apply flips
|
||||
if flip_h:
|
||||
img = img.transpose(Image.FLIP_LEFT_RIGHT)
|
||||
if flip_v:
|
||||
img = img.transpose(Image.FLIP_TOP_BOTTOM)
|
||||
|
||||
# Output as PNG (lossless)
|
||||
buffer = io.BytesIO()
|
||||
img.save(buffer, format="PNG")
|
||||
buffer.seek(0)
|
||||
|
||||
stem = (
|
||||
image_file.filename.rsplit(".", 1)[0]
|
||||
if "." in image_file.filename
|
||||
else image_file.filename
|
||||
)
|
||||
return send_file(
|
||||
buffer,
|
||||
mimetype="image/png",
|
||||
as_attachment=True,
|
||||
download_name=f"{stem}_transformed.png",
|
||||
)
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/tools/compress", methods=["POST"])
|
||||
@login_required
|
||||
def api_tools_compress():
|
||||
"""Compress image to JPEG at specified quality."""
|
||||
from PIL import Image
|
||||
|
||||
image_file = request.files.get("image")
|
||||
if not image_file:
|
||||
return jsonify({"success": False, "error": "No image provided"}), 400
|
||||
|
||||
quality = int(request.form.get("quality", 85))
|
||||
quality = max(10, min(100, quality)) # Clamp to valid range
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(image_file.read()))
|
||||
|
||||
# Convert to RGB if necessary (JPEG doesn't support alpha)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
img = img.convert("RGB")
|
||||
|
||||
buffer = io.BytesIO()
|
||||
img.save(buffer, format="JPEG", quality=quality)
|
||||
buffer.seek(0)
|
||||
|
||||
stem = (
|
||||
image_file.filename.rsplit(".", 1)[0]
|
||||
if "." in image_file.filename
|
||||
else image_file.filename
|
||||
)
|
||||
return send_file(
|
||||
buffer,
|
||||
mimetype="image/jpeg",
|
||||
as_attachment=True,
|
||||
download_name=f"{stem}_q{quality}.jpg",
|
||||
)
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/tools/convert", methods=["POST"])
|
||||
@login_required
|
||||
def api_tools_convert():
|
||||
"""Convert image to different format."""
|
||||
from PIL import Image
|
||||
|
||||
image_file = request.files.get("image")
|
||||
if not image_file:
|
||||
return jsonify({"success": False, "error": "No image provided"}), 400
|
||||
|
||||
output_format = request.form.get("format", "PNG").upper()
|
||||
quality = int(request.form.get("quality", 90))
|
||||
quality = max(10, min(100, quality))
|
||||
|
||||
# Validate format
|
||||
format_map = {
|
||||
"PNG": ("png", "image/png"),
|
||||
"JPEG": ("jpg", "image/jpeg"),
|
||||
"WEBP": ("webp", "image/webp"),
|
||||
}
|
||||
if output_format not in format_map:
|
||||
return jsonify({"success": False, "error": f"Unsupported format: {output_format}"}), 400
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(image_file.read()))
|
||||
|
||||
# Convert to RGB for JPEG (no alpha)
|
||||
if output_format == "JPEG" and img.mode in ("RGBA", "LA", "P"):
|
||||
img = img.convert("RGB")
|
||||
|
||||
buffer = io.BytesIO()
|
||||
save_kwargs = {"format": output_format}
|
||||
if output_format in ("JPEG", "WEBP"):
|
||||
save_kwargs["quality"] = quality
|
||||
img.save(buffer, **save_kwargs)
|
||||
buffer.seek(0)
|
||||
|
||||
ext, mimetype = format_map[output_format]
|
||||
stem = (
|
||||
image_file.filename.rsplit(".", 1)[0]
|
||||
if "." in image_file.filename
|
||||
else image_file.filename
|
||||
)
|
||||
return send_file(
|
||||
buffer,
|
||||
mimetype=mimetype,
|
||||
as_attachment=True,
|
||||
download_name=f"{stem}.{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:
|
||||
|
||||
|
||||
@@ -2184,6 +2693,70 @@ def api_channel_key_use(key_id):
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@app.route("/admin/settings")
|
||||
@admin_required
|
||||
def admin_settings():
|
||||
"""System settings page (admin only)."""
|
||||
import platform
|
||||
import sys
|
||||
|
||||
from stegasoo import __version__
|
||||
from stegasoo.channel import get_channel_status
|
||||
|
||||
channel_status = get_channel_status()
|
||||
|
||||
return render_template(
|
||||
"admin/settings.html",
|
||||
# Channel info (key hidden until password verified)
|
||||
channel_configured=channel_status["configured"],
|
||||
channel_fingerprint=channel_status.get("fingerprint"),
|
||||
channel_source=channel_status.get("source"),
|
||||
# Server config
|
||||
hostname=os.environ.get("STEGASOO_HOSTNAME") or socket.gethostname(),
|
||||
port=os.environ.get("STEGASOO_PORT", "5000"),
|
||||
https_enabled=app.config.get("HTTPS_ENABLED", False),
|
||||
auth_enabled=app.config.get("AUTH_ENABLED", True),
|
||||
max_payload_kb=MAX_FILE_PAYLOAD_SIZE // 1024,
|
||||
max_upload_mb=MAX_FILE_SIZE // (1024 * 1024),
|
||||
dct_available=has_dct_support(),
|
||||
qr_available=HAS_QRCODE_READ,
|
||||
# Environment
|
||||
version=__version__,
|
||||
python_version=f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
platform=platform.system(),
|
||||
kdf_type="Argon2id" if has_argon2() else "PBKDF2",
|
||||
)
|
||||
|
||||
|
||||
@app.route("/admin/settings/unlock", methods=["POST"])
|
||||
@admin_required
|
||||
def admin_settings_unlock():
|
||||
"""Verify password and return channel key (AJAX)."""
|
||||
from stegasoo.channel import get_channel_status
|
||||
|
||||
data = request.get_json() or {}
|
||||
password = data.get("password", "")
|
||||
|
||||
if not password:
|
||||
return jsonify({"success": False, "error": "Password required"})
|
||||
|
||||
# Get current user and verify password
|
||||
username = get_username()
|
||||
user = verify_user_password(username, password)
|
||||
|
||||
if not user:
|
||||
return jsonify({"success": False, "error": "Incorrect password"})
|
||||
|
||||
# Password verified - return channel key
|
||||
channel_status = get_channel_status()
|
||||
channel_key = channel_status.get("key") if channel_status["configured"] else ""
|
||||
|
||||
return jsonify({
|
||||
"success": True,
|
||||
"channel_key": channel_key
|
||||
})
|
||||
|
||||
|
||||
@app.route("/admin/users")
|
||||
@admin_required
|
||||
def admin_users():
|
||||
@@ -2314,7 +2887,8 @@ if __name__ == "__main__":
|
||||
# HTTPS configuration
|
||||
ssl_context = None
|
||||
if app.config.get("HTTPS_ENABLED", False):
|
||||
hostname = os.environ.get("STEGASOO_HOSTNAME", "localhost")
|
||||
import socket
|
||||
hostname = os.environ.get("STEGASOO_HOSTNAME") or socket.gethostname()
|
||||
try:
|
||||
cert_path, key_path = ensure_certs(base_dir, hostname)
|
||||
if cert_path.exists() and key_path.exists():
|
||||
|
||||
52
frontends/web/dev_run.sh
Executable file
52
frontends/web/dev_run.sh
Executable file
@@ -0,0 +1,52 @@
|
||||
#!/bin/bash
|
||||
# Stegasoo Web Frontend - Development Runner
|
||||
# Press 'r' to restart, 'q' to quit (single keypress, no Enter needed)
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
PID=""
|
||||
|
||||
cleanup() {
|
||||
echo -e "\n\033[33mShutting down...\033[0m"
|
||||
[[ -n "$PID" ]] && kill "$PID" 2>/dev/null
|
||||
stty sane 2>/dev/null
|
||||
exit 0
|
||||
}
|
||||
|
||||
trap cleanup SIGINT SIGTERM EXIT
|
||||
|
||||
start_server() {
|
||||
clear
|
||||
echo -e "\033[36m┌──────────────────────────────────────┐\033[0m"
|
||||
echo -e "\033[36m│ Stegasoo Dev Server │\033[0m"
|
||||
echo -e "\033[36m│ \033[0m[r] restart [q] quit\033[36m │\033[0m"
|
||||
echo -e "\033[36m└──────────────────────────────────────┘\033[0m"
|
||||
|
||||
pkill -f "python app.py" 2>/dev/null
|
||||
sleep 0.3
|
||||
|
||||
python app.py 2>&1 &
|
||||
PID=$!
|
||||
echo -e "\033[32m✓ Running on http://localhost:5000 (PID: $PID)\033[0m\n"
|
||||
}
|
||||
|
||||
start_server
|
||||
|
||||
# Single keypress mode
|
||||
stty -echo -icanon time 0 min 0
|
||||
|
||||
while true; do
|
||||
key=$(dd bs=1 count=1 2>/dev/null)
|
||||
case "$key" in
|
||||
r|R) start_server ;;
|
||||
q|Q) cleanup ;;
|
||||
esac
|
||||
|
||||
# Check if crashed
|
||||
if [[ -n "$PID" ]] && ! kill -0 "$PID" 2>/dev/null; then
|
||||
echo -e "\033[31m✗ Crashed! Press 'r' to restart\033[0m"
|
||||
PID=""
|
||||
fi
|
||||
|
||||
sleep 0.1
|
||||
done
|
||||
@@ -7,6 +7,7 @@ Uses cryptography library (already a dependency).
|
||||
|
||||
import datetime
|
||||
import ipaddress
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography import x509
|
||||
@@ -15,6 +16,33 @@ from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.x509.oid import NameOID
|
||||
|
||||
|
||||
def _get_local_ips() -> list[str]:
|
||||
"""Get local IP addresses for this machine."""
|
||||
ips = []
|
||||
try:
|
||||
# Get hostname and resolve to IP
|
||||
hostname = socket.gethostname()
|
||||
for addr_info in socket.getaddrinfo(hostname, None, socket.AF_INET):
|
||||
ip = addr_info[4][0]
|
||||
if ip not in ips and not ip.startswith("127."):
|
||||
ips.append(ip)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Also try connecting to external to get primary interface IP
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(("8.8.8.8", 80))
|
||||
ip = s.getsockname()[0]
|
||||
if ip not in ips:
|
||||
ips.append(ip)
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return ips
|
||||
|
||||
|
||||
def get_cert_paths(base_dir: Path) -> tuple[Path, Path]:
|
||||
"""Get paths for cert and key files."""
|
||||
cert_dir = base_dir / "certs"
|
||||
@@ -64,12 +92,26 @@ def generate_self_signed_cert(
|
||||
x509.DNSName("localhost"),
|
||||
x509.IPAddress(ipaddress.IPv4Address("127.0.0.1")),
|
||||
]
|
||||
|
||||
# Add hostname.local for mDNS access
|
||||
if not hostname.endswith(".local"):
|
||||
san_list.append(x509.DNSName(f"{hostname}.local"))
|
||||
|
||||
# Add the hostname as IP if it looks like one
|
||||
try:
|
||||
san_list.append(x509.IPAddress(ipaddress.IPv4Address(hostname)))
|
||||
except ipaddress.AddressValueError:
|
||||
pass
|
||||
|
||||
# Add local network IPs
|
||||
for local_ip in _get_local_ips():
|
||||
try:
|
||||
ip_addr = ipaddress.IPv4Address(local_ip)
|
||||
if x509.IPAddress(ip_addr) not in san_list:
|
||||
san_list.append(x509.IPAddress(ip_addr))
|
||||
except (ipaddress.AddressValueError, ValueError):
|
||||
pass
|
||||
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
|
||||
@@ -231,20 +231,14 @@ const StegasooGenerate = {
|
||||
printWindow.document.write(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Stegasoo RSA Key QR Code</title>
|
||||
<title>QR Code</title>
|
||||
<style>
|
||||
body { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; margin: 0; font-family: sans-serif; }
|
||||
body { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; margin: 0; }
|
||||
img { max-width: 400px; }
|
||||
.warning { margin-top: 20px; padding: 10px; border: 2px solid #ff9800; background: #fff3e0; max-width: 400px; text-align: center; font-size: 12px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>Stegasoo RSA Private Key</h2>
|
||||
<img src="${qrImg.src}" alt="RSA Key QR Code">
|
||||
<div class="warning">
|
||||
<strong>Warning:</strong> This QR code contains your unencrypted RSA private key.
|
||||
Store securely and destroy after use.
|
||||
</div>
|
||||
<img src="${qrImg.src}" alt="QR Code">
|
||||
<script>window.onload = function() { window.print(); }<\/script>
|
||||
</body>
|
||||
</html>`);
|
||||
|
||||
6
frontends/web/static/js/qrcode.min.js
vendored
Normal file
6
frontends/web/static/js/qrcode.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -333,56 +333,68 @@ const Stegasoo = {
|
||||
generateEmbedTraces(container, width, height) {
|
||||
// Color classes for variety
|
||||
const colors = ['color-yellow', 'color-cyan', 'color-purple', 'color-blue'];
|
||||
|
||||
// Generate 6-8 snake paths spread across the whole image
|
||||
const numPaths = 6 + Math.floor(Math.random() * 3);
|
||||
|
||||
for (let p = 0; p < numPaths; p++) {
|
||||
// Each path gets a random color
|
||||
const pathColor = colors[Math.floor(Math.random() * colors.length)];
|
||||
|
||||
// Distribute starting points across the image
|
||||
let x = (width * 0.1) + (Math.random() * width * 0.8);
|
||||
let y = (height * 0.1) + (Math.random() * height * 0.8);
|
||||
let delay = p * 40;
|
||||
|
||||
// Each path has 3-5 segments for more coverage
|
||||
const numSegments = 3 + Math.floor(Math.random() * 3);
|
||||
let horizontal = Math.random() > 0.5;
|
||||
|
||||
for (let s = 0; s < numSegments; s++) {
|
||||
const trace = document.createElement('div');
|
||||
trace.className = 'embed-trace ' + (horizontal ? 'h' : 'v') + ' ' + pathColor;
|
||||
|
||||
const length = 30 + Math.random() * 60;
|
||||
trace.style.left = x + 'px';
|
||||
trace.style.top = y + 'px';
|
||||
trace.style.animationDelay = delay + 'ms';
|
||||
|
||||
if (horizontal) {
|
||||
trace.style.width = length + 'px';
|
||||
} else {
|
||||
trace.style.height = length + 'px';
|
||||
|
||||
// Grid-based distribution: divide image into cells for even coverage
|
||||
const gridCols = 5;
|
||||
const gridRows = 4;
|
||||
const cellWidth = width / gridCols;
|
||||
const cellHeight = height / gridRows;
|
||||
|
||||
let pathIndex = 0;
|
||||
|
||||
// Spawn 1-2 paths from each grid cell for even distribution
|
||||
for (let row = 0; row < gridRows; row++) {
|
||||
for (let col = 0; col < gridCols; col++) {
|
||||
// 1-2 paths per cell
|
||||
const pathsInCell = 1 + Math.floor(Math.random() * 2);
|
||||
|
||||
for (let p = 0; p < pathsInCell; p++) {
|
||||
const pathColor = colors[Math.floor(Math.random() * colors.length)];
|
||||
|
||||
// Start within this grid cell (with padding)
|
||||
let x = (col * cellWidth) + (cellWidth * 0.15) + (Math.random() * cellWidth * 0.7);
|
||||
let y = (row * cellHeight) + (cellHeight * 0.15) + (Math.random() * cellHeight * 0.7);
|
||||
let delay = pathIndex * 15;
|
||||
|
||||
// Each path has 3-5 short segments
|
||||
const numSegments = 3 + Math.floor(Math.random() * 3);
|
||||
let horizontal = Math.random() > 0.5;
|
||||
|
||||
for (let s = 0; s < numSegments; s++) {
|
||||
const trace = document.createElement('div');
|
||||
trace.className = 'embed-trace ' + (horizontal ? 'h' : 'v') + ' ' + pathColor;
|
||||
|
||||
// Shorter segments: 12-30px for denser circuit look
|
||||
const length = 12 + Math.random() * 18;
|
||||
trace.style.left = Math.max(0, Math.min(x, width - length)) + 'px';
|
||||
trace.style.top = Math.max(0, Math.min(y, height - length)) + 'px';
|
||||
trace.style.animationDelay = delay + 'ms';
|
||||
|
||||
if (horizontal) {
|
||||
trace.style.width = length + 'px';
|
||||
} else {
|
||||
trace.style.height = length + 'px';
|
||||
}
|
||||
|
||||
container.appendChild(trace);
|
||||
|
||||
// Move position for next segment
|
||||
if (horizontal) {
|
||||
x += length * (Math.random() > 0.5 ? 1 : -1);
|
||||
} else {
|
||||
y += length * (Math.random() > 0.5 ? 1 : -1);
|
||||
}
|
||||
|
||||
// Keep within bounds
|
||||
x = Math.max(5, Math.min(x, width - 20));
|
||||
y = Math.max(5, Math.min(y, height - 20));
|
||||
|
||||
// Alternate direction (90 degree turn)
|
||||
horizontal = !horizontal;
|
||||
delay += 20;
|
||||
}
|
||||
pathIndex++;
|
||||
}
|
||||
|
||||
container.appendChild(trace);
|
||||
|
||||
// Move position for next segment
|
||||
if (horizontal) {
|
||||
x += length;
|
||||
} else {
|
||||
y += length;
|
||||
}
|
||||
|
||||
// Wrap around if out of bounds to keep traces in view
|
||||
if (x > width - 20) x = 10 + Math.random() * 40;
|
||||
if (y > height - 20) y = 10 + Math.random() * 40;
|
||||
if (x < 10) x = width - 60 + Math.random() * 40;
|
||||
if (y < 10) y = height - 60 + Math.random() * 40;
|
||||
|
||||
// Alternate direction (90 degree turn)
|
||||
horizontal = !horizontal;
|
||||
delay += 30;
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1090,6 +1102,400 @@ const Stegasoo = {
|
||||
if (phaseText) phaseText.textContent = phase;
|
||||
},
|
||||
|
||||
// ========================================================================
|
||||
// ASYNC DECODE WITH PROGRESS (v4.1.5)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Submit decode form asynchronously with progress tracking
|
||||
* @param {HTMLFormElement} form - The decode form
|
||||
* @param {HTMLElement} btn - The submit button
|
||||
*/
|
||||
async submitDecodeAsync(form, btn) {
|
||||
const formData = new FormData(form);
|
||||
formData.append('async', 'true');
|
||||
|
||||
// Show progress modal
|
||||
this.showProgressModal('Decoding');
|
||||
|
||||
try {
|
||||
// Start decode job
|
||||
const response = await fetch('/decode', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to start decode');
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
const jobId = result.job_id;
|
||||
|
||||
// Poll for progress
|
||||
await this.pollDecodeProgress(jobId);
|
||||
|
||||
} catch (error) {
|
||||
this.hideProgressModal();
|
||||
alert('Decode failed: ' + error.message);
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="bi bi-unlock-fill me-2"></i>Decode';
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Poll decode progress until complete
|
||||
* @param {string} jobId - The job ID
|
||||
*/
|
||||
async pollDecodeProgress(jobId) {
|
||||
const poll = async () => {
|
||||
try {
|
||||
// Check status first
|
||||
const statusResponse = await fetch(`/decode/status/${jobId}`);
|
||||
const statusData = await statusResponse.json();
|
||||
|
||||
if (statusData.status === 'complete') {
|
||||
// Done - redirect to result page
|
||||
this.updateProgress(100, 'Complete!');
|
||||
setTimeout(() => {
|
||||
window.location.href = `/decode/result/${jobId}`;
|
||||
}, 500);
|
||||
return;
|
||||
}
|
||||
|
||||
if (statusData.status === 'error') {
|
||||
// Handle specific error types
|
||||
const errorType = statusData.error_type;
|
||||
let errorMsg = statusData.error || 'Decode failed';
|
||||
|
||||
if (errorType === 'DecryptionError' || errorMsg.toLowerCase().includes('decrypt')) {
|
||||
errorMsg = 'Wrong credentials. Double-check your reference photo, passphrase, PIN, and channel key.';
|
||||
}
|
||||
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
// Get progress
|
||||
const progressResponse = await fetch(`/decode/progress/${jobId}`);
|
||||
const progressData = await progressResponse.json();
|
||||
|
||||
const percent = progressData.percent || 0;
|
||||
const phase = progressData.phase || 'processing';
|
||||
|
||||
this.updateProgress(percent, this.formatDecodePhase(phase));
|
||||
|
||||
// Continue polling
|
||||
setTimeout(poll, 500);
|
||||
|
||||
} catch (error) {
|
||||
this.hideProgressModal();
|
||||
alert(error.message);
|
||||
}
|
||||
};
|
||||
|
||||
await poll();
|
||||
},
|
||||
|
||||
/**
|
||||
* Format decode phase name for display
|
||||
*/
|
||||
formatDecodePhase(phase) {
|
||||
const phases = {
|
||||
'starting': 'Starting...',
|
||||
'reading': 'Reading image...',
|
||||
'extracting': 'Extracting data...',
|
||||
'decrypting': 'Decrypting...',
|
||||
'verifying': 'Verifying...',
|
||||
'finalizing': 'Finalizing...',
|
||||
'complete': 'Complete!',
|
||||
};
|
||||
return phases[phase] || phase;
|
||||
},
|
||||
|
||||
// ========================================================================
|
||||
// WEBCAM QR SCANNING (v4.1.5)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Active scanner instance
|
||||
*/
|
||||
_qrScanner: null,
|
||||
_qrScannerModal: null,
|
||||
_qrScannerCallback: null,
|
||||
|
||||
/**
|
||||
* Show webcam QR scanner modal
|
||||
* @param {Function} onSuccess - Callback with decoded QR text
|
||||
* @param {string} title - Modal title
|
||||
*/
|
||||
showQrScanner(onSuccess, title = 'Scan QR Code') {
|
||||
this._qrScannerCallback = onSuccess;
|
||||
|
||||
// Create modal if doesn't exist
|
||||
let modal = document.getElementById('qrScannerModal');
|
||||
if (!modal) {
|
||||
modal = document.createElement('div');
|
||||
modal.id = 'qrScannerModal';
|
||||
modal.className = 'modal fade';
|
||||
modal.innerHTML = `
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content bg-dark text-light">
|
||||
<div class="modal-header border-secondary">
|
||||
<h5 class="modal-title">
|
||||
<i class="bi bi-camera-video me-2"></i>
|
||||
<span id="qrScannerTitle">${title}</span>
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body p-0">
|
||||
<div id="qrScannerReader" style="width: 100%;"></div>
|
||||
<div id="qrScannerStatus" class="text-center py-3 text-muted">
|
||||
<i class="bi bi-qr-code-scan me-2"></i>
|
||||
Point camera at QR code
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer border-secondary">
|
||||
<button type="button" class="btn btn-primary" id="qrCaptureBtn">
|
||||
<i class="bi bi-camera me-1"></i>Capture
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(modal);
|
||||
|
||||
// Clean up scanner when modal hides
|
||||
modal.addEventListener('hidden.bs.modal', () => {
|
||||
this.stopQrScanner();
|
||||
});
|
||||
|
||||
// Manual capture button
|
||||
modal.querySelector('#qrCaptureBtn')?.addEventListener('click', () => {
|
||||
this.captureQrFrame();
|
||||
});
|
||||
}
|
||||
|
||||
// Update title
|
||||
const titleEl = modal.querySelector('#qrScannerTitle');
|
||||
if (titleEl) titleEl.textContent = title;
|
||||
|
||||
// Reset status
|
||||
const statusEl = modal.querySelector('#qrScannerStatus');
|
||||
if (statusEl) {
|
||||
statusEl.innerHTML = '<i class="bi bi-qr-code-scan me-2"></i>Point camera at QR code';
|
||||
statusEl.className = 'text-center py-3 text-muted';
|
||||
}
|
||||
|
||||
// Show modal
|
||||
this._qrScannerModal = new bootstrap.Modal(modal);
|
||||
this._qrScannerModal.show();
|
||||
|
||||
// Start scanner after modal is shown
|
||||
modal.addEventListener('shown.bs.modal', () => {
|
||||
this.startQrScanner();
|
||||
}, { once: true });
|
||||
},
|
||||
|
||||
/**
|
||||
* Start the QR scanner
|
||||
*/
|
||||
startQrScanner() {
|
||||
const readerEl = document.getElementById('qrScannerReader');
|
||||
if (!readerEl) return;
|
||||
|
||||
// Check if Html5Qrcode is available
|
||||
if (typeof Html5Qrcode === 'undefined') {
|
||||
console.error('Html5Qrcode library not loaded');
|
||||
const statusEl = document.getElementById('qrScannerStatus');
|
||||
if (statusEl) {
|
||||
statusEl.innerHTML = '<i class="bi bi-exclamation-triangle text-warning me-2"></i>QR scanner not available';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this._qrScanner = new Html5Qrcode('qrScannerReader');
|
||||
|
||||
const config = {
|
||||
fps: 10,
|
||||
qrbox: { width: 250, height: 250 },
|
||||
aspectRatio: 1.0,
|
||||
};
|
||||
|
||||
this._qrScanner.start(
|
||||
{ facingMode: 'environment' }, // Prefer back camera
|
||||
config,
|
||||
(decodedText, decodedResult) => {
|
||||
// QR code detected
|
||||
this.onQrCodeDetected(decodedText);
|
||||
},
|
||||
(errorMessage) => {
|
||||
// Scan error (ignore, keep scanning)
|
||||
}
|
||||
).catch((err) => {
|
||||
console.error('Failed to start scanner:', err);
|
||||
const statusEl = document.getElementById('qrScannerStatus');
|
||||
if (statusEl) {
|
||||
if (err.toString().includes('Permission')) {
|
||||
statusEl.innerHTML = '<i class="bi bi-camera-video-off text-danger me-2"></i>Camera permission denied';
|
||||
} else {
|
||||
statusEl.innerHTML = '<i class="bi bi-exclamation-triangle text-warning me-2"></i>Could not access camera';
|
||||
}
|
||||
statusEl.className = 'text-center py-3';
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Capture a frame with countdown and try to decode
|
||||
*/
|
||||
captureQrFrame() {
|
||||
const statusEl = document.getElementById('qrScannerStatus');
|
||||
const captureBtn = document.getElementById('qrCaptureBtn');
|
||||
if (!statusEl || !this._qrScanner) return;
|
||||
|
||||
// Disable button during countdown
|
||||
if (captureBtn) captureBtn.disabled = true;
|
||||
|
||||
let count = 3;
|
||||
const countdown = () => {
|
||||
if (count > 0) {
|
||||
statusEl.innerHTML = `<i class="bi bi-camera me-2"></i><span style="font-size: 1.5rem; font-weight: bold;">${count}</span>`;
|
||||
statusEl.className = 'text-center py-3 text-warning';
|
||||
count--;
|
||||
setTimeout(countdown, 1000);
|
||||
} else {
|
||||
// Capture!
|
||||
statusEl.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Analyzing...';
|
||||
statusEl.className = 'text-center py-3 text-info';
|
||||
|
||||
// Get video element and capture frame
|
||||
const video = document.querySelector('#qrScannerReader video');
|
||||
if (video) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(video, 0, 0);
|
||||
|
||||
// Stop the scanner before file scan (prevents conflicts)
|
||||
const scanner = this._qrScanner;
|
||||
scanner.stop().then(() => {
|
||||
canvas.toBlob((blob) => {
|
||||
const file = new File([blob], 'capture.png', { type: 'image/png' });
|
||||
scanner.scanFile(file, true)
|
||||
.then((decodedText) => {
|
||||
this.onQrCodeDetected(decodedText);
|
||||
})
|
||||
.catch((err) => {
|
||||
statusEl.innerHTML = '<i class="bi bi-x-circle text-danger me-2"></i>No QR code found. Try again.';
|
||||
statusEl.className = 'text-center py-3 text-danger';
|
||||
if (captureBtn) captureBtn.disabled = false;
|
||||
// Restart the scanner
|
||||
this.startQrScanner();
|
||||
});
|
||||
}, 'image/png');
|
||||
}).catch(() => {
|
||||
statusEl.innerHTML = '<i class="bi bi-x-circle text-danger me-2"></i>Scanner error';
|
||||
statusEl.className = 'text-center py-3 text-danger';
|
||||
if (captureBtn) captureBtn.disabled = false;
|
||||
});
|
||||
} else {
|
||||
statusEl.innerHTML = '<i class="bi bi-x-circle text-danger me-2"></i>Camera not ready';
|
||||
statusEl.className = 'text-center py-3 text-danger';
|
||||
if (captureBtn) captureBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
countdown();
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop the QR scanner
|
||||
*/
|
||||
stopQrScanner() {
|
||||
if (this._qrScanner) {
|
||||
this._qrScanner.stop().then(() => {
|
||||
this._qrScanner.clear();
|
||||
this._qrScanner = null;
|
||||
}).catch((err) => {
|
||||
console.log('Scanner stop error:', err);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle detected QR code
|
||||
* @param {string} text - Decoded QR text
|
||||
*/
|
||||
onQrCodeDetected(text) {
|
||||
// Update status
|
||||
const statusEl = document.getElementById('qrScannerStatus');
|
||||
if (statusEl) {
|
||||
statusEl.innerHTML = '<i class="bi bi-check-circle text-success me-2"></i>QR code detected!';
|
||||
statusEl.className = 'text-center py-3 text-success';
|
||||
}
|
||||
|
||||
// Close modal after brief delay
|
||||
setTimeout(() => {
|
||||
this._qrScannerModal?.hide();
|
||||
|
||||
// Call callback
|
||||
if (this._qrScannerCallback) {
|
||||
this._qrScannerCallback(text);
|
||||
}
|
||||
}, 500);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add camera scan button to an input field
|
||||
* @param {string} inputId - ID of the input field
|
||||
* @param {string} title - Modal title
|
||||
* @param {Function} validator - Optional validation function for scanned text
|
||||
*/
|
||||
addCameraScanButton(inputId, title = 'Scan QR Code', validator = null) {
|
||||
const input = document.getElementById(inputId);
|
||||
if (!input) return;
|
||||
|
||||
// Create button
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'btn btn-outline-secondary';
|
||||
btn.innerHTML = '<i class="bi bi-camera"></i>';
|
||||
btn.title = 'Scan QR code with camera';
|
||||
|
||||
btn.addEventListener('click', () => {
|
||||
this.showQrScanner((text) => {
|
||||
// Validate if validator provided
|
||||
if (validator && !validator(text)) {
|
||||
alert('Invalid QR code format');
|
||||
return;
|
||||
}
|
||||
// Set input value
|
||||
input.value = text;
|
||||
// Trigger input event for formatting
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}, title);
|
||||
});
|
||||
|
||||
// Wrap input in input-group if not already
|
||||
const parent = input.parentElement;
|
||||
if (!parent.classList.contains('input-group')) {
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'input-group';
|
||||
parent.insertBefore(wrapper, input);
|
||||
wrapper.appendChild(input);
|
||||
wrapper.appendChild(btn);
|
||||
} else {
|
||||
parent.appendChild(btn);
|
||||
}
|
||||
},
|
||||
|
||||
// ========================================================================
|
||||
// INITIALIZATION HELPERS
|
||||
// ========================================================================
|
||||
@@ -1111,6 +1517,39 @@ const Stegasoo = {
|
||||
generateBtnId: 'channelKeyGenerate'
|
||||
});
|
||||
|
||||
// Webcam QR scanning for channel key (v4.1.5)
|
||||
document.getElementById('channelKeyScan')?.addEventListener('click', () => {
|
||||
this.showQrScanner((text) => {
|
||||
const input = document.getElementById('channelKeyInput');
|
||||
if (input) {
|
||||
const clean = text.replace(/[^A-Za-z0-9]/g, '').toUpperCase();
|
||||
input.value = clean.length === 32 ? clean.match(/.{4}/g).join('-') : text.toUpperCase();
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
}, 'Scan Channel Key');
|
||||
});
|
||||
|
||||
// Webcam QR scanning for RSA key (v4.1.5)
|
||||
document.getElementById('rsaQrWebcam')?.addEventListener('click', () => {
|
||||
this.showQrScanner((text) => {
|
||||
// Check for raw PEM or compressed format (STEGASOO-Z: prefix)
|
||||
const isRawPem = text.includes('-----BEGIN') && text.includes('KEY-----');
|
||||
const isCompressed = text.startsWith('STEGASOO-Z:');
|
||||
if (isRawPem || isCompressed) {
|
||||
// Valid RSA key data scanned
|
||||
document.getElementById('rsaKeyPem').value = text;
|
||||
// Show success in drop zone
|
||||
const dropZone = document.getElementById('qrDropZone');
|
||||
const label = dropZone?.querySelector('.drop-zone-label');
|
||||
if (label) {
|
||||
label.innerHTML = '<i class="bi bi-check-circle text-success fs-4 d-block mb-1"></i><span class="text-success small">RSA Key scanned successfully</span>';
|
||||
}
|
||||
} else {
|
||||
alert('QR code does not contain a valid RSA key');
|
||||
}
|
||||
}, 'Scan RSA Key QR');
|
||||
});
|
||||
|
||||
// Form submission with async progress tracking (v4.1.2)
|
||||
const form = document.getElementById('encodeForm');
|
||||
const btn = document.getElementById('encodeBtn');
|
||||
@@ -1136,7 +1575,7 @@ const Stegasoo = {
|
||||
this.initRsaMethodToggle();
|
||||
this.initDropZones();
|
||||
this.initClipboardPaste(['input[name="stego_image"]', 'input[name="reference_photo"]']);
|
||||
this.initQrCropAnimation('rsaKeyQrInput');
|
||||
this.initQrCropAnimation('rsaQrInput');
|
||||
this.initCollapseChevrons();
|
||||
this.initPassphraseFontResize();
|
||||
|
||||
@@ -1148,28 +1587,56 @@ const Stegasoo = {
|
||||
serverInfoId: 'channelServerInfoDec'
|
||||
});
|
||||
|
||||
// Form submission with channel key validation and mode display
|
||||
// Webcam QR scanning for channel key (v4.1.5)
|
||||
document.getElementById('channelKeyScanDec')?.addEventListener('click', () => {
|
||||
this.showQrScanner((text) => {
|
||||
const input = document.getElementById('channelKeyInputDec');
|
||||
if (input) {
|
||||
const clean = text.replace(/[^A-Za-z0-9]/g, '').toUpperCase();
|
||||
input.value = clean.length === 32 ? clean.match(/.{4}/g).join('-') : text.toUpperCase();
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
}, 'Scan Channel Key');
|
||||
});
|
||||
|
||||
// Webcam QR scanning for RSA key (v4.1.5)
|
||||
document.getElementById('rsaQrWebcam')?.addEventListener('click', () => {
|
||||
this.showQrScanner((text) => {
|
||||
// Check for raw PEM or compressed format (STEGASOO-Z: prefix)
|
||||
const isRawPem = text.includes('-----BEGIN') && text.includes('KEY-----');
|
||||
const isCompressed = text.startsWith('STEGASOO-Z:');
|
||||
if (isRawPem || isCompressed) {
|
||||
// Valid RSA key data scanned
|
||||
document.getElementById('rsaKeyPem').value = text;
|
||||
// Show success in drop zone
|
||||
const dropZone = document.getElementById('qrDropZone');
|
||||
const label = dropZone?.querySelector('.drop-zone-label');
|
||||
if (label) {
|
||||
label.innerHTML = '<i class="bi bi-check-circle text-success fs-4 d-block mb-1"></i><span class="text-success small">RSA Key scanned successfully</span>';
|
||||
}
|
||||
} else {
|
||||
alert('QR code does not contain a valid RSA key');
|
||||
}
|
||||
}, 'Scan RSA Key QR');
|
||||
});
|
||||
|
||||
// Form submission with async progress tracking (v4.1.5)
|
||||
const form = document.getElementById('decodeForm');
|
||||
const btn = document.getElementById('decodeBtn');
|
||||
form?.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!this.validateChannelKeyOnSubmit(form, 'channelSelectDec', 'channelKeyInputDec')) {
|
||||
e.preventDefault();
|
||||
return false;
|
||||
}
|
||||
const selectedMode = document.querySelector('input[name="embed_mode"]:checked')?.value || 'auto';
|
||||
|
||||
if (btn) {
|
||||
btn.disabled = true;
|
||||
const startTime = Date.now();
|
||||
const updateTimer = () => {
|
||||
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
||||
const mins = Math.floor(elapsed / 60);
|
||||
const secs = elapsed % 60;
|
||||
const timeStr = mins > 0 ? `${mins}:${secs.toString().padStart(2, '0')}` : `${secs}s`;
|
||||
btn.innerHTML = `<span class="spinner-border spinner-border-sm me-2"></span>Decoding (${selectedMode.toUpperCase()})... ${timeStr}`;
|
||||
};
|
||||
updateTimer();
|
||||
setInterval(updateTimer, 1000);
|
||||
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Starting...';
|
||||
}
|
||||
|
||||
// Use async submission with progress tracking
|
||||
this.submitDecodeAsync(form, btn);
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
@@ -91,6 +91,31 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Compact inline mode buttons */
|
||||
.mode-btn.mode-btn-sm {
|
||||
padding: 0.35rem 0.6rem;
|
||||
padding-left: 1.75rem;
|
||||
font-size: 0.8rem;
|
||||
border-radius: 0.375rem;
|
||||
border-width: 1px;
|
||||
}
|
||||
|
||||
.mode-btn.mode-btn-sm .form-check-input {
|
||||
left: 8px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.mode-btn.mode-btn-sm i {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* Disabled button labels for btn-check groups */
|
||||
.btn-check:disabled + .btn {
|
||||
opacity: 0.4;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
Security Factor Boxes - Matches drop-zone dashed border style
|
||||
---------------------------------------------------------------------------- */
|
||||
@@ -125,6 +150,115 @@ body {
|
||||
.navbar {
|
||||
background: var(--overlay-dark) !important;
|
||||
backdrop-filter: blur(10px);
|
||||
z-index: 1030; /* Above page content for dropdowns */
|
||||
}
|
||||
|
||||
/* Ensure navbar dropdown appears above all page content */
|
||||
.navbar .dropdown-menu {
|
||||
z-index: 1031;
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
Nav Icons - Floating Label on Hover (label floats below, no layout shift)
|
||||
---------------------------------------------------------------------------- */
|
||||
.nav-icons {
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.nav-icons .nav-item {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.nav-expand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.5rem 0.75rem !important;
|
||||
border-radius: 0.5rem;
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
background: transparent;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.nav-expand i {
|
||||
font-size: 1.15rem;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
/* Floating label - absolutely positioned below */
|
||||
.nav-expand span {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 50%;
|
||||
transform: translateX(-50%) translateY(-4px);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
white-space: nowrap;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
color: var(--header-gold);
|
||||
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
|
||||
background: linear-gradient(135deg, rgba(74, 40, 96, 0.95) 0%, rgba(85, 112, 212, 0.9) 100%);
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
transition: opacity 0.2s ease,
|
||||
transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
z-index: 1040;
|
||||
}
|
||||
|
||||
.nav-expand:hover {
|
||||
background: linear-gradient(135deg, rgba(74, 40, 96, 0.5) 0%, rgba(85, 112, 212, 0.4) 100%);
|
||||
box-shadow: 0 0 12px rgba(102, 126, 234, 0.25),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.nav-expand:hover i {
|
||||
color: var(--header-gold);
|
||||
filter: drop-shadow(0 0 4px rgba(254, 232, 98, 0.4));
|
||||
}
|
||||
|
||||
.nav-expand:hover span {
|
||||
opacity: 1;
|
||||
transform: translateX(-50%) translateY(2px);
|
||||
}
|
||||
|
||||
/* Active state for current page */
|
||||
.nav-expand.active,
|
||||
.nav-item.active .nav-expand {
|
||||
background: linear-gradient(135deg, rgba(74, 40, 96, 0.6) 0%, rgba(85, 112, 212, 0.5) 100%);
|
||||
}
|
||||
|
||||
.nav-expand.active i,
|
||||
.nav-item.active .nav-expand i {
|
||||
color: var(--header-gold);
|
||||
}
|
||||
|
||||
/* Mobile: Always show labels inline in collapsed menu */
|
||||
@media (max-width: 991.98px) {
|
||||
.nav-expand span {
|
||||
position: static;
|
||||
transform: none;
|
||||
opacity: 1;
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
padding: 0;
|
||||
margin-left: 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
text-transform: none;
|
||||
letter-spacing: normal;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.nav-expand:hover span {
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.nav-expand:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
@@ -893,36 +1027,36 @@ footer {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* Color variants - 60% opacity */
|
||||
/* Color variants - 70% opacity with tighter glow for thin lines */
|
||||
.embed-trace.color-yellow {
|
||||
background: rgba(212, 225, 87, 0.6);
|
||||
box-shadow: 0 0 6px rgba(212, 225, 87, 0.5), 0 0 12px rgba(212, 225, 87, 0.3);
|
||||
background: rgba(212, 225, 87, 0.7);
|
||||
box-shadow: 0 0 3px rgba(212, 225, 87, 0.6), 0 0 6px rgba(212, 225, 87, 0.3);
|
||||
}
|
||||
|
||||
.embed-trace.color-cyan {
|
||||
background: rgba(0, 255, 170, 0.6);
|
||||
box-shadow: 0 0 6px rgba(0, 255, 170, 0.5), 0 0 12px rgba(0, 255, 170, 0.3);
|
||||
background: rgba(0, 255, 170, 0.7);
|
||||
box-shadow: 0 0 3px rgba(0, 255, 170, 0.6), 0 0 6px rgba(0, 255, 170, 0.3);
|
||||
}
|
||||
|
||||
.embed-trace.color-purple {
|
||||
background: rgba(167, 139, 250, 0.6);
|
||||
box-shadow: 0 0 6px rgba(167, 139, 250, 0.5), 0 0 12px rgba(167, 139, 250, 0.3);
|
||||
background: rgba(167, 139, 250, 0.7);
|
||||
box-shadow: 0 0 3px rgba(167, 139, 250, 0.6), 0 0 6px rgba(167, 139, 250, 0.3);
|
||||
}
|
||||
|
||||
.embed-trace.color-blue {
|
||||
background: rgba(102, 126, 234, 0.6);
|
||||
box-shadow: 0 0 6px rgba(102, 126, 234, 0.5), 0 0 12px rgba(102, 126, 234, 0.3);
|
||||
background: rgba(102, 126, 234, 0.7);
|
||||
box-shadow: 0 0 3px rgba(102, 126, 234, 0.6), 0 0 6px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
/* Vertical segments shrink from top */
|
||||
.embed-trace.v {
|
||||
width: 2px;
|
||||
width: 1px;
|
||||
transform-origin: top center;
|
||||
}
|
||||
|
||||
/* Horizontal segments shrink from left */
|
||||
.embed-trace.h {
|
||||
height: 2px;
|
||||
height: 1px;
|
||||
transform-origin: left center;
|
||||
}
|
||||
|
||||
@@ -1699,3 +1833,456 @@ footer {
|
||||
font-size: 3rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================================================
|
||||
TOOLS PAGE - Office-style Ribbon + Two-Panel Layout
|
||||
============================================================================ */
|
||||
|
||||
/* Icon Toolbar Ribbon - Purple/Blue Gradient Theme */
|
||||
.tools-ribbon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(139, 92, 246, 0.15) 100%);
|
||||
border-bottom: 1px solid rgba(139, 92, 246, 0.2);
|
||||
border-radius: 0.5rem 0.5rem 0 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.tools-ribbon-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.tools-ribbon-divider {
|
||||
width: 2px;
|
||||
height: 32px;
|
||||
background: linear-gradient(180deg, rgba(102, 126, 234, 0.4) 0%, rgba(139, 92, 246, 0.4) 100%);
|
||||
margin: 0 0.75rem;
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
/* Tool Icon Buttons */
|
||||
.tool-icon-btn {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 52px;
|
||||
height: 48px;
|
||||
padding: 0.25rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 0.375rem;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.tool-icon-btn i {
|
||||
font-size: 1.25rem;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.tool-icon-btn span {
|
||||
font-size: 0.6rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.3px;
|
||||
}
|
||||
|
||||
.tool-icon-btn:hover {
|
||||
background: rgba(139, 92, 246, 0.15);
|
||||
border-color: rgba(139, 92, 246, 0.3);
|
||||
color: rgba(255, 255, 255, 0.95);
|
||||
}
|
||||
|
||||
.tool-icon-btn.active {
|
||||
background: linear-gradient(135deg, rgba(102, 126, 234, 0.25) 0%, rgba(139, 92, 246, 0.25) 100%);
|
||||
border-color: rgba(139, 92, 246, 0.5);
|
||||
color: #c4b5fd;
|
||||
box-shadow: 0 0 12px rgba(139, 92, 246, 0.2);
|
||||
}
|
||||
|
||||
/* Two-Panel Layout */
|
||||
.tools-panels {
|
||||
display: flex;
|
||||
min-height: 400px;
|
||||
border-radius: 0 0 0.5rem 0.5rem;
|
||||
}
|
||||
|
||||
/* Left Panel - Input/Dropzone */
|
||||
.tools-panel-input {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
border-right: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
/* Tool Mode Banner - bottom of input panel */
|
||||
.tool-mode-banner {
|
||||
margin-top: auto; /* Push to bottom */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.6rem 1.25rem;
|
||||
background: linear-gradient(135deg, rgba(102, 126, 234, 0.2) 0%, rgba(139, 92, 246, 0.2) 100%);
|
||||
border-top: 1px solid rgba(139, 92, 246, 0.2);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.tool-mode-type {
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
font-weight: 600;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 3px;
|
||||
background: rgba(139, 92, 246, 0.3);
|
||||
color: #c4b5fd;
|
||||
}
|
||||
|
||||
.tool-mode-banner.mode-analyze .tool-mode-type {
|
||||
background: rgba(72, 187, 120, 0.3);
|
||||
color: #9ae6b4;
|
||||
}
|
||||
|
||||
.tool-mode-banner.mode-transform .tool-mode-type {
|
||||
background: rgba(237, 181, 71, 0.3);
|
||||
color: #fbd38d;
|
||||
}
|
||||
|
||||
.tool-mode-name {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Right Panel - Results */
|
||||
.tools-panel-results {
|
||||
width: 280px;
|
||||
min-width: 280px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 1.25rem;
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
/* Tool Options Row */
|
||||
.tool-options {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.tool-options:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tool-options label {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.tool-options .form-select,
|
||||
.tool-options .form-control {
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border-color: rgba(255, 255, 255, 0.15);
|
||||
font-size: 0.85rem;
|
||||
padding: 0.4rem 0.75rem;
|
||||
}
|
||||
|
||||
/* Tool Drop Zone */
|
||||
.tool-dropzone {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 200px;
|
||||
border: 2px dashed rgba(255, 255, 255, 0.2);
|
||||
border-radius: 0.5rem;
|
||||
background: rgba(0, 0, 0, 0.15);
|
||||
transition: all 0.3s ease;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tool-dropzone input[type="file"] {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.tool-dropzone-label {
|
||||
text-align: center;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.tool-dropzone-label i {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
display: block;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.tool-dropzone.drag-over {
|
||||
border-color: #63b3ed;
|
||||
background: rgba(99, 179, 237, 0.1);
|
||||
}
|
||||
|
||||
.tool-dropzone.drag-over .tool-dropzone-label i {
|
||||
color: #63b3ed;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Dropzone with preview */
|
||||
.tool-dropzone.has-file .tool-dropzone-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tool-dropzone-preview {
|
||||
display: none;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.tool-dropzone.has-file .tool-dropzone-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.tool-dropzone-preview img {
|
||||
max-width: 100%;
|
||||
max-height: 180px;
|
||||
object-fit: contain;
|
||||
border-radius: 0.375rem;
|
||||
border: 2px solid rgba(99, 179, 237, 0.3);
|
||||
}
|
||||
|
||||
/* Rotate preview - smooth transitions for size and transform */
|
||||
#rotateThumb {
|
||||
transition: transform 0.1s ease-out, width 0.1s ease-out, height 0.1s ease-out;
|
||||
}
|
||||
|
||||
/* Rotate image container - fixed height to contain rotated images */
|
||||
.rotate-img-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 180px;
|
||||
}
|
||||
|
||||
/* Rotate file info - separate row below dropzone */
|
||||
.rotate-file-info {
|
||||
text-align: center;
|
||||
padding: 0.5rem 0;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.rotate-file-info .file-name {
|
||||
font-size: 0.85rem;
|
||||
color: #63b3ed;
|
||||
font-weight: 500;
|
||||
}
|
||||
.rotate-file-info .file-meta {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.tool-dropzone-preview .file-name {
|
||||
margin-top: 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
color: #63b3ed;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tool-dropzone-preview .file-meta {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.tool-dropzone-clear {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 20;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.tool-dropzone-clear:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Results Panel Content */
|
||||
.tool-results-header {
|
||||
margin-bottom: 1rem;
|
||||
padding-bottom: 0.75rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.tool-results-header h6 {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.tool-results-header small {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.tool-results-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.tool-results-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tool-results-empty i {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
/* Result Items */
|
||||
.tool-result-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
padding: 0.5rem 0;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.tool-result-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.tool-result-label {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.tool-result-value {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: #fff;
|
||||
font-family: 'SF Mono', 'Consolas', monospace;
|
||||
}
|
||||
|
||||
.tool-result-value.text-primary { color: #63b3ed !important; }
|
||||
.tool-result-value.text-success { color: #48bb78 !important; }
|
||||
.tool-result-value.text-warning { color: #edb547 !important; }
|
||||
|
||||
/* Results Actions */
|
||||
.tool-results-actions {
|
||||
margin-top: auto;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.tool-results-actions .btn {
|
||||
flex: 1;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* Tool Section Visibility */
|
||||
.tool-section {
|
||||
display: none;
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.tool-section.active {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* EXIF Table in Results */
|
||||
.tool-exif-table {
|
||||
font-size: 0.8rem;
|
||||
max-height: 250px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.tool-exif-table table {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tool-exif-table th,
|
||||
.tool-exif-table td {
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.tool-exif-table th {
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
text-align: left;
|
||||
width: 40%;
|
||||
}
|
||||
|
||||
.tool-exif-table td {
|
||||
font-family: 'SF Mono', 'Consolas', monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* Loading State */
|
||||
.tool-loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
z-index: 30;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
/* Mobile Responsive */
|
||||
@media (max-width: 768px) {
|
||||
.tools-panels {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.tools-panel-results {
|
||||
width: 100%;
|
||||
min-width: 100%;
|
||||
border-right: none;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.tools-ribbon {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.tool-icon-btn {
|
||||
width: 48px;
|
||||
height: 44px;
|
||||
}
|
||||
|
||||
.tool-icon-btn span {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
5
frontends/web/static/vendor/css/bootstrap-icons.min.css
vendored
Normal file
5
frontends/web/static/vendor/css/bootstrap-icons.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
6
frontends/web/static/vendor/css/bootstrap.min.css
vendored
Normal file
6
frontends/web/static/vendor/css/bootstrap.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
BIN
frontends/web/static/vendor/css/fonts/bootstrap-icons.woff
vendored
Normal file
BIN
frontends/web/static/vendor/css/fonts/bootstrap-icons.woff
vendored
Normal file
Binary file not shown.
BIN
frontends/web/static/vendor/css/fonts/bootstrap-icons.woff2
vendored
Normal file
BIN
frontends/web/static/vendor/css/fonts/bootstrap-icons.woff2
vendored
Normal file
Binary file not shown.
7
frontends/web/static/vendor/js/bootstrap.bundle.min.js
vendored
Normal file
7
frontends/web/static/vendor/js/bootstrap.bundle.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
frontends/web/static/vendor/js/html5-qrcode.min.js
vendored
Normal file
1
frontends/web/static/vendor/js/html5-qrcode.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -136,14 +136,33 @@ def encode_operation(params: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _write_decode_progress(progress_file: str | None, percent: int, phase: str) -> None:
|
||||
"""Write decode progress to file."""
|
||||
if not progress_file:
|
||||
return
|
||||
try:
|
||||
import json
|
||||
with open(progress_file, "w") as f:
|
||||
json.dump({"percent": percent, "phase": phase}, f)
|
||||
except Exception:
|
||||
pass # Best effort
|
||||
|
||||
|
||||
def decode_operation(params: dict) -> dict:
|
||||
"""Handle decode operation."""
|
||||
from stegasoo import decode
|
||||
|
||||
progress_file = params.get("progress_file")
|
||||
|
||||
# Progress: starting
|
||||
_write_decode_progress(progress_file, 5, "reading")
|
||||
|
||||
# Decode base64 inputs
|
||||
stego_data = base64.b64decode(params["stego_b64"])
|
||||
reference_data = base64.b64decode(params["reference_b64"])
|
||||
|
||||
_write_decode_progress(progress_file, 15, "reading")
|
||||
|
||||
# Optional RSA key
|
||||
rsa_key_data = None
|
||||
if params.get("rsa_key_b64"):
|
||||
@@ -152,6 +171,8 @@ def decode_operation(params: dict) -> dict:
|
||||
# Resolve channel key (v4.0.0)
|
||||
resolved_channel_key = _resolve_channel_key(params.get("channel_key", "auto"))
|
||||
|
||||
_write_decode_progress(progress_file, 25, "extracting")
|
||||
|
||||
# Call decode with correct parameter names
|
||||
result = decode(
|
||||
stego_image=stego_data,
|
||||
@@ -164,6 +185,8 @@ def decode_operation(params: dict) -> dict:
|
||||
channel_key=resolved_channel_key, # v4.0.0
|
||||
)
|
||||
|
||||
_write_decode_progress(progress_file, 90, "finalizing")
|
||||
|
||||
if result.is_file:
|
||||
return {
|
||||
"success": True,
|
||||
|
||||
@@ -314,6 +314,8 @@ class SubprocessStego:
|
||||
# Channel key (v4.0.0)
|
||||
channel_key: str | None = "auto",
|
||||
timeout: int | None = None,
|
||||
# Progress tracking (v4.1.5)
|
||||
progress_file: str | None = None,
|
||||
) -> DecodeResult:
|
||||
"""
|
||||
Decode a message or file from a stego image.
|
||||
@@ -328,6 +330,7 @@ class SubprocessStego:
|
||||
embed_mode: 'auto', 'lsb', or 'dct'
|
||||
channel_key: 'auto' (server config), 'none' (public), or explicit key (v4.0.0)
|
||||
timeout: Operation timeout in seconds
|
||||
progress_file: Path to write progress updates (v4.1.5)
|
||||
|
||||
Returns:
|
||||
DecodeResult with message or file_data on success
|
||||
@@ -340,6 +343,7 @@ class SubprocessStego:
|
||||
"pin": pin,
|
||||
"embed_mode": embed_mode,
|
||||
"channel_key": channel_key, # v4.0.0
|
||||
"progress_file": progress_file, # v4.1.5
|
||||
}
|
||||
|
||||
if rsa_key_data:
|
||||
|
||||
@@ -14,8 +14,6 @@ It does NOT touch instance/ (auth database) or any other directories.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
|
||||
@@ -317,55 +317,19 @@
|
||||
</div>
|
||||
|
||||
{% if channel_configured %}
|
||||
<div class="alert alert-success mt-3 mb-3">
|
||||
<div class="alert alert-success mt-3 mb-0">
|
||||
<i class="bi bi-shield-lock me-2"></i>
|
||||
<strong>This server has a channel key configured:</strong>
|
||||
<code class="ms-2">{{ channel_fingerprint }}</code>
|
||||
<span class="text-muted ms-2">({{ channel_source }})</span>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info mt-3 mb-3">
|
||||
<div class="alert alert-info mt-3 mb-0">
|
||||
<i class="bi bi-info-circle me-2"></i>
|
||||
This server is running in <strong>public mode</strong>.
|
||||
Set <code>STEGASOO_CHANNEL_KEY</code> to enable server-wide channel isolation.
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- Channel Key QR Generator -->
|
||||
<div class="card bg-dark border-secondary">
|
||||
<div class="card-header">
|
||||
<i class="bi bi-qr-code me-2"></i>Share Channel Key via QR
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="small text-muted mb-3">Generate a QR code to share a channel key with others.</p>
|
||||
<div class="row g-2 align-items-end">
|
||||
<div class="col-md-8">
|
||||
<label class="form-label small">Channel Key</label>
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control font-monospace" id="channelKeyQrInput"
|
||||
placeholder="Enter or generate a key">
|
||||
<button class="btn btn-outline-secondary" type="button" id="channelKeyQrGenerate"
|
||||
title="Generate random key">
|
||||
<i class="bi bi-shuffle"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<button class="btn btn-primary w-100" type="button" id="channelKeyQrShow">
|
||||
<i class="bi bi-qr-code me-1"></i>Show QR
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-center mt-3 d-none" id="channelKeyQrContainer">
|
||||
<canvas id="channelKeyQrCanvas" class="bg-white p-2 rounded"></canvas>
|
||||
<div class="mt-2">
|
||||
<button class="btn btn-sm btn-outline-secondary" type="button" id="channelKeyQrDownload">
|
||||
<i class="bi bi-download me-1"></i>Download PNG
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -632,62 +596,3 @@
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<!-- QR Code library for channel key sharing -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
|
||||
<script src="{{ url_for('static', filename='js/stegasoo.js') }}"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const input = document.getElementById('channelKeyQrInput');
|
||||
const generateBtn = document.getElementById('channelKeyQrGenerate');
|
||||
const showBtn = document.getElementById('channelKeyQrShow');
|
||||
const container = document.getElementById('channelKeyQrContainer');
|
||||
const canvas = document.getElementById('channelKeyQrCanvas');
|
||||
const downloadBtn = document.getElementById('channelKeyQrDownload');
|
||||
|
||||
// Generate random key
|
||||
generateBtn?.addEventListener('click', function() {
|
||||
if (input && typeof Stegasoo !== 'undefined') {
|
||||
input.value = Stegasoo.generateChannelKey();
|
||||
}
|
||||
});
|
||||
|
||||
// Show QR code
|
||||
showBtn?.addEventListener('click', function() {
|
||||
const key = input?.value?.trim().replace(/-/g, '');
|
||||
if (!key || key.length !== 32) {
|
||||
alert('Please enter a valid 32-character channel key');
|
||||
return;
|
||||
}
|
||||
|
||||
// Format key with dashes for QR
|
||||
const formatted = key.match(/.{4}/g)?.join('-') || key;
|
||||
|
||||
// Generate QR code
|
||||
if (typeof QRCode !== 'undefined' && canvas) {
|
||||
QRCode.toCanvas(canvas, formatted, {
|
||||
width: 200,
|
||||
margin: 2,
|
||||
color: { dark: '#000', light: '#fff' }
|
||||
}, function(error) {
|
||||
if (error) {
|
||||
console.error('QR generation error:', error);
|
||||
return;
|
||||
}
|
||||
container?.classList.remove('d-none');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Download QR as PNG
|
||||
downloadBtn?.addEventListener('click', function() {
|
||||
if (canvas) {
|
||||
const link = document.createElement('a');
|
||||
link.download = 'stegasoo-channel-key.png';
|
||||
link.href = canvas.toDataURL('image/png');
|
||||
link.click();
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -140,6 +140,13 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="btn-group btn-group-sm">
|
||||
{% if is_admin %}
|
||||
<button type="button" class="btn btn-outline-info"
|
||||
onclick="showKeyQr('{{ key.channel_key }}', '{{ key.name }}')"
|
||||
title="Show QR Code">
|
||||
<i class="bi bi-qr-code"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
<button type="button" class="btn btn-outline-secondary"
|
||||
onclick="renameKey({{ key.id }}, '{{ key.name }}')"
|
||||
title="Rename">
|
||||
@@ -170,9 +177,16 @@
|
||||
placeholder="Key name" required maxlength="50">
|
||||
</div>
|
||||
<div class="col-7">
|
||||
<input type="text" name="channel_key" class="form-control form-control-sm font-monospace"
|
||||
placeholder="Channel key (32 hex chars)" required
|
||||
pattern="[0-9a-fA-F\-]{32,39}" title="32 hex characters">
|
||||
<div class="input-group input-group-sm">
|
||||
<input type="text" name="channel_key" id="channelKeyInput"
|
||||
class="form-control font-monospace"
|
||||
placeholder="XXXX-XXXX-..." required
|
||||
pattern="[A-Za-z0-9]{4}(-[A-Za-z0-9]{4}){7}">
|
||||
<button type="button" class="btn btn-outline-secondary" id="scanChannelKeyBtn"
|
||||
title="Scan QR code with camera">
|
||||
<i class="bi bi-camera"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-sm btn-outline-primary">
|
||||
@@ -218,17 +232,209 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if is_admin %}
|
||||
<!-- QR Code Modal (Admin only) -->
|
||||
<div class="modal fade" id="qrModal" tabindex="-1">
|
||||
<div class="modal-dialog modal-sm">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title"><i class="bi bi-qr-code me-2"></i><span id="qrKeyName">Channel Key</span></h6>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<canvas id="qrCanvas" class="bg-white p-2 rounded"></canvas>
|
||||
<div class="mt-2">
|
||||
<code class="small" id="qrKeyDisplay"></code>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-center">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="qrDownload">
|
||||
<i class="bi bi-download me-1"></i>Download
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="qrPrint">
|
||||
<i class="bi bi-printer me-1"></i>Print Sheet
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/auth.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/stegasoo.js') }}"></script>
|
||||
{% if is_admin %}
|
||||
<script src="{{ url_for('static', filename='js/qrcode.min.js') }}"></script>
|
||||
{% endif %}
|
||||
<script>
|
||||
StegasooAuth.initPasswordConfirmation('accountForm', 'newPasswordInput', 'newPasswordConfirmInput');
|
||||
|
||||
// Webcam QR scanning for channel key input (v4.1.5)
|
||||
document.getElementById('scanChannelKeyBtn')?.addEventListener('click', function() {
|
||||
Stegasoo.showQrScanner((text) => {
|
||||
const input = document.getElementById('channelKeyInput');
|
||||
if (input) {
|
||||
// Clean and format the key
|
||||
const clean = text.replace(/[^A-Za-z0-9]/g, '').toUpperCase();
|
||||
if (clean.length === 32) {
|
||||
input.value = clean.match(/.{4}/g).join('-');
|
||||
} else {
|
||||
input.value = text.toUpperCase();
|
||||
}
|
||||
}
|
||||
}, 'Scan Channel Key');
|
||||
});
|
||||
|
||||
// Format channel key input as user types
|
||||
document.getElementById('channelKeyInput')?.addEventListener('input', function() {
|
||||
Stegasoo.formatChannelKeyInput(this);
|
||||
});
|
||||
|
||||
function renameKey(keyId, currentName) {
|
||||
document.getElementById('renameInput').value = currentName;
|
||||
document.getElementById('renameForm').action = '/account/keys/' + keyId + '/rename';
|
||||
new bootstrap.Modal(document.getElementById('renameModal')).show();
|
||||
}
|
||||
|
||||
{% if is_admin %}
|
||||
function showKeyQr(channelKey, keyName) {
|
||||
// Format key with dashes if not already
|
||||
const clean = channelKey.replace(/-/g, '').toUpperCase();
|
||||
const formatted = clean.match(/.{4}/g)?.join('-') || clean;
|
||||
|
||||
// Update modal content
|
||||
document.getElementById('qrKeyName').textContent = keyName;
|
||||
document.getElementById('qrKeyDisplay').textContent = formatted;
|
||||
|
||||
// Generate QR code using QRious
|
||||
const canvas = document.getElementById('qrCanvas');
|
||||
if (typeof QRious !== 'undefined' && canvas) {
|
||||
try {
|
||||
new QRious({
|
||||
element: canvas,
|
||||
value: formatted,
|
||||
size: 200,
|
||||
level: 'M'
|
||||
});
|
||||
new bootstrap.Modal(document.getElementById('qrModal')).show();
|
||||
} catch (error) {
|
||||
console.error('QR generation error:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Download QR as PNG
|
||||
document.getElementById('qrDownload')?.addEventListener('click', function() {
|
||||
const canvas = document.getElementById('qrCanvas');
|
||||
const keyName = document.getElementById('qrKeyName').textContent;
|
||||
if (canvas) {
|
||||
const link = document.createElement('a');
|
||||
link.download = 'stegasoo-channel-key-' + keyName.toLowerCase().replace(/\s+/g, '-') + '.png';
|
||||
link.href = canvas.toDataURL('image/png');
|
||||
link.click();
|
||||
}
|
||||
});
|
||||
|
||||
// Print tiled QR sheet (US Letter)
|
||||
document.getElementById('qrPrint')?.addEventListener('click', function() {
|
||||
const canvas = document.getElementById('qrCanvas');
|
||||
const keyText = document.getElementById('qrKeyDisplay').textContent;
|
||||
const keyName = document.getElementById('qrKeyName').textContent;
|
||||
if (canvas && keyText) {
|
||||
printQrSheet(canvas, keyText, keyName);
|
||||
}
|
||||
});
|
||||
|
||||
// Print QR codes tiled on US Letter paper (8.5" x 11")
|
||||
function printQrSheet(canvas, keyText, title) {
|
||||
const qrDataUrl = canvas.toDataURL('image/png');
|
||||
const printWindow = window.open('', '_blank');
|
||||
if (!printWindow) {
|
||||
alert('Please allow popups to print');
|
||||
return;
|
||||
}
|
||||
|
||||
// US Letter: 8.5" x 11" - create 4x5 grid of QR codes
|
||||
const cols = 4;
|
||||
const rows = 5;
|
||||
|
||||
// Split key into two lines (4 groups each)
|
||||
const keyParts = keyText.split('-');
|
||||
const keyLine1 = keyParts.slice(0, 4).join('-');
|
||||
const keyLine2 = keyParts.slice(4).join('-');
|
||||
|
||||
let qrGrid = '';
|
||||
for (let i = 0; i < rows * cols; i++) {
|
||||
qrGrid += `
|
||||
<div class="qr-tile">
|
||||
<div class="key-text">${keyLine1}</div>
|
||||
<img src="${qrDataUrl}" alt="QR">
|
||||
<div class="key-text">${keyLine2}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
printWindow.document.write(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title></title>
|
||||
<style>
|
||||
@page {
|
||||
size: letter;
|
||||
margin: 0.2in;
|
||||
margin-top: 0.1in;
|
||||
margin-bottom: 0.1in;
|
||||
}
|
||||
@media print {
|
||||
@page { margin: 0.15in; }
|
||||
html, body { margin: 0; padding: 0; }
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Courier New', monospace;
|
||||
background: white;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(${cols}, 1fr);
|
||||
gap: 0;
|
||||
margin-top: 0.09in;
|
||||
}
|
||||
.qr-tile {
|
||||
border: 1px dashed #ccc;
|
||||
padding: 0.04in;
|
||||
text-align: center;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
.qr-tile img {
|
||||
width: 1.6in;
|
||||
height: 1.6in;
|
||||
}
|
||||
.key-text {
|
||||
font-size: 10pt;
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.footer {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="grid">${qrGrid}</div>
|
||||
<div class="footer">Cut along dashed lines</div>
|
||||
<script>
|
||||
window.onload = function() { window.print(); };
|
||||
<\/script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
printWindow.document.close();
|
||||
}
|
||||
{% endif %}
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
506
frontends/web/templates/admin/settings.html
Normal file
506
frontends/web/templates/admin/settings.html
Normal file
@@ -0,0 +1,506 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}System Settings - Stegasoo{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-lg-10">
|
||||
<!-- Channel Key Configuration -->
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0"><i class="bi bi-broadcast me-2"></i>Channel Key Configuration</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
{% if channel_configured %}
|
||||
<div class="alert alert-success mb-4">
|
||||
<i class="bi bi-shield-lock me-2"></i>
|
||||
<strong>Server channel key active:</strong>
|
||||
<code class="ms-2">{{ channel_fingerprint }}</code>
|
||||
<span class="text-muted ms-2">({{ channel_source }})</span>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-info mb-4">
|
||||
<i class="bi bi-info-circle me-2"></i>
|
||||
Server running in <strong>public mode</strong>.
|
||||
Set <code>STEGASOO_CHANNEL_KEY</code> environment variable to enable server-wide channel isolation.
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- QR Code Generator -->
|
||||
<div class="card bg-dark border-secondary">
|
||||
<div class="card-header">
|
||||
<i class="bi bi-qr-code me-2"></i>Share Channel Key via QR
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="small text-muted mb-3">Generate a QR code to share a channel key with others.</p>
|
||||
|
||||
<!-- Locked state - requires password -->
|
||||
<div id="channelKeyLocked">
|
||||
<div class="row g-2 align-items-end">
|
||||
<div class="col-md-8">
|
||||
<label class="form-label small">Channel Key</label>
|
||||
<div class="input-group">
|
||||
<input type="password" class="form-control font-monospace"
|
||||
value="********************************" disabled>
|
||||
<span class="input-group-text"><i class="bi bi-lock"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<button class="btn btn-warning w-100" type="button" id="channelKeyUnlock">
|
||||
<i class="bi bi-unlock me-1"></i>Unlock
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<small class="text-muted mt-2 d-block">
|
||||
<i class="bi bi-shield-lock me-1"></i>Re-enter your password to view or export the channel key.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Unlocked state - shows key and QR options -->
|
||||
<div id="channelKeyUnlocked" style="display: none;">
|
||||
<div class="row g-2 align-items-end">
|
||||
<div class="col-md-8">
|
||||
<label class="form-label small">Channel Key</label>
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control font-monospace" id="channelKeyQrInput"
|
||||
placeholder="Enter or generate a key">
|
||||
<button class="btn btn-outline-secondary" type="button" id="channelKeyQrGenerate"
|
||||
title="Generate random key">
|
||||
<i class="bi bi-shuffle"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<button class="btn btn-primary w-100" type="button" id="channelKeyQrShow">
|
||||
<i class="bi bi-qr-code me-1"></i>Show QR
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<small class="text-success mt-2 d-block">
|
||||
<i class="bi bi-unlock me-1"></i>Unlocked for this session.
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Server Configuration -->
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0"><i class="bi bi-gear me-2"></i>Server Configuration</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<table class="table table-dark table-sm">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><i class="bi bi-hdd-network me-2"></i>Hostname</td>
|
||||
<td><code>{{ hostname }}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><i class="bi bi-ethernet me-2"></i>Port</td>
|
||||
<td><code>{{ port }}</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><i class="bi bi-shield-lock me-2"></i>HTTPS</td>
|
||||
<td>
|
||||
{% if https_enabled %}
|
||||
<span class="badge bg-success"><i class="bi bi-lock me-1"></i>Enabled</span>
|
||||
{% else %}
|
||||
<span class="badge bg-warning text-dark"><i class="bi bi-unlock me-1"></i>Disabled</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><i class="bi bi-person-lock me-2"></i>Authentication</td>
|
||||
<td>
|
||||
{% if auth_enabled %}
|
||||
<span class="badge bg-success"><i class="bi bi-check me-1"></i>Enabled</span>
|
||||
{% else %}
|
||||
<span class="badge bg-danger"><i class="bi bi-x me-1"></i>Disabled</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<table class="table table-dark table-sm">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><i class="bi bi-file-earmark me-2"></i>Max Payload</td>
|
||||
<td><code>{{ max_payload_kb }} KB</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><i class="bi bi-upload me-2"></i>Max Upload</td>
|
||||
<td><code>{{ max_upload_mb }} MB</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><i class="bi bi-soundwave me-2"></i>DCT Mode</td>
|
||||
<td>
|
||||
{% if dct_available %}
|
||||
<span class="badge bg-success"><i class="bi bi-check me-1"></i>Available</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">Not Available</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><i class="bi bi-qr-code me-2"></i>QR Support</td>
|
||||
<td>
|
||||
{% if qr_available %}
|
||||
<span class="badge bg-success"><i class="bi bi-check me-1"></i>Available</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary">Not Available</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-secondary small mt-3 mb-0">
|
||||
<i class="bi bi-info-circle me-2"></i>
|
||||
To change server settings, edit environment variables or config file and restart the service.
|
||||
<br>See <code>STEGASOO_HTTPS_ENABLED</code>, <code>STEGASOO_PORT</code>, <code>STEGASOO_CHANNEL_KEY</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Environment Info -->
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0"><i class="bi bi-info-circle me-2"></i>Environment</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row text-center">
|
||||
<div class="col-6 col-md-3 mb-3">
|
||||
<div class="p-3 bg-dark rounded h-100">
|
||||
<i class="bi bi-box text-primary fs-3 d-block mb-2"></i>
|
||||
<div class="small text-muted">Version</div>
|
||||
<strong>{{ version }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-md-3 mb-3">
|
||||
<div class="p-3 bg-dark rounded h-100">
|
||||
<i class="bi bi-terminal text-info fs-3 d-block mb-2"></i>
|
||||
<div class="small text-muted">Python</div>
|
||||
<strong>{{ python_version }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-md-3 mb-3">
|
||||
<div class="p-3 bg-dark rounded h-100">
|
||||
<i class="bi bi-cpu text-warning fs-3 d-block mb-2"></i>
|
||||
<div class="small text-muted">Platform</div>
|
||||
<strong>{{ platform }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-md-3 mb-3">
|
||||
<div class="p-3 bg-dark rounded h-100">
|
||||
<i class="bi bi-shield-check text-success fs-3 d-block mb-2"></i>
|
||||
<div class="small text-muted">KDF</div>
|
||||
<strong>{{ kdf_type }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Password Verification Modal -->
|
||||
<div class="modal fade" id="passwordModal" tabindex="-1">
|
||||
<div class="modal-dialog modal-sm modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title"><i class="bi bi-shield-lock me-2"></i>Verify Password</h6>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p class="small text-muted mb-3">Re-enter your password to access sensitive data.</p>
|
||||
<div class="mb-3">
|
||||
<label class="form-label small">Password</label>
|
||||
<input type="password" class="form-control" id="verifyPassword" autocomplete="current-password">
|
||||
<div class="invalid-feedback" id="passwordError">Incorrect password</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="button" class="btn btn-warning btn-sm" id="verifyPasswordBtn">
|
||||
<i class="bi bi-unlock me-1"></i>Unlock
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- QR Code Modal -->
|
||||
<div class="modal fade" id="channelKeyQrModal" tabindex="-1">
|
||||
<div class="modal-dialog modal-sm modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title"><i class="bi bi-qr-code me-2"></i>Channel Key</h6>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body text-center">
|
||||
<canvas id="channelKeyQrCanvas" class="bg-white p-2 rounded"></canvas>
|
||||
<div class="mt-2">
|
||||
<code class="small" id="channelKeyQrDisplay"></code>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-center">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="channelKeyQrDownload">
|
||||
<i class="bi bi-download me-1"></i>Download
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" id="channelKeyQrPrint">
|
||||
<i class="bi bi-printer me-1"></i>Print Sheet
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/qrcode.min.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/stegasoo.js') }}"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const input = document.getElementById('channelKeyQrInput');
|
||||
const generateBtn = document.getElementById('channelKeyQrGenerate');
|
||||
const showBtn = document.getElementById('channelKeyQrShow');
|
||||
const canvas = document.getElementById('channelKeyQrCanvas');
|
||||
const displayEl = document.getElementById('channelKeyQrDisplay');
|
||||
const downloadBtn = document.getElementById('channelKeyQrDownload');
|
||||
const modalEl = document.getElementById('channelKeyQrModal');
|
||||
const modal = modalEl ? new bootstrap.Modal(modalEl) : null;
|
||||
|
||||
// Password verification elements
|
||||
const lockedDiv = document.getElementById('channelKeyLocked');
|
||||
const unlockedDiv = document.getElementById('channelKeyUnlocked');
|
||||
const unlockBtn = document.getElementById('channelKeyUnlock');
|
||||
const passwordModalEl = document.getElementById('passwordModal');
|
||||
const passwordModal = passwordModalEl ? new bootstrap.Modal(passwordModalEl) : null;
|
||||
const verifyPasswordInput = document.getElementById('verifyPassword');
|
||||
const verifyPasswordBtn = document.getElementById('verifyPasswordBtn');
|
||||
const passwordError = document.getElementById('passwordError');
|
||||
|
||||
// Unlock button shows password modal
|
||||
unlockBtn?.addEventListener('click', function() {
|
||||
verifyPasswordInput.value = '';
|
||||
verifyPasswordInput.classList.remove('is-invalid');
|
||||
passwordModal?.show();
|
||||
setTimeout(() => verifyPasswordInput.focus(), 300);
|
||||
});
|
||||
|
||||
// Handle Enter key in password field
|
||||
verifyPasswordInput?.addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
verifyPasswordBtn?.click();
|
||||
}
|
||||
});
|
||||
|
||||
// Verify password and unlock
|
||||
verifyPasswordBtn?.addEventListener('click', async function() {
|
||||
const password = verifyPasswordInput.value;
|
||||
if (!password) {
|
||||
verifyPasswordInput.classList.add('is-invalid');
|
||||
return;
|
||||
}
|
||||
|
||||
verifyPasswordBtn.disabled = true;
|
||||
verifyPasswordBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Verifying...';
|
||||
|
||||
try {
|
||||
const response = await fetch('/admin/settings/unlock', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: JSON.stringify({ password })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
// Unlock successful
|
||||
passwordModal?.hide();
|
||||
lockedDiv.style.display = 'none';
|
||||
unlockedDiv.style.display = 'block';
|
||||
if (data.channel_key && input) {
|
||||
input.value = data.channel_key;
|
||||
}
|
||||
} else {
|
||||
// Password incorrect
|
||||
verifyPasswordInput.classList.add('is-invalid');
|
||||
passwordError.textContent = data.error || 'Incorrect password';
|
||||
}
|
||||
} catch (error) {
|
||||
verifyPasswordInput.classList.add('is-invalid');
|
||||
passwordError.textContent = 'Verification failed';
|
||||
} finally {
|
||||
verifyPasswordBtn.disabled = false;
|
||||
verifyPasswordBtn.innerHTML = '<i class="bi bi-unlock me-1"></i>Unlock';
|
||||
}
|
||||
});
|
||||
|
||||
// Generate random key
|
||||
generateBtn?.addEventListener('click', function() {
|
||||
if (!input) return;
|
||||
if (typeof Stegasoo !== 'undefined' && Stegasoo.generateChannelKey) {
|
||||
input.value = Stegasoo.generateChannelKey();
|
||||
} else {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
let key = '';
|
||||
for (let i = 0; i < 8; i++) {
|
||||
if (i > 0) key += '-';
|
||||
for (let j = 0; j < 4; j++) {
|
||||
key += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
}
|
||||
input.value = key;
|
||||
}
|
||||
});
|
||||
|
||||
// Show QR code in modal
|
||||
showBtn?.addEventListener('click', function() {
|
||||
const key = input?.value?.trim().replace(/-/g, '');
|
||||
if (!key || key.length !== 32) {
|
||||
alert('Please enter a valid 32-character channel key');
|
||||
return;
|
||||
}
|
||||
|
||||
const formatted = key.match(/.{4}/g)?.join('-') || key;
|
||||
|
||||
if (typeof QRious === 'undefined') {
|
||||
alert('QR Code library failed to load.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
new QRious({
|
||||
element: canvas,
|
||||
value: formatted,
|
||||
size: 200,
|
||||
level: 'M'
|
||||
});
|
||||
if (displayEl) displayEl.textContent = formatted;
|
||||
modal?.show();
|
||||
} catch (error) {
|
||||
alert('Failed to generate QR code: ' + error.message);
|
||||
}
|
||||
});
|
||||
|
||||
// Download QR as PNG
|
||||
downloadBtn?.addEventListener('click', function() {
|
||||
if (canvas) {
|
||||
const link = document.createElement('a');
|
||||
link.download = 'stegasoo-channel-key.png';
|
||||
link.href = canvas.toDataURL('image/png');
|
||||
link.click();
|
||||
}
|
||||
});
|
||||
|
||||
// Print tiled QR sheet (US Letter)
|
||||
document.getElementById('channelKeyQrPrint')?.addEventListener('click', function() {
|
||||
if (canvas && displayEl) {
|
||||
printQrSheet(canvas, displayEl.textContent, 'Channel Key');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Print QR codes tiled on US Letter paper (8.5" x 11")
|
||||
function printQrSheet(canvas, keyText, title) {
|
||||
const qrDataUrl = canvas.toDataURL('image/png');
|
||||
const printWindow = window.open('', '_blank');
|
||||
if (!printWindow) {
|
||||
alert('Please allow popups to print');
|
||||
return;
|
||||
}
|
||||
|
||||
// US Letter: 8.5" x 11" - create 4x5 grid of QR codes
|
||||
const cols = 4;
|
||||
const rows = 5;
|
||||
|
||||
// Split key into two lines (4 groups each)
|
||||
const keyParts = keyText.split('-');
|
||||
const keyLine1 = keyParts.slice(0, 4).join('-');
|
||||
const keyLine2 = keyParts.slice(4).join('-');
|
||||
|
||||
let qrGrid = '';
|
||||
for (let i = 0; i < rows * cols; i++) {
|
||||
qrGrid += `
|
||||
<div class="qr-tile">
|
||||
<div class="key-text">${keyLine1}</div>
|
||||
<img src="${qrDataUrl}" alt="QR">
|
||||
<div class="key-text">${keyLine2}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
printWindow.document.write(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title></title>
|
||||
<style>
|
||||
@page {
|
||||
size: letter;
|
||||
margin: 0.2in;
|
||||
margin-top: 0.1in;
|
||||
margin-bottom: 0.1in;
|
||||
}
|
||||
@media print {
|
||||
@page { margin: 0.15in; }
|
||||
html, body { margin: 0; padding: 0; }
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Courier New', monospace;
|
||||
background: white;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(${cols}, 1fr);
|
||||
gap: 0;
|
||||
margin-top: 0.09in;
|
||||
}
|
||||
.qr-tile {
|
||||
border: 1px dashed #ccc;
|
||||
padding: 0.04in;
|
||||
text-align: center;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
.qr-tile img {
|
||||
width: 1.6in;
|
||||
height: 1.6in;
|
||||
}
|
||||
.key-text {
|
||||
font-size: 10pt;
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.footer {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="grid">${qrGrid}</div>
|
||||
<div class="footer">Cut along dashed lines</div>
|
||||
<script>
|
||||
window.onload = function() { window.print(); };
|
||||
<\/script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
printWindow.document.close();
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -5,8 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}Stegasoo{% endblock %}</title>
|
||||
<link rel="icon" type="image/svg+xml" href="{{ url_for('static', filename='favicon.svg') }}">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
|
||||
<link href="{{ url_for('static', filename='vendor/css/bootstrap.min.css') }}" rel="stylesheet">
|
||||
<link href="{{ url_for('static', filename='vendor/css/bootstrap-icons.min.css') }}" rel="stylesheet">
|
||||
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
@@ -23,26 +23,23 @@
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navbarNav">
|
||||
<ul class="navbar-nav ms-auto">
|
||||
<ul class="navbar-nav ms-auto nav-icons">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/"><i class="bi bi-house me-1"></i> Home</a>
|
||||
<a class="nav-link nav-expand" href="/"><i class="bi bi-house"></i><span>Home</span></a>
|
||||
</li>
|
||||
{% if not auth_enabled or is_authenticated %}
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/encode"><i class="bi bi-lock me-1"></i> Encode</a>
|
||||
<a class="nav-link nav-expand" href="/encode"><i class="bi bi-lock"></i><span>Encode</span></a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/decode"><i class="bi bi-unlock me-1"></i> Decode</a>
|
||||
<a class="nav-link nav-expand" href="/decode"><i class="bi bi-unlock"></i><span>Decode</span></a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/generate"><i class="bi bi-key me-1"></i> Generate</a>
|
||||
<a class="nav-link nav-expand" href="/generate"><i class="bi bi-key"></i><span>Generate</span></a>
|
||||
</li>
|
||||
{% endif %}
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/about"><i class="bi bi-info-circle me-1"></i> About</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/tools"><i class="bi bi-tools me-1"></i> Tools</a>
|
||||
<a class="nav-link nav-expand" href="/tools"><i class="bi bi-tools"></i><span>Tools</span></a>
|
||||
</li>
|
||||
{% if auth_enabled %}
|
||||
{% if is_authenticated %}
|
||||
@@ -54,6 +51,7 @@
|
||||
<li><a class="dropdown-item" href="/account"><i class="bi bi-gear me-2"></i>Account</a></li>
|
||||
{% if is_admin %}
|
||||
<li><a class="dropdown-item" href="/admin/users"><i class="bi bi-people me-2"></i>Users</a></li>
|
||||
<li><a class="dropdown-item" href="/admin/settings"><i class="bi bi-sliders me-2"></i>System Settings</a></li>
|
||||
{% endif %}
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item" href="/logout"><i class="bi bi-box-arrow-left me-2"></i>Logout</a></li>
|
||||
@@ -96,11 +94,15 @@
|
||||
<small>
|
||||
<img src="{{ url_for('static', filename='favicon.svg') }}" alt="" height="16" class="me-1" style="vertical-align: text-bottom;">
|
||||
Stegasoo v{{ version }} — Steganography with Reference Photo + Passphrase + PIN/Key
|
||||
<span class="mx-2">|</span>
|
||||
<a href="/about" class="text-muted text-decoration-none"><i class="bi bi-info-circle me-1"></i>About</a>
|
||||
</small>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="{{ url_for('static', filename='vendor/js/bootstrap.bundle.min.js') }}"></script>
|
||||
<!-- QR Code scanning library (local) -->
|
||||
<script src="{{ url_for('static', filename='vendor/js/html5-qrcode.min.js') }}"></script>
|
||||
<script>
|
||||
// Initialize toasts (auto-hide after delay)
|
||||
document.querySelectorAll('.toast').forEach(el => new bootstrap.Toast(el));
|
||||
|
||||
@@ -4,6 +4,74 @@
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
/* Accordion styling */
|
||||
.step-accordion .accordion-button {
|
||||
background: rgba(30, 40, 50, 0.6);
|
||||
color: #fff;
|
||||
padding: 0.75rem 1rem;
|
||||
border-left: 3px solid transparent;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
.step-accordion .accordion-button:not(.collapsed) {
|
||||
background: linear-gradient(90deg, rgba(99, 179, 237, 0.15) 0%, rgba(40, 50, 60, 0.8) 40%, rgba(40, 50, 60, 0.8) 100%);
|
||||
color: #fff;
|
||||
box-shadow: inset 0 1px 0 rgba(99, 179, 237, 0.1);
|
||||
border-left: 3px solid rgba(99, 179, 237, 0.6);
|
||||
}
|
||||
.step-accordion .accordion-button::after {
|
||||
filter: invert(1);
|
||||
}
|
||||
.step-accordion .accordion-body {
|
||||
background: rgba(30, 40, 50, 0.4);
|
||||
padding: 1rem;
|
||||
}
|
||||
.step-accordion .accordion-item {
|
||||
border-color: rgba(255,255,255,0.1);
|
||||
background: transparent;
|
||||
}
|
||||
.step-accordion .accordion-item:first-child .accordion-button {
|
||||
border-radius: 0;
|
||||
}
|
||||
.step-accordion .accordion-item:last-child .accordion-button.collapsed {
|
||||
border-radius: 0;
|
||||
}
|
||||
.step-summary {
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255,255,255,0.5);
|
||||
margin-left: auto;
|
||||
padding-right: 1rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 50%;
|
||||
}
|
||||
.step-summary.has-content {
|
||||
color: rgba(99, 179, 237, 0.8);
|
||||
}
|
||||
.step-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.step-number {
|
||||
background: rgba(246, 173, 85, 0.2);
|
||||
color: #f6ad55;
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.75rem;
|
||||
font-weight: bold;
|
||||
border: 1px solid rgba(246, 173, 85, 0.3);
|
||||
}
|
||||
.step-number.complete {
|
||||
background: rgba(72, 187, 120, 0.2);
|
||||
color: #48bb78;
|
||||
border-color: rgba(72, 187, 120, 0.3);
|
||||
}
|
||||
|
||||
/* Glowing passphrase input */
|
||||
.passphrase-input {
|
||||
background: rgba(30, 40, 50, 0.8) !important;
|
||||
@@ -13,20 +81,17 @@
|
||||
font-size: 1.1rem;
|
||||
letter-spacing: 0.5px;
|
||||
padding: 12px 16px;
|
||||
transition: border-color 0.3s ease, box-shadow 0.3s ease, background 0.3s ease;
|
||||
transition: border-color 0.3s ease, box-shadow 0.3s ease;
|
||||
}
|
||||
|
||||
.passphrase-input:focus {
|
||||
border-color: rgba(99, 179, 237, 0.8) !important;
|
||||
box-shadow: 0 0 20px rgba(99, 179, 237, 0.4), 0 0 40px rgba(99, 179, 237, 0.2) !important;
|
||||
background: rgba(30, 40, 50, 0.95) !important;
|
||||
box-shadow: 0 0 20px rgba(99, 179, 237, 0.4) !important;
|
||||
}
|
||||
|
||||
.passphrase-input::placeholder {
|
||||
color: rgba(99, 179, 237, 0.4);
|
||||
}
|
||||
|
||||
/* Glowing PIN input */
|
||||
/* PIN input */
|
||||
.pin-input-container .form-control {
|
||||
background: rgba(30, 40, 50, 0.8) !important;
|
||||
border: 2px solid rgba(246, 173, 85, 0.3) !important;
|
||||
@@ -35,18 +100,10 @@
|
||||
font-size: 1.2rem;
|
||||
letter-spacing: 3px;
|
||||
text-align: center;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.pin-input-container .form-control:focus {
|
||||
border-color: rgba(246, 173, 85, 0.8) !important;
|
||||
box-shadow: 0 0 20px rgba(246, 173, 85, 0.4), 0 0 40px rgba(246, 173, 85, 0.2) !important;
|
||||
background: rgba(30, 40, 50, 0.95) !important;
|
||||
}
|
||||
|
||||
.pin-input-container .form-control::placeholder {
|
||||
color: rgba(246, 173, 85, 0.4);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: 0 0 20px rgba(246, 173, 85, 0.4) !important;
|
||||
}
|
||||
|
||||
/* QR Crop Animation */
|
||||
@@ -55,8 +112,12 @@
|
||||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.qr-crop-container img {
|
||||
display: block;
|
||||
max-height: 180px;
|
||||
@@ -65,15 +126,10 @@
|
||||
margin: 0 auto;
|
||||
transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.qr-crop-container .qr-original {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.qr-crop-container .qr-original { opacity: 1; }
|
||||
.qr-crop-container .qr-cropped {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
top: 50%; left: 50%;
|
||||
transform: translate(-50%, -50%) scale(0.3);
|
||||
opacity: 0;
|
||||
max-height: 160px;
|
||||
@@ -81,30 +137,15 @@
|
||||
min-height: 140px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.qr-crop-container.scan-complete .qr-original {
|
||||
opacity: 0;
|
||||
transform: scale(1.1);
|
||||
filter: blur(4px);
|
||||
}
|
||||
|
||||
.qr-crop-container.scan-complete .qr-cropped {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -50%) scale(1);
|
||||
}
|
||||
|
||||
.qr-crop-container .crop-badge {
|
||||
position: absolute;
|
||||
bottom: 4px;
|
||||
right: 4px;
|
||||
font-size: 0.65rem;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease 0.4s;
|
||||
}
|
||||
|
||||
.qr-crop-container.scan-complete .crop-badge {
|
||||
opacity: 1;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="row justify-content-center">
|
||||
@@ -113,13 +154,13 @@
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0"><i class="bi bi-unlock-fill me-2"></i>Decode Secret Message or File</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="card-body {% if not decoded_message and not decoded_file %}p-0{% endif %}">
|
||||
{% if decoded_message %}
|
||||
<!-- Text Message Result -->
|
||||
<div class="alert alert-success">
|
||||
<h6><i class="bi bi-check-circle me-2"></i>Message Decrypted Successfully!</h6>
|
||||
</div>
|
||||
|
||||
|
||||
<label class="form-label text-muted">Decoded Message: <small class="text-secondary">(click to copy)</small></label>
|
||||
<div class="alert-message p-3 rounded bg-dark border border-secondary mb-3" id="decodedContent" style="white-space: pre-wrap; cursor: pointer; transition: border-color 0.2s;"
|
||||
onclick="navigator.clipboard.writeText(this.innerText).then(() => { this.style.borderColor = '#198754'; this.dataset.origText = this.innerHTML; this.innerHTML = '<i class=\'bi bi-check-circle text-success\'></i> Copied to clipboard!'; setTimeout(() => { this.innerHTML = this.dataset.origText; this.style.borderColor = ''; }, 1500); }).catch(() => alert('Failed to copy'))"
|
||||
@@ -129,13 +170,13 @@
|
||||
<a href="/decode" class="btn btn-outline-light w-100">
|
||||
<i class="bi bi-arrow-repeat me-2"></i>Decode Another
|
||||
</a>
|
||||
|
||||
|
||||
{% elif decoded_file %}
|
||||
<!-- File Result -->
|
||||
<div class="alert alert-success">
|
||||
<h6><i class="bi bi-check-circle me-2"></i>File Decrypted Successfully!</h6>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="text-center mb-4">
|
||||
<i class="bi bi-file-earmark-check text-success" style="font-size: 4rem;"></i>
|
||||
<h5 class="mt-3">{{ filename }}</h5>
|
||||
@@ -144,345 +185,266 @@
|
||||
<small class="text-muted">Type: {{ mime_type }}</small>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
|
||||
<a href="{{ url_for('decode_download', file_id=file_id) }}" class="btn btn-primary btn-lg w-100 mb-3">
|
||||
<i class="bi bi-download me-2"></i>Download File
|
||||
</a>
|
||||
|
||||
|
||||
<div class="alert alert-warning small">
|
||||
<i class="bi bi-clock me-1"></i>
|
||||
<strong>File expires in 5 minutes.</strong> Download now.
|
||||
</div>
|
||||
|
||||
|
||||
<a href="/decode" class="btn btn-outline-light w-100">
|
||||
<i class="bi bi-arrow-repeat me-2"></i>Decode Another
|
||||
</a>
|
||||
|
||||
|
||||
{% else %}
|
||||
<!-- Decode Form -->
|
||||
<form method="POST" enctype="multipart/form-data" id="decodeForm">
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-image me-1"></i> Reference Photo
|
||||
</label>
|
||||
<div class="drop-zone scan-container" id="refDropZone">
|
||||
<input type="file" name="reference_photo" accept="image/*" required>
|
||||
<div class="drop-zone-label">
|
||||
<i class="bi bi-cloud-arrow-up fs-3 d-block mb-2 text-muted"></i>
|
||||
<span class="text-muted">Drop image or click to browse</span>
|
||||
</div>
|
||||
<img class="drop-zone-preview d-none" id="refPreview">
|
||||
<!-- Scan overlay elements -->
|
||||
<div class="scan-overlay">
|
||||
<div class="scan-grid"></div>
|
||||
<div class="scan-line"></div>
|
||||
</div>
|
||||
<!-- Corner brackets (shown after scan) -->
|
||||
<div class="scan-corners">
|
||||
<div class="scan-corner tl"></div>
|
||||
<div class="scan-corner tr"></div>
|
||||
<div class="scan-corner bl"></div>
|
||||
<div class="scan-corner br"></div>
|
||||
</div>
|
||||
<!-- Data panel (shown after scan) -->
|
||||
<div class="scan-data-panel">
|
||||
<div class="scan-data-filename">
|
||||
<i class="bi bi-check-circle-fill"></i>
|
||||
<span id="refFileName">image.jpg</span>
|
||||
</div>
|
||||
<div class="scan-data-row">
|
||||
<span class="scan-status-badge">Hash Acquired</span>
|
||||
<span class="scan-data-value" id="refFileSize">--</span>
|
||||
</div>
|
||||
<div class="scan-hash-preview" id="refHashPreview">SHA256: ················</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-text">
|
||||
The same reference photo used for encoding
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-file-earmark-image me-1"></i> Stego Image
|
||||
</label>
|
||||
<div class="drop-zone pixel-container" id="stegoDropZone">
|
||||
<input type="file" name="stego_image" accept="image/*" required>
|
||||
<div class="drop-zone-label">
|
||||
<i class="bi bi-cloud-arrow-up fs-3 d-block mb-2 text-muted"></i>
|
||||
<span class="text-muted">Drop image or click to browse</span>
|
||||
</div>
|
||||
<img class="drop-zone-preview d-none" id="stegoPreview">
|
||||
<!-- Pixel blocks overlay - populated by JS -->
|
||||
<div class="pixel-blocks"></div>
|
||||
<!-- Pixel scan line -->
|
||||
<div class="pixel-scan-line"></div>
|
||||
<!-- Corner brackets -->
|
||||
<div class="pixel-corners">
|
||||
<div class="pixel-corner tl"></div>
|
||||
<div class="pixel-corner tr"></div>
|
||||
<div class="pixel-corner bl"></div>
|
||||
<div class="pixel-corner br"></div>
|
||||
</div>
|
||||
<!-- Data panel -->
|
||||
<div class="pixel-data-panel">
|
||||
<div class="pixel-data-filename">
|
||||
<i class="bi bi-check-circle-fill"></i>
|
||||
<span id="stegoFileName">image.png</span>
|
||||
</div>
|
||||
<div class="pixel-data-row">
|
||||
<span class="pixel-status-badge">Stego Loaded</span>
|
||||
<span class="pixel-data-value" id="stegoFileSize">--</span>
|
||||
</div>
|
||||
<div class="pixel-dimensions" id="stegoDims">-- × -- px</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-text">
|
||||
The image containing the hidden message/file
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-chat-quote me-1"></i> Passphrase
|
||||
</label>
|
||||
<input type="text" name="passphrase" id="passphraseInput" class="form-control passphrase-input"
|
||||
placeholder="e.g., correct horse battery staple" required>
|
||||
<div class="form-text">
|
||||
The passphrase used during encoding (typically 4 words)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class="my-4">
|
||||
|
||||
<h6 class="text-muted mb-3">
|
||||
SECURITY FACTORS
|
||||
<span class="text-warning small">(provide same factors used during encoding)</span>
|
||||
</h6>
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="security-box">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-file-earmark-lock me-1"></i> RSA Key
|
||||
</label>
|
||||
|
||||
<!-- RSA Input Method Toggle -->
|
||||
<div class="btn-group w-100 mb-2" role="group">
|
||||
<input type="radio" class="btn-check" name="rsa_input_method" id="rsaMethodFile" value="file" checked>
|
||||
<label class="btn btn-outline-secondary btn-sm" for="rsaMethodFile">
|
||||
<i class="bi bi-file-earmark me-1"></i>.pem File
|
||||
</label>
|
||||
<div class="accordion step-accordion" id="decodeAccordion">
|
||||
|
||||
<input type="radio" class="btn-check" name="rsa_input_method" id="rsaMethodQr" value="qr">
|
||||
<label class="btn btn-outline-secondary btn-sm" for="rsaMethodQr">
|
||||
<i class="bi bi-qr-code me-1"></i>QR Code
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- .pem File Input -->
|
||||
<div id="rsaFileSection">
|
||||
<input type="file" name="rsa_key" class="form-control form-control-sm" id="rsaKeyInput" accept=".pem,.key,application/x-pem-file">
|
||||
</div>
|
||||
|
||||
<!-- QR Code Input -->
|
||||
<div id="rsaQrSection" class="d-none">
|
||||
<div class="drop-zone p-3" id="qrDropZone">
|
||||
<input type="file" name="rsa_key_qr" accept="image/*" id="rsaKeyQrInput">
|
||||
<div class="drop-zone-label text-center">
|
||||
<i class="bi bi-qr-code-scan fs-4 d-block text-muted mb-1"></i>
|
||||
<span class="text-muted small">Drop QR image or click to browse</span>
|
||||
</div>
|
||||
<!-- Crop animation container -->
|
||||
<div class="qr-scan-container qr-crop-container d-none" id="qrCropContainer">
|
||||
<img class="qr-original" id="qrOriginal" alt="Original">
|
||||
<img class="qr-cropped" id="qrCropped" alt="Cropped QR">
|
||||
<!-- Data panel -->
|
||||
<div class="qr-data-panel">
|
||||
<div class="qr-data-filename">
|
||||
<i class="bi bi-check-circle-fill"></i>
|
||||
<span>RSA Key loaded</span>
|
||||
</div>
|
||||
<div class="qr-data-row">
|
||||
<span class="qr-status-badge">RSA Key</span>
|
||||
<span class="qr-data-value">--</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Key Password (always visible) -->
|
||||
<div class="input-group input-group-sm mt-2">
|
||||
<input type="password" name="rsa_password" class="form-control" id="rsaPasswordInput" placeholder="Key password (if encrypted)">
|
||||
<button class="btn btn-outline-secondary" type="button" data-toggle-password="rsaPasswordInput">
|
||||
<i class="bi bi-eye"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PIN + Channel Row -->
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<div class="security-box h-100">
|
||||
<label class="form-label"><i class="bi bi-123 me-1"></i> PIN</label>
|
||||
<div class="input-group pin-input-container">
|
||||
<input type="password" name="pin" class="form-control" id="pinInput" placeholder="••••••" maxlength="9">
|
||||
<button class="btn btn-outline-secondary" type="button" data-toggle-password="pinInput">
|
||||
<i class="bi bi-eye"></i>
|
||||
<!-- ================================================================
|
||||
STEP 1: IMAGES & MODE
|
||||
================================================================ -->
|
||||
<div class="accordion-item">
|
||||
<h2 class="accordion-header">
|
||||
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#stepImages">
|
||||
<span class="step-title">
|
||||
<span class="step-number" id="stepImagesNumber">1</span>
|
||||
<i class="bi bi-images me-1"></i> Images & Mode
|
||||
</span>
|
||||
<span class="step-summary" id="stepImagesSummary">Select reference & stego</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="form-text">If PIN was used during encoding</div>
|
||||
</div>
|
||||
</div>
|
||||
</h2>
|
||||
<div id="stepImages" class="accordion-collapse collapse show" data-bs-parent="#decodeAccordion">
|
||||
<div class="accordion-body">
|
||||
|
||||
<div class="col-md-6 mb-3">
|
||||
<div class="security-box h-100">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-broadcast me-1"></i> Channel
|
||||
<span class="badge bg-info ms-1">v4.1</span>
|
||||
<a href="/about#channel-keys" class="text-muted ms-1" title="Learn about channels"><i class="bi bi-info-circle"></i></a>
|
||||
</label>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-image me-1"></i> Reference Photo
|
||||
</label>
|
||||
<div class="drop-zone scan-container" id="refDropZone">
|
||||
<input type="file" name="reference_photo" accept="image/*" required id="refPhotoInput">
|
||||
<div class="drop-zone-label">
|
||||
<i class="bi bi-cloud-arrow-up fs-3 d-block mb-2 text-muted"></i>
|
||||
<span class="text-muted">Drop image or click</span>
|
||||
</div>
|
||||
<img class="drop-zone-preview d-none" id="refPreview">
|
||||
<div class="scan-overlay"><div class="scan-grid"></div><div class="scan-line"></div></div>
|
||||
<div class="scan-corners">
|
||||
<div class="scan-corner tl"></div><div class="scan-corner tr"></div>
|
||||
<div class="scan-corner bl"></div><div class="scan-corner br"></div>
|
||||
</div>
|
||||
<div class="scan-data-panel">
|
||||
<div class="scan-data-filename"><i class="bi bi-check-circle-fill"></i><span id="refFileName">image.jpg</span></div>
|
||||
<div class="scan-data-row"><span class="scan-status-badge">Hash Acquired</span><span class="scan-data-value" id="refFileSize">--</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-text">Same reference photo used for encoding</div>
|
||||
</div>
|
||||
|
||||
<select class="form-select" name="channel_key" id="channelSelectDec">
|
||||
<option value="auto" selected>Auto{% if channel_configured %} (Server Key){% endif %}</option>
|
||||
<option value="none">Public</option>
|
||||
{% if saved_channel_keys %}
|
||||
<optgroup label="Saved Keys">
|
||||
{% for key in saved_channel_keys %}
|
||||
<option value="{{ key.channel_key }}" data-key-id="{{ key.id }}">{{ key.name }} ({{ key.channel_key[:4] }}...)</option>
|
||||
{% endfor %}
|
||||
</optgroup>
|
||||
{% endif %}
|
||||
<option value="custom">Custom...</option>
|
||||
</select>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-file-earmark-image me-1"></i> Stego Image
|
||||
</label>
|
||||
<div class="drop-zone pixel-container" id="stegoDropZone">
|
||||
<input type="file" name="stego_image" accept="image/*" required id="stegoInput">
|
||||
<div class="drop-zone-label">
|
||||
<i class="bi bi-cloud-arrow-up fs-3 d-block mb-2 text-muted"></i>
|
||||
<span class="text-muted">Drop image or click</span>
|
||||
</div>
|
||||
<img class="drop-zone-preview d-none" id="stegoPreview">
|
||||
<div class="pixel-blocks"></div>
|
||||
<div class="pixel-scan-line"></div>
|
||||
<div class="pixel-corners">
|
||||
<div class="pixel-corner tl"></div><div class="pixel-corner tr"></div>
|
||||
<div class="pixel-corner bl"></div><div class="pixel-corner br"></div>
|
||||
</div>
|
||||
<div class="pixel-data-panel">
|
||||
<div class="pixel-data-filename"><i class="bi bi-check-circle-fill"></i><span id="stegoFileName">image.png</span></div>
|
||||
<div class="pixel-data-row"><span class="pixel-status-badge">Stego Loaded</span><span class="pixel-data-value" id="stegoFileSize">--</span></div>
|
||||
<div class="pixel-dimensions" id="stegoDims">-- x -- px</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-text">Image containing the hidden message</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Server channel indicator (compact) -->
|
||||
<div class="small text-success mt-2 {% if not channel_configured %}d-none{% endif %}" id="channelServerInfoDec" data-fingerprint="{{ (channel_fingerprint[:4] if channel_fingerprint else '') }}-••••-···-••••-{{ channel_fingerprint[-4:] if channel_fingerprint else '' }}">
|
||||
{% if channel_configured and channel_fingerprint %}
|
||||
<i class="bi bi-shield-lock me-1"></i>
|
||||
Server: <code>{{ channel_fingerprint[:4] }}-••••-···-••••-{{ channel_fingerprint[-4:] }}</code>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Custom Channel Key Input (shown when Custom selected) -->
|
||||
<div class="mb-4 d-none" id="channelCustomInputDec">
|
||||
<div class="security-box">
|
||||
<label class="form-label"><i class="bi bi-key me-1"></i> Custom Channel Key</label>
|
||||
<div class="input-group">
|
||||
<input type="text" name="channel_key_custom" class="form-control font-monospace"
|
||||
placeholder="XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX"
|
||||
pattern="[A-Za-z0-9]{4}(-[A-Za-z0-9]{4}){7}"
|
||||
id="channelKeyInputDec">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================================================================
|
||||
ADVANCED OPTIONS (v3.0) - Extraction Mode
|
||||
================================================================ -->
|
||||
<div class="mb-4">
|
||||
<a class="btn btn-sm btn-outline-secondary w-100" data-bs-toggle="collapse" href="#advancedOptionsDec" role="button" aria-expanded="false">
|
||||
<i class="bi bi-gear me-1"></i> Advanced Options
|
||||
<i class="bi bi-chevron-down ms-1" id="advancedChevronDec"></i>
|
||||
</a>
|
||||
|
||||
<div class="collapse" id="advancedOptionsDec">
|
||||
<div class="card card-body mt-2 bg-dark border-secondary">
|
||||
|
||||
<!-- Extraction Mode Selection -->
|
||||
<div class="mb-0">
|
||||
<label class="form-label">
|
||||
<i class="bi bi-cpu me-1"></i> Extraction Mode
|
||||
<span class="badge bg-info ms-1">v3.0</span>
|
||||
</label>
|
||||
|
||||
<div class="d-flex gap-2">
|
||||
<!-- Auto Mode -->
|
||||
<label class="mode-btn flex-fill active" id="autoModeCard" for="modeAuto">
|
||||
<!-- Extraction Mode (compact inline) -->
|
||||
<div class="d-flex gap-2 align-items-center flex-wrap mb-2">
|
||||
<label class="mode-btn mode-btn-sm active" id="autoModeCard" for="modeAuto">
|
||||
<input class="form-check-input" type="radio" name="embed_mode" id="modeAuto" value="auto" checked>
|
||||
<i class="bi bi-magic text-success"></i>
|
||||
<span class="ms-2"><strong>Auto</strong> <span class="text-muted d-none d-sm-inline">· Try both</span></span>
|
||||
<i class="bi bi-magic text-success"></i> Auto
|
||||
</label>
|
||||
|
||||
<!-- LSB Mode -->
|
||||
<label class="mode-btn flex-fill" id="lsbModeCardDec" for="modeLsbDec">
|
||||
<input class="form-check-input" type="radio" name="embed_mode" id="modeLsbDec" value="lsb">
|
||||
<i class="bi bi-grid-3x3-gap text-primary"></i>
|
||||
<span class="ms-2"><strong>LSB</strong> <span class="text-muted d-none d-sm-inline">· Spatial</span></span>
|
||||
<label class="mode-btn mode-btn-sm" id="lsbModeCard" for="modeLsb">
|
||||
<input class="form-check-input" type="radio" name="embed_mode" id="modeLsb" value="lsb">
|
||||
<i class="bi bi-grid-3x3-gap text-primary"></i> LSB
|
||||
</label>
|
||||
|
||||
<!-- DCT Mode -->
|
||||
<label class="mode-btn flex-fill {% if not has_dct %}opacity-50{% endif %}" id="dctModeCardDec" for="modeDctDec">
|
||||
<input class="form-check-input" type="radio" name="embed_mode" id="modeDctDec" value="dct" {% if not has_dct %}disabled{% endif %}>
|
||||
<i class="bi bi-soundwave text-warning"></i>
|
||||
<span class="ms-2"><strong>DCT</strong> <span class="text-muted d-none d-sm-inline">· Frequency</span></span>
|
||||
<label class="mode-btn mode-btn-sm {% if not has_dct %}opacity-50{% endif %}" id="dctModeCard" for="modeDct">
|
||||
<input class="form-check-input" type="radio" name="embed_mode" id="modeDct" value="dct" {% if not has_dct %}disabled{% endif %}>
|
||||
<i class="bi bi-soundwave text-warning"></i> DCT
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="form-text mt-2">
|
||||
<i class="bi bi-lightbulb me-1"></i>
|
||||
<strong>Auto</strong> tries LSB first, then DCT.
|
||||
{% if not has_dct %}
|
||||
<span class="text-warning ms-2"><i class="bi bi-exclamation-triangle me-1"></i>DCT requires scipy</span>
|
||||
{% endif %}
|
||||
<div class="form-text" id="modeHint">
|
||||
<i class="bi bi-lightning me-1"></i>Tries LSB first, then DCT
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ================================================================
|
||||
STEP 2: SECURITY
|
||||
================================================================ -->
|
||||
<div class="accordion-item">
|
||||
<h2 class="accordion-header">
|
||||
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#stepSecurity">
|
||||
<span class="step-title">
|
||||
<span class="step-number" id="stepSecurityNumber">2</span>
|
||||
<i class="bi bi-shield-lock me-1"></i> Security
|
||||
</span>
|
||||
<span class="step-summary" id="stepSecuritySummary">Passphrase & keys</span>
|
||||
</button>
|
||||
</h2>
|
||||
<div id="stepSecurity" class="accordion-collapse collapse" data-bs-parent="#decodeAccordion">
|
||||
<div class="accordion-body">
|
||||
|
||||
<!-- Passphrase -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label"><i class="bi bi-chat-quote me-1"></i> Passphrase</label>
|
||||
<input type="text" name="passphrase" class="form-control passphrase-input"
|
||||
placeholder="e.g., apple forest thunder mountain" required id="passphraseInput">
|
||||
<div class="form-text">The passphrase used during encoding</div>
|
||||
</div>
|
||||
|
||||
<hr class="my-3 opacity-25">
|
||||
<div class="small text-muted mb-2">Provide same factors used during encoding</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- PIN -->
|
||||
<div class="col-md-6 mb-2">
|
||||
<div class="security-box h-100">
|
||||
<label class="form-label"><i class="bi bi-123 me-1"></i> PIN</label>
|
||||
<div class="input-group pin-input-container">
|
||||
<input type="password" name="pin" class="form-control" id="pinInput" placeholder="••••••" maxlength="9">
|
||||
<button class="btn btn-outline-secondary" type="button" data-toggle-password="pinInput">
|
||||
<i class="bi bi-eye"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Channel -->
|
||||
<div class="col-md-6 mb-2">
|
||||
<div class="security-box h-100">
|
||||
<label class="form-label"><i class="bi bi-broadcast me-1"></i> Channel</label>
|
||||
<select class="form-select form-select-sm" name="channel_key" id="channelSelectDec">
|
||||
<option value="auto" selected>Auto{% if channel_configured %} (Server){% endif %}</option>
|
||||
<option value="none">Public</option>
|
||||
{% if saved_channel_keys %}
|
||||
<optgroup label="Saved Keys">
|
||||
{% for key in saved_channel_keys %}
|
||||
<option value="{{ key.channel_key }}">{{ key.name }}</option>
|
||||
{% endfor %}
|
||||
</optgroup>
|
||||
{% endif %}
|
||||
<option value="custom">Custom...</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Custom Channel Key -->
|
||||
<div class="mb-3 d-none" id="channelCustomInputDec">
|
||||
<div class="security-box">
|
||||
<label class="form-label"><i class="bi bi-key me-1"></i> Custom Channel Key</label>
|
||||
<div class="input-group">
|
||||
<input type="text" name="channel_key_custom" class="form-control form-control-sm font-monospace"
|
||||
placeholder="XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX" id="channelKeyInputDec">
|
||||
<button class="btn btn-outline-secondary btn-sm" type="button" id="channelKeyScanDec" title="Scan QR"><i class="bi bi-camera"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RSA Key -->
|
||||
<div class="mb-3">
|
||||
<div class="security-box">
|
||||
<label class="form-label"><i class="bi bi-file-earmark-lock me-1"></i> RSA Key <span class="text-muted">(if used)</span></label>
|
||||
<div class="btn-group w-100 mb-2" role="group">
|
||||
<input type="radio" class="btn-check" name="rsa_input_method" id="rsaMethodFile" value="file" checked>
|
||||
<label class="btn btn-outline-secondary btn-sm" for="rsaMethodFile"><i class="bi bi-file-earmark me-1"></i>.pem</label>
|
||||
<input type="radio" class="btn-check" name="rsa_input_method" id="rsaMethodQr" value="qr">
|
||||
<label class="btn btn-outline-secondary btn-sm" for="rsaMethodQr"><i class="bi bi-qr-code me-1"></i>QR</label>
|
||||
</div>
|
||||
<div id="rsaFileSection">
|
||||
<input type="file" name="rsa_key" class="form-control form-control-sm" accept=".pem">
|
||||
</div>
|
||||
<div id="rsaQrSection" class="d-none d-flex flex-column">
|
||||
<input type="hidden" name="rsa_key_pem" id="rsaKeyPem">
|
||||
<div class="drop-zone p-2 w-100" id="qrDropZone">
|
||||
<input type="file" name="rsa_key_qr" accept="image/*" id="rsaQrInput">
|
||||
<div class="drop-zone-label text-center">
|
||||
<i class="bi bi-qr-code-scan fs-5 d-block text-muted mb-1"></i>
|
||||
<span class="text-muted small">Drop QR image</span>
|
||||
</div>
|
||||
<div class="qr-scan-container qr-crop-container d-none" id="qrCropContainer">
|
||||
<img class="qr-original" id="qrOriginal" alt="Original">
|
||||
<img class="qr-cropped" id="qrCropped" alt="Cropped">
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm w-100 mt-2" id="rsaQrWebcam">
|
||||
<i class="bi bi-camera me-1"></i>Scan with Camera
|
||||
</button>
|
||||
</div>
|
||||
<div class="input-group input-group-sm mt-2">
|
||||
<input type="password" name="rsa_password" class="form-control" id="rsaPasswordInput" placeholder="Key password (if encrypted)">
|
||||
<button class="btn btn-outline-secondary" type="button" data-toggle-password="rsaPasswordInput"><i class="bi bi-eye"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-lg w-100" id="decodeBtn">
|
||||
<i class="bi bi-unlock me-2"></i>Decode
|
||||
</button>
|
||||
|
||||
<!-- Submit Button -->
|
||||
<div class="p-3">
|
||||
<button type="submit" class="btn btn-primary btn-lg w-100" id="decodeBtn">
|
||||
<i class="bi bi-unlock me-2"></i>Decode
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{% if not decoded_message and not decoded_file %}
|
||||
<!-- Troubleshooting Card -->
|
||||
<div class="card mt-4">
|
||||
<div class="card-body">
|
||||
<h6 class="text-muted mb-3"><i class="bi bi-question-circle me-2"></i>Troubleshooting</h6>
|
||||
<ul class="list-unstyled text-muted small mb-0">
|
||||
<li class="mb-2">
|
||||
<i class="bi bi-check-circle-fill text-success me-1"></i>
|
||||
Use the <strong>exact same reference photo</strong> file (byte-for-byte identical)
|
||||
Use the <strong>exact same reference photo</strong> (byte-for-byte identical)
|
||||
</li>
|
||||
<li class="mb-2">
|
||||
<i class="bi bi-check-circle-fill text-success me-1"></i>
|
||||
Enter the <strong>exact passphrase</strong> used during encoding (case-sensitive, spacing matters)
|
||||
</li>
|
||||
<li class="mb-2">
|
||||
<i class="bi bi-check-circle-fill text-success me-1"></i>
|
||||
Provide the <strong>same security factors</strong> (PIN and/or RSA key) used during encoding
|
||||
Enter the <strong>exact passphrase</strong> used during encoding
|
||||
</li>
|
||||
<li class="mb-2">
|
||||
<i class="bi bi-exclamation-triangle-fill text-warning me-1"></i>
|
||||
Ensure the stego image hasn't been <strong>resized, cropped, or recompressed</strong>
|
||||
</li>
|
||||
<li class="mb-2">
|
||||
<i class="bi bi-exclamation-triangle-fill text-warning me-1"></i>
|
||||
<strong>Format compatibility:</strong> v4.0 cannot decode messages from v3.1 or earlier (different format)
|
||||
</li>
|
||||
<li class="mb-2">
|
||||
<i class="bi bi-broadcast text-info me-1"></i>
|
||||
<strong>Channel key:</strong> Use the same channel (Auto/Public/Custom) that was used during encoding
|
||||
</li>
|
||||
<li class="mb-2">
|
||||
<i class="bi bi-info-circle-fill text-info me-1"></i>
|
||||
If using an RSA key, verify the <strong>password is correct</strong> (if key is encrypted)
|
||||
Ensure the stego image hasn't been <strong>resized or recompressed</strong>
|
||||
</li>
|
||||
<li class="mb-0">
|
||||
<i class="bi bi-info-circle-fill text-info me-1"></i>
|
||||
If auto-detection fails, try specifying <strong>LSB or DCT mode</strong> in Advanced Options
|
||||
If auto-detection fails, try specifying <strong>LSB or DCT mode</strong>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -495,31 +457,111 @@
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/stegasoo.js') }}"></script>
|
||||
<script>
|
||||
// Extraction mode button active state toggle
|
||||
const extractModeRadios = document.querySelectorAll('input[name="embed_mode"]');
|
||||
const extractModeBtns = {
|
||||
'auto': document.getElementById('autoModeCard'),
|
||||
'lsb': document.getElementById('lsbModeCardDec'),
|
||||
'dct': document.getElementById('dctModeCardDec')
|
||||
// ============================================================================
|
||||
// MODE HINT - Dynamic text based on selected extraction mode
|
||||
// ============================================================================
|
||||
const modeHints = {
|
||||
auto: { icon: 'lightning', text: 'Tries LSB first, then DCT' },
|
||||
lsb: { icon: 'hdd', text: 'For email and direct transfers' },
|
||||
dct: { icon: 'phone', text: 'For social media images' }
|
||||
};
|
||||
|
||||
extractModeRadios.forEach(radio => {
|
||||
radio.addEventListener('change', () => {
|
||||
Object.values(extractModeBtns).forEach(btn => btn?.classList.remove('active'));
|
||||
extractModeBtns[radio.value]?.classList.add('active');
|
||||
document.querySelectorAll('input[name="embed_mode"]').forEach(radio => {
|
||||
radio.addEventListener('change', function() {
|
||||
const hint = document.getElementById('modeHint');
|
||||
const data = modeHints[this.value];
|
||||
if (hint && data) {
|
||||
hint.innerHTML = `<i class="bi bi-${data.icon} me-1"></i>${data.text}`;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Advanced options chevron
|
||||
const advancedOptionsDec = document.getElementById('advancedOptionsDec');
|
||||
advancedOptionsDec?.addEventListener('show.bs.collapse', () => {
|
||||
document.getElementById('advancedChevronDec')?.classList.replace('bi-chevron-down', 'bi-chevron-up');
|
||||
});
|
||||
advancedOptionsDec?.addEventListener('hide.bs.collapse', () => {
|
||||
document.getElementById('advancedChevronDec')?.classList.replace('bi-chevron-up', 'bi-chevron-down');
|
||||
// ============================================================================
|
||||
// ACCORDION SUMMARY UPDATES
|
||||
// ============================================================================
|
||||
|
||||
function updateImagesSummary() {
|
||||
const ref = document.getElementById('refPhotoInput')?.files[0];
|
||||
const stego = document.getElementById('stegoInput')?.files[0];
|
||||
const mode = document.querySelector('input[name="embed_mode"]:checked')?.value?.toUpperCase() || 'AUTO';
|
||||
const summary = document.getElementById('stepImagesSummary');
|
||||
const stepNum = document.getElementById('stepImagesNumber');
|
||||
|
||||
if (ref && stego) {
|
||||
const refName = ref.name.length > 12 ? ref.name.slice(0, 10) + '..' : ref.name;
|
||||
const stegoName = stego.name.length > 12 ? stego.name.slice(0, 10) + '..' : stego.name;
|
||||
summary.textContent = `${refName} + ${stegoName}, ${mode}`;
|
||||
summary.classList.add('has-content');
|
||||
stepNum.classList.add('complete');
|
||||
stepNum.innerHTML = '<i class="bi bi-check"></i>';
|
||||
} else if (ref || stego) {
|
||||
summary.textContent = ref ? ref.name.slice(0, 15) : stego.name.slice(0, 15);
|
||||
summary.classList.remove('has-content');
|
||||
stepNum.classList.remove('complete');
|
||||
stepNum.textContent = '1';
|
||||
} else {
|
||||
summary.textContent = 'Select reference & stego';
|
||||
summary.classList.remove('has-content');
|
||||
stepNum.classList.remove('complete');
|
||||
stepNum.textContent = '1';
|
||||
}
|
||||
}
|
||||
|
||||
function updateSecuritySummary() {
|
||||
const passphrase = document.getElementById('passphraseInput')?.value || '';
|
||||
const pin = document.getElementById('pinInput')?.value || '';
|
||||
const rsaFile = document.querySelector('input[name="rsa_key"]')?.files[0];
|
||||
const rsaPem = document.getElementById('rsaKeyPem')?.value || '';
|
||||
const summary = document.getElementById('stepSecuritySummary');
|
||||
const stepNum = document.getElementById('stepSecurityNumber');
|
||||
|
||||
const parts = [];
|
||||
if (passphrase.trim()) parts.push('passphrase');
|
||||
if (pin) parts.push('PIN');
|
||||
if (rsaFile || rsaPem) parts.push('RSA');
|
||||
|
||||
if (parts.length > 0) {
|
||||
summary.textContent = parts.join(' + ');
|
||||
summary.classList.add('has-content');
|
||||
if (passphrase.trim()) {
|
||||
stepNum.classList.add('complete');
|
||||
stepNum.innerHTML = '<i class="bi bi-check"></i>';
|
||||
}
|
||||
} else {
|
||||
summary.textContent = 'Passphrase & keys';
|
||||
summary.classList.remove('has-content');
|
||||
stepNum.classList.remove('complete');
|
||||
stepNum.textContent = '2';
|
||||
}
|
||||
}
|
||||
|
||||
// Attach listeners
|
||||
document.getElementById('refPhotoInput')?.addEventListener('change', updateImagesSummary);
|
||||
document.getElementById('stegoInput')?.addEventListener('change', updateImagesSummary);
|
||||
document.querySelectorAll('input[name="embed_mode"]').forEach(r => r.addEventListener('change', updateImagesSummary));
|
||||
|
||||
document.getElementById('passphraseInput')?.addEventListener('input', updateSecuritySummary);
|
||||
document.getElementById('pinInput')?.addEventListener('input', updateSecuritySummary);
|
||||
document.querySelector('input[name="rsa_key"]')?.addEventListener('change', updateSecuritySummary);
|
||||
|
||||
// ============================================================================
|
||||
// MODE SWITCHING
|
||||
// ============================================================================
|
||||
|
||||
const modeRadios = document.querySelectorAll('input[name="embed_mode"]');
|
||||
const modeBtns = { 'auto': document.getElementById('autoModeCard'), 'lsb': document.getElementById('lsbModeCard'), 'dct': document.getElementById('dctModeCard') };
|
||||
|
||||
modeRadios.forEach(radio => {
|
||||
radio.addEventListener('change', () => {
|
||||
Object.values(modeBtns).forEach(btn => btn?.classList.remove('active'));
|
||||
modeBtns[radio.value]?.classList.add('active');
|
||||
});
|
||||
});
|
||||
|
||||
// Loading state for decode button
|
||||
// ============================================================================
|
||||
// LOADING STATE
|
||||
// ============================================================================
|
||||
|
||||
Stegasoo.initFormLoading('decodeForm', 'decodeBtn', 'Decoding...');
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
||||
6a7378172fc0ec37143720f09a4ca34e83ec2409893aa8cd79ace5b78a64276c
|
||||
Binary file not shown.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "stegasoo"
|
||||
version = "4.1.2"
|
||||
version = "4.1.5"
|
||||
description = "Secure steganography with hybrid photo + passphrase + PIN authentication"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
# Stegasoo Pi Image Build Workflow
|
||||
|
||||
> **Note:** This guide is for developers building custom Pi images.
|
||||
> **End users:** Just download the pre-built `.img.zst` from [Releases](https://github.com/adlee-was-taken/stegasoo/releases), flash it, and boot. No build process needed.
|
||||
|
||||
Quick reference for building a distributable SD card image.
|
||||
|
||||
## Step 1: Flash Fresh Raspbian
|
||||
@@ -26,26 +29,48 @@ ssh admin@stegasoo.local
|
||||
# Take ownership of /opt (for pyenv, jpegio builds)
|
||||
sudo chown admin:admin /opt
|
||||
|
||||
# Install git (not included in Lite image)
|
||||
sudo apt-get update && sudo apt-get install -y git
|
||||
# Install git and zstd (not included in Lite image)
|
||||
sudo apt-get update && sudo apt-get install -y git zstd jq
|
||||
```
|
||||
|
||||
## Step 4: Clone & Run Setup
|
||||
## Step 4: Clone Repo
|
||||
|
||||
```bash
|
||||
cd /opt
|
||||
git clone -b 4.1 https://github.com/adlee-was-taken/stegasoo.git stegasoo
|
||||
cd stegasoo
|
||||
./rpi/setup.sh
|
||||
```
|
||||
|
||||
This takes ~15-20 minutes and installs:
|
||||
- Python 3.12 via pyenv
|
||||
- jpegio (patched for ARM)
|
||||
- Stegasoo with web UI
|
||||
- Systemd service
|
||||
## Step 5: Copy Pre-built Tarball (from host)
|
||||
|
||||
## Step 5: Test It Works
|
||||
> **Dev-only asset:** This tarball is for building Pi images, not for end users.
|
||||
> It's available on [Releases](https://github.com/adlee-was-taken/stegasoo/releases) for image builders.
|
||||
|
||||
```bash
|
||||
# On your host machine:
|
||||
scp rpi/stegasoo-rpi-runtime-env-arm64.tar.zst admin@stegasoo.local:/opt/stegasoo/rpi/
|
||||
```
|
||||
|
||||
This tarball contains:
|
||||
- pyenv with Python 3.12 (pre-compiled for ARM64)
|
||||
- venv with all dependencies (jpegio, scipy, etc.)
|
||||
|
||||
Install time: **~2 minutes** (vs 20+ min from source)
|
||||
|
||||
## Step 6: Run Setup
|
||||
|
||||
```bash
|
||||
cd /opt/stegasoo
|
||||
./rpi/setup.sh # Detects local tarball, skips download
|
||||
```
|
||||
|
||||
### From-Source Build (optional)
|
||||
|
||||
To build without the pre-built tarball:
|
||||
```bash
|
||||
./rpi/setup.sh --no-prebuilt # Takes 15-20 minutes
|
||||
```
|
||||
|
||||
## Step 7: Test It Works
|
||||
|
||||
```bash
|
||||
sudo systemctl start stegasoo
|
||||
@@ -53,7 +78,7 @@ curl -k https://localhost:5000
|
||||
# Should return HTML
|
||||
```
|
||||
|
||||
## Step 6: Sanitize for Distribution
|
||||
## Step 8: Sanitize for Distribution
|
||||
|
||||
```bash
|
||||
# Full sanitize (for final image - removes WiFi, shuts down)
|
||||
@@ -73,7 +98,7 @@ This removes:
|
||||
|
||||
The script validates all cleanup steps before finishing.
|
||||
|
||||
## Step 7: Copy the Image
|
||||
## Step 9: Pull the Image
|
||||
|
||||
Remove SD card, insert into your Linux machine:
|
||||
|
||||
@@ -81,23 +106,13 @@ Remove SD card, insert into your Linux machine:
|
||||
# Find the SD card device (CAREFUL!)
|
||||
lsblk
|
||||
|
||||
# Copy (replace sdX with actual device, e.g., sda)
|
||||
sudo dd if=/dev/sdX of=stegasoo-rpi-$(date +%Y%m%d).img bs=4M status=progress
|
||||
# Pull image (auto-resizes to 16GB, compresses with zstd)
|
||||
sudo ./rpi/pull-image.sh /dev/sdX stegasoo-rpi-4.1.5.img.zst
|
||||
```
|
||||
|
||||
## Step 8: Shrink & Compress
|
||||
The script automatically resizes rootfs to 16GB, disables auto-expand, and compresses.
|
||||
|
||||
```bash
|
||||
# Optional: Shrink image (saves space)
|
||||
wget https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh
|
||||
chmod +x pishrink.sh
|
||||
sudo ./pishrink.sh stegasoo-rpi-*.img
|
||||
|
||||
# Compress (zstd is faster than xz with similar ratio)
|
||||
zstd -19 -T0 stegasoo-rpi-*.img
|
||||
```
|
||||
|
||||
## Step 9: Distribute
|
||||
## Step 10: Distribute
|
||||
|
||||
Upload `.img.zst` to GitHub Releases.
|
||||
|
||||
@@ -115,19 +130,57 @@ zstdcat stegasoo-rpi-*.img.zst | sudo dd of=/dev/sdX bs=4M status=progress
|
||||
|
||||
---
|
||||
|
||||
## Creating the Pre-built Tarball
|
||||
|
||||
After a successful from-source build, create the pre-built tarball for future installs:
|
||||
|
||||
```bash
|
||||
# On the Pi after successful setup:
|
||||
cd ~
|
||||
|
||||
# Strip caches and tests from venv (295MB → 208MB)
|
||||
find /opt/stegasoo/venv/ -type d -name '__pycache__' -exec rm -rf {} + 2>/dev/null
|
||||
find /opt/stegasoo/venv/ -type d -name 'tests' -exec rm -rf {} + 2>/dev/null
|
||||
find /opt/stegasoo/venv/ -type d -name 'test' -exec rm -rf {} + 2>/dev/null
|
||||
|
||||
# Create venv tarball
|
||||
cd /opt/stegasoo
|
||||
tar -cf - venv/ | zstd -19 -T0 > ~/stegasoo-venv.tar.zst
|
||||
|
||||
# Create combined tarball (pyenv + venv pointer)
|
||||
cd ~
|
||||
tar -cf - .pyenv stegasoo-venv.tar.zst | zstd -19 -T0 > /tmp/stegasoo-rpi-runtime-env-arm64.tar.zst
|
||||
|
||||
# Check size (should be ~50-60MB)
|
||||
ls -lh /tmp/stegasoo-rpi-runtime-env-arm64.tar.zst
|
||||
```
|
||||
|
||||
Pull to host and upload to GitHub releases:
|
||||
```bash
|
||||
# On host:
|
||||
scp admin@stegasoo.local:/tmp/stegasoo-rpi-runtime-env-arm64.tar.zst ./
|
||||
# Upload to GitHub releases as stegasoo-rpi-runtime-env-arm64.tar.zst
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Command Summary
|
||||
|
||||
```bash
|
||||
# On Pi (after SSH):
|
||||
sudo chown admin:admin /opt
|
||||
sudo apt-get update && sudo apt-get install -y git
|
||||
sudo apt-get update && sudo apt-get install -y git zstd jq
|
||||
cd /opt && git clone -b 4.1 https://github.com/adlee-was-taken/stegasoo.git stegasoo
|
||||
cd stegasoo && ./rpi/setup.sh
|
||||
|
||||
# On host (copy tarball):
|
||||
scp rpi/stegasoo-rpi-runtime-env-arm64.tar.zst admin@stegasoo.local:/opt/stegasoo/rpi/
|
||||
|
||||
# On Pi (run setup):
|
||||
cd /opt/stegasoo && ./rpi/setup.sh
|
||||
sudo systemctl start stegasoo
|
||||
curl -k https://localhost:5000
|
||||
sudo /opt/stegasoo/rpi/sanitize-for-image.sh
|
||||
|
||||
# On your machine:
|
||||
sudo dd if=/dev/sdX of=stegasoo-rpi-$(date +%Y%m%d).img bs=4M status=progress
|
||||
zstd -19 -T0 stegasoo-rpi-*.img
|
||||
# On host (pull image - auto-resizes to 16GB):
|
||||
sudo ./rpi/pull-image.sh /dev/sdX stegasoo-rpi-4.1.5.img.zst
|
||||
```
|
||||
|
||||
@@ -32,7 +32,7 @@ cd stegasoo
|
||||
- Raspberry Pi 4 or 5
|
||||
- Raspberry Pi OS Lite (64-bit) - Bookworm or later
|
||||
- 4GB+ RAM recommended (2GB minimum)
|
||||
- ~2GB free disk space
|
||||
- 16GB+ SD card (pre-built images are 16GB)
|
||||
- Internet connection
|
||||
|
||||
### Performance
|
||||
@@ -49,6 +49,25 @@ If using a pre-built image from GitHub Releases:
|
||||
|
||||
> **Security note**: Change the default password after setup with `passwd`
|
||||
|
||||
## Updating an Existing Installation
|
||||
|
||||
To update to the latest version:
|
||||
|
||||
```bash
|
||||
cd /opt/stegasoo
|
||||
git pull origin main
|
||||
sudo systemctl restart stegasoo
|
||||
```
|
||||
|
||||
That's it - the editable install means Python uses the source directly.
|
||||
|
||||
**If dependencies changed** (check release notes), also run:
|
||||
```bash
|
||||
source venv/bin/activate
|
||||
pip install -e ".[web]"
|
||||
sudo systemctl restart stegasoo
|
||||
```
|
||||
|
||||
## After Installation
|
||||
|
||||
### Start the Service
|
||||
@@ -180,18 +199,15 @@ After Pi shuts down, remove SD card and on another Linux machine:
|
||||
# Find SD card device (BE CAREFUL - wrong device = data loss!)
|
||||
lsblk
|
||||
|
||||
# Copy (replace sdX with your SD card)
|
||||
sudo dd if=/dev/sdX of=stegasoo-rpi-$(date +%Y%m%d).img bs=4M status=progress
|
||||
|
||||
# Shrink the image (optional but recommended)
|
||||
wget https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh
|
||||
chmod +x pishrink.sh
|
||||
sudo ./pishrink.sh stegasoo-rpi-*.img
|
||||
|
||||
# Compress (zstd is faster than xz with similar compression)
|
||||
zstd -19 -T0 stegasoo-rpi-*.img
|
||||
# Pull image (auto-resizes to 16GB, compresses with zstd)
|
||||
sudo ./rpi/pull-image.sh /dev/sdX stegasoo-rpi-4.1.5.img.zst
|
||||
```
|
||||
|
||||
The `pull-image.sh` script automatically:
|
||||
- Resizes rootfs to exactly 16GB (consistent image size)
|
||||
- Disables Pi OS auto-expand
|
||||
- Compresses with zstd for fast decompression
|
||||
|
||||
### 6. Distribute
|
||||
|
||||
Upload the `.img.zst` file to GitHub Releases.
|
||||
|
||||
63
rpi/banner.sh
Normal file
63
rpi/banner.sh
Normal file
@@ -0,0 +1,63 @@
|
||||
#!/bin/bash
|
||||
# Stegasoo Banner/Header Template
|
||||
# Source this file to use the banner functions
|
||||
#
|
||||
# Usage:
|
||||
# source "$(dirname "${BASH_SOURCE[0]}")/banner.sh"
|
||||
# print_banner "Raspberry Pi Setup"
|
||||
# print_gradient_line
|
||||
|
||||
# Colors
|
||||
STEGASOO_GOLD='\033[38;5;220m'
|
||||
STEGASOO_GRAY='\033[0;90m'
|
||||
STEGASOO_WHITE='\033[1;37m'
|
||||
STEGASOO_GREEN='\033[0;32m'
|
||||
STEGASOO_NC='\033[0m'
|
||||
|
||||
# Gradient line (purple -> blue)
|
||||
print_gradient_line() {
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
}
|
||||
|
||||
# Starfield decoration line
|
||||
print_starfield() {
|
||||
echo -e "${STEGASOO_GRAY} · . · . * · . * · . * · . * · . * · . ·${STEGASOO_NC}"
|
||||
}
|
||||
|
||||
# ASCII logo (gold)
|
||||
print_logo() {
|
||||
echo -e "${STEGASOO_GOLD} ___ _____ ___ ___ _ ___ ___ ___${STEGASOO_NC}"
|
||||
echo -e "${STEGASOO_GOLD} / __||_ _|| __| / __| /_\\ / __| / _ \\ / _ \\\\${STEGASOO_NC}"
|
||||
echo -e "${STEGASOO_GOLD} \\__ \\ | | | _| | (_ | / _ \\ \\__ \\ | (_) || (_) |${STEGASOO_NC}"
|
||||
echo -e "${STEGASOO_GOLD} |___/ |_| |___| \\___//_/ \\_\\|___/ \\___/ \\___/${STEGASOO_NC}"
|
||||
}
|
||||
|
||||
# Full banner with optional subtitle
|
||||
# Usage: print_banner "Subtitle Text"
|
||||
print_banner() {
|
||||
local subtitle="$1"
|
||||
echo ""
|
||||
print_gradient_line
|
||||
print_starfield
|
||||
print_logo
|
||||
print_starfield
|
||||
print_gradient_line
|
||||
if [ -n "$subtitle" ]; then
|
||||
echo -e "${STEGASOO_WHITE} ${subtitle}${STEGASOO_NC}"
|
||||
print_gradient_line
|
||||
fi
|
||||
}
|
||||
|
||||
# Completion banner (green title)
|
||||
# Usage: print_complete_banner "Setup Complete!"
|
||||
print_complete_banner() {
|
||||
local title="$1"
|
||||
echo ""
|
||||
print_gradient_line
|
||||
print_starfield
|
||||
print_logo
|
||||
print_starfield
|
||||
print_gradient_line
|
||||
echo -e "\033[1;32m ${title}\033[0m"
|
||||
print_gradient_line
|
||||
}
|
||||
12
rpi/config.json.example
Normal file
12
rpi/config.json.example
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"hostname": "stegasoo",
|
||||
"username": "admin",
|
||||
"password": "stegasoo",
|
||||
"wifiSSID": "YourNetworkName",
|
||||
"wifiPassword": "YourWiFiPassword",
|
||||
"wifiCountry": "US",
|
||||
"locale": "en_US.UTF-8",
|
||||
"keyboardLayout": "us",
|
||||
"timezone": "America/New_York",
|
||||
"enableSSH": true
|
||||
}
|
||||
@@ -14,6 +14,10 @@
|
||||
INSTALL_DIR="/opt/stegasoo"
|
||||
FLAG_FILE="/etc/stegasoo-first-boot"
|
||||
PROFILE_HOOK="/etc/profile.d/stegasoo-wizard.sh"
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Source banner functions
|
||||
source "$SCRIPT_DIR/banner.sh"
|
||||
|
||||
# Check if this is first boot
|
||||
if [ ! -f "$FLAG_FILE" ]; then
|
||||
@@ -39,21 +43,12 @@ clear
|
||||
# Welcome
|
||||
# =============================================================================
|
||||
|
||||
print_banner "First Boot Wizard"
|
||||
echo ""
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e "\033[0;90m · . · . * · . * · . * · . * · . * · . ·\033[0m"
|
||||
echo -e "\033[38;5;220m ___ _____ ___ ___ _ ___ ___ ___\033[0m"
|
||||
echo -e "\033[38;5;220m / __||_ _|| __| / __| /_\\ / __| / _ \\ / _ \\\\\033[0m"
|
||||
echo -e "\033[38;5;220m \\__ \\ | | | _| | (_ | / _ \\ \\__ \\ | (_) || (_) |\033[0m"
|
||||
echo -e "\033[38;5;220m |___/ |_| |___| \\___//_/ \\_\\|___/ \\___/ \\___/\033[0m"
|
||||
echo -e "\033[0;90m · . · . * · . * · . * · . * · . * · . ·\033[0m"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e "\033[1;37m First Boot Wizard\033[0m"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
|
||||
gum style --foreground 245 "This wizard will help you configure your Stegasoo server"
|
||||
echo ""
|
||||
gum style --foreground 245 "This wizard will help you configure your Stegasoo server."
|
||||
gum style --foreground 245 "You can reconfigure later by editing /etc/systemd/system/stegasoo.service"
|
||||
gum style --foreground 245 "You can reconfigure later by editing:"
|
||||
gum style --foreground 214 " /etc/systemd/system/stegasoo.service"
|
||||
echo ""
|
||||
|
||||
gum confirm "Ready to begin setup?" || exit 0
|
||||
@@ -407,22 +402,11 @@ else
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo ""
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e "\033[0;90m · . · . * · . * · . * · . * · . * · . ·\033[0m"
|
||||
echo -e "\033[38;5;220m ___ _____ ___ ___ _ ___ ___ ___\033[0m"
|
||||
echo -e "\033[38;5;220m / __||_ _|| __| / __| /_\\ / __| / _ \\ / _ \\\\\033[0m"
|
||||
echo -e "\033[38;5;220m \\__ \\ | | | _| | (_ | / _ \\ \\__ \\ | (_) || (_) |\033[0m"
|
||||
echo -e "\033[38;5;220m |___/ |_| |___| \\___//_/ \\_\\|___/ \\___/ \\___/\033[0m"
|
||||
echo -e "\033[0;90m · . · . * · . * · . * · . * · . * · . ·\033[0m"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e "\033[1;32m Setup Complete!\033[0m"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
|
||||
print_complete_banner "Setup Complete!"
|
||||
echo ""
|
||||
gum style --foreground 82 --bold "Create your admin account:"
|
||||
gum style --foreground 226 " $ACCESS_URL"
|
||||
gum style --foreground 245 " $ACCESS_URL_LOCAL (if mDNS works)"
|
||||
gum style --foreground 226 " $ACCESS_URL_LOCAL"
|
||||
gum style --foreground 245 " $ACCESS_URL (fallback IP)"
|
||||
|
||||
if [ -n "$CHANNEL_KEY" ]; then
|
||||
echo ""
|
||||
|
||||
@@ -8,9 +8,14 @@
|
||||
# Supports: .img, .img.zst, .img.xz, .img.gz, .img.zst.zip (GitHub release format)
|
||||
# If device is specified, skips auto-detection (useful for NVMe/large drives)
|
||||
#
|
||||
# Optional: Place config.json in same directory for headless WiFi setup
|
||||
#
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
CONFIG_FILE="$SCRIPT_DIR/config.json"
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
@@ -18,6 +23,28 @@ BLUE='\033[0;34m'
|
||||
BOLD='\033[1m'
|
||||
NC='\033[0m'
|
||||
|
||||
# Load config if present (optional - for headless WiFi setup)
|
||||
HAS_CONFIG=false
|
||||
if [ -f "$CONFIG_FILE" ] && command -v jq &> /dev/null; then
|
||||
WIFI_SSID=$(jq -r '.wifiSSID // empty' "$CONFIG_FILE")
|
||||
WIFI_PASS=$(jq -r '.wifiPassword // empty' "$CONFIG_FILE")
|
||||
WIFI_COUNTRY=$(jq -r '.wifiCountry // "US"' "$CONFIG_FILE")
|
||||
PI_HOSTNAME=$(jq -r '.hostname // empty' "$CONFIG_FILE")
|
||||
if [ -n "$WIFI_SSID" ] && [ -n "$WIFI_PASS" ]; then
|
||||
HAS_CONFIG=true
|
||||
echo -e "${GREEN}Found config.json - will configure WiFi after flash${NC}"
|
||||
echo -e " WiFi: ${YELLOW}$WIFI_SSID${NC}"
|
||||
if [ -n "$PI_HOSTNAME" ]; then
|
||||
echo -e " Hostname: ${YELLOW}$PI_HOSTNAME${NC}"
|
||||
fi
|
||||
echo ""
|
||||
fi
|
||||
elif [ -f "$CONFIG_FILE" ]; then
|
||||
echo -e "${YELLOW}Note: config.json found but jq not installed (apt install jq)${NC}"
|
||||
echo -e "${YELLOW} WiFi will need to be configured manually after boot${NC}"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Check for required tools
|
||||
for cmd in dd lsblk; do
|
||||
if ! command -v $cmd &> /dev/null; then
|
||||
@@ -222,6 +249,17 @@ if [ -n "$MOUNTED" ]; then
|
||||
done
|
||||
fi
|
||||
|
||||
# Ask about wiping
|
||||
echo
|
||||
read -p "Wipe partition table first? (recommended if having issues) [y/N] " wipe_confirm
|
||||
if [[ "$wipe_confirm" =~ ^[Yy]$ ]]; then
|
||||
echo "Wiping partition table..."
|
||||
sudo wipefs -a "$SELECTED"
|
||||
sudo dd if=/dev/zero of="$SELECTED" bs=1M count=10 status=none
|
||||
sync
|
||||
echo " Wiped clean"
|
||||
fi
|
||||
|
||||
# Final confirmation
|
||||
echo -e "${RED}╔═══════════════════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${RED}║ WARNING: ALL DATA ON THIS DEVICE WILL BE DESTROYED! ║${NC}"
|
||||
@@ -284,6 +322,109 @@ echo ""
|
||||
echo -e "${GREEN}Syncing...${NC}"
|
||||
sync
|
||||
|
||||
# Inject WiFi config if config.json was loaded
|
||||
if [ "$HAS_CONFIG" = true ]; then
|
||||
echo ""
|
||||
echo -e "${GREEN}Configuring WiFi from config.json...${NC}"
|
||||
|
||||
# Wait for partitions to appear
|
||||
sleep 2
|
||||
partprobe "$SELECTED" 2>/dev/null || true
|
||||
sleep 1
|
||||
|
||||
# Determine boot partition
|
||||
if [[ "$SELECTED" == *"nvme"* ]] || [[ "$SELECTED" == *"mmcblk"* ]]; then
|
||||
BOOT_PART="${SELECTED}p1"
|
||||
else
|
||||
BOOT_PART="${SELECTED}1"
|
||||
fi
|
||||
|
||||
if [ -b "$BOOT_PART" ]; then
|
||||
MOUNT_DIR=$(mktemp -d)
|
||||
if mount "$BOOT_PART" "$MOUNT_DIR" 2>/dev/null; then
|
||||
# Create firstrun.sh for WiFi setup
|
||||
cat > "$MOUNT_DIR/firstrun.sh" << 'EOFSCRIPT'
|
||||
#!/bin/bash
|
||||
set +e
|
||||
|
||||
# Set hostname if provided
|
||||
if [ -n "PLACEHOLDER_HOSTNAME" ] && [ "PLACEHOLDER_HOSTNAME" != "" ]; then
|
||||
CURRENT_HOSTNAME=$(cat /etc/hostname | tr -d " \t\n\r")
|
||||
if [ -f /usr/lib/raspberrypi-sys-mods/imager_custom ]; then
|
||||
/usr/lib/raspberrypi-sys-mods/imager_custom set_hostname PLACEHOLDER_HOSTNAME
|
||||
else
|
||||
echo PLACEHOLDER_HOSTNAME >/etc/hostname
|
||||
sed -i "s/127.0.1.1.*$CURRENT_HOSTNAME/127.0.1.1\tPLACEHOLDER_HOSTNAME/g" /etc/hosts
|
||||
fi
|
||||
fi
|
||||
|
||||
# Configure WiFi
|
||||
if [ -f /usr/lib/raspberrypi-sys-mods/imager_custom ]; then
|
||||
/usr/lib/raspberrypi-sys-mods/imager_custom set_wlan 'PLACEHOLDER_SSID' 'PLACEHOLDER_WIFIPASS' 'PLACEHOLDER_COUNTRY'
|
||||
else
|
||||
# NetworkManager method (Trixie)
|
||||
cat >/etc/NetworkManager/system-connections/preconfigured.nmconnection <<'NMEOF'
|
||||
[connection]
|
||||
id=preconfigured
|
||||
type=wifi
|
||||
autoconnect=true
|
||||
|
||||
[wifi]
|
||||
mode=infrastructure
|
||||
ssid=PLACEHOLDER_SSID
|
||||
|
||||
[wifi-security]
|
||||
auth-alg=open
|
||||
key-mgmt=wpa-psk
|
||||
psk=PLACEHOLDER_WIFIPASS
|
||||
|
||||
[ipv4]
|
||||
method=auto
|
||||
|
||||
[ipv6]
|
||||
method=auto
|
||||
NMEOF
|
||||
chmod 600 /etc/NetworkManager/system-connections/preconfigured.nmconnection
|
||||
rfkill unblock wifi
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
rm -f /boot/firstrun.sh
|
||||
rm -f /boot/firmware/firstrun.sh
|
||||
sed -i 's| systemd.run.*||g' /boot/cmdline.txt 2>/dev/null
|
||||
sed -i 's| systemd.run.*||g' /boot/firmware/cmdline.txt 2>/dev/null
|
||||
exit 0
|
||||
EOFSCRIPT
|
||||
|
||||
# Replace placeholders
|
||||
sed -i "s/PLACEHOLDER_SSID/$WIFI_SSID/g" "$MOUNT_DIR/firstrun.sh"
|
||||
sed -i "s/PLACEHOLDER_WIFIPASS/$WIFI_PASS/g" "$MOUNT_DIR/firstrun.sh"
|
||||
sed -i "s/PLACEHOLDER_COUNTRY/$WIFI_COUNTRY/g" "$MOUNT_DIR/firstrun.sh"
|
||||
if [ -n "$PI_HOSTNAME" ]; then
|
||||
sed -i "s/PLACEHOLDER_HOSTNAME/$PI_HOSTNAME/g" "$MOUNT_DIR/firstrun.sh"
|
||||
else
|
||||
sed -i "s/PLACEHOLDER_HOSTNAME//g" "$MOUNT_DIR/firstrun.sh"
|
||||
fi
|
||||
chmod +x "$MOUNT_DIR/firstrun.sh"
|
||||
|
||||
# Update cmdline.txt to run firstrun.sh
|
||||
CMDLINE="$MOUNT_DIR/cmdline.txt"
|
||||
if [ -f "$CMDLINE" ]; then
|
||||
CURRENT=$(cat "$CMDLINE" | tr -d '\n' | sed 's| systemd.run.*||g')
|
||||
echo "$CURRENT systemd.run=/boot/firmware/firstrun.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target" > "$CMDLINE"
|
||||
fi
|
||||
|
||||
umount "$MOUNT_DIR"
|
||||
echo -e " ${GREEN}✓${NC} WiFi configured for: $WIFI_SSID"
|
||||
else
|
||||
echo -e " ${YELLOW}⚠${NC} Could not mount boot partition"
|
||||
fi
|
||||
rmdir "$MOUNT_DIR" 2>/dev/null || true
|
||||
else
|
||||
echo -e " ${YELLOW}⚠${NC} Boot partition not found"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}╔═══════════════════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${GREEN}║ Flash Complete! ║${NC}"
|
||||
@@ -291,5 +432,11 @@ echo -e "${GREEN}╚════════════════════
|
||||
echo ""
|
||||
echo -e "You can now remove the SD card and boot your Raspberry Pi."
|
||||
echo ""
|
||||
echo -e "${YELLOW}Tip:${NC} On first boot, SSH in and the setup wizard will run automatically."
|
||||
if [ "$HAS_CONFIG" = true ]; then
|
||||
echo -e "${GREEN}WiFi pre-configured${NC} - Pi will connect to $WIFI_SSID on boot"
|
||||
echo -e "SSH: ${YELLOW}ssh admin@${PI_HOSTNAME:-stegasoo}.local${NC} (password: stegasoo)"
|
||||
else
|
||||
echo -e "${YELLOW}Tip:${NC} On first boot, the setup wizard will help configure WiFi."
|
||||
echo -e "${YELLOW}Tip:${NC} Or place config.json in rpi/ for headless setup next time."
|
||||
fi
|
||||
echo ""
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
# Flash Raspberry Pi image with headless config (Trixie/Bookworm compatible)
|
||||
# Usage: ./flash-pi.sh <image.img.xz> <device>
|
||||
# Usage: ./flash-stock-img.sh <image.img.xz> <device>
|
||||
# Reads settings from config.json in same directory
|
||||
#
|
||||
# Uses the same firstrun.sh approach as rpi-imager for compatibility
|
||||
@@ -103,13 +103,100 @@ sleep 1
|
||||
# ============================================================================
|
||||
if [ -b "${DEVICE}1" ]; then
|
||||
BOOT_PART="${DEVICE}1"
|
||||
ROOT_PART="${DEVICE}2"
|
||||
elif [ -b "${DEVICE}p1" ]; then
|
||||
BOOT_PART="${DEVICE}p1"
|
||||
ROOT_PART="${DEVICE}p2"
|
||||
else
|
||||
echo "Error: Could not find boot partition"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
# Resize rootfs to 16GB (faster imaging)
|
||||
# ============================================================================
|
||||
echo
|
||||
read -p "Resize rootfs to 16GB for faster imaging? [Y/n] " resize_confirm
|
||||
if [[ ! "$resize_confirm" =~ ^[Nn]$ ]]; then
|
||||
echo "Resizing rootfs partition to 16GB..."
|
||||
|
||||
# Get current partition size in bytes
|
||||
CURRENT_SIZE=$(sudo blockdev --getsize64 "$ROOT_PART")
|
||||
TARGET_BYTES=$((16 * 1024 * 1024 * 1024)) # 16GB in bytes
|
||||
|
||||
# Get boot partition end in sectors
|
||||
BOOT_END=$(sudo parted -s "$DEVICE" unit s print | grep "^ 1" | awk '{print $3}' | tr -d 's')
|
||||
|
||||
# Calculate 16GB in sectors (512 byte sectors)
|
||||
ROOT_SIZE_SECTORS=33554432
|
||||
ROOT_END=$((BOOT_END + ROOT_SIZE_SECTORS))
|
||||
|
||||
if [ "$CURRENT_SIZE" -lt "$TARGET_BYTES" ]; then
|
||||
# EXPANDING: partition first, then filesystem
|
||||
echo "Current partition is smaller than 16GB - expanding..."
|
||||
|
||||
# Delete and recreate partition 2 with 16GB size
|
||||
echo "Expanding partition to 16GB..."
|
||||
sudo parted -s "$DEVICE" rm 2
|
||||
sudo parted -s "$DEVICE" mkpart primary ext4 $((BOOT_END + 1))s ${ROOT_END}s
|
||||
|
||||
# Refresh partition table
|
||||
sudo partprobe "$DEVICE"
|
||||
sleep 2
|
||||
|
||||
# Expand filesystem to fill the new partition
|
||||
echo "Expanding filesystem to fill partition..."
|
||||
sudo e2fsck -f -y "$ROOT_PART" 2>/dev/null || true
|
||||
sudo resize2fs "$ROOT_PART"
|
||||
else
|
||||
# SHRINKING: filesystem first, then partition
|
||||
echo "Current partition is larger than 16GB - shrinking..."
|
||||
|
||||
# Check and shrink filesystem first
|
||||
echo "Checking filesystem..."
|
||||
sudo e2fsck -f -y "$ROOT_PART" 2>/dev/null || true
|
||||
|
||||
# Shrink filesystem to 15.5GB (leave room for partition overhead)
|
||||
echo "Shrinking filesystem to 15500M..."
|
||||
sudo resize2fs "$ROOT_PART" 15500M
|
||||
|
||||
# Delete and recreate partition 2 with 16GB size
|
||||
echo "Shrinking partition to 16GB..."
|
||||
sudo parted -s "$DEVICE" rm 2
|
||||
sudo parted -s "$DEVICE" mkpart primary ext4 $((BOOT_END + 1))s ${ROOT_END}s
|
||||
|
||||
# Refresh partition table
|
||||
sudo partprobe "$DEVICE"
|
||||
sleep 2
|
||||
|
||||
# Expand filesystem to fill the partition exactly
|
||||
echo "Expanding filesystem to fill partition..."
|
||||
sudo e2fsck -f -y "$ROOT_PART" 2>/dev/null || true
|
||||
sudo resize2fs "$ROOT_PART"
|
||||
fi
|
||||
|
||||
# Verify and show result
|
||||
echo "Verifying partition size..."
|
||||
sudo parted -s "$DEVICE" unit GB print | grep "^ 2"
|
||||
|
||||
# Disable Pi OS auto-expand on first boot
|
||||
echo "Disabling auto-expand..."
|
||||
TEMP_ROOT=$(mktemp -d)
|
||||
sudo mount "$ROOT_PART" "$TEMP_ROOT"
|
||||
|
||||
# Remove resize2fs_once service if it exists
|
||||
sudo rm -f "$TEMP_ROOT/etc/init.d/resize2fs_once"
|
||||
sudo rm -f "$TEMP_ROOT/etc/rc3.d/S01resize2fs_once"
|
||||
|
||||
# Disable the systemd resize service
|
||||
sudo rm -f "$TEMP_ROOT/etc/systemd/system/multi-user.target.wants/rpi-resizerootfs.service"
|
||||
|
||||
sudo umount "$TEMP_ROOT"
|
||||
rmdir "$TEMP_ROOT"
|
||||
|
||||
echo " Rootfs set to 16GB (auto-expand disabled)"
|
||||
fi
|
||||
|
||||
MOUNT_DIR=$(mktemp -d)
|
||||
|
||||
# ============================================================================
|
||||
@@ -213,8 +300,8 @@ sudo chmod +x "$MOUNT_DIR/firstrun.sh"
|
||||
echo "Updating cmdline.txt..."
|
||||
CMDLINE="$MOUNT_DIR/cmdline.txt"
|
||||
if [ -f "$CMDLINE" ]; then
|
||||
# Read current cmdline, strip any existing systemd.run, append new one
|
||||
CURRENT=$(cat "$CMDLINE" | tr -d '\n' | sed 's| systemd.run.*||g')
|
||||
# Read current cmdline, strip existing systemd.run and init= (auto-expand)
|
||||
CURRENT=$(cat "$CMDLINE" | tr -d '\n' | sed 's| systemd.run.*||g' | sed 's| init=[^ ]*||g')
|
||||
echo "$CURRENT systemd.run=/boot/firmware/firstrun.sh systemd.run_success_action=reboot systemd.unit=kernel-command-line.target" | sudo tee "$CMDLINE" > /dev/null
|
||||
echo " cmdline.txt updated"
|
||||
fi
|
||||
@@ -229,4 +316,17 @@ echo " User: $PI_USER"
|
||||
echo " SSH: enabled"
|
||||
echo " WiFi: $WIFI_SSID"
|
||||
echo
|
||||
echo "Insert into Pi and boot. Find it with: ping $PI_HOSTNAME.local"
|
||||
echo "Insert into Pi and boot. Access via:"
|
||||
echo " mDNS: http://$PI_HOSTNAME.local"
|
||||
echo " Find IP: ping $PI_HOSTNAME.local"
|
||||
echo
|
||||
echo "Once booted, SSH with: ssh $PI_USER@$PI_HOSTNAME.local"
|
||||
|
||||
# If we resized, remind about pull-image.sh
|
||||
if [[ ! "$resize_confirm" =~ ^[Nn]$ ]]; then
|
||||
echo
|
||||
echo "=== After setup, use pull-image.sh to create distributable image ==="
|
||||
echo " ./pull-image.sh $DEVICE stegasoo-rpi-VERSION.img.zst"
|
||||
echo
|
||||
echo "This will only pull the 16GB partition, not the entire SD card."
|
||||
fi
|
||||
29
rpi/host-requirements.txt
Normal file
29
rpi/host-requirements.txt
Normal file
@@ -0,0 +1,29 @@
|
||||
# Host Machine Dependencies for Stegasoo Pi Scripts
|
||||
# =================================================
|
||||
#
|
||||
# Quick install (Debian/Ubuntu):
|
||||
# sudo apt install parted e2fsprogs zstd zip bc pv jq unzip sshpass
|
||||
#
|
||||
# Or install with this file:
|
||||
# sudo apt install $(grep -v '^#' rpi/host-requirements.txt | grep -v '^$' | xargs)
|
||||
|
||||
# pull-image.sh - Create distributable images
|
||||
parted # Partition table reading/writing
|
||||
e2fsprogs # e2fsck, resize2fs for ext4
|
||||
zstd # Compression (zstd -T0 -3)
|
||||
zip # Optional .zst.zip wrapper for GitHub
|
||||
bc # Floating point math for size display
|
||||
pv # Progress bar (optional, falls back to dd status)
|
||||
|
||||
# flash-image.sh - Flash images to SD cards
|
||||
unzip # Extract .zst.zip wrappers
|
||||
zstd # Decompress .zst images
|
||||
pv # Progress bar (optional)
|
||||
jq # Parse config.json for headless WiFi (optional)
|
||||
|
||||
# kickoff-pi-test.sh - Automated flash+test
|
||||
sshpass # Non-interactive SSH with password
|
||||
avahi-utils # avahi-resolve for .local hostname lookup
|
||||
|
||||
# Optional tools
|
||||
rpi-imager # Faster flashing (flash-image.sh falls back to dd)
|
||||
193
rpi/kickoff-pi-test.sh
Executable file
193
rpi/kickoff-pi-test.sh
Executable file
@@ -0,0 +1,193 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Stegasoo Pi Test Kickoff Script
|
||||
# Automates: flash -> wait for boot -> setup -> test
|
||||
#
|
||||
# Usage: ./kickoff-pi-test.sh <image.img.zst> </dev/sdX>
|
||||
#
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Pi connection settings
|
||||
PI_HOST="stegasoo.local"
|
||||
PI_USER="admin"
|
||||
PI_PASS="stegasoo"
|
||||
|
||||
# Colors
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m'
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Helper functions
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
# Wait for Pi to be reachable
|
||||
wait_for_pi() {
|
||||
local attempt=1
|
||||
ssh-keygen -R "$PI_HOST" 2>/dev/null
|
||||
|
||||
echo "Waiting for $PI_USER@$PI_HOST..."
|
||||
while ! sshpass -p "$PI_PASS" ssh -o ConnectTimeout=2 -o StrictHostKeyChecking=no -o BatchMode=no -o UserKnownHostsFile=/dev/null "$PI_USER@$PI_HOST" "exit" 2>/dev/null; do
|
||||
printf "\rAttempt %d..." "$attempt"
|
||||
((attempt++))
|
||||
sleep 2
|
||||
done
|
||||
|
||||
printf "\r${GREEN}✓ Ready after %d attempts${NC}\n" "$attempt"
|
||||
printf '\a' # Terminal bell
|
||||
}
|
||||
|
||||
# Run command on Pi (non-interactive)
|
||||
run_on_pi() {
|
||||
sshpass -p "$PI_PASS" ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$PI_USER@$PI_HOST" "$@"
|
||||
}
|
||||
|
||||
# Run command on Pi (interactive/PTY)
|
||||
run_on_pi_interactive() {
|
||||
sshpass -p "$PI_PASS" ssh -t -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$PI_USER@$PI_HOST" "$@"
|
||||
}
|
||||
|
||||
# Copy file to Pi
|
||||
scp_to_pi() {
|
||||
local src="$1"
|
||||
local dst="$2"
|
||||
sshpass -p "$PI_PASS" scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$src" "$PI_USER@$PI_HOST:$dst"
|
||||
}
|
||||
|
||||
# Interactive SSH session
|
||||
ssh_pi() {
|
||||
ssh-keygen -R "$PI_HOST" 2>/dev/null
|
||||
sshpass -p "$PI_PASS" ssh -t -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$PI_USER@$PI_HOST" "$@"
|
||||
}
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Main
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
if [[ $# -lt 2 ]]; then
|
||||
echo "Usage: $0 <image.img.zst> </dev/sdX>"
|
||||
echo ""
|
||||
echo "Example: $0 stegasoo-v4.1.img.zst /dev/sda"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
IMAGE="$1"
|
||||
DEVICE="$2"
|
||||
|
||||
if [[ ! -f "$IMAGE" ]]; then
|
||||
echo -e "${RED}Error: Image file not found: $IMAGE${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -b "$DEVICE" ]]; then
|
||||
echo -e "${RED}Error: Device not found: $DEVICE${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${CYAN}╔═══════════════════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${CYAN}║ Stegasoo Pi Test Kickoff ║${NC}"
|
||||
echo -e "${CYAN}╚═══════════════════════════════════════════════════════════════╝${NC}"
|
||||
echo ""
|
||||
echo -e "Image: ${YELLOW}$IMAGE${NC}"
|
||||
echo -e "Device: ${YELLOW}$DEVICE${NC}"
|
||||
echo ""
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 1: Flash the image
|
||||
# -----------------------------------------------------------------------------
|
||||
echo -e "${GREEN}[1/8]${NC} Flashing image..."
|
||||
echo ""
|
||||
|
||||
# Auto-answer: "yes" for confirm, "y" for wipe, "y" for resize
|
||||
printf 'yes\ny\ny\n' | "$SCRIPT_DIR/flash-stock-img.sh" "$IMAGE" "$DEVICE"
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}[2/8]${NC} Flash complete! Waiting for SD card insertion..."
|
||||
echo ""
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 2: Wait for user to insert SD card
|
||||
# -----------------------------------------------------------------------------
|
||||
echo -e "${YELLOW}════════════════════════════════════════════════════════════════${NC}"
|
||||
echo -e "${YELLOW} Insert SD card into Pi and power on${NC}"
|
||||
echo -e "${YELLOW}════════════════════════════════════════════════════════════════${NC}"
|
||||
echo ""
|
||||
read -p "Press ENTER when Pi is booting..."
|
||||
|
||||
echo ""
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 3: Wait for Pi to be ready
|
||||
# -----------------------------------------------------------------------------
|
||||
echo -e "${GREEN}[3/8]${NC} Waiting for Pi to boot..."
|
||||
echo ""
|
||||
|
||||
wait_for_pi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 4: Pre-setup (install dependencies)
|
||||
# -----------------------------------------------------------------------------
|
||||
echo ""
|
||||
echo -e "${GREEN}[4/8]${NC} Installing dependencies on Pi..."
|
||||
echo ""
|
||||
|
||||
run_on_pi "sudo chown admin:admin /opt && sudo apt-get update && sudo apt-get install -y git zstd jq"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 5: Clone repo
|
||||
# -----------------------------------------------------------------------------
|
||||
echo ""
|
||||
echo -e "${GREEN}[5/8]${NC} Cloning Stegasoo repo..."
|
||||
echo ""
|
||||
|
||||
run_on_pi "cd /opt && git clone -b 4.1 https://github.com/adlee-was-taken/stegasoo.git stegasoo"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 6: Copy pre-built tarball
|
||||
# -----------------------------------------------------------------------------
|
||||
echo ""
|
||||
echo -e "${GREEN}[6/8]${NC} Copying pre-built tarball to Pi..."
|
||||
echo ""
|
||||
|
||||
TARBALL="$SCRIPT_DIR/stegasoo-rpi-runtime-env-arm64.tar.zst"
|
||||
if [[ -f "$TARBALL" ]]; then
|
||||
scp_to_pi "$TARBALL" "/opt/stegasoo/rpi/"
|
||||
echo -e " ${GREEN}✓${NC} Tarball copied"
|
||||
else
|
||||
echo -e " ${YELLOW}⚠${NC} Tarball not found at $TARBALL"
|
||||
echo -e " ${YELLOW}⚠${NC} Setup will build from source (takes longer)"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 7: Run setup
|
||||
# -----------------------------------------------------------------------------
|
||||
echo ""
|
||||
echo -e "${GREEN}[7/8]${NC} Running setup.sh on Pi..."
|
||||
echo ""
|
||||
|
||||
run_on_pi_interactive "cd /opt/stegasoo && ./rpi/setup.sh"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Step 8: Test it works
|
||||
# -----------------------------------------------------------------------------
|
||||
echo ""
|
||||
echo -e "${GREEN}[8/8]${NC} Testing Stegasoo..."
|
||||
echo ""
|
||||
|
||||
run_on_pi "sudo systemctl start stegasoo && sleep 2 && curl -sk https://localhost:5000 | head -5"
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}════════════════════════════════════════════════════════════════${NC}"
|
||||
echo -e "${GREEN} Build complete! Pi is ready for testing.${NC}"
|
||||
echo -e "${GREEN}════════════════════════════════════════════════════════════════${NC}"
|
||||
echo ""
|
||||
echo -e "Access: ${YELLOW}https://stegasoo.local:5000${NC}"
|
||||
echo ""
|
||||
read -p "Press ENTER to SSH into Pi for manual testing..."
|
||||
|
||||
ssh_pi
|
||||
@@ -1,31 +1,26 @@
|
||||
#!/bin/bash
|
||||
# Pull Raspberry Pi image from SD card (after setup)
|
||||
# Resizes rootfs to 16GB for consistent image size, then pulls
|
||||
#
|
||||
# Pull Stegasoo image from SD card
|
||||
# Auto-detects SD card, copies with progress, shrinks, and compresses
|
||||
#
|
||||
# Usage: ./pull-image.sh [output-name] [device]
|
||||
# Output will be: stegasoo-rpi-YYYYMMDD.img.zst (or custom name)
|
||||
# Use .img extension to skip compression: ./pull-image.sh foo.img
|
||||
#
|
||||
# If device is specified, skips auto-detection (useful for large drives)
|
||||
#
|
||||
# Usage: ./pull-image.sh <device> <output.img.zst>
|
||||
# Example: ./pull-image.sh /dev/sdb stegasoo-rpi-4.1.5.img.zst
|
||||
|
||||
set -e
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
BOLD='\033[1m'
|
||||
NC='\033[0m'
|
||||
|
||||
# Check for required tools
|
||||
for cmd in dd pv zstd lsblk; do
|
||||
if ! command -v $cmd &> /dev/null; then
|
||||
echo -e "${RED}Error: $cmd is required but not installed.${NC}"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [ $# -ne 2 ]; then
|
||||
echo "Usage: $0 <device> <output.img.zst>"
|
||||
echo "Example: $0 /dev/sdb stegasoo-rpi-4.1.5.img.zst"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
DEVICE="$1"
|
||||
OUTPUT="$2"
|
||||
|
||||
# Check for root
|
||||
if [ "$EUID" -ne 0 ]; then
|
||||
@@ -33,175 +28,185 @@ if [ "$EUID" -ne 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Output filename and optional device
|
||||
if [ -n "$1" ]; then
|
||||
OUTPUT="$1"
|
||||
else
|
||||
OUTPUT="stegasoo-rpi-$(date +%Y%m%d).img.zst"
|
||||
fi
|
||||
MANUAL_DEVICE="$2"
|
||||
|
||||
# Check if output ends in .img (skip compression) or .zst (compress)
|
||||
SKIP_COMPRESS=false
|
||||
if [[ "$OUTPUT" == *.img ]]; then
|
||||
IMG_FILE="$OUTPUT"
|
||||
SKIP_COMPRESS=true
|
||||
elif [[ "$OUTPUT" == *.zst ]]; then
|
||||
IMG_FILE="${OUTPUT%.zst}"
|
||||
else
|
||||
# No recognized extension, add .img.zst
|
||||
IMG_FILE="${OUTPUT}.img"
|
||||
OUTPUT="${OUTPUT}.img.zst"
|
||||
if [ ! -b "$DEVICE" ]; then
|
||||
echo -e "${RED}Error: Device not found: $DEVICE${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${BLUE}"
|
||||
echo "╔═══════════════════════════════════════════════════════════════╗"
|
||||
echo "║ Stegasoo SD Card Image Puller ║"
|
||||
echo "╚═══════════════════════════════════════════════════════════════╝"
|
||||
echo -e "${NC}"
|
||||
|
||||
# Use manual device or auto-detect
|
||||
if [ -n "$MANUAL_DEVICE" ]; then
|
||||
# Manual device specified
|
||||
if [ ! -b "$MANUAL_DEVICE" ]; then
|
||||
echo -e "${RED}Error: $MANUAL_DEVICE is not a block device${NC}"
|
||||
exit 1
|
||||
fi
|
||||
SELECTED="$MANUAL_DEVICE"
|
||||
echo -e "Using specified device: ${YELLOW}$SELECTED${NC}"
|
||||
echo ""
|
||||
lsblk "$SELECTED" -o NAME,SIZE,TYPE,MODEL
|
||||
echo ""
|
||||
else
|
||||
# Auto-detect SD card candidates
|
||||
# Looking for: USB/removable, 8-128GB, not mounted as root filesystem
|
||||
echo -e "${BOLD}Scanning for SD cards...${NC}"
|
||||
echo ""
|
||||
|
||||
declare -a CANDIDATES
|
||||
declare -a CANDIDATE_INFO
|
||||
|
||||
while IFS= read -r line; do
|
||||
DEV=$(echo "$line" | awk '{print $1}')
|
||||
SIZE=$(echo "$line" | awk '{print $2}')
|
||||
TYPE=$(echo "$line" | awk '{print $3}')
|
||||
TRAN=$(echo "$line" | awk '{print $4}')
|
||||
MODEL=$(echo "$line" | awk '{print $5" "$6" "$7}' | xargs)
|
||||
|
||||
# Skip if it's the root filesystem
|
||||
if mount | grep -q "^/dev/${DEV}[0-9]* on / "; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# Skip if any partition is mounted as root
|
||||
ROOT_DEV=$(mount | grep " on / " | awk '{print $1}' | sed 's/[0-9]*$//')
|
||||
if [[ "/dev/$DEV" == "$ROOT_DEV" ]]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# Get size in bytes for reliable comparison
|
||||
SIZE_BYTES=$(lsblk -b -d -o SIZE -n "/dev/$DEV" 2>/dev/null | tr -d ' ')
|
||||
SIZE_GB_INT=$((SIZE_BYTES / 1073741824)) # 1024^3
|
||||
|
||||
# Check if size is in SD card range (8GB - 128GB)
|
||||
if [ "$SIZE_GB_INT" -ge 8 ] && [ "$SIZE_GB_INT" -le 128 ]; then
|
||||
CANDIDATES+=("/dev/$DEV")
|
||||
CANDIDATE_INFO+=("$SIZE $TYPE ${TRAN:-???} $MODEL")
|
||||
fi
|
||||
done < <(lsblk -d -o NAME,SIZE,TYPE,TRAN,MODEL -n | grep "disk")
|
||||
|
||||
if [ ${#CANDIDATES[@]} -eq 0 ]; then
|
||||
echo -e "${RED}No SD card candidates found.${NC}"
|
||||
echo "Looking for USB/removable disks between 8GB and 128GB."
|
||||
echo ""
|
||||
echo "Available disks:"
|
||||
lsblk -d -o NAME,SIZE,TYPE,TRAN,MODEL
|
||||
echo ""
|
||||
echo -e "${YELLOW}Tip: Specify device manually: $0 output.img.zst /dev/sdX${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}Found ${#CANDIDATES[@]} candidate(s):${NC}"
|
||||
echo ""
|
||||
|
||||
for i in "${!CANDIDATES[@]}"; do
|
||||
echo -e " ${BOLD}[$((i+1))]${NC} ${CANDIDATES[$i]} - ${CANDIDATE_INFO[$i]}"
|
||||
done
|
||||
|
||||
echo ""
|
||||
|
||||
if [ ${#CANDIDATES[@]} -eq 1 ]; then
|
||||
SELECTED="${CANDIDATES[0]}"
|
||||
echo -e "Auto-selected: ${YELLOW}$SELECTED${NC}"
|
||||
else
|
||||
read -p "Select device [1-${#CANDIDATES[@]}]: " -r
|
||||
if [[ ! $REPLY =~ ^[0-9]+$ ]] || [ "$REPLY" -lt 1 ] || [ "$REPLY" -gt ${#CANDIDATES[@]} ]; then
|
||||
echo -e "${RED}Invalid selection.${NC}"
|
||||
exit 1
|
||||
fi
|
||||
SELECTED="${CANDIDATES[$((REPLY-1))]}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Show partitions
|
||||
echo ""
|
||||
echo -e "${BOLD}Partitions on $SELECTED:${NC}"
|
||||
lsblk "$SELECTED" -o NAME,SIZE,FSTYPE,LABEL,MOUNTPOINT
|
||||
echo ""
|
||||
|
||||
# Final confirmation
|
||||
echo -e "${RED}╔═══════════════════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${RED}║ WARNING: This will read the ENTIRE device: ║${NC}"
|
||||
echo -e "${RED}║ $SELECTED ║${NC}"
|
||||
echo -e "${RED}╚═══════════════════════════════════════════════════════════════╝${NC}"
|
||||
echo ""
|
||||
echo -e "Output: ${YELLOW}$OUTPUT${NC}"
|
||||
echo ""
|
||||
read -p "Continue? [y/N] " -n 1 -r
|
||||
echo -e "${BOLD}Device info:${NC}"
|
||||
lsblk "$DEVICE"
|
||||
echo
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||
|
||||
# Find partitions
|
||||
if [ -b "${DEVICE}1" ]; then
|
||||
BOOT_PART="${DEVICE}1"
|
||||
ROOT_PART="${DEVICE}2"
|
||||
elif [ -b "${DEVICE}p1" ]; then
|
||||
BOOT_PART="${DEVICE}p1"
|
||||
ROOT_PART="${DEVICE}p2"
|
||||
else
|
||||
echo -e "${RED}Error: Could not find partitions${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Unmount any mounted partitions
|
||||
echo -e "${YELLOW}Unmounting partitions...${NC}"
|
||||
umount "$BOOT_PART" 2>/dev/null || true
|
||||
umount "$ROOT_PART" 2>/dev/null || true
|
||||
|
||||
# ============================================================================
|
||||
# Resize rootfs to 16GB
|
||||
# ============================================================================
|
||||
echo
|
||||
echo -e "${BOLD}Checking partition size...${NC}"
|
||||
|
||||
# Get current partition size in bytes
|
||||
CURRENT_SIZE=$(blockdev --getsize64 "$ROOT_PART")
|
||||
TARGET_BYTES=$((16 * 1024 * 1024 * 1024)) # 16GB in bytes
|
||||
CURRENT_GB=$(echo "scale=2; $CURRENT_SIZE / 1073741824" | bc)
|
||||
|
||||
echo " Current rootfs size: ${CURRENT_GB}GB"
|
||||
|
||||
if [ "$CURRENT_SIZE" -gt "$TARGET_BYTES" ]; then
|
||||
echo -e "${YELLOW}Resizing rootfs to 16GB...${NC}"
|
||||
|
||||
# Get boot partition end in sectors
|
||||
BOOT_END=$(parted -s "$DEVICE" unit s print | grep "^ 1" | awk '{print $3}' | tr -d 's')
|
||||
|
||||
# Calculate 16GB in sectors (512 byte sectors)
|
||||
ROOT_SIZE_SECTORS=33554432
|
||||
ROOT_END=$((BOOT_END + ROOT_SIZE_SECTORS))
|
||||
|
||||
# SHRINKING: filesystem first, then partition
|
||||
echo " Checking filesystem..."
|
||||
e2fsck -f -y "$ROOT_PART" 2>/dev/null || true
|
||||
|
||||
# Shrink filesystem to 15.5GB (leave room for partition overhead)
|
||||
echo " Shrinking filesystem to 15500M..."
|
||||
resize2fs "$ROOT_PART" 15500M
|
||||
|
||||
# Delete and recreate partition 2 with 16GB size
|
||||
echo " Shrinking partition to 16GB..."
|
||||
parted -s "$DEVICE" rm 2
|
||||
parted -s "$DEVICE" mkpart primary ext4 $((BOOT_END + 1))s ${ROOT_END}s
|
||||
|
||||
# Refresh partition table
|
||||
partprobe "$DEVICE"
|
||||
sleep 2
|
||||
|
||||
# Expand filesystem to fill the partition exactly
|
||||
echo " Expanding filesystem to fill partition..."
|
||||
e2fsck -f -y "$ROOT_PART" 2>/dev/null || true
|
||||
resize2fs "$ROOT_PART"
|
||||
|
||||
echo -e "${GREEN} Rootfs resized to 16GB${NC}"
|
||||
elif [ "$CURRENT_SIZE" -lt "$TARGET_BYTES" ]; then
|
||||
echo -e "${YELLOW} Rootfs is smaller than 16GB - expanding...${NC}"
|
||||
|
||||
# Get boot partition end in sectors
|
||||
BOOT_END=$(parted -s "$DEVICE" unit s print | grep "^ 1" | awk '{print $3}' | tr -d 's')
|
||||
ROOT_SIZE_SECTORS=33554432
|
||||
ROOT_END=$((BOOT_END + ROOT_SIZE_SECTORS))
|
||||
|
||||
# EXPANDING: partition first, then filesystem
|
||||
parted -s "$DEVICE" rm 2
|
||||
parted -s "$DEVICE" mkpart primary ext4 $((BOOT_END + 1))s ${ROOT_END}s
|
||||
|
||||
partprobe "$DEVICE"
|
||||
sleep 2
|
||||
|
||||
e2fsck -f -y "$ROOT_PART" 2>/dev/null || true
|
||||
resize2fs "$ROOT_PART"
|
||||
|
||||
echo -e "${GREEN} Rootfs expanded to 16GB${NC}"
|
||||
else
|
||||
echo -e "${GREEN} Rootfs already ~16GB${NC}"
|
||||
fi
|
||||
|
||||
# ============================================================================
|
||||
# Disable auto-expand on first boot
|
||||
# ============================================================================
|
||||
echo
|
||||
echo -e "${YELLOW}Disabling auto-expand...${NC}"
|
||||
TEMP_ROOT=$(mktemp -d)
|
||||
mount "$ROOT_PART" "$TEMP_ROOT"
|
||||
|
||||
# Remove resize2fs_once service if it exists
|
||||
rm -f "$TEMP_ROOT/etc/init.d/resize2fs_once"
|
||||
rm -f "$TEMP_ROOT/etc/rc3.d/S01resize2fs_once"
|
||||
|
||||
# Disable the systemd resize service
|
||||
rm -f "$TEMP_ROOT/etc/systemd/system/multi-user.target.wants/rpi-resizerootfs.service"
|
||||
|
||||
umount "$TEMP_ROOT"
|
||||
rmdir "$TEMP_ROOT"
|
||||
echo -e "${GREEN} Auto-expand disabled${NC}"
|
||||
|
||||
# ============================================================================
|
||||
# Pull image
|
||||
# ============================================================================
|
||||
echo
|
||||
echo -e "${BOLD}Partition table:${NC}"
|
||||
parted -s "$DEVICE" unit s print
|
||||
echo
|
||||
|
||||
# Get the end of the last partition (partition 2 = rootfs)
|
||||
END_SECTOR=$(parted -s "$DEVICE" unit s print | grep "^ 2" | awk '{print $3}' | tr -d 's')
|
||||
|
||||
if [ -z "$END_SECTOR" ]; then
|
||||
echo -e "${RED}Error: Could not determine partition 2 end sector${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Add a small buffer (1MB = 2048 sectors) for safety
|
||||
TOTAL_SECTORS=$((END_SECTOR + 2048))
|
||||
TOTAL_BYTES=$((TOTAL_SECTORS * 512))
|
||||
TOTAL_GB=$(echo "scale=2; $TOTAL_BYTES / 1073741824" | bc)
|
||||
|
||||
echo -e "Image size: ${YELLOW}~${TOTAL_GB}GB${NC} (${TOTAL_SECTORS} sectors)"
|
||||
echo -e "Output: ${YELLOW}$OUTPUT${NC}"
|
||||
echo
|
||||
|
||||
read -p "Proceed with image pull? [Y/n] " confirm
|
||||
if [[ "$confirm" =~ ^[Nn]$ ]]; then
|
||||
echo "Aborted."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Get device size for pv
|
||||
DEV_SIZE=$(blockdev --getsize64 "$SELECTED")
|
||||
echo
|
||||
echo -e "${GREEN}Pulling image...${NC}"
|
||||
echo
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}[1/3]${NC} Copying image from $SELECTED..."
|
||||
dd if="$SELECTED" bs=4M status=none | pv -s "$DEV_SIZE" > "$IMG_FILE"
|
||||
sync
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}[2/3]${NC} Shrinking image..."
|
||||
if command -v pishrink.sh &> /dev/null; then
|
||||
pishrink.sh "$IMG_FILE"
|
||||
elif [ -f "./pishrink.sh" ]; then
|
||||
bash ./pishrink.sh "$IMG_FILE"
|
||||
elif [ -f "../pishrink.sh" ]; then
|
||||
bash ../pishrink.sh "$IMG_FILE"
|
||||
# Use pv if available for progress, otherwise fallback to dd status
|
||||
if command -v pv &> /dev/null; then
|
||||
dd if="$DEVICE" bs=512 count=$TOTAL_SECTORS 2>/dev/null | \
|
||||
pv -s $TOTAL_BYTES | \
|
||||
zstd -T0 -3 > "$OUTPUT"
|
||||
else
|
||||
echo -e "${YELLOW}pishrink.sh not found, skipping shrink step.${NC}"
|
||||
echo "Download from: https://github.com/Drewsif/PiShrink"
|
||||
dd if="$DEVICE" bs=512 count=$TOTAL_SECTORS status=progress | \
|
||||
zstd -T0 -3 > "$OUTPUT"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
if [ "$SKIP_COMPRESS" = true ]; then
|
||||
echo -e "${GREEN}[3/3]${NC} Skipping compression (.img output)"
|
||||
FINAL_SIZE=$(du -h "$IMG_FILE" | awk '{print $1}')
|
||||
OUTPUT="$IMG_FILE"
|
||||
else
|
||||
echo -e "${GREEN}[3/3]${NC} Compressing with zstd..."
|
||||
pv "$IMG_FILE" | zstd -19 -T0 -q > "$OUTPUT"
|
||||
rm -f "$IMG_FILE"
|
||||
FINAL_SIZE=$(du -h "$OUTPUT" | awk '{print $1}')
|
||||
fi
|
||||
echo
|
||||
echo -e "${GREEN}Done!${NC} Image saved to: $OUTPUT"
|
||||
ls -lh "$OUTPUT"
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}╔═══════════════════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${GREEN}║ Image Complete! ║${NC}"
|
||||
echo -e "${GREEN}╚═══════════════════════════════════════════════════════════════╝${NC}"
|
||||
echo ""
|
||||
echo -e "Output: ${YELLOW}$OUTPUT${NC}"
|
||||
echo -e "Size: ${YELLOW}$FINAL_SIZE${NC}"
|
||||
echo ""
|
||||
# ============================================================================
|
||||
# Optional: Zip-wrap for GitHub releases
|
||||
# ============================================================================
|
||||
echo
|
||||
read -p "Create .zst.zip wrapper for GitHub? [y/N] " zip_confirm
|
||||
if [[ "$zip_confirm" =~ ^[Yy]$ ]]; then
|
||||
ZIP_OUTPUT="${OUTPUT}.zip"
|
||||
echo -e "${YELLOW}Creating zip wrapper (store mode, no compression)...${NC}"
|
||||
zip -0 "$ZIP_OUTPUT" "$OUTPUT"
|
||||
echo -e "${GREEN}Done!${NC} Upload this to GitHub Releases:"
|
||||
ls -lh "$ZIP_OUTPUT"
|
||||
echo
|
||||
echo "Users can flash with:"
|
||||
echo " sudo ./rpi/flash-image.sh $ZIP_OUTPUT"
|
||||
else
|
||||
echo
|
||||
echo "To verify:"
|
||||
echo " zstdcat $OUTPUT | fdisk -l /dev/stdin"
|
||||
fi
|
||||
|
||||
@@ -29,6 +29,10 @@ GRAY='\033[0;90m'
|
||||
BOLD='\033[1m'
|
||||
NC='\033[0m'
|
||||
|
||||
# Source banner functions
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/banner.sh"
|
||||
|
||||
# Show help
|
||||
show_help() {
|
||||
echo "Stegasoo Sanitize Script - Prepare Pi for SD Card Imaging"
|
||||
@@ -70,21 +74,11 @@ if [ "$EUID" -ne 0 ]; then
|
||||
fi
|
||||
|
||||
clear
|
||||
echo ""
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e "${GRAY} · . · . * · . * · . * · . * · . * · . ·${NC}"
|
||||
echo -e "\033[38;5;220m ___ _____ ___ ___ _ ___ ___ ___\033[0m"
|
||||
echo -e "\033[38;5;220m / __||_ _|| __| / __| /_\\\\ / __| / _ \\\\ / _ \\\\\033[0m"
|
||||
echo -e "\033[38;5;220m \\\\__ \\\\ | | | _| | (_ | / _ \\\\ \\\\__ \\\\ | (_) || (_) |\033[0m"
|
||||
echo -e "\033[38;5;220m |___/ |_| |___| \\___|/_/ \\_\\\\|___/ \\\\___/ \\\\___/\033[0m"
|
||||
echo -e "${GRAY} · . · . * · . * · . * · . * · . * · . ·${NC}"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
if [ "$SOFT_RESET" = true ]; then
|
||||
echo -e "\033[1;37m Soft Reset (Factory)\033[0m"
|
||||
print_banner "Soft Reset (Factory)"
|
||||
else
|
||||
echo -e "\033[1;37m Sanitize for Imaging\033[0m"
|
||||
print_banner "Sanitize for Imaging"
|
||||
fi
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo ""
|
||||
|
||||
if [ "$SOFT_RESET" = true ]; then
|
||||
|
||||
328
rpi/setup.sh
328
rpi/setup.sh
@@ -29,6 +29,33 @@ GRAY='\033[0;90m'
|
||||
BOLD='\033[1m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Source banner.sh if available (for local runs), otherwise define inline
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)"
|
||||
if [ -f "$SCRIPT_DIR/banner.sh" ]; then
|
||||
source "$SCRIPT_DIR/banner.sh"
|
||||
else
|
||||
# Inline banner functions for curl-pipe execution
|
||||
print_gradient_line() {
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
}
|
||||
print_banner() {
|
||||
local subtitle="$1"
|
||||
echo ""
|
||||
print_gradient_line
|
||||
echo -e "\033[0;90m · . · . * · . * · . * · . * · . * · . ·\033[0m"
|
||||
echo -e "\033[38;5;220m ___ _____ ___ ___ _ ___ ___ ___\033[0m"
|
||||
echo -e "\033[38;5;220m / __||_ _|| __| / __| /_\\ / __| / _ \\ / _ \\\\\033[0m"
|
||||
echo -e "\033[38;5;220m \\__ \\ | | | _| | (_ | / _ \\ \\__ \\ | (_) || (_) |\033[0m"
|
||||
echo -e "\033[38;5;220m |___/ |_| |___| \\___//_/ \\_\\|___/ \\___/ \\___/\033[0m"
|
||||
echo -e "\033[0;90m · . · . * · . * · . * · . * · . * · . ·\033[0m"
|
||||
print_gradient_line
|
||||
if [ -n "$subtitle" ]; then
|
||||
echo -e "\033[1;37m ${subtitle}\033[0m"
|
||||
print_gradient_line
|
||||
fi
|
||||
}
|
||||
fi
|
||||
|
||||
# Show help
|
||||
show_help() {
|
||||
echo "Stegasoo Raspberry Pi Setup Script"
|
||||
@@ -36,7 +63,9 @@ show_help() {
|
||||
echo "Usage: $0 [options]"
|
||||
echo ""
|
||||
echo "Options:"
|
||||
echo " -h, --help Show this help message"
|
||||
echo " -h, --help Show this help message"
|
||||
echo " --no-prebuilt Build from source instead of using pre-built venv"
|
||||
echo " --from-source Same as --no-prebuilt"
|
||||
echo ""
|
||||
echo "Configuration:"
|
||||
echo " Config files are loaded in order (later overrides earlier):"
|
||||
@@ -80,20 +109,10 @@ for config_file in "/etc/stegasoo.conf" "$HOME/.config/stegasoo/stegasoo.conf";
|
||||
done
|
||||
|
||||
clear
|
||||
echo ""
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e "${GRAY} · . · . * · . * · . * · . * · . * · . ·${NC}"
|
||||
echo -e "\033[38;5;220m ___ _____ ___ ___ _ ___ ___ ___\033[0m"
|
||||
echo -e "\033[38;5;220m / __||_ _|| __| / __| /_\\\\ / __| / _ \\\\ / _ \\\\\033[0m"
|
||||
echo -e "\033[38;5;220m \\\\__ \\\\ | | | _| | (_ | / _ \\\\ \\\\__ \\\\ | (_) || (_) |\033[0m"
|
||||
echo -e "\033[38;5;220m |___/ |_| |___| \\___|/_/ \\_\\\\|___/ \\\\___/ \\\\___/\033[0m"
|
||||
echo -e "${GRAY} · . · . * · . * · . * · . * · . * · . ·${NC}"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e "\033[1;37m Raspberry Pi Setup\033[0m"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
print_banner "Raspberry Pi Setup"
|
||||
echo ""
|
||||
echo " This will install Stegasoo with full DCT support"
|
||||
echo " Estimated time: 15-20 minutes on Pi 5"
|
||||
echo " Estimated time: ~2 minutes (pre-built) or 15-20 min (from source)"
|
||||
echo ""
|
||||
|
||||
# Check if running on ARM
|
||||
@@ -135,6 +154,7 @@ sudo apt-get install -y \
|
||||
build-essential \
|
||||
git \
|
||||
curl \
|
||||
zstd \
|
||||
libssl-dev \
|
||||
zlib1g-dev \
|
||||
libbz2-dev \
|
||||
@@ -164,49 +184,9 @@ else
|
||||
echo " gum already installed"
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}[4/12]${NC} Installing pyenv and Python $PYTHON_VERSION..."
|
||||
echo -e "${GREEN}[4/12]${NC} Cloning Stegasoo..."
|
||||
|
||||
# Install pyenv if not present
|
||||
if [ ! -d "$HOME/.pyenv" ]; then
|
||||
curl https://pyenv.run | bash
|
||||
|
||||
# Add pyenv to current shell
|
||||
export PYENV_ROOT="$HOME/.pyenv"
|
||||
export PATH="$PYENV_ROOT/bin:$PATH"
|
||||
eval "$(pyenv init -)"
|
||||
|
||||
# Add to .bashrc if not already there
|
||||
if ! grep -q 'PYENV_ROOT' ~/.bashrc; then
|
||||
echo '' >> ~/.bashrc
|
||||
echo '# pyenv' >> ~/.bashrc
|
||||
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
|
||||
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
|
||||
echo 'eval "$(pyenv init - bash)"' >> ~/.bashrc
|
||||
fi
|
||||
else
|
||||
echo "pyenv already installed, skipping..."
|
||||
export PYENV_ROOT="$HOME/.pyenv"
|
||||
export PATH="$PYENV_ROOT/bin:$PATH"
|
||||
eval "$(pyenv init -)"
|
||||
fi
|
||||
|
||||
# Install Python 3.12 if not present
|
||||
if ! pyenv versions | grep -q "$PYTHON_VERSION"; then
|
||||
echo "Building Python $PYTHON_VERSION (this takes ~10 minutes)..."
|
||||
pyenv install $PYTHON_VERSION
|
||||
fi
|
||||
pyenv global $PYTHON_VERSION
|
||||
|
||||
# Verify Python version
|
||||
INSTALLED_PY=$(python --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1,2)
|
||||
if [ "$INSTALLED_PY" != "$PYTHON_VERSION" ]; then
|
||||
echo -e "${RED}Error: Python $PYTHON_VERSION not active. Got: $INSTALLED_PY${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}[5/12]${NC} Cloning Stegasoo..."
|
||||
|
||||
# Clone Stegasoo first (needed for jpegio patch script)
|
||||
# Clone Stegasoo first (needed to check for pre-built tarball)
|
||||
if [ -d "$INSTALL_DIR/.git" ]; then
|
||||
echo " Stegasoo directory exists, updating..."
|
||||
cd "$INSTALL_DIR"
|
||||
@@ -218,49 +198,166 @@ else
|
||||
cd "$INSTALL_DIR"
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}[6/12]${NC} Creating Python virtual environment..."
|
||||
# Pre-built environment tarball (skips 20+ min compile time)
|
||||
# Includes both pyenv Python 3.12 AND venv with all dependencies
|
||||
PREBUILT_TARBALL="$INSTALL_DIR/rpi/stegasoo-rpi-runtime-env-arm64.tar.zst"
|
||||
PREBUILT_URL="${PREBUILT_URL:-https://github.com/adlee-was-taken/stegasoo/releases/download/v4.1.5/stegasoo-rpi-runtime-env-arm64.tar.zst}"
|
||||
USE_PREBUILT=true
|
||||
|
||||
# Create venv with pyenv Python (not system Python)
|
||||
# Use pyenv which to get actual path (handles 3.12 -> 3.12.12 mapping)
|
||||
PYENV_PYTHON=$(pyenv which python)
|
||||
echo " Using Python: $PYENV_PYTHON"
|
||||
if [ ! -d "venv" ]; then
|
||||
"$PYENV_PYTHON" -m venv venv
|
||||
fi
|
||||
source venv/bin/activate
|
||||
|
||||
# Verify we're using the right Python
|
||||
VENV_PY=$(python --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1,2)
|
||||
echo " venv Python: $VENV_PY"
|
||||
|
||||
echo -e "${GREEN}[7/12]${NC} Building jpegio for ARM..."
|
||||
|
||||
# Clone jpegio
|
||||
JPEGIO_DIR="/tmp/jpegio-build"
|
||||
rm -rf "$JPEGIO_DIR"
|
||||
git clone "$JPEGIO_REPO" "$JPEGIO_DIR"
|
||||
|
||||
# Apply ARM64 patch
|
||||
if [ -f "$INSTALL_DIR/rpi/patches/jpegio/apply-patch.sh" ]; then
|
||||
bash "$INSTALL_DIR/rpi/patches/jpegio/apply-patch.sh" "$JPEGIO_DIR"
|
||||
# Use local tarball if present, otherwise will download
|
||||
if [ -f "$PREBUILT_TARBALL" ]; then
|
||||
echo -e "${GREEN}Found local pre-built environment - fast install mode${NC}"
|
||||
else
|
||||
echo " Applying inline ARM64 patch..."
|
||||
sed -i "s/cargs.append('-m64')/pass # ARM64 fix/g" "$JPEGIO_DIR/setup.py"
|
||||
echo -e "${GREEN}Will download pre-built environment - fast install mode${NC}"
|
||||
fi
|
||||
|
||||
cd "$JPEGIO_DIR"
|
||||
# Allow --no-prebuilt flag to force from-source build
|
||||
if [[ " $* " =~ " --no-prebuilt " ]] || [[ " $* " =~ " --from-source " ]]; then
|
||||
USE_PREBUILT=false
|
||||
echo -e "${YELLOW}Building from source (--no-prebuilt specified)${NC}"
|
||||
fi
|
||||
|
||||
# Build jpegio into venv
|
||||
pip install --upgrade pip setuptools wheel cython numpy
|
||||
pip install .
|
||||
# Fast path: use pre-built environment if available
|
||||
if [ "$USE_PREBUILT" = true ]; then
|
||||
echo -e "${GREEN}[5/8]${NC} Installing pre-built Python environment..."
|
||||
|
||||
cd "$INSTALL_DIR"
|
||||
rm -rf "$JPEGIO_DIR"
|
||||
# Download if local file doesn't exist
|
||||
if [ ! -f "$PREBUILT_TARBALL" ]; then
|
||||
echo " Downloading pre-built environment (~50MB)..."
|
||||
curl -L -o "$PREBUILT_TARBALL" "$PREBUILT_URL"
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}[8/12]${NC} Installing Stegasoo..."
|
||||
# Extract pre-built environment (includes pyenv Python + venv)
|
||||
echo " Extracting pre-built environment..."
|
||||
zstd -d "$PREBUILT_TARBALL" --stdout | tar -xf - -C "$HOME"
|
||||
|
||||
# Install dependencies (jpegio already in venv, won't re-download)
|
||||
pip install -e ".[web]"
|
||||
# Setup pyenv in current shell
|
||||
export PYENV_ROOT="$HOME/.pyenv"
|
||||
export PATH="$PYENV_ROOT/bin:$PATH"
|
||||
eval "$(pyenv init -)"
|
||||
pyenv global $PYTHON_VERSION
|
||||
|
||||
# Add to .bashrc if not already there
|
||||
if ! grep -q 'PYENV_ROOT' ~/.bashrc; then
|
||||
echo '' >> ~/.bashrc
|
||||
echo '# pyenv' >> ~/.bashrc
|
||||
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
|
||||
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
|
||||
echo 'eval "$(pyenv init - bash)"' >> ~/.bashrc
|
||||
fi
|
||||
|
||||
# Verify Python
|
||||
INSTALLED_PY=$(python --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1,2)
|
||||
echo -e " ${GREEN}✓${NC} Python: $INSTALLED_PY"
|
||||
|
||||
# Extract venv to install dir
|
||||
echo -e "${GREEN}[6/8]${NC} Setting up virtual environment..."
|
||||
if [ -f "$HOME/stegasoo-venv.tar.zst" ]; then
|
||||
zstd -d "$HOME/stegasoo-venv.tar.zst" --stdout | tar -xf - -C "$INSTALL_DIR"
|
||||
rm "$HOME/stegasoo-venv.tar.zst"
|
||||
fi
|
||||
|
||||
# Activate and verify
|
||||
source "$INSTALL_DIR/venv/bin/activate"
|
||||
VENV_PY=$(python --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1,2)
|
||||
echo -e " ${GREEN}✓${NC} venv Python: $VENV_PY"
|
||||
|
||||
# Install stegasoo package in editable mode (quick, no compile)
|
||||
echo -e "${GREEN}[7/8]${NC} Installing Stegasoo package..."
|
||||
pip install -e "." --quiet
|
||||
|
||||
# Adjust step numbers for rest of script
|
||||
STEP_OFFSET=-4
|
||||
else
|
||||
echo -e "${GREEN}[5/12]${NC} Installing pyenv and Python $PYTHON_VERSION..."
|
||||
|
||||
# Install pyenv if not present
|
||||
if [ ! -d "$HOME/.pyenv" ]; then
|
||||
curl https://pyenv.run | bash
|
||||
|
||||
# Add pyenv to current shell
|
||||
export PYENV_ROOT="$HOME/.pyenv"
|
||||
export PATH="$PYENV_ROOT/bin:$PATH"
|
||||
eval "$(pyenv init -)"
|
||||
|
||||
# Add to .bashrc if not already there
|
||||
if ! grep -q 'PYENV_ROOT' ~/.bashrc; then
|
||||
echo '' >> ~/.bashrc
|
||||
echo '# pyenv' >> ~/.bashrc
|
||||
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
|
||||
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
|
||||
echo 'eval "$(pyenv init - bash)"' >> ~/.bashrc
|
||||
fi
|
||||
else
|
||||
echo " pyenv already installed"
|
||||
export PYENV_ROOT="$HOME/.pyenv"
|
||||
export PATH="$PYENV_ROOT/bin:$PATH"
|
||||
eval "$(pyenv init -)"
|
||||
fi
|
||||
|
||||
# Install Python 3.12 if not present
|
||||
if ! pyenv versions | grep -q "$PYTHON_VERSION"; then
|
||||
echo " Building Python $PYTHON_VERSION (this takes ~10 minutes)..."
|
||||
pyenv install $PYTHON_VERSION
|
||||
else
|
||||
echo " Python $PYTHON_VERSION already installed"
|
||||
fi
|
||||
pyenv global $PYTHON_VERSION
|
||||
|
||||
# Verify Python version
|
||||
INSTALLED_PY=$(python --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1,2)
|
||||
if [ "$INSTALLED_PY" != "$PYTHON_VERSION" ]; then
|
||||
echo -e "${RED}Error: Python $PYTHON_VERSION not active. Got: $INSTALLED_PY${NC}"
|
||||
exit 1
|
||||
fi
|
||||
echo -e "${GREEN}[6/12]${NC} Creating Python virtual environment..."
|
||||
echo -e " ${YELLOW}Note: No pre-built venv found. Building from source (20+ min)${NC}"
|
||||
echo -e " ${YELLOW}To speed up future installs, add stegasoo-venv-pi-arm64.tar.gz to rpi/${NC}"
|
||||
|
||||
# Create venv with pyenv Python (not system Python)
|
||||
# Use pyenv which to get actual path (handles 3.12 -> 3.12.12 mapping)
|
||||
PYENV_PYTHON=$(pyenv which python)
|
||||
echo " Using Python: $PYENV_PYTHON"
|
||||
if [ ! -d "venv" ]; then
|
||||
"$PYENV_PYTHON" -m venv venv
|
||||
fi
|
||||
source venv/bin/activate
|
||||
|
||||
# Verify we're using the right Python
|
||||
VENV_PY=$(python --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1,2)
|
||||
echo " venv Python: $VENV_PY"
|
||||
|
||||
echo -e "${GREEN}[7/12]${NC} Building jpegio for ARM..."
|
||||
|
||||
# Clone jpegio
|
||||
JPEGIO_DIR="/tmp/jpegio-build"
|
||||
rm -rf "$JPEGIO_DIR"
|
||||
git clone "$JPEGIO_REPO" "$JPEGIO_DIR"
|
||||
|
||||
# Apply ARM64 patch
|
||||
if [ -f "$INSTALL_DIR/rpi/patches/jpegio/apply-patch.sh" ]; then
|
||||
bash "$INSTALL_DIR/rpi/patches/jpegio/apply-patch.sh" "$JPEGIO_DIR"
|
||||
else
|
||||
echo " Applying inline ARM64 patch..."
|
||||
sed -i "s/cargs.append('-m64')/pass # ARM64 fix/g" "$JPEGIO_DIR/setup.py"
|
||||
fi
|
||||
|
||||
cd "$JPEGIO_DIR"
|
||||
|
||||
# Build jpegio into venv
|
||||
pip install --upgrade pip setuptools wheel cython numpy
|
||||
pip install .
|
||||
|
||||
cd "$INSTALL_DIR"
|
||||
rm -rf "$JPEGIO_DIR"
|
||||
|
||||
echo -e "${GREEN}[8/12]${NC} Installing Stegasoo..."
|
||||
|
||||
# Install dependencies (jpegio already in venv, won't re-download)
|
||||
pip install -e ".[web]"
|
||||
|
||||
STEP_OFFSET=0
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}[9/12]${NC} Creating systemd service..."
|
||||
|
||||
@@ -344,18 +441,35 @@ if systemctl is-active --quiet stegasoo 2>/dev/null; then
|
||||
echo -e "\033[38;5;220m |___/ |_| |___| \\___//_/ \\_\\|___/ \\___/ \\___/\033[0m"
|
||||
echo -e "\033[0;90m · . · . * · . * · . * · . * · . * · . ·\033[0m"
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo -e " \033[0;32m●\033[0m Stegasoo is running"
|
||||
echo -e " \033[0;33m$STEGASOO_URL\033[0m"
|
||||
# Show CPU stats if overclocked
|
||||
if grep -qE "^(arm_freq|over_voltage)" /boot/firmware/config.txt 2>/dev/null || \
|
||||
grep -qE "^(arm_freq|over_voltage)" /boot/config.txt 2>/dev/null; then
|
||||
CPU_FREQ=$(vcgencmd measure_clock arm 2>/dev/null | cut -d= -f2)
|
||||
# Show CPU stats if overclocked (read configured freq, not current idle freq)
|
||||
CONFIG_FILE=""
|
||||
if [ -f /boot/firmware/config.txt ]; then CONFIG_FILE="/boot/firmware/config.txt"
|
||||
elif [ -f /boot/config.txt ]; then CONFIG_FILE="/boot/config.txt"; fi
|
||||
CPU_MHZ=""
|
||||
CPU_TEMP=""
|
||||
if [ -n "$CONFIG_FILE" ] && grep -qE "^arm_freq=" "$CONFIG_FILE" 2>/dev/null; then
|
||||
CPU_MHZ=$(grep "^arm_freq=" "$CONFIG_FILE" | cut -d= -f2)
|
||||
CPU_TEMP=$(vcgencmd measure_temp 2>/dev/null | cut -d= -f2)
|
||||
if [ -n "$CPU_FREQ" ] && [ -n "$CPU_TEMP" ]; then
|
||||
CPU_MHZ=$((CPU_FREQ / 1000000))
|
||||
echo -e " \033[0;35m⚡\033[0m ${CPU_MHZ} MHz \033[0;35m🌡\033[0m ${CPU_TEMP}"
|
||||
fi
|
||||
fi
|
||||
# Compact two-column layout
|
||||
echo -e " 🚀 Stegasoo running 🌐 \033[0;33m$STEGASOO_URL\033[0m"
|
||||
if [ -n "$CPU_MHZ" ] && [ -n "$CPU_TEMP" ]; then
|
||||
# Temp emoji: ice<50, cool 50-70, fire>70
|
||||
TEMP_NUM=$(echo "$CPU_TEMP" | grep -oE "[0-9]+" | head -1)
|
||||
if [ -n "$TEMP_NUM" ]; then
|
||||
if [ "$TEMP_NUM" -ge 70 ]; then
|
||||
TEMP_EMOJI="🔥"
|
||||
elif [ "$TEMP_NUM" -ge 50 ]; then
|
||||
TEMP_EMOJI="😎"
|
||||
else
|
||||
TEMP_EMOJI="🧊"
|
||||
fi
|
||||
else
|
||||
TEMP_EMOJI="🌡"
|
||||
fi
|
||||
echo -e " \033[0;35m⚡\033[0m ${CPU_MHZ} MHz ${TEMP_EMOJI} ${CPU_TEMP}"
|
||||
fi
|
||||
echo -e "\033[38;5;93m══════════════\033[38;5;99m══════════════\033[38;5;105m══════════════\033[38;5;117m══════════════\033[0m"
|
||||
echo ""
|
||||
else
|
||||
echo ""
|
||||
@@ -367,6 +481,10 @@ MOTDEOF
|
||||
sudo chmod 644 /etc/profile.d/stegasoo-motd.sh
|
||||
echo " Created login banner"
|
||||
|
||||
# Shorten the default Debian MOTD boilerplate
|
||||
echo "Debian GNU/Linux · License: /usr/share/doc/*/copyright" | sudo tee /etc/motd > /dev/null
|
||||
echo " Shortened system MOTD"
|
||||
|
||||
echo ""
|
||||
echo -e "${BOLD}Installation Complete!${NC}"
|
||||
echo -e "${BLUE}-------------------------------------------------------${NC}"
|
||||
@@ -532,15 +650,19 @@ echo -e "${BLUE}-------------------------------------------------------${NC}"
|
||||
echo ""
|
||||
|
||||
PI_IP=$(hostname -I | awk '{print $1}')
|
||||
PI_HOST=$(hostname)
|
||||
|
||||
echo -e "${GREEN}Create your admin account:${NC}"
|
||||
if [ "$ENABLE_HTTPS" = "true" ]; then
|
||||
if [ "$USE_PORT_443" = "true" ]; then
|
||||
echo -e " ${YELLOW}https://$PI_HOST.local/setup${NC}"
|
||||
echo -e " ${YELLOW}https://$PI_IP/setup${NC}"
|
||||
else
|
||||
echo -e " ${YELLOW}https://$PI_HOST.local:5000/setup${NC}"
|
||||
echo -e " ${YELLOW}https://$PI_IP:5000/setup${NC}"
|
||||
fi
|
||||
else
|
||||
echo -e " ${YELLOW}http://$PI_HOST.local:5000/setup${NC}"
|
||||
echo -e " ${YELLOW}http://$PI_IP:5000/setup${NC}"
|
||||
fi
|
||||
|
||||
@@ -568,12 +690,12 @@ if [[ ! $REPLY =~ ^[Nn]$ ]]; then
|
||||
echo -e "${GREEN}✓ Stegasoo is running!${NC}"
|
||||
if [ "$ENABLE_HTTPS" = "true" ]; then
|
||||
if [ "$USE_PORT_443" = "true" ]; then
|
||||
echo -e " Create admin: ${YELLOW}https://$PI_IP/setup${NC}"
|
||||
echo -e " Create admin: ${YELLOW}https://$PI_HOST.local/setup${NC} or ${YELLOW}https://$PI_IP/setup${NC}"
|
||||
else
|
||||
echo -e " Create admin: ${YELLOW}https://$PI_IP:5000/setup${NC}"
|
||||
echo -e " Create admin: ${YELLOW}https://$PI_HOST.local:5000/setup${NC} or ${YELLOW}https://$PI_IP:5000/setup${NC}"
|
||||
fi
|
||||
else
|
||||
echo -e " Create admin: ${YELLOW}http://$PI_IP:5000/setup${NC}"
|
||||
echo -e " Create admin: ${YELLOW}http://$PI_HOST.local:5000/setup${NC} or ${YELLOW}http://$PI_IP:5000/setup${NC}"
|
||||
fi
|
||||
else
|
||||
echo -e "${RED}✗ Failed to start. Check logs:${NC} journalctl -u stegasoo -f"
|
||||
|
||||
@@ -120,7 +120,34 @@ else
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# 2. Unit Tests (if they exist)
|
||||
# 2. Security Audit
|
||||
# =============================================================================
|
||||
section "Security Audit"
|
||||
|
||||
# pip-audit for known vulnerabilities
|
||||
if command -v ./venv/bin/pip-audit &> /dev/null; then
|
||||
echo -n "Running pip-audit... "
|
||||
if ./venv/bin/pip-audit --quiet 2>/dev/null; then
|
||||
pass "No known vulnerabilities"
|
||||
else
|
||||
fail "pip-audit found vulnerabilities (run: ./venv/bin/pip-audit)"
|
||||
fi
|
||||
else
|
||||
echo -n "Installing pip-audit... "
|
||||
if ./venv/bin/pip install pip-audit --quiet 2>/dev/null; then
|
||||
echo -n "Running pip-audit... "
|
||||
if ./venv/bin/pip-audit --quiet 2>/dev/null; then
|
||||
pass "No known vulnerabilities"
|
||||
else
|
||||
fail "pip-audit found vulnerabilities (run: ./venv/bin/pip-audit)"
|
||||
fi
|
||||
else
|
||||
skip "Could not install pip-audit"
|
||||
fi
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# 3. Unit Tests (if they exist)
|
||||
# =============================================================================
|
||||
section "Unit Tests"
|
||||
|
||||
@@ -136,7 +163,7 @@ else
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# 3. Import Tests
|
||||
# 4. Import Tests
|
||||
# =============================================================================
|
||||
section "Import Tests"
|
||||
|
||||
@@ -165,7 +192,7 @@ else
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# 4. Encode/Decode Sanity Test
|
||||
# 5. Encode/Decode Sanity Test
|
||||
# =============================================================================
|
||||
section "Encode/Decode Test"
|
||||
|
||||
@@ -205,7 +232,7 @@ else
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# 5. Docker Build & Test (optional)
|
||||
# 6. Docker Build & Test (optional)
|
||||
# =============================================================================
|
||||
if $INCLUDE_DOCKER; then
|
||||
section "Docker"
|
||||
@@ -248,7 +275,7 @@ else
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# 6. Pi Smoke Test (optional)
|
||||
# 7. Pi Smoke Test (optional)
|
||||
# =============================================================================
|
||||
if $INCLUDE_PI; then
|
||||
section "Pi Smoke Test"
|
||||
|
||||
@@ -1,7 +1,69 @@
|
||||
"""
|
||||
Stegasoo CLI Module (v3.2.0)
|
||||
|
||||
Command-line interface with batch processing and compression support.
|
||||
A proper CLI architecture using Click. This module demonstrates several
|
||||
important patterns for building production-quality command-line tools:
|
||||
|
||||
PATTERN: COMMAND GROUPS
|
||||
=======================
|
||||
Click's @group decorator creates a hierarchy of commands:
|
||||
|
||||
stegasoo <- Main entry point
|
||||
├── encode <- Simple commands at root level
|
||||
├── decode
|
||||
├── generate
|
||||
├── info
|
||||
├── batch/ <- Group for related commands
|
||||
│ ├── encode
|
||||
│ ├── decode
|
||||
│ └── check
|
||||
├── channel/ <- Another group
|
||||
│ ├── generate
|
||||
│ ├── show
|
||||
│ ├── status
|
||||
│ ├── qr
|
||||
│ └── clear
|
||||
├── tools/ <- Utility group
|
||||
│ ├── capacity
|
||||
│ ├── strip
|
||||
│ ├── peek
|
||||
│ └── exif
|
||||
└── admin/ <- Administration group
|
||||
├── recover
|
||||
└── generate-key
|
||||
|
||||
PATTERN: JSON OUTPUT MODE
|
||||
=========================
|
||||
Every command supports --json for machine-readable output. The pattern:
|
||||
|
||||
@click.pass_context
|
||||
def my_command(ctx, ...):
|
||||
if ctx.obj.get("json"):
|
||||
click.echo(json.dumps(result, indent=2))
|
||||
else:
|
||||
# Human-readable output with colors/formatting
|
||||
click.echo(f"✓ Success: {result}")
|
||||
|
||||
This makes the CLI scriptable - you can pipe to jq, use in shell scripts, etc.
|
||||
|
||||
PATTERN: SENSITIVE INPUT
|
||||
========================
|
||||
Passwords/secrets use Click's secure prompts:
|
||||
|
||||
@click.option("--passphrase", prompt=True, hide_input=True,
|
||||
confirmation_prompt=True, help="Passphrase")
|
||||
|
||||
- prompt=True: Asks if not provided
|
||||
- hide_input=True: No echo (like sudo)
|
||||
- confirmation_prompt=True: "Repeat for confirmation"
|
||||
|
||||
PATTERN: DRY-RUN MODE
|
||||
=====================
|
||||
For destructive or slow operations, --dry-run shows what WOULD happen:
|
||||
|
||||
if dry_run:
|
||||
click.echo(f"Would encode to {output}")
|
||||
return
|
||||
|
||||
Changes in v3.2.0:
|
||||
- Updated to use DEFAULT_PASSPHRASE_WORDS (consistency with v3.2.0 naming)
|
||||
@@ -32,10 +94,23 @@ from .constants import (
|
||||
__version__,
|
||||
)
|
||||
|
||||
# Click context settings
|
||||
# Click context settings - these apply to all commands
|
||||
# help_option_names lets users use either -h or --help
|
||||
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ROOT GROUP - The main entry point
|
||||
# =============================================================================
|
||||
#
|
||||
# @click.group() creates a command group. The function becomes both:
|
||||
# 1. A callable that sets up shared state (ctx.obj)
|
||||
# 2. A container for subcommands via @cli.command() decorators
|
||||
#
|
||||
# The context object (ctx.obj) is passed down to all subcommands.
|
||||
# We use it to share the --json flag across the entire CLI.
|
||||
|
||||
|
||||
@click.group(context_settings=CONTEXT_SETTINGS)
|
||||
@click.version_option(__version__, "-v", "--version")
|
||||
@click.option("--json", "json_output", is_flag=True, help="Output results as JSON")
|
||||
@@ -46,6 +121,8 @@ def cli(ctx, json_output):
|
||||
|
||||
Hide messages in images using PIN + passphrase security.
|
||||
"""
|
||||
# ensure_object(dict) creates ctx.obj if it doesn't exist
|
||||
# This prevents "NoneType has no attribute" errors
|
||||
ctx.ensure_object(dict)
|
||||
ctx.obj["json"] = json_output
|
||||
|
||||
@@ -53,6 +130,31 @@ def cli(ctx, json_output):
|
||||
# =============================================================================
|
||||
# ENCODE COMMANDS
|
||||
# =============================================================================
|
||||
#
|
||||
# The encode command demonstrates several Click patterns:
|
||||
#
|
||||
# 1. ARGUMENT vs OPTION
|
||||
# - Arguments are positional: `stegasoo encode photo.png`
|
||||
# - Options have flags: `stegasoo encode -m "message" --pin 1234`
|
||||
# Rule of thumb: required inputs → arguments, optional/secret → options
|
||||
#
|
||||
# 2. MUTUAL EXCLUSIVITY
|
||||
# We need either --message OR --file, not both. Click doesn't have built-in
|
||||
# mutual exclusivity, so we check manually:
|
||||
#
|
||||
# if not message and not file_payload:
|
||||
# raise click.UsageError("Either --message or --file is required")
|
||||
#
|
||||
# 3. TYPE VALIDATION
|
||||
# Click validates types automatically:
|
||||
# - type=click.Path(exists=True) → file must exist
|
||||
# - type=click.Choice(["a", "b"]) → must be one of these values
|
||||
# - type=int → must be an integer
|
||||
#
|
||||
# 4. DEFAULT VALUES
|
||||
# Options can have smart defaults:
|
||||
# - default="zlib" → use this if not specified
|
||||
# - default=True with is_flag=True → boolean flag defaults to on
|
||||
|
||||
|
||||
@cli.command()
|
||||
@@ -320,6 +422,32 @@ def decode(ctx, image, reference, passphrase, pin, output):
|
||||
# =============================================================================
|
||||
# BATCH COMMANDS
|
||||
# =============================================================================
|
||||
#
|
||||
# Batch processing demonstrates:
|
||||
#
|
||||
# 1. SUBGROUPS
|
||||
# @cli.group() creates a nested command group:
|
||||
# stegasoo batch encode *.png
|
||||
# stegasoo batch decode *.png
|
||||
# stegasoo batch check *.png
|
||||
#
|
||||
# 2. VARIADIC ARGUMENTS
|
||||
# nargs=-1 accepts multiple arguments:
|
||||
# @click.argument("images", nargs=-1, required=True)
|
||||
# This lets users do: `stegasoo batch encode img1.png img2.png img3.png`
|
||||
# Or with shell expansion: `stegasoo batch encode *.png`
|
||||
#
|
||||
# 3. PROGRESS CALLBACKS
|
||||
# We pass a callback to the BatchProcessor for real-time updates:
|
||||
#
|
||||
# def progress(current, total, item):
|
||||
# click.echo(f"[{current}/{total}] {item.input_path.name}")
|
||||
#
|
||||
# processor.batch_encode(..., progress_callback=progress)
|
||||
#
|
||||
# 4. PARALLEL PROCESSING
|
||||
# --jobs/-j controls worker count. Default is 4 for good balance between
|
||||
# speed and memory usage. Each worker loads images into memory.
|
||||
|
||||
|
||||
@cli.group()
|
||||
@@ -586,11 +714,113 @@ def generate(ctx, words, pin_length, channel_key):
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option("--full", is_flag=True, help="Show full system information (Pi stats)")
|
||||
@click.pass_context
|
||||
def info(ctx):
|
||||
"""Show version and feature information."""
|
||||
def info(ctx, full):
|
||||
"""Show version, features, and system information."""
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
# Check for DCT support
|
||||
try:
|
||||
from .dct_steganography import HAS_JPEGIO, HAS_SCIPY
|
||||
has_dct = HAS_SCIPY and HAS_JPEGIO
|
||||
except ImportError:
|
||||
has_dct = False
|
||||
|
||||
# Check service status
|
||||
service_status = "unknown"
|
||||
service_url = None
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["systemctl", "is-active", "stegasoo"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=2,
|
||||
)
|
||||
service_status = result.stdout.strip()
|
||||
if service_status == "active":
|
||||
# Try to get URL from service environment
|
||||
env_result = subprocess.run(
|
||||
["systemctl", "show", "stegasoo", "--property=Environment"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=2,
|
||||
)
|
||||
https_enabled = "HTTPS_ENABLED=true" in env_result.stdout
|
||||
protocol = "https" if https_enabled else "http"
|
||||
# Get IP
|
||||
ip_result = subprocess.run(
|
||||
["hostname", "-I"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=2,
|
||||
)
|
||||
ip = ip_result.stdout.strip().split()[0] if ip_result.stdout.strip() else "localhost"
|
||||
service_url = f"{protocol}://{ip}"
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, IndexError):
|
||||
pass
|
||||
|
||||
# Check channel key
|
||||
channel_fingerprint = None
|
||||
channel_source = None
|
||||
try:
|
||||
from .channel import get_channel_fingerprint, get_channel_key, get_channel_status
|
||||
key = get_channel_key()
|
||||
if key:
|
||||
channel_fingerprint = get_channel_fingerprint(key)
|
||||
status = get_channel_status()
|
||||
channel_source = status.get("source")
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# System info (Pi-specific)
|
||||
cpu_freq = None
|
||||
cpu_temp = None
|
||||
disk_free = None
|
||||
uptime = None
|
||||
|
||||
if full:
|
||||
try:
|
||||
# CPU frequency
|
||||
with open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") as f:
|
||||
cpu_freq = int(f.read().strip()) // 1000 # MHz
|
||||
except (FileNotFoundError, ValueError):
|
||||
pass
|
||||
|
||||
try:
|
||||
# CPU temp
|
||||
with open("/sys/class/thermal/thermal_zone0/temp") as f:
|
||||
cpu_temp = int(f.read().strip()) / 1000 # Celsius
|
||||
except (FileNotFoundError, ValueError):
|
||||
pass
|
||||
|
||||
try:
|
||||
# Disk free
|
||||
st = os.statvfs("/")
|
||||
disk_free = (st.f_bavail * st.f_frsize) / (1024 ** 3) # GB
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
try:
|
||||
# Uptime
|
||||
with open("/proc/uptime") as f:
|
||||
uptime_secs = float(f.read().split()[0])
|
||||
days = int(uptime_secs // 86400)
|
||||
hours = int((uptime_secs % 86400) // 3600)
|
||||
uptime = f"{days}d {hours}h" if days else f"{hours}h"
|
||||
except (FileNotFoundError, ValueError):
|
||||
pass
|
||||
|
||||
info_data = {
|
||||
"version": __version__,
|
||||
"service": service_status,
|
||||
"url": service_url,
|
||||
"dct_support": has_dct,
|
||||
"channel": {
|
||||
"fingerprint": channel_fingerprint,
|
||||
"source": channel_source,
|
||||
} if channel_fingerprint else None,
|
||||
"compression": {
|
||||
"available": [algorithm_name(a) for a in get_available_algorithms()],
|
||||
"lz4_installed": HAS_LZ4,
|
||||
@@ -599,20 +829,54 @@ def info(ctx):
|
||||
"max_message_bytes": MAX_MESSAGE_SIZE,
|
||||
"max_file_payload_bytes": MAX_FILE_PAYLOAD_SIZE,
|
||||
},
|
||||
"system": {
|
||||
"cpu_mhz": cpu_freq,
|
||||
"temp_c": cpu_temp,
|
||||
"disk_free_gb": round(disk_free, 1) if disk_free else None,
|
||||
"uptime": uptime,
|
||||
} if full else None,
|
||||
}
|
||||
|
||||
if ctx.obj.get("json"):
|
||||
click.echo(json.dumps(info_data, indent=2))
|
||||
else:
|
||||
click.echo(f"Stegasoo v{__version__}")
|
||||
click.echo("\nCompression algorithms:")
|
||||
for algo in get_available_algorithms():
|
||||
click.echo(f" • {algorithm_name(algo)}")
|
||||
if not HAS_LZ4:
|
||||
click.echo(" (install 'lz4' for LZ4 support)")
|
||||
click.echo("\nLimits:")
|
||||
click.echo(f" • Max message: {MAX_MESSAGE_SIZE:,} bytes")
|
||||
click.echo(f" • Max file payload: {MAX_FILE_PAYLOAD_SIZE:,} bytes")
|
||||
# Fastfetch-style output
|
||||
click.echo(f"\033[1mSTEGASOO\033[0m v{__version__}")
|
||||
click.echo("─" * 36)
|
||||
|
||||
# Service status
|
||||
if service_status == "active":
|
||||
click.echo(" Service: \033[32m● running\033[0m")
|
||||
if service_url:
|
||||
click.echo(f" URL: {service_url}")
|
||||
elif service_status == "inactive":
|
||||
click.echo(" Service: \033[31m○ stopped\033[0m")
|
||||
else:
|
||||
click.echo(f" Service: \033[33m? {service_status}\033[0m")
|
||||
|
||||
# Channel
|
||||
if channel_fingerprint:
|
||||
masked = f"{channel_fingerprint[:4]}••••••••{channel_fingerprint[-4:]}"
|
||||
click.echo(f" Channel: {masked}")
|
||||
else:
|
||||
click.echo(" Channel: \033[33mpublic\033[0m")
|
||||
|
||||
# DCT
|
||||
dct_status = "\033[32m✓ enabled\033[0m" if has_dct else "\033[31m✗ disabled\033[0m"
|
||||
click.echo(f" DCT: {dct_status}")
|
||||
|
||||
# System info (if --full)
|
||||
if full and any([cpu_freq, cpu_temp, disk_free, uptime]):
|
||||
click.echo("─" * 36)
|
||||
if cpu_freq:
|
||||
click.echo(f" CPU: {cpu_freq} MHz")
|
||||
if cpu_temp:
|
||||
temp_color = "\033[32m" if cpu_temp < 60 else "\033[33m" if cpu_temp < 75 else "\033[31m"
|
||||
click.echo(f" Temp: {temp_color}{cpu_temp:.1f}°C\033[0m")
|
||||
if uptime:
|
||||
click.echo(f" Uptime: {uptime}")
|
||||
if disk_free:
|
||||
click.echo(f" Disk: {disk_free:.1f} GB free")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
|
||||
@@ -25,7 +25,7 @@ from pathlib import Path
|
||||
# VERSION
|
||||
# ============================================================================
|
||||
|
||||
__version__ = "4.1.3"
|
||||
__version__ = "4.1.5"
|
||||
|
||||
# ============================================================================
|
||||
# FILE FORMAT
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
"""
|
||||
Stegasoo Cryptographic Functions (v4.0.0 - Channel Key Support)
|
||||
|
||||
Key derivation, encryption, and decryption using AES-256-GCM.
|
||||
Supports both text messages and binary file payloads.
|
||||
This is the crypto layer - where we turn plaintext into indecipherable noise.
|
||||
|
||||
BREAKING CHANGES in v4.0.0:
|
||||
- Added channel key support for deployment/group isolation
|
||||
- Messages encoded with a channel key require the same key to decode
|
||||
- Channel key can be configured via environment, config file, or explicit parameter
|
||||
- FORMAT_VERSION bumped to 5
|
||||
The security model is multi-factor:
|
||||
┌────────────────────────────────────────────────────────────────────┐
|
||||
│ SOMETHING YOU HAVE SOMETHING YOU KNOW │
|
||||
│ ├─ Reference photo ├─ Passphrase (4+ BIP-39 words) │
|
||||
│ └─ RSA private key (opt) └─ PIN (6-9 digits) │
|
||||
│ │
|
||||
│ DEPLOYMENT BINDING │
|
||||
│ └─ Channel key (ties messages to a specific server/group) │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
BREAKING CHANGES in v3.2.0:
|
||||
- Removed date dependency from key derivation
|
||||
- Renamed day_phrase → passphrase (no daily rotation needed)
|
||||
All factors get mixed together through Argon2id (memory-hard KDF) to derive
|
||||
the actual encryption key. Miss any factor = wrong key = garbage output.
|
||||
|
||||
Encryption: AES-256-GCM (authenticated encryption - tamper = detection)
|
||||
KDF: Argon2id (256MB RAM, 4 iterations) or PBKDF2 fallback (600K iterations)
|
||||
|
||||
v4.0.0: Added channel key for server/group isolation
|
||||
v3.2.0: Removed date dependency (was cute but annoying in practice)
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
@@ -98,25 +106,38 @@ def _resolve_channel_key(channel_key: str | bool | None) -> bytes | None:
|
||||
# =============================================================================
|
||||
# CORE CRYPTO FUNCTIONS
|
||||
# =============================================================================
|
||||
#
|
||||
# The "reference photo as a key" concept is one of Stegasoo's unique features.
|
||||
# Most steganography tools just use a password. We add the photo as a
|
||||
# "something you have" factor - like a hardware token, but it's a cat picture.
|
||||
|
||||
|
||||
def hash_photo(image_data: bytes) -> bytes:
|
||||
"""
|
||||
Compute deterministic hash of photo pixel content.
|
||||
|
||||
This normalizes the image to RGB and hashes the raw pixel data,
|
||||
making it resistant to metadata changes.
|
||||
This is the magic sauce that turns your cat photo into a cryptographic key.
|
||||
|
||||
Why pixels and not the file hash?
|
||||
- File metadata changes (EXIF stripped, resaved) = different file hash
|
||||
- But pixel content stays the same
|
||||
- We hash the RGB values directly, so format conversions don't matter
|
||||
|
||||
The double-hash with prefix is belt-and-suspenders mixing. Probably
|
||||
overkill, but hey, it's crypto - paranoia is a feature.
|
||||
|
||||
Args:
|
||||
image_data: Raw image file bytes
|
||||
image_data: Raw image file bytes (any format PIL can read)
|
||||
|
||||
Returns:
|
||||
32-byte SHA-256 hash
|
||||
32-byte SHA-256 hash of pixel content
|
||||
"""
|
||||
# Convert to RGB to normalize (RGBA, grayscale, etc. all become RGB)
|
||||
img: Image.Image = Image.open(io.BytesIO(image_data)).convert("RGB")
|
||||
pixels = img.tobytes()
|
||||
|
||||
# Double-hash with prefix for additional mixing
|
||||
# Double-hash: SHA256(SHA256(pixels) + first 1KB of pixels)
|
||||
# The prefix adds image-specific data to prevent length-extension shenanigans
|
||||
h = hashlib.sha256(pixels).digest()
|
||||
h = hashlib.sha256(h + pixels[:1024]).digest()
|
||||
return h
|
||||
@@ -133,20 +154,38 @@ def derive_hybrid_key(
|
||||
"""
|
||||
Derive encryption key from multiple factors.
|
||||
|
||||
Combines:
|
||||
- Photo hash (something you have)
|
||||
- Passphrase (something you know)
|
||||
- PIN (something you know, static)
|
||||
- RSA key (something you have)
|
||||
- Channel key (deployment/group binding)
|
||||
- Salt (random per message)
|
||||
This is the heart of Stegasoo's security model. We take all the things
|
||||
you need to prove you're authorized (photo, passphrase, PIN, etc.) and
|
||||
blend them together into one 32-byte key.
|
||||
|
||||
Uses Argon2id if available, falls back to PBKDF2.
|
||||
The flow:
|
||||
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||
│ Photo hash │ + │ passphrase │ + │ PIN + RSA │ + salt
|
||||
└─────────────┘ └─────────────┘ └─────────────┘
|
||||
│ │ │
|
||||
└────────────────┴────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Argon2id │ <- Memory-hard KDF
|
||||
│ 256MB / 4 iter │ <- Makes brute force expensive
|
||||
└─────────────────┘
|
||||
│
|
||||
▼
|
||||
32-byte AES key
|
||||
|
||||
Why Argon2id?
|
||||
- Memory-hard: attackers can't just throw GPUs at it
|
||||
- 256MB RAM per attempt = expensive at scale
|
||||
- Winner of the Password Hashing Competition (2015)
|
||||
- "id" variant resists both side-channel and GPU attacks
|
||||
|
||||
Fallback: PBKDF2-SHA512 with 600K iterations (for systems without argon2)
|
||||
|
||||
Args:
|
||||
photo_data: Reference photo bytes
|
||||
passphrase: Shared passphrase (recommend 4+ words)
|
||||
salt: Random salt for this message
|
||||
passphrase: Shared passphrase (recommend 4+ words from BIP-39)
|
||||
salt: Random salt for this message (32 bytes)
|
||||
pin: Optional static PIN
|
||||
rsa_key_data: Optional RSA key bytes
|
||||
channel_key: Channel key parameter:
|
||||
@@ -155,7 +194,7 @@ def derive_hybrid_key(
|
||||
- "" or False: No channel key (public mode)
|
||||
|
||||
Returns:
|
||||
32-byte derived key
|
||||
32-byte derived key (ready for AES-256)
|
||||
|
||||
Raises:
|
||||
KeyDerivationError: If key derivation fails
|
||||
@@ -163,31 +202,36 @@ def derive_hybrid_key(
|
||||
try:
|
||||
photo_hash = hash_photo(photo_data)
|
||||
|
||||
# Resolve channel key
|
||||
# Resolve channel key (server-specific binding)
|
||||
channel_hash = _resolve_channel_key(channel_key)
|
||||
|
||||
# Build key material
|
||||
# Build key material by concatenating all factors
|
||||
# Passphrase is lowercased to be forgiving of case differences
|
||||
key_material = photo_hash + passphrase.lower().encode() + pin.encode() + salt
|
||||
|
||||
# Add RSA key hash if provided
|
||||
# Add RSA key hash if provided (another "something you have")
|
||||
if rsa_key_data:
|
||||
key_material += hashlib.sha256(rsa_key_data).digest()
|
||||
|
||||
# Add channel key hash if configured (v4.0.0)
|
||||
# Add channel key hash if configured (v4.0.0 - deployment binding)
|
||||
if channel_hash:
|
||||
key_material += channel_hash
|
||||
|
||||
# Run it all through the KDF
|
||||
if HAS_ARGON2:
|
||||
# Argon2id: the good stuff
|
||||
key = hash_secret_raw(
|
||||
secret=key_material,
|
||||
salt=salt[:32],
|
||||
time_cost=ARGON2_TIME_COST,
|
||||
memory_cost=ARGON2_MEMORY_COST,
|
||||
parallelism=ARGON2_PARALLELISM,
|
||||
time_cost=ARGON2_TIME_COST, # 4 iterations
|
||||
memory_cost=ARGON2_MEMORY_COST, # 256 MB RAM
|
||||
parallelism=ARGON2_PARALLELISM, # 4 threads
|
||||
hash_len=32,
|
||||
type=Type.ID,
|
||||
type=Type.ID, # Hybrid mode: resists side-channel AND GPU attacks
|
||||
)
|
||||
else:
|
||||
# PBKDF2 fallback for systems without argon2-cffi
|
||||
# 600K iterations is slow but not memory-hard
|
||||
kdf = PBKDF2HMAC(
|
||||
algorithm=hashes.SHA512(),
|
||||
length=32,
|
||||
@@ -347,9 +391,12 @@ def _unpack_payload(data: bytes) -> DecodeResult:
|
||||
# =============================================================================
|
||||
# HEADER FLAGS (v4.0.0)
|
||||
# =============================================================================
|
||||
#
|
||||
# The flags byte tells us about the message without decrypting it.
|
||||
# Currently just one flag, but the byte gives us room for 8.
|
||||
|
||||
# Header flag bits
|
||||
FLAG_CHANNEL_KEY = 0x01 # Set if encoded with a channel key
|
||||
FLAG_CHANNEL_KEY = 0x01 # Bit 0: Message was encoded with a channel key
|
||||
# Future flags could include: compression, file attachment, etc.
|
||||
|
||||
|
||||
def encrypt_message(
|
||||
@@ -361,33 +408,40 @@ def encrypt_message(
|
||||
channel_key: str | bool | None = None,
|
||||
) -> bytes:
|
||||
"""
|
||||
Encrypt message or file using AES-256-GCM with hybrid key derivation.
|
||||
Encrypt message or file using AES-256-GCM.
|
||||
|
||||
Message format (v4.0.0 - with channel key support):
|
||||
- Magic header (4 bytes)
|
||||
- Version (1 byte) = 5
|
||||
- Flags (1 byte) - indicates if channel key was used
|
||||
- Salt (32 bytes)
|
||||
- IV (12 bytes)
|
||||
- Auth tag (16 bytes)
|
||||
- Ciphertext (variable, padded)
|
||||
This is where plaintext becomes ciphertext. We use AES-256-GCM which is:
|
||||
- AES: The standard, used by everyone from banks to governments
|
||||
- 256-bit key: Enough entropy to survive until the heat death of the universe
|
||||
- GCM mode: Authenticated encryption - if anyone tampers, decryption fails
|
||||
|
||||
The output format (v4.0.0):
|
||||
┌──────────────────────────────────────────────────────────────────────┐
|
||||
│ \x89ST3 │ 05 │ flags │ salt (32B) │ iv (12B) │ tag (16B) │ ··· │
|
||||
│ magic │ver │ │ │ │ │cipher│
|
||||
└──────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Why the random padding at the end?
|
||||
- Message length can reveal information (traffic analysis)
|
||||
- We add 64-319 random bytes and round to 256-byte boundary
|
||||
- All messages look roughly the same size
|
||||
|
||||
Args:
|
||||
message: Message string, raw bytes, or FilePayload to encrypt
|
||||
photo_data: Reference photo bytes
|
||||
passphrase: Shared passphrase (recommend 4+ words for good entropy)
|
||||
pin: Optional static PIN
|
||||
rsa_key_data: Optional RSA key bytes
|
||||
photo_data: Reference photo bytes (your "key photo")
|
||||
passphrase: Shared passphrase (recommend 4+ words from BIP-39)
|
||||
pin: Optional static PIN for additional security
|
||||
rsa_key_data: Optional RSA key bytes (another "something you have")
|
||||
channel_key: Channel key parameter:
|
||||
- None or "auto": Use configured key
|
||||
- None or "auto": Use server's configured key
|
||||
- str: Use this specific key
|
||||
- "" or False: No channel key (public mode)
|
||||
|
||||
Returns:
|
||||
Encrypted message bytes
|
||||
Encrypted message bytes ready for embedding
|
||||
|
||||
Raises:
|
||||
EncryptionError: If encryption fails
|
||||
EncryptionError: If encryption fails (shouldn't happen with valid inputs)
|
||||
"""
|
||||
try:
|
||||
salt = secrets.token_bytes(SALT_SIZE)
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
"""
|
||||
DCT Domain Steganography Module (v4.1.0)
|
||||
|
||||
Embeds data in DCT coefficients with two approaches:
|
||||
1. PNG output: Scipy-based DCT transform (grayscale or color)
|
||||
2. JPEG output: jpegio-based coefficient manipulation (if available)
|
||||
The fancy pants mode. Instead of hiding bits in pixel values (LSB mode),
|
||||
we hide them in the *frequency domain* - specifically in the Discrete Cosine
|
||||
Transform coefficients that JPEG compression uses internally.
|
||||
|
||||
v4.1.0 Changes:
|
||||
- Reed-Solomon error correction protects against bit errors in problematic blocks
|
||||
- Majority voting on length headers (3 copies) for additional robustness
|
||||
- RS can correct up to 16 byte errors per 223-byte chunk
|
||||
Why is this cool?
|
||||
- Survives some image processing that would destroy LSB data
|
||||
- Works with JPEG without the usual "save destroys everything" problem
|
||||
- Uses the same math that JPEG itself uses - we're hiding in plain sight
|
||||
|
||||
v3.2.0-patch2 Changes:
|
||||
- Chunked processing for large images to avoid heap corruption
|
||||
- Process image in vertical strips to limit memory per operation
|
||||
- Isolated DCT operations with fresh array allocations
|
||||
- Workaround for scipy.fftpack memory issues
|
||||
Two approaches depending on what you want:
|
||||
1. PNG output: We do our own DCT math via scipy (works on any image)
|
||||
2. JPEG output: We use jpegio to directly tweak the coefficients (chef's kiss)
|
||||
|
||||
Requires: scipy (for PNG mode), optionally jpegio (for JPEG mode), reedsolo (for error correction)
|
||||
v4.1.0 - The "please stop corrupting my data" release:
|
||||
- Reed-Solomon error correction (can fix up to 16 byte errors per chunk)
|
||||
- Majority voting on headers (store 3 copies, take the winner)
|
||||
- Because some image regions are just... problematic
|
||||
|
||||
v3.2.0-patch2 - The "scipy why are you like this" release:
|
||||
- Chunked processing because scipy's FFT was corrupting memory on big images
|
||||
- Process blocks one at a time with fresh arrays
|
||||
- Yes, it's slower. No, I don't care. Correctness > speed.
|
||||
|
||||
Requires: scipy (PNG mode), optionally jpegio (JPEG mode), reedsolo (error correction)
|
||||
"""
|
||||
|
||||
import gc
|
||||
@@ -87,11 +95,31 @@ def _write_progress(progress_file: str | None, current: int, total: int, phase:
|
||||
# CONSTANTS
|
||||
# ============================================================================
|
||||
|
||||
# JPEG uses 8x8 blocks for DCT - this is baked into the standard
|
||||
BLOCK_SIZE = 8
|
||||
|
||||
# The zig-zag order of DCT coefficients. JPEG stores them this way because
|
||||
# the human eye is more sensitive to low frequencies (top-left corner)
|
||||
# than high frequencies (bottom-right). After quantization, most high-freq
|
||||
# coefficients become zero, so zig-zag gives great compression.
|
||||
#
|
||||
# Visual of an 8x8 DCT block with zig-zag numbering:
|
||||
#
|
||||
# DC 1 5 6 14 15 27 28 <- Low frequency (smooth gradients)
|
||||
# 2 4 7 13 16 26 29 42
|
||||
# 3 8 12 17 25 30 41 43
|
||||
# 9 11 18 24 31 40 44 53
|
||||
# 10 19 23 32 39 45 52 54
|
||||
# 20 22 33 38 46 51 55 60
|
||||
# 21 34 37 47 50 56 59 61
|
||||
# 35 36 48 49 57 58 62 63 <- High frequency (fine detail/noise)
|
||||
#
|
||||
# Position (0,0) is the DC coefficient - the average brightness of the block.
|
||||
# We NEVER touch DC because changing it causes visible brightness shifts.
|
||||
EMBED_POSITIONS = [
|
||||
(0, 1),
|
||||
(1, 0),
|
||||
(2, 0),
|
||||
(0, 1), # 1st AC coefficient
|
||||
(1, 0), # 2nd AC coefficient
|
||||
(2, 0), # ... and so on in zig-zag order
|
||||
(1, 1),
|
||||
(0, 2),
|
||||
(0, 3),
|
||||
@@ -124,32 +152,59 @@ EMBED_POSITIONS = [
|
||||
(6, 1),
|
||||
(7, 0),
|
||||
]
|
||||
|
||||
# We use positions 4-20 (mid-frequency range). Here's the reasoning:
|
||||
# - Positions 0-3: Too low frequency, changes are visible as color shifts
|
||||
# - Positions 4-20: Sweet spot - carries enough energy to survive, not visible
|
||||
# - Positions 21+: High frequency, often quantized to zero, unreliable
|
||||
DEFAULT_EMBED_POSITIONS = EMBED_POSITIONS[4:20]
|
||||
|
||||
# Quantization step for QIM (Quantization Index Modulation).
|
||||
# This is how we actually embed bits: we round the coefficient to a grid
|
||||
# and then nudge it based on whether we want a 0 or 1.
|
||||
# Bigger step = more robust to noise, but more visible. 25 is a good balance.
|
||||
QUANT_STEP = 25
|
||||
DCT_MAGIC = b"DCTS"
|
||||
HEADER_SIZE = 10
|
||||
|
||||
# Magic bytes so we can identify our own images
|
||||
DCT_MAGIC = b"DCTS" # scipy DCT mode marker
|
||||
JPEGIO_MAGIC = b"JPGS" # jpegio native JPEG mode marker
|
||||
HEADER_SIZE = 10 # Magic (4) + version (1) + flags (1) + length (4)
|
||||
|
||||
OUTPUT_FORMAT_PNG = "png"
|
||||
OUTPUT_FORMAT_JPEG = "jpeg"
|
||||
JPEG_OUTPUT_QUALITY = 95
|
||||
JPEGIO_MAGIC = b"JPGS"
|
||||
JPEG_OUTPUT_QUALITY = 95 # High quality but not 100 (100 causes issues, see below)
|
||||
|
||||
# For jpegio mode: we only embed in coefficients with magnitude >= 2
|
||||
# Coefficients of 0 or 1 are usually quantized noise - unreliable
|
||||
JPEGIO_MIN_COEF_MAGNITUDE = 2
|
||||
|
||||
# We embed in the Y (luminance) channel only - it has the most capacity
|
||||
# Cb/Cr are often subsampled 4:2:0 anyway
|
||||
JPEGIO_EMBED_CHANNEL = 0
|
||||
FLAG_COLOR_MODE = 0x01
|
||||
FLAG_RS_PROTECTED = 0x02 # Reed-Solomon error correction enabled
|
||||
|
||||
# Reed-Solomon settings - 32 symbols can correct up to 16 byte errors per 223-byte chunk
|
||||
# Header flags
|
||||
FLAG_COLOR_MODE = 0x01 # Set if we preserved color (YCbCr mode)
|
||||
FLAG_RS_PROTECTED = 0x02 # Set if Reed-Solomon protected (v4.1.0+)
|
||||
|
||||
# Reed-Solomon settings - the "please don't lose my data" system
|
||||
# 32 parity symbols per chunk means we can correct up to 16 byte errors
|
||||
# Math: RS(255, 223) where 255-223=32 parity bytes, corrects floor(32/2)=16
|
||||
RS_NSYM = 32
|
||||
RS_LENGTH_HEADER_SIZE = 8 # 8 bytes: 4 for raw_payload_length + 4 for rs_payload_length
|
||||
RS_LENGTH_COPIES = 3 # Store length header 3 times for majority voting
|
||||
RS_LENGTH_PREFIX_SIZE = RS_LENGTH_HEADER_SIZE * RS_LENGTH_COPIES # Total: 24 bytes
|
||||
|
||||
# Chunking settings for large images
|
||||
MAX_CHUNK_HEIGHT = 512 # Process in 512-pixel tall strips
|
||||
# We store the payload length 3 times and take majority vote
|
||||
# Because if the length is wrong, everything is wrong
|
||||
RS_LENGTH_HEADER_SIZE = 8 # 4 bytes raw length + 4 bytes RS-encoded length
|
||||
RS_LENGTH_COPIES = 3 # Store 3 copies, need 2 to agree
|
||||
RS_LENGTH_PREFIX_SIZE = RS_LENGTH_HEADER_SIZE * RS_LENGTH_COPIES # 24 bytes total
|
||||
|
||||
# JPEG normalization settings
|
||||
# JPEGs with quality=100 have all quantization values = 1, which crashes jpegio
|
||||
JPEGIO_NORMALIZE_QUALITY = 95 # Re-save quality for problematic JPEGs
|
||||
JPEGIO_MAX_QUANT_VALUE_THRESHOLD = 1 # If all quant values <= this, normalize
|
||||
# Chunking for large images - scipy's FFT gets memory-corrupty on huge arrays
|
||||
MAX_CHUNK_HEIGHT = 512 # Process in strips to keep memory sane
|
||||
|
||||
# Fun bug: JPEGs saved with quality=100 have quantization tables full of 1s
|
||||
# This makes the DCT coefficients HUGE and jpegio crashes spectacularly
|
||||
# Solution: detect and re-save at quality 95 first
|
||||
JPEGIO_NORMALIZE_QUALITY = 95
|
||||
JPEGIO_MAX_QUANT_VALUE_THRESHOLD = 1 # All 1s in quant table = bad news
|
||||
|
||||
|
||||
# ============================================================================
|
||||
@@ -209,13 +264,26 @@ def has_jpegio_support() -> bool:
|
||||
|
||||
# ============================================================================
|
||||
# REED-SOLOMON ERROR CORRECTION
|
||||
# Protects against bit errors in problematic image blocks
|
||||
# ============================================================================
|
||||
#
|
||||
# Why do we need this? DCT embedding isn't perfect. Some image regions are
|
||||
# problematic - flat areas, high compression, edge cases. Bits can flip.
|
||||
#
|
||||
# Reed-Solomon is the same error correction used in CDs, DVDs, QR codes, and
|
||||
# deep space communications. If it's good enough for Voyager, it's good enough
|
||||
# for hiding cat pictures in other cat pictures.
|
||||
#
|
||||
# How it works (simplified):
|
||||
# 1. Take your data bytes
|
||||
# 2. Add extra "parity" bytes calculated from the data
|
||||
# 3. If some bytes get corrupted, the math lets you reconstruct them
|
||||
# 4. RS(255, 223) means: 255 byte blocks, 223 data + 32 parity
|
||||
# 5. Can correct up to 16 corrupted bytes per block (floor(32/2))
|
||||
#
|
||||
# The tradeoff: ~14% overhead (32/223). Worth it for reliability.
|
||||
|
||||
# Check for reedsolo availability
|
||||
try:
|
||||
from reedsolo import ReedSolomonError, RSCodec
|
||||
|
||||
HAS_REEDSOLO = True
|
||||
except ImportError:
|
||||
HAS_REEDSOLO = False
|
||||
@@ -224,48 +292,78 @@ except ImportError:
|
||||
|
||||
|
||||
def _rs_encode(data: bytes) -> bytes:
|
||||
"""Add Reed-Solomon error correction symbols to data."""
|
||||
"""
|
||||
Wrap data in Reed-Solomon error correction.
|
||||
|
||||
Takes your precious payload and adds parity bytes so we can
|
||||
recover from the inevitable bit-rot of DCT embedding.
|
||||
"""
|
||||
if not HAS_REEDSOLO:
|
||||
return data # No protection if reedsolo not available
|
||||
return data # YOLO mode - no protection, good luck
|
||||
rs = RSCodec(RS_NSYM)
|
||||
return bytes(rs.encode(data))
|
||||
|
||||
|
||||
def _rs_decode(data: bytes) -> bytes:
|
||||
"""Decode Reed-Solomon protected data, correcting errors if possible."""
|
||||
"""
|
||||
Decode Reed-Solomon protected data, fixing errors along the way.
|
||||
|
||||
This is where the magic happens. If bits got flipped during
|
||||
extraction, RS will quietly fix them. If too many flipped...
|
||||
well, we tried.
|
||||
"""
|
||||
if not HAS_REEDSOLO:
|
||||
return data # No decoding if reedsolo not available
|
||||
return data
|
||||
rs = RSCodec(RS_NSYM)
|
||||
try:
|
||||
decoded, _, errata_pos = rs.decode(data)
|
||||
if errata_pos:
|
||||
pass # Errors were corrected
|
||||
# Errors were found and corrected - RS earned its keep today
|
||||
pass
|
||||
return bytes(decoded)
|
||||
except ReedSolomonError as e:
|
||||
# Too many errors - the image got mangled beyond repair
|
||||
raise StegasooRSError(f"Image corrupted beyond repair: {e}") from e
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# SAFE DCT FUNCTIONS
|
||||
# These create fresh arrays to avoid scipy memory corruption issues
|
||||
# ============================================================================
|
||||
#
|
||||
# Story time: scipy's fftpack (the old DCT implementation) has memory issues
|
||||
# when you process large images. We'd get random garbage in our output, or
|
||||
# worse, segfaults. Turns out it was reusing internal buffers in unsafe ways.
|
||||
#
|
||||
# The fix? Be paranoid. Every single array operation creates a fresh copy.
|
||||
# Is it slower? Yes. Does it work? Also yes. I'll take correct over fast.
|
||||
#
|
||||
# The newer scipy.fft module is better, but we still play it safe because
|
||||
# not everyone has the latest scipy and I don't want debugging nightmares.
|
||||
|
||||
|
||||
def _safe_dct2(block: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Apply 2D DCT with memory isolation.
|
||||
Creates a completely fresh array to avoid heap corruption.
|
||||
Apply 2D DCT (Discrete Cosine Transform) to an 8x8 block.
|
||||
|
||||
The DCT converts spatial data (pixel values) into frequency data
|
||||
(how much of each frequency component is present). It's the heart
|
||||
of JPEG compression.
|
||||
|
||||
We do it row-by-row and column-by-column with fresh arrays each time
|
||||
because scipy's built-in dct2 can corrupt memory on large batches.
|
||||
Paranoid? Yes. Necessary? Also yes.
|
||||
"""
|
||||
# Create a brand new array (not a view)
|
||||
# Create a brand new array (not a view) - paranoia level: maximum
|
||||
safe_block = np.array(block, dtype=np.float64, copy=True, order="C")
|
||||
|
||||
# First DCT on columns (transpose -> DCT rows -> transpose back)
|
||||
# 2D DCT = 1D DCT on rows, then 1D DCT on columns (separable transform)
|
||||
# First pass: DCT each column
|
||||
temp = np.zeros_like(safe_block, dtype=np.float64, order="C")
|
||||
for i in range(BLOCK_SIZE):
|
||||
col = np.array(safe_block[:, i], dtype=np.float64, copy=True)
|
||||
temp[:, i] = dct(col, norm="ortho")
|
||||
temp[:, i] = dct(col, norm="ortho") # ortho normalization for symmetry
|
||||
|
||||
# Second DCT on rows
|
||||
# Second pass: DCT each row of the result
|
||||
result = np.zeros_like(temp, dtype=np.float64, order="C")
|
||||
for i in range(BLOCK_SIZE):
|
||||
row = np.array(temp[i, :], dtype=np.float64, copy=True)
|
||||
@@ -276,19 +374,22 @@ def _safe_dct2(block: np.ndarray) -> np.ndarray:
|
||||
|
||||
def _safe_idct2(block: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Apply 2D inverse DCT with memory isolation.
|
||||
Creates a completely fresh array to avoid heap corruption.
|
||||
Apply 2D inverse DCT - convert frequency data back to pixels.
|
||||
|
||||
After we've embedded our secret bits in the DCT coefficients,
|
||||
we need to convert back to pixel values. This is the reverse
|
||||
of _safe_dct2.
|
||||
|
||||
Same paranoid memory handling because same paranoid developer.
|
||||
"""
|
||||
# Create a brand new array (not a view)
|
||||
safe_block = np.array(block, dtype=np.float64, copy=True, order="C")
|
||||
|
||||
# First IDCT on rows
|
||||
# Inverse is the same idea: IDCT rows, then IDCT columns
|
||||
temp = np.zeros_like(safe_block, dtype=np.float64, order="C")
|
||||
for i in range(BLOCK_SIZE):
|
||||
row = np.array(safe_block[i, :], dtype=np.float64, copy=True)
|
||||
temp[i, :] = idct(row, norm="ortho")
|
||||
|
||||
# Second IDCT on columns
|
||||
result = np.zeros_like(temp, dtype=np.float64, order="C")
|
||||
for i in range(BLOCK_SIZE):
|
||||
col = np.array(temp[:, i], dtype=np.float64, copy=True)
|
||||
@@ -348,8 +449,25 @@ def _unpad_image(image: np.ndarray, original_size: tuple[int, int]) -> np.ndarra
|
||||
|
||||
|
||||
def _embed_bit_in_coeff(coef: float, bit: int, quant_step: int = QUANT_STEP) -> float:
|
||||
"""
|
||||
Embed a single bit into a DCT coefficient using QIM.
|
||||
|
||||
QIM (Quantization Index Modulation) is smarter than simple LSB flipping.
|
||||
Instead of just changing the last bit, we round to a quantization grid
|
||||
and use odd/even to encode 0/1.
|
||||
|
||||
Why is this better?
|
||||
- More robust to noise (small changes don't flip the bit)
|
||||
- Works naturally with JPEG's own quantization
|
||||
- The change is spread across the coefficient's magnitude
|
||||
|
||||
Visual example (quant_step=25):
|
||||
- Coef = 73, want bit=0 -> round to 75 (75/25=3, 3%2=1) -> nudge to 50 (50/25=2, 2%2=0)
|
||||
- Coef = 73, want bit=1 -> round to 75 (75/25=3, 3%2=1) -> already odd, keep at 75
|
||||
"""
|
||||
quantized = round(coef / quant_step)
|
||||
if (quantized % 2) != bit:
|
||||
# Need to flip even<->odd. Nudge in the direction that's closest.
|
||||
if quantized % 2 == 0 and bit == 1:
|
||||
quantized += 1 if coef >= quantized * quant_step else -1
|
||||
elif quantized % 2 == 1 and bit == 0:
|
||||
@@ -358,13 +476,35 @@ def _embed_bit_in_coeff(coef: float, bit: int, quant_step: int = QUANT_STEP) ->
|
||||
|
||||
|
||||
def _extract_bit_from_coeff(coef: float, quant_step: int = QUANT_STEP) -> int:
|
||||
"""
|
||||
Extract a bit from a DCT coefficient.
|
||||
|
||||
The inverse of _embed_bit_in_coeff. We round to the quantization grid
|
||||
and check if it's odd (1) or even (0).
|
||||
|
||||
This is why QIM is robust: small noise in the coefficient usually
|
||||
doesn't change which grid point we round to.
|
||||
"""
|
||||
quantized = round(coef / quant_step)
|
||||
return int(quantized % 2)
|
||||
|
||||
|
||||
def _generate_block_order(num_blocks: int, seed: bytes) -> list:
|
||||
"""
|
||||
Generate a pseudo-random order for processing blocks.
|
||||
|
||||
This is crucial for security - if we just went left-to-right, top-to-bottom,
|
||||
anyone could find the message by checking blocks in order. Instead, we
|
||||
use a keyed shuffle so only someone with the same seed can find the data.
|
||||
|
||||
The seed comes from the crypto layer (derived from passphrase + photo + pin),
|
||||
so the block order is effectively part of the encryption.
|
||||
"""
|
||||
# Use SHA-256 to expand the seed into randomness
|
||||
hash_bytes = hashlib.sha256(seed).digest()
|
||||
# Seed numpy's RNG (we use RandomState for reproducibility across versions)
|
||||
rng = np.random.RandomState(int.from_bytes(hash_bytes[:4], "big"))
|
||||
# Fisher-Yates shuffle
|
||||
order = list(range(num_blocks))
|
||||
rng.shuffle(order)
|
||||
return order
|
||||
@@ -393,14 +533,28 @@ def _save_color_image(rgb_array: np.ndarray, output_format: str = OUTPUT_FORMAT_
|
||||
|
||||
|
||||
def _rgb_to_ycbcr(rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""
|
||||
Convert RGB to YCbCr color space.
|
||||
|
||||
YCbCr separates brightness (Y) from color (Cb=blue-ish, Cr=red-ish).
|
||||
This is what JPEG uses internally, and it's great for us because:
|
||||
- Human eyes are WAY more sensitive to brightness than color
|
||||
- We can hide data in Y without it being as visible
|
||||
- Cb/Cr are often subsampled (4:2:0) so Y has more capacity anyway
|
||||
|
||||
The coefficients here are from ITU-R BT.601 - the standard for video.
|
||||
"""
|
||||
R = rgb[:, :, 0].astype(np.float64)
|
||||
G = rgb[:, :, 1].astype(np.float64)
|
||||
B = rgb[:, :, 2].astype(np.float64)
|
||||
|
||||
# Y = luminance (brightness). Green contributes most because eyes are most sensitive to it.
|
||||
Y = np.array(0.299 * R + 0.587 * G + 0.114 * B, dtype=np.float64, copy=True, order="C")
|
||||
# Cb = blue-difference chroma (centered at 128)
|
||||
Cb = np.array(
|
||||
128 - 0.168736 * R - 0.331264 * G + 0.5 * B, dtype=np.float64, copy=True, order="C"
|
||||
)
|
||||
# Cr = red-difference chroma (centered at 128)
|
||||
Cr = np.array(
|
||||
128 + 0.5 * R - 0.418688 * G - 0.081312 * B, dtype=np.float64, copy=True, order="C"
|
||||
)
|
||||
@@ -409,6 +563,12 @@ def _rgb_to_ycbcr(rgb: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
|
||||
|
||||
def _ycbcr_to_rgb(Y: np.ndarray, Cb: np.ndarray, Cr: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Convert YCbCr back to RGB.
|
||||
|
||||
After embedding in the Y channel, we need to reconstruct RGB for display.
|
||||
The Cb/Cr channels are unchanged - we only touched luminance.
|
||||
"""
|
||||
R = Y + 1.402 * (Cr - 128)
|
||||
G = Y - 0.344136 * (Cb - 128) - 0.714136 * (Cr - 128)
|
||||
B = Y + 1.772 * (Cb - 128)
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
"""
|
||||
Stegasoo Steganography Functions (v3.2.0)
|
||||
|
||||
LSB and DCT embedding modes with pseudo-random pixel/coefficient selection.
|
||||
This is the core embedding/extraction module. Two modes available:
|
||||
|
||||
Changes in v3.0:
|
||||
- DCT domain embedding mode (requires scipy)
|
||||
- embed_mode parameter for encode/decode
|
||||
- Auto-detection of embedding mode
|
||||
- Comparison utilities
|
||||
LSB (Least Significant Bit) Mode:
|
||||
- Classic steganography technique - hide bits in the least significant bit of pixel values
|
||||
- Works on any image, outputs lossless PNG/BMP
|
||||
- Higher capacity than DCT, but destroyed by JPEG compression
|
||||
- Great for: high-capacity needs, lossless workflows
|
||||
|
||||
Changes in v3.0.1:
|
||||
- dct_output_format parameter for DCT mode ('png' or 'jpeg')
|
||||
- dct_color_mode parameter for DCT mode ('grayscale' or 'color')
|
||||
DCT Mode (see dct_steganography.py):
|
||||
- Hides data in frequency-domain coefficients
|
||||
- Survives some image processing, works with JPEG
|
||||
- Lower capacity but more robust
|
||||
- Great for: JPEG images, robustness needs
|
||||
|
||||
Changes in v3.2.0:
|
||||
- Fixed HEADER_OVERHEAD constant (65 bytes, not 104 - date field removed)
|
||||
- Updated ENCRYPTION_OVERHEAD calculation
|
||||
Both modes use pseudo-random pixel/coefficient selection based on a key.
|
||||
Without the key, you don't know where to look - security through obscurity
|
||||
PLUS actual encryption of the payload.
|
||||
|
||||
v3.0: Added DCT mode with scipy
|
||||
v3.0.1: DCT output format options (PNG/JPEG, grayscale/color)
|
||||
v3.2.0: Fixed overhead calculations after removing date field
|
||||
"""
|
||||
|
||||
import io
|
||||
@@ -83,24 +89,31 @@ EXT_TO_FORMAT = {
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# OVERHEAD CONSTANTS (v4.0.0 - Updated for channel key support)
|
||||
# OVERHEAD CONSTANTS
|
||||
# =============================================================================
|
||||
# v4.0.0 Header format (with flags byte for channel key indicator):
|
||||
# Magic: 4 bytes (\x89ST3)
|
||||
# Version: 1 byte (5 for v4.0.0)
|
||||
# Flags: 1 byte (bit 0 = has channel key)
|
||||
# Salt: 32 bytes
|
||||
# IV: 12 bytes
|
||||
# Tag: 16 bytes
|
||||
# -----------------
|
||||
# Total: 66 bytes
|
||||
#
|
||||
# v3.2.0 had 65 bytes (no flags byte)
|
||||
# v3.1.0 had date field (10 bytes + 1 byte length) = 76 bytes header
|
||||
# Every stego image has some overhead before the actual payload:
|
||||
#
|
||||
# The encrypted message format (v4.0.0):
|
||||
# ┌─────────────────────────────────────────────────────────────────┐
|
||||
# │ \x89ST3 │ v5 │ flags │ salt (32) │ iv (12) │ tag (16) │ ... │
|
||||
# │ magic │ ver│ │ │ │ │ data│
|
||||
# └─────────────────────────────────────────────────────────────────┘
|
||||
# 4 bytes 1 1 32 12 16 var
|
||||
#
|
||||
# Plus LSB embedding adds a 4-byte length prefix so we know where to stop.
|
||||
#
|
||||
# History of overhead sizes (in case you're debugging old images):
|
||||
# - v3.1.0: 76 bytes (had date field - 10+1 bytes)
|
||||
# - v3.2.0: 65 bytes (removed date, simpler)
|
||||
# - v4.0.0: 66 bytes (added flags byte for channel key)
|
||||
|
||||
HEADER_OVERHEAD = 66 # v4.0.0: Magic + version + flags + salt + iv + tag
|
||||
LENGTH_PREFIX = 4 # 4 bytes for payload length in LSB embedding
|
||||
ENCRYPTION_OVERHEAD = HEADER_OVERHEAD + LENGTH_PREFIX # 70 bytes total
|
||||
HEADER_OVERHEAD = 66 # What the crypto layer adds to any message
|
||||
LENGTH_PREFIX = 4 # We prepend the payload length for LSB extraction
|
||||
ENCRYPTION_OVERHEAD = HEADER_OVERHEAD + LENGTH_PREFIX # Total: 70 bytes
|
||||
|
||||
# That 70 bytes is your minimum image capacity requirement.
|
||||
# A tiny 100x100 image gives you ~3750 bytes capacity, minus 70 = ~3680 usable.
|
||||
|
||||
# DCT output format options (v3.0.1)
|
||||
DCT_OUTPUT_PNG = "png"
|
||||
@@ -456,6 +469,20 @@ def compare_modes(image_data: bytes) -> dict:
|
||||
# =============================================================================
|
||||
# PIXEL INDEX GENERATION
|
||||
# =============================================================================
|
||||
#
|
||||
# The key insight: we don't hide data in sequential pixels (that's easy to find).
|
||||
# Instead, we scatter the data across pseudo-random pixel locations.
|
||||
#
|
||||
# The pixel selection key (derived from passphrase + photo + pin) determines
|
||||
# WHICH pixels get modified. Without the key, an attacker would have to:
|
||||
# 1. Know we're using LSB steganography
|
||||
# 2. Try every possible subset of pixels
|
||||
# 3. Decrypt the result (which they also can't do without the key)
|
||||
#
|
||||
# We use ChaCha20 as a CSPRNG (Cryptographically Secure PRNG). It's:
|
||||
# - Fast (faster than AES-CTR on most CPUs)
|
||||
# - Deterministic (same key = same sequence, needed for extraction)
|
||||
# - Secure (can't predict the sequence without the key)
|
||||
|
||||
|
||||
@debug.time
|
||||
@@ -463,8 +490,13 @@ def generate_pixel_indices(key: bytes, num_pixels: int, num_needed: int) -> list
|
||||
"""
|
||||
Generate pseudo-random pixel indices for embedding.
|
||||
|
||||
Uses ChaCha20 as a CSPRNG seeded by the key to deterministically
|
||||
select which pixels will hold hidden data.
|
||||
This is the "where do we hide the bits?" function. We use ChaCha20
|
||||
to generate a deterministic sequence of pixel indices that only
|
||||
someone with the same key can reproduce.
|
||||
|
||||
Two strategies based on how much of the image we're using:
|
||||
- >= 50% capacity: Full Fisher-Yates shuffle (sample without replacement)
|
||||
- < 50% capacity: Direct random sampling (faster, same result)
|
||||
"""
|
||||
debug.validate(len(key) == 32, f"Pixel key must be 32 bytes, got {len(key)}")
|
||||
debug.validate(num_pixels > 0, f"Number of pixels must be positive, got {num_pixels}")
|
||||
@@ -475,6 +507,8 @@ def generate_pixel_indices(key: bytes, num_pixels: int, num_needed: int) -> list
|
||||
|
||||
debug.print(f"Generating {num_needed} pixel indices from {num_pixels} total pixels")
|
||||
|
||||
# Strategy 1: Full shuffle when we need a lot of pixels
|
||||
# Fisher-Yates shuffle is O(n) and gives us perfect random sampling
|
||||
if num_needed >= num_pixels // 2:
|
||||
debug.print(f"Using full shuffle (needed {num_needed}/{num_pixels} pixels)")
|
||||
nonce = b"\x00" * 16
|
||||
@@ -482,8 +516,10 @@ def generate_pixel_indices(key: bytes, num_pixels: int, num_needed: int) -> list
|
||||
encryptor = cipher.encryptor()
|
||||
|
||||
indices = list(range(num_pixels))
|
||||
# Get enough random bytes to do the shuffle
|
||||
random_bytes = encryptor.update(b"\x00" * (num_pixels * 4))
|
||||
|
||||
# Fisher-Yates shuffle - swap each element with a random earlier element
|
||||
for i in range(num_pixels - 1, 0, -1):
|
||||
j_bytes = random_bytes[(num_pixels - 1 - i) * 4 : (num_pixels - i) * 4]
|
||||
j = int.from_bytes(j_bytes, "big") % (i + 1)
|
||||
@@ -493,14 +529,17 @@ def generate_pixel_indices(key: bytes, num_pixels: int, num_needed: int) -> list
|
||||
debug.print(f"Generated {len(selected)} indices via shuffle")
|
||||
return selected
|
||||
|
||||
# Strategy 2: Direct sampling when we need fewer pixels
|
||||
# Generate random indices until we have enough unique ones
|
||||
debug.print(f"Using optimized selection (needed {num_needed}/{num_pixels} pixels)")
|
||||
selected = []
|
||||
used = set()
|
||||
used = set() # Track which pixels we've already picked
|
||||
|
||||
nonce = b"\x00" * 16
|
||||
cipher = Cipher(algorithms.ChaCha20(key, nonce), mode=None, backend=default_backend())
|
||||
encryptor = cipher.encryptor()
|
||||
|
||||
# Pre-generate 2x the bytes we think we'll need (for collision handling)
|
||||
bytes_needed = (num_needed * 2) * 4
|
||||
random_bytes = encryptor.update(b"\x00" * bytes_needed)
|
||||
|
||||
@@ -514,8 +553,9 @@ def generate_pixel_indices(key: bytes, num_pixels: int, num_needed: int) -> list
|
||||
used.add(idx)
|
||||
selected.append(idx)
|
||||
else:
|
||||
collisions += 1
|
||||
collisions += 1 # Birthday paradox in action
|
||||
|
||||
# Edge case: ran out of pre-generated bytes (very high collision rate)
|
||||
if len(selected) < num_needed:
|
||||
debug.print(f"Need {num_needed - len(selected)} more indices, generating...")
|
||||
extra_needed = num_needed - len(selected)
|
||||
@@ -539,6 +579,23 @@ def generate_pixel_indices(key: bytes, num_pixels: int, num_needed: int) -> list
|
||||
# =============================================================================
|
||||
# EMBEDDING FUNCTIONS
|
||||
# =============================================================================
|
||||
#
|
||||
# The actual bit-hiding magic happens here. LSB embedding is conceptually simple:
|
||||
#
|
||||
# Original pixel RGB: (142, 87, 201)
|
||||
# In binary: (10001110, 01010111, 11001001)
|
||||
# ^ ^ ^
|
||||
# These are the LSBs (least significant bits)
|
||||
#
|
||||
# To hide the bits [1, 0, 1]:
|
||||
# Modified pixel RGB: (10001111, 01010110, 11001001) = (143, 86, 201)
|
||||
# ^ ^ ^
|
||||
# Changed! Changed! Already 1, no change needed
|
||||
#
|
||||
# The human eye can't see the difference between 142 and 143.
|
||||
# But we've hidden 3 bits of secret data in one pixel.
|
||||
#
|
||||
# With a 1000x1000 image: 1 million pixels * 3 channels = 3 million bits = 375 KB!
|
||||
|
||||
|
||||
@debug.time
|
||||
|
||||
@@ -5,27 +5,24 @@ Tests core functionality: encode/decode, LSB/DCT modes, channel keys, validation
|
||||
"""
|
||||
|
||||
import io
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
import stegasoo
|
||||
from stegasoo import (
|
||||
encode,
|
||||
decode,
|
||||
decode_text,
|
||||
encode,
|
||||
generate_channel_key,
|
||||
generate_passphrase,
|
||||
generate_pin,
|
||||
generate_channel_key,
|
||||
validate_passphrase,
|
||||
validate_pin,
|
||||
has_dct_support,
|
||||
validate_image,
|
||||
validate_message,
|
||||
has_dct_support,
|
||||
EncodeResult,
|
||||
DecodeResult,
|
||||
ValidationError,
|
||||
CapacityError,
|
||||
validate_passphrase,
|
||||
validate_pin,
|
||||
)
|
||||
|
||||
# Test data paths
|
||||
|
||||
Reference in New Issue
Block a user