openvibers/openvibe.blog Commits
Blog on the service kit (plan T1): sign-in is openvibe-sdk/sso createSsoClient (state + PKCE S256, server-side exchange, next limited to this site and the Network), service tokens are checked by openvibe-sdk/auth verifyServiceToken (the key their kid names), the outbox is createServiceOutbox; server/auth/sso.js and server/events/outbox.js are deleted. Pins: openvibe-sdk v0.25.0, openvibe-contracts v0.79.0, openvibe-shared v2.0.0. Both suites green (verified).
Changes
@@@ -244,8 +244,8 @@ Called elsewhere, as the service principal `blog`: `identity.subject.resolve` an`openvibe-sdk/db`; Valkey holds the per-actor limit counters (optional: without `VALKEY_URL` they count per process).- **Packages** (all pinned by release tarball): `openvibe-publishing` v1.0.0 (async PostgreSQL stores: revisions,schedule, taxonomy, citations, media, discussion, seo, authorship, index-hooks, ssr), `openvibe-contracts`-- v0.76.0, `openvibe-shared` v1.27.0 (Frame, app icon, footer, legal, release, metrics, ready, theme presets),-- `openvibe-sdk` v0.19.0 (db, PostgreSQL events outbox, service tokens, per-actor limits, testing).++ v0.79.0, `openvibe-shared` v2.0.0 (Frame, app icon, footer, legal, release, metrics, ready, theme presets),++ `openvibe-sdk` v0.25.0 (sso, db, PostgreSQL events outbox, service tokens, per-actor limits, testing).- **OpenVibe.Network:**- SSO: the OAuth client `blog` is already seeded with redirect`https://openvibe.blog/auth/callback`.@@@ -7,12 +7,12 @@"runtime": "node 22, express 4, PostgreSQL 18 (openvibe-sdk/db, async) + Valkey 9","port": 4810,"domain": "openvibe.blog",-- "contracts": "openvibe-contracts v0.76.0",++ "contracts": "openvibe-contracts v0.79.0","packages": ["openvibe-publishing v1.0.0",-- "openvibe-contracts v0.76.0",-- "openvibe-shared v1.27.0",-- "openvibe-sdk v0.19.0"++ "openvibe-contracts v0.79.0",++ "openvibe-shared v2.0.0",++ "openvibe-sdk v0.25.0"],"capabilities": ["blog.blog.create",@@@ -35,7 +35,7 @@"deployed": true,"deployment": "Public at https://openvibe.blog since 2026-09-23 (~03:00 UTC): deployed with `sudo ovhost deploy blog`, /opt/openvibe.blog, unit openvibe-blog on 127.0.0.1:4810 behind the openvibe.blog nginx vhost, principal blog. The network changelog publishes Patch notes posts on the official blog. Restore drill passed 2026-09-23.","placeholderInSites": false,-- "updated": "2026-09-28",++ "updated": "2026-09-29","deployedAt": "2026-09-23","features": ["the official blog and a blog for every member, with owners, editors and authors",@@@ -15,10 +15,10 @@"express-rate-limit": "^7.5.0","helmet": "^8.1.0","iovalkey": "^0.4.0",-- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.76.0",++ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.79.0","openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.0.0",-- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.19.0",-- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.29.2",++ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.0",++ "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v2.0.0","pg": "^8.23.0"},"devDependencies": {@@@ -1147,9 +1147,9 @@}},"node_modules/openvibe-contracts": {-- "version": "0.76.0",-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.76.0",-- "integrity": "sha512-zTdx776KWrcJKm1JTnf+0+BnsvswdvXy1ldPyse1hSqhnW/SSr98sX696eRetFUhTl8qVM1xSRCykqIUbqItPw==",++ "version": "0.79.0",++ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.79.0",++ "integrity": "sha512-FY5GLbiOq0kDw5lUPPzX6h3ATbzvsr/mX5DUCF4GRfn6vGMP0p89rZZDhgtVDaS+yCBCYMZ8zFaZxuHEkEVwVg==","license": "AGPL-3.0-only","dependencies": {"ajv": "^8.17.1",@@@ -1181,9 +1181,9 @@}},"node_modules/openvibe-sdk": {-- "version": "0.19.0",-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.19.0",-- "integrity": "sha512-5hNT9KVxtkLeGNYirqY1+n939lga/8XPbmrtqISQTNKaXNsS1AHhf4TBwWe+ZAamuCHUADJZu5Ov3OyZLN0nIA==",++ "version": "0.25.0",++ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.0",++ "integrity": "sha512-8eurZLyFUtB8XN16hLUuYkah+qwS3tkvdzul5qdZkJTi0aZ4q8dq2QGWSq6pN5mtVPdJyuJ8Mo53r36lixmP1g==","license": "MIT","engines": {"node": ">=20"@@@ -1210,9 +1210,9 @@}},"node_modules/openvibe-shared": {-- "version": "1.29.2",-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.29.2",-- "integrity": "sha512-w5daRSzujokYT1/Q3fu0KdcSZUBEv1pm66H8vIAI2SY0xtOaLqgfkXJpfIz1NgvJuyK8dhXBbLjM8Ow9RZ5x+A==",++ "version": "2.0.0",++ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v2.0.0",++ "integrity": "sha512-n5CHC0hfxOo0jo/3kS4O3KiwhirhZDlx5zZTIuPyIf3Dq0yI/R6R64btx7NYwZe5dI0NjvqzEtnv19m8unwLMg==","license": "MIT","dependencies": {"jsonwebtoken": "^9.0.0"@@@ -27,10 +27,10 @@"express-rate-limit": "^7.5.0","helmet": "^8.1.0","iovalkey": "^0.4.0",-- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.76.0",++ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.79.0","openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.0.0",-- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.19.0",-- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.29.2",++ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.0",++ "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v2.0.0","pg": "^8.23.0"},"devDependencies": {@@@ -17,7 +17,8 @@ const contracts = require('openvibe-contracts');const configLib = require('./config');const { openStore } = require('./db');--const { createAuthClient, createAuthRoutes } = require('./auth/sso');++const { createSsoClient, claimsToUser } = require('openvibe-sdk/sso');++const { jwksClient } = require('openvibe-sdk/auth');const { createViewerResolver } = require('./auth/viewer');const access = require('./domain/access');const { createBlogs } = require('./domain/blogs');@@@ -29,7 +30,7 @@ const { createPeople } = require('./clients/network');const { createCommunity } = require('./clients/community');const { createMedia } = require('./clients/media');const { createVip } = require('./clients/vip');--const { createBlogOutbox } = require('./events/outbox');++const { createServiceOutbox } = require('openvibe-sdk/events');const { createPublicRoutes } = require('./http/public');const { createEditorRoutes } = require('./http/editor');const { createApi } = require('./http/api');@@@ -43,7 +44,7 @@ const PUBLIC_DIR = path.join(__dirname, '..', 'public');const VERSION = require('../package.json').version;/**-- * opts: config, store, now (clock), fetchImpl, auth (a createAuthClient-like object),++ * opts: config, store, now (clock), fetchImpl, auth (an openvibe-sdk/sso client-like object),* entitlementCheck ({ subject, key, blog, post }) → bool (replaces VIP), log,* limitsNow (the per-actor limiter's clock, tests)*/@@@ -54,7 +55,13 @@ async function createApp(opts = {}) {// PostgreSQL (ADR-035): opened and migrated here unless the caller (a test, a script) hands in a store.const store = opts.store || await openStore(config, { now: opts.now, log });-- const outbox = createBlogOutbox({ db: store.db, config, fetchImpl, now: store.now, log });++ // Service outbox (openvibe-sdk/events): rows join the change's own transaction; the relay publishes++ // with Blog's service token when EVENTS_URL and the client secret are set, else rows wait in event_outbox.++ const outbox = createServiceOutbox({++ db: store.db, source: 'blog', eventsUrl: config.events.url, networkInternalUrl: config.networkInternalUrl,++ clientId: config.oauth.clientId, clientSecret: config.oauth.clientSecret, intervalMs: config.events.intervalMs,++ now: store.now, fetch: fetchImpl, log,++ });const blogs = createBlogs({ store, config });const publication = createPublication({ store, config, outbox });const posts = createPosts({ store, blogs, publication, access, outbox, log });@@@ -65,7 +72,16 @@ async function createApp(opts = {}) {const reading = createReading({ store, blogs, posts, publication, people, media, vip });const effects = createEffects({ outbox, community });const entitlements = access.createEntitlementChecker({ provider: config.entitlements.provider, check: opts.entitlementCheck, vip });-- const auth = opts.auth || createAuthClient(config);++ // Sign-in with OpenVibe.Network (openvibe-sdk/sso): routes, cookies and offline verification in one call.++ const networkJwksUrl = `${config.networkInternalUrl}/api/.well-known/jwks`;++ const sso = createSsoClient({++ site: 'blog', baseUrl: config.baseUrl, clientId: config.oauth.clientId, clientSecret: config.oauth.clientSecret,++ redirectUri: config.oauth.redirectUri, scope: config.oauth.scope, networkUrl: config.networkUrl,++ networkInternalUrl: config.networkInternalUrl, issuer: config.networkUrl, secureCookies: config.cookies.secure,++ });++ const auth = opts.auth || sso;++ // Warm the shared JWKS cache at boot (non-fatal if the Network is down).++ if (auth === sso) jwksClient(networkJwksUrl).keysForKid(null).catch(() => {});const viewers = createViewerResolver({ auth, config, people });const worker = createWorker({ config, store, posts, media, outbox, log });await blogs.ensureOfficial();@@@ -121,12 +137,25 @@ async function createApp(opts = {}) {app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-blog', version: VERSION }));// GET /release.json (ADR-016) and POST /release-metrics: open tabs' update reports into /metrics.release.mount(app, { registry: metrics.registry });-- const readiness = createBlogReadiness({ store, auth, outbox, release: release.release, valkey: ctx.valkey });++ const readiness = createBlogReadiness({ store, auth, outbox, release: release.release, valkey: ctx.valkey, jwksUrl: networkJwksUrl });app.get('/api/ready', readiness.handler);// ── Sign-in (OAuth2 client of OpenVibe.Network) ─────────app.use('/auth/', rateLimit({ windowMs: 15 * 60_000, max: 60, standardHeaders: true, legacyHeaders: false }));-- app.use('/auth', createAuthRoutes(config, auth));++ // /auth/me: the shared navbar probes it on every page view, so a guest is a signed-out answer (200++ // { user: null }), not a 401. The SDK router's own /me answers 401 for an absent session; this route,++ // registered first, keeps Blog's contract and marks the answer private / no-store.++ app.get('/auth/me', async (req, res) => {++ res.set('Cache-Control', 'private, no-store');++ res.vary('Cookie');++ res.vary('Authorization');++ const token = auth.extractToken(req);++ if (!token) return res.json({ user: null });++ const claims = await auth.verify(token);++ if (!claims) return res.status(401).json({ error: 'Invalid or expired token' });++ return res.json({ user: claimsToUser(claims), expires_at: claims.exp ? claims.exp * 1000 : null });++ });++ app.use('/auth', sso.router(express));{ const legal = require('openvibe-shared/legal'); app.get(legal.PATHS, legal.handler({ id: 'blog', service: 'blog', host: 'openvibe.blog', name: 'OpenVibe.Blog', profile: 'ugc' })); }// ── Static assets (content-hashed ?v= → immutable) ──────ddeleted file mode 100644@@@ -1,429 +0,0 @@--'use strict';----// ═══════════════════════════════════════════════════════════════--// openvibe.blog — OAuth2 CLIENT session layer (sign-in via OpenVibe.Network SSO)--//--// The same session layer OpenVibe.Community uses (server/auth/routes.js there, MIT), with--// Blog's client id: registered in the Network as OAuth client `blog`, redirect--// https://openvibe.blog/auth/callback.--//--// GET /auth/login → redirect to Network /oauth/authorize (?silent=1: prompt=none;--// ?next=… same-site path or an https://openvibe.network/… URL)--// GET /auth/callback → server-side code exchange, set cookies--// POST /auth/fedcm → the shared navbar's FedCM assertion → tokens (jwt-bearer grant)--// GET /auth/logout → clear cookies (+ best-effort refresh revoke), hint=guest--// GET /auth/me → offline-verify ov_token, return profile ({ user: null } for a guest)--// POST /auth/refresh → rotate tokens via refresh_token grant--//--// Cookies (host-only for openvibe.blog):--// ov_token access JWT, SameSite=Lax, Secure, JS-readable (navbar.js reads it)--// ov_refresh opaque refresh token, httpOnly, Path=/auth--// ov_sso_hint 'account' after a sign-in, 'guest' after a sign-out (navbar silent-login hint)--// Pages never trust a body or query for identity: only the verified ov_token (or a Bearer token).--// ═══════════════════════════════════════════════════════════════----const express = require('express');--const crypto = require('crypto');--const { OpenVibeAuthClient } = require('openvibe-shared/auth-client');----const ACCESS_COOKIE = 'ov_token';--const REFRESH_COOKIE = 'ov_refresh';--const HINT_COOKIE = 'ov_sso_hint';--const STATE_COOKIE = 'ov_oauth_state';--const NEXT_COOKIE = 'ov_oauth_next';--const SILENT_COOKIE = 'ov_oauth_silent';----/**-- * Create the auth client + JWKS fetcher shared by the whole app.-- * Verification is OFFLINE: we cache the Network's RS256 public key from-- * GET /api/.well-known/jwks and verify JWTs locally on every request.-- */--function createAuthClient(config) {-- const client = new OpenVibeAuthClient({-- clientId: config.oauth.clientId,-- clientSecret: config.oauth.clientSecret,-- redirectUri: config.oauth.redirectUri,-- publicKey: null, // filled by ensureKey()-- authBase: config.networkUrl,-- internalBase: config.networkInternalUrl,-- });---- let lastFetch = 0;-- let inflight = null;-- async function ensureKey() {-- if (client.publicKey) return client.publicKey;-- // A request that arrives while the key is being fetched waits for that fetch rather than-- // being treated as signed out.-- if (inflight) return inflight;-- // Don't hammer the Network if it's down — retry at most every 30s-- if (Date.now() - lastFetch < 30_000) return null;-- lastFetch = Date.now();-- inflight = fetchKey().finally(() => { inflight = null; });-- return inflight;-- }-- async function fetchKey() {-- for (const base of [config.networkInternalUrl, config.networkUrl]) {-- if (!base) continue;-- try {-- const res = await fetch(`${base}/api/.well-known/jwks`, { signal: AbortSignal.timeout(5000) });-- if (!res.ok) continue;-- const jwks = await res.json();-- if (jwks.public_key) {-- client.publicKey = jwks.public_key;-- console.log(`[Blog] Network public key loaded from ${base} (${jwks.algorithm || 'RS256'})`);-- return client.publicKey;-- }-- } catch (err) {-- console.warn(`[Blog auth] JWKS fetch failed from ${base}: ${err.message}`);-- }-- }-- return null;-- }---- /** Offline JWT verification. Returns decoded claims or null. */-- async function verify(token) {-- if (!token) return null;-- await ensureKey();-- return client.verifyToken(token);-- }---- // Warm the key cache at boot (non-fatal if the Network is down)-- ensureKey().catch(() => {});---- return { client, ensureKey, verify };--}----/** Token from Authorization header or the ov_token cookie. */--function extractToken(req) {-- const h = req.headers.authorization;-- if (h && h.startsWith('Bearer ')) return h.slice(7);-- return req.cookies?.[ACCESS_COOKIE] || null;--}----/** Strip registered claims — what the site shows as "the user". */--function claimsToUser(claims) {-- if (!claims) return null;-- const { iat, exp, aud, iss, nbf, jti, ...user } = claims;-- return user;--}----/**-- * Decode a JWT's payload WITHOUT checking its signature. Only for reading claims-- * we cross-check locally (the FedCM nonce) before the Network — which does verify-- * the signature — sees the assertion. Never use it to trust an identity.-- */--function decodeJwtPayload(token) {-- if (typeof token !== 'string') return null;-- const parts = token.split('.');-- if (parts.length !== 3) return null;-- try {-- const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));-- return claims && typeof claims === 'object' && !Array.isArray(claims) ? claims : null;-- } catch { return null; }--}----/** True when the assertion's `nonce` claim is exactly the nonce the page posted. */--function fedcmNonceMatches(token, nonce) {-- if (typeof nonce !== 'string' || !nonce || nonce.length > 256) return false;-- const claims = decodeJwtPayload(token);-- if (!claims || typeof claims.nonce !== 'string') return false;-- const a = Buffer.from(claims.nonce), b = Buffer.from(nonce);-- return a.length === b.length && crypto.timingSafeEqual(a, b);--}----/**-- * Only allow same-site relative paths, this site's own https origin, or an-- * https://openvibe.network/… URL (sign-in / sign-out-everywhere chains) as post-auth targets.-- */--function sanitizeNext(next, config) {-- // Browsers drop tab and newline characters from a URL and read a backslash as "/": "/<TAB>/evil.com" would-- // leave the site. A next with any control character or backslash goes home.-- if (typeof next === 'string' && /[\u0000-\u001f\u007f\\]/.test(next)) return '/';-- if (!next || typeof next !== 'string') return '/';-- if (/^\/(?!\/|\\)/.test(next)) return next; // relative path, not protocol-relative-- try {-- const u = new URL(next);-- if (u.protocol !== 'https:') return '/';-- const allowed = [config.baseUrl, config.networkUrl]-- .map((b) => { try { return new URL(b).hostname; } catch { return null; } })-- .filter(Boolean);-- if (allowed.includes(u.hostname)) return u.toString();-- } catch { /* fall through */ }-- return '/';--}----/** Append ?key=value to a same-site path or absolute URL, keeping any existing query/hash. */--function withParam(target, key, value) {-- const hashAt = target.indexOf('#');-- const hash = hashAt >= 0 ? target.slice(hashAt) : '';-- const base = hashAt >= 0 ? target.slice(0, hashAt) : target;-- const sep = base.includes('?') ? '&' : '?';-- return `${base}${sep}${encodeURIComponent(key)}=${encodeURIComponent(value)}${hash}`;--}----/**-- * Build the Network authorize URL for a login. Exported (and pure) so tests can-- * cover the silent-login shape without a browser.-- */--function buildAuthorizeUrl(config, auth, { silent = false } = {}) {-- const { url, state } = auth.client.getAuthorizationUrl(config.oauth.scope);-- if (!silent) return { url, state };-- // ?silent=1: continue as the account openvibe.network already knows (no chooser); if the-- // network has no session either, it bounces back with error=login_required and we stay quiet.-- const u = new URL(url);-- u.searchParams.set('prompt', 'none');-- return { url: u.toString(), state };--}----function createAuthRoutes(config, auth) {-- const router = express.Router();---- const accessCookieOpts = () => ({-- sameSite: 'lax',-- secure: config.cookies.secure,-- httpOnly: false, // JS-readable by design — the shared navbar reads it client-side-- path: '/',-- maxAge: 24 * 60 * 60 * 1000, // matches the 24h access JWT-- });---- const refreshCookieOpts = () => ({-- sameSite: 'lax',-- secure: config.cookies.secure,-- httpOnly: true,-- path: '/auth', // only ever sent back to this session layer-- maxAge: 30 * 24 * 60 * 60 * 1000,-- });---- const flowCookieOpts = () => ({-- sameSite: 'lax', secure: config.cookies.secure, httpOnly: true,-- path: '/auth', maxAge: 10 * 60 * 1000,-- });---- const hintCookieOpts = () => ({-- sameSite: 'lax',-- secure: config.cookies.secure,-- httpOnly: false, // navbar.js reads it to decide whether a silent login is worth trying-- path: '/',-- maxAge: 365 * 24 * 60 * 60 * 1000,-- });---- function setSessionCookies(res, accessToken, refreshToken) {-- res.cookie(ACCESS_COOKIE, accessToken, accessCookieOpts());-- if (refreshToken) res.cookie(REFRESH_COOKIE, refreshToken, refreshCookieOpts());-- res.cookie(HINT_COOKIE, 'account', hintCookieOpts());-- }---- function clearSessionCookies(res) {-- res.clearCookie(ACCESS_COOKIE, { ...accessCookieOpts(), maxAge: undefined });-- res.clearCookie(REFRESH_COOKIE, { ...refreshCookieOpts(), maxAge: undefined });-- }---- function clearFlowCookies(res) {-- for (const c of [STATE_COOKIE, NEXT_COOKIE, SILENT_COOKIE]) res.clearCookie(c, { path: '/auth' });-- }---- /** Exchange at the Network — internal URL first, public as fallback. */-- async function tokenGrant(body) {-- let lastErr = null;-- for (const base of [config.networkInternalUrl, config.networkUrl]) {-- if (!base) continue;-- try {-- const res = await fetch(`${base}/oauth/token`, {-- method: 'POST',-- headers: { 'Content-Type': 'application/json' },-- body: JSON.stringify({-- client_id: config.oauth.clientId,-- client_secret: config.oauth.clientSecret,-- ...body,-- }),-- signal: AbortSignal.timeout(10_000),-- });-- const data = await res.json().catch(() => ({}));-- if (!res.ok) {-- const err = new Error(data.error_description || data.error || `token grant failed (${res.status})`);-- err.status = res.status;-- err.error = data.error || 'invalid_grant';-- err.error_description = data.error_description || null;-- throw err;-- }-- return data;-- } catch (err) {-- lastErr = err;-- // 4xx = the grant itself is bad; retrying against another base won't help-- if (err.status && err.status < 500) throw err;-- }-- }-- throw lastErr || new Error('Network unreachable');-- }---- // ── GET /auth/login ──────────────────────────────────────-- router.get('/login', async (req, res) => {-- const silent = !!req.query.silent && req.query.silent !== '0';-- if (silent) {-- // Already signed in here? Then the silent round trip through the Network would-- // only hand back the session we have: go straight to where the caller wanted.-- const existing = req.cookies?.[ACCESS_COOKIE];-- if (existing && await auth.verify(existing)) {-- clearFlowCookies(res);-- return res.redirect(sanitizeNext(req.query.next, config));-- }-- }-- const { url, state } = buildAuthorizeUrl(config, auth, { silent });-- res.cookie(STATE_COOKIE, state, flowCookieOpts());-- const next = sanitizeNext(req.query.next, config);-- if (next !== '/') res.cookie(NEXT_COOKIE, next, flowCookieOpts());-- else res.clearCookie(NEXT_COOKIE, { path: '/auth' });-- if (silent) res.cookie(SILENT_COOKIE, '1', flowCookieOpts());-- else res.clearCookie(SILENT_COOKIE, { path: '/auth' });-- res.redirect(url);-- });---- // ── GET /auth/callback ───────────────────────────────────-- router.get('/callback', async (req, res) => {-- const { code, state, error } = req.query;-- const next = sanitizeNext(req.cookies?.[NEXT_COOKIE], config);-- const silent = req.cookies?.[SILENT_COOKIE] === '1';---- if (error) {-- clearFlowCookies(res);-- // Silent sign-in found no network session — go back quietly as a guest. The-- // ?sso=none marker stops navbar.js from trying again on that page.-- if (silent || error === 'login_required') return res.redirect(withParam(next, 'sso', 'none'));-- return res.redirect(withParam('/', 'auth_error', String(error)));-- }-- if (!code) return res.status(400).send('Missing authorization code');---- const expectedState = req.cookies?.[STATE_COOKIE];-- clearFlowCookies(res);-- // The state cookie is required, not just compared when present: skipping the check when-- // the cookie is missing would let a crafted link sign a visitor into someone else's account.-- if (!expectedState || !state || !crypto.timingSafeEqual(-- Buffer.from(String(state).padEnd(64).slice(0, 64)),-- Buffer.from(String(expectedState).padEnd(64).slice(0, 64))-- )) {-- return res.status(400).send('OAuth state mismatch — please try signing in again.');-- }---- try {-- const data = await tokenGrant({-- grant_type: 'authorization_code',-- redirect_uri: config.oauth.redirectUri,-- code,-- });-- setSessionCookies(res, data.access_token, data.refresh_token);-- return res.redirect(next);-- } catch (err) {-- console.error('[Blog auth] Code exchange failed:', err.message);-- return res.status(502).send('Sign-in failed — could not reach OpenVibe.Network. Please try again.');-- }-- });---- // ── POST /auth/fedcm ─────────────────────────────────────-- // The shared navbar obtained a FedCM assertion from openvibe.network (the-- // browser's own account chooser) and posts it same-origin with the nonce it-- // put in the FedCM request. We only pre-check the nonce; the Network verifies-- // the assertion's signature when it swaps it for tokens.-- const fedcmBody = express.json({ limit: '16kb', type: 'application/json' });-- const fedcmBodyError = (err, _req, res, next) => (err ? res.status(400).json({ error: 'invalid_request', error_description: 'Malformed JSON body' }) : next());-- router.post('/fedcm', fedcmBody, fedcmBodyError, async (req, res) => {-- if (!req.is('application/json')) return res.status(400).json({ error: 'invalid_request', error_description: 'Expected application/json' });-- const { token, nonce } = req.body || {};-- if (typeof token !== 'string' || !token || typeof nonce !== 'string' || !nonce) {-- return res.status(400).json({ error: 'invalid_request', error_description: 'token and nonce are required' });-- }-- if (!fedcmNonceMatches(token, nonce)) {-- return res.status(400).json({ error: 'invalid_request', error_description: 'nonce mismatch' });-- }-- try {-- const data = await tokenGrant({-- grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',-- assertion: token,-- });-- if (!data.access_token) throw Object.assign(new Error('no token'), { status: 401, error: 'invalid_grant' });-- setSessionCookies(res, data.access_token, data.refresh_token);-- const user = data.user || claimsToUser(await auth.verify(data.access_token));-- return res.json({ ok: true, user });-- } catch (err) {-- if (err.status && err.status < 500) {-- return res.status(401).json({ error: err.error || 'invalid_grant', error_description: err.error_description || err.message });-- }-- console.error('[Blog auth] FedCM exchange failed:', err.message);-- return res.status(502).json({ error: 'server_error', error_description: 'Could not reach OpenVibe.Network' });-- }-- });---- // ── GET /auth/logout ─────────────────────────────────────-- router.get('/logout', async (req, res) => {-- // Best-effort refresh revocation. The Network's rotating refresh tokens-- // self-invalidate, so a failure here is harmless.-- const refresh = req.cookies?.[REFRESH_COOKIE];-- if (refresh) {-- try {-- await fetch(`${config.networkInternalUrl}/oauth/revoke`, {-- method: 'POST',-- headers: { 'Content-Type': 'application/json' },-- body: JSON.stringify({-- client_id: config.oauth.clientId,-- client_secret: config.oauth.clientSecret,-- token: refresh,-- }),-- signal: AbortSignal.timeout(3000),-- });-- } catch { /* optional */ }-- }-- clearSessionCookies(res);-- res.cookie(HINT_COOKIE, 'guest', hintCookieOpts());-- res.redirect(sanitizeNext(req.query.next, config));-- });---- // ── GET /auth/me ─────────────────────────────────────────-- router.get('/me', async (req, res) => {-- res.set('Cache-Control', 'private, no-store');-- res.vary('Cookie');-- res.vary('Authorization');-- const token = extractToken(req);-- // No credential at all (a guest) is signed out, not an error: the shared navbar asks this on every-- // page view, and a 401 logged a console error on each (browser check, OpenVibe.Host). A credential-- // that is present but invalid or expired still answers 401.-- if (!token) return res.json({ user: null });-- const claims = await auth.verify(token);-- if (!claims) return res.status(401).json({ error: 'Invalid or expired token' });-- res.json({ user: claimsToUser(claims), expires_at: claims.exp ? claims.exp * 1000 : null });-- });---- // ── POST /auth/refresh ───────────────────────────────────-- // Small endpoint the shared navbar can call when ov_token expires.-- router.post('/refresh', async (req, res) => {-- const refresh = req.cookies?.[REFRESH_COOKIE];-- if (!refresh) return res.status(401).json({ error: 'No refresh token' });-- try {-- const data = await tokenGrant({ grant_type: 'refresh_token', refresh_token: refresh });-- setSessionCookies(res, data.access_token, data.refresh_token);-- const claims = await auth.verify(data.access_token);-- return res.json({ token: data.access_token, user: claimsToUser(claims) });-- } catch (err) {-- if (err.status && err.status < 500) {-- clearSessionCookies(res);-- return res.status(401).json({ error: 'Refresh token rejected — please sign in again' });-- }-- console.error('[Blog auth] Refresh failed:', err.message);-- return res.status(502).json({ error: 'Could not reach OpenVibe.Network' });-- }-- });---- return router;--}----/** Attaches req.user (JWT claims) and req.token when a valid ov_token is presented; never blocks. */--function optionalAuth(auth) {-- return async (req, _res, next) => {-- const token = extractToken(req);-- if (token) {-- const claims = await auth.verify(token);-- if (claims) { req.user = claimsToUser(claims); req.token = token; }-- }-- next();-- };--}----module.exports = { createAuthClient, createAuthRoutes, extractToken, optionalAuth, sanitizeNext, withParam, buildAuthorizeUrl, claimsToUser, decodeJwtPayload, fedcmNonceMatches };@@@ -19,10 +19,11 @@* on that token alone: a bad one is refused (problem+json), never downgraded to anonymous.*/const contracts = require('openvibe-contracts');--const { extractToken, claimsToUser, decodeJwtPayload } = require('./sso');++const { claimsToUser, decodeJwtPayload } = require('openvibe-sdk/sso');++const { verifyServiceToken } = require('openvibe-sdk/auth');const { checkCapability } = require('./capabilities');--const { ids, serviceAuth, http, staff: staffMap } = contracts;++const { ids, http, staff: staffMap } = contracts;const PRINCIPAL_SUB = /^(svc|app|mod):/;const AUDIENCE = 'openvibe.blog';@@@ -34,10 +35,15 @@ const ANONYMOUS = Object.freeze({ kind: 'anonymous', subject: null, staff: falsefunction createViewerResolver({ auth, config, people }) {async function fromServiceToken(req, token) {-- const publicKey = await auth.ensureKey();-- if (!publicKey) throw new ViewerError(503, 'identity.unavailable', 'the Network signing key is not loaded yet');-- const r = serviceAuth.verifyServiceToken(token, { publicKey, issuer: config.networkUrl, audience: AUDIENCE });-- if (!r.ok) throw new ViewerError(401, r.code, r.reason);++ // openvibe-sdk/auth verifyServiceToken supplies the key (the shared JWKS client) and every rule is++ // Blog's own pinned contracts serviceAuth.verifyServiceToken, passed in as `contracts`.++ const r = await verifyServiceToken(token, {++ jwks: `${config.networkInternalUrl}/api/.well-known/jwks`, issuer: config.networkUrl, audience: AUDIENCE, contracts,++ });++ if (!r.ok) {++ if (r.code === 'token.unavailable') throw new ViewerError(503, 'identity.unavailable', r.reason);++ throw new ViewerError(401, r.code, r.reason);++ }// Developer apps (app:…) and modules (mod:…) are third parties: they act only for the person// who authorized them (on_behalf_of), never for whoever X-OV-Subject names. Only first-party// service principals (svc:…) are trusted to name the acting person.@@@ -82,7 +88,7 @@ function createViewerResolver({ auth, config, people }) {return await fromServiceToken(req, token);}}-- const token = extractToken(req);++ const token = auth.extractToken(req);if (!token) return ANONYMOUS;return (await fromUserToken(token)) || ANONYMOUS;}ddeleted file mode 100644@@@ -1,87 +0,0 @@--'use strict';----/**-- * Blog → OpenVibe.Events through the openvibe-sdk transactional outbox (ADR-004).-- *-- * blog.post.created a post (draft) exists-- * blog.post.published|updated|unpublished|deleted-- * publication changes (openvibe-publishing/index-hooks-- * publicationEvent: canonical URL, state, indexability; public-- * only for public, listable posts)-- * blog.schedule.failed a scheduled publish/unpublish gave up after its retries-- * blog.moderation.action staff unpublished or deleted a post only their staff powers-- * allowed (common.moderation-action@1, ADR-022), for Network's-- * moderation audit log-- * blog.index_document.upserted|deleted the OpenVibe.Search document or tombstone (index-hooks-- * indexEvent), consumed by Search's '*.index_document.*'-- * subscription-- *-- * emit() runs inside the PostgreSQL transaction that makes the change, so an event exists if and only-- * if its change committed. The relay publishes with Blog's service token (events.event.publish,-- * audience openvibe.events) only when EVENTS_URL and OV_OAUTH_CLIENT_SECRET are set; otherwise-- * rows wait in event_outbox and /api/ready reports the relay as off.-- */--const { createClient } = require('openvibe-sdk/core');--const { createServiceTokenClient } = require('openvibe-sdk/auth');--const { createEventsClient, createPgOutbox } = require('openvibe-sdk/events');----function createBlogOutbox({ db, config, fetchImpl, now, log = console }) {-- const enabled = Boolean(config.events.url && config.oauth.clientSecret);-- const clientOpts = { baseUrls: { events: config.events.url || 'http://127.0.0.1:4300' }, retries: 0 };-- if (fetchImpl) clientOpts.fetch = fetchImpl;-- if (enabled) {-- clientOpts.tokenProvider = createServiceTokenClient({-- tokenUrl: `${config.networkInternalUrl}/oauth/token`, clientId: config.oauth.clientId, clientSecret: config.oauth.clientSecret,-- scope: { 'openvibe.events': 'events.event.publish' }, ...(fetchImpl ? { fetch: fetchImpl } : {}),-- });-- } else {-- clientOpts.getToken = async () => { throw new Error('events relay disabled (EVENTS_URL / OV_OAUTH_CLIENT_SECRET unset)'); };-- }-- const events = createEventsClient(createClient(clientOpts), { source: 'blog' });-- let lastError = null;-- // The PostgreSQL outbox: rows are written in the change's own transaction (enqueue(db, …) joins the ambient-- // transaction); several processes relay one table safely (leases).-- const outbox = createPgOutbox(db, {-- events,-- intervalMs: config.events.intervalMs,-- now,-- onError: (err) => {-- const msg = err && err.message;-- if (msg !== lastError) log.warn('[Blog] event publish failed (will retry):', msg);-- lastError = msg;-- },-- });---- /** Inside the caller's transaction. Returns the complete envelope (with its event_id). */-- async function emit(envelope, { traceparent } = {}) {-- return await outbox.enqueue(db, envelope, { traceparent });-- }---- /**-- * blog.moderation.action, inside the caller's transaction. actorSubject: the staff member;-- * target: { type, id, owner_subject? }. Never the content.-- */-- async function moderationAction({ action, target, actorSubject, reason = null, details = {} }, { traceparent } = {}) {-- const t = { type: target.type, id: String(target.id).slice(0, 200), owner_subject: target.owner_subject || null };-- return await emit({-- event_type: 'blog.moderation.action',-- actor: actorSubject ? { type: 'user', id: actorSubject } : { type: 'service', id: 'blog' },-- subject: { type: 'moderation_action', id: `${t.type}:${t.id}`.slice(0, 200) },-- visibility: 'internal',-- payload: { action, target: t, actor_subject: actorSubject || null, reason: reason ? String(reason).slice(0, 500) : null, details: details || {} },-- }, { traceparent });-- }---- return {-- emit,-- moderationAction,-- outbox,-- enabled,-- start() { if (enabled) outbox.start(); },-- stop: () => outbox.stop(),-- async kick() { if (enabled) await outbox.kick(); },-- status: async () => ({ enabled, pending: await outbox.pending(), rejected: await outbox.rejected(), last_error: lastError }),-- };--}----module.exports = { createBlogOutbox };@@@ -12,9 +12,10 @@* Request metrics come from openvibe-shared/metrics in app.js; content counts are not metrics.*/const { createReadiness } = require('openvibe-shared/ready');++const { jwksStatus, jwksClient } = require('openvibe-sdk/auth');const { CHARTER_TABLES } = require('./db');--function createBlogReadiness({ store, auth, outbox, valkey = null, release = null }) {++function createBlogReadiness({ store, auth, outbox, valkey = null, release = null, jwksUrl = null }) {const { db } = store;return createReadiness({service: 'blog',@@@ -35,8 +36,9 @@ function createBlogReadiness({ store, auth, outbox, valkey = null, release = nul{name: 'network_jwks', required: false,check: () => {-- if (auth.client.publicKey) return true;-- auth.ensureKey().catch(() => {});++ const st = jwksUrl ? jwksStatus().find((s) => s.url === jwksUrl) : null;++ if (st && st.ready) return true;++ if (jwksUrl) jwksClient(jwksUrl).keysForKid(null).catch(() => {});return 'Network signing key not loaded yet: sign-in and service calls are unavailable';},},@@@ -46,7 +46,8 @@ async function boot(opts = {}) {async function start() {const config = configLib.load(env);built = await createApp({ config, store: createStore(testdb.db, { now: clock.now }), now: clock.now, log: opts.log || quiet, entitlementCheck: opts.entitlementCheck, limitsNow: opts.limitsNow });-- await built.ctx.auth.ensureKey();++ // Warm the shared JWKS cache so an immediately-verified token does not race the first fetch.++ await require('openvibe-sdk/auth').jwksClient(`${network.url}/api/.well-known/jwks`).keysForKid(null);server = await new Promise((resolve) => { const s = http.createServer(built.app); s.listen(0, '127.0.0.1', () => resolve(s)); });t.base = `http://127.0.0.1:${server.address().port}`;t.app = built.app;@@@ -77,7 +77,9 @@ async function startNetwork() {return u;}function userToken(u) {-- return jwt.sign({ sub: String(Math.floor(Math.random() * 1e6)), subject_id: u.subject, username: u.username, display_name: u.display_name, role: u.role || 'user' }, privatePem, { algorithm: 'RS256', issuer, expiresIn: '1h' });++ // Network session tokens carry an audience; openvibe-sdk/sso checks it (verifyUserToken), so the mock++ // signs the audiences a real session token carries for this site.++ return jwt.sign({ sub: String(Math.floor(Math.random() * 1e6)), subject_id: u.subject, username: u.username, display_name: u.display_name, role: u.role || 'user', aud: ['openvibe.network', 'openvibe.blog'] }, privatePem, { algorithm: 'RS256', issuer, expiresIn: '1h' });}function serviceToken(client, cap) {return signService({ sub: `svc:${client}`, aud: ['openvibe.blog'], cap });@@@ -3,7 +3,7 @@// newline characters from a URL and read a backslash as "/", so "/<TAB>/evil.com" is "//evil.com" to them;// until 2026-09-26 it got through here.const assert = require('assert');--const { sanitizeNext } = require('../server/auth/sso');++const { sanitizeNext } = require('openvibe-sdk/sso');const config = { baseUrl: 'https://site.openvibe.test', networkUrl: 'https://openvibe.network' };const home = (v) => {@@@ -58,7 +58,9 @@ const LONG = Array.from({ length: 100 }, (_, i) => `w${i}`).join(' ');await check('ratchet: every file that makes an outbound request itself is reviewed', () => {const REVIEWED = {-- 'server/auth/sso.js': 'Network JWKS, OAuth token and revoke (configured)',++ // server/auth/sso.js and server/events/outbox.js are superseded by openvibe-sdk/sso and++ // openvibe-sdk/events and are no longer imported; they await deletion (the sandbox denies rm).++ 'server/auth/sso.js': 'Network JWKS, OAuth token and revoke (configured); dead after the SDK move','server/changelog.js': 'Network registry (configured) and api.github.com (fixed host) for the repositories the registry names','server/clients/community.js': 'OpenVibe.Community (configured)','server/clients/media.js': 'OpenVibe.Media (configured)',
@@ -244,8 +244,8 @@ Called elsewhere, as the service principal `blog`: `identity.subject.resolve` an
@@ -244,8 +244,8 @@ Called elsewhere, as the service principal `blog`: `identity.subject.resolve` an
`openvibe-sdk/db`; Valkey holds the per-actor limit counters (optional: without `VALKEY_URL` they count per process).
`openvibe-sdk/db`; Valkey holds the per-actor limit counters (optional: without `VALKEY_URL` they count per process).
- **Packages** (all pinned by release tarball): `openvibe-publishing` v1.0.0 (async PostgreSQL stores: revisions,
- **Packages** (all pinned by release tarball): `openvibe-publishing` v1.0.0 (async PostgreSQL stores: revisions,
schedule, taxonomy, citations, media, discussion, seo, authorship, index-hooks, ssr), `openvibe-contracts`
schedule, taxonomy, citations, media, discussion, seo, authorship, index-hooks, ssr), `openvibe-contracts`
- v0.76.0, `openvibe-shared` v1.27.0 (Frame, app icon, footer, legal, release, metrics, ready, theme presets),
- `openvibe-sdk` v0.19.0 (db, PostgreSQL events outbox, service tokens, per-actor limits, testing).
+ v0.79.0, `openvibe-shared` v2.0.0 (Frame, app icon, footer, legal, release, metrics, ready, theme presets),
+ `openvibe-sdk` v0.25.0 (sso, db, PostgreSQL events outbox, service tokens, per-actor limits, testing).
- **OpenVibe.Network:**
- **OpenVibe.Network:**
- SSO: the OAuth client `blog` is already seeded with redirect
- SSO: the OAuth client `blog` is already seeded with redirect
`https://openvibe.blog/auth/callback`.
`https://openvibe.blog/auth/callback`.
@@ -7,12 +7,12 @@
@@ -7,12 +7,12 @@
"runtime": "node 22, express 4, PostgreSQL 18 (openvibe-sdk/db, async) + Valkey 9",
"runtime": "node 22, express 4, PostgreSQL 18 (openvibe-sdk/db, async) + Valkey 9",
"port": 4810,
"port": 4810,
"domain": "openvibe.blog",
"domain": "openvibe.blog",
- "contracts": "openvibe-contracts v0.76.0",
+ "contracts": "openvibe-contracts v0.79.0",
"packages": [
"packages": [
"openvibe-publishing v1.0.0",
"openvibe-publishing v1.0.0",
- "openvibe-contracts v0.76.0",
- "openvibe-shared v1.27.0",
- "openvibe-sdk v0.19.0"
+ "openvibe-contracts v0.79.0",
+ "openvibe-shared v2.0.0",
+ "openvibe-sdk v0.25.0"
],
],
"capabilities": [
"capabilities": [
"blog.blog.create",
"blog.blog.create",
@@ -35,7 +35,7 @@
@@ -35,7 +35,7 @@
"deployed": true,
"deployed": true,
"deployment": "Public at https://openvibe.blog since 2026-09-23 (~03:00 UTC): deployed with `sudo ovhost deploy blog`, /opt/openvibe.blog, unit openvibe-blog on 127.0.0.1:4810 behind the openvibe.blog nginx vhost, principal blog. The network changelog publishes Patch notes posts on the official blog. Restore drill passed 2026-09-23.",
"deployment": "Public at https://openvibe.blog since 2026-09-23 (~03:00 UTC): deployed with `sudo ovhost deploy blog`, /opt/openvibe.blog, unit openvibe-blog on 127.0.0.1:4810 behind the openvibe.blog nginx vhost, principal blog. The network changelog publishes Patch notes posts on the official blog. Restore drill passed 2026-09-23.",
"placeholderInSites": false,
"placeholderInSites": false,
- "updated": "2026-09-28",
+ "updated": "2026-09-29",
"deployedAt": "2026-09-23",
"deployedAt": "2026-09-23",
"features": [
"features": [
"the official blog and a blog for every member, with owners, editors and authors",
"the official blog and a blog for every member, with owners, editors and authors",
@@ -15,10 +15,10 @@
@@ -15,10 +15,10 @@
"express-rate-limit": "^7.5.0",
"express-rate-limit": "^7.5.0",
"helmet": "^8.1.0",
"helmet": "^8.1.0",
"iovalkey": "^0.4.0",
"iovalkey": "^0.4.0",
- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.76.0",
+ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.79.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.0.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.0.0",
- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.19.0",
- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.29.2",
+ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.0",
+ "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v2.0.0",
"pg": "^8.23.0"
"pg": "^8.23.0"
},
},
"devDependencies": {
"devDependencies": {
@@ -1147,9 +1147,9 @@
@@ -1147,9 +1147,9 @@
}
}
},
},
"node_modules/openvibe-contracts": {
"node_modules/openvibe-contracts": {
- "version": "0.76.0",
- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.76.0",
- "integrity": "sha512-zTdx776KWrcJKm1JTnf+0+BnsvswdvXy1ldPyse1hSqhnW/SSr98sX696eRetFUhTl8qVM1xSRCykqIUbqItPw==",
+ "version": "0.79.0",
+ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.79.0",
+ "integrity": "sha512-FY5GLbiOq0kDw5lUPPzX6h3ATbzvsr/mX5DUCF4GRfn6vGMP0p89rZZDhgtVDaS+yCBCYMZ8zFaZxuHEkEVwVg==",
"license": "AGPL-3.0-only",
"license": "AGPL-3.0-only",
"dependencies": {
"dependencies": {
"ajv": "^8.17.1",
"ajv": "^8.17.1",
@@ -1181,9 +1181,9 @@
@@ -1181,9 +1181,9 @@
}
}
},
},
"node_modules/openvibe-sdk": {
"node_modules/openvibe-sdk": {
- "version": "0.19.0",
- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.19.0",
- "integrity": "sha512-5hNT9KVxtkLeGNYirqY1+n939lga/8XPbmrtqISQTNKaXNsS1AHhf4TBwWe+ZAamuCHUADJZu5Ov3OyZLN0nIA==",
+ "version": "0.25.0",
+ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.0",
+ "integrity": "sha512-8eurZLyFUtB8XN16hLUuYkah+qwS3tkvdzul5qdZkJTi0aZ4q8dq2QGWSq6pN5mtVPdJyuJ8Mo53r36lixmP1g==",
"license": "MIT",
"license": "MIT",
"engines": {
"engines": {
"node": ">=20"
"node": ">=20"
@@ -1210,9 +1210,9 @@
@@ -1210,9 +1210,9 @@
}
}
},
},
"node_modules/openvibe-shared": {
"node_modules/openvibe-shared": {
- "version": "1.29.2",
- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.29.2",
- "integrity": "sha512-w5daRSzujokYT1/Q3fu0KdcSZUBEv1pm66H8vIAI2SY0xtOaLqgfkXJpfIz1NgvJuyK8dhXBbLjM8Ow9RZ5x+A==",
+ "version": "2.0.0",
+ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v2.0.0",
+ "integrity": "sha512-n5CHC0hfxOo0jo/3kS4O3KiwhirhZDlx5zZTIuPyIf3Dq0yI/R6R64btx7NYwZe5dI0NjvqzEtnv19m8unwLMg==",
"license": "MIT",
"license": "MIT",
"dependencies": {
"dependencies": {
"jsonwebtoken": "^9.0.0"
"jsonwebtoken": "^9.0.0"
@@ -27,10 +27,10 @@
@@ -27,10 +27,10 @@
"express-rate-limit": "^7.5.0",
"express-rate-limit": "^7.5.0",
"helmet": "^8.1.0",
"helmet": "^8.1.0",
"iovalkey": "^0.4.0",
"iovalkey": "^0.4.0",
- "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.76.0",
+ "openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.79.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.0.0",
"openvibe-publishing": "https://codeload.github.com/OpenVibers/OpenVibe.Publishing/tar.gz/refs/tags/v1.0.0",
- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.19.0",
- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.29.2",
+ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.0",
+ "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v2.0.0",
"pg": "^8.23.0"
"pg": "^8.23.0"
},
},
"devDependencies": {
"devDependencies": {
@@ -17,7 +17,8 @@ const contracts = require('openvibe-contracts');
@@ -17,7 +17,8 @@ const contracts = require('openvibe-contracts');
const configLib = require('./config');
const configLib = require('./config');
const { openStore } = require('./db');
const { openStore } = require('./db');
-const { createAuthClient, createAuthRoutes } = require('./auth/sso');
+const { createSsoClient, claimsToUser } = require('openvibe-sdk/sso');
+const { jwksClient } = require('openvibe-sdk/auth');
const { createViewerResolver } = require('./auth/viewer');
const { createViewerResolver } = require('./auth/viewer');
const access = require('./domain/access');
const access = require('./domain/access');
const { createBlogs } = require('./domain/blogs');
const { createBlogs } = require('./domain/blogs');
@@ -29,7 +30,7 @@ const { createPeople } = require('./clients/network');
@@ -29,7 +30,7 @@ const { createPeople } = require('./clients/network');
const { createCommunity } = require('./clients/community');
const { createCommunity } = require('./clients/community');
const { createMedia } = require('./clients/media');
const { createMedia } = require('./clients/media');
const { createVip } = require('./clients/vip');
const { createVip } = require('./clients/vip');
-const { createBlogOutbox } = require('./events/outbox');
+const { createServiceOutbox } = require('openvibe-sdk/events');
const { createPublicRoutes } = require('./http/public');
const { createPublicRoutes } = require('./http/public');
const { createEditorRoutes } = require('./http/editor');
const { createEditorRoutes } = require('./http/editor');
const { createApi } = require('./http/api');
const { createApi } = require('./http/api');
@@ -43,7 +44,7 @@ const PUBLIC_DIR = path.join(__dirname, '..', 'public');
@@ -43,7 +44,7 @@ const PUBLIC_DIR = path.join(__dirname, '..', 'public');
const VERSION = require('../package.json').version;
const VERSION = require('../package.json').version;
/**
/**
- * opts: config, store, now (clock), fetchImpl, auth (a createAuthClient-like object),
+ * opts: config, store, now (clock), fetchImpl, auth (an openvibe-sdk/sso client-like object),
* entitlementCheck ({ subject, key, blog, post }) → bool (replaces VIP), log,
* entitlementCheck ({ subject, key, blog, post }) → bool (replaces VIP), log,
* limitsNow (the per-actor limiter's clock, tests)
* limitsNow (the per-actor limiter's clock, tests)
*/
*/
@@ -54,7 +55,13 @@ async function createApp(opts = {}) {
@@ -54,7 +55,13 @@ async function createApp(opts = {}) {
// PostgreSQL (ADR-035): opened and migrated here unless the caller (a test, a script) hands in a store.
// PostgreSQL (ADR-035): opened and migrated here unless the caller (a test, a script) hands in a store.
const store = opts.store || await openStore(config, { now: opts.now, log });
const store = opts.store || await openStore(config, { now: opts.now, log });
- const outbox = createBlogOutbox({ db: store.db, config, fetchImpl, now: store.now, log });
+ // Service outbox (openvibe-sdk/events): rows join the change's own transaction; the relay publishes
+ // with Blog's service token when EVENTS_URL and the client secret are set, else rows wait in event_outbox.
+ const outbox = createServiceOutbox({
+ db: store.db, source: 'blog', eventsUrl: config.events.url, networkInternalUrl: config.networkInternalUrl,
+ clientId: config.oauth.clientId, clientSecret: config.oauth.clientSecret, intervalMs: config.events.intervalMs,
+ now: store.now, fetch: fetchImpl, log,
+ });
const blogs = createBlogs({ store, config });
const blogs = createBlogs({ store, config });
const publication = createPublication({ store, config, outbox });
const publication = createPublication({ store, config, outbox });
const posts = createPosts({ store, blogs, publication, access, outbox, log });
const posts = createPosts({ store, blogs, publication, access, outbox, log });
@@ -65,7 +72,16 @@ async function createApp(opts = {}) {
@@ -65,7 +72,16 @@ async function createApp(opts = {}) {
const reading = createReading({ store, blogs, posts, publication, people, media, vip });
const reading = createReading({ store, blogs, posts, publication, people, media, vip });
const effects = createEffects({ outbox, community });
const effects = createEffects({ outbox, community });
const entitlements = access.createEntitlementChecker({ provider: config.entitlements.provider, check: opts.entitlementCheck, vip });
const entitlements = access.createEntitlementChecker({ provider: config.entitlements.provider, check: opts.entitlementCheck, vip });
- const auth = opts.auth || createAuthClient(config);
+ // Sign-in with OpenVibe.Network (openvibe-sdk/sso): routes, cookies and offline verification in one call.
+ const networkJwksUrl = `${config.networkInternalUrl}/api/.well-known/jwks`;
+ const sso = createSsoClient({
+ site: 'blog', baseUrl: config.baseUrl, clientId: config.oauth.clientId, clientSecret: config.oauth.clientSecret,
+ redirectUri: config.oauth.redirectUri, scope: config.oauth.scope, networkUrl: config.networkUrl,
+ networkInternalUrl: config.networkInternalUrl, issuer: config.networkUrl, secureCookies: config.cookies.secure,
+ });
+ const auth = opts.auth || sso;
+ // Warm the shared JWKS cache at boot (non-fatal if the Network is down).
+ if (auth === sso) jwksClient(networkJwksUrl).keysForKid(null).catch(() => {});
const viewers = createViewerResolver({ auth, config, people });
const viewers = createViewerResolver({ auth, config, people });
const worker = createWorker({ config, store, posts, media, outbox, log });
const worker = createWorker({ config, store, posts, media, outbox, log });
await blogs.ensureOfficial();
await blogs.ensureOfficial();
@@ -121,12 +137,25 @@ async function createApp(opts = {}) {
@@ -121,12 +137,25 @@ async function createApp(opts = {}) {
app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-blog', version: VERSION }));
app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-blog', version: VERSION }));
// GET /release.json (ADR-016) and POST /release-metrics: open tabs' update reports into /metrics.
// GET /release.json (ADR-016) and POST /release-metrics: open tabs' update reports into /metrics.
release.mount(app, { registry: metrics.registry });
release.mount(app, { registry: metrics.registry });
- const readiness = createBlogReadiness({ store, auth, outbox, release: release.release, valkey: ctx.valkey });
+ const readiness = createBlogReadiness({ store, auth, outbox, release: release.release, valkey: ctx.valkey, jwksUrl: networkJwksUrl });
app.get('/api/ready', readiness.handler);
app.get('/api/ready', readiness.handler);
// ── Sign-in (OAuth2 client of OpenVibe.Network) ─────────
// ── Sign-in (OAuth2 client of OpenVibe.Network) ─────────
app.use('/auth/', rateLimit({ windowMs: 15 * 60_000, max: 60, standardHeaders: true, legacyHeaders: false }));
app.use('/auth/', rateLimit({ windowMs: 15 * 60_000, max: 60, standardHeaders: true, legacyHeaders: false }));
- app.use('/auth', createAuthRoutes(config, auth));
+ // /auth/me: the shared navbar probes it on every page view, so a guest is a signed-out answer (200
+ // { user: null }), not a 401. The SDK router's own /me answers 401 for an absent session; this route,
+ // registered first, keeps Blog's contract and marks the answer private / no-store.
+ app.get('/auth/me', async (req, res) => {
+ res.set('Cache-Control', 'private, no-store');
+ res.vary('Cookie');
+ res.vary('Authorization');
+ const token = auth.extractToken(req);
+ if (!token) return res.json({ user: null });
+ const claims = await auth.verify(token);
+ if (!claims) return res.status(401).json({ error: 'Invalid or expired token' });
+ return res.json({ user: claimsToUser(claims), expires_at: claims.exp ? claims.exp * 1000 : null });
+ });
+ app.use('/auth', sso.router(express));
{ const legal = require('openvibe-shared/legal'); app.get(legal.PATHS, legal.handler({ id: 'blog', service: 'blog', host: 'openvibe.blog', name: 'OpenVibe.Blog', profile: 'ugc' })); }
{ const legal = require('openvibe-shared/legal'); app.get(legal.PATHS, legal.handler({ id: 'blog', service: 'blog', host: 'openvibe.blog', name: 'OpenVibe.Blog', profile: 'ugc' })); }
// ── Static assets (content-hashed ?v= → immutable) ──────
// ── Static assets (content-hashed ?v= → immutable) ──────
deleted file mode 100644
deleted file mode 100644
@@ -1,429 +0,0 @@
@@ -1,429 +0,0 @@
-'use strict';
-
-// ═══════════════════════════════════════════════════════════════
-// openvibe.blog — OAuth2 CLIENT session layer (sign-in via OpenVibe.Network SSO)
-//
-// The same session layer OpenVibe.Community uses (server/auth/routes.js there, MIT), with
-// Blog's client id: registered in the Network as OAuth client `blog`, redirect
-// https://openvibe.blog/auth/callback.
-//
-// GET /auth/login → redirect to Network /oauth/authorize (?silent=1: prompt=none;
-// ?next=… same-site path or an https://openvibe.network/… URL)
-// GET /auth/callback → server-side code exchange, set cookies
-// POST /auth/fedcm → the shared navbar's FedCM assertion → tokens (jwt-bearer grant)
-// GET /auth/logout → clear cookies (+ best-effort refresh revoke), hint=guest
-// GET /auth/me → offline-verify ov_token, return profile ({ user: null } for a guest)
-// POST /auth/refresh → rotate tokens via refresh_token grant
-//
-// Cookies (host-only for openvibe.blog):
-// ov_token access JWT, SameSite=Lax, Secure, JS-readable (navbar.js reads it)
-// ov_refresh opaque refresh token, httpOnly, Path=/auth
-// ov_sso_hint 'account' after a sign-in, 'guest' after a sign-out (navbar silent-login hint)
-// Pages never trust a body or query for identity: only the verified ov_token (or a Bearer token).
-// ═══════════════════════════════════════════════════════════════
-
-const express = require('express');
-const crypto = require('crypto');
-const { OpenVibeAuthClient } = require('openvibe-shared/auth-client');
-
-const ACCESS_COOKIE = 'ov_token';
-const REFRESH_COOKIE = 'ov_refresh';
-const HINT_COOKIE = 'ov_sso_hint';
-const STATE_COOKIE = 'ov_oauth_state';
-const NEXT_COOKIE = 'ov_oauth_next';
-const SILENT_COOKIE = 'ov_oauth_silent';
-
-/**
- * Create the auth client + JWKS fetcher shared by the whole app.
- * Verification is OFFLINE: we cache the Network's RS256 public key from
- * GET /api/.well-known/jwks and verify JWTs locally on every request.
- */
-function createAuthClient(config) {
- const client = new OpenVibeAuthClient({
- clientId: config.oauth.clientId,
- clientSecret: config.oauth.clientSecret,
- redirectUri: config.oauth.redirectUri,
- publicKey: null, // filled by ensureKey()
- authBase: config.networkUrl,
- internalBase: config.networkInternalUrl,
- });
-
- let lastFetch = 0;
- let inflight = null;
- async function ensureKey() {
- if (client.publicKey) return client.publicKey;
- // A request that arrives while the key is being fetched waits for that fetch rather than
- // being treated as signed out.
- if (inflight) return inflight;
- // Don't hammer the Network if it's down — retry at most every 30s
- if (Date.now() - lastFetch < 30_000) return null;
- lastFetch = Date.now();
- inflight = fetchKey().finally(() => { inflight = null; });
- return inflight;
- }
- async function fetchKey() {
- for (const base of [config.networkInternalUrl, config.networkUrl]) {
- if (!base) continue;
- try {
- const res = await fetch(`${base}/api/.well-known/jwks`, { signal: AbortSignal.timeout(5000) });
- if (!res.ok) continue;
- const jwks = await res.json();
- if (jwks.public_key) {
- client.publicKey = jwks.public_key;
- console.log(`[Blog] Network public key loaded from ${base} (${jwks.algorithm || 'RS256'})`);
- return client.publicKey;
- }
- } catch (err) {
- console.warn(`[Blog auth] JWKS fetch failed from ${base}: ${err.message}`);
- }
- }
- return null;
- }
-
- /** Offline JWT verification. Returns decoded claims or null. */
- async function verify(token) {
- if (!token) return null;
- await ensureKey();
- return client.verifyToken(token);
- }
-
- // Warm the key cache at boot (non-fatal if the Network is down)
- ensureKey().catch(() => {});
-
- return { client, ensureKey, verify };
-}
-
-/** Token from Authorization header or the ov_token cookie. */
-function extractToken(req) {
- const h = req.headers.authorization;
- if (h && h.startsWith('Bearer ')) return h.slice(7);
- return req.cookies?.[ACCESS_COOKIE] || null;
-}
-
-/** Strip registered claims — what the site shows as "the user". */
-function claimsToUser(claims) {
- if (!claims) return null;
- const { iat, exp, aud, iss, nbf, jti, ...user } = claims;
- return user;
-}
-
-/**
- * Decode a JWT's payload WITHOUT checking its signature. Only for reading claims
- * we cross-check locally (the FedCM nonce) before the Network — which does verify
- * the signature — sees the assertion. Never use it to trust an identity.
- */
-function decodeJwtPayload(token) {
- if (typeof token !== 'string') return null;
- const parts = token.split('.');
- if (parts.length !== 3) return null;
- try {
- const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
- return claims && typeof claims === 'object' && !Array.isArray(claims) ? claims : null;
- } catch { return null; }
-}
-
-/** True when the assertion's `nonce` claim is exactly the nonce the page posted. */
-function fedcmNonceMatches(token, nonce) {
- if (typeof nonce !== 'string' || !nonce || nonce.length > 256) return false;
- const claims = decodeJwtPayload(token);
- if (!claims || typeof claims.nonce !== 'string') return false;
- const a = Buffer.from(claims.nonce), b = Buffer.from(nonce);
- return a.length === b.length && crypto.timingSafeEqual(a, b);
-}
-
-/**
- * Only allow same-site relative paths, this site's own https origin, or an
- * https://openvibe.network/… URL (sign-in / sign-out-everywhere chains) as post-auth targets.
- */
-function sanitizeNext(next, config) {
- // Browsers drop tab and newline characters from a URL and read a backslash as "/": "/<TAB>/evil.com" would
- // leave the site. A next with any control character or backslash goes home.
- if (typeof next === 'string' && /[\u0000-\u001f\u007f\\]/.test(next)) return '/';
- if (!next || typeof next !== 'string') return '/';
- if (/^\/(?!\/|\\)/.test(next)) return next; // relative path, not protocol-relative
- try {
- const u = new URL(next);
- if (u.protocol !== 'https:') return '/';
- const allowed = [config.baseUrl, config.networkUrl]
- .map((b) => { try { return new URL(b).hostname; } catch { return null; } })
- .filter(Boolean);
- if (allowed.includes(u.hostname)) return u.toString();
- } catch { /* fall through */ }
- return '/';
-}
-
-/** Append ?key=value to a same-site path or absolute URL, keeping any existing query/hash. */
-function withParam(target, key, value) {
- const hashAt = target.indexOf('#');
- const hash = hashAt >= 0 ? target.slice(hashAt) : '';
- const base = hashAt >= 0 ? target.slice(0, hashAt) : target;
- const sep = base.includes('?') ? '&' : '?';
- return `${base}${sep}${encodeURIComponent(key)}=${encodeURIComponent(value)}${hash}`;
-}
-
-/**
- * Build the Network authorize URL for a login. Exported (and pure) so tests can
- * cover the silent-login shape without a browser.
- */
-function buildAuthorizeUrl(config, auth, { silent = false } = {}) {
- const { url, state } = auth.client.getAuthorizationUrl(config.oauth.scope);
- if (!silent) return { url, state };
- // ?silent=1: continue as the account openvibe.network already knows (no chooser); if the
- // network has no session either, it bounces back with error=login_required and we stay quiet.
- const u = new URL(url);
- u.searchParams.set('prompt', 'none');
- return { url: u.toString(), state };
-}
-
-function createAuthRoutes(config, auth) {
- const router = express.Router();
-
- const accessCookieOpts = () => ({
- sameSite: 'lax',
- secure: config.cookies.secure,
- httpOnly: false, // JS-readable by design — the shared navbar reads it client-side
- path: '/',
- maxAge: 24 * 60 * 60 * 1000, // matches the 24h access JWT
- });
-
- const refreshCookieOpts = () => ({
- sameSite: 'lax',
- secure: config.cookies.secure,
- httpOnly: true,
- path: '/auth', // only ever sent back to this session layer
- maxAge: 30 * 24 * 60 * 60 * 1000,
- });
-
- const flowCookieOpts = () => ({
- sameSite: 'lax', secure: config.cookies.secure, httpOnly: true,
- path: '/auth', maxAge: 10 * 60 * 1000,
- });
-
- const hintCookieOpts = () => ({
- sameSite: 'lax',
- secure: config.cookies.secure,
- httpOnly: false, // navbar.js reads it to decide whether a silent login is worth trying
- path: '/',
- maxAge: 365 * 24 * 60 * 60 * 1000,
- });
-
- function setSessionCookies(res, accessToken, refreshToken) {
- res.cookie(ACCESS_COOKIE, accessToken, accessCookieOpts());
- if (refreshToken) res.cookie(REFRESH_COOKIE, refreshToken, refreshCookieOpts());
- res.cookie(HINT_COOKIE, 'account', hintCookieOpts());
- }
-
- function clearSessionCookies(res) {
- res.clearCookie(ACCESS_COOKIE, { ...accessCookieOpts(), maxAge: undefined });
- res.clearCookie(REFRESH_COOKIE, { ...refreshCookieOpts(), maxAge: undefined });
- }
-
- function clearFlowCookies(res) {
- for (const c of [STATE_COOKIE, NEXT_COOKIE, SILENT_COOKIE]) res.clearCookie(c, { path: '/auth' });
- }
-
- /** Exchange at the Network — internal URL first, public as fallback. */
- async function tokenGrant(body) {
- let lastErr = null;
- for (const base of [config.networkInternalUrl, config.networkUrl]) {
- if (!base) continue;
- try {
- const res = await fetch(`${base}/oauth/token`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- client_id: config.oauth.clientId,
- client_secret: config.oauth.clientSecret,
- ...body,
- }),
- signal: AbortSignal.timeout(10_000),
- });
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- const err = new Error(data.error_description || data.error || `token grant failed (${res.status})`);
- err.status = res.status;
- err.error = data.error || 'invalid_grant';
- err.error_description = data.error_description || null;
- throw err;
- }
- return data;
- } catch (err) {
- lastErr = err;
- // 4xx = the grant itself is bad; retrying against another base won't help
- if (err.status && err.status < 500) throw err;
- }
- }
- throw lastErr || new Error('Network unreachable');
- }
-
- // ── GET /auth/login ──────────────────────────────────────
- router.get('/login', async (req, res) => {
- const silent = !!req.query.silent && req.query.silent !== '0';
- if (silent) {
- // Already signed in here? Then the silent round trip through the Network would
- // only hand back the session we have: go straight to where the caller wanted.
- const existing = req.cookies?.[ACCESS_COOKIE];
- if (existing && await auth.verify(existing)) {
- clearFlowCookies(res);
- return res.redirect(sanitizeNext(req.query.next, config));
- }
- }
- const { url, state } = buildAuthorizeUrl(config, auth, { silent });
- res.cookie(STATE_COOKIE, state, flowCookieOpts());
- const next = sanitizeNext(req.query.next, config);
- if (next !== '/') res.cookie(NEXT_COOKIE, next, flowCookieOpts());
- else res.clearCookie(NEXT_COOKIE, { path: '/auth' });
- if (silent) res.cookie(SILENT_COOKIE, '1', flowCookieOpts());
- else res.clearCookie(SILENT_COOKIE, { path: '/auth' });
- res.redirect(url);
- });
-
- // ── GET /auth/callback ───────────────────────────────────
- router.get('/callback', async (req, res) => {
- const { code, state, error } = req.query;
- const next = sanitizeNext(req.cookies?.[NEXT_COOKIE], config);
- const silent = req.cookies?.[SILENT_COOKIE] === '1';
-
- if (error) {
- clearFlowCookies(res);
- // Silent sign-in found no network session — go back quietly as a guest. The
- // ?sso=none marker stops navbar.js from trying again on that page.
- if (silent || error === 'login_required') return res.redirect(withParam(next, 'sso', 'none'));
- return res.redirect(withParam('/', 'auth_error', String(error)));
- }
- if (!code) return res.status(400).send('Missing authorization code');
-
- const expectedState = req.cookies?.[STATE_COOKIE];
- clearFlowCookies(res);
- // The state cookie is required, not just compared when present: skipping the check when
- // the cookie is missing would let a crafted link sign a visitor into someone else's account.
- if (!expectedState || !state || !crypto.timingSafeEqual(
- Buffer.from(String(state).padEnd(64).slice(0, 64)),
- Buffer.from(String(expectedState).padEnd(64).slice(0, 64))
- )) {
- return res.status(400).send('OAuth state mismatch — please try signing in again.');
- }
-
- try {
- const data = await tokenGrant({
- grant_type: 'authorization_code',
- redirect_uri: config.oauth.redirectUri,
- code,
- });
- setSessionCookies(res, data.access_token, data.refresh_token);
- return res.redirect(next);
- } catch (err) {
- console.error('[Blog auth] Code exchange failed:', err.message);
- return res.status(502).send('Sign-in failed — could not reach OpenVibe.Network. Please try again.');
- }
- });
-
- // ── POST /auth/fedcm ─────────────────────────────────────
- // The shared navbar obtained a FedCM assertion from openvibe.network (the
- // browser's own account chooser) and posts it same-origin with the nonce it
- // put in the FedCM request. We only pre-check the nonce; the Network verifies
- // the assertion's signature when it swaps it for tokens.
- const fedcmBody = express.json({ limit: '16kb', type: 'application/json' });
- const fedcmBodyError = (err, _req, res, next) => (err ? res.status(400).json({ error: 'invalid_request', error_description: 'Malformed JSON body' }) : next());
- router.post('/fedcm', fedcmBody, fedcmBodyError, async (req, res) => {
- if (!req.is('application/json')) return res.status(400).json({ error: 'invalid_request', error_description: 'Expected application/json' });
- const { token, nonce } = req.body || {};
- if (typeof token !== 'string' || !token || typeof nonce !== 'string' || !nonce) {
- return res.status(400).json({ error: 'invalid_request', error_description: 'token and nonce are required' });
- }
- if (!fedcmNonceMatches(token, nonce)) {
- return res.status(400).json({ error: 'invalid_request', error_description: 'nonce mismatch' });
- }
- try {
- const data = await tokenGrant({
- grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
- assertion: token,
- });
- if (!data.access_token) throw Object.assign(new Error('no token'), { status: 401, error: 'invalid_grant' });
- setSessionCookies(res, data.access_token, data.refresh_token);
- const user = data.user || claimsToUser(await auth.verify(data.access_token));
- return res.json({ ok: true, user });
- } catch (err) {
- if (err.status && err.status < 500) {
- return res.status(401).json({ error: err.error || 'invalid_grant', error_description: err.error_description || err.message });
- }
- console.error('[Blog auth] FedCM exchange failed:', err.message);
- return res.status(502).json({ error: 'server_error', error_description: 'Could not reach OpenVibe.Network' });
- }
- });
-
- // ── GET /auth/logout ─────────────────────────────────────
- router.get('/logout', async (req, res) => {
- // Best-effort refresh revocation. The Network's rotating refresh tokens
- // self-invalidate, so a failure here is harmless.
- const refresh = req.cookies?.[REFRESH_COOKIE];
- if (refresh) {
- try {
- await fetch(`${config.networkInternalUrl}/oauth/revoke`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- client_id: config.oauth.clientId,
- client_secret: config.oauth.clientSecret,
- token: refresh,
- }),
- signal: AbortSignal.timeout(3000),
- });
- } catch { /* optional */ }
- }
- clearSessionCookies(res);
- res.cookie(HINT_COOKIE, 'guest', hintCookieOpts());
- res.redirect(sanitizeNext(req.query.next, config));
- });
-
- // ── GET /auth/me ─────────────────────────────────────────
- router.get('/me', async (req, res) => {
- res.set('Cache-Control', 'private, no-store');
- res.vary('Cookie');
- res.vary('Authorization');
- const token = extractToken(req);
- // No credential at all (a guest) is signed out, not an error: the shared navbar asks this on every
- // page view, and a 401 logged a console error on each (browser check, OpenVibe.Host). A credential
- // that is present but invalid or expired still answers 401.
- if (!token) return res.json({ user: null });
- const claims = await auth.verify(token);
- if (!claims) return res.status(401).json({ error: 'Invalid or expired token' });
- res.json({ user: claimsToUser(claims), expires_at: claims.exp ? claims.exp * 1000 : null });
- });
-
- // ── POST /auth/refresh ───────────────────────────────────
- // Small endpoint the shared navbar can call when ov_token expires.
- router.post('/refresh', async (req, res) => {
- const refresh = req.cookies?.[REFRESH_COOKIE];
- if (!refresh) return res.status(401).json({ error: 'No refresh token' });
- try {
- const data = await tokenGrant({ grant_type: 'refresh_token', refresh_token: refresh });
- setSessionCookies(res, data.access_token, data.refresh_token);
- const claims = await auth.verify(data.access_token);
- return res.json({ token: data.access_token, user: claimsToUser(claims) });
- } catch (err) {
- if (err.status && err.status < 500) {
- clearSessionCookies(res);
- return res.status(401).json({ error: 'Refresh token rejected — please sign in again' });
- }
- console.error('[Blog auth] Refresh failed:', err.message);
- return res.status(502).json({ error: 'Could not reach OpenVibe.Network' });
- }
- });
-
- return router;
-}
-
-/** Attaches req.user (JWT claims) and req.token when a valid ov_token is presented; never blocks. */
-function optionalAuth(auth) {
- return async (req, _res, next) => {
- const token = extractToken(req);
- if (token) {
- const claims = await auth.verify(token);
- if (claims) { req.user = claimsToUser(claims); req.token = token; }
- }
- next();
- };
-}
-
-module.exports = { createAuthClient, createAuthRoutes, extractToken, optionalAuth, sanitizeNext, withParam, buildAuthorizeUrl, claimsToUser, decodeJwtPayload, fedcmNonceMatches };
@@ -19,10 +19,11 @@
@@ -19,10 +19,11 @@
* on that token alone: a bad one is refused (problem+json), never downgraded to anonymous.
* on that token alone: a bad one is refused (problem+json), never downgraded to anonymous.
*/
*/
const contracts = require('openvibe-contracts');
const contracts = require('openvibe-contracts');
-const { extractToken, claimsToUser, decodeJwtPayload } = require('./sso');
+const { claimsToUser, decodeJwtPayload } = require('openvibe-sdk/sso');
+const { verifyServiceToken } = require('openvibe-sdk/auth');
const { checkCapability } = require('./capabilities');
const { checkCapability } = require('./capabilities');
-const { ids, serviceAuth, http, staff: staffMap } = contracts;
+const { ids, http, staff: staffMap } = contracts;
const PRINCIPAL_SUB = /^(svc|app|mod):/;
const PRINCIPAL_SUB = /^(svc|app|mod):/;
const AUDIENCE = 'openvibe.blog';
const AUDIENCE = 'openvibe.blog';
@@ -34,10 +35,15 @@ const ANONYMOUS = Object.freeze({ kind: 'anonymous', subject: null, staff: false
@@ -34,10 +35,15 @@ const ANONYMOUS = Object.freeze({ kind: 'anonymous', subject: null, staff: false
function createViewerResolver({ auth, config, people }) {
function createViewerResolver({ auth, config, people }) {
async function fromServiceToken(req, token) {
async function fromServiceToken(req, token) {
- const publicKey = await auth.ensureKey();
- if (!publicKey) throw new ViewerError(503, 'identity.unavailable', 'the Network signing key is not loaded yet');
- const r = serviceAuth.verifyServiceToken(token, { publicKey, issuer: config.networkUrl, audience: AUDIENCE });
- if (!r.ok) throw new ViewerError(401, r.code, r.reason);
+ // openvibe-sdk/auth verifyServiceToken supplies the key (the shared JWKS client) and every rule is
+ // Blog's own pinned contracts serviceAuth.verifyServiceToken, passed in as `contracts`.
+ const r = await verifyServiceToken(token, {
+ jwks: `${config.networkInternalUrl}/api/.well-known/jwks`, issuer: config.networkUrl, audience: AUDIENCE, contracts,
+ });
+ if (!r.ok) {
+ if (r.code === 'token.unavailable') throw new ViewerError(503, 'identity.unavailable', r.reason);
+ throw new ViewerError(401, r.code, r.reason);
+ }
// Developer apps (app:…) and modules (mod:…) are third parties: they act only for the person
// Developer apps (app:…) and modules (mod:…) are third parties: they act only for the person
// who authorized them (on_behalf_of), never for whoever X-OV-Subject names. Only first-party
// who authorized them (on_behalf_of), never for whoever X-OV-Subject names. Only first-party
// service principals (svc:…) are trusted to name the acting person.
// service principals (svc:…) are trusted to name the acting person.
@@ -82,7 +88,7 @@ function createViewerResolver({ auth, config, people }) {
@@ -82,7 +88,7 @@ function createViewerResolver({ auth, config, people }) {
return await fromServiceToken(req, token);
return await fromServiceToken(req, token);
}
}
}
}
- const token = extractToken(req);
+ const token = auth.extractToken(req);
if (!token) return ANONYMOUS;
if (!token) return ANONYMOUS;
return (await fromUserToken(token)) || ANONYMOUS;
return (await fromUserToken(token)) || ANONYMOUS;
}
}
deleted file mode 100644
deleted file mode 100644
@@ -1,87 +0,0 @@
@@ -1,87 +0,0 @@
-'use strict';
-
-/**
- * Blog → OpenVibe.Events through the openvibe-sdk transactional outbox (ADR-004).
- *
- * blog.post.created a post (draft) exists
- * blog.post.published|updated|unpublished|deleted
- * publication changes (openvibe-publishing/index-hooks
- * publicationEvent: canonical URL, state, indexability; public
- * only for public, listable posts)
- * blog.schedule.failed a scheduled publish/unpublish gave up after its retries
- * blog.moderation.action staff unpublished or deleted a post only their staff powers
- * allowed (common.moderation-action@1, ADR-022), for Network's
- * moderation audit log
- * blog.index_document.upserted|deleted the OpenVibe.Search document or tombstone (index-hooks
- * indexEvent), consumed by Search's '*.index_document.*'
- * subscription
- *
- * emit() runs inside the PostgreSQL transaction that makes the change, so an event exists if and only
- * if its change committed. The relay publishes with Blog's service token (events.event.publish,
- * audience openvibe.events) only when EVENTS_URL and OV_OAUTH_CLIENT_SECRET are set; otherwise
- * rows wait in event_outbox and /api/ready reports the relay as off.
- */
-const { createClient } = require('openvibe-sdk/core');
-const { createServiceTokenClient } = require('openvibe-sdk/auth');
-const { createEventsClient, createPgOutbox } = require('openvibe-sdk/events');
-
-function createBlogOutbox({ db, config, fetchImpl, now, log = console }) {
- const enabled = Boolean(config.events.url && config.oauth.clientSecret);
- const clientOpts = { baseUrls: { events: config.events.url || 'http://127.0.0.1:4300' }, retries: 0 };
- if (fetchImpl) clientOpts.fetch = fetchImpl;
- if (enabled) {
- clientOpts.tokenProvider = createServiceTokenClient({
- tokenUrl: `${config.networkInternalUrl}/oauth/token`, clientId: config.oauth.clientId, clientSecret: config.oauth.clientSecret,
- scope: { 'openvibe.events': 'events.event.publish' }, ...(fetchImpl ? { fetch: fetchImpl } : {}),
- });
- } else {
- clientOpts.getToken = async () => { throw new Error('events relay disabled (EVENTS_URL / OV_OAUTH_CLIENT_SECRET unset)'); };
- }
- const events = createEventsClient(createClient(clientOpts), { source: 'blog' });
- let lastError = null;
- // The PostgreSQL outbox: rows are written in the change's own transaction (enqueue(db, …) joins the ambient
- // transaction); several processes relay one table safely (leases).
- const outbox = createPgOutbox(db, {
- events,
- intervalMs: config.events.intervalMs,
- now,
- onError: (err) => {
- const msg = err && err.message;
- if (msg !== lastError) log.warn('[Blog] event publish failed (will retry):', msg);
- lastError = msg;
- },
- });
-
- /** Inside the caller's transaction. Returns the complete envelope (with its event_id). */
- async function emit(envelope, { traceparent } = {}) {
- return await outbox.enqueue(db, envelope, { traceparent });
- }
-
- /**
- * blog.moderation.action, inside the caller's transaction. actorSubject: the staff member;
- * target: { type, id, owner_subject? }. Never the content.
- */
- async function moderationAction({ action, target, actorSubject, reason = null, details = {} }, { traceparent } = {}) {
- const t = { type: target.type, id: String(target.id).slice(0, 200), owner_subject: target.owner_subject || null };
- return await emit({
- event_type: 'blog.moderation.action',
- actor: actorSubject ? { type: 'user', id: actorSubject } : { type: 'service', id: 'blog' },
- subject: { type: 'moderation_action', id: `${t.type}:${t.id}`.slice(0, 200) },
- visibility: 'internal',
- payload: { action, target: t, actor_subject: actorSubject || null, reason: reason ? String(reason).slice(0, 500) : null, details: details || {} },
- }, { traceparent });
- }
-
- return {
- emit,
- moderationAction,
- outbox,
- enabled,
- start() { if (enabled) outbox.start(); },
- stop: () => outbox.stop(),
- async kick() { if (enabled) await outbox.kick(); },
- status: async () => ({ enabled, pending: await outbox.pending(), rejected: await outbox.rejected(), last_error: lastError }),
- };
-}
-
-module.exports = { createBlogOutbox };
@@ -12,9 +12,10 @@
@@ -12,9 +12,10 @@
* Request metrics come from openvibe-shared/metrics in app.js; content counts are not metrics.
* Request metrics come from openvibe-shared/metrics in app.js; content counts are not metrics.
*/
*/
const { createReadiness } = require('openvibe-shared/ready');
const { createReadiness } = require('openvibe-shared/ready');
+const { jwksStatus, jwksClient } = require('openvibe-sdk/auth');
const { CHARTER_TABLES } = require('./db');
const { CHARTER_TABLES } = require('./db');
-function createBlogReadiness({ store, auth, outbox, valkey = null, release = null }) {
+function createBlogReadiness({ store, auth, outbox, valkey = null, release = null, jwksUrl = null }) {
const { db } = store;
const { db } = store;
return createReadiness({
return createReadiness({
service: 'blog',
service: 'blog',
@@ -35,8 +36,9 @@ function createBlogReadiness({ store, auth, outbox, valkey = null, release = nul
@@ -35,8 +36,9 @@ function createBlogReadiness({ store, auth, outbox, valkey = null, release = nul
{
{
name: 'network_jwks', required: false,
name: 'network_jwks', required: false,
check: () => {
check: () => {
- if (auth.client.publicKey) return true;
- auth.ensureKey().catch(() => {});
+ const st = jwksUrl ? jwksStatus().find((s) => s.url === jwksUrl) : null;
+ if (st && st.ready) return true;
+ if (jwksUrl) jwksClient(jwksUrl).keysForKid(null).catch(() => {});
return 'Network signing key not loaded yet: sign-in and service calls are unavailable';
return 'Network signing key not loaded yet: sign-in and service calls are unavailable';
},
},
},
},
@@ -46,7 +46,8 @@ async function boot(opts = {}) {
@@ -46,7 +46,8 @@ async function boot(opts = {}) {
async function start() {
async function start() {
const config = configLib.load(env);
const config = configLib.load(env);
built = await createApp({ config, store: createStore(testdb.db, { now: clock.now }), now: clock.now, log: opts.log || quiet, entitlementCheck: opts.entitlementCheck, limitsNow: opts.limitsNow });
built = await createApp({ config, store: createStore(testdb.db, { now: clock.now }), now: clock.now, log: opts.log || quiet, entitlementCheck: opts.entitlementCheck, limitsNow: opts.limitsNow });
- await built.ctx.auth.ensureKey();
+ // Warm the shared JWKS cache so an immediately-verified token does not race the first fetch.
+ await require('openvibe-sdk/auth').jwksClient(`${network.url}/api/.well-known/jwks`).keysForKid(null);
server = await new Promise((resolve) => { const s = http.createServer(built.app); s.listen(0, '127.0.0.1', () => resolve(s)); });
server = await new Promise((resolve) => { const s = http.createServer(built.app); s.listen(0, '127.0.0.1', () => resolve(s)); });
t.base = `http://127.0.0.1:${server.address().port}`;
t.base = `http://127.0.0.1:${server.address().port}`;
t.app = built.app;
t.app = built.app;
@@ -77,7 +77,9 @@ async function startNetwork() {
@@ -77,7 +77,9 @@ async function startNetwork() {
return u;
return u;
}
}
function userToken(u) {
function userToken(u) {
- return jwt.sign({ sub: String(Math.floor(Math.random() * 1e6)), subject_id: u.subject, username: u.username, display_name: u.display_name, role: u.role || 'user' }, privatePem, { algorithm: 'RS256', issuer, expiresIn: '1h' });
+ // Network session tokens carry an audience; openvibe-sdk/sso checks it (verifyUserToken), so the mock
+ // signs the audiences a real session token carries for this site.
+ return jwt.sign({ sub: String(Math.floor(Math.random() * 1e6)), subject_id: u.subject, username: u.username, display_name: u.display_name, role: u.role || 'user', aud: ['openvibe.network', 'openvibe.blog'] }, privatePem, { algorithm: 'RS256', issuer, expiresIn: '1h' });
}
}
function serviceToken(client, cap) {
function serviceToken(client, cap) {
return signService({ sub: `svc:${client}`, aud: ['openvibe.blog'], cap });
return signService({ sub: `svc:${client}`, aud: ['openvibe.blog'], cap });
@@ -3,7 +3,7 @@
@@ -3,7 +3,7 @@
// newline characters from a URL and read a backslash as "/", so "/<TAB>/evil.com" is "//evil.com" to them;
// newline characters from a URL and read a backslash as "/", so "/<TAB>/evil.com" is "//evil.com" to them;
// until 2026-09-26 it got through here.
// until 2026-09-26 it got through here.
const assert = require('assert');
const assert = require('assert');
-const { sanitizeNext } = require('../server/auth/sso');
+const { sanitizeNext } = require('openvibe-sdk/sso');
const config = { baseUrl: 'https://site.openvibe.test', networkUrl: 'https://openvibe.network' };
const config = { baseUrl: 'https://site.openvibe.test', networkUrl: 'https://openvibe.network' };
const home = (v) => {
const home = (v) => {
@@ -58,7 +58,9 @@ const LONG = Array.from({ length: 100 }, (_, i) => `w${i}`).join(' ');
@@ -58,7 +58,9 @@ const LONG = Array.from({ length: 100 }, (_, i) => `w${i}`).join(' ');
await check('ratchet: every file that makes an outbound request itself is reviewed', () => {
await check('ratchet: every file that makes an outbound request itself is reviewed', () => {
const REVIEWED = {
const REVIEWED = {
- 'server/auth/sso.js': 'Network JWKS, OAuth token and revoke (configured)',
+ // server/auth/sso.js and server/events/outbox.js are superseded by openvibe-sdk/sso and
+ // openvibe-sdk/events and are no longer imported; they await deletion (the sandbox denies rm).
+ 'server/auth/sso.js': 'Network JWKS, OAuth token and revoke (configured); dead after the SDK move',
'server/changelog.js': 'Network registry (configured) and api.github.com (fixed host) for the repositories the registry names',
'server/changelog.js': 'Network registry (configured) and api.github.com (fixed host) for the repositories the registry names',
'server/clients/community.js': 'OpenVibe.Community (configured)',
'server/clients/community.js': 'OpenVibe.Community (configured)',
'server/clients/media.js': 'OpenVibe.Media (configured)',
'server/clients/media.js': 'OpenVibe.Media (configured)',