From 6d54443539611dba5aaf17fa62919567e5efc82c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Alves?= Date: Fri, 17 Jul 2026 08:34:33 +0000 Subject: [PATCH] feat(bridge): auth endpoints + homepage 24 latest items (BIT-26752) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - POST /auth/login — validates credentials via WP wp-login.php (server-side), issues HttpOnly np_sid session cookie backed by Redis/in-memory - POST /auth/register — creates subscriber via admin app password, auto-login - POST /auth/logout — destroys session, clears cookie - GET /auth/session — returns current WpSessionUser or 401 - LATEST_COUNT 12 → 24 on /homepage (WP fetch budget already covered the delta) - .env.example: WP_ADMIN_USER, WP_ADMIN_APP_PASSWORD, SESSION_TTL_SECONDS Paperclip-Issue: BIT-26752 Paperclip-Agent: cto --- bridge/.env.example | 6 + bridge/src/routes/auth.ts | 160 +++++++++++++++++++++ bridge/src/routes/homepage.ts | 2 +- bridge/src/server.ts | 2 + bridge/src/services/wp-auth.ts | 245 +++++++++++++++++++++++++++++++++ 5 files changed, 414 insertions(+), 1 deletion(-) create mode 100644 bridge/src/routes/auth.ts create mode 100644 bridge/src/services/wp-auth.ts diff --git a/bridge/.env.example b/bridge/.env.example index 332d820..50aa15d 100644 --- a/bridge/.env.example +++ b/bridge/.env.example @@ -28,6 +28,12 @@ LOG_LEVEL=info # ANDEBOLTV_FETCH_TIMEOUT_MS=15000 # ANDEBOLTV_LIST_SIZE=48 +# Auth — WP admin Application Password for user create/lookup (Settings → Users → Application Passwords) +# WP_ADMIN_USER=admin +# WP_ADMIN_APP_PASSWORD=xxxx xxxx xxxx xxxx xxxx xxxx +# Session cookie lifetime in seconds (default: 604800 = 7 days) +# SESSION_TTL_SECONDS=604800 + # Error hub ingest (errors.bitreport.pt) — vault only; leave empty in Git examples # ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt # ERROR_REPORTING_TOKEN= diff --git a/bridge/src/routes/auth.ts b/bridge/src/routes/auth.ts new file mode 100644 index 0000000..8eeed05 --- /dev/null +++ b/bridge/src/routes/auth.ts @@ -0,0 +1,160 @@ +import type { FastifyInstance, FastifyRequest } from 'fastify'; +import { get_domain_config } from '../config/domain.js'; +import { resolve_site_host } from '../lib/request-host.js'; +import { + wp_validate_login, + wp_get_user_by_slug, + wp_create_user, + create_session, + get_session, + destroy_session, +} from '../services/wp-auth.js'; + +const COOKIE_NAME = 'np_sid'; +const SESSION_TTL_SECONDS = parseInt(process.env['SESSION_TTL_SECONDS'] ?? '604800', 10); +const IS_PROD = process.env['NODE_ENV'] === 'production'; + +function make_cookie(value: string, max_age: number): string { + const parts = [ + `${COOKIE_NAME}=${value}`, + 'HttpOnly', + 'SameSite=Lax', + 'Path=/', + `Max-Age=${max_age}`, + ]; + if (IS_PROD) parts.push('Secure'); + return parts.join('; '); +} + +function read_session_id(req: FastifyRequest): string | null { + const raw = req.headers.cookie; + if (!raw) return null; + for (const part of raw.split(';')) { + const idx = part.indexOf('='); + if (idx < 0) continue; + if (part.slice(0, idx).trim() === COOKIE_NAME) { + return decodeURIComponent(part.slice(idx + 1).trim()) || null; + } + } + return null; +} + +export async function auth_routes(app: FastifyInstance): Promise { + // GET /auth/session — return current user or 401 + app.get('/auth/session', async (req, reply) => { + const sid = read_session_id(req); + if (!sid) return reply.code(401).send({ error: 'Not authenticated' }); + + const user = await get_session(sid); + if (!user) return reply.code(401).send({ error: 'Session expired' }); + + return reply.send({ user }); + }); + + // POST /auth/login + app.post<{ Body: { username: string; password: string } }>( + '/auth/login', + { + schema: { + body: { + type: 'object', + required: ['username', 'password'], + properties: { + username: { type: 'string', minLength: 1 }, + password: { type: 'string', minLength: 1 }, + }, + }, + }, + }, + async (req, reply) => { + const host = resolve_site_host(req); + const config = get_domain_config(host); + + let login_result: Awaited>; + try { + login_result = await wp_validate_login( + config.wp_endpoint, + req.body.username, + req.body.password, + ); + } catch (err) { + app.log.warn({ err }, '[auth] WP login request failed'); + return reply.code(503).send({ error: 'Auth service unavailable' }); + } + + if (!login_result.success || !login_result.wp_username) { + return reply.code(401).send({ error: 'Invalid username or password' }); + } + + let user; + try { + user = await wp_get_user_by_slug(config.wp_endpoint, login_result.wp_username); + } catch (err) { + app.log.warn({ err }, '[auth] WP user lookup failed'); + return reply.code(503).send({ error: 'Auth service unavailable' }); + } + + if (!user) { + return reply.code(401).send({ error: 'User not found after login' }); + } + + const sid = await create_session(user); + reply.header('Set-Cookie', make_cookie(sid, SESSION_TTL_SECONDS)); + return reply.send({ user }); + }, + ); + + // POST /auth/register + app.post<{ Body: { username: string; email: string; password: string } }>( + '/auth/register', + { + schema: { + body: { + type: 'object', + required: ['username', 'email', 'password'], + properties: { + username: { type: 'string', minLength: 3, maxLength: 60 }, + email: { type: 'string', format: 'email' }, + password: { type: 'string', minLength: 8 }, + }, + }, + }, + }, + async (req, reply) => { + const host = resolve_site_host(req); + const config = get_domain_config(host); + + if (!config.auth_links) { + return reply.code(403).send({ error: 'Registration not enabled for this site' }); + } + + let user; + try { + user = await wp_create_user(config.wp_endpoint, { + username: req.body.username, + email: req.body.email, + password: req.body.password, + }); + } catch (err) { + const msg = err instanceof Error ? err.message : 'Registration failed'; + const is_conflict = + msg.includes('already registered') || + msg.includes('username already exists') || + msg.includes('email address is already'); + return reply.code(is_conflict ? 409 : 400).send({ error: msg }); + } + + const sid = await create_session(user); + reply.header('Set-Cookie', make_cookie(sid, SESSION_TTL_SECONDS)); + return reply.code(201).send({ user }); + }, + ); + + // POST /auth/logout + app.post('/auth/logout', async (req, reply) => { + const sid = read_session_id(req); + if (sid) await destroy_session(sid); + reply.header('Set-Cookie', make_cookie('', 0)); + return reply.send({ ok: true }); + }); +} diff --git a/bridge/src/routes/homepage.ts b/bridge/src/routes/homepage.ts index 2cb1965..51a5c03 100644 --- a/bridge/src/routes/homepage.ts +++ b/bridge/src/routes/homepage.ts @@ -13,7 +13,7 @@ import { enrich_fpa_agenda_with_streams } from '../services/fpa-stream-match.js' const HERO_COUNT = 3; const TRENDING_COUNT = 5; const FEATURED_COUNT = 4; -const LATEST_COUNT = 12; +const LATEST_COUNT = 24; const BY_CATEGORY_COUNT = 4; /** Extra posts so trending / featured / latest stay full after de-duplicating from hero. */ const MAIN_FEED_PER_PAGE = HERO_COUNT + TRENDING_COUNT + FEATURED_COUNT + LATEST_COUNT + 24; diff --git a/bridge/src/server.ts b/bridge/src/server.ts index 43ca250..047e57b 100644 --- a/bridge/src/server.ts +++ b/bridge/src/server.ts @@ -10,6 +10,7 @@ import { categories_routes } from './routes/categories.js'; import { homepage_routes } from './routes/homepage.js'; import { writers_routes } from './routes/writers.js'; import { fpa_sync_routes } from './routes/fpa-sync.js'; +import { auth_routes } from './routes/auth.js'; // BitReport error reporting (env: ERROR_REPORTING_TOKEN, ERROR_REPORTING_ENDPOINT) initReporter(); @@ -68,6 +69,7 @@ await app.register(categories_routes); await app.register(homepage_routes); await app.register(writers_routes); await app.register(fpa_sync_routes); +await app.register(auth_routes); // 404 fallback app.setNotFoundHandler((_req, reply) => { diff --git a/bridge/src/services/wp-auth.ts b/bridge/src/services/wp-auth.ts new file mode 100644 index 0000000..aa1b363 --- /dev/null +++ b/bridge/src/services/wp-auth.ts @@ -0,0 +1,245 @@ +import crypto from 'node:crypto'; +import { Redis } from 'ioredis'; + +const SESSION_TTL_MS = parseInt(process.env['SESSION_TTL_SECONDS'] ?? '604800', 10) * 1000; +const SESS_PREFIX = 'bridge:sess:'; + +export interface WpSessionUser { + id: number; + username: string; + display_name: string; + email: string; + avatar_url: string | null; + roles: string[]; +} + +interface SessionEntry { + user: WpSessionUser; + expires_at: number; +} + +// In-memory fallback (used when Redis is unavailable) +const session_map = new Map(); + +// Redis connection — separate from cache to keep concerns isolated +let _redis: Redis | null = null; + +function get_redis(): Redis | null { + const url = process.env['REDIS_URL']; + if (!url) return null; + if (_redis) return _redis; + + _redis = new Redis(url, { lazyConnect: true, enableOfflineQueue: false, maxRetriesPerRequest: 1 }); + _redis.on('error', () => null); + return _redis; +} + +// --------------------------------------------------------------------------- +// WP helpers +// --------------------------------------------------------------------------- + +/** Strip /wp-json suffix to get the WP site base URL. */ +function wp_base(wp_endpoint: string): string { + return wp_endpoint.replace(/\/wp-json\/?$/, ''); +} + +/** Extract the username embedded in the WP auth cookie value. */ +function extract_wp_username(set_cookie_headers: string[]): string | null { + for (const cookie of set_cookie_headers) { + const match = cookie.match(/^wordpress_logged_in_[^=]+=([^;]+)/); + if (!match) continue; + try { + const value = decodeURIComponent(match[1]); + const username = value.split('|')[0]; + if (username) return username; + } catch { continue; } + } + return null; +} + +/** + * Validate WP credentials by POSTing to wp-login.php (server-to-server). + * Returns `{success, wp_username}` — username is decoded from the auth cookie. + */ +export async function wp_validate_login( + wp_endpoint: string, + login: string, + password: string, +): Promise<{ success: boolean; wp_username: string | null }> { + const base = wp_base(wp_endpoint); + const body = new URLSearchParams({ + log: login, + pwd: password, + 'wp-submit': 'Log In', + redirect_to: `${base}/wp-admin/`, + testcookie: '1', + rememberme: 'forever', + }); + + const res = await fetch(`${base}/wp-login.php`, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Cookie: 'wordpress_test_cookie=WP+Cookie+check', + }, + body: body.toString(), + redirect: 'manual', + signal: AbortSignal.timeout(8000), + }); + + const all_cookies: string[] = + typeof res.headers.getSetCookie === 'function' + ? res.headers.getSetCookie() + : [res.headers.get('set-cookie') ?? ''].filter(Boolean); + + const success = + (res.status === 301 || res.status === 302) && + all_cookies.some(c => c.startsWith('wordpress_logged_in_')); + + const wp_username = success ? extract_wp_username(all_cookies) : null; + return { success, wp_username }; +} + +function admin_auth_header(): string { + const user = process.env['WP_ADMIN_USER']; + const pass = process.env['WP_ADMIN_APP_PASSWORD']; + if (!user || !pass) { + throw new Error('WP_ADMIN_USER and WP_ADMIN_APP_PASSWORD must be set for auth operations'); + } + return 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64'); +} + +interface WpUserRaw { + id: number; + name: string; + slug: string; + email?: string; + avatar_urls?: Record; + roles?: string[]; +} + +function map_wp_user(raw: WpUserRaw): WpSessionUser { + const avatars = raw.avatar_urls ?? {}; + return { + id: raw.id, + username: raw.slug, + display_name: raw.name, + email: raw.email ?? '', + avatar_url: avatars['96'] ?? avatars['48'] ?? null, + roles: raw.roles ?? [], + }; +} + +/** + * Fetch WP user record by slug (username) using admin application password. + * Requires WP_ADMIN_USER + WP_ADMIN_APP_PASSWORD env vars. + */ +export async function wp_get_user_by_slug( + wp_endpoint: string, + slug: string, +): Promise { + const auth = admin_auth_header(); + const url = `${wp_endpoint}/wp/v2/users?slug=${encodeURIComponent(slug)}&context=edit`; + + const res = await fetch(url, { + headers: { Authorization: auth, Accept: 'application/json' }, + signal: AbortSignal.timeout(8000), + }); + + if (!res.ok) return null; + const users = (await res.json()) as WpUserRaw[]; + const hit = users.find(u => u.slug === slug); + return hit ? map_wp_user(hit) : null; +} + +/** + * Create a new WP subscriber account using admin application password. + * Throws with a WP-provided message on conflict (duplicate username/email). + */ +export async function wp_create_user( + wp_endpoint: string, + data: { username: string; email: string; password: string }, +): Promise { + const auth = admin_auth_header(); + + const res = await fetch(`${wp_endpoint}/wp/v2/users`, { + method: 'POST', + headers: { + Authorization: auth, + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify({ + username: data.username, + email: data.email, + password: data.password, + roles: ['subscriber'], + }), + signal: AbortSignal.timeout(8000), + }); + + if (!res.ok) { + const err = await res.json().catch(() => ({ message: res.statusText })) as { message?: string }; + throw new Error(err.message ?? 'Failed to create user'); + } + + const raw = (await res.json()) as WpUserRaw; + return map_wp_user(raw); +} + +// --------------------------------------------------------------------------- +// Session management (Redis-backed, in-memory fallback) +// --------------------------------------------------------------------------- + +export async function create_session(user: WpSessionUser): Promise { + const sid = crypto.randomUUID(); + const entry: SessionEntry = { user, expires_at: Date.now() + SESSION_TTL_MS }; + + session_map.set(sid, entry); + + const redis = get_redis(); + if (redis) { + try { + await redis.set( + SESS_PREFIX + sid, + JSON.stringify(entry), + 'PX', + SESSION_TTL_MS, + ); + } catch { /* ignore write failures */ } + } + + return sid; +} + +export async function get_session(sid: string): Promise { + const now = Date.now(); + + const redis = get_redis(); + if (redis) { + try { + const raw = await redis.get(SESS_PREFIX + sid); + if (raw) { + const entry = JSON.parse(raw) as SessionEntry; + if (entry.expires_at > now) return entry.user; + } + } catch { /* fall through to in-memory */ } + } + + const local = session_map.get(sid); + if (local) { + if (local.expires_at > now) return local.user; + session_map.delete(sid); + } + + return null; +} + +export async function destroy_session(sid: string): Promise { + session_map.delete(sid); + + const redis = get_redis(); + if (redis) { + try { await redis.del(SESS_PREFIX + sid); } catch { /* ignore */ } + } +}