Fix bugs: EISDIR on getImageFile, parseInt nullish fallback, api 404 handler, and docker environment

This commit is contained in:
Jannik committed 2026-10-31 15:41:27 +01:00
1 parent 4ee4de14ee
commit a784d7e37f
11 files changed
+147 -31

No files matched your search

+1 -1
View File
@@ -65,7 +65,7 @@ DB_PASSWORD=solus
# KI Provider
MINIMAX_API_KEY=dein_minimax_key
MINIMAX_MODEL=MiniMax-M2.5
MINIMAX_MODEL=MiniMax-M3
# Alternative Provider (OpenAI, OpenRouter, Gemini, Anthropic, LiteLLM)
# AI_PROVIDER=openrouter
+4
View File
@@ -15,6 +15,10 @@ services:
- DB_NAME=solus
- DB_USER=solus
- DB_PASSWORD=solus
- ADMIN_TOKEN=${ADMIN_TOKEN:-}
- CORS_ORIGINS=${CORS_ORIGINS:-}
- RATE_LIMIT_MAX=${RATE_LIMIT_MAX:-300}
- ADMIN_RATE_MAX=${ADMIN_RATE_MAX:-60}
- MINIMAX_API_KEY=${MINIMAX_API_KEY:-}
- MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3}
- AI_PROVIDER=${AI_PROVIDER:-minimax}
+20 -2
View File
@@ -3,10 +3,11 @@ import globals from 'globals';
export default [
{
ignores: ['node_modules/**', 'uploads/**', 'dist/**', '.wrangler/**', 'public/**'],
ignores: ['node_modules/**', 'uploads/**', 'dist/**', '.wrangler/**'],
},
js.configs.recommended,
{
files: ['src/**', 'tests/**'],
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
@@ -16,7 +17,24 @@ export default [
},
rules: {
'no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
'no-undef': 'off',
'no-undef': 'error',
'no-console': 'off',
eqeqeq: ['error', 'smart'],
'no-empty': ['error', { allowEmptyCatch: true }],
},
},
{
files: ['public/**'],
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
globals: {
...globals.browser,
},
},
rules: {
'no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
'no-undef': 'error',
'no-console': 'off',
eqeqeq: ['error', 'smart'],
'no-empty': ['error', { allowEmptyCatch: true }],
+12 -8
View File
@@ -207,13 +207,16 @@ export async function getChars(options = {}) {
? 'SELECT * FROM characters ORDER BY created_at ASC;'
: 'SELECT * FROM characters WHERE is_banned = 0 ORDER BY created_at ASC;';
const res = await pool.query(query);
return res.rows.map((r) => ({
...r,
gender: r.gender || 'unspecified',
is_banned: r.is_banned ? 1 : 0,
hobbies: Array.isArray(r.hobbies) ? r.hobbies : safeJson(r.hobbies, []),
system_prompt: r.system_prompt || '',
}));
return res.rows.map((r) => {
const rawHobbies = Array.isArray(r.hobbies) ? r.hobbies : safeJson(r.hobbies, []);
return {
...r,
gender: r.gender || 'unspecified',
is_banned: r.is_banned ? 1 : 0,
hobbies: Array.isArray(rawHobbies) ? rawHobbies : [],
system_prompt: r.system_prompt || '',
};
});
}
export async function banCharacter(id, banned = true) {
@@ -410,10 +413,11 @@ export async function updateCharacter(id, fields) {
const res = await pool.query(q, values);
if (!res.rows.length) return null;
const r = res.rows[0];
const rawHobbies = Array.isArray(r.hobbies) ? r.hobbies : safeJson(r.hobbies, []);
return {
...r,
isBanned: r.is_banned === 1,
hobbies: Array.isArray(r.hobbies) ? r.hobbies : safeJson(r.hobbies, []),
hobbies: Array.isArray(rawHobbies) ? rawHobbies : [],
};
}
+27 -11
View File
@@ -19,8 +19,10 @@ export async function reactToUserPost(post, chars) {
const targetCount = minReact + Math.floor(Math.random() * (maxReact - minReact + 1));
const participants = pick(chars, targetCount);
const likeChance = (parseInt(settings.user_post_like_chance, 10) ?? 70) / 100;
const dmChance = (parseInt(settings.proactive_dm_post_chance, 10) ?? 65) / 100;
const rawLike = parseInt(settings.user_post_like_chance, 10);
const likeChance = (Number.isFinite(rawLike) ? rawLike : 70) / 100;
const rawDm = parseInt(settings.proactive_dm_post_chance, 10);
const dmChance = (Number.isFinite(rawDm) ? rawDm : 65) / 100;
const worldLang = settings.world_language || 'mixed';
for (const c of participants) {
@@ -74,8 +76,10 @@ export async function charactersEngageEachOther(post, author, chars) {
if (!others.length) return;
const settings = await getAllSettings().catch(() => ({}));
const minCom = parseInt(settings.bot_to_bot_comments_min, 10) ?? 1;
const maxCom = parseInt(settings.bot_to_bot_comments_max, 10) ?? 2;
const rawMinCom = parseInt(settings.bot_to_bot_comments_min, 10);
const minCom = Number.isFinite(rawMinCom) ? rawMinCom : 1;
const rawMaxCom = parseInt(settings.bot_to_bot_comments_max, 10);
const maxCom = Number.isFinite(rawMaxCom) ? rawMaxCom : 2;
if (maxCom <= 0) return; // Disabled
const count = Math.max(1, minCom + Math.floor(Math.random() * (maxCom - minCom + 1)));
@@ -113,12 +117,15 @@ export async function charactersEngageEachOther(post, author, chars) {
// Characters comment on a user's comment (reply-chain under a post).
export async function charsReplyToUserComment(comment, post, chars) {
const settings = await getAllSettings().catch(() => ({}));
const minCom = parseInt(settings.bot_to_bot_comments_min, 10) ?? 1;
const maxCom = parseInt(settings.bot_to_bot_comments_max, 10) ?? 2;
const rawMinCom = parseInt(settings.bot_to_bot_comments_min, 10);
const minCom = Number.isFinite(rawMinCom) ? rawMinCom : 1;
const rawMaxCom = parseInt(settings.bot_to_bot_comments_max, 10);
const maxCom = Number.isFinite(rawMaxCom) ? rawMaxCom : 2;
const count = Math.max(1, minCom + Math.floor(Math.random() * (maxCom - minCom + 1)));
const participants = pick(chars, count);
const worldLang = settings.world_language || 'mixed';
const dmChance = (parseInt(settings.proactive_dm_comment_chance, 10) ?? 35) / 100;
const rawDmChance = parseInt(settings.proactive_dm_comment_chance, 10);
const dmChance = (Number.isFinite(rawDmChance) ? rawDmChance : 35) / 100;
for (const c of participants) {
try {
@@ -204,7 +211,8 @@ export async function genCharPost(char) {
if (!char || char.is_banned) return null;
const settings = await getAllSettings().catch(() => ({}));
const imagesEnabled = settings.bot_images_enabled !== '0';
const imgChance = (parseInt(settings.bot_image_chance, 10) ?? 35) / 100;
const rawImgChance = parseInt(settings.bot_image_chance, 10);
const imgChance = (Number.isFinite(rawImgChance) ? rawImgChance : 35) / 100;
const wantImage = imagesEnabled && Math.random() < imgChance;
const worldLang = settings.world_language || 'mixed';
@@ -257,7 +265,7 @@ export async function genCharPost(char) {
}
let imageKey = null;
const m = text.match(/\[BILD:\s*(.+?)\]/);
const m = text.match(/\[BILD:\s*([\s\S]+?)\]/);
if (m && imagesEnabled) {
try {
imageKey = await genImage(null, m[1], '1:1');
@@ -293,7 +301,11 @@ export async function updateBotAvatarAutonomously(char, chars = []) {
const isEn = worldLang === 'en' || (worldLang === 'mixed' && char.language === 'en');
try {
const hobbiesStr = (char.hobbies || []).join(', ');
const hobbiesStr = Array.isArray(char.hobbies)
? char.hobbies.join(', ')
: typeof char.hobbies === 'string'
? char.hobbies
: '';
const avatarPrompt = `natural close-up portrait photo of ${char.name}, ${char.bio || ''}, interests: ${hobbiesStr}, fashionable candid profile picture, selfie style, natural daylight, 8k`;
const newAvatarKey = await genImage(null, avatarPrompt, '1:1');
@@ -401,7 +413,11 @@ export async function triggerCharPhotoPost(char, chars = []) {
text = text.replace(m[0], '').trim();
} else {
try {
const hobbiesStr = (char.hobbies || []).join(', ');
const hobbiesStr = Array.isArray(char.hobbies)
? char.hobbies.join(', ')
: typeof char.hobbies === 'string'
? char.hobbies
: '';
imageKey = await genImage(
null,
`authentic photo taken by ${char.name}, related to ${char.bio || ''}, ${hobbiesStr}, aesthetic composition, realistic`,
+9 -2
View File
@@ -1,5 +1,5 @@
// Local filesystem image storage for Solus
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync } from 'node:fs';
import { extname, join, resolve, sep } from 'node:path';
import { uid } from './db.js';
@@ -19,10 +19,17 @@ export function saveImageBuffer(buffer, contentType = 'image/jpeg') {
}
export function getImageFile(key) {
if (typeof key !== 'string' || !key.trim()) return null;
const cleanKey = key.replace(/^img\//, '').replace(/[^a-zA-Z0-9._-]/g, '');
if (!cleanKey || cleanKey === '.' || cleanKey === '..') return null;
const filepath = resolve(join(UPLOAD_DIR, cleanKey));
if (filepath !== UPLOAD_DIR && !filepath.startsWith(UPLOAD_DIR + sep)) return null;
if (!filepath.startsWith(UPLOAD_DIR + sep)) return null;
if (!existsSync(filepath)) return null;
try {
if (!statSync(filepath).isFile()) return null;
} catch {
return null;
}
const ext = extname(filepath).toLowerCase();
const contentType =
+9 -3
View File
@@ -767,7 +767,8 @@ app.post('/api/feed-tick', async (c) => {
}
const settings = await getAllSettings().catch(() => ({}));
const intervalMin = parseInt(settings.feed_tick_interval_min, 10) ?? 20;
const rawInterval = parseInt(settings.feed_tick_interval_min, 10);
const intervalMin = Number.isFinite(rawInterval) ? rawInterval : 20;
if (!body?.manual && intervalMin <= 0) {
return c.json({ generated: false, reason: 'disabled' });
}
@@ -786,8 +787,10 @@ app.post('/api/feed-tick', async (c) => {
Math.max(1, parseInt(settings.feed_tick_posts_count, 10) || 1),
parseInt(process.env.FEED_TICK_MAX_POSTS, 10) || 10
);
const tickDmChance = (parseInt(settings.proactive_dm_tick_chance, 10) ?? 35) / 100;
const avatarChangeChance = (parseInt(settings.bot_avatar_update_chance, 10) ?? 15) / 100;
const rawTickDm = parseInt(settings.proactive_dm_tick_chance, 10);
const tickDmChance = (Number.isFinite(rawTickDm) ? rawTickDm : 35) / 100;
const rawAvatarChange = parseInt(settings.bot_avatar_update_chance, 10);
const avatarChangeChance = (Number.isFinite(rawAvatarChange) ? rawAvatarChange : 15) / 100;
const avatarChangeEnabled = settings.bot_avatar_update_enabled !== '0';
if (body?.manual) {
@@ -1221,4 +1224,7 @@ app.delete('/api/admin/posts/:id', async (c) => {
return c.json({ ok: true });
});
// Fallback for unmatched API routes (returns JSON 404 instead of falling through to SPA HTML)
app.all('/api/*', (c) => c.json({ error: 'Route nicht gefunden' }, 404));
export default app;
+10 -2
View File
@@ -223,7 +223,11 @@ export function personaSystemPrompt(char, extra = '', overrideLang = null) {
const effectiveLang = overrideLang && overrideLang !== 'mixed' ? overrideLang : char.language;
const isEn = effectiveLang === 'en';
const lang = isEn ? 'You ALWAYS reply in natural English.' : 'Du antwortest IMMER auf Deutsch.';
const hobbies = (char.hobbies || []).join(', ');
const hobbies = Array.isArray(char.hobbies)
? char.hobbies.join(', ')
: typeof char.hobbies === 'string'
? char.hobbies
: '';
const rules =
'Regeln: Bleibe IMMER voll in deiner Rolle. Schreibe wie ein echter Mensch in einer Social-Media-App – nie wie ein Assistent. Keine Listen, kein "Als KI…", keine Erklärungen darüber, dass du eine KI bist. Schreib wie auf einer echten Plattform.';
@@ -280,7 +284,11 @@ export function personaSystemPrompt(char, extra = '', overrideLang = null) {
}
export function buildDefaultSystemPrompt(char) {
const hobbies = (char.hobbies || []).join(', ');
const hobbies = Array.isArray(char.hobbies)
? char.hobbies.join(', ')
: typeof char.hobbies === 'string'
? char.hobbies
: '';
const genderDesc =
char.gender === 'female'
? 'Geschlecht: weiblich (sie/ihr)'
+4 -2
View File
@@ -75,7 +75,8 @@ function startBackgroundSimulation() {
await import('./engagement.js');
const settings = await getAllSettings().catch(() => ({}));
const intervalMin = parseInt(settings.feed_tick_interval_min, 10) ?? 20;
const rawInterval = parseInt(settings.feed_tick_interval_min, 10);
const intervalMin = Number.isFinite(rawInterval) ? rawInterval : 20;
if (intervalMin <= 0) return; // Background simulation disabled by setting
const lastTick = Number(await getState('last_feed_tick', '0'));
@@ -158,7 +159,8 @@ function startBackgroundSimulation() {
}
await setState('last_feed_tick', String(now));
const tickDmChance = (parseInt(settings.proactive_dm_tick_chance, 10) ?? 35) / 100;
const rawTickDm = parseInt(settings.proactive_dm_tick_chance, 10);
const tickDmChance = (Number.isFinite(rawTickDm) ? rawTickDm : 35) / 100;
if (Math.random() < tickDmChance) {
const activeChar = chars[Math.floor(Math.random() * chars.length)];
await sendProactiveDM(
+19
View File
@@ -0,0 +1,19 @@
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { app } from '../src/index.js';
describe('API routes integration', () => {
test('GET /healthz returns 200 and healthy JSON', async () => {
const res = await app.request('/healthz');
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.ok, true);
assert.equal(body.service, 'solus');
});
test('GET /api/admin/status rejects with 401 without token (before DB init)', async () => {
delete process.env.ADMIN_TOKEN;
const res = await app.request('/api/admin/status');
assert.equal(res.status, 401);
});
});
+32
View File
@@ -0,0 +1,32 @@
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { getImageFile, saveImageBuffer } from '../src/images.js';
describe('images storage', () => {
test('getImageFile returns null on empty, invalid, or traversal keys', () => {
assert.equal(getImageFile(''), null);
assert.equal(getImageFile(' '), null);
assert.equal(getImageFile(null), null);
assert.equal(getImageFile(undefined), null);
assert.equal(getImageFile('img/'), null);
assert.equal(getImageFile('.'), null);
assert.equal(getImageFile('..'), null);
assert.equal(getImageFile('img/..'), null);
assert.equal(getImageFile('img/.'), null);
assert.equal(getImageFile('../../../etc/passwd'), null);
assert.equal(getImageFile('non_existent_image_12345.png'), null);
});
test('saveImageBuffer stores image and getImageFile reads it back', () => {
const testData = Buffer.from('test-image-content-solus');
const key = saveImageBuffer(testData, 'image/png');
assert.ok(key, 'Key should be generated');
assert.ok(key.startsWith('img/'), 'Key should start with img/');
assert.ok(key.endsWith('.png'), 'Key should end with .png');
const retrieved = getImageFile(key);
assert.ok(retrieved, 'Should retrieve image');
assert.equal(retrieved.contentType, 'image/png');
assert.equal(Buffer.from(retrieved.data).toString(), 'test-image-content-solus');
});
});