openvibers/openvibe.services Commits

Services: sign-in on openvibe-sdk/sso 0.73.0 (#151)

OP OpenVibers committed 14 days ago · 545469c596 · 10 files, +182 −193

Move the site's own copy of the OAuth client onto the one SDK module: one flow, one recovery, one failure page.
Legacy services_at/services_rt cookies are read as the session so nobody is signed out by the move; the staff flag
and the server-side refresh of an expired person token stay; readiness fails on a refused client.

Changes

ddiff --git a/package-lock.json b/package-lock.json
iindex 1536085..0b04928 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -17,7 +17,7 @@
"helmet": "^8.1.0",
"iovalkey": "^0.4.0",
"openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.222.0",
-- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.67.0",
++ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.73.0",
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.43.0",
"pg": "^8.23.0"
},
@@@ -1181,9 +1181,9 @@
}
},
"node_modules/openvibe-sdk": {
-- "version": "0.67.0",
-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.67.0",
-- "integrity": "sha512-s7NzjaNcowVcOIiup2z0ze+xsq/qnr++3pHSI8JzirqJPQ5JsBSUF5RkjOHyfk9bRKlmhY0fsNS6x4dsYylyqw==",
++ "version": "0.73.0",
++ "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.73.0",
++ "integrity": "sha512-XClxoVm9M6RA8eXlGgYZ0u6q9n5h79mCXqAAEg9fX21KgcqP69RmG+cX+6wrOf7TaEj7eSBWMxHjiIeIa9N7Dg==",
"license": "MIT",
"bin": {
"openvibe-download": "bin/openvibe-download.js"
ddiff --git a/package.json b/package.json
iindex 24d7391..bbc38b3 100644
---- a/package.json
++++ b/package.json
@@@ -28,7 +28,7 @@
"helmet": "^8.1.0",
"iovalkey": "^0.4.0",
"openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.222.0",
-- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.67.0",
++ "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.73.0",
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.43.0",
"pg": "^8.23.0"
},
ddiff --git a/server/app.js b/server/app.js
iindex df0e328..cbc0ffd 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -176,7 +176,7 @@ async function createApp(opts = {}) {
}), next));
// GET /release.json (ADR-016) and POST /release-metrics: open tabs' update reports into /metrics.
release.mount(app, { registry: metrics.registry });
-- const readiness = createServicesReadiness({ store, network, outbox, docs, config, authorities, release: release.release, valkey: ctx.valkey });
++ const readiness = createServicesReadiness({ store, network, outbox, docs, config, authorities, release: release.release, valkey: ctx.valkey, sso });
app.get('/api/ready', readiness.handler);
// GET /openapi.json: the public OpenAPI 3.1 document (server/http/openapi.js); /api/v1/openapi.json redirects here.
openapi.mount(app);
ddiff --git a/server/auth/sso.js b/server/auth/sso.js
iindex 9caf1da..f06ad11 100644
---- a/server/auth/sso.js
++++ b/server/auth/sso.js
@@@ -1,38 +1,35 @@
'use strict';
--const { staff: staffMap } = require('openvibe-contracts');
/**
-- * Sign-in with OpenVibe.Network: OAuth 2 authorization code with PKCE (S256), as OAuth client
-- * `services` (the same shape as OpenVibe.Billing's console).
++ * Sign-in with OpenVibe.Network, on openvibe-sdk/sso (0.73.0) instead of this site's own copy of the OAuth client.
++ *
++ * The SDK owns the flow: GET /auth/login (PKCE S256, ?next, ?silent, ?prompt, ?login_hint), GET /auth/callback
++ * (recovering by itself once from a lost flow or a used code), GET /auth/logout, GET /auth/me, POST /auth/fedcm,
++ * POST /auth/refresh and GET /auth/health. This file keeps OpenVibe.Services' own surface on top of it:
*
-- * GET /auth/login → Network /oauth/authorize?…&code_challenge=…&code_challenge_method=S256
-- * (?silent=1 adds prompt=none; ?next= a same-site path)
-- * GET /auth/callback → state check, server-side code exchange (client secret + code_verifier)
-- * GET /auth/logout → clear cookies, revoke the refresh token (best effort)
-- * GET /auth/me → { user } for the shared navbar (it cannot read the httpOnly cookie); { user: null } for a guest
++ * middleware() req.viewer (the page renderer's shape, staff included), from sso.optionalAuth()
++ * routes() the SDK's /auth router, plus this site's /auth/me body and the cross-site sign-out guard
++ * asViewer(req,res,fn) run a Network call as the person, refreshing once on 401
++ * tokenGrant(fields) a token request with this site's client
*
-- * Services calls the Network's /api/v1/projects API with the person's access token, so it keeps that
-- * token — in an httpOnly cookie (services_at) no script can read, unlike the navbar-readable ov_token
-- * other sites use: this portal shows client secrets once, and a script-readable token would let an
-- * injected script mint more. The refresh token (services_rt) is httpOnly too. Neither is ever stored
-- * server-side, rendered or logged.
++ * Services calls the Network's /api/v1/projects API with the person's access token, so it keeps that token in an
++ * httpOnly cookie (httpOnlyAccess): this portal shows client secrets once, and a script-readable token would let an
++ * injected script mint more. The old names (services_at, services_rt) are handed to the SDK as legacyCookies, so nobody
++ * is signed out by the move: they are read as the session until the next sign-in or refresh writes ov_token /
++ * ov_refresh and clears them.
*/
--const crypto = require('crypto');
const express = require('express');
const cache = require('openvibe-shared/cache-policy');
++const { staff: staffMap } = require('openvibe-contracts');
++const { createSsoClient } = require('openvibe-sdk/sso');
const ACCESS_COOKIE = 'services_at';
const REFRESH_COOKIE = 'services_rt';
const HINT_COOKIE = 'ov_sso_hint';
--const FLOW_COOKIE = 'services_oauth';
--
--function pkcePair() {
-- const verifier = crypto.randomBytes(32).toString('base64url'); // 43 characters
-- const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
-- return { verifier, challenge };
--}
++const SDK_ACCESS_COOKIE = 'ov_token';
++const SDK_REFRESH_COOKIE = 'ov_refresh';
--/** This site's own origins: BASE_URL, and the other hosts this process serves (OpenVibe.Homes for Rent). */
++/** This site's own origins: BASE_URL, and any other host this process serves. */
function ownOrigins(config) {
const out = new Set();
for (const u of [config && config.baseUrl, config && config.homes && config.homes.url]) {
@@@ -47,8 +44,6 @@ function ownOrigins(config) {
* 2026-10-22 that landed on the home page (a person signed in quietly found themselves somewhere else).
*/
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 (typeof next === 'string' && /^https?:\/\//i.test(next)) {
let u = null;
@@@ -60,64 +55,52 @@ function sanitizeNext(next, config) {
return next;
}
--function authorizeUrl(config, { state, challenge, silent = false }) {
-- const q = new URLSearchParams({
-- response_type: 'code',
-- client_id: config.oauth.clientId,
-- redirect_uri: config.oauth.redirectUri,
-- scope: config.oauth.scope,
-- state,
-- code_challenge: challenge,
-- code_challenge_method: 'S256',
-- });
-- if (silent) q.set('prompt', 'none');
-- return `${config.network.url}/oauth/authorize?${q.toString()}`;
++function pkcePair() {
++ const crypto = require('crypto');
++ const verifier = crypto.randomBytes(32).toString('base64url'); // 43 characters
++ const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
++ return { verifier, challenge };
}
function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Date.now(), log = console }) {
-- const cookieBase = () => ({ sameSite: 'lax', secure: config.cookies.secure, httpOnly: true, path: '/' });
++ const secure = config.cookies.secure;
++ const sso = createSsoClient({
++ site: 'services',
++ siteName: 'OpenVibe.Services',
++ baseUrl: config.baseUrl,
++ clientId: config.oauth.clientId,
++ clientSecret: config.oauth.clientSecret,
++ networkUrl: config.network.url,
++ networkInternalUrl: config.network.internalUrl,
++ redirectUri: config.oauth.redirectUri,
++ issuer: config.network.issuer,
++ scope: config.oauth.scope,
++ audience: config.oauth.sessionAudience,
++ secureCookies: secure,
++ httpOnlyAccess: true,
++ legacyCookies: { access: [ACCESS_COOKIE], refresh: [REFRESH_COOKIE] },
++ fetch: fetchImpl,
++ log,
++ });
++
++ const cookieBase = (opts) => ({ sameSite: 'lax', secure, httpOnly: true, path: '/', ...opts });
function setSession(res, data) {
-- res.cookie(ACCESS_COOKIE, data.access_token, { ...cookieBase(), maxAge: 24 * 60 * 60 * 1000 });
-- if (data.refresh_token) res.cookie(REFRESH_COOKIE, data.refresh_token, { ...cookieBase(), maxAge: 30 * 24 * 60 * 60 * 1000 });
-- res.cookie(HINT_COOKIE, 'account', { sameSite: 'lax', secure: config.cookies.secure, httpOnly: false, path: '/', maxAge: 365 * 24 * 60 * 60 * 1000 });
++ res.clearCookie(ACCESS_COOKIE, { path: '/' });
++ res.clearCookie(REFRESH_COOKIE, { path: '/' });
++ res.cookie(SDK_ACCESS_COOKIE, data.access_token, cookieBase({ maxAge: 24 * 60 * 60 * 1000 }));
++ if (data.refresh_token) res.cookie(SDK_REFRESH_COOKIE, data.refresh_token, cookieBase({ path: '/auth', maxAge: 30 * 24 * 60 * 60 * 1000 }));
++ res.cookie(HINT_COOKIE, 'account', { sameSite: 'lax', secure, httpOnly: false, path: '/', maxAge: 365 * 24 * 60 * 60 * 1000 });
}
function clearSession(res) {
-- res.clearCookie(ACCESS_COOKIE, cookieBase());
-- res.clearCookie(REFRESH_COOKIE, cookieBase());
-- }
--
-- /** POST the Network token endpoint (internal URL). Throws { status, error } on refusal. */
-- async function tokenGrant(fields) {
-- const body = new URLSearchParams({ client_id: config.oauth.clientId, client_secret: config.oauth.clientSecret, ...fields });
-- let res;
-- try {
-- res = await fetchImpl(`${config.network.internalUrl}/oauth/token`, {
-- method: 'POST',
-- headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
-- body, signal: AbortSignal.timeout(10_000),
-- });
-- } catch (err) {
-- throw Object.assign(new Error('OpenVibe.Network did not answer'), { status: 502, error: err && err.name === 'TimeoutError' ? 'timeout' : 'unreachable' });
-- }
-- const data = await res.json().catch(() => null);
-- if (!res.ok || !data || !data.access_token) {
-- throw Object.assign(new Error((data && (data.error_description || data.error)) || `token endpoint ${res.status}`),
-- { status: res.status, error: (data && data.error) || 'invalid_grant' });
-- }
-- return data;
++ res.clearCookie(ACCESS_COOKIE, { path: '/' });
++ res.clearCookie(REFRESH_COOKIE, { path: '/' });
++ res.clearCookie(SDK_ACCESS_COOKIE, { path: '/' });
++ res.clearCookie(SDK_REFRESH_COOKIE, { path: '/auth' });
}
--
-- /**
-- * A Services session is a Network SESSION token: audience openvibe.network and a person. The Network
-- * signs FedCM assertions (audience = any owned-zone origin that asked), app/service tokens and
-- * internal tokens with the same key and issuer; none of them may become a session here.
-- */
-- async function verifySession(token) {
-- const v = await keys.verifyUser(token, { issuer: config.network.issuer, audience: config.oauth.sessionAudience, now: now() });
-- const c = v.claims;
-- if (c && (c.typ === 'fedcm' || c.actor_type !== undefined)) return { ok: false, reason: 'not a session token' };
-- return v;
++ function readRefresh(req) {
++ const c = req.cookies || {};
++ return c[SDK_REFRESH_COOKIE] || c[REFRESH_COOKIE] || null;
}
function viewerFromClaims(claims, token) {
@@@ -146,35 +129,32 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
}
async function doRefresh(req, res) {
-- const rt = req.cookies && req.cookies[REFRESH_COOKIE];
++ const rt = readRefresh(req);
if (!rt) return null;
try {
-- const data = await tokenGrant({ grant_type: 'refresh_token', refresh_token: rt });
++ const data = await sso.tokenGrant({ grant_type: 'refresh_token', refresh_token: rt });
setSession(res, data);
-- const v = await verifySession(data.access_token);
-- return v.ok ? viewerFromClaims(v.claims, data.access_token) : null;
++ const claims = await sso.verify(data.access_token);
++ return claims ? viewerFromClaims(claims, data.access_token) : null;
} catch (err) {
if (err.status && err.status < 500) clearSession(res);
return null;
}
}
-- /** req.viewer for every page: the signed-in person, refreshed when their token expired. */
++ /** req.viewer for every page: the signed-in person (sso.optionalAuth puts req.user and req.token there). */
function middleware() {
-- return async (req, res, next) => {
-- req.viewer = { kind: 'anonymous' };
-- const token = req.cookies && req.cookies[ACCESS_COOKIE];
-- if (!token) return next();
-- await keys.ensure();
-- const v = await verifySession(token);
-- if (v.ok) { req.viewer = viewerFromClaims(v.claims, token); return next(); }
-- if (v.expired) {
-- const fresh = await refresh(req, res);
-- if (fresh) { req.viewer = fresh; return next(); }
-- }
-- if (keys.loaded()) clearSession(res);
-- next();
-- };
++ const auth = sso.optionalAuth();
++ return (req, res, next) => auth(req, res, () => {
++ if (req.user) { req.viewer = viewerFromClaims(req.user, req.token); return next(); }
++ // A token was presented but did not verify (expired, most often): refresh once with the rotating refresh
++ // token, as this portal's server-side Network calls need a live person token. No token at all: a guest.
++ if (!sso.extractToken(req) || !readRefresh(req)) { req.viewer = { kind: 'anonymous' }; return next(); }
++ refresh(req, res).then((fresh) => {
++ req.viewer = fresh || { kind: 'anonymous' };
++ next();
++ }, () => { req.viewer = { kind: 'anonymous' }; next(); });
++ });
}
/**
@@@ -183,7 +163,7 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
*/
async function asViewer(req, res, fn) {
try {
-- return await fn(req.viewer.token);
++ return await fn(req.viewer && req.viewer.token);
} catch (err) {
if (!err || err.status !== 401) throw err;
const fresh = await refresh(req, res);
@@@ -193,58 +173,41 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
}
}
++ // Sign-out ends the session, so another site must not be able to trigger it (a cross-site
++ // <img src=/auth/logout> or link). A same-origin navigation or form, or the address bar
++ // (Sec-Fetch-Site none), signs out directly; anything else gets a confirm button (POST).
++ const sameOriginRequest = (req) => {
++ const site = String(req.get('sec-fetch-site') || '');
++ if (site) return site === 'same-origin' || (site === 'none' && req.method === 'GET');
++ const origin = req.get('origin');
++ if (origin) return origin === `${req.protocol}://${req.get('host')}`;
++ return req.method === 'GET'; // no fetch metadata and no Origin: an old browser navigating
++ };
++
function routes() {
const r = express.Router();
-- const flowOpts = () => ({ ...cookieBase(), path: '/auth', maxAge: 10 * 60 * 1000 });
-- r.get('/login', (req, res) => {
-- const silent = Boolean(req.query.silent) && req.query.silent !== '0';
-- const state = crypto.randomBytes(16).toString('hex');
-- const { verifier, challenge } = pkcePair();
-- res.cookie(FLOW_COOKIE, JSON.stringify({ state, verifier, next: sanitizeNext(req.query.next, config), silent }), flowOpts());
-- res.set('Cache-Control', cache.htmlHeaders({ private: true }));
-- res.redirect(authorizeUrl(config, { state, challenge, silent }));
++ // The shared navbar's silent sign-in sends the whole page address: keep its path before the SDK sees it.
++ r.use((req, _res, next) => {
++ if (req.method === 'GET' && req.path === '/login') {
++ const target = sanitizeNext(req.query.next, config);
++ if (target === '/') delete req.query.next; else req.query.next = target;
++ }
++ next();
});
-- r.get('/callback', async (req, res) => {
++ // The navbar's { user } shape and the no-store header the shared pages expect.
++ r.get('/me', async (req, res) => {
res.set('Cache-Control', cache.htmlHeaders({ private: true }));
-- let flow = null;
-- try { flow = JSON.parse(req.cookies[FLOW_COOKIE] || 'null'); } catch { flow = null; }
-- res.clearCookie(FLOW_COOKIE, { ...cookieBase(), path: '/auth' });
-- const next = flow ? sanitizeNext(flow.next, config) : '/';
-- const { code, state, error } = req.query;
-- if (error) {
-- if ((flow && flow.silent) || error === 'login_required' || error === 'interaction_required') return res.redirect(next);
-- return res.status(400).type('text/plain').send(`Sign-in was not completed (${String(error).slice(0, 60)}).`);
-- }
-- if (!flow || typeof flow.state !== 'string' || typeof flow.verifier !== 'string' || typeof state !== 'string'
-- || state.length !== flow.state.length || !crypto.timingSafeEqual(Buffer.from(state), Buffer.from(flow.state))) {
-- return res.status(400).type('text/plain').send('Sign-in state did not match. Please try signing in again.');
-- }
-- if (!code) return res.status(400).type('text/plain').send('The Network sent no authorization code.');
-- try {
-- const data = await tokenGrant({ grant_type: 'authorization_code', code: String(code), redirect_uri: config.oauth.redirectUri, code_verifier: flow.verifier });
-- setSession(res, data);
-- // No Clear-Site-Data here or on sign-out: Chrome holds such an answer (and the cookies it sets) until the
-- // cache is cleared, which on phones left people on the account chooser with no session (2026-10-28).
-- return res.redirect(next);
-- } catch (err) {
-- log.warn('[Services] sign-in exchange failed:', err.status || '', err.error || '');
-- return res.status(err.status && err.status < 500 ? 400 : 502).type('text/plain')
-- .send(err.status && err.status < 500 ? 'The Network refused the sign-in code. Please sign in again.' : 'Sign-in failed: OpenVibe.Network did not answer. Please try again.');
++ let v = req.viewer && req.viewer.kind === 'user' ? req.viewer : null;
++ if (!v) {
++ const claims = await sso.verify(sso.extractToken(req));
++ if (claims) v = viewerFromClaims(claims, null);
}
++ if (!v) return res.json({ user: null });
++ return res.json({ user: { username: v.username, display_name: v.displayName, subject_id: v.subject, role: v.role, avatar_url: v.avatarUrl || null, profile_color: v.profileColor || null } });
});
-- // Sign-out ends the session, so another site must not be able to trigger it (a cross-site
-- // <img src=/auth/logout> or link). A same-origin navigation or form, or the address bar
-- // (Sec-Fetch-Site none), signs out directly; anything else gets a confirm button (POST).
-- const sameOriginRequest = (req) => {
-- const site = String(req.get('sec-fetch-site') || '');
-- if (site) return site === 'same-origin' || (site === 'none' && req.method === 'GET');
-- const origin = req.get('origin');
-- if (origin) return origin === `${req.protocol}://${req.get('host')}`;
-- return req.method === 'GET'; // no fetch metadata and no Origin: an old browser navigating
-- };
r.get('/logout', (req, res, next) => {
if (sameOriginRequest(req)) return next();
res.set('Cache-Control', cache.htmlHeaders({ private: true }));
@@@ -255,7 +218,7 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
});
r.post('/logout', (req, res, next) => (sameOriginRequest(req) ? next() : res.status(403).type('text/plain').send('Sign-out must come from this site.')));
r.all('/logout', async (req, res) => {
-- const rt = req.cookies && req.cookies[REFRESH_COOKIE];
++ const rt = readRefresh(req);
if (rt) {
fetchImpl(`${config.network.internalUrl}/oauth/revoke`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
@@@ -264,25 +227,15 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
}).catch(() => {});
}
clearSession(res);
-- res.cookie(HINT_COOKIE, 'guest', { sameSite: 'lax', secure: config.cookies.secure, httpOnly: false, path: '/', maxAge: 365 * 24 * 60 * 60 * 1000 });
++ res.cookie(HINT_COOKIE, 'guest', { sameSite: 'lax', secure, httpOnly: false, path: '/', maxAge: 365 * 24 * 60 * 60 * 1000 });
res.redirect(303, sanitizeNext(req.query.next, config));
});
-- r.get('/me', (req, res) => {
-- res.set('Cache-Control', cache.htmlHeaders({ private: true }));
-- // No session at all (a guest: no access or refresh cookie) 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 session cookie that is present but invalid or expired still answers 401.
-- const c = req.cookies || {};
-- if (!c[ACCESS_COOKIE] && !c[REFRESH_COOKIE] && !req.get('authorization')) return res.json({ user: null });
-- const v = req.viewer;
-- if (!v || v.kind !== 'user') return res.status(401).json({ error: 'Not signed in' });
-- res.json({ user: { username: v.username, display_name: v.displayName, subject_id: v.subject, role: v.role, avatar_url: v.avatarUrl || null, profile_color: v.profileColor || null } });
-- });
++ r.use(sso.router(express));
return r;
}
-- return { middleware, routes, asViewer, tokenGrant, pkcePair };
++ return { middleware, routes, asViewer, tokenGrant: sso.tokenGrant, pkcePair, client: sso };
}
--module.exports = { createSso, pkcePair, sanitizeNext, ownOrigins, authorizeUrl, ACCESS_COOKIE, REFRESH_COOKIE };
++module.exports = { createSso, pkcePair, sanitizeNext, ownOrigins, ACCESS_COOKIE, REFRESH_COOKIE };
ddiff --git a/server/observability.js b/server/observability.js
iindex 84287b9..a9b50f1 100644
---- a/server/observability.js
++++ b/server/observability.js
@@@ -24,7 +24,7 @@ const { jwksStatus } = require('openvibe-sdk/auth');
const { createReadiness } = require('openvibe-shared/ready');
const { TABLES } = require('./db');
--function createServicesReadiness({ store, network, outbox, docs, config, authorities, valkey = null, release = null }) {
++function createServicesReadiness({ store, network, outbox, docs, config, authorities, valkey = null, release = null, sso = null }) {
const { db } = store;
return createReadiness({
service: 'services',
@@@ -67,8 +67,15 @@ function createServicesReadiness({ store, network, outbox, docs, config, authori
},
},
{
-- name: 'oauth_client', required: false,
-- check: () => (config.oauth.clientSecret ? true : 'OV_OAUTH_CLIENT_SECRET unset: sign-in cannot complete'),
++ name: 'oauth_client', required: true,
++ check: async () => {
++ if (!config.oauth.clientSecret) return 'OV_OAUTH_CLIENT_SECRET unset: sign-in cannot complete';
++ if (!sso) return true;
++ // 'invalid': the Network refuses this client, so a deploy with a wrong secret fails at once.
++ // 'unknown' (the Network did not answer the probe) leaves readiness alone.
++ const client = await sso.client.checkClient();
++ return client === 'invalid' ? 'the Network refuses this OAuth client: check OV_OAUTH_CLIENT_ID / OV_OAUTH_CLIENT_SECRET' : true;
++ },
},
{
name: 'events_relay', required: false,
ddiff --git a/test/auth-jwks.test.js b/test/auth-jwks.test.js
iindex 11285f9..c60dfd2 100644
---- a/test/auth-jwks.test.js
++++ b/test/auth-jwks.test.js
@@@ -137,7 +137,8 @@ function jwk(k, kid) { return { ...k.export({ format: 'jwk' }), use: 'sig', alg:
// Signed by the Network, but exp is an hour in the past: the SDK's Math.floor(now / 1000) must see it.
const expired = t.network.userToken(u, { ttl: -3600 });
const me = await t.get('/auth/me', { cookie: `services_at=${expired}` });
-- assert.strictEqual(me.status, 401, `an expired cookie is not a session: ${me.status} ${me.text.slice(0, 200)}`);
++ assert.strictEqual(me.status, 200, `an expired cookie is signed out: ${me.status} ${me.text.slice(0, 200)}`);
++ assert.strictEqual(me.json().user, null, 'an expired cookie is not a session');
const page = await t.get('/', { cookie: `services_at=${expired}` });
assert.ok(page.status < 400, `a page still renders: ${page.status}`);
assert.ok(!page.text.includes('expired-demo'), 'the expired token signed nobody in');
ddiff --git a/test/auth-ops.test.js b/test/auth-ops.test.js
iindex 70ff0d2..d7ab29e 100644
---- a/test/auth-ops.test.js
++++ b/test/auth-ops.test.js
@@@ -7,6 +7,9 @@ const assert = require('assert');
const crypto = require('crypto');
const { boot, check, done } = require('./helpers/boot');
++/** Every Set-Cookie of a response as a Cookie header (the SDK's flow spans several cookies). */
++const cookieHeader = (res) => res.headers.getSetCookie().map((c) => c.split(';')[0]).join('; ');
++
(async () => {
const t = await boot();
const user = t.network.addUser('kim');
@@@ -19,45 +22,58 @@ const { boot, check, done } = require('./helpers/boot');
assert.strictEqual(loc.searchParams.get('client_id'), 'services');
assert.strictEqual(loc.searchParams.get('code_challenge_method'), 'S256');
assert.match(loc.searchParams.get('code_challenge'), /^[A-Za-z0-9_-]{43}$/);
-- assert.match(loc.searchParams.get('state'), /^[0-9a-f]{32}$/);
-- assert.match(r.headers.get('set-cookie'), /services_oauth=.*Path=\/auth.*HttpOnly/i);
++ assert.match(loc.searchParams.get('state'), /^[A-Za-z0-9_-]{32}$/);
++ const set = r.headers.getSetCookie().join('\n');
++ assert.match(set, /ov_oauth_state=[^;]+;.*Path=\/auth.*HttpOnly/i);
++ assert.match(set, /ov_oauth_verifier=[^;]+;.*Path=\/auth.*HttpOnly/i);
++ assert.match(set, /ov_oauth_next=%2Fprojects|ov_oauth_next=\/projects/);
});
await check('callback exchanges the code with the matching verifier and sets httpOnly session cookies', async () => {
const login = await t.get('/auth/login?next=/projects');
const loc = new URL(login.headers.get('location'));
-- const flowCookie = login.headers.get('set-cookie').split(';')[0];
++ const flowCookie = cookieHeader(login);
const code = t.network.issueCode(user, loc.searchParams.get('code_challenge'));
const r = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`, { cookie: flowCookie });
assert.strictEqual(r.status, 302, r.text);
assert.strictEqual(r.headers.get('location'), '/projects');
const set = r.headers.get('set-cookie');
-- assert.match(set, /services_at=[^;]+;.*HttpOnly/i);
-- assert.match(set, /services_rt=[^;]+;.*HttpOnly/i);
-- const at = set.match(/services_at=([^;]+)/)[1];
-- const me = await t.get('/auth/me', { cookie: `services_at=${at}` });
++ assert.match(set, /ov_token=[^;]+;.*HttpOnly/i);
++ assert.match(set, /ov_refresh=[^;]+;.*HttpOnly/i);
++ assert.match(set, /services_at=;/, 'the legacy access cookie is cleared once the SDK session is written');
++ const at = set.match(/ov_token=([^;]+)/)[1];
++ const me = await t.get('/auth/me', { cookie: `ov_token=${at}` });
assert.strictEqual(me.json().user.username, 'kim');
assert.ok(!me.text.includes(at), '/auth/me never returns the token');
++ const legacy = await t.get('/auth/me', { cookie: `services_at=${t.network.userToken(user)}` });
++ assert.strictEqual(legacy.json().user.username, 'kim');
});
-- await check('a wrong state or a verifier that does not match is refused', async () => {
++ await check('a lost flow or a used code recovers once, then shows the page (never a bare line)', async () => {
const login = await t.get('/auth/login');
const loc = new URL(login.headers.get('location'));
-- const flowCookie = login.headers.get('set-cookie').split(';')[0];
++ const flowCookie = cookieHeader(login);
const code = t.network.issueCode(user, loc.searchParams.get('code_challenge'));
-- const bad = await t.get(`/auth/callback?code=${code}&state=${'0'.repeat(32)}`, { cookie: flowCookie });
-- assert.strictEqual(bad.status, 400);
++ const lost = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`);
++ assert.strictEqual(lost.status, 302, 'a lost flow starts the sign-in once more');
++ assert.strictEqual(lost.headers.get('location'), '/auth/login');
++ assert.match(lost.headers.get('set-cookie'), /ov_oauth_retry=1/);
++ const again = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`, { cookie: 'ov_oauth_retry=1' });
++ assert.strictEqual(again.status, 400);
++ assert.match(again.text, /Try again/);
const other = t.network.issueCode(user, crypto.createHash('sha256').update('another-verifier').digest('base64url'));
const mismatch = await t.get(`/auth/callback?code=${other}&state=${loc.searchParams.get('state')}`, { cookie: flowCookie });
-- assert.strictEqual(mismatch.status, 400, 'Network refuses the PKCE check; Services reports it');
-- const noCookie = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`);
-- assert.strictEqual(noCookie.status, 400);
++ assert.strictEqual(mismatch.status, 302, 'a code the Network refuses starts the sign-in once more');
++ const mismatchAgain = await t.get(`/auth/callback?code=${other}&state=${loc.searchParams.get('state')}`, { cookie: `${flowCookie}; ov_oauth_retry=1` });
++ assert.strictEqual(mismatchAgain.status, 400, 'the second failure shows the page');
});
await check('next= only accepts same-site paths', async () => {
const r = await t.get('/auth/login?next=//evil.example/x');
-- const flow = decodeURIComponent(r.headers.get('set-cookie').match(/services_oauth=([^;]+)/)[1]);
-- assert.strictEqual(JSON.parse(flow).next, '/');
++ const nextCookie = r.headers.getSetCookie().find((c) => c.startsWith('ov_oauth_next='));
++ assert.ok(!nextCookie || /^ov_oauth_next=;/.test(nextCookie), 'nothing off-site is remembered as next');
++ const loc = new URL(r.headers.get('location'));
++ assert.strictEqual(loc.searchParams.get('client_id'), 'services');
});
await check('forms need the form token and a same-site Origin', async () => {
@@@ -69,7 +85,7 @@ const { boot, check, done } = require('./helpers/boot');
assert.strictEqual(ok.status, 303);
});
-- await check('readiness is truthful: required db + docs; Network, relay and client are optional', async () => {
++ await check('readiness is truthful: required db, docs and OAuth client; Network and relay optional', async () => {
const r = await t.get('/api/ready');
const b = r.json();
assert.strictEqual(r.status, 200);
@@@ -79,6 +95,8 @@ const { boot, check, done } = require('./helpers/boot');
assert.strictEqual(b.checks.network.status, 'ok');
assert.strictEqual(b.checks.events_relay.status, 'fail', 'EVENTS_URL is unset in this boot, and it says so');
assert.ok(b.degraded.includes('events_relay'));
++ assert.strictEqual(b.checks.oauth_client.status, 'ok');
++ assert.strictEqual(b.checks.oauth_client.required, true);
});
await check('/release.json and /metrics (loopback only)', async () => {
ddiff --git a/test/scaffold.test.js b/test/scaffold.test.js
iindex b2cd36b..16390ed 100644
---- a/test/scaffold.test.js
++++ b/test/scaffold.test.js
@@@ -23,18 +23,21 @@ async function main() {
assert.strictEqual(r.json.events.pending, 0); // nothing has happened in this boot
});
-- await check('readiness: GET /api/ready requires the database and the docs; the rest degrades, never fails', async () => {
++ await check('readiness: GET /api/ready requires the database, the docs and an accepted OAuth client', async () => {
const r = await t.call('GET', '/api/ready', { token: null });
-- assert.strictEqual(r.status, 200, r.text);
-- assert.strictEqual(r.json.ready, true, r.text);
++ // This stub Network refuses the OAuth client (it has no /oauth/token grant for it): a wrong client must
++ // fail the deploy's readiness at once, never read green.
++ assert.strictEqual(r.status, 503, r.text);
++ assert.strictEqual(r.json.ready, false, r.text);
assert.strictEqual(r.json.service, 'services');
-- for (const name of ['db', 'docs']) {
-- assert.strictEqual(r.json.checks[name].status, 'ok', name);
++ for (const name of ['db', 'docs', 'oauth_client']) {
assert.strictEqual(r.json.checks[name].required, true, name);
}
++ for (const name of ['db', 'docs']) assert.strictEqual(r.json.checks[name].status, 'ok', name);
++ assert.strictEqual(r.json.checks.oauth_client.status, 'fail', 'the refused client is named');
++ assert.deepStrictEqual(r.json.failed, ['oauth_client']);
assert.strictEqual(r.json.checks.network_jwks.status, 'ok'); // the stub Network's key is loaded
assert.strictEqual(r.json.checks.network_jwks.required, false); // docs and tools serve without it
-- assert.deepStrictEqual(r.json.failed, []);
// The relay is off in this boot (no EVENTS_URL): reported as degraded, never as ready.
assert.ok(r.json.degraded.includes('events_relay'), r.text);
assert.deepStrictEqual(r.json.authorities, { count: 0, ids: [] });
ddiff --git a/test/secrets.test.js b/test/secrets.test.js
iindex da49c96..89da0a9 100644
---- a/test/secrets.test.js
++++ b/test/secrets.test.js
@@@ -115,11 +115,14 @@ const { boot, check, done } = require('./helpers/boot');
});
await check('session cookies are httpOnly (no script can read the Network token)', async () => {
-- const code = t.network.issueCode(owner, 'x');
-- void code;
const login = await t.get('/auth/login?next=/projects');
-- const flow = login.headers.get('set-cookie');
-- assert.match(flow, /services_oauth=.*HttpOnly/i);
++ const loc = new URL(login.headers.get('location'));
++ const flowCookie = login.headers.getSetCookie().map((c) => c.split(';')[0]).join('; ');
++ const code = t.network.issueCode(owner, loc.searchParams.get('code_challenge'));
++ const cb = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`, { cookie: flowCookie });
++ const set = cb.headers.getSetCookie().join('\n');
++ assert.match(set, /ov_token=[^;]+;.*HttpOnly/i);
++ assert.match(set, /ov_refresh=[^;]+;.*HttpOnly/i);
});
await t.close();
ddiff --git a/test/security-session.test.js b/test/security-session.test.js
iindex 5cd5b84..4238360 100644
---- a/test/security-session.test.js
++++ b/test/security-session.test.js
@@@ -35,16 +35,20 @@ const { signJwt } = require('./helpers/mocks');
await check('an app token is not a Services session', async () => {
const token = signJwt({ iss: s.network.url, sub: `app:${APP}`, actor_type: 'app', aud: ['openvibe.network'], cap: ['x.y.z'], subject_id: staff.subject, iat: now(), exp: now() + 300 }, s.network.privatePem);
const me = await s.get('/auth/me', { cookie: `services_at=${token}` });
-- assert.strictEqual(me.status, 401);
++ assert.strictEqual(me.status, 200);
++ assert.strictEqual(JSON.parse(me.text).user, null);
});
-- await check('/auth/me: a guest is signed out (200 { user: null }); a session cookie that fails is 401', async () => {
++ await check('/auth/me: a guest and a session that fails are both 200 { user: null } (the SDK shape)', async () => {
const guest = await s.get('/auth/me');
assert.strictEqual(guest.status, 200, 'no session cookie at all: not an error');
assert.deepStrictEqual(JSON.parse(guest.text), { user: null });
assert.strictEqual(guest.headers.get('cache-control'), 'private, no-store');
-- assert.strictEqual((await s.get('/auth/me', { cookie: 'services_at=garbage' })).status, 401, 'a present but invalid access cookie');
-- assert.strictEqual((await s.get('/auth/me', { cookie: 'services_rt=stale' })).status, 401, 'a refresh cookie alone is a session that did not resolve');
++ for (const cookie of ['services_at=garbage', 'services_rt=stale']) {
++ const r = await s.get('/auth/me', { cookie });
++ assert.strictEqual(r.status, 200, `${cookie}: a signed-out answer, not an error`);
++ assert.strictEqual(JSON.parse(r.text).user, null, `${cookie} signs nobody in`);
++ }
assert.strictEqual((await s.get('/auth/me', { as: staff })).status, 200);
});