The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
v2.5.0 B4: structured logger with key-substring redaction
purplec6a1a00c68c3
diff --git a/src/lib/__tests__/logger.test.ts b/src/lib/__tests__/logger.test.tsnew file mode 100644index 00000000..04870e19--- /dev/null+++ b/src/lib/__tests__/logger.test.ts@@ -0,0 +1,108 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { log, _scrubForTest } from '../logger'++describe('logger scrubber', () => {+ it('redacts top-level secret-like keys', () => {+ const r = _scrubForTest({+ ok: 1,+ password: 'p',+ apiKey: 'k',+ api_key: 'k',+ authorization: 'Bearer x',+ cookie: 'c',+ service_role: 'srv',+ private_key: 'pk',+ token: 't',+ }) as Record<string, unknown>+ expect(r.ok).toBe(1)+ for (const k of [+ 'password',+ 'apiKey',+ 'api_key',+ 'authorization',+ 'cookie',+ 'service_role',+ 'private_key',+ 'token',+ ]) {+ expect(r[k]).toBe('[REDACTED]')+ }+ })++ it('recurses into nested objects', () => {+ const r = _scrubForTest({+ user: { id: 'u', authorization: 'Bearer x' },+ }) as { user: { id: string; authorization: string } }+ expect(r.user.id).toBe('u')+ expect(r.user.authorization).toBe('[REDACTED]')+ })++ it('walks arrays without losing them', () => {+ const r = _scrubForTest({ items: [{ password: 'p' }, { ok: 1 }] }) as {+ items: Array<Record<string, unknown>>+ }+ expect(r.items[0].password).toBe('[REDACTED]')+ expect(r.items[1].ok).toBe(1)+ })++ it('caps recursion depth so cyclic-but-bounded input still scrubs', () => {+ let deep: Record<string, unknown> = { password: 'p' }+ for (let i = 0; i < 20; i++) deep = { next: deep }+ const r = _scrubForTest(deep)+ expect(JSON.stringify(r)).toBeTruthy()+ })++ it('passes through primitives unchanged', () => {+ expect(_scrubForTest(null)).toBeNull()+ expect(_scrubForTest(undefined)).toBeUndefined()+ expect(_scrubForTest(42)).toBe(42)+ expect(_scrubForTest('hi')).toBe('hi')+ })+})++describe('log levels', () => {+ const originalEnv = process.env.NODE_ENV++ beforeEach(() => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ })++ afterEach(() => {+ process.env.NODE_ENV = originalEnv+ vi.restoreAllMocks()+ })++ it('writes JSON in production and skips debug', () => {+ process.env.NODE_ENV = 'production'+ log.debug('skipped')+ log.info('hello', { a: 1 })+ expect(console.log).not.toHaveBeenCalledWith(expect.stringContaining('"skipped"'))+ const infoCall = (console.log as ReturnType<typeof vi.fn>).mock.calls[0][0]+ expect(typeof infoCall).toBe('string')+ expect(JSON.parse(infoCall)).toMatchObject({ level: 'info', msg: 'hello', a: 1 })+ })++ it('routes warn/error through console.error in production', () => {+ process.env.NODE_ENV = 'production'+ log.warn('bad')+ log.error('worse')+ expect(console.error).toHaveBeenCalledTimes(2)+ })++ it('serialises an Error object into name/message/stack', () => {+ process.env.NODE_ENV = 'production'+ log.error('boom', { err: new Error('kapow') })+ const line = (console.error as ReturnType<typeof vi.fn>).mock.calls[0][0] as string+ const parsed = JSON.parse(line)+ expect(parsed.err.message).toBe('kapow')+ expect(parsed.err.name).toBe('Error')+ expect(typeof parsed.err.stack).toBe('string')+ })++ it('renders human-readable output in dev', () => {+ process.env.NODE_ENV = 'development'+ log.info('hello', { a: 1 })+ expect(console.log).toHaveBeenCalledWith('[info]', 'hello', { a: 1 })+ })+})diff --git a/src/lib/logger.ts b/src/lib/logger.tsnew file mode 100644index 00000000..6f9df48d--- /dev/null+++ b/src/lib/logger.ts@@ -0,0 +1,101 @@+// Tiny structured logger for the web app.+//+// In production, every call serialises to a single-line JSON object on+// stdout/stderr so log aggregators (Vercel, Logflare, Datadog, etc.) can+// parse it without an SDK. In development, calls render as human-readable+// console output instead.+//+// Sensitive keys are redacted before serialisation — the denylist matches+// substring-by-name so `apiKey`, `apikey`, `api_key`, `headers.authorization`+// all collapse to `"[REDACTED]"`. Keep the list short and grow it only when+// a real leak risk shows up; an over-aggressive scrubber hides bugs.+//+// Why not pino: zero extra runtime dep, no transport setup, fits the+// uselu-on-Vercel deploy where stdout IS the transport.++export type LogLevel = 'debug' | 'info' | 'warn' | 'error'++export type LogContext = Record<string, unknown>++const DENY_SUBSTRINGS = [+ 'password',+ 'token',+ 'secret',+ 'authorization',+ 'cookie',+ 'apikey',+ 'api_key',+ 'service_role',+ 'private_key',+]++const isProd = () => process.env.NODE_ENV === 'production'++function scrub(value: unknown, depth = 0): unknown {+ if (depth > 6 || value === null || value === undefined) return value+ if (typeof value !== 'object') return value+ if (Array.isArray(value)) return value.map((v) => scrub(v, depth + 1))+ const out: Record<string, unknown> = {}+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {+ const lower = k.toLowerCase()+ if (DENY_SUBSTRINGS.some((d) => lower.includes(d))) {+ out[k] = '[REDACTED]'+ } else {+ out[k] = scrub(v, depth + 1)+ }+ }+ return out+}++function serializeError(err: unknown): Record<string, unknown> | unknown {+ if (err instanceof Error) {+ return {+ name: err.name,+ message: err.message,+ stack: err.stack,+ }+ }+ return err+}++function emit(level: LogLevel, msg: string, ctx?: LogContext): void {+ if (level === 'debug' && isProd()) return++ const safeCtx = ctx+ ? Object.fromEntries(+ Object.entries(ctx).map(([k, v]) => [+ k,+ k.toLowerCase() === 'err' || k.toLowerCase() === 'error'+ ? serializeError(v)+ : v,+ ]),+ )+ : undefined+ const cleaned = scrub(safeCtx) as LogContext | undefined++ if (isProd()) {+ const line = JSON.stringify({+ ts: new Date().toISOString(),+ level,+ msg,+ ...(cleaned ?? {}),+ })+ if (level === 'error' || level === 'warn') console.error(line)+ else console.log(line)+ return+ }++ const prefix = `[${level}]`+ if (cleaned) console.log(prefix, msg, cleaned)+ else console.log(prefix, msg)+}++export const log = {+ debug: (msg: string, ctx?: LogContext) => emit('debug', msg, ctx),+ info: (msg: string, ctx?: LogContext) => emit('info', msg, ctx),+ warn: (msg: string, ctx?: LogContext) => emit('warn', msg, ctx),+ error: (msg: string, ctx?: LogContext) => emit('error', msg, ctx),+}++/** Exported for the test only — exercise the scrubber on arbitrary input. */+export const _scrubForTest = (v: unknown) => scrub(v)