Skip to content

一分钟搭建影视站,支持Docker等部署方式

feat: implement password protection feature with environment variable injection

developer7833cd3059f6
diff --git a/Dockerfile b/Dockerfile
index e2d92cc..0dcba91 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -5,8 +5,18 @@ LABEL description="LibreTV - 免费在线视频搜索与观看平台"
# 复制应用文件
COPY . /usr/share/nginx/html
+# 添加执行权限并设置为入口点脚本
+COPY docker-entrypoint.sh /
+RUN chmod +x /docker-entrypoint.sh
+
# 暴露端口
EXPOSE 80
+# 设置入口点
+ENTRYPOINT ["/docker-entrypoint.sh"]
+
+# 启动nginx
+CMD ["nginx", "-g", "daemon off;"]
+
# 健康检查
HEALTHCHECK --interval=30s --timeout=3s CMD wget --quiet --tries=1 --spider http://localhost/ || exit 1
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..bffe837
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,16 @@
+version: '3'
+
+services:
+ libretv:
+ build:
+ context: .
+ dockerfile: Dockerfile
+ ports:
+ - "8080:80"
+ environment:
+ - PASSWORD=your_password_here # 设置密码保护,留空则不启用密码
+ # 可以添加其他环境变量
+ restart: unless-stopped
+ # 如果您想使用外部卷存储数据
+ # volumes:
+ # - ./data:/usr/share/nginx/html/data
\ No newline at end of file
diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh
new file mode 100644
index 0000000..227e18d
--- /dev/null
+++ b/docker-entrypoint.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+set -e
+
+# Function to replace environment variables in HTML files
+replace_env_vars() {
+ # Replace the password placeholder in all HTML files
+ find /usr/share/nginx/html -type f -name "*.html" -exec sed -i "s/window.__ENV__.PASSWORD = \"{{PASSWORD}}\";/window.__ENV__.PASSWORD = \"${PASSWORD:-}\";/g" {} \;
+
+ echo "Environment variables have been injected into HTML files."
+}
+
+# Replace environment variables in HTML files
+replace_env_vars
+
+# Execute the command provided as arguments
+exec "$@"
\ No newline at end of file
diff --git a/functions/_middleware.js b/functions/_middleware.js
new file mode 100644
index 0000000..8351aa7
--- /dev/null
+++ b/functions/_middleware.js
@@ -0,0 +1,31 @@
+// Cloudflare Pages Middleware to inject environment variables
+export async function onRequest(context) {
+ const { request, env, next } = context;
+
+ // Proceed to the next middleware or route handler
+ const response = await next();
+
+ // Check if the response is HTML
+ const contentType = response.headers.get("content-type") || "";
+
+ if (contentType.includes("text/html")) {
+ // Get the original HTML content
+ let html = await response.text();
+
+ // Replace the placeholder with actual environment variable value
+ // If PASSWORD is not set, replace with empty string
+ const password = env.PASSWORD || "";
+ html = html.replace('window.__ENV__.PASSWORD = "{{PASSWORD}}";',
+ `window.__ENV__.PASSWORD = "${password}";`);
+
+ // Create a new response with the modified HTML
+ return new Response(html, {
+ headers: response.headers,
+ status: response.status,
+ statusText: response.statusText,
+ });
+ }
+
+ // Return the original response for non-HTML content
+ return response;
+}
\ No newline at end of file
diff --git a/index.html b/index.html
index a7d097a..5add310 100644
--- a/index.html
+++ b/index.html
@@ -253,6 +253,23 @@
</div>
</div>
+ <!-- 密码验证弹窗 -->
+ <div id="passwordModal" class="fixed inset-0 bg-black/95 hidden items-center justify-center z-[65] transition-opacity duration-300">
+ <div class="bg-[#111] p-8 rounded-lg w-11/12 max-w-md border border-[#333] max-h-[90vh] flex flex-col">
+ <div class="flex justify-between items-center mb-6 flex-none">
+ <h2 class="text-2xl font-bold gradient-text">访问验证</h2>
+ </div>
+ <div class="mb-6">
+ <p class="text-gray-300 mb-4">请输入密码继续访问</p>
+ <input type="password" id="passwordInput" class="w-full bg-[#111] border border-[#333] text-white px-4 py-3 rounded-lg focus:outline-none focus:border-white transition-colors" placeholder="密码...">
+ <p id="passwordError" class="text-red-500 mt-2 hidden">密码错误,请重试</p>
+ </div>
+ <button id="passwordSubmitBtn" class="px-6 py-3 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 text-white font-semibold rounded-lg hover:shadow-lg transition-all duration-300">
+ 确认
+ </button>
+ </div>
+ </div>
+
<!-- 版权声明弹窗 -->
<div id="disclaimerModal" class="fixed inset-0 bg-black/90 hidden items-center justify-center z-[60]">
<div class="bg-[#111] p-8 rounded-lg border border-[#333] w-11/12 max-w-2xl max-h-[90vh] overflow-y-auto">
@@ -311,8 +328,19 @@
<script src="js/config.js"></script>
<script src="js/ui.js"></script>
<script src="js/api.js"></script>
+ <script src="js/password.js"></script>
<script src="js/app.js"></script>
+ <!-- 环境变量注入脚本 -->
+ <script>
+ // 创建全局环境变量对象
+ window.__ENV__ = window.__ENV__ || {};
+
+ // 注入服务器端环境变量 (将由服务器端替换)
+ // PASSWORD 变量将在这里被服务器端注入
+ window.__ENV__.PASSWORD = "{{PASSWORD}}";
+ </script>
+
<!-- 弹窗显示脚本 -->
<script>
// 在页面加载完成后检查用户是否首次访问
diff --git a/js/config.js b/js/config.js
index 024aa2c..aa14787 100644
--- a/js/config.js
+++ b/js/config.js
@@ -4,6 +4,12 @@ const PROXY_URL = '/proxy/'; // 适用于 Cloudflare, Netlify (带重写), Ve
const SEARCH_HISTORY_KEY = 'videoSearchHistory';
const MAX_HISTORY_ITEMS = 5;
+// 密码保护配置
+const PASSWORD_CONFIG = {
+ localStorageKey: 'passwordVerified', // 存储验证状态的键名
+ verificationTTL: 70 * 24 * 60 * 60 * 1000, // 验证有效期(70天)
+};
+
// 网站信息配置
const SITE_CONFIG = {
name: 'LibreTV',
diff --git a/js/password.js b/js/password.js
new file mode 100644
index 0000000..72f13ea
--- /dev/null
+++ b/js/password.js
@@ -0,0 +1,160 @@
+// 密码保护功能
+
+/**
+ * 检查是否设置了密码保护
+ * 通过读取页面上嵌入的环境变量来检查
+ */
+function isPasswordProtected() {
+ // 检查页面上嵌入的环境变量
+ const passwordRequired = window.__ENV__ && window.__ENV__.PASSWORD && window.__ENV__.PASSWORD.trim() !== '';
+ return passwordRequired;
+}
+
+/**
+ * 检查用户是否已通过密码验证
+ * 检查localStorage中的验证状态和时间戳是否有效
+ */
+function isPasswordVerified() {
+ try {
+ // 如果没有设置密码保护,则视为已验证
+ if (!isPasswordProtected()) {
+ return true;
+ }
+
+ const verificationData = JSON.parse(localStorage.getItem(PASSWORD_CONFIG.localStorageKey) || '{}');
+ const { verified, timestamp } = verificationData;
+
+ // 验证是否已验证且未过期
+ if (verified && timestamp) {
+ const now = Date.now();
+ const expiry = timestamp + PASSWORD_CONFIG.verificationTTL;
+ return now < expiry;
+ }
+
+ return false;
+ } catch (error) {
+ console.error('验证密码状态时出错:', error);
+ return false;
+ }
+}
+
+/**
+ * 验证用户输入的密码是否正确
+ */
+function verifyPassword(password) {
+ // 检查密码是否匹配环境变量中设置的密码
+ const correctPassword = window.__ENV__ && window.__ENV__.PASSWORD;
+ const isValid = password === correctPassword;
+
+ if (isValid) {
+ // 保存验证状态到localStorage
+ const verificationData = {
+ verified: true,
+ timestamp: Date.now()
+ };
+ localStorage.setItem(PASSWORD_CONFIG.localStorageKey, JSON.stringify(verificationData));
+ }
+
+ return isValid;
+}
+
+/**
+ * 显示密码验证弹窗
+ */
+function showPasswordModal() {
+ const passwordModal = document.getElementById('passwordModal');
+ if (passwordModal) {
+ passwordModal.style.display = 'flex';
+
+ // 确保输入框获取焦点
+ setTimeout(() => {
+ const passwordInput = document.getElementById('passwordInput');
+ if (passwordInput) {
+ passwordInput.focus();
+ }
+ }, 100);
+ }
+}
+
+/**
+ * 隐藏密码验证弹窗
+ */
+function hidePasswordModal() {
+ const passwordModal = document.getElementById('passwordModal');
+ if (passwordModal) {
+ passwordModal.style.display = 'none';
+ }
+}
+
+/**
+ * 显示密码错误信息
+ */
+function showPasswordError() {
+ const errorElement = document.getElementById('passwordError');
+ if (errorElement) {
+ errorElement.classList.remove('hidden');
+ }
+}
+
+/**
+ * 隐藏密码错误信息
+ */
+function hidePasswordError() {
+ const errorElement = document.getElementById('passwordError');
+ if (errorElement) {
+ errorElement.classList.add('hidden');
+ }
+}
+
+/**
+ * 处理密码提交事件
+ */
+function handlePasswordSubmit() {
+ const passwordInput = document.getElementById('passwordInput');
+ const password = passwordInput ? passwordInput.value.trim() : '';
+
+ if (verifyPassword(password)) {
+ hidePasswordError();
+ hidePasswordModal();
+ } else {
+ showPasswordError();
+ // 清空密码输入框
+ if (passwordInput) {
+ passwordInput.value = '';
+ passwordInput.focus();
+ }
+ }
+}
+
+/**
+ * 初始化密码验证系统
+ */
+function initPasswordProtection() {
+ if (!isPasswordProtected()) {
+ return; // 如果未设置密码保护,则不进行任何操作
+ }
+
+ // 如果未验证密码,则显示密码验证弹窗
+ if (!isPasswordVerified()) {
+ showPasswordModal();
+
+ // 设置密码提交按钮事件监听
+ const submitButton = document.getElementById('passwordSubmitBtn');
+ if (submitButton) {
+ submitButton.addEventListener('click', handlePasswordSubmit);
+ }
+
+ // 设置密码输入框回车键监听
+ const passwordInput = document.getElementById('passwordInput');
+ if (passwordInput) {
+ passwordInput.addEventListener('keypress', function(e) {
+ if (e.key === 'Enter') {
+ handlePasswordSubmit();
+ }
+ });
+ }
+ }
+}
+
+// 在页面加载完成后初始化密码保护
+document.addEventListener('DOMContentLoaded', initPasswordProtection);
\ No newline at end of file
diff --git a/middleware.js b/middleware.js
new file mode 100644
index 0000000..6020f3f
--- /dev/null
+++ b/middleware.js
@@ -0,0 +1,43 @@
+// Vercel Middleware to inject environment variables
+import { NextResponse } from 'next/server';
+
+export default function middleware(request) {
+ // Get the original response
+ const response = NextResponse.next();
+
+ // Modify this to intercept HTML responses only
+ // This is a simplified example - in production you'd want more robust content-type checking
+ if (request.nextUrl.pathname.endsWith('.html') || request.nextUrl.pathname.endsWith('/')) {
+ response.then(async (res) => {
+ const contentType = res.headers.get('content-type');
+
+ if (contentType && contentType.includes('text/html')) {
+ // Get the HTML content
+ const originalHtml = await res.text();
+
+ // Replace the placeholder with actual environment variable
+ // If PASSWORD is not set, replace with empty string
+ const password = process.env.PASSWORD || '';
+ const modifiedHtml = originalHtml.replace(
+ 'window.__ENV__.PASSWORD = "{{PASSWORD}}";',
+ `window.__ENV__.PASSWORD = "${password}";`
+ );
+
+ // Create a new response with the modified HTML
+ return new Response(modifiedHtml, {
+ status: res.status,
+ statusText: res.statusText,
+ headers: res.headers
+ });
+ }
+
+ return res;
+ });
+ }
+
+ return response;
+}
+
+export const config = {
+ matcher: ['/', '/((?!api|_next/static|favicon.ico).*)'],
+};
\ No newline at end of file
diff --git a/readme.md b/readme.md
index 1daaeb5..ce7b4d8 100644
--- a/readme.md
+++ b/readme.md
@@ -116,6 +116,75 @@ services:
## 🔧 自定义配置
+### 密码保护功能
+
+LibreTV 现在支持密码保护功能,可以通过环境变量设置访问密码。当设置了 `PASSWORD` 环境变量后,用户首次访问网站时需要输入密码才能继续使用。
+
+- 如果 `PASSWORD` 环境变量为空或未设置,将不启用密码保护。
+- 密码验证状态会保存在浏览器本地存储中,有效期默认为7天。
+
+不同部署平台设置密码的方法:
+
+#### Cloudflare Pages
+
+1. 进入 Cloudflare Dashboard > Pages > 你的项目
+2. 点击"设置" > "环境变量"
+3. 添加新的变量:
+ - 变量名: `PASSWORD`
+ - 值: 你想设置的密码
+4. 选择应用于"生产环境"或同时包括"预览环境"
+5. 保存并重新部署项目
+
+#### Vercel
+
+1. 进入 Vercel Dashboard > 你的项目
+2. 点击"设置" > "环境变量"
+3. 添加新的环境变量:
+ - 名称: `PASSWORD`
+ - 值: 你想设置的密码
+4. 选择作用范围(生产/预览/开发环境)
+5. 点击"保存"并重新部署项目
+
+#### Docker/Docker Compose
+
+使用 Docker 运行时,可以通过环境变量传递密码:
+
+```bash
+# 使用 Docker 命令
+docker run -d --name libretv -p 8899:80 -e PASSWORD=your_password_here bestzwei/libretv:latest
+```
+
+使用 Docker Compose,在 `docker-compose.yml` 文件中设置:
+
+```yaml
+version: '3'
+services:
+ libretv:
+ image: bestzwei/libretv:latest
+ container_name: libretv
+ ports:
+ - "8899:80"
+ environment:
+ - PASSWORD=your_password_here # 留空则不启用密码保护
+ restart: unless-stopped
+```
+
+#### 本地测试环境
+
+对于本地测试,你可以在启动服务器之前设置环境变量:
+
+```bash
+# Linux/MacOS
+export PASSWORD=your_password_here
+python -m http.server 8080
+
+# Windows
+set PASSWORD=your_password_here
+python -m http.server 8080
+```
+
+## 🔧 自定义配置
+
项目主要配置在`js/config.js`文件中,你可以修改以下内容:
- `PROXY_URL`: 修改为你自己的代理服务地址