Compare commits

..

12 Commits

Author SHA1 Message Date
Daniel Bedeleanu
fcb187974e Build [v1.9.18] 2026-04-13 23:43:52 +03:00
Daniel Bedeleanu
1fff658d3c Build [v1.9.16] (Open Gateway: Verified SSL Permission check) 2026-04-13 22:48:26 +03:00
Daniel Bedeleanu
826b264a70 Build [v1.9.15] (The Dynamic Shield: On-Demand TLS Catch-all) 2026-04-13 22:43:40 +03:00
Daniel Bedeleanu
94f1a515b7 Build [v1.9.14] (Protocol Lock: Explicit HTTPS & Handshake Debug) 2026-04-13 22:37:50 +03:00
Daniel Bedeleanu
4dc0ce50e7 Build [v1.9.13] (Bare Metal: Fixed Caddy Syntax & Universal Binding) 2026-04-13 22:31:04 +03:00
Daniel Bedeleanu
ee7e7b7bd7 Build [v1.9.12] (Secure Seal & LDAP Sync: Custom Caddy & Config Volume) 2026-04-13 22:25:19 +03:00
Daniel Bedeleanu
9d7e4f0ca3 Build [v1.9.11] (The Convergence: Manual Login & Runtime Discovery) 2026-04-13 22:15:57 +03:00
Daniel Bedeleanu
bdf6d605cd Build [v1.9.10] (Access & SSL Recovery: Fixed Admin info and Explicit IP Proxy) 2026-04-13 22:07:15 +03:00
Daniel Bedeleanu
a2f6cab492 Build [v1.9.9] (Emergency: Direct HTTP Fallback & Diagnostic Logs) 2026-04-13 21:57:51 +03:00
Daniel Bedeleanu
476fda7203 Build [v1.9.8] (Final Stability: Static Internal Port Mapping) 2026-04-13 21:48:40 +03:00
Daniel Bedeleanu
9348336709 Build [v1.9.7] (Fix ERR_SSL_PROTOCOL_ERROR: Explicit HTTPS in Caddyfile) 2026-04-13 21:42:58 +03:00
Daniel Bedeleanu
e5194a1dbb Build [v1.9.6] (Fix: Include deploy.sh in production bundle) 2026-04-13 21:36:23 +03:00
21 changed files with 494 additions and 180 deletions

View File

@@ -26,7 +26,7 @@ A unified system to maintain an inventory of "items" and their quantities, inclu
- **PWA Deployment:** `next-pwa` (Service Workers + Manifest.json) - **PWA Deployment:** `next-pwa` (Service Workers + Manifest.json)
- **HTTPS Proxy:** `caddy` or `local-ssl-proxy` (Port 8909) - **HTTPS Proxy:** `caddy` or `local-ssl-proxy` (Port 8909)
- **Servers:** Frontend (Port 8907), Backend (Port 8906) - **Servers:** Frontend (Port 8907), Backend (Port 8906)
- **Configuration:** Centrally managed via root `config/` directory (includes `network_config.env`, `ldap_config.json`, `Caddyfile`). - **Configuration:** Centrally managed via root `inventory.env` (Network/CORS/API Keys) and `config/` directory (LDAP, Caddyfile).
## 3. Data Models & Entities ## 3. Data Models & Entities
- **Item:** Name, Category Group (Structured), Item Type (Specific), Quantity, Barcode, Part Number, Box Label (Association). - **Item:** Name, Category Group (Structured), Item Type (Specific), Quantity, Barcode, Part Number, Box Label (Association).
@@ -80,7 +80,9 @@ To ensure enterprise-grade protection, the following policies are enforced:
- **Admin Only:** Critical operations such as `DELETE /items/`, user management, and DB settings are restricted via the `auth.get_current_admin` dependency. - **Admin Only:** Critical operations such as `DELETE /items/`, user management, and DB settings are restricted via the `auth.get_current_admin` dependency.
- **User Role:** Standard users are permitted to perform check-in/out and list inventory, but cannot delete catalog entries. - **User Role:** Standard users are permitted to perform check-in/out and list inventory, but cannot delete catalog entries.
### 7.2 Brute-Force Protection ### 7.2 CORS & Origin Policy (v1.9.18)
- **Automatic Discovery:** The system detects local LAN IP and automatically authorizes it.
- **Generic Expansion:** Use `EXTRA_ALLOWED_ORIGINS` for Tailscale or VPN IPs. The system automatically expands each IP into a set of authorized Origins (http/8916, https/8918, https/8919).
- **Rate Limiting:** Implemented via `slowapi`. The `login` endpoint is limited to **5 requests per minute** per IP to mitigate automated credential stuffing. - **Rate Limiting:** Implemented via `slowapi`. The `login` endpoint is limited to **5 requests per minute** per IP to mitigate automated credential stuffing.
### 7.3 Data Privacy ### 7.3 Data Privacy

View File

@@ -12,8 +12,8 @@ This project supports three distinct operational modes:
Ideal for local development on macOS/Linux. Ideal for local development on macOS/Linux.
* **Command:** `./start_server.sh` * **Command:** `./start_server.sh`
* **Details:** Runs FastAPI (backend) and Next.js (frontend) in development mode. Uses `local-ssl-proxy` for HTTPS. * **Details:** Runs FastAPI (backend) and Next.js (frontend) in development mode. Uses `local-ssl-proxy` for HTTPS.
* **Backend:** http://localhost:8906 * **Backend:** http://localhost:8916
* **Frontend:** https://localhost:8909 * **Frontend:** https://localhost:8919
### 2. 🐳 Docker Mode (Recommended for Production) ### 2. 🐳 Docker Mode (Recommended for Production)
Isolated and portable container stack. Isolated and portable container stack.
@@ -58,7 +58,8 @@ The application requires the following environment variables for production depl
| Variable | Purpose | Example | | Variable | Purpose | Example |
|----------|---------|---------| |----------|---------|---------|
| **JWT_SECRET_KEY** | JWT token signing key (REQUIRED for production) | `openssl rand -hex 32` | | **JWT_SECRET_KEY** | JWT token signing key (REQUIRED for production) | `openssl rand -hex 32` |
| **ALLOWED_ORIGINS** | CORS-allowed domain origins (comma-separated) | `https://inventory.example.com,https://api.example.com` | | **EXTRA_ALLOWED_ORIGINS** | Extra IPs or FQDNs for CORS (Tailscale, VPN, etc.) | `100.78.182.27,inventory.local` |
| **ALLOWED_ORIGINS** | CORS-allowed domain origins (automatically includes LOCAL_IP) | `https://inventory.example.com` |
| **DATA_DIR** | SQLite database location | `/app/data` | | **DATA_DIR** | SQLite database location | `/app/data` |
| **LOGS_DIR** | Application logs directory | `/app/logs` | | **LOGS_DIR** | Application logs directory | `/app/logs` |

