refactor progress
This commit is contained in:
83
packages/app_proxy/src/app_server/AppServerMiddleware.tsx
Normal file
83
packages/app_proxy/src/app_server/AppServerMiddleware.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {AppTelemetryOptions, HonoEnv} from '@fluxer/app_proxy/src/AppServerTypes';
|
||||
import {isExpectedError} from '@fluxer/app_proxy/src/ErrorClassification';
|
||||
import {applyMiddlewareStack} from '@fluxer/hono/src/middleware/MiddlewareStack';
|
||||
import type {Logger} from '@fluxer/logger/src/Logger';
|
||||
import type {Hono} from 'hono';
|
||||
|
||||
interface ApplyAppServerMiddlewareOptions {
|
||||
app: Hono<HonoEnv>;
|
||||
captureException?: (error: Error, context?: Record<string, unknown>) => void;
|
||||
env?: string;
|
||||
logger: Logger;
|
||||
telemetry?: AppTelemetryOptions;
|
||||
}
|
||||
|
||||
export function applyAppServerMiddleware(options: ApplyAppServerMiddlewareOptions): void {
|
||||
const {app, captureException, env, logger, telemetry} = options;
|
||||
|
||||
applyMiddlewareStack(app, {
|
||||
requestId: {},
|
||||
tracing: telemetry?.tracing,
|
||||
metrics: telemetry?.metricsCollector
|
||||
? {
|
||||
enabled: true,
|
||||
collector: telemetry.metricsCollector,
|
||||
skipPaths: ['/_health'],
|
||||
}
|
||||
: undefined,
|
||||
logger: {
|
||||
log: (data) => {
|
||||
logger.info(
|
||||
{
|
||||
method: data.method,
|
||||
path: data.path,
|
||||
status: data.status,
|
||||
durationMs: data.durationMs,
|
||||
},
|
||||
'Request completed',
|
||||
);
|
||||
},
|
||||
skip: ['/_health'],
|
||||
},
|
||||
errorHandler: {
|
||||
includeStack: env === 'development',
|
||||
logger: (error, c) => {
|
||||
if (!isExpectedError(error) && captureException) {
|
||||
captureException(error, {
|
||||
path: c.req.path,
|
||||
method: c.req.method,
|
||||
});
|
||||
}
|
||||
|
||||
logger.error(
|
||||
{
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
path: c.req.path,
|
||||
method: c.req.method,
|
||||
},
|
||||
'Request error',
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
50
packages/app_proxy/src/app_server/AppServerRoutes.tsx
Normal file
50
packages/app_proxy/src/app_server/AppServerRoutes.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {HonoEnv} from '@fluxer/app_proxy/src/AppServerTypes';
|
||||
import {createSpaIndexRoute} from '@fluxer/app_proxy/src/app_server/routes/SpaIndexRoute';
|
||||
import {createSpaRoute} from '@fluxer/app_proxy/src/app_server/routes/SpaRoute';
|
||||
import type {CSPOptions} from '@fluxer/app_proxy/src/app_server/utils/CSP';
|
||||
import type {Logger} from '@fluxer/logger/src/Logger';
|
||||
import type {Hono} from 'hono';
|
||||
|
||||
interface RegisterAppServerRoutesOptions {
|
||||
app: Hono<HonoEnv>;
|
||||
assetVersion?: string;
|
||||
cspDirectives?: CSPOptions;
|
||||
logger: Logger;
|
||||
staticDir: string;
|
||||
}
|
||||
|
||||
export function registerAppServerRoutes(options: RegisterAppServerRoutesOptions): void {
|
||||
const {app, assetVersion, cspDirectives, logger, staticDir} = options;
|
||||
|
||||
app.get('/_health', (c) => c.text('OK'));
|
||||
|
||||
createSpaRoute(app, {
|
||||
staticDir,
|
||||
assetVersion,
|
||||
});
|
||||
|
||||
createSpaIndexRoute(app, {
|
||||
staticDir,
|
||||
cspDirectives,
|
||||
logger,
|
||||
});
|
||||
}
|
||||
66
packages/app_proxy/src/app_server/routes/SpaIndexRoute.tsx
Normal file
66
packages/app_proxy/src/app_server/routes/SpaIndexRoute.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type {CSPOptions} from '@fluxer/app_proxy/src/app_server/utils/CSP';
|
||||
import {isStaticAsset} from '@fluxer/app_proxy/src/app_server/utils/Mime';
|
||||
import {
|
||||
applySpaHeaders,
|
||||
serveSpaFallback,
|
||||
serveStaticFile,
|
||||
} from '@fluxer/app_proxy/src/app_server/utils/StaticFileUtils';
|
||||
import type {Logger} from '@fluxer/logger/src/Logger';
|
||||
import type {Env, Hono} from 'hono';
|
||||
|
||||
export interface SpaIndexRouteOptions {
|
||||
staticDir: string;
|
||||
cspDirectives?: CSPOptions;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
export function createSpaIndexRoute<E extends Env>(app: Hono<E>, options: SpaIndexRouteOptions): void {
|
||||
const {cspDirectives, logger, staticDir} = options;
|
||||
|
||||
app.get('*', (c) => {
|
||||
const requestPath = c.req.path;
|
||||
|
||||
if (isStaticAsset(requestPath)) {
|
||||
const result = serveStaticFile({requestPath, resolvedStaticDir: staticDir, logger});
|
||||
if (!result.success) {
|
||||
if (result.error) {
|
||||
return c.text(result.error, 500);
|
||||
}
|
||||
return c.notFound();
|
||||
}
|
||||
return new Response(result.content, {
|
||||
headers: {
|
||||
'Content-Type': result.mimeType,
|
||||
'Cache-Control': result.cacheControl,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const fallbackResult = serveSpaFallback({resolvedStaticDir: staticDir, cspDirectives, logger});
|
||||
if (!fallbackResult.success) {
|
||||
return c.text(fallbackResult.error, 500);
|
||||
}
|
||||
|
||||
applySpaHeaders(c, fallbackResult.csp);
|
||||
return c.body(fallbackResult.content);
|
||||
});
|
||||
}
|
||||
81
packages/app_proxy/src/app_server/routes/SpaRoute.tsx
Normal file
81
packages/app_proxy/src/app_server/routes/SpaRoute.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {existsSync, readFileSync} from 'node:fs';
|
||||
import {join} from 'node:path';
|
||||
import type {Env, Hono} from 'hono';
|
||||
|
||||
export interface SpaRouteOptions {
|
||||
staticDir: string;
|
||||
assetVersion?: string;
|
||||
}
|
||||
|
||||
export function createSpaRoute<E extends Env>(app: Hono<E>, options: SpaRouteOptions): void {
|
||||
const {assetVersion, staticDir} = options;
|
||||
|
||||
app.get('/version.json', (c) => {
|
||||
const versionFileContent = readStaticTextFile(staticDir, 'version.json');
|
||||
if (!versionFileContent) {
|
||||
if (assetVersion) {
|
||||
return c.json({version: assetVersion});
|
||||
}
|
||||
return c.notFound();
|
||||
}
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
return c.json(JSON.parse(versionFileContent) as unknown);
|
||||
});
|
||||
|
||||
app.get('/manifest.json', (c) => {
|
||||
const manifestContent = readStaticTextFile(staticDir, 'manifest.json');
|
||||
if (!manifestContent) {
|
||||
return c.notFound();
|
||||
}
|
||||
c.header('Content-Type', 'application/manifest+json');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
return c.body(manifestContent);
|
||||
});
|
||||
|
||||
app.get('/sw.js', (c) => {
|
||||
const serviceWorkerContent = readStaticTextFile(staticDir, 'sw.js');
|
||||
if (!serviceWorkerContent) {
|
||||
return c.notFound();
|
||||
}
|
||||
c.header('Content-Type', 'application/javascript; charset=utf-8');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
return c.body(serviceWorkerContent);
|
||||
});
|
||||
|
||||
app.get('/sw.js.map', (c) => {
|
||||
const sourceMapContent = readStaticTextFile(staticDir, 'sw.js.map');
|
||||
if (!sourceMapContent) {
|
||||
return c.notFound();
|
||||
}
|
||||
c.header('Content-Type', 'application/json');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
return c.body(sourceMapContent);
|
||||
});
|
||||
}
|
||||
|
||||
function readStaticTextFile(staticDir: string, filename: string): string | null {
|
||||
const filePath = join(staticDir, filename);
|
||||
if (!existsSync(filePath)) {
|
||||
return null;
|
||||
}
|
||||
return readFileSync(filePath, 'utf-8');
|
||||
}
|
||||
182
packages/app_proxy/src/app_server/utils/CSP.tsx
Normal file
182
packages/app_proxy/src/app_server/utils/CSP.tsx
Normal file
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {randomBytes} from 'node:crypto';
|
||||
import type {SentryDSN} from '@fluxer/app_proxy/src/app_server/utils/SentryDSN';
|
||||
|
||||
export const CSP_HOSTS = {
|
||||
FRAME: [
|
||||
'https://www.youtube.com/embed/',
|
||||
'https://www.youtube.com/s/player/',
|
||||
'https://hcaptcha.com',
|
||||
'https://*.hcaptcha.com',
|
||||
'https://challenges.cloudflare.com',
|
||||
],
|
||||
IMAGE: [
|
||||
'https://*.fluxer.app',
|
||||
'https://i.ytimg.com',
|
||||
'https://*.youtube.com',
|
||||
'https://fluxerusercontent.com',
|
||||
'https://fluxerstatic.com',
|
||||
'https://*.fluxer.media',
|
||||
'https://fluxer.media',
|
||||
],
|
||||
MEDIA: [
|
||||
'https://*.fluxer.app',
|
||||
'https://*.youtube.com',
|
||||
'https://fluxerusercontent.com',
|
||||
'https://fluxerstatic.com',
|
||||
'https://*.fluxer.media',
|
||||
'https://fluxer.media',
|
||||
],
|
||||
SCRIPT: [
|
||||
'https://*.fluxer.app',
|
||||
'https://hcaptcha.com',
|
||||
'https://*.hcaptcha.com',
|
||||
'https://challenges.cloudflare.com',
|
||||
'https://fluxerstatic.com',
|
||||
],
|
||||
STYLE: [
|
||||
'https://*.fluxer.app',
|
||||
'https://hcaptcha.com',
|
||||
'https://*.hcaptcha.com',
|
||||
'https://challenges.cloudflare.com',
|
||||
'https://fluxerstatic.com',
|
||||
],
|
||||
FONT: ['https://*.fluxer.app', 'https://fluxerstatic.com'],
|
||||
CONNECT: [
|
||||
'https://*.fluxer.app',
|
||||
'wss://*.fluxer.app',
|
||||
'https://*.fluxer.media',
|
||||
'wss://*.fluxer.media',
|
||||
'https://hcaptcha.com',
|
||||
'https://*.hcaptcha.com',
|
||||
'https://challenges.cloudflare.com',
|
||||
'https://*.fluxer.workers.dev',
|
||||
'https://fluxerusercontent.com',
|
||||
'https://fluxerstatic.com',
|
||||
'https://sentry.web.fluxer.app',
|
||||
'https://sentry.web.canary.fluxer.app',
|
||||
'https://fluxer.media',
|
||||
'http://127.0.0.1:21863',
|
||||
'http://127.0.0.1:21864',
|
||||
],
|
||||
WORKER: ['https://*.fluxer.app', 'https://fluxerstatic.com', 'blob:'],
|
||||
MANIFEST: ['https://*.fluxer.app'],
|
||||
} as const;
|
||||
|
||||
export interface CSPOptions {
|
||||
defaultSrc?: ReadonlyArray<string>;
|
||||
scriptSrc?: ReadonlyArray<string>;
|
||||
styleSrc?: ReadonlyArray<string>;
|
||||
imgSrc?: ReadonlyArray<string>;
|
||||
mediaSrc?: ReadonlyArray<string>;
|
||||
fontSrc?: ReadonlyArray<string>;
|
||||
connectSrc?: ReadonlyArray<string>;
|
||||
frameSrc?: ReadonlyArray<string>;
|
||||
workerSrc?: ReadonlyArray<string>;
|
||||
manifestSrc?: ReadonlyArray<string>;
|
||||
reportUri?: string;
|
||||
}
|
||||
|
||||
export interface SentryProxyConfig {
|
||||
sentryProxy: SentryDSN | null;
|
||||
sentryProxyPath: string;
|
||||
sentryReportHost: string;
|
||||
}
|
||||
|
||||
export function generateNonce(): string {
|
||||
return randomBytes(16).toString('hex');
|
||||
}
|
||||
|
||||
export function buildSentryReportURI(config: SentryProxyConfig): string {
|
||||
const sentry = config.sentryProxy;
|
||||
if (!sentry) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const pathPrefix = config.sentryProxyPath.replace(/\/+$/, '');
|
||||
let uri = `${pathPrefix}/api/${sentry.projectId}/security/?sentry_version=7`;
|
||||
|
||||
if (sentry.publicKey) {
|
||||
uri += `&sentry_key=${sentry.publicKey}`;
|
||||
}
|
||||
|
||||
if (config.sentryReportHost) {
|
||||
return config.sentryReportHost + uri;
|
||||
}
|
||||
|
||||
return uri;
|
||||
}
|
||||
|
||||
export function buildCSP(nonce: string, options?: CSPOptions): string {
|
||||
const defaultSrc = ["'self'", ...(options?.defaultSrc ?? [])];
|
||||
const scriptSrc = ["'self'", `'nonce-${nonce}'`, "'wasm-unsafe-eval'", ...(options?.scriptSrc ?? [])];
|
||||
const styleSrc = ["'self'", "'unsafe-inline'", ...(options?.styleSrc ?? [])];
|
||||
const imgSrc = ["'self'", 'blob:', 'data:', ...(options?.imgSrc ?? [])];
|
||||
const mediaSrc = ["'self'", 'blob:', ...(options?.mediaSrc ?? [])];
|
||||
const fontSrc = ["'self'", 'data:', ...(options?.fontSrc ?? [])];
|
||||
const connectSrc = ["'self'", 'data:', ...(options?.connectSrc ?? [])];
|
||||
const frameSrc = ["'self'", ...(options?.frameSrc ?? [])];
|
||||
const workerSrc = ["'self'", 'blob:', ...(options?.workerSrc ?? [])];
|
||||
const manifestSrc = ["'self'", ...(options?.manifestSrc ?? [])];
|
||||
|
||||
const directives = [
|
||||
`default-src ${defaultSrc.join(' ')}`,
|
||||
`script-src ${scriptSrc.join(' ')}`,
|
||||
`style-src ${styleSrc.join(' ')}`,
|
||||
`img-src ${imgSrc.join(' ')}`,
|
||||
`media-src ${mediaSrc.join(' ')}`,
|
||||
`font-src ${fontSrc.join(' ')}`,
|
||||
`connect-src ${connectSrc.join(' ')}`,
|
||||
`frame-src ${frameSrc.join(' ')}`,
|
||||
`worker-src ${workerSrc.join(' ')}`,
|
||||
`manifest-src ${manifestSrc.join(' ')}`,
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
];
|
||||
|
||||
if (options?.reportUri) {
|
||||
directives.push(`report-uri ${options.reportUri}`);
|
||||
}
|
||||
|
||||
return directives.join('; ');
|
||||
}
|
||||
|
||||
export function buildFluxerCSPOptions(config: SentryProxyConfig): CSPOptions {
|
||||
const reportURI = buildSentryReportURI(config);
|
||||
|
||||
return {
|
||||
scriptSrc: [...CSP_HOSTS.SCRIPT],
|
||||
styleSrc: [...CSP_HOSTS.STYLE],
|
||||
imgSrc: [...CSP_HOSTS.IMAGE],
|
||||
mediaSrc: [...CSP_HOSTS.MEDIA],
|
||||
fontSrc: [...CSP_HOSTS.FONT],
|
||||
connectSrc: [...CSP_HOSTS.CONNECT],
|
||||
frameSrc: [...CSP_HOSTS.FRAME],
|
||||
workerSrc: [...CSP_HOSTS.WORKER],
|
||||
manifestSrc: [...CSP_HOSTS.MANIFEST],
|
||||
reportUri: reportURI || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildFluxerCSP(nonce: string, config: SentryProxyConfig): string {
|
||||
return buildCSP(nonce, buildFluxerCSPOptions(config));
|
||||
}
|
||||
78
packages/app_proxy/src/app_server/utils/Mime.tsx
Normal file
78
packages/app_proxy/src/app_server/utils/Mime.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.htm': 'text/html; charset=utf-8',
|
||||
|
||||
'.js': 'application/javascript; charset=utf-8',
|
||||
'.mjs': 'application/javascript; charset=utf-8',
|
||||
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.avif': 'image/avif',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.eot': 'application/vnd.ms-fontobject',
|
||||
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.mp4': 'video/mp4',
|
||||
'.webm': 'video/webm',
|
||||
'.ogg': 'audio/ogg',
|
||||
'.wav': 'audio/wav',
|
||||
|
||||
'.pdf': 'application/pdf',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.xml': 'application/xml; charset=utf-8',
|
||||
|
||||
'.webmanifest': 'application/manifest+json',
|
||||
|
||||
'.map': 'application/json',
|
||||
|
||||
'.wasm': 'application/wasm',
|
||||
};
|
||||
|
||||
export function getMimeType(path: string): string {
|
||||
const ext = path.slice(path.lastIndexOf('.')).toLowerCase();
|
||||
return MIME_TYPES[ext] ?? 'application/octet-stream';
|
||||
}
|
||||
|
||||
export function isStaticAsset(path: string): boolean {
|
||||
const lastSlashIndex = path.lastIndexOf('/');
|
||||
const filename = lastSlashIndex >= 0 ? path.slice(lastSlashIndex + 1) : path;
|
||||
return filename.includes('.');
|
||||
}
|
||||
|
||||
export function isHashedAsset(path: string): boolean {
|
||||
const hashPattern = /\.[a-f0-9]{8,}\.(?:js|css|mjs|woff2?|ttf|eot|otf|png|jpg|jpeg|gif|webp|avif|svg)$/i;
|
||||
const hashPattern2 = /-[a-f0-9]{8,}\.(?:js|css|mjs|woff2?|ttf|eot|otf|png|jpg|jpeg|gif|webp|avif|svg)$/i;
|
||||
return hashPattern.test(path) || hashPattern2.test(path);
|
||||
}
|
||||
64
packages/app_proxy/src/app_server/utils/SentryDSN.tsx
Normal file
64
packages/app_proxy/src/app_server/utils/SentryDSN.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
export interface SentryDSN {
|
||||
projectId: string;
|
||||
publicKey: string;
|
||||
targetUrl: string;
|
||||
pathPrefix: string;
|
||||
}
|
||||
|
||||
export function parseSentryDSN(dsn: string | undefined): SentryDSN | null {
|
||||
if (!dsn?.trim()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(dsn.trim());
|
||||
|
||||
if (!parsed.protocol || !parsed.host) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pathPart = parsed.pathname.replace(/^\/+|\/+$/g, '');
|
||||
const segments = pathPart ? pathPart.split('/') : [];
|
||||
|
||||
if (segments.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const projectId = segments[segments.length - 1]!;
|
||||
const prefixSegments = segments.slice(0, -1);
|
||||
const pathPrefix = prefixSegments.length > 0 ? `/${prefixSegments.join('/')}` : '';
|
||||
|
||||
const publicKey = parsed.username;
|
||||
if (!publicKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
projectId,
|
||||
publicKey,
|
||||
targetUrl: `${parsed.protocol}//${parsed.host}`,
|
||||
pathPrefix,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
109
packages/app_proxy/src/app_server/utils/StaticFileUtils.tsx
Normal file
109
packages/app_proxy/src/app_server/utils/StaticFileUtils.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright (C) 2026 Fluxer Contributors
|
||||
*
|
||||
* This file is part of Fluxer.
|
||||
*
|
||||
* Fluxer is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Fluxer is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {existsSync, readFileSync} from 'node:fs';
|
||||
import {join} from 'node:path';
|
||||
import type {CSPOptions} from '@fluxer/app_proxy/src/app_server/utils/CSP';
|
||||
import {buildCSP, generateNonce} from '@fluxer/app_proxy/src/app_server/utils/CSP';
|
||||
import {getMimeType, isHashedAsset} from '@fluxer/app_proxy/src/app_server/utils/Mime';
|
||||
import type {Logger} from '@fluxer/logger/src/Logger';
|
||||
import type {Context} from 'hono';
|
||||
|
||||
export function isPathSafe(filePath: string, resolvedStaticDir: string): boolean {
|
||||
return filePath.startsWith(resolvedStaticDir);
|
||||
}
|
||||
|
||||
export interface ServeStaticFileOptions {
|
||||
requestPath: string;
|
||||
resolvedStaticDir: string;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
export type ServeStaticFileResult =
|
||||
| {success: true; content: Buffer; mimeType: string; cacheControl: string}
|
||||
| {success: false; error?: string};
|
||||
|
||||
export function serveStaticFile(options: ServeStaticFileOptions): ServeStaticFileResult {
|
||||
const {requestPath, resolvedStaticDir, logger} = options;
|
||||
const filePath = join(resolvedStaticDir, requestPath);
|
||||
|
||||
if (!isPathSafe(filePath, resolvedStaticDir)) {
|
||||
logger.warn({requestPath, filePath}, 'directory traversal attempt blocked');
|
||||
return {success: false};
|
||||
}
|
||||
|
||||
if (!existsSync(filePath)) {
|
||||
return {success: false};
|
||||
}
|
||||
|
||||
try {
|
||||
const content = readFileSync(filePath);
|
||||
const mimeType = getMimeType(requestPath);
|
||||
const cacheControl = isHashedAsset(requestPath)
|
||||
? 'public, max-age=31536000, immutable'
|
||||
: 'public, max-age=3600, must-revalidate';
|
||||
|
||||
return {success: true, content, mimeType, cacheControl};
|
||||
} catch (err) {
|
||||
logger.error({requestPath, error: err}, 'failed to read static file');
|
||||
return {success: false, error: 'Internal Server Error'};
|
||||
}
|
||||
}
|
||||
|
||||
export interface ServeSpaFallbackOptions {
|
||||
resolvedStaticDir: string;
|
||||
cspDirectives?: CSPOptions;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
export type ServeSpaFallbackResult =
|
||||
| {success: true; content: string; nonce: string; csp: string}
|
||||
| {success: false; error: string};
|
||||
|
||||
export function serveSpaFallback(options: ServeSpaFallbackOptions): ServeSpaFallbackResult {
|
||||
const {resolvedStaticDir, cspDirectives, logger} = options;
|
||||
const indexPath = join(resolvedStaticDir, 'index.html');
|
||||
|
||||
if (!existsSync(indexPath)) {
|
||||
logger.error({path: indexPath}, 'index.html not found');
|
||||
return {success: false, error: 'Internal Server Error'};
|
||||
}
|
||||
|
||||
try {
|
||||
const nonce = generateNonce();
|
||||
const csp = buildCSP(nonce, cspDirectives);
|
||||
|
||||
let indexContent = readFileSync(indexPath, 'utf-8');
|
||||
indexContent = indexContent.replaceAll('{{CSP_NONCE_PLACEHOLDER}}', nonce);
|
||||
|
||||
return {success: true, content: indexContent, nonce, csp};
|
||||
} catch (err) {
|
||||
logger.error({error: err}, 'failed to serve index.html');
|
||||
return {success: false, error: 'Internal Server Error'};
|
||||
}
|
||||
}
|
||||
|
||||
export function applySpaHeaders(c: Context, csp: string): void {
|
||||
c.header('Content-Security-Policy', csp);
|
||||
c.header('Content-Type', 'text/html; charset=utf-8');
|
||||
c.header('Cache-Control', 'no-cache');
|
||||
c.header('X-Content-Type-Options', 'nosniff');
|
||||
c.header('X-Frame-Options', 'DENY');
|
||||
c.header('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
}
|
||||
Reference in New Issue
Block a user