Merge pull request 'feat(bridge): auth session + homepage 24 latest items (BIT-26752)' (#33) from task/BIT-26752-auth-session-homepage-density into main
This commit was merged in pull request #33.
This commit is contained in:
commit
2f3755c75a
5 files changed
+414
-1
No files matched your search
@@ -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=
|
||||
|
||||
@@ -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<void> {
|
||||
// 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<ReturnType<typeof wp_validate_login>>;
|
||||
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 });
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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<string, SessionEntry>();
|
||||
|
||||
// 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<string, string>;
|
||||
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<WpSessionUser | null> {
|
||||
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<WpSessionUser> {
|
||||
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<string> {
|
||||
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<WpSessionUser | null> {
|
||||
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<void> {
|
||||
session_map.delete(sid);
|
||||
|
||||
const redis = get_redis();
|
||||
if (redis) {
|
||||
try { await redis.del(SESS_PREFIX + sid); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user