refactor(phase5-6): domain persistence, policy engine, OAuth extraction, proxy decoupling

Phase 5 — Foundation & Security:
- SQLite domain state persistence (5 tables, 4 modules: fallback, budget, lockout, circuit breaker)
- Write-through cache pattern for state survival across restarts
- Race condition fix in route.js (Promise-based singleton)
- Default password hardening (.env.example)
- Server init error handling improvement

Phase 6 — Architecture Refactoring:
- OAuth providers extracted into 12 individual modules (providers.js 1051→144 lines)
- Policy Engine (lockout→budget→fallback) with evaluateRequest/evaluateFirstAllowed
- Deterministic round-robin via persistent counter Map
- Telemetry window fix with proper recordedAt timestamps
- Proxy decoupled from API settings (direct import vs HTTP self-fetch)

Tests: 295 pass (22 new: domain-persistence 16, policy-engine 6)
Docs: CHANGELOG, README, ARCHITECTURE.md updated
This commit is contained in:
diegosouzapw
2026-02-15 08:12:12 -03:00
parent 25f4f5987c
commit 33c28f73db
33 changed files with 2206 additions and 1007 deletions

View File

@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
import { fetchWithTimeout } from "./shared/utils/fetchTimeout.js";
import { generateRequestId } from "./shared/utils/requestId.js";
import { getSettings } from "./lib/localDb.js";
// FASE-01: Fail-fast — no hardcoded fallback. Server must have JWT_SECRET configured.
if (!process.env.JWT_SECRET) {
@@ -42,25 +42,22 @@ export async function proxy(request) {
}
}
const origin = request.nextUrl.origin;
try {
// Pipeline: Use fetchWithTimeout instead of bare fetch
const res = await fetchWithTimeout(`${origin}/api/settings`, { timeoutMs: 5000 });
const data = await res.json();
// Direct import — no HTTP self-fetch overhead
const settings = await getSettings();
// Skip auth if login is not required
if (data.requireLogin === false) {
if (settings.requireLogin === false) {
return response;
}
// Skip auth if no password has been set yet (fresh install)
// This prevents an unresolvable loop where requireLogin=true but no password exists
if (!data.hasPassword) {
if (!settings.password) {
return response;
}
} catch (err) {
// FASE-01: Log settings fetch errors instead of silencing them
console.error("[Middleware] settings_error: Settings fetch failed:", err.message, {
console.error("[Middleware] settings_error: Settings read failed:", err.message, {
path: pathname,
origin,
requestId,
});
// On error, require login
@@ -79,4 +76,3 @@ export async function proxy(request) {
export const config = {
matcher: ["/", "/dashboard/:path*"],
};