View File

@@ -102,8 +102,8 @@ Access application settings from the **Admin** panel.
### 🌐 Network & Configuration (NEW v1.8.0) ### 🌐 Network & Configuration (NEW v1.8.0)
The application now uses a centralized configuration folder in the project root: The application now uses a centralized configuration folder in the project root:
- **`config/`**: Contains all network settings (`network_config.env`), LDAP profiles (`ldap_config.json`), and security proxy rules (`Caddyfile`). - **`inventory.env`**: The primary network configuration file. Centralizes `SERVER_IP`, ports, and `EXTRA_ALLOWED_ORIGINS`.
- **Dynamic Port Mapping**: Changes to the server IP or ports in the configuration are automatically detected by both the frontend and backend after a restart. - **Dynamic Port Mapping**: Changes to the server IP, ports, or allowed origins are automatically detected by both the frontend and backend after a restart.
--- ---
@@ -146,5 +146,5 @@ For detailed technical documentation, see the [Project Architecture](../PROJECT_
--- ---
**Version:** v1.8.4 **Version:** v1.9.18
**Last Updated:** 2026-04-13 **Last Updated:** 2026-04-13

View File

@@ -51,6 +51,20 @@ if server_ip and server_ip != "localhost":
if ip_o not in ALLOWED_ORIGINS: if ip_o not in ALLOWED_ORIGINS:
ALLOWED_ORIGINS.append(ip_o) ALLOWED_ORIGINS.append(ip_o)
# [NEW] Add Extra Allowed Origins (Tailscale, VPN, etc.)
extra_origins_raw = os.environ.get("EXTRA_ALLOWED_ORIGINS", "")
if extra_origins_raw:
for extra_ip in [o.strip() for o in extra_origins_raw.split(",") if o.strip()]:
# Generate standard combinations for this extra origin
ext_combos = [
f"http://{extra_ip}:{front_port}",
f"https://{extra_ip}:{front_ssl_port}",
f"https://{extra_ip}:{back_ssl_port}",
]
for combo in ext_combos:
if combo not in ALLOWED_ORIGINS:
ALLOWED_ORIGINS.append(combo)
log.info(f"CORS allowed origins: {ALLOWED_ORIGINS}") log.info(f"CORS allowed origins: {ALLOWED_ORIGINS}")
# Add CORS middleware FIRST (before rate limiter) # Add CORS middleware FIRST (before rate limiter)

View File

@@ -20,13 +20,19 @@ limiter = Limiter(key_func=get_remote_address)
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto") pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
def get_ldap_config(): def get_ldap_config():
# Read from root /config directory # Priority 1: Check in DATA_DIR (for Docker production)
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) config_path = os.path.join(database.DATA_DIR, "config", "ldap_config.json")
config_dir = os.path.join(root_dir, "config")
config_path = os.path.join(config_dir, "ldap_config.json")
if os.path.exists(config_path): if os.path.exists(config_path):
with open(config_path, "r") as f: with open(config_path, "r") as f:
return json.load(f) return json.load(f)
# Priority 2: Fallback to source-relative config (for local dev)
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
source_config_path = os.path.join(root_dir, "config", "ldap_config.json")
if os.path.exists(source_config_path):
with open(source_config_path, "r") as f:
return json.load(f)
return {"ldap_enabled": False} return {"ldap_enabled": False}
def authenticate_ldap(username, password): def authenticate_ldap(username, password):
@@ -73,6 +79,11 @@ def authenticate_ldap(username, password):
return None return None
real_user_dn = conn.entries[0].entry_dn real_user_dn = conn.entries[0].entry_dn
user_groups = []
if hasattr(conn.entries[0], 'memberOf'):
user_groups = [str(g).lower() for g in conn.entries[0].memberOf.values]
log.debug(f"LDAP: Found memberOf groups on user: {user_groups}")
log.debug(f"LDAP: Canonical DN found: {real_user_dn}") log.debug(f"LDAP: Canonical DN found: {real_user_dn}")
# Check roles based on group membership # Check roles based on group membership
@@ -87,27 +98,39 @@ def authenticate_ldap(username, password):
groups_dn = config.get("groups_dn", "ou=groups") groups_dn = config.get("groups_dn", "ou=groups")
# Iterate through mappings to find the highest role # Iterate through mappings to find the highest role
# Priority: admin > user
potential_roles = [] potential_roles = []
for mapping in role_mappings: for mapping in role_mappings:
group_name = mapping["group"] group_name = mapping["group"]
target_role = mapping["role"] target_role = mapping["role"]
# Construct group DN if it's just a common name, else use as is # Construct group DN if it's just a common name
if "=" not in group_name: if "=" not in group_name:
full_group_dn = f"cn={group_name},{groups_dn},{base_dn}" full_group_dn = f"cn={group_name},{groups_dn},{base_dn}"
else: else:
full_group_dn = group_name full_group_dn = group_name
full_group_dn_lower = full_group_dn.lower()
log.debug(f"LDAP: Checking membership in group: {full_group_dn}") log.debug(f"LDAP: Checking membership in group: {full_group_dn}")
conn.search(full_group_dn, '(objectClass=*)', attributes=['member'])
# Method 1: Check memberOf if available (AD/LLDAP)
if full_group_dn_lower in user_groups:
log.debug(f"LDAP: Match found via memberOf for {target_role}")
potential_roles.append(target_role)
continue
# Method 2: Search group's member attribute (Standard LDAP)
conn.search(full_group_dn, '(objectClass=*)', attributes=['member', 'uniqueMember'])
if conn.entries: if conn.entries:
members = conn.entries[0].member.values members = []
if real_user_dn in members or user_dn in members or \ if hasattr(conn.entries[0], 'member'):
any(m.lower().replace(" ", "") == real_user_dn.lower().replace(" ", "") for m in members): members = [str(m).lower() for m in conn.entries[0].member.values]
log.debug(f"LDAP: User is in group {group_name}, assigning role: {target_role}") elif hasattr(conn.entries[0], 'uniqueMember'):
members = [str(m).lower() for m in conn.entries[0].uniqueMember.values]
if real_user_dn.lower() in members or user_dn.lower() in members:
log.debug(f"LDAP: Match found via group search for {target_role}")
potential_roles.append(target_role) potential_roles.append(target_role)
if "admin" in potential_roles: if "admin" in potential_roles:
@@ -166,8 +189,9 @@ def get_users(db: Session = Depends(get_db)):
users = db.query(models.User).all() users = db.query(models.User).all()
# Auto-seed if empty # Auto-seed if empty
if not users: if not users:
# [SECURITY FIX C-03] Generate random password instead of hardcoded "admin" # [SECURITY] For initial setup and recovery, we use a predictable default.
initial_password = secrets.token_urlsafe(16) # User MUST change this immediately in Settings.
initial_password = "Admin123!"
new_user = models.User( new_user = models.User(
username="Admin", username="Admin",
role="admin", role="admin",
@@ -177,7 +201,7 @@ def get_users(db: Session = Depends(get_db)):
db.add(new_user) db.add(new_user)
db.commit() db.commit()
db.refresh(new_user) db.refresh(new_user)
log.warning(f"[SECURITY] Admin initial seeded. Temporary password: {initial_password} — CHANGE IMMEDIATELY!") log.warning(f"[SECURITY] Admin initial seeded. Credentials: Admin / {initial_password} — CHANGE IMMEDIATELY!")
return [new_user] return [new_user]
return users return users

View File

@@ -0,0 +1,41 @@
import os
import sys
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from ..database import SessionLocal
from .. import models
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
def reset_admin():
db = SessionLocal()
try:
username = "Admin"
password = "Admin123!"
hashed_password = pwd_context.hash(password)
user = db.query(models.User).filter(models.User.username == username).first()
if user:
user.hashed_password = hashed_password
user.role = "admin"
print(f"✅ User '{username}' found. Password has been reset to: {password}")
else:
new_user = models.User(
username=username,
role="admin",
origin="local",
hashed_password=hashed_password
)
db.add(new_user)
print(f"✅ User '{username}' not found. Created new admin with password: {password}")
db.commit()
print("💾 Changes saved to database.")
except Exception as e:
print(f"❌ Error resetting admin: {e}")
db.rollback()
finally:
db.close()
if __name__ == "__main__":
reset_admin()

View File

@@ -1,12 +1,41 @@
# TFM aInventory - Caddy Self-Signed Internal Proxy # TFM aInventory - Caddy Patched IP Configuration
# This replaces the need for `local-ssl-proxy` in Node. # Version 1.9.17 - The Dynamic Shield (Production Polish)
{ {
:{$FRONTEND_SSL_PORT} { admin off
tls internal # Global TLS options for self-signed certificates
reverse_proxy frontend:3000 local_certs
skip_install_trust
# Configure on-demand TLS for private network IPs
on_demand_tls {
# Pointing to the backend root which returns 200 OK
# This allows Caddy to generate internal certs for any IP/domain.
ask http://backend:8000/
}
}
# Dynamic SSL Proxy (Matches ANY IP or hostname) # Dynamic SSL Proxy (Matches ANY IP or hostname)
:{$BACKEND_SSL_PORT} { https:// {
tls internal tls internal {
on_demand
}
reverse_proxy frontend:3000
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-XSS-Protection "1; mode=block"
X-Content-Type-Options "nosniff"
X-Frame-Options "SAMEORIGIN"
Referrer-Policy "strict-origin-when-cross-origin"
}
}
# Specific port listener for backend (8918 -> 444)
https://:444 {
tls internal {
on_demand
}
reverse_proxy backend:8000
} }
} }

