openvibers/openvibe.surf Commits
Surf: sign-in on openvibe-sdk/sso 0.73.0 (#12)
Changes
@@@ -15,7 +15,7 @@"express-rate-limit": "^7.5.0","helmet": "^8.1.0","openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.232.0",-- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.70.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.45.0"},"engines": {@@@ -1075,9 +1075,9 @@}},"node_modules/openvibe-sdk": {-- "version": "0.70.0",-- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.70.0",-- "integrity": "sha512-iMNxlnRm0fmyj60nHiC/lKAaG3JAqiJgu42lShnkby4yF4dQJRG3G0trrqOoULZKBalrYHb/gjauRwNQYN/tog==",++ "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"@@@ -21,7 +21,7 @@"express-rate-limit": "^7.5.0","helmet": "^8.1.0","openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.232.0",-- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.70.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.45.0"},"engines": {@@@ -81,7 +81,7 @@ function createApp(opts = {}) {// ── Machine endpoints ───────────────────────────────────app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-surf', version: VERSION }));-- const readiness = createServiceReadiness({ config, feed, ride, keys, release: release.release, fetchImpl });++ const readiness = createServiceReadiness({ config, feed, ride, keys, release: release.release, fetchImpl, sso });app.get('/api/ready', readiness.handler);app.use(contracts.http.middleware());@@@ -1,32 +1,31 @@'use strict';/**-- * Sign-in with OpenVibe.Network: OAuth 2 authorization code with PKCE (S256), as OAuth client `surf`.++ * Sign-in with OpenVibe.Network, on openvibe-sdk/sso (0.73.0) instead of this site's own copy of the OAuth client.*-- * 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++ * 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.Surf's own surface on top of it:*-- * The person's Network access token lives in an httpOnly cookie (surf_at) no script can read: with it, a script-- * could act as them. The refresh token (surf_rt) is httpOnly too. Neither is ever stored server-side, rendered-- * or logged.++ * middleware() req.viewer (the page renderer's shape), 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 call as the person, refreshing once on 401++ * tokenGrant(fields) a token request with this site's client++ *++ * The browser is sent to authorize on the Network's PUBLIC origin; token grants and the JWKS go to the internal one.++ * The old names (surf_at, surf_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 { createSsoClient } = require('openvibe-sdk/sso');const ACCESS_COOKIE = 'surf_at';const REFRESH_COOKIE = 'surf_rt';const HINT_COOKIE = 'ov_sso_hint';--const FLOW_COOKIE = 'surf_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 (the one origin OpenVibe.Surf is served from). */function ownOrigins(config) {@@@ -43,8 +42,6 @@ function ownOrigins(config) {* person signed in quietly should land on the page they asked for.*/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;@@@ -56,64 +53,51 @@ 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.networkPublicUrl || config.networkUrl}/oauth/authorize?${q.toString()}`;++function pkcePair() {++ 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: 'surf',++ siteName: 'OpenVibe.Surf',++ baseUrl: config.baseUrl,++ clientId: config.oauth.clientId,++ clientSecret: config.oauth.clientSecret,++ networkUrl: config.networkPublicUrl || config.networkUrl,++ networkInternalUrl: config.networkInternalUrl || config.networkUrl,++ redirectUri: config.oauth.redirectUri,++ issuer: config.networkIssuer || config.networkPublicUrl || config.networkUrl,++ 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.networkInternalUrl || config.networkUrl}/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' });}---- /**-- * An OpenVibe.Surf 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.networkIssuer || config.networkPublicUrl || config.networkUrl, 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) {@@@ -140,35 +124,30 @@ 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, refreshed once when the token they presented has expired. */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(); }++ 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(); });++ });}/**@@@ -177,7 +156,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);@@@ -187,58 +166,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.-- return res.redirect(next);-- } catch (err) {-- log.warn('[OpenVibe.Surf] 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 }));@@@ -249,7 +211,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.networkInternalUrl || config.networkUrl}/oauth/revoke`, {method: 'POST', headers: { 'Content-Type': 'application/json' },@@@ -258,25 +220,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. 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 };@@@ -15,7 +15,7 @@*/const { createReadiness } = require('openvibe-shared/ready');--function createServiceReadiness({ config, feed, ride, keys = null, release = null, fetchImpl = globalThis.fetch }) {++function createServiceReadiness({ config, feed, ride, keys = null, release = null, fetchImpl = globalThis.fetch, sso = null }) {return createReadiness({service: 'surf',release,@@@ -41,7 +41,17 @@ function createServiceReadiness({ config, feed, ride, keys = null, release = nulrequired: false,check: () => (keys && keys.loaded() ? true : 'Network signing key not loaded yet: sign-in is unavailable'),},-- { 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: 'live', required: false, check: () => feed.probe() },{ name: 'games', required: false, check: () => ride.probe() },{@@@ -70,7 +70,10 @@ async function startNetwork() {if (url.pathname === '/api/.well-known/jwks') return json(200, { public_key: publicPem, algorithm: 'RS256' });if (url.pathname === '/oauth/revoke') return json(200, {});if (url.pathname === '/oauth/token' && req.method === 'POST') {-- const form = Object.fromEntries(new URLSearchParams(text));++ // The SDK sends application/json; the site's old module sent a form. Accept both.++ const form = String(req.headers['content-type'] || '').includes('json')++ ? (() => { try { return JSON.parse(text) || {}; } catch { return {}; } })()++ : Object.fromEntries(new URLSearchParams(text));st.tokenRequests.push(form);if (form.client_id !== 'surf' || form.client_secret !== 'surf-secret') return json(401, { error: 'invalid_client', error_description: 'bad client secret' });if (form.grant_type === 'authorization_code') {@@@ -44,39 +44,41 @@ const cookieNamed = (r, name) => {assert.strictEqual(loc.searchParams.get('scope'), 'profile');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}$/);-- const flow = cookieNamed(r, 'surf_oauth');-- assert.ok(flow, 'the flow cookie is set');-- assert.match(cookies(r).find((c) => c.includes('surf_oauth=')), /Path=\/auth.*HttpOnly/i);-- const payload = JSON.parse(decodeURIComponent(flow.split('=')[1]));-- assert.strictEqual(payload.next, '/web');-- assert.strictEqual(payload.silent, false);++ assert.match(loc.searchParams.get('state'), /^[A-Za-z0-9_-]{32}$/);++ const all = cookies(r).join('\n');++ assert.match(all, /ov_oauth_state=[^;]+;.*Path=\/auth.*HttpOnly/i);++ assert.match(all, /ov_oauth_verifier=[^;]+;.*Path=\/auth.*HttpOnly/i);++ const next = cookieNamed(r, 'ov_oauth_next');++ assert.ok(next, 'the page to return to is set');++ assert.strictEqual(decodeURIComponent(next.split('=')[1]), '/web');});await check('silent sign-in adds prompt=none and next= only keeps this site', async () => {const r = await t.get('/auth/login?silent=1&next=' + encodeURIComponent('https://evil.example/x'));const loc = new URL(r.headers.get('location'));assert.strictEqual(loc.searchParams.get('prompt'), 'none');-- const flow = JSON.parse(decodeURIComponent(cookieNamed(r, 'surf_oauth').split('=')[1]));-- assert.strictEqual(flow.next, '/', 'another origin goes home');++ const offSite = cookieNamed(r, 'ov_oauth_next');++ assert.ok(!offSite, 'another origin is not remembered as next');const own = await t.get('/auth/login?next=' + encodeURIComponent('https://openvibe.surf/ride/surf_lagoon?x=1'));-- const ownFlow = JSON.parse(decodeURIComponent(cookieNamed(own, 'surf_oauth').split('=')[1]));-- assert.strictEqual(ownFlow.next, '/ride/surf_lagoon?x=1');++ const ownNext = cookieNamed(own, 'ov_oauth_next');++ assert.ok(ownNext, 'this site\'s own page is remembered');++ assert.strictEqual(decodeURIComponent(ownNext.split('=')[1]), '/ride/surf_lagoon?x=1');});-- await check('the callback exchanges the code and sets httpOnly surf_at/surf_rt cookies', async () => {++ await check('the callback exchanges the code and sets httpOnly ov_token/ov_refresh cookies', async () => {const login = await t.get('/auth/login?next=/web');const loc = new URL(login.headers.get('location'));-- const flowCookie = cookieNamed(login, 'surf_oauth');++ const flowCookie = cookies(login).map((c) => c.split(';')[0]).join('; ');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'), '/web');const all = cookies(r).join('\n');-- assert.match(all, /surf_at=[^;]+;.*HttpOnly/i);-- assert.match(all, /surf_rt=[^;]+;.*HttpOnly/i);++ assert.match(all, /ov_token=[^;]+;.*HttpOnly/i);++ assert.match(all, /ov_refresh=[^;]+;.*HttpOnly/i);++ assert.match(all, /surf_at=;/, 'the legacy access cookie is cleared once the SDK session is written');assert.ok(!/SameSite=None/i.test(all), 'SameSite=Lax, not None');-- const at = cookieNamed(r, 'surf_at');++ const at = cookieNamed(r, 'ov_token');assert.ok(at, 'the access cookie is set');const me = await t.get('/auth/me', { cookie: at });assert.strictEqual(me.status, 200);@@@ -89,26 +91,30 @@ const cookieNamed = (r, name) => {assert.ok(tokenRequest.code_verifier, 'the verifier is sent server-side');});-- await check('a wrong state or no flow cookie is refused', async () => {++ await check('a lost flow or a wrong state recovers once, then shows the page', async () => {const login = await t.get('/auth/login');const loc = new URL(login.headers.get('location'));-- const flowCookie = cookieNamed(login, 'surf_oauth');++ const flowCookie = cookies(login).map((c) => c.split(';')[0]).join('; ');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);++ assert.strictEqual(bad.status, 302, 'the sign-in starts once more');++ assert.strictEqual(bad.headers.get('location'), '/auth/login');++ const badAgain = await t.get(`/auth/callback?code=${code}&state=${'0'.repeat(32)}`, { cookie: 'ov_oauth_retry=1' });++ assert.strictEqual(badAgain.status, 400, 'the second failure shows the page');++ assert.match(badAgain.text, /Try again/);const noCookie = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`);-- assert.strictEqual(noCookie.status, 400);++ assert.strictEqual(noCookie.status, 302, 'a lost flow cookie starts the sign-in once more');const none = await t.get('/auth/callback?state=x');-- assert.strictEqual(none.status, 400);++ assert.strictEqual(none.status, 400, 'no code at all is the page, not a retry');});-- await check('/auth/me is null for a guest and 401 for a cookie that does not verify', async () => {++ await check('/auth/me is null for a guest and for a cookie that does not verify (the SDK shape)', async () => {const guest = await t.get('/auth/me');assert.strictEqual(guest.status, 200);assert.deepStrictEqual(guest.json(), { user: null });const bad = await t.get('/auth/me', { cookie: 'surf_at=not-a-token' });-- assert.strictEqual(bad.status, 401);-- assert.strictEqual(bad.json().error, 'Not signed in');++ assert.strictEqual(bad.status, 200);++ assert.deepStrictEqual(bad.json(), { user: null });});await check('sign-out clears the cookies and returns to next', async () => {
@@ -15,7 +15,7 @@
@@ -15,7 +15,7 @@
"express-rate-limit": "^7.5.0",
"express-rate-limit": "^7.5.0",
"helmet": "^8.1.0",
"helmet": "^8.1.0",
"openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.232.0",
"openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.232.0",
- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.70.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.45.0"
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.45.0"
},
},
"engines": {
"engines": {
@@ -1075,9 +1075,9 @@
@@ -1075,9 +1075,9 @@
}
}
},
},
"node_modules/openvibe-sdk": {
"node_modules/openvibe-sdk": {
- "version": "0.70.0",
- "resolved": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.70.0",
- "integrity": "sha512-iMNxlnRm0fmyj60nHiC/lKAaG3JAqiJgu42lShnkby4yF4dQJRG3G0trrqOoULZKBalrYHb/gjauRwNQYN/tog==",
+ "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",
"license": "MIT",
"bin": {
"bin": {
"openvibe-download": "bin/openvibe-download.js"
"openvibe-download": "bin/openvibe-download.js"
@@ -21,7 +21,7 @@
@@ -21,7 +21,7 @@
"express-rate-limit": "^7.5.0",
"express-rate-limit": "^7.5.0",
"helmet": "^8.1.0",
"helmet": "^8.1.0",
"openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.232.0",
"openvibe-contracts": "https://codeload.github.com/OpenVibers/OpenVibe.Contracts/tar.gz/refs/tags/v0.232.0",
- "openvibe-sdk": "https://codeload.github.com/OpenVibers/OpenVibe.SDK/tar.gz/refs/tags/v0.70.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.45.0"
"openvibe-shared": "https://codeload.github.com/OpenVibers/OpenVibe.Shared/tar.gz/refs/tags/v4.45.0"
},
},
"engines": {
"engines": {
@@ -81,7 +81,7 @@ function createApp(opts = {}) {
@@ -81,7 +81,7 @@ function createApp(opts = {}) {
// ── Machine endpoints ───────────────────────────────────
// ── Machine endpoints ───────────────────────────────────
app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-surf', version: VERSION }));
app.get('/api/health', (_req, res) => res.json({ status: 'ok', service: 'openvibe-surf', version: VERSION }));
- const readiness = createServiceReadiness({ config, feed, ride, keys, release: release.release, fetchImpl });
+ const readiness = createServiceReadiness({ config, feed, ride, keys, release: release.release, fetchImpl, sso });
app.get('/api/ready', readiness.handler);
app.get('/api/ready', readiness.handler);
app.use(contracts.http.middleware());
app.use(contracts.http.middleware());
@@ -1,32 +1,31 @@
@@ -1,32 +1,31 @@
'use strict';
'use strict';
/**
/**
- * Sign-in with OpenVibe.Network: OAuth 2 authorization code with PKCE (S256), as OAuth client `surf`.
+ * Sign-in with OpenVibe.Network, on openvibe-sdk/sso (0.73.0) instead of this site's own copy of the OAuth client.
*
*
- * 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
+ * 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.Surf's own surface on top of it:
*
*
- * The person's Network access token lives in an httpOnly cookie (surf_at) no script can read: with it, a script
- * could act as them. The refresh token (surf_rt) is httpOnly too. Neither is ever stored server-side, rendered
- * or logged.
+ * middleware() req.viewer (the page renderer's shape), 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 call as the person, refreshing once on 401
+ * tokenGrant(fields) a token request with this site's client
+ *
+ * The browser is sent to authorize on the Network's PUBLIC origin; token grants and the JWKS go to the internal one.
+ * The old names (surf_at, surf_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 crypto = require('crypto');
const express = require('express');
const express = require('express');
const cache = require('openvibe-shared/cache-policy');
const cache = require('openvibe-shared/cache-policy');
+const { createSsoClient } = require('openvibe-sdk/sso');
const ACCESS_COOKIE = 'surf_at';
const ACCESS_COOKIE = 'surf_at';
const REFRESH_COOKIE = 'surf_rt';
const REFRESH_COOKIE = 'surf_rt';
const HINT_COOKIE = 'ov_sso_hint';
const HINT_COOKIE = 'ov_sso_hint';
-const FLOW_COOKIE = 'surf_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 (the one origin OpenVibe.Surf is served from). */
/** This site's own origins: BASE_URL (the one origin OpenVibe.Surf is served from). */
function ownOrigins(config) {
function ownOrigins(config) {
@@ -43,8 +42,6 @@ function ownOrigins(config) {
@@ -43,8 +42,6 @@ function ownOrigins(config) {
* person signed in quietly should land on the page they asked for.
* person signed in quietly should land on the page they asked for.
*/
*/
function sanitizeNext(next, config) {
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' && /[\u0000-\u001f\u007f\\]/.test(next)) return '/';
if (typeof next === 'string' && /^https?:\/\//i.test(next)) {
if (typeof next === 'string' && /^https?:\/\//i.test(next)) {
let u = null;
let u = null;
@@ -56,64 +53,51 @@ function sanitizeNext(next, config) {
@@ -56,64 +53,51 @@ function sanitizeNext(next, config) {
return next;
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.networkPublicUrl || config.networkUrl}/oauth/authorize?${q.toString()}`;
+function pkcePair() {
+ 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 }) {
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: 'surf',
+ siteName: 'OpenVibe.Surf',
+ baseUrl: config.baseUrl,
+ clientId: config.oauth.clientId,
+ clientSecret: config.oauth.clientSecret,
+ networkUrl: config.networkPublicUrl || config.networkUrl,
+ networkInternalUrl: config.networkInternalUrl || config.networkUrl,
+ redirectUri: config.oauth.redirectUri,
+ issuer: config.networkIssuer || config.networkPublicUrl || config.networkUrl,
+ 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) {
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) {
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.networkInternalUrl || config.networkUrl}/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' });
}
}
-
- /**
- * An OpenVibe.Surf 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.networkIssuer || config.networkPublicUrl || config.networkUrl, 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) {
function viewerFromClaims(claims, token) {
@@ -140,35 +124,30 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
@@ -140,35 +124,30 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
}
}
async function doRefresh(req, res) {
async function doRefresh(req, res) {
- const rt = req.cookies && req.cookies[REFRESH_COOKIE];
+ const rt = readRefresh(req);
if (!rt) return null;
if (!rt) return null;
try {
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);
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) {
} catch (err) {
if (err.status && err.status < 500) clearSession(res);
if (err.status && err.status < 500) clearSession(res);
return null;
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, refreshed once when the token they presented has expired. */
function middleware() {
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(); }
+ 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(); });
+ });
}
}
/**
/**
@@ -177,7 +156,7 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
@@ -177,7 +156,7 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
*/
*/
async function asViewer(req, res, fn) {
async function asViewer(req, res, fn) {
try {
try {
- return await fn(req.viewer.token);
+ return await fn(req.viewer && req.viewer.token);
} catch (err) {
} catch (err) {
if (!err || err.status !== 401) throw err;
if (!err || err.status !== 401) throw err;
const fresh = await refresh(req, res);
const fresh = await refresh(req, res);
@@ -187,58 +166,41 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
@@ -187,58 +166,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() {
function routes() {
const r = express.Router();
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 }));
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.
- return res.redirect(next);
- } catch (err) {
- log.warn('[OpenVibe.Surf] 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) => {
r.get('/logout', (req, res, next) => {
if (sameOriginRequest(req)) return next();
if (sameOriginRequest(req)) return next();
res.set('Cache-Control', cache.htmlHeaders({ private: true }));
res.set('Cache-Control', cache.htmlHeaders({ private: true }));
@@ -249,7 +211,7 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
@@ -249,7 +211,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.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) => {
r.all('/logout', async (req, res) => {
- const rt = req.cookies && req.cookies[REFRESH_COOKIE];
+ const rt = readRefresh(req);
if (rt) {
if (rt) {
fetchImpl(`${config.networkInternalUrl || config.networkUrl}/oauth/revoke`, {
fetchImpl(`${config.networkInternalUrl || config.networkUrl}/oauth/revoke`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
method: 'POST', headers: { 'Content-Type': 'application/json' },
@@ -258,25 +220,15 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
@@ -258,25 +220,15 @@ function createSso({ config, keys, fetchImpl = globalThis.fetch, now = () => Dat
}).catch(() => {});
}).catch(() => {});
}
}
clearSession(res);
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));
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. 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 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 };
@@ -15,7 +15,7 @@
@@ -15,7 +15,7 @@
*/
*/
const { createReadiness } = require('openvibe-shared/ready');
const { createReadiness } = require('openvibe-shared/ready');
-function createServiceReadiness({ config, feed, ride, keys = null, release = null, fetchImpl = globalThis.fetch }) {
+function createServiceReadiness({ config, feed, ride, keys = null, release = null, fetchImpl = globalThis.fetch, sso = null }) {
return createReadiness({
return createReadiness({
service: 'surf',
service: 'surf',
release,
release,
@@ -41,7 +41,17 @@ function createServiceReadiness({ config, feed, ride, keys = null, release = nul
@@ -41,7 +41,17 @@ function createServiceReadiness({ config, feed, ride, keys = null, release = nul
required: false,
required: false,
check: () => (keys && keys.loaded() ? true : 'Network signing key not loaded yet: sign-in is unavailable'),
check: () => (keys && keys.loaded() ? true : 'Network signing key not loaded yet: sign-in is unavailable'),
},
},
- { 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: 'live', required: false, check: () => feed.probe() },
{ name: 'live', required: false, check: () => feed.probe() },
{ name: 'games', required: false, check: () => ride.probe() },
{ name: 'games', required: false, check: () => ride.probe() },
{
{
@@ -70,7 +70,10 @@ async function startNetwork() {
@@ -70,7 +70,10 @@ async function startNetwork() {
if (url.pathname === '/api/.well-known/jwks') return json(200, { public_key: publicPem, algorithm: 'RS256' });
if (url.pathname === '/api/.well-known/jwks') return json(200, { public_key: publicPem, algorithm: 'RS256' });
if (url.pathname === '/oauth/revoke') return json(200, {});
if (url.pathname === '/oauth/revoke') return json(200, {});
if (url.pathname === '/oauth/token' && req.method === 'POST') {
if (url.pathname === '/oauth/token' && req.method === 'POST') {
- const form = Object.fromEntries(new URLSearchParams(text));
+ // The SDK sends application/json; the site's old module sent a form. Accept both.
+ const form = String(req.headers['content-type'] || '').includes('json')
+ ? (() => { try { return JSON.parse(text) || {}; } catch { return {}; } })()
+ : Object.fromEntries(new URLSearchParams(text));
st.tokenRequests.push(form);
st.tokenRequests.push(form);
if (form.client_id !== 'surf' || form.client_secret !== 'surf-secret') return json(401, { error: 'invalid_client', error_description: 'bad client secret' });
if (form.client_id !== 'surf' || form.client_secret !== 'surf-secret') return json(401, { error: 'invalid_client', error_description: 'bad client secret' });
if (form.grant_type === 'authorization_code') {
if (form.grant_type === 'authorization_code') {
@@ -44,39 +44,41 @@ const cookieNamed = (r, name) => {
@@ -44,39 +44,41 @@ const cookieNamed = (r, name) => {
assert.strictEqual(loc.searchParams.get('scope'), 'profile');
assert.strictEqual(loc.searchParams.get('scope'), 'profile');
assert.strictEqual(loc.searchParams.get('code_challenge_method'), 'S256');
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('code_challenge'), /^[A-Za-z0-9_-]{43}$/);
- assert.match(loc.searchParams.get('state'), /^[0-9a-f]{32}$/);
- const flow = cookieNamed(r, 'surf_oauth');
- assert.ok(flow, 'the flow cookie is set');
- assert.match(cookies(r).find((c) => c.includes('surf_oauth=')), /Path=\/auth.*HttpOnly/i);
- const payload = JSON.parse(decodeURIComponent(flow.split('=')[1]));
- assert.strictEqual(payload.next, '/web');
- assert.strictEqual(payload.silent, false);
+ assert.match(loc.searchParams.get('state'), /^[A-Za-z0-9_-]{32}$/);
+ const all = cookies(r).join('\n');
+ assert.match(all, /ov_oauth_state=[^;]+;.*Path=\/auth.*HttpOnly/i);
+ assert.match(all, /ov_oauth_verifier=[^;]+;.*Path=\/auth.*HttpOnly/i);
+ const next = cookieNamed(r, 'ov_oauth_next');
+ assert.ok(next, 'the page to return to is set');
+ assert.strictEqual(decodeURIComponent(next.split('=')[1]), '/web');
});
});
await check('silent sign-in adds prompt=none and next= only keeps this site', async () => {
await check('silent sign-in adds prompt=none and next= only keeps this site', async () => {
const r = await t.get('/auth/login?silent=1&next=' + encodeURIComponent('https://evil.example/x'));
const r = await t.get('/auth/login?silent=1&next=' + encodeURIComponent('https://evil.example/x'));
const loc = new URL(r.headers.get('location'));
const loc = new URL(r.headers.get('location'));
assert.strictEqual(loc.searchParams.get('prompt'), 'none');
assert.strictEqual(loc.searchParams.get('prompt'), 'none');
- const flow = JSON.parse(decodeURIComponent(cookieNamed(r, 'surf_oauth').split('=')[1]));
- assert.strictEqual(flow.next, '/', 'another origin goes home');
+ const offSite = cookieNamed(r, 'ov_oauth_next');
+ assert.ok(!offSite, 'another origin is not remembered as next');
const own = await t.get('/auth/login?next=' + encodeURIComponent('https://openvibe.surf/ride/surf_lagoon?x=1'));
const own = await t.get('/auth/login?next=' + encodeURIComponent('https://openvibe.surf/ride/surf_lagoon?x=1'));
- const ownFlow = JSON.parse(decodeURIComponent(cookieNamed(own, 'surf_oauth').split('=')[1]));
- assert.strictEqual(ownFlow.next, '/ride/surf_lagoon?x=1');
+ const ownNext = cookieNamed(own, 'ov_oauth_next');
+ assert.ok(ownNext, 'this site\'s own page is remembered');
+ assert.strictEqual(decodeURIComponent(ownNext.split('=')[1]), '/ride/surf_lagoon?x=1');
});
});
- await check('the callback exchanges the code and sets httpOnly surf_at/surf_rt cookies', async () => {
+ await check('the callback exchanges the code and sets httpOnly ov_token/ov_refresh cookies', async () => {
const login = await t.get('/auth/login?next=/web');
const login = await t.get('/auth/login?next=/web');
const loc = new URL(login.headers.get('location'));
const loc = new URL(login.headers.get('location'));
- const flowCookie = cookieNamed(login, 'surf_oauth');
+ const flowCookie = cookies(login).map((c) => c.split(';')[0]).join('; ');
const code = t.network.issueCode(user, loc.searchParams.get('code_challenge'));
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 });
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.status, 302, r.text);
assert.strictEqual(r.headers.get('location'), '/web');
assert.strictEqual(r.headers.get('location'), '/web');
const all = cookies(r).join('\n');
const all = cookies(r).join('\n');
- assert.match(all, /surf_at=[^;]+;.*HttpOnly/i);
- assert.match(all, /surf_rt=[^;]+;.*HttpOnly/i);
+ assert.match(all, /ov_token=[^;]+;.*HttpOnly/i);
+ assert.match(all, /ov_refresh=[^;]+;.*HttpOnly/i);
+ assert.match(all, /surf_at=;/, 'the legacy access cookie is cleared once the SDK session is written');
assert.ok(!/SameSite=None/i.test(all), 'SameSite=Lax, not None');
assert.ok(!/SameSite=None/i.test(all), 'SameSite=Lax, not None');
- const at = cookieNamed(r, 'surf_at');
+ const at = cookieNamed(r, 'ov_token');
assert.ok(at, 'the access cookie is set');
assert.ok(at, 'the access cookie is set');
const me = await t.get('/auth/me', { cookie: at });
const me = await t.get('/auth/me', { cookie: at });
assert.strictEqual(me.status, 200);
assert.strictEqual(me.status, 200);
@@ -89,26 +91,30 @@ const cookieNamed = (r, name) => {
@@ -89,26 +91,30 @@ const cookieNamed = (r, name) => {
assert.ok(tokenRequest.code_verifier, 'the verifier is sent server-side');
assert.ok(tokenRequest.code_verifier, 'the verifier is sent server-side');
});
});
- await check('a wrong state or no flow cookie is refused', async () => {
+ await check('a lost flow or a wrong state recovers once, then shows the page', async () => {
const login = await t.get('/auth/login');
const login = await t.get('/auth/login');
const loc = new URL(login.headers.get('location'));
const loc = new URL(login.headers.get('location'));
- const flowCookie = cookieNamed(login, 'surf_oauth');
+ const flowCookie = cookies(login).map((c) => c.split(';')[0]).join('; ');
const code = t.network.issueCode(user, loc.searchParams.get('code_challenge'));
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 });
const bad = await t.get(`/auth/callback?code=${code}&state=${'0'.repeat(32)}`, { cookie: flowCookie });
- assert.strictEqual(bad.status, 400);
+ assert.strictEqual(bad.status, 302, 'the sign-in starts once more');
+ assert.strictEqual(bad.headers.get('location'), '/auth/login');
+ const badAgain = await t.get(`/auth/callback?code=${code}&state=${'0'.repeat(32)}`, { cookie: 'ov_oauth_retry=1' });
+ assert.strictEqual(badAgain.status, 400, 'the second failure shows the page');
+ assert.match(badAgain.text, /Try again/);
const noCookie = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`);
const noCookie = await t.get(`/auth/callback?code=${code}&state=${loc.searchParams.get('state')}`);
- assert.strictEqual(noCookie.status, 400);
+ assert.strictEqual(noCookie.status, 302, 'a lost flow cookie starts the sign-in once more');
const none = await t.get('/auth/callback?state=x');
const none = await t.get('/auth/callback?state=x');
- assert.strictEqual(none.status, 400);
+ assert.strictEqual(none.status, 400, 'no code at all is the page, not a retry');
});
});
- await check('/auth/me is null for a guest and 401 for a cookie that does not verify', async () => {
+ await check('/auth/me is null for a guest and for a cookie that does not verify (the SDK shape)', async () => {
const guest = await t.get('/auth/me');
const guest = await t.get('/auth/me');
assert.strictEqual(guest.status, 200);
assert.strictEqual(guest.status, 200);
assert.deepStrictEqual(guest.json(), { user: null });
assert.deepStrictEqual(guest.json(), { user: null });
const bad = await t.get('/auth/me', { cookie: 'surf_at=not-a-token' });
const bad = await t.get('/auth/me', { cookie: 'surf_at=not-a-token' });
- assert.strictEqual(bad.status, 401);
- assert.strictEqual(bad.json().error, 'Not signed in');
+ assert.strictEqual(bad.status, 200);
+ assert.deepStrictEqual(bad.json(), { user: null });
});
});
await check('sign-out clears the cookies and returns to next', async () => {
await check('sign-out clears the cookies and returns to next', async () => {