Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 33 additions & 6 deletions packages/server/src/routes/serve.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
import crypto from "node:crypto";
import fs from "node:fs";
import { createReadStream } from "node:fs";
import path from "node:path";
import { getPageDir, readPageMeta, readDbConfig } from "../plugins/storage.js";
import { pushPageView } from "../lib/request-logger.js";
Expand Down Expand Up @@ -267,8 +268,7 @@ export async function serveRoutes(app: FastifyInstance, options: { webRoot?: str
const versionDir = path.join(getPageDir(dataDir(), userId, name), "versions", `v${version}`);
const indexPath = path.join(versionDir, "index.html");
if (fs.existsSync(indexPath)) {
reply.header("Content-Security-Policy", CSP_HEADER);
return reply.type("text/html").send(fs.readFileSync(indexPath));
return sendAppFile(req, reply, indexPath, "index.html");
}
return reply.status(404).send({ success: false, error: "index.html not found" });
},
Expand Down Expand Up @@ -444,22 +444,49 @@ export async function serveRoutes(app: FastifyInstance, options: { webRoot?: str

let filePath = path.join(versionDir, restPath || "index.html");
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
reply.header("Content-Security-Policy", CSP_HEADER);
return reply.type(getMimeType(filePath)).send(fs.readFileSync(filePath));
return sendAppFile(req, reply, filePath, restPath);
}

// SPA fallback: if not a static asset (no extension), serve index.html
const indexPath = path.join(versionDir, "index.html");
if (fs.existsSync(indexPath) && !restPath.includes(".")) {
reply.header("Content-Security-Policy", CSP_HEADER);
return reply.type("text/html").send(fs.readFileSync(indexPath));
return sendAppFile(req, reply, indexPath, restPath);
}

return reply.status(404).send({ success: false, error: "File not found" });
}
);
}

/**
* Vite emits bundled assets as `assets/<name>-<contentHash>.<ext>`, so the URL
* already changes whenever the bytes change. Anything else under an app version
* directory (index.html, or a file the app itself shipped) keeps its name across
* versions and must revalidate instead.
*/
function isImmutableAppAsset(restPath: string): boolean {
return /(?:^|\/)assets\/[^/]+-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/.test(restPath);
}

/**
* Serves one file from an app version directory with the validators the platform
* shell already has and app resources used to lack: without them every visit
* re-downloaded the whole bundle, and a revalidation could not answer 304.
*/
function sendAppFile(req: FastifyRequest, reply: FastifyReply, filePath: string, restPath: string): FastifyReply {
const stat = fs.statSync(filePath);
const etag = `W/"${stat.size.toString(16)}-${Math.trunc(stat.mtimeMs).toString(16)}"`;
reply.header("ETag", etag);
reply.header("Last-Modified", stat.mtime.toUTCString());
reply.header("Cache-Control", isImmutableAppAsset(restPath) ? "public, max-age=31536000, immutable" : "no-cache");
reply.header("Content-Security-Policy", CSP_HEADER);
const ifNoneMatch = req.headers["if-none-match"];
if (typeof ifNoneMatch === "string" && ifNoneMatch.split(",").some((value) => value.trim() === etag)) {
return reply.status(304).send();
}
return reply.type(getMimeType(filePath)).send(createReadStream(filePath));
}

function injectNativeShellMetadata(html: string, userId: string, name: string): string {
const resourceBase = `/serve/${userId}/${name}/`;
const marker = [
Expand Down
20 changes: 20 additions & 0 deletions packages/server/tests/integration/serve-edge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,12 @@ describe("Serve edge cases", () => {
body += `--${boundary}\r\nContent-Disposition: form-data; name="filepath_1"\r\n\r\nassets/main.js\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="filepath_2"\r\n\r\nassets/main.css\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="filepath_3"\r\n\r\nassets/pdf.worker.mjs\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="filepath_4"\r\n\r\nassets/main-2f9a1c3b4d.js\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="files"; filename="index.html"\r\nContent-Type: text/html\r\n\r\n${html}\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="files"; filename="main.js"\r\nContent-Type: application/javascript\r\n\r\nconsole.log("hello");\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="files"; filename="main.css"\r\nContent-Type: text/css\r\n\r\nbody { margin: 0; }\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="files"; filename="pdf.worker.mjs"\r\nContent-Type: application/javascript\r\n\r\nexport const workerVersion = "test";\r\n`;
body += `--${boundary}\r\nContent-Disposition: form-data; name="files"; filename="main-2f9a1c3b4d.js"\r\nContent-Type: application/javascript\r\n\r\nconsole.log("hashed");\r\n`;
body += `--${boundary}--\r\n`;

await fetch(`${baseUrl}/api/upload`, {
Expand Down Expand Up @@ -126,6 +128,24 @@ describe("Serve edge cases", () => {
expect(html).toContain("data-localapp-app-resource-base");
});

it("marks content-hashed app assets immutable and revalidates the rest", async () => {
// Break caught: app resources were served with no validators at all, so
// every visit re-downloaded the whole bundle instead of answering 304.
const hashed = await fetch(`${baseUrl}/serve/${userId}/${pageName}/assets/main-2f9a1c3b4d.js`);
expect(hashed.status).toBe(200);
expect(hashed.headers.get("cache-control")).toBe("public, max-age=31536000, immutable");
expect(hashed.headers.get("etag")).toBeTruthy();

const plain = await fetch(`${baseUrl}/serve/${userId}/${pageName}/assets/main.js`);
expect(plain.headers.get("cache-control")).toBe("no-cache");
const etag = plain.headers.get("etag");
expect(etag).toBeTruthy();
const revalidated = await fetch(`${baseUrl}/serve/${userId}/${pageName}/assets/main.js`, {
headers: { "If-None-Match": String(etag) },
});
expect(revalidated.status).toBe(304);
});

it("未登录访问返回 Next.js Shell HTML(登录 UI 由客户端渲染)", async () => {
const res = await fetch(`${baseUrl}/${userId}/${pageName}`);
expect(res.status).toBe(200);
Expand Down
Loading