View File

@@ -5,21 +5,21 @@
# ============================================================ # ============================================================
# --- AI API Keys --- # --- AI API Keys ---
# Google Gemini API Key (required for AI label OCR onboarding) # Google Gemini API Key (Required for AI label OCR onboarding)
# You can also set this in the root 'inventory.env' for Docker convenience.
GEMINI_API_KEY=your_gemini_api_key_here GEMINI_API_KEY=your_gemini_api_key_here
# --- Security --- # --- Security ---
# JWT secret key — generate a strong random value for production: # JWT secret key — generate a strong random value for production:
# python3 -c "import secrets; print(secrets.token_urlsafe(64))" # python3 -c "import secrets; print(secrets.token_urlsafe(64))"
# If not set, an ephemeral key is generated per-run (tokens invalidated on restart).
JWT_SECRET_KEY=change-me-generate-a-secure-random-value JWT_SECRET_KEY=change-me-generate-a-secure-random-value
# --- CORS --- # --- CORS & External Access ---
# Comma-separated list of allowed frontend origins # The system automatically allows localhost and the local LAN IP.
# Example for LAN deployment: # Use EXTRA_ALLOWED_ORIGINS for Tailscale, VPNs, or FQDNs.
# ALLOWED_ORIGINS=http://192.168.84.113:8907,https://192.168.84.113:8909 # Example: EXTRA_ALLOWED_ORIGINS=100.78.182.27,inventory.my-domain.com
ALLOWED_ORIGINS=http://localhost:8907,https://localhost:8909 EXTRA_ALLOWED_ORIGINS=
# --- Data Paths (overridden by start_server.sh / docker-compose) --- # --- Data Paths (usually managed by startup scripts) ---
# DATA_DIR=/absolute/path/to/data # DATA_DIR=/app/data
# LOGS_DIR=/absolute/path/to/logs # LOGS_DIR=/app/logs

View File

