mirror of
https://github.com/whyour/qinglong.git
synced 2026-08-06 00:34:33 +08:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 855f591992 | |||
| d30eb2008c | |||
| e1ce0f3fa9 | |||
| 82514e65e1 | |||
| 31261190f0 |
@@ -206,6 +206,7 @@ export default (app: Router) => {
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let { filename, content, path } = req.body as {
|
||||
filename: string;
|
||||
@@ -223,6 +224,7 @@ export default (app: Router) => {
|
||||
await writeFileWithLock(filePath, content);
|
||||
return res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error saving script: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
|
||||
+5
-34
@@ -13,29 +13,9 @@ import { isValidToken } from '../shared/auth';
|
||||
import path from 'path';
|
||||
|
||||
export default ({ app }: { app: Application }) => {
|
||||
// Security: Enable strict routing to prevent case-insensitive path bypass
|
||||
app.set('case sensitive routing', true);
|
||||
app.set('strict routing', true);
|
||||
app.set('trust proxy', 'loopback');
|
||||
app.use(cors());
|
||||
|
||||
// Security: Path normalization middleware to prevent case variation attacks
|
||||
app.use((req, res, next) => {
|
||||
const originalPath = req.path;
|
||||
const normalizedPath = originalPath.toLowerCase();
|
||||
|
||||
// Block requests with case variations on protected paths
|
||||
if (originalPath !== normalizedPath &&
|
||||
(normalizedPath.startsWith('/api/') || normalizedPath.startsWith('/open/'))) {
|
||||
return res.status(400).json({
|
||||
code: 400,
|
||||
message: 'Invalid path format'
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
// Rewrite URLs to strip baseUrl prefix if configured
|
||||
// This allows the rest of the app to work without baseUrl awareness
|
||||
if (config.baseUrl) {
|
||||
@@ -56,7 +36,7 @@ export default ({ app }: { app: Application }) => {
|
||||
secret: config.jwt.secret,
|
||||
algorithms: ['HS384'],
|
||||
}).unless({
|
||||
path: [...config.apiWhiteList, /^(\/(?!api\/).*)$/i],
|
||||
path: [...config.apiWhiteList, /^\/(?!api\/).*/],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -71,20 +51,19 @@ export default ({ app }: { app: Application }) => {
|
||||
});
|
||||
|
||||
app.use(async (req: Request, res, next) => {
|
||||
const pathLower = req.path.toLowerCase();
|
||||
if (!['/open/', '/api/'].some((x) => pathLower.startsWith(x))) {
|
||||
if (!['/open/', '/api/'].some((x) => req.path.startsWith(x))) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const headerToken = getToken(req);
|
||||
if (pathLower.startsWith('/open/')) {
|
||||
if (req.path.startsWith('/open/')) {
|
||||
const apps = await shareStore.getApps();
|
||||
const doc = apps?.filter((x) =>
|
||||
x.tokens?.find((y) => y.value === headerToken),
|
||||
)?.[0];
|
||||
if (doc && doc.tokens && doc.tokens.length > 0) {
|
||||
const currentToken = doc.tokens.find((x) => x.value === headerToken);
|
||||
const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/);
|
||||
const keyMatch = req.path.match(/\/open\/([a-z]+)\/*/);
|
||||
const key = keyMatch && keyMatch[1];
|
||||
if (
|
||||
doc.scopes.includes(key as any) &&
|
||||
@@ -119,15 +98,7 @@ export default ({ app }: { app: Application }) => {
|
||||
});
|
||||
|
||||
app.use(async (req, res, next) => {
|
||||
const pathLower = req.path.toLowerCase();
|
||||
if (
|
||||
![
|
||||
'/api/user/init',
|
||||
'/api/user/notification/init',
|
||||
'/open/user/init',
|
||||
'/open/user/notification/init',
|
||||
].includes(req.path)
|
||||
) {
|
||||
if (!['/api/user/init', '/api/user/notification/init'].includes(req.path)) {
|
||||
return next();
|
||||
}
|
||||
const authInfo =
|
||||
|
||||
@@ -16,6 +16,17 @@ export class HttpServerService {
|
||||
metricsService.record('http_service_start', 1, {
|
||||
port: port.toString(),
|
||||
});
|
||||
|
||||
// Set server timeouts to prevent premature connection drops
|
||||
if (this.server) {
|
||||
// Timeout for receiving the entire request (including body) - 5 minutes
|
||||
this.server.requestTimeout = 300000;
|
||||
// Timeout for headers - 2 minutes
|
||||
this.server.headersTimeout = 120000;
|
||||
// Keep-alive timeout - 65 seconds (slightly more than typical load balancer timeout)
|
||||
this.server.keepAliveTimeout = 65000;
|
||||
}
|
||||
|
||||
resolve(this.server);
|
||||
});
|
||||
|
||||
|
||||
+54
-16
@@ -1,8 +1,9 @@
|
||||
import { lock } from 'proper-lockfile';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { writeFile, open, chmod } from 'fs/promises';
|
||||
import { writeFile, open, chmod, FileHandle } from 'fs/promises';
|
||||
import { fileExist } from '../config/util';
|
||||
import Logger from '../loaders/logger';
|
||||
|
||||
function getUniqueLockPath(filePath: string) {
|
||||
const sanitizedPath = filePath
|
||||
@@ -19,24 +20,61 @@ export async function writeFileWithLock(
|
||||
if (typeof options === 'string') {
|
||||
options = { encoding: options };
|
||||
}
|
||||
|
||||
// Ensure file exists before locking
|
||||
if (!(await fileExist(filePath))) {
|
||||
const fileHandle = await open(filePath, 'w');
|
||||
fileHandle.close();
|
||||
let fileHandle: FileHandle | undefined;
|
||||
try {
|
||||
fileHandle = await open(filePath, 'w');
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to create file ${filePath}: ${errorMessage}`);
|
||||
} finally {
|
||||
if (fileHandle !== undefined) {
|
||||
try {
|
||||
await fileHandle.close();
|
||||
} catch (closeError) {
|
||||
// Log close error but don't throw to avoid masking the original error
|
||||
Logger.error(`Failed to close file handle for ${filePath}:`, closeError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const lockfilePath = getUniqueLockPath(filePath);
|
||||
let release: (() => Promise<void>) | undefined;
|
||||
|
||||
const release = await lock(filePath, {
|
||||
retries: {
|
||||
retries: 10,
|
||||
factor: 2,
|
||||
minTimeout: 100,
|
||||
maxTimeout: 3000,
|
||||
},
|
||||
lockfilePath,
|
||||
});
|
||||
await writeFile(filePath, content, { encoding: 'utf8', ...options });
|
||||
if (options?.mode) {
|
||||
await chmod(filePath, options.mode);
|
||||
try {
|
||||
release = await lock(filePath, {
|
||||
retries: {
|
||||
retries: 10,
|
||||
factor: 2,
|
||||
minTimeout: 100,
|
||||
maxTimeout: 3000,
|
||||
},
|
||||
lockfilePath,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to acquire lock for ${filePath}: ${errorMessage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
await writeFile(filePath, content, { encoding: 'utf8', ...options });
|
||||
if (options?.mode) {
|
||||
await chmod(filePath, options.mode);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to write to file ${filePath}: ${errorMessage}`);
|
||||
} finally {
|
||||
if (release) {
|
||||
try {
|
||||
await release();
|
||||
} catch (error) {
|
||||
// Log but don't throw on release failure
|
||||
Logger.error(`Failed to release lock for ${filePath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
await release();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user