This commit is contained in:
Chris 2026-05-27 00:04:36 -04:00
parent 97733b8570
commit 02f0ecb587
9 changed files with 3378 additions and 368 deletions

4
.gitignore vendored
View file

@ -28,6 +28,10 @@ pnpm-debug.log*
.idea/ .idea/
.DS_Store .DS_Store
Thumbs.db Thumbs.db
backups/
# Scratch and test scripts # Scratch and test scripts
test_scraper.js test_scraper.js
# Application Settings Configuration
public/settings.json

938
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -11,7 +11,10 @@
"axios": "^1.7.2", "axios": "^1.7.2",
"cheerio": "^1.0.0-rc.12", "cheerio": "^1.0.0-rc.12",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.19.2" "express": "^4.19.2",
"puppeteer": "^25.1.0",
"puppeteer-extra": "^3.3.6",
"puppeteer-extra-plugin-stealth": "^2.11.2"
}, },
"private": true "private": true
} }

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GourmetVault – Curated Recipe Manager</title> <title>ForkFolio – Curated Recipe Manager</title>
<!-- Google Fonts Outfit & Inter --> <!-- Google Fonts Outfit & Inter -->
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@ -16,12 +16,20 @@
<body class="dark-theme"> <body class="dark-theme">
<!-- Top Navigation --> <!-- Top Navigation -->
<header class="app-header"> <header class="app-header">
<div class="header-logo"> <div class="header-logo" style="cursor: pointer;" onclick="switchTab('my-cookbook')">
<div class="logo-icon"><i data-lucide="cooking-pot"></i></div> <div class="logo-icon"><i data-lucide="cooking-pot"></i></div>
<span class="logo-text">Gourmet<span>Vault</span></span> <span class="logo-text">Fork<span>Folio</span></span>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<div class="user-badge-container" id="user-badge-container" style="display: none;">
<span class="user-display"><i data-lucide="user"></i> <span id="user-display-name">@chef</span></span>
<button class="btn btn-icon-round" id="btn-settings" title="Application Settings"><i data-lucide="settings"></i></button>
<button class="btn btn-icon-round" id="btn-logout" title="Log Out"><i data-lucide="log-out"></i></button>
</div>
<button class="btn btn-outline" id="tab-user-admin" style="display: none;" title="User Admin Management Console">
<i data-lucide="shield"></i> <span>User Admin</span>
</button>
<button class="btn btn-outline" id="btn-manual-add" title="Create Recipe Manually"> <button class="btn btn-outline" id="btn-manual-add" title="Create Recipe Manually">
<i data-lucide="plus"></i> <span>Manual Recipe</span> <i data-lucide="plus"></i> <span>Manual Recipe</span>
</button> </button>
@ -44,24 +52,37 @@
<form class="url-input-form" id="url-scrape-form"> <form class="url-input-form" id="url-scrape-form">
<div class="input-wrapper"> <div class="input-wrapper">
<i data-lucide="link" class="input-icon"></i> <i data-lucide="link" class="input-icon"></i>
<input type="url" id="scrape-url-input" placeholder="Paste cooking website link here (e.g., allrecipes.com, foodnetwork.com...)" required autocomplete="off"> <input type="url" id="scrape-url-input" placeholder="Paste cooking website link here (e.g., allrecipes.com, foodnetwork.com...)" autocomplete="off">
</div> </div>
<div class="hero-buttons-group" style="display: flex; gap: 8px;">
<button type="submit" class="btn btn-primary" id="btn-scrape-submit"> <button type="submit" class="btn btn-primary" id="btn-scrape-submit">
<i data-lucide="wand-2"></i> <span>Extract Recipe</span> <i data-lucide="wand-2"></i> <span>Extract Recipe</span>
</button> </button>
<input type="file" id="scan-image-input" accept="image/*" style="display: none;">
<button type="button" class="btn btn-accent" id="btn-scan-image" style="background-color: var(--secondary); color: var(--text-white);" title="Scan Recipe from Photo">
<i data-lucide="camera"></i> <span>Scan Photo</span>
</button>
</div>
</form> </form>
</section> </section>
<!-- Recipe Library Dashboard --> <!-- Recipe Library Dashboard -->
<section class="library-section"> <section class="library-section">
<div class="library-header"> <div class="library-header">
<h2 class="section-title">My Cookbook</h2> <div class="dashboard-tabs">
<button class="dashboard-tab-btn active" id="tab-my-cookbook">
<i data-lucide="book-open"></i> <span>My Cookbook</span>
</button>
<button class="dashboard-tab-btn" id="tab-community-vault">
<i data-lucide="globe"></i> <span>Community Vault</span>
</button>
</div>
<!-- Search and Filters --> <!-- Search and Filters -->
<div class="filter-controls"> <div class="filter-controls">
<div class="search-wrapper"> <div class="search-wrapper">
<i data-lucide="search" class="search-icon"></i> <i data-lucide="search" class="search-icon"></i>
<input type="text" id="library-search" placeholder="Search saved recipes..."> <input type="text" id="library-search" placeholder="Search recipes...">
</div> </div>
</div> </div>
</div> </div>
@ -77,6 +98,35 @@
<h3>Your vault is empty</h3> <h3>Your vault is empty</h3>
<p>Insert a cooking web link above or create one manually to build your digital recipe collections.</p> <p>Insert a cooking web link above or create one manually to build your digital recipe collections.</p>
</div> </div>
<!-- User Admin Management Console -->
<div id="user-admin-panel" style="display: none;" class="admin-panel-container">
<div class="admin-panel-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
<div>
<h3 style="font-size: 1.4rem; color: var(--text-main); margin-bottom: 4px;">Chef Profiles Management</h3>
<p style="font-size: 0.85rem; color: var(--text-muted);">Create new user profiles and delete accounts with custom recipe preservation options.</p>
</div>
<button class="btn btn-primary" id="btn-admin-add-user">
<i data-lucide="user-plus"></i> <span>Create Chef Account</span>
</button>
</div>
<div class="table-responsive">
<table class="admin-users-table">
<thead>
<tr>
<th>Username</th>
<th>Account Type</th>
<th>Created Date</th>
<th style="text-align: right;">Actions</th>
</tr>
</thead>
<tbody id="admin-users-list">
<!-- Dynamic list loaded via JS -->
</tbody>
</table>
</div>
</div>
</section> </section>
</main> </main>
@ -133,11 +183,19 @@
</div> </div>
<div class="input-wrapper custom-img-url-wrapper"> <div class="input-wrapper custom-img-url-wrapper">
<i data-lucide="image" class="input-icon"></i>
<input type="url" id="edit-image-url" placeholder="Or enter a direct custom image URL..."> <input type="url" id="edit-image-url" placeholder="Or enter a direct custom image URL...">
</div> </div>
</div> </div>
<!-- Share Option -->
<div class="form-group share-toggle-group">
<label class="checkbox-container">
<input type="checkbox" id="edit-is-public" checked>
<span class="checkbox-label"><i data-lucide="globe" style="width: 14px; height: 14px; display: inline-block; vertical-align: middle; margin-right: 4px;"></i> Share with ForkFolio Community (Public)</span>
</label>
<p class="form-help text-sm opacity-80" style="margin-top: 4px; font-size: 0.8rem; color: var(--text-muted);">If enabled, this recipe will be shared to the global Community Vault feed for everyone to view and clone.</p>
</div>
<div class="form-grid-2"> <div class="form-grid-2">
<!-- Ingredients Editing --> <!-- Ingredients Editing -->
<div class="form-group"> <div class="form-group">
@ -168,7 +226,10 @@
<div class="detail-hero-banner" id="recipe-detail-banner"> <div class="detail-hero-banner" id="recipe-detail-banner">
<button class="detail-back-btn" onclick="closeModal('detail-modal')"><i data-lucide="arrow-left"></i> <span>Back</span></button> <button class="detail-back-btn" onclick="closeModal('detail-modal')"><i data-lucide="arrow-left"></i> <span>Back</span></button>
<div class="detail-actions"> <div class="detail-actions">
<button class="btn btn-icon-round" id="btn-detail-edit" title="Edit Recipe"><i data-lucide="edit-3"></i></button> <button class="btn btn-accent" id="btn-detail-clone" style="display: none;" title="Clone to My Cookbook">
<i data-lucide="copy"></i> <span>Clone to My Cookbook</span>
</button>
<button class="btn btn-icon-round" id="btn-detail-edit" title="Edit Recipe"><i data-lucide="edit"></i></button>
<button class="btn btn-icon-round btn-danger-hover" id="btn-detail-delete" title="Delete Recipe"><i data-lucide="trash-2"></i></button> <button class="btn btn-icon-round btn-danger-hover" id="btn-detail-delete" title="Delete Recipe"><i data-lucide="trash-2"></i></button>
</div> </div>
</div> </div>
@ -176,10 +237,16 @@
<div class="detail-main-content"> <div class="detail-main-content">
<div class="detail-header-info"> <div class="detail-header-info">
<h2 id="recipe-detail-title">Garlic Butter Salmon</h2> <h2 id="recipe-detail-title">Garlic Butter Salmon</h2>
<div class="recipe-creator-credit" id="recipe-detail-creator" style="display: none; margin-bottom: 12px;">
<span class="creator-badge" style="font-size: 0.85rem; padding: 4px 8px; background: rgba(245, 158, 11, 0.15); border: 1px dashed rgba(245, 158, 11, 0.3); border-radius: 6px; color: #f59e0b; display: inline-flex; align-items: center; gap: 4px;"><i data-lucide="user" style="width: 12px; height: 12px;"></i> Shared by <span id="recipe-detail-creator-name">@chef</span></span>
</div>
<div class="recipe-meta-tags"> <div class="recipe-meta-tags">
<span id="tag-servings"><i data-lucide="users"></i> <span class="val">4 servings</span></span> <span id="tag-servings"><i data-lucide="users"></i> <span class="val">4 servings</span></span>
<span id="tag-prep"><i data-lucide="clock"></i> Prep: <span class="val">15 mins</span></span> <span id="tag-prep"><i data-lucide="clock"></i> Prep: <span class="val">15 mins</span></span>
<span id="tag-cook"><i data-lucide="flame"></i> Cook: <span class="val">25 mins</span></span> <span id="tag-cook"><i data-lucide="flame"></i> Cook: <span class="val">25 mins</span></span>
<a id="tag-source" href="#" target="_blank" rel="noopener noreferrer" style="display: none;">
<i data-lucide="external-link"></i> <span class="val">Original Source</span>
</a>
</div> </div>
<p class="recipe-detail-desc" id="recipe-detail-description">A quick and delicious salmon dinner.</p> <p class="recipe-detail-desc" id="recipe-detail-description">A quick and delicious salmon dinner.</p>
</div> </div>
@ -290,6 +357,192 @@
</div> </div>
</div> </div>
<!-- AUTHENTICATION DIALOG (LOG IN ONLY) -->
<div class="modal-overlay" id="auth-modal" style="display: flex;">
<div class="modal-box max-width-xs auth-modal-box">
<div class="modal-header justify-center border-none pb-0">
<div class="auth-logo">
<div class="logo-icon"><i data-lucide="cooking-pot"></i></div>
<h2>Fork<span>Folio</span></h2>
</div>
</div>
<div class="modal-body auth-modal-body">
<div id="auth-error-msg" class="auth-error-alert" style="display: none;">
<i data-lucide="alert-circle" class="error-alert-icon"></i>
<span id="auth-error-text">Error message here</span>
</div>
<!-- Log In Form -->
<form id="login-form">
<div class="form-group mb-4">
<label for="login-username">Username</label>
<div class="input-wrapper">
<input type="text" id="login-username" required placeholder="Enter username" autocomplete="username">
</div>
</div>
<div class="form-group mb-6">
<label for="login-password">Password</label>
<div class="input-wrapper">
<input type="password" id="login-password" required placeholder="Enter password" autocomplete="current-password">
</div>
</div>
<button type="submit" class="btn btn-primary btn-full-width">
<i data-lucide="log-in"></i> <span>Log In</span>
</button>
</form>
</div>
</div>
</div>
<!-- ADMIN: CREATE USER MODAL -->
<div class="modal-overlay" id="admin-create-user-modal">
<div class="modal-box max-width-xs">
<div class="modal-header">
<h3>Create New Chef Account</h3>
<button class="close-btn" onclick="closeModal('admin-create-user-modal')"><i data-lucide="x"></i></button>
</div>
<div class="modal-body">
<div id="admin-create-error" class="auth-error-alert" style="display: none;">
<i data-lucide="alert-circle" class="error-alert-icon"></i>
<span id="admin-create-error-text"></span>
</div>
<form id="admin-create-user-form">
<div class="form-group mb-3">
<label for="admin-new-username">Username *</label>
<div class="input-wrapper">
<i data-lucide="user" class="input-icon"></i>
<input type="text" id="admin-new-username" required placeholder="e.g. chef_julie" autocomplete="off">
</div>
<p class="form-help text-sm opacity-80" style="margin-top: 4px; font-size: 0.8rem; color: var(--text-muted);">Lowercase letters, numbers, underscores (3-20 characters).</p>
</div>
<div class="form-group mb-6">
<label for="admin-new-password">Temporary Password *</label>
<div class="input-wrapper">
<i data-lucide="lock" class="input-icon"></i>
<input type="password" id="admin-new-password" required placeholder="Minimum 6 characters" autocomplete="off">
</div>
</div>
<button type="submit" class="btn btn-primary btn-full-width">
<i data-lucide="user-plus"></i> <span>Create Account</span>
</button>
</form>
</div>
</div>
</div>
<!-- ADMIN: DELETE USER CONFIRMATION MODAL -->
<div class="modal-overlay" id="admin-delete-user-modal">
<div class="modal-box max-width-xs">
<div class="modal-header border-none pb-0">
<h3 style="color: var(--danger); display: flex; align-items: center; gap: 8px;">
<i data-lucide="trash-2"></i> Delete Chef Account
</h3>
<button class="close-btn" onclick="closeModal('admin-delete-user-modal')"><i data-lucide="x"></i></button>
</div>
<div class="modal-body" style="padding-top: 12px;">
<input type="hidden" id="delete-user-target-id">
<p style="font-size: 0.95rem; line-height: 1.5; color: var(--text-main); margin-bottom: 20px;">
Are you sure you want to delete account <strong id="delete-user-target-name">@username</strong>? This action cannot be undone.
</p>
<div class="form-group" style="background: rgba(245, 158, 11, 0.08); border: 1px dashed rgba(245, 158, 11, 0.25); border-radius: 8px; padding: 12px; margin-bottom: 24px;">
<label class="checkbox-container" style="align-items: flex-start;">
<input type="checkbox" id="delete-user-preserve-recipes" checked>
<span class="checkbox-label" style="font-size: 0.9rem; line-height: 1.4; color: var(--text-main); font-weight: 500;">
<i data-lucide="globe" style="width: 14px; height: 14px; display: inline-block; vertical-align: middle; margin-right: 4px;"></i> Keep recipes in Community Vault?
</span>
</label>
<p style="font-size: 0.75rem; color: var(--text-muted); margin-top: 6px; padding-left: 30px; margin-bottom: 0;">
If enabled, this chef's private recipes will be transferred to a public archive in the Community Vault. If disabled, all recipes owned by this chef will be purged.
</p>
</div>
<div style="display: flex; gap: 12px; justify-content: flex-end;">
<button class="btn btn-outline" onclick="closeModal('admin-delete-user-modal')">Cancel</button>
<button class="btn btn-danger" id="btn-admin-confirm-delete" style="background-color: var(--danger); color: white;">
<span>Delete Account</span>
</button>
</div>
</div>
</div>
</div>
<!-- SETTINGS MODAL -->
<div class="modal-overlay" id="settings-modal">
<div class="modal-box max-width-xs">
<div class="modal-header">
<h3 style="display: flex; align-items: center; gap: 8px;">
<i data-lucide="settings"></i> Application Settings
</h3>
<button class="close-btn" onclick="closeModal('settings-modal')"><i data-lucide="x"></i></button>
</div>
<div class="modal-body" style="padding-top: 12px;">
<div id="settings-status-msg" class="auth-error-alert" style="display: none; background: rgba(16, 185, 129, 0.1); border-color: rgba(16, 185, 129, 0.3); color: #10b981; margin-bottom: 16px; padding: 10px; border-radius: 8px; font-size: 0.85rem; align-items: center; gap: 8px;">
<i data-lucide="check-circle" style="color: #10b981; width: 16px; height: 16px; flex-shrink: 0;"></i>
<span id="settings-status-text">Credentials saved successfully.</span>
</div>
<!-- SECTION 1: AI API CREDENTIALS -->
<div class="settings-section" style="margin-bottom: 24px;">
<div class="settings-section-title" style="display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 1.05rem; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; margin-bottom: 12px; color: var(--text-main);">
<i data-lucide="brain-circuit" style="color: var(--primary); width: 18px; height: 18px;"></i>
<span>AI API Credentials</span>
</div>
<p style="font-size: 0.85rem; line-height: 1.4; color: var(--text-muted); margin-bottom: 16px;">
Configure your system-wide AI credentials to enable physical recipe photo scanning.
</p>
<form id="settings-api-form" style="margin-bottom: 8px;">
<div class="form-group mb-4">
<label for="settings-gemini-key" style="font-size: 0.85rem; margin-bottom: 6px; display: block; font-weight: 500;">Google Gemini API Key</label>
<div class="input-wrapper" style="position: relative; display: flex; align-items: center;">
<input type="password" id="settings-gemini-key" placeholder="Enter your Gemini API key..." autocomplete="off" style="width: 100%; padding-right: 40px; height: 40px; border-radius: var(--border-radius-md); border: 1px solid var(--border-color); background: rgba(0,0,0,0.2); color: var(--text-main); padding-left: 12px;">
<button type="button" id="btn-toggle-gemini-key" style="position: absolute; right: 10px; background: none; border: none; color: var(--text-muted); cursor: pointer;" title="Toggle Visibility">
<i data-lucide="eye" style="width: 16px; height: 16px;"></i>
</button>
</div>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%; height: 40px;">
<i data-lucide="save"></i> <span>Save Credentials</span>
</button>
</form>
</div>
<!-- SECTION 2: CULINARY OPTIONS (COMING SOON) -->
<div class="settings-section" style="opacity: 0.55; margin-bottom: 24px;">
<div class="settings-section-title" style="display: flex; align-items: center; justify-content: space-between; font-weight: 600; font-size: 1.05rem; border-bottom: 1px solid var(--border-color); padding-bottom: 8px; margin-bottom: 12px; color: var(--text-main);">
<div style="display: flex; align-items: center; gap: 8px;">
<i data-lucide="cooking-pot" style="color: var(--text-muted); width: 18px; height: 18px;"></i>
<span>Cookbook Options</span>
</div>
<span style="font-size: 0.65rem; background: var(--border-color); padding: 2px 6px; border-radius: 4px; color: var(--text-muted); text-transform: uppercase; font-weight: 700; font-family: var(--font-heading);">Coming Soon</span>
</div>
<p style="font-size: 0.85rem; line-height: 1.4; color: var(--text-muted); margin-bottom: 12px;">
Set default preferences for unit systems, portions, and timer configurations.
</p>
<div style="display: flex; flex-direction: column; gap: 8px;">
<label class="checkbox-container" style="cursor: not-allowed; display: flex; align-items: center; gap: 6px;">
<input type="checkbox" disabled style="cursor: not-allowed;">
<span class="checkbox-label" style="font-size: 0.85rem; color: var(--text-muted);">Default to Metric Units (grams, milliliters)</span>
</label>
<label class="checkbox-container" style="cursor: not-allowed; display: flex; align-items: center; gap: 6px;">
<input type="checkbox" disabled style="cursor: not-allowed;">
<span class="checkbox-label" style="font-size: 0.85rem; color: var(--text-muted);">Sound notifications on timer completion</span>
</label>
</div>
</div>
<div style="display: flex; justify-content: flex-end;">
<button class="btn btn-outline" onclick="closeModal('settings-modal')" style="width: 100%;">
<span>Close Settings</span>
</button>
</div>
</div>
</div>
</div>
<script> <script>
// Initialize Lucide Icons initially // Initialize Lucide Icons initially
window.addEventListener('DOMContentLoaded', () => { window.addEventListener('DOMContentLoaded', () => {

BIN
public/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 KiB

View file

@ -0,0 +1,3 @@
{
"geminiApiKey": "PASTE_YOUR_GEMINI_API_KEY_HERE"
}

View file

@ -1,4 +1,4 @@
/* GourmetVault CSS - Premium Styling System */ /* ForkFolio CSS - Premium Styling System */
/* Design Tokens & Root Custom Variables */ /* Design Tokens & Root Custom Variables */
:root { :root {
@ -104,6 +104,13 @@ h1, h2, h3, h4, h5, h6 {
white-space: nowrap; white-space: nowrap;
} }
.btn i,
.btn svg {
width: 18px;
height: 18px;
flex-shrink: 0;
}
.btn-primary { .btn-primary {
background-color: var(--primary); background-color: var(--primary);
color: var(--text-white); color: var(--text-white);
@ -159,6 +166,14 @@ h1, h2, h3, h4, h5, h6 {
backdrop-filter: var(--glass-blur); backdrop-filter: var(--glass-blur);
} }
.btn-icon-round i,
.btn-icon-round svg {
width: 20px;
height: 20px;
display: block;
flex-shrink: 0;
}
.btn-icon-round:hover { .btn-icon-round:hover {
transform: scale(1.08); transform: scale(1.08);
background-color: var(--border-color); background-color: var(--border-color);
@ -599,6 +614,15 @@ h1, h2, h3, h4, h5, h6 {
padding: 20px; padding: 20px;
} }
/* Modal Stacking Z-Index Hierarchy */
#detail-modal { z-index: 1000; }
#save-modal { z-index: 1100; }
#admin-create-user-modal { z-index: 1150; }
#admin-delete-user-modal { z-index: 1160; }
#cooking-mode-modal { z-index: 1200; }
#loading-overlay { z-index: 1300; }
#auth-modal { z-index: 1400; }
.modal-overlay.active { .modal-overlay.active {
opacity: 1; opacity: 1;
pointer-events: all; pointer-events: all;
@ -622,6 +646,7 @@ h1, h2, h3, h4, h5, h6 {
transform: translateY(0) scale(1); transform: translateY(0) scale(1);
} }
.max-width-xs { max-width: 420px; }
.max-width-lg { max-width: 850px; } .max-width-lg { max-width: 850px; }
.max-width-xl { max-width: 1100px; } .max-width-xl { max-width: 1100px; }
.no-padding { padding: 0; } .no-padding { padding: 0; }
@ -694,6 +719,7 @@ h1, h2, h3, h4, h5, h6 {
.form-group input[type="text"], .form-group input[type="text"],
.form-group input[type="url"], .form-group input[type="url"],
.form-group input[type="password"],
.form-group textarea { .form-group textarea {
width: 100%; width: 100%;
padding: 12px 14px; padding: 12px 14px;
@ -708,6 +734,7 @@ h1, h2, h3, h4, h5, h6 {
.form-group input[type="text"]:focus, .form-group input[type="text"]:focus,
.form-group input[type="url"]:focus, .form-group input[type="url"]:focus,
.form-group input[type="password"]:focus,
.form-group textarea:focus { .form-group textarea:focus {
border-color: var(--primary); border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-glow); box-shadow: 0 0 0 3px var(--primary-glow);
@ -1445,3 +1472,415 @@ h1, h2, h3, h4, h5, h6 {
.spinning-icon { .spinning-icon {
animation: spin 2s linear infinite; animation: spin 2s linear infinite;
} }
/* User Badge & Logout in Header */
.user-badge-container {
display: flex;
align-items: center;
gap: 8px;
background-color: var(--glass-bg);
border: 1px solid var(--glass-border);
padding: 4px 6px 4px 12px;
border-radius: var(--border-radius-full);
backdrop-filter: var(--glass-blur);
}
.user-display {
display: flex;
align-items: center;
gap: 6px;
font-family: var(--font-heading);
font-weight: 600;
font-size: 0.9rem;
color: var(--primary);
}
.user-display i {
width: 14px;
height: 14px;
opacity: 0.8;
}
#btn-logout {
width: 32px;
height: 32px;
background-color: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.2);
color: var(--danger);
}
#btn-logout:hover {
background-color: var(--danger);
color: var(--text-white);
border-color: var(--danger);
}
/* Dashboard Tabs Navigation */
.dashboard-tabs {
display: flex;
gap: 8px;
background-color: var(--glass-bg);
border: 1px solid var(--glass-border);
padding: 6px;
border-radius: var(--border-radius-md);
backdrop-filter: var(--glass-blur);
}
.dashboard-tab-btn {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 20px;
border: none;
background: transparent;
color: var(--text-muted);
font-family: var(--font-heading);
font-weight: 600;
font-size: 0.95rem;
cursor: pointer;
border-radius: var(--border-radius-sm);
transition: all var(--transition-fast);
}
.dashboard-tab-btn i {
width: 16px;
height: 16px;
}
.dashboard-tab-btn:hover {
color: var(--text-main);
background-color: rgba(255, 255, 255, 0.05);
}
.dashboard-tab-btn.active {
color: var(--text-white);
background: linear-gradient(135deg, var(--primary), var(--secondary));
box-shadow: 0 4px 12px var(--primary-glow);
}
/* Auth Modal Overlay & Cards */
.auth-modal-box {
background: var(--bg-card);
backdrop-filter: var(--glass-blur);
border: 1px solid var(--glass-border);
box-shadow: var(--shadow-lg);
border-radius: var(--border-radius-lg);
}
.auth-logo {
text-align: center;
width: 100%;
}
.auth-logo .logo-icon {
width: 52px;
height: 52px;
font-size: 1.6rem;
margin: 0 auto 12px auto;
border-radius: var(--border-radius-md);
box-shadow: 0 6px 20px var(--primary-glow);
}
.auth-logo h2 {
font-family: var(--font-heading);
font-size: 1.6rem;
font-weight: 800;
color: var(--text-main);
margin-bottom: 4px;
}
.auth-logo h2 span {
color: var(--primary);
}
.auth-logo p {
font-size: 0.85rem;
color: var(--text-muted);
}
.auth-tabs {
display: flex;
background-color: var(--bg-app);
border: 1px solid var(--border-color);
padding: 4px;
border-radius: var(--border-radius-md);
margin-bottom: 24px;
}
.auth-tab-btn {
flex: 1;
padding: 10px;
border: none;
background: transparent;
color: var(--text-muted);
font-family: var(--font-heading);
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
border-radius: var(--border-radius-sm);
transition: all var(--transition-fast);
}
.auth-tab-btn.active {
background-color: var(--bg-card);
color: var(--primary);
box-shadow: var(--shadow-sm);
}
.auth-error-alert {
background-color: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.2);
color: var(--danger);
border-radius: var(--border-radius-md);
padding: 12px 16px;
margin-bottom: 20px;
font-size: 0.88rem;
display: flex;
align-items: center;
gap: 10px;
animation: slideIn var(--transition-fast);
}
.auth-error-alert i {
width: 16px;
height: 16px;
flex-shrink: 0;
}
.btn-full-width {
width: 100%;
padding: 12px;
font-size: 1rem;
}
/* Custom Checkbox (Public/Private Share Toggle) */
.checkbox-container {
display: inline-flex;
align-items: center;
cursor: pointer;
user-select: none;
gap: 10px;
}
.checkbox-container input {
display: none;
}
.checkbox-label {
font-size: 0.95rem;
font-weight: 600;
color: var(--text-main);
display: flex;
align-items: center;
gap: 6px;
}
.checkbox-container input + .checkbox-label::before {
content: '';
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid var(--border-color);
border-radius: 6px;
background-color: var(--bg-app);
transition: all var(--transition-fast);
flex-shrink: 0;
}
.checkbox-container input:checked + .checkbox-label::before {
background-color: var(--primary);
border-color: var(--primary);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");
background-size: 12px;
background-position: center;
background-repeat: no-repeat;
}
.checkbox-container:hover input + .checkbox-label::before {
border-color: var(--primary);
}
/* Card Creator Badge & Community Feeds */
.recipe-card-creator {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 0.75rem;
font-weight: 600;
color: var(--text-muted);
background-color: var(--border-color);
padding: 4px 8px;
border-radius: var(--border-radius-sm);
margin-top: 8px;
max-width: fit-content;
}
.recipe-card-creator i {
width: 12px;
height: 12px;
}
/* Glassmorphic border utility classes */
.border-none { border: none !important; }
.pb-0 { padding-bottom: 0 !important; }
.pt-0 { padding-top: 0 !important; }
.mb-3 { margin-bottom: 12px !important; }
.mb-4 { margin-bottom: 16px !important; }
.mb-6 { margin-bottom: 24px !important; }
/* User Admin management page styles */
.admin-panel-container {
background-color: var(--bg-card);
border-radius: var(--border-radius-lg);
border: 1px solid var(--border-color);
padding: 30px;
box-shadow: var(--shadow-sm);
margin-top: 10px;
animation: fadeIn var(--transition-normal);
}
.table-responsive {
width: 100%;
overflow-x: auto;
border-radius: var(--border-radius-md);
border: 1px solid var(--border-color);
}
.admin-users-table {
width: 100%;
border-collapse: collapse;
text-align: left;
font-size: 0.95rem;
}
.admin-users-table th {
background-color: var(--bg-app);
color: var(--text-muted);
font-family: var(--font-heading);
font-weight: 600;
padding: 14px 20px;
border-bottom: 1px solid var(--border-color);
font-size: 0.88rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.admin-users-table td {
padding: 16px 20px;
border-bottom: 1px solid var(--border-color);
color: var(--text-main);
vertical-align: middle;
}
.admin-users-table tr:last-child td {
border-bottom: none;
}
.admin-users-table tr:hover td {
background-color: rgba(255, 255, 255, 0.02);
}
.admin-role-badge {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 0.75rem;
font-weight: 700;
padding: 4px 8px;
border-radius: 6px;
text-transform: uppercase;
}
.admin-role-badge.admin {
background-color: rgba(245, 158, 11, 0.15);
border: 1px solid rgba(245, 158, 11, 0.3);
color: #f59e0b;
}
.admin-role-badge.chef {
background-color: rgba(16, 185, 129, 0.15);
border: 1px solid rgba(16, 185, 129, 0.3);
color: #10b981;
}
.btn-danger {
background-color: var(--danger);
color: var(--text-white);
box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
}
.btn-danger:hover {
background-color: var(--danger-hover);
transform: translateY(-1px);
box-shadow: 0 6px 18px rgba(239, 68, 68, 0.3);
}
.btn-danger:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
/* Original recipe source URL tag styling */
.recipe-meta-tags a#tag-source {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 0.9rem;
color: var(--text-muted);
background-color: var(--bg-app);
padding: 6px 14px;
border-radius: var(--border-radius-full);
border: 1px solid var(--border-color);
text-decoration: none;
transition: all var(--transition-fast);
cursor: pointer;
}
.recipe-meta-tags a#tag-source i {
width: 16px;
height: 16px;
color: var(--primary);
}
.recipe-meta-tags a#tag-source .val {
font-weight: 600;
color: var(--text-main);
}
.recipe-meta-tags a#tag-source:hover {
border-color: var(--primary);
color: var(--primary);
background-color: var(--primary-glow);
}
.recipe-meta-tags a#tag-source:hover .val {
color: var(--primary);
}
.admin-role-badge.manager {
background-color: rgba(99, 102, 241, 0.15);
border: 1px solid rgba(99, 102, 241, 0.3);
color: #6366f1;
}
/* AI Settings Status Badges */
.status-badge {
display: inline-flex;
align-items: center;
gap: 4px;
font-family: var(--font-heading);
letter-spacing: 0.02em;
text-transform: uppercase;
}
.status-badge.configured {
background-color: rgba(16, 185, 129, 0.15);
border: 1px dashed rgba(16, 185, 129, 0.35);
color: #10b981;
}
.status-badge.not-configured {
background-color: rgba(239, 68, 68, 0.15);
border: 1px dashed rgba(239, 68, 68, 0.35);
color: #ef4444;
}

639
server.js
View file

@ -4,6 +4,12 @@ const cheerio = require('cheerio');
const cors = require('cors'); const cors = require('cors');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const crypto = require('crypto');
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
// Enable stealth mode to bypass bot detection (Cloudflare, Akamai, etc.)
puppeteer.use(StealthPlugin());
const app = express(); const app = express();
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
@ -11,6 +17,7 @@ const PORT = process.env.PORT || 3000;
// Setup directories for persistence // Setup directories for persistence
const DATA_DIR = path.join(__dirname, 'data'); const DATA_DIR = path.join(__dirname, 'data');
const DATA_FILE = path.join(DATA_DIR, 'recipes.json'); const DATA_FILE = path.join(DATA_DIR, 'recipes.json');
const USERS_FILE = path.join(DATA_DIR, 'users.json');
if (!fs.existsSync(DATA_DIR)) { if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true }); fs.mkdirSync(DATA_DIR, { recursive: true });
@ -18,9 +25,43 @@ if (!fs.existsSync(DATA_DIR)) {
if (!fs.existsSync(DATA_FILE)) { if (!fs.existsSync(DATA_FILE)) {
fs.writeFileSync(DATA_FILE, JSON.stringify([], null, 2)); fs.writeFileSync(DATA_FILE, JSON.stringify([], null, 2));
} }
if (!fs.existsSync(USERS_FILE)) {
fs.writeFileSync(USERS_FILE, JSON.stringify([], null, 2));
}
// Ensure default admin user exists
try {
const usersData = fs.readFileSync(USERS_FILE, 'utf8');
const existingUsers = JSON.parse(usersData);
const hasAdmin = existingUsers.some(u => u.isAdmin === true);
if (!hasAdmin) {
const salt = crypto.randomBytes(16).toString('hex');
const passwordHash = crypto.pbkdf2Sync('admin123', salt, 1000, 64, 'sha512').toString('hex');
existingUsers.push({
id: 'u_admin',
username: 'admin',
salt,
passwordHash,
isAdmin: true,
isRecipeManager: true,
createdAt: new Date().toISOString()
});
fs.writeFileSync(USERS_FILE, JSON.stringify(existingUsers, null, 2), 'utf8');
console.log('--- ForkFolio Admin Initialized ---');
console.log('Default Admin Username: admin');
console.log('Default Admin Password: admin123');
console.log('--------------------------------------');
}
} catch (e) {
console.error('Failed to initialize default admin user:', e);
}
// In-memory sessions storage (token -> { id, username })
const activeSessions = new Map();
app.use(cors()); app.use(cors());
app.use(express.json()); app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
// Helper: Parse ISO 8601 Durations (e.g. PT1H30M to "1 hr 30 mins") // Helper: Parse ISO 8601 Durations (e.g. PT1H30M to "1 hr 30 mins")
@ -87,11 +128,83 @@ function normalizeImages(imageObj) {
return []; return [];
} }
// Helper: Retrieve saved recipes // Helper: Retrieve saved users
function readUsers() {
try {
const data = fs.readFileSync(USERS_FILE, 'utf8');
let users = JSON.parse(data);
let migrated = false;
users = users.map(u => {
if (u.isAdmin && !u.isRecipeManager) {
u.isRecipeManager = true;
migrated = true;
}
return u;
});
if (migrated) {
writeUsers(users);
}
return users;
} catch (e) {
console.error('Error reading users database:', e);
return [];
}
}
// Helper: Save users to storage
function writeUsers(users) {
try {
fs.writeFileSync(USERS_FILE, JSON.stringify(users, null, 2), 'utf8');
return true;
} catch (e) {
console.error('Error writing users database:', e);
return false;
}
}
// Password Hashing and Salt helpers
function generateSalt() {
return crypto.randomBytes(16).toString('hex');
}
function hashPassword(password, salt) {
return crypto.pbkdf2Sync(password, salt, 1000, 64, 'sha512').toString('hex');
}
// Middleware: Authenticate Session Token
function requireAuth(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Authorization required. Please log in.' });
}
const token = authHeader.substring(7);
const session = activeSessions.get(token);
if (!session) {
return res.status(401).json({ error: 'Session expired. Please log in again.' });
}
req.user = session;
next();
}
// Helper: Retrieve saved recipes with automatic backward-compatibility migration
function readRecipes() { function readRecipes() {
try { try {
const data = fs.readFileSync(DATA_FILE, 'utf8'); const data = fs.readFileSync(DATA_FILE, 'utf8');
return JSON.parse(data); let recipes = JSON.parse(data);
let migrated = false;
recipes = recipes.map(r => {
if (!r.userId) {
r.userId = 'system_admin';
r.createdBy = 'gourmet_system';
r.isPublic = true;
migrated = true;
}
return r;
});
if (migrated) {
writeRecipes(recipes);
}
return recipes;
} catch (e) { } catch (e) {
console.error('Error reading recipes database:', e); console.error('Error reading recipes database:', e);
return []; return [];
@ -109,17 +222,287 @@ function writeRecipes(recipes) {
} }
} }
// API: List saved recipes // Auth API: User Registration (Requires Admin session)
app.get('/api/recipes', (req, res) => { app.post('/api/auth/register', requireAuth, (req, res) => {
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Access denied. Administrator privileges required.' });
}
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password are required.' });
}
const cleanUsername = username.trim().toLowerCase();
if (!/^[a-z0-9_]{3,20}$/.test(cleanUsername)) {
return res.status(400).json({ error: 'Username must be 3-20 characters long and contain only alphanumeric characters or underscores.' });
}
if (password.length < 6) {
return res.status(400).json({ error: 'Password must be at least 6 characters long.' });
}
const users = readUsers();
const existingUser = users.find(u => u.username.toLowerCase() === cleanUsername);
if (existingUser) {
return res.status(400).json({ error: 'Username is already taken.' });
}
const salt = generateSalt();
const passwordHash = hashPassword(password, salt);
const newUser = {
id: 'u_' + Date.now().toString(36) + Math.random().toString(36).substr(2, 5),
username: cleanUsername,
salt,
passwordHash,
isAdmin: false,
isRecipeManager: false,
createdAt: new Date().toISOString()
};
users.push(newUser);
writeUsers(users);
res.status(201).json({
user: {
id: newUser.id,
username: newUser.username,
isAdmin: false,
isRecipeManager: false
}
});
});
// Auth API: User Login
app.post('/api/auth/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password are required.' });
}
const cleanUsername = username.trim().toLowerCase();
const users = readUsers();
const user = users.find(u => u.username.toLowerCase() === cleanUsername);
if (!user) {
return res.status(401).json({ error: 'Invalid username or password.' });
}
const hash = hashPassword(password, user.salt);
if (hash !== user.passwordHash) {
return res.status(401).json({ error: 'Invalid username or password.' });
}
const token = crypto.randomBytes(32).toString('hex');
activeSessions.set(token, {
id: user.id,
username: user.username,
isAdmin: user.isAdmin || false,
isRecipeManager: user.isRecipeManager || false
});
res.json({
token,
user: {
id: user.id,
username: user.username,
isAdmin: user.isAdmin || false,
isRecipeManager: user.isRecipeManager || false
}
});
});
// Admin API: List all users (Requires Admin session)
app.get('/api/admin/users', requireAuth, (req, res) => {
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Access denied. Administrator privileges required.' });
}
const users = readUsers().map(u => ({
id: u.id,
username: u.username,
isAdmin: u.isAdmin || false,
isRecipeManager: u.isRecipeManager || false,
createdAt: u.createdAt
}));
res.json(users);
});
// Admin API: Delete user (Requires Admin session)
app.delete('/api/admin/users/:id', requireAuth, (req, res) => {
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Access denied. Administrator privileges required.' });
}
if (req.params.id === req.user.id) {
return res.status(400).json({ error: 'You cannot delete your own administrative account.' });
}
const users = readUsers();
const userIndex = users.findIndex(u => u.id === req.params.id);
if (userIndex === -1) {
return res.status(404).json({ error: 'User not found.' });
}
const deletedUser = users[userIndex];
const preserveRecipes = req.body.preserveRecipes === true;
// Handle recipe dependencies
const recipes = readRecipes(); const recipes = readRecipes();
res.json(recipes); let updatedRecipes;
if (preserveRecipes) {
// Keep in Community Vault (reassign to system_admin, set as public)
updatedRecipes = recipes.map(r => {
if (r.userId === deletedUser.id) {
r.userId = 'system_admin';
r.createdBy = `${deletedUser.username} (former)`;
r.isPublic = true;
}
return r;
});
} else {
// Purge entirely
updatedRecipes = recipes.filter(r => r.userId !== deletedUser.id);
}
writeRecipes(updatedRecipes);
// Remove user profile
users.splice(userIndex, 1);
writeUsers(users);
// Invalidate any active session tokens of deleted user
for (const [token, session] of activeSessions.entries()) {
if (session.id === deletedUser.id) {
activeSessions.delete(token);
}
}
res.json({ success: true });
});
// Admin API: Change user role (Requires Admin session)
app.put('/api/admin/users/:id/role', requireAuth, (req, res) => {
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Access denied. Administrator privileges required.' });
}
if (req.params.id === req.user.id) {
return res.status(400).json({ error: 'You cannot change your own administrator role privileges.' });
}
const { isAdmin } = req.body;
if (typeof isAdmin !== 'boolean') {
return res.status(400).json({ error: 'isAdmin property must be a boolean.' });
}
const users = readUsers();
const userIndex = users.findIndex(u => u.id === req.params.id);
if (userIndex === -1) {
return res.status(404).json({ error: 'User not found.' });
}
users[userIndex].isAdmin = isAdmin;
writeUsers(users);
// Update active sessions to reflect the privilege change immediately
for (const [token, session] of activeSessions.entries()) {
if (session.id === users[userIndex].id) {
session.isAdmin = isAdmin;
activeSessions.set(token, session);
}
}
res.json({ success: true, user: { id: users[userIndex].id, username: users[userIndex].username, isAdmin } });
});
// Admin API: Toggle recipe manager role (Requires Admin session)
app.put('/api/admin/users/:id/recipe-manager', requireAuth, (req, res) => {
if (!req.user.isAdmin) {
return res.status(403).json({ error: 'Access denied. Administrator privileges required.' });
}
const { isRecipeManager } = req.body;
if (typeof isRecipeManager !== 'boolean') {
return res.status(400).json({ error: 'isRecipeManager property must be a boolean.' });
}
const users = readUsers();
const userIndex = users.findIndex(u => u.id === req.params.id);
if (userIndex === -1) {
return res.status(404).json({ error: 'User not found.' });
}
users[userIndex].isRecipeManager = isRecipeManager;
writeUsers(users);
// Update active sessions to reflect the privilege change immediately
for (const [token, session] of activeSessions.entries()) {
if (session.id === users[userIndex].id) {
session.isRecipeManager = isRecipeManager;
activeSessions.set(token, session);
}
}
res.json({ success: true, user: { id: users[userIndex].id, username: users[userIndex].username, isRecipeManager } });
});
// API: List authenticated user's private recipes
app.get('/api/recipes', requireAuth, (req, res) => {
const recipes = readRecipes();
const userRecipes = recipes.filter(r => r.userId === req.user.id);
res.json(userRecipes);
});
// API: List all public recipes for Community Vault
app.get('/api/recipes/public', requireAuth, (req, res) => {
const recipes = readRecipes();
const publicRecipes = recipes.filter(r => r.isPublic !== false);
res.json(publicRecipes);
});
// API: Clone a public recipe to user's private collection
app.post('/api/recipes/clone/:id', requireAuth, (req, res) => {
const recipes = readRecipes();
const sourceRecipe = recipes.find(r => r.id === req.params.id);
if (!sourceRecipe) {
return res.status(404).json({ error: 'Recipe not found' });
}
if (sourceRecipe.isPublic === false) {
return res.status(403).json({ error: 'This recipe is private and cannot be cloned.' });
}
const clonedRecipe = {
...sourceRecipe,
id: Date.now().toString(36) + Math.random().toString(36).substr(2, 5),
userId: req.user.id,
createdBy: req.user.username,
isPublic: false, // Default cloned copies to private so users can customize them privately
createdAt: new Date().toISOString(),
updatedAt: undefined
};
recipes.push(clonedRecipe);
writeRecipes(recipes);
res.status(201).json(clonedRecipe);
}); });
// API: Save new recipe // API: Save new recipe
app.post('/api/recipes', (req, res) => { app.post('/api/recipes', requireAuth, (req, res) => {
const recipes = readRecipes(); const recipes = readRecipes();
const newRecipe = { const newRecipe = {
id: Date.now().toString(36) + Math.random().toString(36).substr(2, 5), id: Date.now().toString(36) + Math.random().toString(36).substr(2, 5),
userId: req.user.id,
createdBy: req.user.username,
isPublic: req.body.isPublic !== false,
title: req.body.title || 'Untitled Recipe', title: req.body.title || 'Untitled Recipe',
description: req.body.description || '', description: req.body.description || '',
ingredients: Array.isArray(req.body.ingredients) ? req.body.ingredients : [], ingredients: Array.isArray(req.body.ingredients) ? req.body.ingredients : [],
@ -140,7 +523,7 @@ app.post('/api/recipes', (req, res) => {
}); });
// API: Update recipe // API: Update recipe
app.put('/api/recipes/:id', (req, res) => { app.put('/api/recipes/:id', requireAuth, (req, res) => {
const recipes = readRecipes(); const recipes = readRecipes();
const index = recipes.findIndex(r => r.id === req.params.id); const index = recipes.findIndex(r => r.id === req.params.id);
@ -148,6 +531,10 @@ app.put('/api/recipes/:id', (req, res) => {
return res.status(404).json({ error: 'Recipe not found' }); return res.status(404).json({ error: 'Recipe not found' });
} }
if (recipes[index].userId !== req.user.id && !req.user.isRecipeManager && !req.user.isAdmin) {
return res.status(403).json({ error: 'You do not have permission to modify this recipe.' });
}
const updatedRecipe = { const updatedRecipe = {
...recipes[index], ...recipes[index],
title: req.body.title || recipes[index].title, title: req.body.title || recipes[index].title,
@ -161,6 +548,7 @@ app.put('/api/recipes/:id', (req, res) => {
image: req.body.image !== undefined ? req.body.image : recipes[index].image, image: req.body.image !== undefined ? req.body.image : recipes[index].image,
images: Array.isArray(req.body.images) ? req.body.images : recipes[index].images, images: Array.isArray(req.body.images) ? req.body.images : recipes[index].images,
sourceUrl: req.body.sourceUrl !== undefined ? req.body.sourceUrl : recipes[index].sourceUrl, sourceUrl: req.body.sourceUrl !== undefined ? req.body.sourceUrl : recipes[index].sourceUrl,
isPublic: req.body.isPublic !== undefined ? req.body.isPublic : recipes[index].isPublic,
updatedAt: new Date().toISOString() updatedAt: new Date().toISOString()
}; };
@ -170,49 +558,28 @@ app.put('/api/recipes/:id', (req, res) => {
}); });
// API: Delete recipe // API: Delete recipe
app.delete('/api/recipes/:id', (req, res) => { app.delete('/api/recipes/:id', requireAuth, (req, res) => {
let recipes = readRecipes(); let recipes = readRecipes();
const filtered = recipes.filter(r => r.id !== req.params.id); const index = recipes.findIndex(r => r.id === req.params.id);
if (recipes.length === filtered.length) { if (index === -1) {
return res.status(404).json({ error: 'Recipe not found' }); return res.status(404).json({ error: 'Recipe not found' });
} }
if (recipes[index].userId !== req.user.id && !req.user.isRecipeManager && !req.user.isAdmin) {
return res.status(403).json({ error: 'You do not have permission to delete this recipe.' });
}
const filtered = recipes.filter(r => r.id !== req.params.id);
writeRecipes(filtered); writeRecipes(filtered);
res.json({ success: true }); res.json({ success: true });
}); });
// API: Scrape Recipe from Link // Helper: Parse recipe data from raw HTML string
app.post('/api/scrape', async (req, res) => { function parseRecipeFromHtml(html, url) {
const { url } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
try {
const response = await axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Upgrade-Insecure-Requests': '1'
},
timeout: 10000
});
const html = response.data;
const $ = cheerio.load(html); const $ = cheerio.load(html);
// Initial search: Extract JSON-LD structures // Extract JSON-LD structures
let schemaRecipe = null; let schemaRecipe = null;
$('script[type="application/ld+json"]').each((i, el) => { $('script[type="application/ld+json"]').each((i, el) => {
try { try {
@ -267,7 +634,6 @@ app.post('/api/scrape', async (req, res) => {
$('img').each((i, el) => { $('img').each((i, el) => {
const src = $(el).attr('src') || $(el).attr('data-src') || $(el).attr('data-lazy-src'); const src = $(el).attr('src') || $(el).attr('data-src') || $(el).attr('data-lazy-src');
if (src && src.startsWith('http')) { if (src && src.startsWith('http')) {
// Skip tracking pixels, tiny graphics or profile avatars
const width = $(el).attr('width'); const width = $(el).attr('width');
const height = $(el).attr('height'); const height = $(el).attr('height');
const isSmall = (width && parseInt(width, 10) < 150) || (height && parseInt(height, 10) < 150); const isSmall = (width && parseInt(width, 10) < 150) || (height && parseInt(height, 10) < 150);
@ -284,19 +650,16 @@ app.post('/api/scrape', async (req, res) => {
recipeData.title = schemaRecipe.name || $('title').text().trim() || ''; recipeData.title = schemaRecipe.name || $('title').text().trim() || '';
recipeData.description = schemaRecipe.description || ''; recipeData.description = schemaRecipe.description || '';
// Servings
if (schemaRecipe.recipeYield) { if (schemaRecipe.recipeYield) {
recipeData.servings = Array.isArray(schemaRecipe.recipeYield) recipeData.servings = Array.isArray(schemaRecipe.recipeYield)
? schemaRecipe.recipeYield[0] ? schemaRecipe.recipeYield[0]
: schemaRecipe.recipeYield.toString(); : schemaRecipe.recipeYield.toString();
} }
// Times
recipeData.prepTime = parseISODuration(schemaRecipe.prepTime || ''); recipeData.prepTime = parseISODuration(schemaRecipe.prepTime || '');
recipeData.cookTime = parseISODuration(schemaRecipe.cookTime || ''); recipeData.cookTime = parseISODuration(schemaRecipe.cookTime || '');
recipeData.totalTime = parseISODuration(schemaRecipe.totalTime || ''); recipeData.totalTime = parseISODuration(schemaRecipe.totalTime || '');
// Ingredients (Support singular and plural, also support plain strings)
const rawIngredients = schemaRecipe.recipeIngredient || schemaRecipe.recipeIngredients || []; const rawIngredients = schemaRecipe.recipeIngredient || schemaRecipe.recipeIngredients || [];
if (typeof rawIngredients === 'string') { if (typeof rawIngredients === 'string') {
recipeData.ingredients = rawIngredients.split(/\r?\n/).map(i => i.trim()).filter(Boolean); recipeData.ingredients = rawIngredients.split(/\r?\n/).map(i => i.trim()).filter(Boolean);
@ -304,14 +667,12 @@ app.post('/api/scrape', async (req, res) => {
recipeData.ingredients = rawIngredients; recipeData.ingredients = rawIngredients;
} }
// Instructions (Support singular and plural)
recipeData.instructions = extractInstructions(schemaRecipe.recipeInstructions || schemaRecipe.recipeInstruction); recipeData.instructions = extractInstructions(schemaRecipe.recipeInstructions || schemaRecipe.recipeInstruction);
// Schema Image fallback
const schemaImages = normalizeImages(schemaRecipe.image); const schemaImages = normalizeImages(schemaRecipe.image);
schemaImages.forEach(img => { schemaImages.forEach(img => {
if (!extractedImages.includes(img)) { if (!extractedImages.includes(img)) {
extractedImages.unshift(img); // Prioritize JSON-LD schema images at the start extractedImages.unshift(img);
} }
}); });
} else { } else {
@ -422,7 +783,7 @@ app.post('/api/scrape', async (req, res) => {
next = next.next(); next = next.next();
limit++; limit++;
} }
if (recipeData.ingredients.length > 2) return false; // Break heading loop if (recipeData.ingredients.length > 2) return false;
} }
}); });
} }
@ -457,7 +818,7 @@ app.post('/api/scrape', async (req, res) => {
next = next.next(); next = next.next();
limit++; limit++;
} }
if (recipeData.instructions.length > 1) return false; // Break heading loop if (recipeData.instructions.length > 1) return false;
} }
}); });
} }
@ -465,7 +826,7 @@ app.post('/api/scrape', async (req, res) => {
// Heuristics Fallback: Blockquote / Multi-paragraph text classifier (for vintage/informal blogs) // Heuristics Fallback: Blockquote / Multi-paragraph text classifier (for vintage/informal blogs)
if (recipeData.ingredients.length === 0 && recipeData.instructions.length === 0) { if (recipeData.ingredients.length === 0 && recipeData.instructions.length === 0) {
const isStepText = (text) => { const isStepText = (text) => {
if (/^(?:step\s*)?\d+[\.\)\-]\s/i.test(text)) return true; if (/^(?:step\s*)?\d+[\.\\)\-]\s/i.test(text)) return true;
if (/^\d+\s+(?:mix|stir|combine|sift|bake|heat|preheat|fry|drain|serve|boil|chop|pour|place|add|cook|whisk|beat|divide|mould|brush|roll|repeat|prepare|cut)\b/i.test(text)) return true; if (/^\d+\s+(?:mix|stir|combine|sift|bake|heat|preheat|fry|drain|serve|boil|chop|pour|place|add|cook|whisk|beat|divide|mould|brush|roll|repeat|prepare|cut)\b/i.test(text)) return true;
if (/^(?:mix|stir|combine|sift|bake|heat|preheat|fry|drain|serve|boil|chop|pour|place|add|cook|whisk|beat|divide|mould|brush|roll|repeat|prepare|cut)\b/i.test(text) && text.length > 25) return true; if (/^(?:mix|stir|combine|sift|bake|heat|preheat|fry|drain|serve|boil|chop|pour|place|add|cook|whisk|beat|divide|mould|brush|roll|repeat|prepare|cut)\b/i.test(text) && text.length > 25) return true;
return false; return false;
@ -479,7 +840,6 @@ app.post('/api/scrape', async (req, res) => {
return false; return false;
}; };
// Prioritize containers: blockquote first (specific card), then entry-content, then article
let selectedContainer = null; let selectedContainer = null;
if ($('blockquote').length > 0) { if ($('blockquote').length > 0) {
selectedContainer = $('blockquote'); selectedContainer = $('blockquote');
@ -496,7 +856,6 @@ app.post('/api/scrape', async (req, res) => {
paragraphs.each((j, el) => { paragraphs.each((j, el) => {
const html = $(el).html() || ''; const html = $(el).html() || '';
if (html.includes('<br>')) { if (html.includes('<br>')) {
// Split by BR tags if it's a single block
const lines = html.split(/<br\s*\/?>/i) const lines = html.split(/<br\s*\/?>/i)
.map(l => cheerio.load(l).text().trim().replace(/\s+/g, ' ')) .map(l => cheerio.load(l).text().trim().replace(/\s+/g, ' '))
.filter(Boolean); .filter(Boolean);
@ -520,7 +879,7 @@ app.post('/api/scrape', async (req, res) => {
} }
} }
}); });
if (recipeData.ingredients.length > 1) return false; // Break container loop if (recipeData.ingredients.length > 1) return false;
} }
}); });
} }
@ -529,14 +888,184 @@ app.post('/api/scrape', async (req, res) => {
// Clean up lists // Clean up lists
recipeData.ingredients = recipeData.ingredients.map(i => i.trim()).filter(Boolean); recipeData.ingredients = recipeData.ingredients.map(i => i.trim()).filter(Boolean);
recipeData.instructions = recipeData.instructions.map(i => i.trim()).filter(Boolean); recipeData.instructions = recipeData.instructions.map(i => i.trim()).filter(Boolean);
recipeData.images = extractedImages.slice(0, 15); // Send top 15 images to UI for selection recipeData.images = extractedImages.slice(0, 15);
return recipeData;
}
// Helper: Detect if HTML response is a bot challenge page rather than real content
function isBotChallengePage(html) {
if (!html || typeof html !== 'string') return true;
const lowerHtml = html.toLowerCase();
// Cloudflare challenge signatures
if (lowerHtml.includes('cf-browser-verification') || lowerHtml.includes('cf_chl_opt')) return true;
if (lowerHtml.includes('checking your browser') && lowerHtml.includes('cloudflare')) return true;
// Akamai bot manager
if (lowerHtml.includes('akamai') && lowerHtml.includes('bot manager')) return true;
// Generic CAPTCHA / challenge
if (lowerHtml.includes('recaptcha') && !lowerHtml.includes('recipeingredient')) return true;
// Very short response with no recipe-related content
if (html.length < 500 && !lowerHtml.includes('recipe')) return true;
return false;
}
// Helper: Fetch HTML using Puppeteer with stealth (headless browser fallback)
async function fetchWithPuppeteer(url) {
console.log('[Puppeteer] Launching headless browser for:', url);
let browser = null;
try {
browser = await puppeteer.launch({
headless: 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--disable-gpu',
'--window-size=1920,1080'
]
});
const page = await browser.newPage();
// Set a realistic viewport and user agent
await page.setViewport({ width: 1920, height: 1080 });
await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
// Set extra headers to appear more like a real browser
await page.setExtraHTTPHeaders({
'Accept-Language': 'en-US,en;q=0.9',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8'
});
// Navigate and wait for the page to fully load (networkidle0 waits for all requests to finish)
await page.goto(url, {
waitUntil: 'networkidle0',
timeout: 30000
});
// Give JS-rendered content a moment to hydrate
await new Promise(resolve => setTimeout(resolve, 2000));
// Scroll down to trigger any lazy-loaded content
await page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight / 2);
});
await new Promise(resolve => setTimeout(resolve, 1000));
const html = await page.content();
console.log('[Puppeteer] Successfully retrieved', html.length, 'bytes of HTML');
return html;
} finally {
if (browser) {
await browser.close();
console.log('[Puppeteer] Browser closed');
}
}
}
// API: Load System Settings
app.get('/api/settings', requireAuth, (req, res) => {
const settingsFile = path.join(__dirname, 'data', 'settings.json');
try {
if (!fs.existsSync(settingsFile)) {
fs.writeFileSync(settingsFile, JSON.stringify({ geminiApiKey: '' }, null, 2));
}
const data = fs.readFileSync(settingsFile, 'utf8');
res.json(JSON.parse(data));
} catch (e) {
res.status(500).json({ error: 'Failed to read settings file' });
}
});
// API: Save System Settings
app.post('/api/settings', requireAuth, (req, res) => {
const settingsFile = path.join(__dirname, 'data', 'settings.json');
const { geminiApiKey } = req.body;
try {
const settings = { geminiApiKey: geminiApiKey || '' };
fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2), 'utf8');
res.json(settings);
} catch (e) {
res.status(500).json({ error: 'Failed to save settings file' });
}
});
// API: Scrape Recipe from Link
app.post('/api/scrape', requireAuth, async (req, res) => {
const { url } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
try {
let html = null;
let usedPuppeteer = false;
// Strategy 1: Fast axios fetch
try {
const response = await axios.get(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Upgrade-Insecure-Requests': '1'
},
timeout: 10000
});
html = response.data;
// Check if we got a bot challenge instead of real content
if (isBotChallengePage(html)) {
console.log('[Scraper] Axios response appears to be a bot challenge page, falling back to Puppeteer...');
html = null; // Force Puppeteer fallback
}
} catch (axiosError) {
const status = axiosError.response ? axiosError.response.status : 0;
if (status === 403 || status === 503 || status === 429) {
console.log(`[Scraper] Axios blocked with HTTP ${status}, falling back to Puppeteer...`);
// Will fall through to Puppeteer below
} else {
throw axiosError; // Re-throw non-blocking errors (DNS failures, timeouts, etc.)
}
}
// Strategy 2: Puppeteer with stealth (headless browser fallback)
if (!html) {
try {
html = await fetchWithPuppeteer(url);
usedPuppeteer = true;
} catch (puppeteerError) {
console.error('[Puppeteer] Fallback also failed:', puppeteerError.message);
return res.status(500).json({
error: 'This website could not be accessed. Both standard and browser-based scraping methods failed.',
details: puppeteerError.message,
isBlocked: true
});
}
}
// Parse the retrieved HTML into recipe data
const recipeData = parseRecipeFromHtml(html, url);
// Include metadata about which method succeeded
recipeData._scrapingMethod = usedPuppeteer ? 'puppeteer-stealth' : 'axios';
res.json(recipeData); res.json(recipeData);
} catch (error) { } catch (error) {
console.error('Error occurred while scraping URL:', error.message); console.error('Error occurred while scraping URL:', error.message);
const status = error.response ? error.response.status : 500; const status = error.response ? error.response.status : 500;
const message = error.response && error.response.status === 403 const message = error.response && error.response.status === 403
? 'This website is protected by Cloudflare bot protection and blocks automated access.' ? 'This website is protected and blocks automated access. The Puppeteer fallback was also unavailable.'
: error.message; : error.message;
res.status(status).json({ res.status(status).json({
error: message, error: message,