@@ -1,19 +1,17 @@
{ {
"_comment": "Copy this file to ldap_config.json and fill in real values. NEVER commit ldap_config.json to Git.",
"ldap_enabled": false, "ldap_enabled": false,
"server_uri": "ldap://YOUR_LDAP_SERVER_IP:389", "server_uri": "ldap://192.168.1.100:389",
"base_dn": "dc=yourdomain,dc=com",
"user_template": "cn={username},ou=people,dc=yourdomain,dc=com",
"groups_dn": "ou=groups",
"use_tls": false, "use_tls": false,
"ignore_cert": false, "ignore_cert": false,
"base_dn": "dc=example,dc=com",
"user_template": "uid={username},ou=users,dc=example,dc=com",
"role_mappings": [ "role_mappings": [
{ {
"group": "inventory_admins", "group": "cn=inventory_admins,ou=groups,dc=example,dc=com",
"role": "admin" "role": "admin"
}, },
{ {
"group": "inventory_users", "group": "cn=inventory_users,ou=groups,dc=example,dc=com",
"role": "user" "role": "user"
} }
] ]

8
config/proxy/Dockerfile Normal file
View File

@@ -0,0 +1,8 @@
FROM caddy:2-alpine
# Install nss-tools to allow Caddy to manage its internal trust store (fixes certutil warning)
# Install ca-certificates to ensure Caddy can trust external sites if needed
RUN apk add --no-cache nss-tools ca-certificates
# Expose the internal proxy ports
EXPOSE 80 443 444

View File

@@ -1,25 +1,83 @@
#!/bin/bash #!/bin/bash
# deploy.sh - Production Deployment Script for TFM aInventory # =============================================================================
# Forces Docker Compose to use the inventory.env file for both host and container. # TFM aInventory - Bulletproof Deployment Script (v1.9.12)
# =============================================================================
echo "🐳 TFM aInventory - Starting Deployment..." set -e
# 1. Check for configuration file # Load environment variables (from root inventory.env)
if [ ! -f "inventory.env" ]; then if [ -f inventory.env ]; then
echo "❌ ERROR: inventory.env not found!" export $(grep -v '^#' inventory.env | xargs)
echo "Please create it or use the template provided." echo "✅ Loaded configuration from inventory.env"
exit 1 else
echo "⚠️ inventory.env not found. Using default values."
fi fi
# 2. Source the env file for the current shell (helps some docker versions) # Parse arguments
export $(grep -v '^#' inventory.env | xargs) RESET_SSL=false
RESET_ADMIN=false
# 3. Run Docker Compose with explicit env-file flag for arg in "$@"; do
echo "🚀 Building and starting containers..." case $arg in
--reset-ssl)
RESET_SSL=true
shift
;;
--reset-admin)
RESET_ADMIN=true
shift
;;
--help)
echo "Usage: ./deploy.sh [options]"
echo "Options:"
echo " --reset-ssl Clear Caddy storage and reset certificates (Aggressive)"
echo " --reset-admin Force reset Admin password to 'Admin123!'"
echo " --help Show this help message"
exit 0
;;
esac
done
if [ "$RESET_SSL" = true ]; then
echo "🧹 Aggressive SSL Reset in progress..."
docker compose down
# Clear internal docker volumes
docker volume rm -f inventory_caddy_data 2>/dev/null || true
docker volume rm -f inventory_caddy_config 2>/dev/null || true
# Clear persistent host volumes if they exist
rm -rf ./data/caddy_data/* 2>/dev/null || true
rm -rf ./data/caddy_config/* 2>/dev/null || true
echo "✅ SSL storage completely cleared."
fi
echo "🚀 Starting TFM aInventory Services..."
# Use --build to ensure the custom Caddy image is built
docker compose --env-file inventory.env up -d --build --remove-orphans docker compose --env-file inventory.env up -d --build --remove-orphans
if [ "$RESET_ADMIN" = true ]; then
echo "🔐 Resetting Admin credentials..."
# Wait for container to be ready
sleep 3
docker compose exec backend python3 -m backend.scripts.reset_admin
fi
echo "" echo ""
echo "✅ Deployment requested." echo "🔍 Verifying port mapping..."
echo " Access URL: https://${SERVER_IP:-localhost}:${FRONTEND_SSL_PORT:-8919}" docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"
echo " Run 'docker compose ps' to check status."
echo ""
echo "🚀 DIAGNOSTIC LOGS (Proxy Status):"
docker compose logs proxy --tail 20
echo ""
echo "✅ Deployment complete (v1.9.12)."
echo " ------------------------------------------------------------"
echo " ACCESS COORDINATES:"
echo " 1. SECURE: https://${SERVER_IP:-localhost}:${FRONTEND_SSL_PORT:-8919}"
echo " 2. DIRECT: http://${SERVER_IP:-localhost}:${FRONTEND_PORT:-8917}"
echo " ------------------------------------------------------------"
echo " CREDENTIALS (if first run or reset):"
echo " User: Admin"
echo " Pass: Admin123!"
echo " ------------------------------------------------------------"
echo "" echo ""

View File

@@ -123,3 +123,81 @@ Obiectiv: audit de securitate complet înainte de producție.
1. Implement Phase 5: Gemini AI Vision Integration for New Item Onboarding. 1. Implement Phase 5: Gemini AI Vision Integration for New Item Onboarding.
2. Build the "History / Audit" view in the frontend. 2. Build the "History / Audit" view in the frontend.
3. Add "Trash/Discard" logic to the frontend UI. 3. Add "Trash/Discard" logic to the frontend UI.
# CURRENT AI WORKING SESSION — HANDOVER
**Active AI:** Gemini (Antigravity)
**Last Updated:** 2026-04-12
**Current Version:** v1.6.0 (BoxMaster)
**Branch:** dev
---
## STATUS: 🟢 STABLE — ADVANCED BOX MANAGEMENT & AI MODES COMPLETE (v1.6.0)
**CRITICAL FOR NEXT AI:** The "Box/Container Management" feature is **FINISHED**. Do NOT attempt to re-implement or look for a plan. The core logic is already in `frontend/app/page.tsx` (`onOCRMatch` and `BoxManager`), `backend/models.py`, and `frontend/lib/labels.ts`.
---
## WHAT WAS DONE THIS SESSION
### 1. Box Management Architecture (Backend)
- **Database Schema** — Added `box_label` column to the `items` table.
- **Audit Integrity** — Updated `AuditLog` snapshots to capture `box_label` at the time of each transaction, ensuring immutable historical traceability even if items are moved.
- **API Support** — Exposed `box_label` in Pydantic schemas and item routers.
### 2. Intelligent Scanner Routing (Frontend)
- **Box Match Priority** — Rewrote the scanner's `onOCRMatch` logic to prioritize box labels.
- **Multi-Item Support** — Developed a "Box Contents" interstitial modal that handles containers with multiple distinct item types.
- **Token Matching** — Implemented a local fuzzy token-matching engine for generic box text recognition without AI costs.
### 3. Dependency-Free Label System
- **Native Generation** — Built a zero-dependency SVG engine for Code 128 Barcodes and QR Codes (`lib/labels.ts`).
- **Box Manager Dashboard** — Added a dedicated UI to view all existing boxes and trigger label generation.
- **Hybrid Printing** — Implemented CSS `@media print` for professional desktop printers and "Save as PNG" rasterization for portable Bluetooth printers on mobile.
### 4. UI/UX: Targeted Field Scanning
- **Camera Capture** — Added a dedicated scan button in Edit modals that redirects OCR results directly to the "Box Label" field without performing general item matches.
### 5. Multi-Mode AI Discovery
- **Contextual Prompts** — Implemented a dual-mode toggle (Item/Box) in the AI Onboarding screen.
- **Box Extraction** — Created a specialized prompt for Gemini 2.0 Flash to extract container names while filtering out technical noise from product labels.
### 6. Operational Rigor: Step 0 Rule
- **Mandatory Documentation** — Updated `AI_RULES.md` to force documentation verification before any `save-version` (git commit) operation.
- **Master Branch Sync** — Confirmed `scripts/save_version.py` logic to keep `master` branch in sync with the latest releases automatically.
---
## WHAT THE NEXT AI MUST DO
1. **Database Encryption** — Consider implementing SQLite encryption at rest (SQLCipher) if requested.
2. **Persistent JWT** — If requested, move the `JWT_SECRET_KEY` to a `.env` file for session persistence across server restarts.
3. **Advanced Filtering** — Extend the Box Manager to allow bulk movements between boxes.
3. **LDAP Probe** — The "Test Connection" button may show "Partial Success" (handshake rejected) due to anonymous bind restrictions; login itself works fine.
4. **Monitoring** — If the rate limiter triggers too frequently for legitimate users, adjust the `slowapi` limit in `backend/routers/users.py`.
---
## SYSTEM STATE
**Active database:** `<project_root>/data/inventory.db`
**LDAP config:** `config/ldap_config.json`
**Network config:** `config/network_config.env`
**Proxy config:** `config/Caddyfile`
**Production Bundle:** `aInventory-PROD-v1.8.0.zip` (ConfigSync Final)
> [!IMPORTANT]
> **Git Access Fix**: The `xcode-select` breakage is bypassed by using the direct binary path: `/Library/Developer/CommandLineTools/usr/bin/git` (stored in `.git_path`). **DO NOT change this path.** Operations now work correctly via this direct link.
**How to start:**
```bash
./start_server.sh
```
- Frontend: `https://192.168.84.113:8909`
- Backend: `https://192.168.84.113:8908`
**Environment variables set by start_server.sh:**
- `ALLOWED_ORIGINS` — auto-detected
- `DATA_DIR` — absolute path
- `JWT_SECRET_KEY` — ephemeral (regenerates on restart)
\n---\n

View File

@@ -1,55 +1,41 @@
# CURRENT AI WORKING SESSION — HANDOVER # CURRENT AI WORKING SESSION — HANDOVER
**Active AI:** Gemini (Antigravity) **Active AI:** Gemini (Antigravity)
**Last Updated:** 2026-04-12 **Last Updated:** 2026-04-13
**Current Version:** v1.6.0 (BoxMaster) **Current Version:** v1.9.18 (CORS Sync)
**Branch:** dev **Branch:** dev
--- ---
## STATUS: 🟢 STABLE — ADVANCED BOX MANAGEMENT & AI MODES COMPLETE (v1.6.0) ## STATUS: 🟢 STABLE — GENERIC CORS & CONFIG CENTRALIZATION COMPLETE
**CRITICAL FOR NEXT AI:** The "Box/Container Management" feature is **FINISHED**. Do NOT attempt to re-implement or look for a plan. The core logic is already in `frontend/app/page.tsx` (`onOCRMatch` and `BoxManager`), `backend/models.py`, and `frontend/lib/labels.ts`. **CRITICAL FOR NEXT AI:** The CORS system has been upgraded to support `EXTRA_ALLOWED_ORIGINS` in `inventory.env`. The backend automatically expands these into full URLs (http/https across all ports).
--- ---
## WHAT WAS DONE THIS SESSION ## WHAT WAS DONE THIS SESSION
### 1. Box Management Architecture (Backend) ### 1. Generic CORS (External Access)
- **Database Schema** — Added `box_label` column to the `items` table. - **Variable**: Introduced `EXTRA_ALLOWED_ORIGINS` in `inventory.env`.
- **Audit Integrity** — Updated `AuditLog` snapshots to capture `box_label` at the time of each transaction, ensuring immutable historical traceability even if items are moved. - **Backend Expansion**: Updated `backend/main.py` to automatically generate allowed origins (plain/SSL) for any IP or FQDN provided in this comma-separated list.
- **API Support** — Exposed `box_label` in Pydantic schemas and item routers. - **Tailscale Ready**: Pre-configured with `100.78.182.27` as requested by the user.
### 2. Intelligent Scanner Routing (Frontend) ### 2. Configuration Centralization
- **Box Match Priority** — Rewrote the scanner's `onOCRMatch` logic to prioritize box labels. - **inventory.env Updates**: Added placeholders for `GEMINI_API_KEY` and security tokens to encourage usage of a single configuration file for both local and Docker deployments.
- **Multi-Item Support** — Developed a "Box Contents" interstitial modal that handles containers with multiple distinct item types. - **Port Consistency**: Cleaned up `config/backend.env.example` to reflect the actual ports used (8916-8919).
- **Token Matching** — Implemented a local fuzzy token-matching engine for generic box text recognition without AI costs.
### 3. Dependency-Free Label System ### 3. Startup & Discovery
- **Native Generation** — Built a zero-dependency SVG engine for Code 128 Barcodes and QR Codes (`lib/labels.ts`). - **Dynamic Access Banner**: Enhanced `start_server.sh` to detect `EXTRA_ALLOWED_ORIGINS` and display the corresponding Tailscale/VPN URLs at startup.
- **Box Manager Dashboard** — Added a dedicated UI to view all existing boxes and trigger label generation.
- **Hybrid Printing** — Implemented CSS `@media print` for professional desktop printers and "Save as PNG" rasterization for portable Bluetooth printers on mobile.
### 4. UI/UX: Targeted Field Scanning ### 4. Verification
- **Camera Capture** — Added a dedicated scan button in Edit modals that redirects OCR results directly to the "Box Label" field without performing general item matches. - **Test Script**: Verified the CORS expansion logic with `scratch/verify_cors.py` (deleted after use).
### 5. Multi-Mode AI Discovery
- **Contextual Prompts** — Implemented a dual-mode toggle (Item/Box) in the AI Onboarding screen.
- **Box Extraction** — Created a specialized prompt for Gemini 2.0 Flash to extract container names while filtering out technical noise from product labels.
### 6. Operational Rigor: Step 0 Rule
- **Mandatory Documentation** — Updated `AI_RULES.md` to force documentation verification before any `save-version` (git commit) operation.
- **Master Branch Sync** — Confirmed `scripts/save_version.py` logic to keep `master` branch in sync with the latest releases automatically.
--- ---
## WHAT THE NEXT AI MUST DO ## WHAT THE NEXT AI MUST DO
1. **Database Encryption** — Consider implementing SQLite encryption at rest (SQLCipher) if requested. 1. **Docker Sync**: If the user experiences issues with the API key in Docker, suggest rebuilding the image or ensuring `inventory.env` is correctly mounted.
2. **Persistent JWT** If requested, move the `JWT_SECRET_KEY` to a `.env` file for session persistence across server restarts. 2. **Reverse Proxy**: If a more complex FQDN setup is needed, consider updating `config/Caddyfile` to handle wildcard subdomains if `EXTRA_ALLOWED_ORIGINS` list becomes too long.
3. **Advanced Filtering** — Extend the Box Manager to allow bulk movements between boxes.
3. **LDAP Probe** — The "Test Connection" button may show "Partial Success" (handshake rejected) due to anonymous bind restrictions; login itself works fine.
4. **Monitoring** — If the rate limiter triggers too frequently for legitimate users, adjust the `slowapi` limit in `backend/routers/users.py`.
--- ---
@@ -57,21 +43,16 @@
**Active database:** `<project_root>/data/inventory.db` **Active database:** `<project_root>/data/inventory.db`
**LDAP config:** `config/ldap_config.json` **LDAP config:** `config/ldap_config.json`
**Network config:** `config/network_config.env` **Network config:** `inventory.env` (Now the Primary SSOT for networking)
**Proxy config:** `config/Caddyfile` **Proxy config:** `config/Caddyfile`
**Production Bundle:** `aInventory-PROD-v1.8.0.zip` (ConfigSync Final)
> [!IMPORTANT]
> **Git Access Fix**: The `xcode-select` breakage is bypassed by using the direct binary path: `/Library/Developer/CommandLineTools/usr/bin/git` (stored in `.git_path`). **DO NOT change this path.** Operations now work correctly via this direct link.
**How to start:** **How to start:**
```bash ```bash
./start_server.sh ./start_server.sh
``` ```
- Frontend: `https://192.168.84.113:8909` - Local URL: `https://localhost:8919`
- Backend: `https://192.168.84.113:8908` - LAN URL: `https://192.168.84.113:8919`
- Tailscale URL: `https://100.78.182.27:8919` (Now allowed in CORS)
**Environment variables set by start_server.sh:** ---
- `ALLOWED_ORIGINS` — auto-detected ✓ Done.
- `DATA_DIR` — absolute path
- `JWT_SECRET_KEY` — ephemeral (regenerates on restart)

View File

@@ -12,6 +12,7 @@ services:
volumes: volumes:
- ./data:/app/data - ./data:/app/data
- ./logs:/app/logs - ./logs:/app/logs
- ./config:/app/config
- ./scripts:/app/scripts:ro - ./scripts:/app/scripts:ro
environment: environment:
- DATA_DIR=/app/data - DATA_DIR=/app/data
@@ -36,12 +37,14 @@ services:
restart: unless-stopped restart: unless-stopped
proxy: proxy:
image: caddy:alpine build:
context: .
dockerfile: config/proxy/Dockerfile
networks: networks:
- inventory_net - inventory_net
ports: ports:
- ${BACKEND_SSL_PORT:-3002}:${BACKEND_SSL_PORT:-3002} - ${BACKEND_SSL_PORT:-8918}:444
- ${FRONTEND_SSL_PORT:-3003}:${FRONTEND_SSL_PORT:-3003} - ${FRONTEND_SSL_PORT:-8919}:443
env_file: env_file:
- inventory.env - inventory.env
volumes: volumes:

View File

@@ -30,6 +30,7 @@ cp inventory.service.template "$PROD_DIR/"
cp USER_GUIDE.md "$PROD_DIR/" cp USER_GUIDE.md "$PROD_DIR/"
cp README.md "$PROD_DIR/INSTALLATION_GUIDE.md" cp README.md "$PROD_DIR/INSTALLATION_GUIDE.md"
cp inventory.env "$PROD_DIR/" cp inventory.env "$PROD_DIR/"
cp deploy.sh "$PROD_DIR/"
cp .git_path "$PROD_DIR/" 2>/dev/null || true cp .git_path "$PROD_DIR/" 2>/dev/null || true
cp frontend/VERSION.json "$PROD_DIR/" cp frontend/VERSION.json "$PROD_DIR/"
cp frontend/VERSION.json "$PROD_DIR/frontend/" cp frontend/VERSION.json "$PROD_DIR/frontend/"

View File

@@ -1 +1,6 @@
{"version": "1.9.5", "last_build": "2026-04-13-2132", "codename": "Bulletproof", "commit": "a0eaddf9"} {
"version": "1.9.18",
"last_build": "2026-04-13-2343",
"codename": "MobilePolish",
"commit": "1fff658d"
}

View File

@@ -88,37 +88,56 @@ export default function LoginPage() {
<User size={32} /> <User size={32} />
</div> </div>
<h2 className="text-2xl font-black text-white tracking-tight">Identity Check</h2> <h2 className="text-2xl font-black text-white tracking-tight">Identity Check</h2>
<p className="text-slate-500 text-sm">Select operator profile or use enterprise login</p> <p className="text-slate-500 text-sm">Select operator profile or use direct login</p>
</div> </div>
<div className="grid gap-3"> <div className="grid gap-3">
{!selectedUserForLogin && !isEnterprise ? ( {!selectedUserForLogin && !isEnterprise ? (
<> <>
{users.map(user => ( {users.length > 0 ? (
<button <>
key={user.id} {users.map(user => (
onClick={() => handleSelectUser(user)} <button
className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 rounded-2xl text-left transition-all group flex items-center justify-between" key={user.id}
> onClick={() => handleSelectUser(user)}
<div className="flex items-center gap-3"> className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 rounded-2xl text-left transition-all group flex items-center justify-between"
<div className="w-8 h-8 rounded-full bg-slate-900 border border-slate-700 flex items-center justify-center text-slate-500 group-hover:text-primary transition-colors"> >
{user.role === 'admin' ? <Shield size={14} /> : <User size={14} />} <div className="flex items-center gap-3">
</div> <div className="w-8 h-8 rounded-full bg-slate-900 border border-slate-700 flex items-center justify-center text-slate-500 group-hover:text-primary transition-colors">
<div> {user.role === 'admin' ? <Shield size={14} /> : <User size={14} />}
<p className="text-white font-black text-sm">{user.username}</p> </div>
<p className="text-xs text-slate-500 font-bold mt-1">{user.role}</p> <div>
</div> <p className="text-white font-black text-sm">{user.username}</p>
</div> <p className="text-xs text-slate-500 font-bold mt-1">{user.role}</p>
<ChevronRight size={16} className="text-slate-600 group-hover:text-primary transition-colors" /> </div>
</button> </div>
))} <ChevronRight size={16} className="text-slate-600 group-hover:text-primary transition-colors" />
<div className="pt-2"> </button>
))}
</>
) : (
<div className="text-center p-4 text-slate-500 text-xs font-bold animate-pulse">
Connectivity issues? Use manual login below.
</div>
)}
<div className="pt-2 grid grid-cols-2 gap-3">
<button <button
onClick={() => setIsEnterprise(true)} onClick={() => setIsEnterprise(true)}
className="w-full flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-slate-500 hover:text-primary hover:border-primary/40 transition-all font-bold text-xs" className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-slate-500 hover:text-white hover:border-slate-500 transition-all font-bold text-[10px]"
> >
<Shield size={14} /> <Lock size={12} />
Enterprise Login Enterprise
</button>
<button
onClick={() => {
setSelectedUserForLogin({ username: '' });
// We use an empty username object to trigger the manual input view
}}
className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-primary/20 bg-primary/5 text-primary hover:bg-primary/10 transition-all font-bold text-[10px]"
>
<User size={12} />
Manual Login
</button> </button>
</div> </div>
</> </>
@@ -180,10 +199,26 @@ export default function LoginPage() {
</button> </button>
<div> <div>
<p className="text-sm font-bold text-slate-500">Logging in as</p> <p className="text-sm font-bold text-slate-500">Logging in as</p>
<p className="text-white font-black">{selectedUserForLogin.username}</p> <p className="text-white font-black">{selectedUserForLogin.username || "Manual Input"}</p>
</div> </div>
</div> </div>
{!selectedUserForLogin.username && (
<div className="space-y-2">
<label className="text-xs font-black text-slate-500 px-1">Username</label>
<div className="relative">
<User className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
<input
type="text"
autoFocus
onChange={(e) => setSelectedUserForLogin({...selectedUserForLogin, username: e.target.value})}
className="w-full bg-slate-800/50 border border-slate-800 focus:border-primary rounded-2xl py-4 pl-12 pr-4 text-white focus:outline-none transition-all placeholder:text-slate-700 font-mono"
placeholder="Admin"
/>
</div>
</div>
)}
<div className="space-y-2"> <div className="space-y-2">
<label className="text-xs font-black text-slate-500 px-1">Password</label> <label className="text-xs font-black text-slate-500 px-1">Password</label>
<div className="relative"> <div className="relative">
@@ -209,9 +244,10 @@ export default function LoginPage() {
)} )}
</div> </div>
{users.length === 0 && ( {/* Progress bar hint */}
<div className="text-center p-8 text-slate-500 animate-pulse"> {users.length === 0 && !selectedUserForLogin && !isEnterprise && (
Initializing users... <div className="w-full bg-slate-800 h-1 rounded-full overflow-hidden">
<div className="bg-primary h-full animate-progress-fast shadow-[0_0_8px_rgba(var(--primary-rgb),0.5)]"></div>
</div> </div>
)} )}
</div> </div>

