fix: harden authentication and file access security

This commit is contained in:
whyour
2026-09-05 18:19:01 +08:00
parent be2580d0e8
commit 4df52094f2
26 changed files with 1165 additions and 99 deletions
+18 -6
View File
@@ -1,11 +1,8 @@
import { AuthInfo, TokenInfo } from '../data/system';
import jwt from 'jsonwebtoken';
export function isDefaultAuthInfo(authInfo: AuthInfo): boolean {
return (
Object.keys(authInfo).length === 2 &&
authInfo.username === 'admin' &&
authInfo.password === 'admin'
);
return authInfo.username === 'admin' && authInfo.password === 'admin';
}
/**
@@ -21,11 +18,21 @@ export function isValidToken(
authInfo: AuthInfo | null | undefined,
headerToken: string,
platform: string,
secret: string,
): boolean {
if (!authInfo || !headerToken) {
return false;
}
try {
const claims = jwt.verify(headerToken, secret, { algorithms: ['HS384'] });
if (typeof claims === 'string' || typeof claims.exp !== 'number') {
return false;
}
} catch {
return false;
}
const { token = '', tokens = {} } = authInfo;
// Check legacy token field
@@ -46,7 +53,12 @@ export function isValidToken(
return headerToken === platformTokens;
} else if (Array.isArray(platformTokens)) {
// New format: array of TokenInfo objects
return platformTokens.some((t: TokenInfo) => t && t.value === headerToken);
return platformTokens.some(
(t: TokenInfo) =>
t &&
t.value === headerToken &&
(t.expiration === undefined || t.expiration > Date.now() / 1000),
);
}
// Unexpected type - log warning and reject
+17
View File
@@ -0,0 +1,17 @@
// All account mutations in the HTTP service share one queue. In particular,
// a login that read old credentials must finish before a password reset revokes
// its session, and two initialization requests must not both claim the account.
let pending: Promise<unknown> = Promise.resolve();
export function serializeAuthMutation(
_target: object,
_key: string,
descriptor: PropertyDescriptor,
) {
const method = descriptor.value;
descriptor.value = function (this: unknown, ...args: unknown[]) {
const result = pending.then(() => method.apply(this, args));
pending = result.catch(() => undefined);
return result;
};
}
+57
View File
@@ -0,0 +1,57 @@
import fs from 'fs';
import path from 'path';
function isWithin(root: string, target: string): boolean {
const relative = path.relative(root, target);
return (
relative === '' ||
(!relative.startsWith(`..${path.sep}`) &&
relative !== '..' &&
!path.isAbsolute(relative))
);
}
/** Resolve existing files and not-yet-created children without following an
* existing symlink outside the root. Blacklisted directories cover descendants. */
export function resolveFileAccess(
root: string,
parts: string[],
blacklist: string[] = [],
): string {
if (parts.some((part) => typeof part !== 'string' || part.includes('\0'))) {
return '';
}
const resolvedRoot = path.resolve(root);
const target = path.resolve(resolvedRoot, ...parts);
if (target === resolvedRoot || !isWithin(resolvedRoot, target)) return '';
const isBlocked = (relative: string) =>
relative.split(path.sep).some((part) => blacklist.includes(part));
if (isBlocked(path.relative(resolvedRoot, target))) return '';
try {
const realRoot = fs.realpathSync(resolvedRoot);
let existing = target;
const missing: string[] = [];
while (!fs.existsSync(existing)) {
// existsSync is false for a dangling symlink; never treat one as absent.
try {
fs.lstatSync(existing);
return '';
} catch (error: any) {
if (error.code !== 'ENOENT') return '';
}
if (existing === resolvedRoot) return '';
missing.unshift(path.basename(existing));
existing = path.dirname(existing);
}
const realTarget = path.resolve(fs.realpathSync(existing), ...missing);
if (
!isWithin(realRoot, realTarget) ||
isBlocked(path.relative(realRoot, realTarget))
) {
return '';
}
return target;
} catch {
return '';
}
}
+30
View File
@@ -0,0 +1,30 @@
import { randomBytes, scrypt, timingSafeEqual } from 'crypto';
import { promisify } from 'util';
const deriveKey = promisify(scrypt);
const HASH_PREFIX = 'scrypt$';
export async function hashPassword(password: string): Promise<string> {
const salt = randomBytes(16).toString('hex');
const key = (await deriveKey(password, salt, 64)) as Buffer;
return `${HASH_PREFIX}${salt}$${key.toString('hex')}`;
}
export function isPasswordHash(password: string): boolean {
return /^scrypt\$[a-f0-9]{32}\$[a-f0-9]{128}$/.test(password);
}
export async function verifyPassword(
password: string,
stored: string,
): Promise<boolean> {
if (!isPasswordHash(stored)) {
// Existing installations migrate after a successful password check.
const input = Buffer.from(password);
const expected = Buffer.from(stored);
return input.length === expected.length && timingSafeEqual(input, expected);
}
const [, salt, hash] = stored.split('$');
const key = (await deriveKey(password, salt, 64)) as Buffer;
return timingSafeEqual(key, Buffer.from(hash, 'hex'));
}