diff --git a/backend/package.json b/backend/package.json
index 5d69ccb9..fa1741e6 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -1,6 +1,6 @@
{
"name": "sub-store",
- "version": "2.36.11",
+ "version": "2.36.12",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"packageManager": "pnpm@11.0.9",
diff --git a/backend/src/restful/index.js b/backend/src/restful/index.js
index dbbd79b7..6cc60726 100644
--- a/backend/src/restful/index.js
+++ b/backend/src/restful/index.js
@@ -12,6 +12,7 @@ import {
import { gistBackupAction } from '@/restful/miscs';
import { SETTINGS_KEY } from '@/constants';
import { startArtifactCronJobs } from '@/utils/artifact-cron';
+import { createFrontendStaticMiddleware } from '@/utils/frontend-static';
import registerSubscriptionRoutes from './subscriptions';
import registerCollectionRoutes from './collections';
@@ -46,6 +47,10 @@ export default function serve() {
const be_prefix = eval('process.env.SUB_STORE_BACKEND_PREFIX');
const fe_be_path = eval('process.env.SUB_STORE_FRONTEND_BACKEND_PATH');
const fe_path = eval('process.env.SUB_STORE_FRONTEND_PATH');
+ const mergedFrontend =
+ be_merge && fe_path
+ ? createFrontendStaticMiddleware(fe_path, '/index.html')
+ : null;
if (be_prefix || be_merge) {
if (!fe_be_path.startsWith('/')) {
throw new Error(
@@ -101,25 +106,8 @@ export default function serve() {
const isBackendRoute = /^\/(api|download|share)(\/|$)/.test(
req.path,
);
- if (be_merge && fe_path && !isBackendRoute) {
- const express_ = eval(`require("express")`);
- const mime_ = eval(`require("mime-types")`);
- const path_ = eval(`require("path")`);
- const fs_ = eval(`require("fs")`);
- // 检查请求的文件是否真实存在,不存在则返回 index.html(SPA 路由)
- const filePath = path_.join(fe_path, req.path);
- if (!fs_.existsSync(filePath)) {
- req.url = '/index.html';
- }
- const staticFileMiddleware = express_.static(fe_path, {
- setHeaders: (res, path) => {
- const type = mime_.contentType(path_.extname(path));
- if (type) {
- res.set('Content-Type', type);
- }
- },
- });
- staticFileMiddleware(req, res, next);
+ if (mergedFrontend && !isBackendRoute) {
+ mergedFrontend(req, res, next);
return;
}
res.status(404).end();
@@ -368,7 +356,8 @@ export default function serve() {
const app = express_();
- const staticFileMiddleware = express_.static(fe_path);
+ const staticFileMiddleware =
+ createFrontendStaticMiddleware(fe_path);
let be_api = '/api/';
let be_download = '/download/';
diff --git a/backend/src/test/utils/frontend-static.spec.js b/backend/src/test/utils/frontend-static.spec.js
new file mode 100644
index 00000000..a254521d
--- /dev/null
+++ b/backend/src/test/utils/frontend-static.spec.js
@@ -0,0 +1,302 @@
+import { expect } from 'chai';
+import { afterEach, beforeEach, describe, it } from 'mocha';
+import fs from 'fs';
+import http from 'http';
+import os from 'os';
+import path from 'path';
+import zlib from 'zlib';
+
+import history from 'connect-history-api-fallback';
+import express from 'express';
+
+import {
+ createFrontendStaticMiddleware,
+ isHashedFrontendAsset,
+} from '@/utils/frontend-static';
+
+const HOST = '127.0.0.1';
+
+describe('frontend static middleware', function () {
+ let tempDir;
+ let frontendDir;
+ let originalChunk;
+ let compressedChunk;
+
+ beforeEach(function () {
+ tempDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'sub-store-frontend-static-'),
+ );
+ frontendDir = path.join(tempDir, 'frontend');
+ fs.mkdirSync(path.join(frontendDir, 'chunks'), { recursive: true });
+ fs.mkdirSync(path.join(frontendDir, 'css'));
+
+ originalChunk = Buffer.from('console.log("original chunk")');
+ compressedChunk = zlib.gzipSync(originalChunk);
+ fs.writeFileSync(
+ path.join(frontendDir, 'chunks/main-84da2e86.js'),
+ originalChunk,
+ );
+ fs.writeFileSync(
+ path.join(frontendDir, 'chunks/main-84da2e86.js.gz'),
+ compressedChunk,
+ );
+ fs.writeFileSync(
+ path.join(frontendDir, 'index.html'),
+ 'SPA',
+ );
+ fs.writeFileSync(path.join(frontendDir, 'index.js'), 'entry');
+ fs.writeFileSync(path.join(frontendDir, 'css/main.css'), 'body{}');
+ fs.writeFileSync(path.join(frontendDir, 'sw.js'), 'worker');
+ fs.writeFileSync(path.join(tempDir, 'secret.txt'), 'secret');
+ });
+
+ afterEach(function () {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ it('serves a hashed gzip representation with logical asset headers', async function () {
+ await withServer(createStaticApp(frontendDir), async (baseUrl) => {
+ const response = await request(
+ baseUrl,
+ '/chunks/main-84da2e86.js?cache=1',
+ {
+ headers: { 'Accept-Encoding': 'gzip' },
+ },
+ );
+
+ expect(response.statusCode).to.equal(200);
+ expect(response.body).to.deep.equal(compressedChunk);
+ expect(response.headers['content-encoding']).to.equal('gzip');
+ expect(response.headers['content-type']).to.match(/javascript/);
+ expect(response.headers.vary).to.include('Accept-Encoding');
+ expect(response.headers['content-length']).to.equal(
+ `${compressedChunk.length}`,
+ );
+ expect(response.headers['cache-control']).to.equal(
+ 'public, max-age=31536000, immutable',
+ );
+ expect(response.headers.etag).to.be.a('string');
+ expect(response.headers['last-modified']).to.equal(
+ fs
+ .statSync(
+ path.join(frontendDir, 'chunks/main-84da2e86.js.gz'),
+ )
+ .mtime.toUTCString(),
+ );
+
+ const conditional = await request(
+ baseUrl,
+ '/chunks/main-84da2e86.js',
+ {
+ headers: {
+ 'Accept-Encoding': 'gzip',
+ 'If-None-Match': response.headers.etag,
+ },
+ },
+ );
+
+ expect(conditional.statusCode).to.equal(304);
+ expect(conditional.body).to.have.length(0);
+
+ const replacement = zlib.gzipSync(
+ Buffer.from('console.log("replacement chunk")'),
+ );
+ fs.writeFileSync(
+ path.join(frontendDir, 'chunks/main-84da2e86.js.gz'),
+ replacement,
+ );
+ const replaced = await request(
+ baseUrl,
+ '/chunks/main-84da2e86.js',
+ { headers: { 'Accept-Encoding': 'gzip' } },
+ );
+
+ expect(replaced.body).to.deep.equal(replacement);
+ });
+ });
+
+ it('honors identity preferences and falls back when gzip is absent', async function () {
+ await withServer(createStaticApp(frontendDir), async (baseUrl) => {
+ for (const acceptEncoding of [
+ undefined,
+ 'gzip;q=0',
+ 'gzip;q=0.5, identity;q=1',
+ ]) {
+ const headers = acceptEncoding
+ ? { 'Accept-Encoding': acceptEncoding }
+ : {};
+ const response = await request(
+ baseUrl,
+ '/chunks/main-84da2e86.js',
+ { headers },
+ );
+
+ expect(response.body).to.deep.equal(originalChunk);
+ expect(response.headers['content-encoding']).to.equal(
+ undefined,
+ );
+ expect(response.headers['cache-control']).to.equal(
+ 'public, max-age=31536000, immutable',
+ );
+ }
+
+ const fallback = await request(baseUrl, '/index.js?cache=1', {
+ headers: { 'Accept-Encoding': 'gzip' },
+ });
+
+ expect(fallback.body.toString()).to.equal('entry');
+ expect(fallback.headers['content-encoding']).to.equal(undefined);
+ expect(fallback.headers['cache-control']).to.equal(
+ 'public, max-age=0',
+ );
+ expect(fallback.headers.etag).to.be.a('string');
+ });
+ });
+
+ it('returns gzip metadata without a body for HEAD', async function () {
+ await withServer(createStaticApp(frontendDir), async (baseUrl) => {
+ const response = await request(
+ baseUrl,
+ '/chunks/main-84da2e86.js',
+ {
+ method: 'HEAD',
+ headers: { 'Accept-Encoding': 'gzip' },
+ },
+ );
+
+ expect(response.statusCode).to.equal(200);
+ expect(response.body).to.have.length(0);
+ expect(response.headers['content-encoding']).to.equal('gzip');
+ expect(response.headers['content-length']).to.equal(
+ `${compressedChunk.length}`,
+ );
+ });
+ });
+
+ it('keeps stable names revalidatable and blocks traversal', async function () {
+ expect(
+ isHashedFrontendAsset('C:\\dist\\release-deadbeef.dir\\index.html'),
+ ).to.equal(false);
+
+ const compressedCss = zlib.gzipSync(Buffer.from('body{}'));
+ fs.writeFileSync(
+ path.join(frontendDir, 'css/main.css.gz'),
+ compressedCss,
+ );
+
+ await withServer(createStaticApp(frontendDir), async (baseUrl) => {
+ for (const pathname of ['/index.html', '/sw.js', '/css/main.css']) {
+ const response = await request(baseUrl, pathname, {
+ headers: { 'Accept-Encoding': 'gzip' },
+ });
+
+ expect(response.headers['cache-control']).to.equal(
+ 'public, max-age=0',
+ );
+ expect(response.headers.etag).to.be.a('string');
+ }
+
+ const traversal = await request(baseUrl, '/%2e%2e%2fsecret.txt');
+
+ expect(traversal.statusCode).to.equal(404);
+ expect(traversal.body.toString()).not.to.equal('secret');
+ });
+ });
+
+ it('preserves merged and standalone SPA routing', async function () {
+ const merged = express();
+ const mergedFrontend = createFrontendStaticMiddleware(
+ frontendDir,
+ '/index.html',
+ );
+ merged.use((req, res, next) => {
+ if (/^\/(api|download|share)(\/|$)/.test(req.path)) {
+ next();
+ return;
+ }
+ mergedFrontend(req, res, next);
+ });
+ merged.use(['/api', '/download', '/share'], (req, res) =>
+ res.status(204).end(),
+ );
+
+ await withServer(merged, async (baseUrl) => {
+ const spa = await request(baseUrl, '/settings', {
+ headers: { Accept: 'text/html' },
+ });
+
+ expect(spa.body.toString()).to.equal('SPA');
+ for (const prefix of ['/api', '/download', '/share']) {
+ const backend = await request(baseUrl, `${prefix}/settings`);
+ expect(backend.statusCode).to.equal(204);
+ }
+ });
+
+ const standalone = express();
+ const staticFiles = createFrontendStaticMiddleware(frontendDir);
+ standalone.use(staticFiles);
+ standalone.use(history({ disableDotRule: true, verbose: false }));
+ standalone.use(staticFiles);
+
+ await withServer(standalone, async (baseUrl) => {
+ const spa = await request(baseUrl, '/settings', {
+ headers: { Accept: 'text/html' },
+ });
+ expect(spa.body.toString()).to.equal('SPA');
+ });
+ });
+});
+
+function createStaticApp(root) {
+ const app = express();
+ app.use(createFrontendStaticMiddleware(root));
+ return app;
+}
+
+async function withServer(app, run) {
+ const server = await listen(app);
+ const { port } = server.address();
+
+ try {
+ await run(`http://${HOST}:${port}`);
+ } finally {
+ await close(server);
+ }
+}
+
+function listen(app) {
+ return new Promise((resolve) => {
+ const server = app.listen(0, HOST, () => resolve(server));
+ });
+}
+
+function close(server) {
+ return new Promise((resolve, reject) => {
+ server.close((error) => {
+ if (error) reject(error);
+ else resolve();
+ });
+ });
+}
+
+function request(baseUrl, pathname, { method = 'GET', headers = {} } = {}) {
+ return new Promise((resolve, reject) => {
+ const req = http.request(
+ `${baseUrl}${pathname}`,
+ { method, headers },
+ (res) => {
+ const chunks = [];
+ res.on('data', (chunk) => chunks.push(chunk));
+ res.on('end', () => {
+ resolve({
+ statusCode: res.statusCode,
+ headers: res.headers,
+ body: Buffer.concat(chunks),
+ });
+ });
+ },
+ );
+ req.on('error', reject);
+ req.end();
+ });
+}
diff --git a/backend/src/utils/frontend-static.js b/backend/src/utils/frontend-static.js
new file mode 100644
index 00000000..092cd0e2
--- /dev/null
+++ b/backend/src/utils/frontend-static.js
@@ -0,0 +1,70 @@
+const GZIP_SUFFIX = '.gz';
+const HASHED_ASSET = /-[0-9a-f]{8}\.[^/\\]+$/i;
+
+export function isHashedFrontendAsset(filePath) {
+ return HASHED_ASSET.test(filePath);
+}
+
+export function createFrontendStaticMiddleware(root, fallbackPath) {
+ const express = eval(`require("express")`);
+ const mime = eval(`require("mime-types")`);
+ const staticFiles = express.static(root, {
+ setHeaders(res, filePath) {
+ const isGzip = filePath.endsWith(GZIP_SUFFIX);
+ const logicalPath = isGzip
+ ? filePath.slice(0, -GZIP_SUFFIX.length)
+ : filePath;
+ const contentType = mime.contentType(mime.lookup(logicalPath));
+
+ if (contentType) res.setHeader('Content-Type', contentType);
+ if (isGzip) res.setHeader('Content-Encoding', 'gzip');
+ res.vary('Accept-Encoding');
+ res.setHeader(
+ 'Cache-Control',
+ isHashedFrontendAsset(logicalPath)
+ ? 'public, max-age=31536000, immutable'
+ : 'public, max-age=0',
+ );
+ },
+ });
+
+ function serveFile(req, res, next) {
+ if (req.acceptsEncodings(['gzip', 'identity']) !== 'gzip') {
+ staticFiles(req, res, next);
+ return;
+ }
+
+ const originalUrl = req.url;
+ req.url = appendGzipSuffix(originalUrl);
+ staticFiles(req, res, (error) => {
+ req.url = originalUrl;
+ if (error) next(error);
+ else staticFiles(req, res, next);
+ });
+ req.url = originalUrl;
+ }
+
+ if (!fallbackPath) return serveFile;
+
+ return (req, res, next) => {
+ const originalUrl = req.url;
+ serveFile(req, res, (error) => {
+ if (error) {
+ next(error);
+ return;
+ }
+ req.url = fallbackPath;
+ serveFile(req, res, (fallbackError) => {
+ req.url = originalUrl;
+ next(fallbackError);
+ });
+ req.url = originalUrl;
+ });
+ };
+}
+
+function appendGzipSuffix(url) {
+ const queryStart = url.indexOf('?');
+ if (queryStart === -1) return `${url}${GZIP_SUFFIX}`;
+ return `${url.slice(0, queryStart)}${GZIP_SUFFIX}${url.slice(queryStart)}`;
+}
diff --git a/docs/brainstorms/2026-05-15-h2-connect-proxy-headers-requirements.md b/docs/brainstorms/2026-05-15-h2-connect-proxy-headers-requirements.md
deleted file mode 100644
index 45dd4669..00000000
--- a/docs/brainstorms/2026-05-15-h2-connect-proxy-headers-requirements.md
+++ /dev/null
@@ -1,67 +0,0 @@
----
-date: 2026-05-15
-topic: h2-connect-proxy-headers
----
-
-# HTTP/2 CONNECT Proxy Headers
-
-## Summary
-
-Sub-Store will preserve Surge HTTP/2 CONNECT proxies as canonical `h2-connect` nodes and round-trip custom proxy request headers for the Surge proxy types that now support them. Egern HTTP/HTTPS output will also carry root `headers` fields, while unsupported targets must not silently drop headers.
-
----
-
-## Problem Frame
-
-Surge now supports custom request headers on HTTP, HTTPS, HTTP/2 CONNECT, and TrustTunnel proxy definitions, including dynamic placeholders such as `` and ``. Without parser and producer support, these nodes either fail to round-trip or lose headers during conversion. Egern documentation also lists `headers` for HTTP and HTTPS proxies, but current output does not emit it.
-
----
-
-## Requirements
-
-**Protocol Coverage**
-- R1. Surge input must parse `h2-connect` proxy lines into type `h2-connect`.
-- R2. Surge output must emit type `h2-connect` for canonical `h2-connect` nodes.
-- R3. Frontend protocol filtering must expose HTTP/2 CONNECT and use value `h2-connect`.
-
-**Header Handling**
-- R4. Surge input and output must preserve root `headers` for HTTP, HTTPS, HTTP/2 CONNECT, and TrustTunnel proxies.
-- R5. Header placeholder text such as `` and `` must round-trip as literal configuration text.
-- R6. Egern HTTP and HTTPS output must include root `headers` when present.
-- R7. Outputs that cannot represent root headers for HTTP/HTTPS, HTTP/2 CONNECT, or TrustTunnel must log and filter or error instead of silently dropping those headers.
-
-**Compatibility**
-- R8. Existing proxy types and transport-layer headers, such as WebSocket or VMess/VLESS h2 transport headers, must keep current behavior.
-- R9. Mihomo support must be based on local source verification, not assumption.
-
----
-
-## Acceptance Examples
-
-- AE1. **Covers R1, R4, R5.** Given `Proxy = h2-connect, example.com, 443, headers=X-Padding:`, when Surge input is parsed, the node type is `h2-connect` and the header value remains unchanged.
-- AE2. **Covers R2, R4.** Given a Surge HTTP, HTTPS, HTTP/2 CONNECT, or TrustTunnel node with root headers, when Surge output is generated, the line contains `headers=...`.
-- AE3. **Covers R6.** Given an Egern HTTP or HTTPS node with root headers, when Egern output is generated, the YAML object includes `headers`.
-- AE4. **Covers R7.** Given a TrustTunnel node with root headers, when outputting to a target without TrustTunnel header support, Sub-Store logs the unsupported header condition and omits or errors the node.
-
----
-
-## Success Criteria
-
-- Users can parse and re-export Surge HTTP/2 CONNECT and supported header-bearing Surge proxies without losing header configuration.
-- Downstream implementation has explicit platform boundaries for header support and does not need to infer unsupported-target behavior.
-
----
-
-## Scope Boundaries
-
-- No frontend node editor for authoring headers is added in this pass.
-- No runtime generation of `` values is implemented by Sub-Store; placeholders remain Surge configuration text.
-- No claim that Mihomo supports HTTP/2 CONNECT as a standalone outbound type unless verified in `adapter/parser.go` and `constant/adapters.go`.
-
----
-
-## Dependencies / Assumptions
-
-- Egern HTTP/HTTPS `headers` support is based on the current Egern proxy configuration documentation.
-- Local Mihomo source shows HTTP proxy `headers` support for the regular HTTP outbound, but no standalone `h2-connect` adapter type and no TrustTunnel `headers` option.
-- sing-box HTTP outbound supports root `headers`, and JSON output preserves canonical proxy objects without platform-specific header loss.