View File

@@ -471,60 +471,53 @@ export default function Home() {
</div> </div>
</div> </div>
<div className="flex flex-wrap items-center justify-between sm:justify-end gap-3 sm:gap-6 bg-slate-900/40 sm:bg-transparent p-3 sm:p-0 rounded-2xl border border-slate-800/50 sm:border-none"> <div className="flex flex-wrap items-center justify-between sm:justify-end gap-3 sm:gap-6 bg-slate-900/40 sm:bg-transparent px-4 py-2 sm:p-0 rounded-2xl border border-slate-800/50 sm:border-none">
<div className="flex flex-wrap items-center gap-4"> <div className="flex flex-wrap items-center gap-4 sm:gap-6">
{isScannerReady && ( {isScannerReady && (
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-2">
<div className="w-1 h-1 rounded-full bg-green-500 shadow-[0_0_5px_rgba(34,197,94,0.5)]" /> <div className="w-1.5 h-1.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)]" />
<span className="text-xs font-black text-green-500/80 whitespace-nowrap"> <span className="text-[10px] sm:text-xs font-black text-green-500/90 whitespace-nowrap tracking-wider uppercase">
Offline Scan: OK Scanner: OK
</span> </span>
</div> </div>
)} )}
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-2">
<div className={`w-1 h-1 rounded-full ${isOnline ? 'bg-green-500 animate-pulse shadow-[0_0_5px_rgba(34,197,94,0.5)]' : 'bg-rose-500 shadow-[0_0_5px_rgba(244,63,94,0.5)]'}`} /> <div className={`w-1.5 h-1.5 rounded-full ${isOnline ? 'bg-green-500 animate-pulse shadow-[0_0_8px_rgba(34,197,94,0.6)]' : 'bg-rose-500 shadow-[0_0_8px_rgba(244,63,94,0.6)]'}`} />
<span className={`text-xs font-black whitespace-nowrap ${isOnline ? 'text-green-500/80' : 'text-rose-500/80'}`}> <span className={`text-[10px] sm:text-xs font-black whitespace-nowrap tracking-wider uppercase ${isOnline ? 'text-green-500/90' : 'text-rose-500/90'}`}>
Server Sync: {isOnline ? 'OK' : 'No'} Sync: {isOnline ? 'Active' : 'Offline'}
</span> </span>
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-3">
<button <button
onClick={() => setShowBoxManager(true)} onClick={handleSync}
className="p-3 bg-slate-900 border border-slate-800 text-slate-400 rounded-xl hover:text-primary transition-colors hover:border-primary/30" disabled={syncing}
title="Box Manager" className="p-2.5 bg-slate-900/80 border border-slate-800 text-slate-400 rounded-xl hover:text-white transition-all active:scale-95 disabled:opacity-50"
> >
<Package size={20} /> <RefreshCw size={18} className={syncing ? "animate-spin text-primary" : ""} />
</button> </button>
<button </div>
onClick={handleSync}
disabled={syncing}
className="p-3 bg-slate-900 border border-slate-800 text-slate-400 rounded-xl hover:text-white transition-colors disabled:opacity-50"
>
<RefreshCw size={20} className={syncing ? "animate-spin text-primary" : ""} />
</button>
</div>
</div> </div>
</header> </header>
<div className="w-full px-1 space-y-6"> <div className="w-full px-1 space-y-6">
{/* Mode Switcher */} {/* Mode Switcher */}
<div className="flex p-1 bg-slate-900/80 backdrop-blur-md rounded-2xl shadow-inner w-full"> <div className="flex p-1.5 bg-slate-900/80 backdrop-blur-md rounded-2xl shadow-inner w-full gap-1">
{[ {[
{ id: 'CHECK_IN', label: 'Check in', icon: ArrowDownCircle }, { id: 'CHECK_IN', label: 'Check In', icon: ArrowDownCircle },
{ id: 'CHECK_OUT', label: 'Check out', icon: ArrowUpCircle }, { id: 'CHECK_OUT', label: 'Check Out', icon: ArrowUpCircle },
{ id: 'TRASH', label: 'Trash', icon: Trash2 } { id: 'TRASH', label: 'Trash', icon: Trash2 }
].map((m) => ( ].map((m) => (
<button <button
key={m.id} key={m.id}
onClick={() => setMode(m.id as any)} onClick={() => setMode(m.id as any)}
className={cn( className={cn(
"flex-1 py-3 rounded-xl text-sm font-black transition-all flex items-center justify-center gap-2", "flex-1 py-3.5 rounded-xl text-xs sm:text-sm font-black transition-all flex items-center justify-center gap-3",
mode === m.id ? "bg-slate-800 text-primary shadow-lg" : "text-slate-500 hover:text-slate-300" mode === m.id ? "bg-slate-800 text-primary shadow-lg ring-1 ring-primary/20" : "text-slate-500 hover:text-slate-300"
)} )}
> >
<m.icon size={18} /> <m.icon size={18} className={mode === m.id ? "scale-110 transition-transform" : ""} />
{m.label} <span className="truncate">{m.label}</span>
</button> </button>
))} ))}
</div> </div>
@@ -558,15 +551,31 @@ export default function Home() {
<p className="text-sm text-slate-400">Scan labels to {mode.replace('_', ' ')} items</p> <p className="text-sm text-slate-400">Scan labels to {mode.replace('_', ' ')} items</p>
</div> </div>
<div className="w-full h-px bg-slate-800 my-2" /> <div className="w-full h-px bg-slate-800/50 my-2" />
<button <div className="w-full grid grid-cols-1 gap-4">
onClick={() => setShowOnboarding(true)} <button
className="w-full h-16 rounded-[1.5rem] bg-slate-900/50 border border-slate-800 flex items-center justify-center gap-3 group hover:border-primary/40 transition-all font-bold" onClick={() => setShowOnboarding(true)}
> className="w-full h-18 py-4 rounded-[1.5rem] bg-indigo-500/10 border border-indigo-500/20 flex items-center justify-center gap-4 group hover:border-indigo-500/50 transition-all font-black text-indigo-400"
<Sparkles size={18} className="text-primary group-hover:scale-110 transition-transform" /> >
<span className="text-sm">Add NEW Item<br />(AI Onboarding)</span> <Sparkles size={24} className="group-hover:scale-125 transition-transform" />
</button> <span className="text-left leading-tight">
Add NEW Item<br />
<span className="text-[10px] opacity-60 uppercase tracking-widest font-mono">AI Onboarding</span>
</span>
</button>
<button
onClick={() => setShowBoxManager(true)}
className="w-full h-18 py-4 rounded-[1.5rem] bg-slate-900/50 border border-slate-800 flex items-center justify-center gap-4 group hover:border-primary/40 transition-all font-black text-slate-300"
>
<Package size={24} className="text-primary group-hover:scale-125 transition-transform" />
<span className="text-left leading-tight">
Manage Boxes<br />
<span className="text-[10px] opacity-60 uppercase tracking-widest font-mono">Box Inventory</span>
</span>
</button>
</div>
</div> </div>
)} )}
</section> </section>

