diff --git a/src/components/OurTools/OurTools.tsx b/src/components/OurTools/OurTools.tsx index 21fea6ac..fe4ed731 100644 --- a/src/components/OurTools/OurTools.tsx +++ b/src/components/OurTools/OurTools.tsx @@ -44,7 +44,7 @@ const OurTools: FC = ({ const urls = { uxcore: '/uxcore', 'company-management': '/company-management', - bob: 'https://chat.openai.com/g/g-BtuSiGF18-bob-trickery-and-deception-by-ux-core', + bob: 'https://windrunner.si/bob', }; const icons = { diff --git a/src/lib/sso/windrunnerToken.ts b/src/lib/sso/windrunnerToken.ts new file mode 100644 index 00000000..f889994e --- /dev/null +++ b/src/lib/sso/windrunnerToken.ts @@ -0,0 +1,133 @@ +import { + createHash, + createPrivateKey, + createPublicKey, + KeyObject, + randomBytes, + sign, +} from 'crypto'; + +// Server-only. Signs the one-time identity assertion that lets a KeepSimple +// account sign in on Windrunner. KeepSimple holds the Ed25519 private key; +// Windrunner pins the public key, so Windrunner can check an assertion but +// can never mint one. + +export const SSO_TOKEN_TTL_SECONDS = 120; +export const SSO_STATE_PATTERN = /^[A-Za-z0-9_-]{16,128}$/; + +const DEFAULT_CALLBACK = 'https://windrunner.si/auth/keepsimple'; + +// Providers whose sign-in proves the visitor controls the email address. +// Other providers can hand Strapi a placeholder or an unchecked address, so +// they are reported unverified even when the address happens to be real. +const VERIFIED_EMAIL_PROVIDERS = new Set(['google', 'magic-link']); + +export type SsoUser = { + id: number | string; + email?: string | null; + username?: string | null; + name?: string | null; + surname?: string | null; + provider?: string | null; +}; + +const b64url = (input: Buffer | string): string => + Buffer.from(input).toString('base64url'); + +let cachedKey: KeyObject | null | undefined; + +export const getSigningKey = (): KeyObject | null => { + if (cachedKey !== undefined) return cachedKey; + const raw = process.env.WINDRUNNER_SSO_PRIVATE_KEY; + if (!raw) { + cachedKey = null; + return cachedKey; + } + try { + const key = createPrivateKey({ + key: Buffer.from(raw, 'base64'), + format: 'der', + type: 'pkcs8', + }); + cachedKey = key.asymmetricKeyType === 'ed25519' ? key : null; + } catch { + cachedKey = null; + } + return cachedKey; +}; + +export const keyId = (key: KeyObject): string => { + const spki = createPublicKey(key).export({ format: 'der', type: 'spki' }); + return createHash('sha256').update(spki).digest('base64url').slice(0, 16); +}; + +export const getCallbackUrl = (): URL => { + const url = new URL(process.env.WINDRUNNER_SSO_CALLBACK || DEFAULT_CALLBACK); + if (url.protocol !== 'https:') throw new Error('callback must be https'); + return url; +}; + +export const getIssuer = (): string => + new URL(process.env.NEXTAUTH_URL || 'https://keepsimple.io').origin; + +export const displayName = (user: SsoUser): string => { + const full = [user.name, user.surname].filter(Boolean).join(' ').trim(); + return full || user.username || ''; +}; + +export const signWindrunnerAssertion = ( + key: KeyObject, + user: SsoUser, + nonce: string, + now: number = Math.floor(Date.now() / 1000), +): string => { + const provider = String(user.provider || ''); + const header = { alg: 'EdDSA', typ: 'JWT', kid: keyId(key) }; + const payload = { + iss: getIssuer(), + aud: getCallbackUrl().origin, + sub: String(user.id), + email: String(user.email || '').toLowerCase(), + email_verified: VERIFIED_EMAIL_PROVIDERS.has(provider), + name: displayName(user), + provider, + nonce, + iat: now, + exp: now + SSO_TOKEN_TTL_SECONDS, + jti: randomBytes(16).toString('base64url'), + }; + const signingInput = `${b64url(JSON.stringify(header))}.${b64url( + JSON.stringify(payload), + )}`; + const signature = sign(null, Buffer.from(signingInput), key); + return `${signingInput}.${b64url(signature)}`; +}; + +// Parameters travel in the URL fragment: browsers never send it to a server, +// so the assertion and the email inside it stay out of every access log. +export const callbackRedirect = (params: Record): string => { + const url = getCallbackUrl(); + url.hash = new URLSearchParams(params).toString(); + return url.toString(); +}; + +// One JSON line per request: the trail of this mechanism. The account id is +// hashed so the log never names a person. +export const logSso = (entry: { + ok: boolean; + why: string; + status: number; + sub?: string; +}): void => { + const line = { + ts: new Date().toISOString(), + evt: 'sso.windrunner', + ok: entry.ok, + why: entry.why, + status: entry.status, + user: entry.sub + ? createHash('sha256').update(entry.sub).digest('hex').slice(0, 12) + : undefined, + }; + console.log(JSON.stringify(line)); +}; diff --git a/src/pages/api/sso/windrunner.ts b/src/pages/api/sso/windrunner.ts new file mode 100644 index 00000000..983b67ea --- /dev/null +++ b/src/pages/api/sso/windrunner.ts @@ -0,0 +1,151 @@ +import type { NextApiRequest, NextApiResponse } from 'next'; + +import { + callbackRedirect, + getSigningKey, + logSso, + signWindrunnerAssertion, + SSO_STATE_PATTERN, + type SsoUser, +} from '@lib/sso/windrunnerToken'; + +// POST /api/sso/windrunner +// Called by /sso/windrunner in the visitor's own browser, with the visitor's +// KeepSimple session as a Bearer token. Strapi confirms who the session +// belongs to; we answer with the Windrunner callback URL carrying a signed, +// short-lived assertion. Nothing here writes to Strapi or touches the +// existing sign-in flow. + +const STRAPI_TIMEOUT_MS = 5000; + +class StrapiUnavailable extends Error {} + +// null = Strapi refused the session (401). Anything else that is not a user, +// a 403 from a proxy or access rule included, throws StrapiUnavailable, so an +// outage never reads as a bad session and never signs anyone out. +const fetchStrapiUser = async (jwt: string): Promise => { + const base = process.env.NEXT_PUBLIC_STRAPI; + if (!base) throw new StrapiUnavailable('no strapi url'); + const response = await fetch(`${base}/api/users/me`, { + headers: { Authorization: `Bearer ${jwt}` }, + signal: AbortSignal.timeout(STRAPI_TIMEOUT_MS), + }); + if (response.status === 401) return null; + if (!response.ok) throw new StrapiUnavailable(String(response.status)); + const body = await response.json().catch(() => null); + if (!body || body.id == null) throw new StrapiUnavailable('bad body'); + return body as SsoUser; +}; + +// Same-origin check against the host this request was served on, so it holds +// on every environment whatever NEXTAUTH_URL says. +const isSameOrigin = (req: NextApiRequest): boolean => { + const origin = req.headers.origin; + if (!origin) return false; + const forwarded = req.headers['x-forwarded-host']; + const host = + (Array.isArray(forwarded) ? forwarded[0] : forwarded) + ?.split(',')[0] + .trim() || req.headers.host; + try { + return Boolean(host) && new URL(origin).host === host; + } catch { + return false; + } +}; + +export default async function handler( + req: NextApiRequest, + res: NextApiResponse, +) { + res.setHeader('Cache-Control', 'no-store'); + + const reply = ( + status: number, + why: string, + body: Record, + sub?: string, + ) => { + logSso({ ok: status === 200, why, status, sub }); + return res.status(status).json(body); + }; + + if (req.method !== 'POST') { + res.setHeader('Allow', 'POST'); + return reply(405, 'method', { error: 'method' }); + } + + if (!isSameOrigin(req)) { + return reply(403, 'origin', { + error: 'origin', + redirect: callbackRedirect({ error: 'invalid_request' }), + }); + } + + const state = typeof req.body?.state === 'string' ? req.body.state : ''; + if (!SSO_STATE_PATTERN.test(state)) { + return reply(400, 'state', { + error: 'state', + redirect: callbackRedirect({ error: 'invalid_request' }), + }); + } + + const key = getSigningKey(); + if (!key) { + return reply(503, 'no-key', { + error: 'unavailable', + redirect: callbackRedirect({ error: 'server_error', state }), + }); + } + + const auth = req.headers.authorization || ''; + const jwt = auth.startsWith('Bearer ') ? auth.slice(7).trim() : ''; + if (!jwt || jwt.length > 4096) { + return reply(401, 'no-session', { error: 'session' }); + } + + let user: SsoUser | null = null; + try { + user = await fetchStrapiUser(jwt); + } catch { + return reply(502, 'strapi', { + error: 'unavailable', + redirect: callbackRedirect({ error: 'temporarily_unavailable', state }), + }); + } + if (!user) { + return reply(401, 'session-refused', { error: 'session' }); + } + + const sub = String(user.id); + if ((user as { blocked?: boolean }).blocked) { + return reply( + 403, + 'blocked', + { + error: 'denied', + redirect: callbackRedirect({ error: 'access_denied', state }), + }, + sub, + ); + } + if (!user.email) { + return reply( + 403, + 'no-email', + { + error: 'denied', + redirect: callbackRedirect({ error: 'access_denied', state }), + }, + sub, + ); + } + + const token = signWindrunnerAssertion(key, user, state); + return reply( + 200, + 'issued', + { redirect: callbackRedirect({ token, state }) }, + sub, + ); +} diff --git a/src/pages/sso/windrunner.tsx b/src/pages/sso/windrunner.tsx new file mode 100644 index 00000000..0ba21a56 --- /dev/null +++ b/src/pages/sso/windrunner.tsx @@ -0,0 +1,125 @@ +import Head from 'next/head'; +import { useRouter } from 'next/router'; +import { FC, useEffect, useState } from 'react'; + +import { deleteRedirectCookie } from '@lib/cookies'; +import { getAccessToken, removeCookie } from '@lib/library/cookie'; + +import AuthLoader from '@components/AuthLoader'; +import LogIn from '@components/LogIn'; + +// Windrunner sends a visitor here to sign in with their KeepSimple account. +// Signed in: the server confirms the session and we hand the visitor back to +// Windrunner with a signed assertion. Not signed in: the usual KeepSimple +// sign-in opens, and every sign-in path returns here through the redirect +// cookie. The only session change this page makes is the one the app already +// makes everywhere: a token Strapi refuses is dropped. + +// An emailed sign-in link lives 15 minutes; the return cookie outlives it so +// a visitor who signs in by email still comes back to Windrunner. +const RETURN_COOKIE_SECONDS = 30 * 60; + +// Used only when the server could not be reached to name the callback. +const FALLBACK_CALLBACK = 'https://windrunner.si/auth/keepsimple'; + +const rememberReturn = (path: string) => { + document.cookie = `redirectAfterLogin=${encodeURIComponent( + path, + )}; path=/; max-age=${RETURN_COOKIE_SECONDS}`; +}; + +const WindrunnerSso: FC = () => { + const router = useRouter(); + const [showLogIn, setShowLogIn] = useState(false); + + useEffect(() => { + if (!router.isReady) return; + let cancelled = false; + + const askForSignIn = () => { + if (cancelled) return; + rememberReturn(router.asPath); + setShowLogIn(true); + }; + + const state = Array.isArray(router.query.state) + ? router.query.state[0] + : router.query.state; + + const leave = (url?: string) => { + if (cancelled) return; + if (url) { + window.location.replace(url); + return; + } + const params = new URLSearchParams({ error: 'temporarily_unavailable' }); + if (state) params.set('state', state); + window.location.replace(`${FALLBACK_CALLBACK}#${params}`); + }; + + const jwt = getAccessToken(); + if (!jwt) { + askForSignIn(); + return; + } + + fetch('/api/sso/windrunner', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${jwt}`, + }, + body: JSON.stringify({ state: state ?? '' }), + }) + .then(async response => { + const body = await response.json().catch(() => null); + if (response.status === 401) { + // Strapi refused this token: drop it the way the rest of the app + // does, so the sign-in below starts clean instead of stalling on + // a dead session. + if (getAccessToken() === jwt) { + localStorage.removeItem('accessToken'); + removeCookie('accessToken'); + window.dispatchEvent(new Event('auth:expired')); + } + askForSignIn(); + return; + } + if (getAccessToken() !== jwt) { + // The account changed in another tab while we waited: start over + // with the session the browser holds now. + if (!cancelled) window.location.reload(); + return; + } + leave(typeof body?.redirect === 'string' ? body.redirect : undefined); + }) + .catch(() => leave()); + + return () => { + cancelled = true; + }; + }, [router.isReady]); + + const handleLogInVisibility = (show: boolean) => { + setShowLogIn(show); + if (!show) { + deleteRedirectCookie(); + router.back(); + } + }; + + return ( + <> + + + + {showLogIn ? ( + + ) : ( + + )} + + ); +}; + +export default WindrunnerSso; diff --git a/src/uxcore/components/PageSwitcher/PageSwitcher.tsx b/src/uxcore/components/PageSwitcher/PageSwitcher.tsx index fc87228a..266869cf 100644 --- a/src/uxcore/components/PageSwitcher/PageSwitcher.tsx +++ b/src/uxcore/components/PageSwitcher/PageSwitcher.tsx @@ -19,8 +19,7 @@ type TPageSwitcher = { const PageSwitcher: FC = ({ page }) => { const router = useRouter(); const { locale } = router as TRouter; - const bobUrl = - 'https://chatgpt.com/g/g-BtuSiGF18-bob-bias-trickery-and-deception-by-uxcore-io/'; + const bobUrl = 'https://windrunner.si/bob'; const arcUrl = 'https://arc-of-self.com/?uxcore'; const handleKeyPress = useCallback( diff --git a/src/uxcore/components/ToolHeader/navItems.tsx b/src/uxcore/components/ToolHeader/navItems.tsx index 252cd0b8..63a09d4a 100644 --- a/src/uxcore/components/ToolHeader/navItems.tsx +++ b/src/uxcore/components/ToolHeader/navItems.tsx @@ -31,7 +31,7 @@ export const navItems = [ }, { label: 'Bob - AI Assistant', - href: 'https://chatgpt.com/g/g-BtuSiGF18-bob-bias-trickery-and-deception-by-uxcore-io/', + href: 'https://windrunner.si/bob', page: '', icon: '', external: true, diff --git a/src/uxcore/layouts/TestResult/TestResultLayout.tsx b/src/uxcore/layouts/TestResult/TestResultLayout.tsx index a688ce5c..4d426e8e 100644 --- a/src/uxcore/layouts/TestResult/TestResultLayout.tsx +++ b/src/uxcore/layouts/TestResult/TestResultLayout.tsx @@ -1,20 +1,5 @@ -import cn from 'classnames'; -import Image from 'next/image'; -import { useRouter } from 'next/router'; -import React, { FC, useContext, useEffect, useState } from 'react'; -import Skeleton from 'react-loading-skeleton'; - -import type { TRouter } from '@uxcore/local-types/global'; -import { uxCatLevels } from '@uxcore/local-types/uxcat-types/types'; - -import { isLevelMilestone } from '@uxcore/lib/uxcat-helpers'; - import { userInfoUpdate } from '@uxcore/api/uxcat/settings'; - -import testResultData from '@uxcore/data/uxcat/testResult'; - import BobIconWhite from '@uxcore/assets/icons/BobIconWhite'; - import AddToCalendar from '@uxcore/components/AddToCalendar'; import Button from '@uxcore/components/Button'; import CompletionBar from '@uxcore/components/CompletionBar'; @@ -24,6 +9,15 @@ import Result from '@uxcore/components/Result'; import ScorePanel from '@uxcore/components/ScorePanel'; import TestResultsAchievements from '@uxcore/components/TestResultsAchievements'; import Toasts from '@uxcore/components/Toasts'; +import testResultData from '@uxcore/data/uxcat/testResult'; +import { isLevelMilestone } from '@uxcore/lib/uxcat-helpers'; +import type { TRouter } from '@uxcore/local-types/global'; +import { uxCatLevels } from '@uxcore/local-types/uxcat-types/types'; +import cn from 'classnames'; +import Image from 'next/image'; +import { useRouter } from 'next/router'; +import React, { FC, useContext, useEffect, useState } from 'react'; +import Skeleton from 'react-loading-skeleton'; import 'react-toastify/dist/ReactToastify.css'; import styles from './TestResultLayout.module.scss'; @@ -105,8 +99,7 @@ const TestResultLayout: FC = ({ const testStartUrlFinal = finalTestInProgress ? '/uxcat/ongoing' : '/uxcat/start-test'; - const bobUrl = - 'https://chatgpt.com/g/g-BtuSiGF18-bob-bias-trickery-and-deception-by-uxcore-io/'; + const bobUrl = 'https://windrunner.si/bob'; const { greatJobTxt,