Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions src/lib/sso/windrunnerGoogle.ts
Original file line number Diff line number Diff line change
@@ -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<GoogleTokenInfo | null> => {
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<string, unknown> & { 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<StrapiGoogleResult> => {
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' };
};
109 changes: 109 additions & 0 deletions src/pages/api/sso/windrunner-google.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>,
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);
}
Loading