From 1cd63b9e76c77851e0b6868942a76140e73a96b8 Mon Sep 17 00:00:00 2001 From: manager Date: Sun, 6 Dec 2026 12:57:56 +0000 Subject: [PATCH] feat(sso): create KeepSimple accounts from Windrunner's Google sign-in Windrunner signs visitors in with its own Google client, so they never see a KeepSimple page. Its server posts the Google access token; we confirm with Google that the token was issued to Windrunner and the email is verified, let Strapi find or create the account by that Google identity, and answer with the existing signed assertion. The Strapi session is discarded. Co-Authored-By: Claude Opus 5.5 --- src/lib/sso/windrunnerGoogle.ts | 90 ++++++++++++++++++++ src/pages/api/sso/windrunner-google.ts | 109 +++++++++++++++++++++++++ 2 files changed, 199 insertions(+) create mode 100644 src/lib/sso/windrunnerGoogle.ts create mode 100644 src/pages/api/sso/windrunner-google.ts diff --git a/src/lib/sso/windrunnerGoogle.ts b/src/lib/sso/windrunnerGoogle.ts new file mode 100644 index 00000000..1f31f5af --- /dev/null +++ b/src/lib/sso/windrunnerGoogle.ts @@ -0,0 +1,90 @@ +// Server-only. Windrunner signs visitors in with its own Google client and +// never shows them a KeepSimple page. Its server hands us the Google access +// token; we confirm with Google that the token was issued to Windrunner's +// client, then let Strapi find or create the KeepSimple account for that +// Google identity, exactly as a Google sign-in on keepsimple.io does. + +// Google OAuth client IDs that belong to Windrunner. Client IDs are public: +// they travel in every Google sign-in URL. An empty list keeps the endpoint +// closed. +export const WINDRUNNER_GOOGLE_CLIENT_IDS: readonly string[] = [ + '854079612714-6e7e8c3upvo9nbv00p3lalmjjgrej4ib.apps.googleusercontent.com', +]; + +const GOOGLE_TOKENINFO = 'https://oauth2.googleapis.com/tokeninfo'; +const TIMEOUT_MS = 5000; + +export class UpstreamUnavailable extends Error {} + +export type GoogleTokenInfo = { + aud?: string; + azp?: string; + email?: string; + email_verified?: string | boolean; + expires_in?: string | number; +}; + +// null = Google does not recognise the token (expired, revoked, forged). +export const fetchGoogleTokenInfo = async ( + accessToken: string, +): Promise => { + const response = await fetch(GOOGLE_TOKENINFO, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ access_token: accessToken }).toString(), + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + if (response.status === 400 || response.status === 401) return null; + if (!response.ok) throw new UpstreamUnavailable(String(response.status)); + const body = await response.json().catch(() => null); + if (!body || typeof body !== 'object') { + throw new UpstreamUnavailable('bad body'); + } + return body as GoogleTokenInfo; +}; + +export const isWindrunnerClient = (info: GoogleTokenInfo): boolean => { + const client = info.azp || info.aud; + return Boolean(client) && WINDRUNNER_GOOGLE_CLIENT_IDS.includes(client); +}; + +export const isEmailVerified = (info: GoogleTokenInfo): boolean => + Boolean(info.email) && + (info.email_verified === true || info.email_verified === 'true'); + +export type StrapiGoogleResult = + | { kind: 'user'; user: Record & { id: number | string } } + | { kind: 'email-taken' } + | { kind: 'refused' }; + +// Strapi's own Google callback: it asks Google who owns the token and finds +// or creates the account by that email. The Strapi session it returns is +// dropped here and never leaves this server. +export const strapiGoogleSignIn = async ( + accessToken: string, +): Promise => { + const base = process.env.NEXT_PUBLIC_STRAPI; + if (!base) throw new UpstreamUnavailable('no strapi url'); + const url = `${base}/api/auth/google/callback?${new URLSearchParams({ + access_token: accessToken, + })}`; + const response = await fetch(url, { + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + const body = await response.json().catch(() => null); + if (response.ok && body?.jwt && body?.user?.id != null) { + return { kind: 'user', user: body.user }; + } + if (response.status >= 500 || response.status === 429 || !body) { + throw new UpstreamUnavailable(String(response.status)); + } + const message: string = + body?.error?.message || + body?.message?.[0]?.messages?.[0]?.message || + (typeof body?.message === 'string' ? body.message : '') || + ''; + // Same reading as the browser sign-in: the email is bound to another + // sign-in method on KeepSimple. + if (/taken|exist/i.test(message)) return { kind: 'email-taken' }; + return { kind: 'refused' }; +}; diff --git a/src/pages/api/sso/windrunner-google.ts b/src/pages/api/sso/windrunner-google.ts new file mode 100644 index 00000000..cbaf9dc1 --- /dev/null +++ b/src/pages/api/sso/windrunner-google.ts @@ -0,0 +1,109 @@ +import type { NextApiRequest, NextApiResponse } from 'next'; + +import { + fetchGoogleTokenInfo, + isEmailVerified, + isWindrunnerClient, + strapiGoogleSignIn, + WINDRUNNER_GOOGLE_CLIENT_IDS, +} from '@lib/sso/windrunnerGoogle'; +import { + getSigningKey, + logSso, + signWindrunnerAssertion, + SSO_STATE_PATTERN, + type SsoUser, +} from '@lib/sso/windrunnerToken'; + +// POST /api/sso/windrunner-google +// Server to server. Windrunner signs a visitor in with its own Google client +// and posts { access_token, nonce }. We check with Google that the token was +// issued to Windrunner, let Strapi find or create the KeepSimple account for +// that Google identity, and answer with the same signed assertion the +// browser bridge issues. The KeepSimple session Strapi creates is discarded. + +const MAX_TOKEN_LENGTH = 4096; + +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: `google:${why}`, status, sub }); + return res.status(status).json(body); + }; + + if (req.method !== 'POST') { + res.setHeader('Allow', 'POST'); + return reply(405, 'method', { error: 'invalid_request' }); + } + + const accessToken = + typeof req.body?.access_token === 'string' ? req.body.access_token : ''; + const nonce = typeof req.body?.nonce === 'string' ? req.body.nonce : ''; + if ( + !accessToken || + accessToken.length > MAX_TOKEN_LENGTH || + !SSO_STATE_PATTERN.test(nonce) + ) { + return reply(400, 'request', { error: 'invalid_request' }); + } + + const key = getSigningKey(); + if (!key || WINDRUNNER_GOOGLE_CLIENT_IDS.length === 0) { + return reply(503, key ? 'no-client' : 'no-key', { error: 'server_error' }); + } + + let info; + try { + info = await fetchGoogleTokenInfo(accessToken); + } catch { + return reply(502, 'google', { error: 'temporarily_unavailable' }); + } + if (!info) return reply(401, 'token', { error: 'invalid_token' }); + if (!isWindrunnerClient(info)) { + return reply(403, 'client', { error: 'unauthorized_client' }); + } + if (!isEmailVerified(info)) { + return reply(403, 'email-unverified', { error: 'access_denied' }); + } + + let result; + try { + result = await strapiGoogleSignIn(accessToken); + } catch { + return reply(502, 'strapi', { error: 'temporarily_unavailable' }); + } + if (result.kind === 'email-taken') { + return reply(409, 'email-taken', { error: 'account_conflict' }); + } + if (result.kind === 'refused') { + return reply(401, 'strapi-refused', { error: 'invalid_token' }); + } + + const user = result.user as SsoUser & { blocked?: boolean }; + const sub = String(user.id); + if (user.blocked) { + return reply(403, 'blocked', { error: 'access_denied' }, sub); + } + const email = String(user.email || '').toLowerCase(); + if (!email || email !== String(info.email).toLowerCase()) { + return reply(403, 'email-mismatch', { error: 'access_denied' }, sub); + } + + // The account was reached through Google, so the address is verified + // whatever method created it. + const token = signWindrunnerAssertion( + key, + { ...user, provider: 'google' }, + nonce, + ); + return reply(200, 'issued', { token }, sub); +}