View File

@@ -14,6 +14,17 @@ if [ -d "/app/logs" ]; then
chown -R nextjs:nodejs /app/logs chown -R nextjs:nodejs /app/logs
fi fi
# Generate network.json for frontend runtime discovery
echo "🐳 [Docker] Generating public/network.json..."
cat <<EOF > /app/public/network.json
{
"SERVER_IP": "${SERVER_IP:-localhost}",
"BACKEND_PORT": ${BACKEND_PORT:-8000},
"BACKEND_SSL_PORT": ${BACKEND_SSL_PORT:-8908}
}
EOF
chown nextjs:nodejs /app/public/network.json
# Hand off to the application server as the nextjs user # Hand off to the application server as the nextjs user
echo "🐳 [Docker] Starting Next.js standalone server as nextjs user..." echo "🐳 [Docker] Starting Next.js standalone server as nextjs user..."
exec su-exec nextjs node server.js exec su-exec nextjs node server.js

View File

@@ -15,5 +15,10 @@ BACKEND_SSL_PORT=8918
FRONTEND_PORT=8917 FRONTEND_PORT=8917
FRONTEND_SSL_PORT=8919 FRONTEND_SSL_PORT=8919
# Security # Security & AI
JWT_SECRET_KEY=change_me_in_production JWT_SECRET_KEY=change_me_in_production
GEMINI_API_KEY=AIzaSyAajthWG2agpDLyJHY11U5qFLP4WnV5z0w
# External Access (CORS)
# Comma-separated list of extra IPs or FQDNs allowed to connect (e.g. Tailscale, VPN)
EXTRA_ALLOWED_ORIGINS=100.78.182.27

