feat(ui): add structured JSON logging to all server-side routes and lib

Introduces a logger.ts module emitting slog-compatible JSON lines to stderr.
Replaces silent catch blocks and console.error calls throughout minio.ts,
pocketbase.ts, hooks.server.ts, login, books, browse, and all API routes so
auth/registration failures, MinIO presign errors, and scraper proxy failures
are now visible in container logs.
This commit is contained in:
Admin
2026-03-03 14:34:48 +05:00
parent 5131ae0bc4
commit bf5774d8d0
13 changed files with 188 additions and 37 deletions

View File

@@ -5,6 +5,7 @@
*/
import { env } from '$env/dynamic/private';
import { log } from '$lib/server/logger';
const PB_URL = env.POCKETBASE_URL ?? 'http://localhost:8090';
const PB_EMAIL = env.POCKETBASE_ADMIN_EMAIL ?? 'admin@libnovel.local';
@@ -58,6 +59,8 @@ let _tokenExp = 0;
async function getToken(): Promise<string> {
if (_token && Date.now() < _tokenExp) return _token;
log.debug('pocketbase', 'authenticating with admin credentials', { url: PB_URL, email: PB_EMAIL });
const res = await fetch(`${PB_URL}/api/admins/auth-with-password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -65,12 +68,15 @@ async function getToken(): Promise<string> {
});
if (!res.ok) {
throw new Error(`PocketBase auth failed: ${res.status}`);
const body = await res.text().catch(() => '');
log.error('pocketbase', 'admin auth failed', { status: res.status, url: PB_URL, body });
throw new Error(`PocketBase auth failed: ${res.status}${body}`);
}
const data = await res.json();
_token = data.token as string;
_tokenExp = Date.now() + 12 * 60 * 60 * 1000; // 12 hours
log.info('pocketbase', 'admin auth token refreshed', { url: PB_URL });
return _token;
}
@@ -81,7 +87,11 @@ async function pbGet<T>(path: string): Promise<T> {
const res = await fetch(`${PB_URL}${path}`, {
headers: { Authorization: token }
});
if (!res.ok) throw new Error(`PocketBase GET ${path} failed: ${res.status}`);
if (!res.ok) {
const body = await res.text().catch(() => '');
log.error('pocketbase', 'GET failed', { path, status: res.status, body });
throw new Error(`PocketBase GET ${path} failed: ${res.status}${body}`);
}
return res.json() as Promise<T>;
}
@@ -103,10 +113,6 @@ async function pbPatch(path: string, body: unknown): Promise<Response> {
});
}
function encodeFilter(filter: string) {
return encodeURIComponent(filter);
}
interface PBList<T> {
items: T[];
totalItems: number;
@@ -170,9 +176,17 @@ export async function setProgress(sessionId: string, slug: string, chapter: numb
};
if (existing) {
await pbPatch(`/api/collections/progress/records/${existing.id}`, payload);
const res = await pbPatch(`/api/collections/progress/records/${existing.id}`, payload);
if (!res.ok) {
const body = await res.text().catch(() => '');
log.error('pocketbase', 'setProgress PATCH failed', { slug, chapter, status: res.status, body });
}
} else {
await pbPost('/api/collections/progress/records', payload);
const res = await pbPost('/api/collections/progress/records', payload);
if (!res.ok) {
const body = await res.text().catch(() => '');
log.error('pocketbase', 'setProgress POST failed', { slug, chapter, status: res.status, body });
}
}
}
@@ -206,11 +220,14 @@ export async function getUserByUsername(username: string): Promise<User | null>
* Create a new user with a hashed password. Throws if username already exists.
*/
export async function createUser(username: string, password: string, role = 'user'): Promise<User> {
log.info('pocketbase', 'createUser: checking for existing username', { username });
const existing = await getUserByUsername(username);
if (existing) {
log.warn('pocketbase', 'createUser: username already taken', { username });
throw new Error('Username already taken');
}
const password_hash = hashPassword(password);
log.info('pocketbase', 'createUser: inserting new user', { username, role });
const res = await pbPost('/api/collections/users/records', {
username,
password_hash,
@@ -218,21 +235,33 @@ export async function createUser(username: string, password: string, role = 'use
created: new Date().toISOString()
});
if (!res.ok) {
const body = await res.text();
const body = await res.text().catch(() => '');
log.error('pocketbase', 'createUser: PocketBase rejected record', {
username,
status: res.status,
body
});
throw new Error(`Failed to create user: ${res.status} ${body}`);
}
log.info('pocketbase', 'createUser: user created', { username, role });
return res.json() as Promise<User>;
}
/**
* Verify username + password. Returns the user on success, null on failure.
*/
export async function loginUser(
username: string,
password: string
): Promise<User | null> {
export async function loginUser(username: string, password: string): Promise<User | null> {
log.debug('pocketbase', 'loginUser: lookup', { username });
const user = await getUserByUsername(username);
if (!user) return null;
if (!verifyPassword(password, user.password_hash)) return null;
if (!user) {
log.warn('pocketbase', 'loginUser: username not found', { username });
return null;
}
const ok = verifyPassword(password, user.password_hash);
if (!ok) {
log.warn('pocketbase', 'loginUser: wrong password', { username });
return null;
}
log.info('pocketbase', 'loginUser: success', { username, role: user.role });
return user;
}