forked from LibreSpark/LibreTV
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
61 lines (51 loc) · 1.85 KB
/
middleware.js
File metadata and controls
61 lines (51 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { sha256 } from './js/sha256.js'; // 需新建或引入SHA-256实现
// Vercel Middleware to inject environment variables
export default async function middleware(request) {
// Get the URL from the request
const url = new URL(request.url);
// Only process HTML pages
const isHtmlPage = url.pathname.endsWith('.html') || url.pathname.endsWith('/');
if (!isHtmlPage) {
return; // Let the request pass through unchanged
}
// Fetch the original response
const response = await fetch(request);
// Check if it's an HTML response
const contentType = response.headers.get('content-type') || '';
if (!contentType.includes('text/html')) {
return response; // Return the original response if not HTML
}
// Get the HTML content
const originalHtml = await response.text();
// Replace the placeholder with actual environment variable
// If PASSWORD is not set, replace with empty string
const password = process.env.PASSWORD || '';
let passwordHash = '';
if (password) {
passwordHash = await sha256(password);
}
const adminpassword = process.env.ADMINPASSWORD || '';
let adminpasswordHash = '';
if (adminpassword) {
adminpasswordHash = await sha256(adminpassword); // 修复变量名
}
// 合并两次替换为一次操作
let modifiedHtml = originalHtml
.replace(
'window.__ENV__.PASSWORD = "{{PASSWORD}}";',
`window.__ENV__.PASSWORD = "${passwordHash}"; // SHA-256 hash`
)
.replace(
'window.__ENV__.ADMINPASSWORD = "{{ADMINPASSWORD}}";',
`window.__ENV__.ADMINPASSWORD = "${adminpasswordHash}"; // SHA-256 hash`
);
// 修复Response构造
return new Response(modifiedHtml, {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
}
export const config = {
matcher: ['/', '/((?!api|_next/static|_vercel|favicon.ico).*)'],
};