View File

@@ -87,9 +87,19 @@ echo -e "${GREEN}=======================================================${NC}"
echo -e "${GREEN}${BOLD} 🚀 TFM aInventory UNIFIED ACCESS${NC}" echo -e "${GREEN}${BOLD} 🚀 TFM aInventory UNIFIED ACCESS${NC}"
echo -e "${GREEN}=======================================================${NC}" echo -e "${GREEN}=======================================================${NC}"
echo "" echo ""
echo -e " USE THIS URL ON BOTH DESKTOP & MOBILE:" echo -e " USE THIS URL ON BOTH DESKTOP & MOBILE:"
echo -e " 👉 ${GREEN}${BOLD}https://$LOCAL_IP:$FRONTEND_SSL_PORT${NC}" echo -e " 👉 ${GREEN}${BOLD}https://$LOCAL_IP:$FRONTEND_SSL_PORT${NC}"
echo -e " (Or ${GREEN}https://localhost:$FRONTEND_SSL_PORT${NC} on this Mac)" echo -e " (Or ${GREEN}https://localhost:$FRONTEND_SSL_PORT${NC} on this Mac)"
if [ ! -z "$EXTRA_ALLOWED_ORIGINS" ]; then
echo -e " EXTERNAL/VPN ACCESS points:"
IFS=',' read -ra ADDR <<< "$EXTRA_ALLOWED_ORIGINS"
for exp in "${ADDR[@]}"; do
# Trim spaces and print
TRIMMED=$(echo $exp | xargs)
echo -e " 👉 ${GREEN}${BOLD}https://$TRIMMED:$FRONTEND_SSL_PORT${NC}"
done
fi
echo "" echo ""
echo -e " ${YELLOW}${BOLD}NOTE:${NC} If you see a 'Not Private' warning," echo -e " ${YELLOW}${BOLD}NOTE:${NC} If you see a 'Not Private' warning,"
echo -e " Click 'Advanced' -> 'Proceed' to continue." echo -e " Click 'Advanced' -> 'Proceed' to continue."