openvibers/openvibe.coupons Commits
Coupons 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) and server/auth/sso.js with the openvibe-shared/auth-client import is deleted; service tokens are checked by openvibe-sdk/auth verifyServiceToken with the key their kid names from the same JWKS client; the outbox is createServiceOutbox. Pins: openvibe-sdk v0.25.1, openvibe-contracts v0.79.0, openvibe-shared v2.0.0. npm test and test:pg 13/13.
Changes
@@@ -7,12 +7,12 @@"runtime": "node 22, express 4, PostgreSQL 18 (openvibe-sdk/db, async) + Valkey 9","port": 4850,"domain": "openvibe.coupons",-- "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.20.0"++ "openvibe-contracts v0.79.0",++ "openvibe-shared v2.0.0",++ "openvibe-sdk v0.25.1"],"capabilities": ["coupons.coupon.submit",@@@ -34,7 +34,7 @@"deployed": true,"deployment": "Deployed with `sudo ovhost deploy coupons`: unit openvibe-coupons, 127.0.0.1:4850 loopback only; Network OAuth client coupons and its grants exist; on 2026-09-23 /api/ready answered 200 and the production database held 0 coupons. Deployed internally, not launched: openvibe.coupons still serves the OpenVibe.Sites placeholder until a person verifies a coupons source's terms and enables it in Sources","placeholderInSites": true,-- "updated": "2026-09-28",++ "updated": "2026-09-29","features": ["merchants with normalized domain rules (public-suffix subset, path rules)","codes with restrictions, known or unknown expiry and evidence",@@@ -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.20.0",-- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.27.0",++ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.1",++ "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.20.0",-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.20.0",-- "integrity": "sha512-CqZFfVuSv3ZPoyG1LuWCAdvo8TG2ZuUCeGaqTsxDKS3gsymSFV2QXPq/5QUotTd82WShTGUKKhTgcyp9ggUMfQ==",++ "version": "0.25.1",++ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.1",++ "integrity": "sha512-c6K1riU7xT60qEd0YFn4QDPjWXTglo0LcE4cU8TSrmRTJL7TPAT7/iqQjS2UACt2zmQ1soNM8gfIZf7v9sVdZg==","license": "MIT","engines": {"node": ">=20"@@@ -1210,9 +1210,9 @@}},"node_modules/openvibe-shared": {-- "version": "1.27.0",-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.27.0",-- "integrity": "sha512-/H7dyFw+cURcdjyfbpyY7mNc6F+Pcb9TwkVwZHR+9d3M62q70KDhZLo/gZi71eaYxUjD8lO8tmbXu70EAa9paQ==",++ "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"@@@ -26,10 +26,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.20.0",-- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.27.0",++ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.1",++ "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v2.0.0","pg": "^8.23.0"},"devDependencies": {@@@ -15,9 +15,11 @@ const cookieParser = require('cookie-parser');const rateLimit = require('express-rate-limit');const contracts = require('openvibe-contracts');++const { createSsoClient } = require('openvibe-sdk/sso');++const { jwksClient } = require('openvibe-sdk/auth');++const configLib = require('./config');const { openStore } = require('./db');--const { createAuthClient, createAuthRoutes } = require('./auth/sso');const { createViewerResolver } = require('./auth/viewer');const { createCouponsOutbox } = require('./events/outbox');const { createPublication } = require('./domain/publication');@@@ -40,7 +42,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), log,++ * opts: config, store, now (clock), fetchImpl, auth (an openvibe-sdk/sso client), jwks, log,* limitsNow (the per-actor limiter's clock, tests)*/async function createApp(opts = {}) {@@@ -59,11 +61,28 @@ async function createApp(opts = {}) {const watches = createWatches({ store });const moderation = createModeration({ store, merchants, coupons, outbox });const importer = createSourcesImporter({ store, config, merchants, coupons, fetchImpl, log });-- const auth = opts.auth || createAuthClient(config);-- const viewers = createViewerResolver({ auth, config, installs });++ // Offline session verification and the service-token key share the SDK's process-wide JWKS client.++ const jwksUrl = `${config.networkInternalUrl}/api/.well-known/jwks`;++ const jwks = opts.jwks || jwksClient(jwksUrl, { log });++ const auth = opts.auth || createSsoClient({++ site: 'coupons',++ 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.issuer || config.networkUrl,++ secureCookies: config.cookies.secure,++ jwks: jwksUrl,++ fetch: fetchImpl,++ log,++ });++ const viewers = createViewerResolver({ auth, jwks, config, installs });const worker = createWorker({ config, coupons, importer, outbox, log });-- const ctx = { config, store, outbox, publication, merchants, coupons, reports, installs, watches, moderation, importer, auth, viewers, worker };++ const ctx = { config, store, outbox, publication, merchants, coupons, reports, installs, watches, moderation, importer, auth, jwks, viewers, worker };const app = express();app.disable('x-powered-by');@@@ -109,12 +128,12 @@ async function createApp(opts = {}) {app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-coupons', 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 = createCouponsReadiness({ store, auth, outbox, worker, importer, reports, config, release: release.release, valkey: ctx.valkey });++ const readiness = createCouponsReadiness({ store, jwks, outbox, worker, importer, reports, config, release: release.release, valkey: ctx.valkey });app.get('/api/ready', readiness.handler);// ── Sign-in (OAuth2 client of OpenVibe.Network) ─────────app.use('/auth/', rateLimit({ windowMs: 15 * 60_000, limit: 60, standardHeaders: true, legacyHeaders: false }));-- app.use('/auth', createAuthRoutes(config, auth));++ app.use('/auth', auth.router(express));{ const legal = require('openvibe-shared/legal'); app.get(legal.PATHS, legal.handler({ id: 'coupons', service: 'coupons', host: 'openvibe.coupons', name: 'OpenVibe.Coupons', profile: 'ugc' })); }// ── Static assets (content-hashed ?v= → immutable) ──────ddeleted file mode 100644@@@ -1,423 +0,0 @@--'use strict';----// ═══════════════════════════════════════════════════════════════--// openvibe.coupons — OAuth2 CLIENT session layer (sign-in via OpenVibe.Network SSO)--//--// The same session layer OpenVibe.Community uses (server/auth/routes.js there, MIT), with--// Coupons' client id: registered in the Network as OAuth client `coupons`, redirect--// https://openvibe.coupons/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--// POST /auth/refresh → rotate tokens via refresh_token grant--//--// Cookies (host-only for openvibe.coupons):--// 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(`[Coupons] Network public key loaded from ${base} (${jwks.algorithm || 'RS256'})`);-- return client.publicKey;-- }-- } catch (err) {-- console.warn(`[Coupons 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('[Coupons 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('[Coupons 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) => {-- const token = extractToken(req);-- if (!token) return res.status(401).json({ error: 'Not authenticated' });-- 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('[Coupons 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 };@@@ -24,17 +24,18 @@* Identity never comes from a request body or query.*/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 { ApiError } = require('../http/errors');--const { ids, serviceAuth, http, staff: staffMap } = contracts;++const { ids, http, staff: staffMap } = contracts;const PRINCIPAL_SUB = /^(svc|app|mod):/;const AUDIENCE = 'openvibe.coupons';const ANONYMOUS = Object.freeze({ kind: 'anonymous', subject: null, staff: false, origin: 'user' });--function createViewerResolver({ auth, config, installs }) {++function createViewerResolver({ auth, jwks, config, installs }) {const staffSubjects = new Set(config.staffSubjects || []);function userFromClaims(claims, token) {@@@ -46,9 +47,10 @@ function createViewerResolver({ auth, config, installs }) {}async function fromServiceToken(req, token) {-- const publicKey = await auth.ensureKey();-- if (!publicKey) throw new ApiError(503, 'identity.unavailable', 'the Network signing key is not loaded yet');-- const r = serviceAuth.verifyServiceToken(token, { publicKey, issuer: config.networkUrl, audience: AUDIENCE });++ // The key the token's kid names, from the same JWKS client the sign-in uses; the rules are this++ // service's pinned openvibe-contracts (which refuse a sandbox token, as before).++ const r = await verifyServiceToken(token, { jwks, issuer: config.networkUrl, audience: AUDIENCE, contracts });++ if (!r.ok && r.code === 'token.unavailable') throw new ApiError(503, 'identity.unavailable', 'the Network signing key is not loaded yet');if (!r.ok) throw new ApiError(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@@@ -95,7 +97,7 @@ function createViewerResolver({ auth, config, installs }) {/** Pages: the ov_token cookie (or a Bearer user token); services and installs are anonymous here. */async function resolvePage(req) {-- const token = extractToken(req);++ const token = auth.extractToken(req);if (!token || token.startsWith('cpx_')) return ANONYMOUS;const payload = decodeJwtPayload(token);if (!payload || (typeof payload.sub === 'string' && PRINCIPAL_SUB.test(payload.sub))) return ANONYMOUS;@@@ -1,93 +1,28 @@'use strict';/**-- * Coupons → OpenVibe.Events through the openvibe-sdk transactional outbox (ADR-004).-- *-- * coupons.coupon.created|updated|expired|disabled a code's lifecycle (charter coupons.created|…)-- * coupons.report.created a new validity report (never who reported)-- * coupons.confidence.changed a code's confidence moved (reports or decay)-- * coupons.index_document.upserted|deleted OpenVibe.Search documents and tombstones for-- * coupons and merchants (openvibe-publishing-- * index-hooks), consumed by Search's-- * '*.index_document.*' subscription-- * coupons.moderation.action staff (or a service holding the staff-- * capability) disabled, expired, re-enabled or-- * approved someone else's code, or approved,-- * disabled or re-enabled a shop-- * (common.moderation-action@1, ADR-022), for-- * Network's moderation audit log-- *-- * Every envelope's actor is the service itself ({ type: 'service', id: 'coupons' }) and no payload-- * names a person: submitters and reporters stay inside Coupons. The one exception is the staff-- * member who took a moderation action, named in coupons.moderation.action (the audit log exists-- * to say who acted); its target never names the submitter.-- *-- * 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 Coupons' 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.++ * Coupons → OpenVibe.Events through the shared openvibe-sdk transactional outbox (ADR-004,++ * openvibe-sdk/events createServiceOutbox; plan T1). The table is event_outbox, the relay is off++ * without EVENTS_URL or OV_OAUTH_CLIENT_SECRET, and status() reports pending/rejected rows for++ * /api/ready. moderationAction never names an owner_subject (moderationOwnerSubject: false), as++ * Coupons' audit event never did.*/--const { createClient } = require('openvibe-sdk/core');--const { createServiceTokenClient } = require('openvibe-sdk/auth');--const { createEventsClient, createPgOutbox } = require('openvibe-sdk/events');++const { createServiceOutbox } = require('openvibe-sdk/events');function createCouponsOutbox({ 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: 'coupons' });-- 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,++ return createServiceOutbox({++ db,++ source: 'coupons',++ eventsUrl: config.events.url,++ networkInternalUrl: config.networkInternalUrl,++ clientId: config.oauth.clientId,++ clientSecret: config.oauth.clientSecret,intervalMs: config.events.intervalMs,now,-- onError: (err) => {-- const msg = err && err.message;-- if (msg !== lastError) log.warn('[Coupons] event publish failed (will retry):', msg);-- lastError = msg;-- },++ fetch: fetchImpl,++ log,++ moderationOwnerSubject: false,});---- /** 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 });-- }---- /**-- * coupons.moderation.action, inside the caller's transaction. actorSubject: the staff member (null-- * for a service); target: { type, id }, owner_subject always null. Never the code or its text.-- */-- async function moderationAction({ action, target, actorSubject, reason = null, details = {} }, { traceparent } = {}) {-- const t = { type: target.type, id: String(target.id).slice(0, 200), owner_subject: null };-- return await emit({-- event_type: 'coupons.moderation.action',-- actor: actorSubject ? { type: 'user', id: actorSubject } : { type: 'service', id: 'coupons' },-- 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(),-- kick() { if (enabled) outbox.kick(); },-- status: async () => ({ enabled, pending: await outbox.pending(), rejected: await outbox.rejected(), last_error: lastError }),-- };}module.exports = { createCouponsOutbox };@@@ -14,7 +14,7 @@const { createReadiness } = require('openvibe-shared/ready');const { CHARTER_TABLES } = require('./db');--function createCouponsReadiness({ store, auth, outbox, worker, importer, reports, config, valkey = null, release = null }) {++function createCouponsReadiness({ store, jwks, outbox, worker, importer, reports, config, valkey = null, release = null }) {const { db } = store;return createReadiness({service: 'coupons',@@@ -35,8 +35,8 @@ function createCouponsReadiness({ store, auth, outbox, worker, importer, reports{name: 'network_jwks', required: false,check: () => {-- if (auth.client.publicKey) return true;-- auth.ensureKey().catch(() => {});++ if (jwks.status().ready) return true;++ jwks.keys().catch(() => {});return 'Network signing key not loaded yet: sign-in and service calls are unavailable';},},@@@ -43,7 +43,7 @@ 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, limitsNow: opts.limitsNow });-- await built.ctx.auth.ensureKey();++ try { await built.ctx.jwks.keys(); } catch { /* started without the key: readiness reports it */ }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;@@@ -61,7 +61,8 @@ async function startNetwork() {return { subject: ids.newId('user'), username, display_name: extra.display_name || username, role: extra.role || 'user' };}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 are for the site: openvibe-sdk/sso verifies the audience (openvibe.coupons).++ 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, audience: 'openvibe.coupons', expiresIn: '1h' });}function serviceToken(client, cap) {return signService({ sub: `svc:${client}`, aud: ['openvibe.coupons'], 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) => {
@@ -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": 4850,
"port": 4850,
"domain": "openvibe.coupons",
"domain": "openvibe.coupons",
- "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.20.0"
+ "openvibe-contracts v0.79.0",
+ "openvibe-shared v2.0.0",
+ "openvibe-sdk v0.25.1"
],
],
"capabilities": [
"capabilities": [
"coupons.coupon.submit",
"coupons.coupon.submit",
@@ -34,7 +34,7 @@
@@ -34,7 +34,7 @@
"deployed": true,
"deployed": true,
"deployment": "Deployed with `sudo ovhost deploy coupons`: unit openvibe-coupons, 127.0.0.1:4850 loopback only; Network OAuth client coupons and its grants exist; on 2026-09-23 /api/ready answered 200 and the production database held 0 coupons. Deployed internally, not launched: openvibe.coupons still serves the OpenVibe.Sites placeholder until a person verifies a coupons source's terms and enables it in Sources",
"deployment": "Deployed with `sudo ovhost deploy coupons`: unit openvibe-coupons, 127.0.0.1:4850 loopback only; Network OAuth client coupons and its grants exist; on 2026-09-23 /api/ready answered 200 and the production database held 0 coupons. Deployed internally, not launched: openvibe.coupons still serves the OpenVibe.Sites placeholder until a person verifies a coupons source's terms and enables it in Sources",
"placeholderInSites": true,
"placeholderInSites": true,
- "updated": "2026-09-28",
+ "updated": "2026-09-29",
"features": [
"features": [
"merchants with normalized domain rules (public-suffix subset, path rules)",
"merchants with normalized domain rules (public-suffix subset, path rules)",
"codes with restrictions, known or unknown expiry and evidence",
"codes with restrictions, known or unknown expiry and evidence",
@@ -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.20.0",
- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.27.0",
+ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.1",
+ "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.20.0",
- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.20.0",
- "integrity": "sha512-CqZFfVuSv3ZPoyG1LuWCAdvo8TG2ZuUCeGaqTsxDKS3gsymSFV2QXPq/5QUotTd82WShTGUKKhTgcyp9ggUMfQ==",
+ "version": "0.25.1",
+ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.1",
+ "integrity": "sha512-c6K1riU7xT60qEd0YFn4QDPjWXTglo0LcE4cU8TSrmRTJL7TPAT7/iqQjS2UACt2zmQ1soNM8gfIZf7v9sVdZg==",
"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.27.0",
- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.27.0",
- "integrity": "sha512-/H7dyFw+cURcdjyfbpyY7mNc6F+Pcb9TwkVwZHR+9d3M62q70KDhZLo/gZi71eaYxUjD8lO8tmbXu70EAa9paQ==",
+ "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"
@@ -26,10 +26,10 @@
@@ -26,10 +26,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.20.0",
- "openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v1.27.0",
+ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.25.1",
+ "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": {
@@ -15,9 +15,11 @@ const cookieParser = require('cookie-parser');
@@ -15,9 +15,11 @@ const cookieParser = require('cookie-parser');
const rateLimit = require('express-rate-limit');
const rateLimit = require('express-rate-limit');
const contracts = require('openvibe-contracts');
const contracts = require('openvibe-contracts');
+const { createSsoClient } = require('openvibe-sdk/sso');
+const { jwksClient } = require('openvibe-sdk/auth');
+
const configLib = require('./config');
const configLib = require('./config');
const { openStore } = require('./db');
const { openStore } = require('./db');
-const { createAuthClient, createAuthRoutes } = require('./auth/sso');
const { createViewerResolver } = require('./auth/viewer');
const { createViewerResolver } = require('./auth/viewer');
const { createCouponsOutbox } = require('./events/outbox');
const { createCouponsOutbox } = require('./events/outbox');
const { createPublication } = require('./domain/publication');
const { createPublication } = require('./domain/publication');
@@ -40,7 +42,7 @@ const PUBLIC_DIR = path.join(__dirname, '..', 'public');
@@ -40,7 +42,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), log,
+ * opts: config, store, now (clock), fetchImpl, auth (an openvibe-sdk/sso client), jwks, log,
* limitsNow (the per-actor limiter's clock, tests)
* limitsNow (the per-actor limiter's clock, tests)
*/
*/
async function createApp(opts = {}) {
async function createApp(opts = {}) {
@@ -59,11 +61,28 @@ async function createApp(opts = {}) {
@@ -59,11 +61,28 @@ async function createApp(opts = {}) {
const watches = createWatches({ store });
const watches = createWatches({ store });
const moderation = createModeration({ store, merchants, coupons, outbox });
const moderation = createModeration({ store, merchants, coupons, outbox });
const importer = createSourcesImporter({ store, config, merchants, coupons, fetchImpl, log });
const importer = createSourcesImporter({ store, config, merchants, coupons, fetchImpl, log });
- const auth = opts.auth || createAuthClient(config);
- const viewers = createViewerResolver({ auth, config, installs });
+ // Offline session verification and the service-token key share the SDK's process-wide JWKS client.
+ const jwksUrl = `${config.networkInternalUrl}/api/.well-known/jwks`;
+ const jwks = opts.jwks || jwksClient(jwksUrl, { log });
+ const auth = opts.auth || createSsoClient({
+ site: 'coupons',
+ 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.issuer || config.networkUrl,
+ secureCookies: config.cookies.secure,
+ jwks: jwksUrl,
+ fetch: fetchImpl,
+ log,
+ });
+ const viewers = createViewerResolver({ auth, jwks, config, installs });
const worker = createWorker({ config, coupons, importer, outbox, log });
const worker = createWorker({ config, coupons, importer, outbox, log });
- const ctx = { config, store, outbox, publication, merchants, coupons, reports, installs, watches, moderation, importer, auth, viewers, worker };
+ const ctx = { config, store, outbox, publication, merchants, coupons, reports, installs, watches, moderation, importer, auth, jwks, viewers, worker };
const app = express();
const app = express();
app.disable('x-powered-by');
app.disable('x-powered-by');
@@ -109,12 +128,12 @@ async function createApp(opts = {}) {
@@ -109,12 +128,12 @@ async function createApp(opts = {}) {
app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-coupons', version: VERSION }));
app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-coupons', 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 = createCouponsReadiness({ store, auth, outbox, worker, importer, reports, config, release: release.release, valkey: ctx.valkey });
+ const readiness = createCouponsReadiness({ store, jwks, outbox, worker, importer, reports, config, release: release.release, valkey: ctx.valkey });
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, limit: 60, standardHeaders: true, legacyHeaders: false }));
app.use('/auth/', rateLimit({ windowMs: 15 * 60_000, limit: 60, standardHeaders: true, legacyHeaders: false }));
- app.use('/auth', createAuthRoutes(config, auth));
+ app.use('/auth', auth.router(express));
{ const legal = require('openvibe-shared/legal'); app.get(legal.PATHS, legal.handler({ id: 'coupons', service: 'coupons', host: 'openvibe.coupons', name: 'OpenVibe.Coupons', profile: 'ugc' })); }
{ const legal = require('openvibe-shared/legal'); app.get(legal.PATHS, legal.handler({ id: 'coupons', service: 'coupons', host: 'openvibe.coupons', name: 'OpenVibe.Coupons', profile: 'ugc' })); }
// ── Static assets (content-hashed ?v= → immutable) ──────
// ── Static assets (content-hashed ?v= → immutable) ──────
deleted file mode 100644
deleted file mode 100644
@@ -1,423 +0,0 @@
@@ -1,423 +0,0 @@
-'use strict';
-
-// ═══════════════════════════════════════════════════════════════
-// openvibe.coupons — OAuth2 CLIENT session layer (sign-in via OpenVibe.Network SSO)
-//
-// The same session layer OpenVibe.Community uses (server/auth/routes.js there, MIT), with
-// Coupons' client id: registered in the Network as OAuth client `coupons`, redirect
-// https://openvibe.coupons/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
-// POST /auth/refresh → rotate tokens via refresh_token grant
-//
-// Cookies (host-only for openvibe.coupons):
-// 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(`[Coupons] Network public key loaded from ${base} (${jwks.algorithm || 'RS256'})`);
- return client.publicKey;
- }
- } catch (err) {
- console.warn(`[Coupons 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('[Coupons 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('[Coupons 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) => {
- const token = extractToken(req);
- if (!token) return res.status(401).json({ error: 'Not authenticated' });
- 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('[Coupons 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 };
@@ -24,17 +24,18 @@
@@ -24,17 +24,18 @@
* Identity never comes from a request body or query.
* Identity never comes from a request body or query.
*/
*/
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 { ApiError } = require('../http/errors');
const { ApiError } = require('../http/errors');
-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.coupons';
const AUDIENCE = 'openvibe.coupons';
const ANONYMOUS = Object.freeze({ kind: 'anonymous', subject: null, staff: false, origin: 'user' });
const ANONYMOUS = Object.freeze({ kind: 'anonymous', subject: null, staff: false, origin: 'user' });
-function createViewerResolver({ auth, config, installs }) {
+function createViewerResolver({ auth, jwks, config, installs }) {
const staffSubjects = new Set(config.staffSubjects || []);
const staffSubjects = new Set(config.staffSubjects || []);
function userFromClaims(claims, token) {
function userFromClaims(claims, token) {
@@ -46,9 +47,10 @@ function createViewerResolver({ auth, config, installs }) {
@@ -46,9 +47,10 @@ function createViewerResolver({ auth, config, installs }) {
}
}
async function fromServiceToken(req, token) {
async function fromServiceToken(req, token) {
- const publicKey = await auth.ensureKey();
- if (!publicKey) throw new ApiError(503, 'identity.unavailable', 'the Network signing key is not loaded yet');
- const r = serviceAuth.verifyServiceToken(token, { publicKey, issuer: config.networkUrl, audience: AUDIENCE });
+ // The key the token's kid names, from the same JWKS client the sign-in uses; the rules are this
+ // service's pinned openvibe-contracts (which refuse a sandbox token, as before).
+ const r = await verifyServiceToken(token, { jwks, issuer: config.networkUrl, audience: AUDIENCE, contracts });
+ if (!r.ok && r.code === 'token.unavailable') throw new ApiError(503, 'identity.unavailable', 'the Network signing key is not loaded yet');
if (!r.ok) throw new ApiError(401, r.code, r.reason);
if (!r.ok) throw new ApiError(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
@@ -95,7 +97,7 @@ function createViewerResolver({ auth, config, installs }) {
@@ -95,7 +97,7 @@ function createViewerResolver({ auth, config, installs }) {
/** Pages: the ov_token cookie (or a Bearer user token); services and installs are anonymous here. */
/** Pages: the ov_token cookie (or a Bearer user token); services and installs are anonymous here. */
async function resolvePage(req) {
async function resolvePage(req) {
- const token = extractToken(req);
+ const token = auth.extractToken(req);
if (!token || token.startsWith('cpx_')) return ANONYMOUS;
if (!token || token.startsWith('cpx_')) return ANONYMOUS;
const payload = decodeJwtPayload(token);
const payload = decodeJwtPayload(token);
if (!payload || (typeof payload.sub === 'string' && PRINCIPAL_SUB.test(payload.sub))) return ANONYMOUS;
if (!payload || (typeof payload.sub === 'string' && PRINCIPAL_SUB.test(payload.sub))) return ANONYMOUS;
@@ -1,93 +1,28 @@
@@ -1,93 +1,28 @@
'use strict';
'use strict';
/**
/**
- * Coupons → OpenVibe.Events through the openvibe-sdk transactional outbox (ADR-004).
- *
- * coupons.coupon.created|updated|expired|disabled a code's lifecycle (charter coupons.created|…)
- * coupons.report.created a new validity report (never who reported)
- * coupons.confidence.changed a code's confidence moved (reports or decay)
- * coupons.index_document.upserted|deleted OpenVibe.Search documents and tombstones for
- * coupons and merchants (openvibe-publishing
- * index-hooks), consumed by Search's
- * '*.index_document.*' subscription
- * coupons.moderation.action staff (or a service holding the staff
- * capability) disabled, expired, re-enabled or
- * approved someone else's code, or approved,
- * disabled or re-enabled a shop
- * (common.moderation-action@1, ADR-022), for
- * Network's moderation audit log
- *
- * Every envelope's actor is the service itself ({ type: 'service', id: 'coupons' }) and no payload
- * names a person: submitters and reporters stay inside Coupons. The one exception is the staff
- * member who took a moderation action, named in coupons.moderation.action (the audit log exists
- * to say who acted); its target never names the submitter.
- *
- * 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 Coupons' 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.
+ * Coupons → OpenVibe.Events through the shared openvibe-sdk transactional outbox (ADR-004,
+ * openvibe-sdk/events createServiceOutbox; plan T1). The table is event_outbox, the relay is off
+ * without EVENTS_URL or OV_OAUTH_CLIENT_SECRET, and status() reports pending/rejected rows for
+ * /api/ready. moderationAction never names an owner_subject (moderationOwnerSubject: false), as
+ * Coupons' audit event never did.
*/
*/
-const { createClient } = require('openvibe-sdk/core');
-const { createServiceTokenClient } = require('openvibe-sdk/auth');
-const { createEventsClient, createPgOutbox } = require('openvibe-sdk/events');
+const { createServiceOutbox } = require('openvibe-sdk/events');
function createCouponsOutbox({ db, config, fetchImpl, now, log = console }) {
function createCouponsOutbox({ 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: 'coupons' });
- 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,
+ return createServiceOutbox({
+ db,
+ source: 'coupons',
+ eventsUrl: config.events.url,
+ networkInternalUrl: config.networkInternalUrl,
+ clientId: config.oauth.clientId,
+ clientSecret: config.oauth.clientSecret,
intervalMs: config.events.intervalMs,
intervalMs: config.events.intervalMs,
now,
now,
- onError: (err) => {
- const msg = err && err.message;
- if (msg !== lastError) log.warn('[Coupons] event publish failed (will retry):', msg);
- lastError = msg;
- },
+ fetch: fetchImpl,
+ log,
+ moderationOwnerSubject: false,
});
});
-
- /** 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 });
- }
-
- /**
- * coupons.moderation.action, inside the caller's transaction. actorSubject: the staff member (null
- * for a service); target: { type, id }, owner_subject always null. Never the code or its text.
- */
- async function moderationAction({ action, target, actorSubject, reason = null, details = {} }, { traceparent } = {}) {
- const t = { type: target.type, id: String(target.id).slice(0, 200), owner_subject: null };
- return await emit({
- event_type: 'coupons.moderation.action',
- actor: actorSubject ? { type: 'user', id: actorSubject } : { type: 'service', id: 'coupons' },
- 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(),
- kick() { if (enabled) outbox.kick(); },
- status: async () => ({ enabled, pending: await outbox.pending(), rejected: await outbox.rejected(), last_error: lastError }),
- };
}
}
module.exports = { createCouponsOutbox };
module.exports = { createCouponsOutbox };
@@ -14,7 +14,7 @@
@@ -14,7 +14,7 @@
const { createReadiness } = require('openvibe-shared/ready');
const { createReadiness } = require('openvibe-shared/ready');
const { CHARTER_TABLES } = require('./db');
const { CHARTER_TABLES } = require('./db');
-function createCouponsReadiness({ store, auth, outbox, worker, importer, reports, config, valkey = null, release = null }) {
+function createCouponsReadiness({ store, jwks, outbox, worker, importer, reports, config, valkey = null, release = null }) {
const { db } = store;
const { db } = store;
return createReadiness({
return createReadiness({
service: 'coupons',
service: 'coupons',
@@ -35,8 +35,8 @@ function createCouponsReadiness({ store, auth, outbox, worker, importer, reports
@@ -35,8 +35,8 @@ function createCouponsReadiness({ store, auth, outbox, worker, importer, reports
{
{
name: 'network_jwks', required: false,
name: 'network_jwks', required: false,
check: () => {
check: () => {
- if (auth.client.publicKey) return true;
- auth.ensureKey().catch(() => {});
+ if (jwks.status().ready) return true;
+ jwks.keys().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';
},
},
},
},
@@ -43,7 +43,7 @@ async function boot(opts = {}) {
@@ -43,7 +43,7 @@ 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, limitsNow: opts.limitsNow });
built = await createApp({ config, store: createStore(testdb.db, { now: clock.now }), now: clock.now, log: opts.log || quiet, limitsNow: opts.limitsNow });
- await built.ctx.auth.ensureKey();
+ try { await built.ctx.jwks.keys(); } catch { /* started without the key: readiness reports it */ }
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;
@@ -61,7 +61,8 @@ async function startNetwork() {
@@ -61,7 +61,8 @@ async function startNetwork() {
return { subject: ids.newId('user'), username, display_name: extra.display_name || username, role: extra.role || 'user' };
return { subject: ids.newId('user'), username, display_name: extra.display_name || username, role: extra.role || 'user' };
}
}
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 are for the site: openvibe-sdk/sso verifies the audience (openvibe.coupons).
+ 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, audience: 'openvibe.coupons', expiresIn: '1h' });
}
}
function serviceToken(client, cap) {
function serviceToken(client, cap) {
return signService({ sub: `svc:${client}`, aud: ['openvibe.coupons'], cap });
return signService({ sub: `svc:${client}`, aud: ['openvibe.coupons'], 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) => {