Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projectFaviconRoute.ts

188 lines5.1 KB

1import fs from "node:fs";
2import http from "node:http";
3import path from "node:path";
4​
5export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
6​
7export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
8 "image/png": ".png",
9 "image/jpeg": ".jpg",
10 "image/jpg": ".jpg",
11 "image/gif": ".gif",
12 "image/webp": ".webp",
13 "image/svg+xml": ".svg",
14 "image/bmp": ".bmp",
15 "image/tiff": ".tiff",
16 "image/heic": ".heic",
17};
18​
19export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
20 ".jpg",
21 ".jpeg",
22 ".png",
23 ".gif",
24 ".webp",
25 ".bmp",
26 ".tiff",
27 ".svg",
28 ".ico",
29]);
30​
31const FAVICON_MIME_TYPES: Record<string, string> = {
32 ".png": "image/png",
33 ".jpg": "image/jpeg",
34 ".svg": "image/svg+xml",
35 ".ico": "image/x-icon",
36};
37​
38// Well-known favicon paths checked in order.
39const FAVICON_CANDIDATES = [
40 "favicon.svg",
41 "favicon.ico",
42 "favicon.png",
43 "public/favicon.svg",
44 "public/favicon.ico",
45 "public/favicon.png",
46 "app/favicon.ico",
47 "app/favicon.png",
48 "app/icon.svg",
49 "app/icon.png",
50 "app/icon.ico",
51 "src/favicon.ico",
52 "src/favicon.svg",
53 "src/app/favicon.ico",
54 "src/app/icon.svg",
55 "src/app/icon.png",
56 "assets/icon.svg",
57 "assets/icon.png",
58 "assets/logo.svg",
59 "assets/logo.png",
60];
61​
62// Files that may contain a <link rel="icon"> or icon metadata declaration.
63const ICON_SOURCE_FILES = [
64 "index.html",
65 "public/index.html",
66 "app/routes/__root.tsx",
67 "src/routes/__root.tsx",
68 "app/root.tsx",
69 "src/root.tsx",
70 "src/index.html",
71];
72​
73// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
74const LINK_ICON_HTML_RE =
75 /<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
76const LINK_ICON_OBJ_RE =
77 /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
78​
79function extractIconHref(source: string): string | null {
80 const htmlMatch = source.match(LINK_ICON_HTML_RE);
81 if (htmlMatch?.[1]) return htmlMatch[1];
82 const objMatch = source.match(LINK_ICON_OBJ_RE);
83 if (objMatch?.[1]) return objMatch[1];
84 return null;
86​
87function resolveIconHref(projectCwd: string, href: string): string[] {
88 const clean = href.replace(/^\//, "");
89 return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
91​
92function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
93 const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
94 return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
96​
97function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
98 const ext = path.extname(filePath).toLowerCase();
99 const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
100 fs.readFile(filePath, (readErr, data) => {
101 if (readErr) {
102 res.writeHead(500, { "Content-Type": "text/plain" });
103 res.end("Read error");
104 return;
105 }
106 res.writeHead(200, {
107 "Content-Type": contentType,
108 "Cache-Control": "public, max-age=3600",
109 });
110 res.end(data);
111 });
113​
114export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
115 if (url.pathname !== "/api/project-favicon") {
116 return false;
117 }
118​
119 const projectCwd = url.searchParams.get("cwd");
120 if (!projectCwd) {
121 res.writeHead(400, { "Content-Type": "text/plain" });
122 res.end("Missing cwd parameter");
123 return true;
124 }
125​
126 const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
127 if (index >= paths.length) {
128 onExhausted();
129 return;
130 }
131 const candidate = paths[index]!;
132 if (!isPathWithinProject(projectCwd, candidate)) {
133 tryResolvedPaths(paths, index + 1, onExhausted);
134 return;
135 }
136 fs.stat(candidate, (err, stats) => {
137 if (err || !stats?.isFile()) {
138 tryResolvedPaths(paths, index + 1, onExhausted);
139 return;
140 }
141 serveFaviconFile(candidate, res);
142 });
143 };
144​
145 const trySourceFiles = (index: number): void => {
146 if (index >= ICON_SOURCE_FILES.length) {
147 res.writeHead(404, { "Content-Type": "text/plain" });
148 res.end("No favicon found");
149 return;
150 }
151 const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
152 fs.readFile(sourceFile, "utf8", (err, content) => {
153 if (err) {
154 trySourceFiles(index + 1);
155 return;
156 }
157 const href = extractIconHref(content);
158 if (!href) {
159 trySourceFiles(index + 1);
160 return;
161 }
162 const candidates = resolveIconHref(projectCwd, href);
163 tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
164 });
165 };
166​
167 const tryCandidates = (index: number): void => {
168 if (index >= FAVICON_CANDIDATES.length) {
169 trySourceFiles(0);
170 return;
171 }
172 const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
173 if (!isPathWithinProject(projectCwd, candidate)) {
174 tryCandidates(index + 1);
175 return;
176 }
177 fs.stat(candidate, (err, stats) => {
178 if (err || !stats?.isFile()) {
179 tryCandidates(index + 1);
180 return;
181 }
182 serveFaviconFile(candidate, res);
183 });
184 };
185​
186 tryCandidates(0);
187 return true;