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
2 changes: 1 addition & 1 deletion src/components/OurTools/OurTools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const OurTools: FC<OurToolsProps> = ({
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 = {
Expand Down
133 changes: 133 additions & 0 deletions src/lib/sso/windrunnerToken.ts
Original file line number Diff line number Diff line change
@@ -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, string>): 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the comment says hashing means the log "never names a person", but a truncated unsalted SHA-256 of a small sequential integer id is trivially reversible by enumeration. Either salt it (HMAC with a server secret) or soften the claim.

: undefined,
};
console.log(JSON.stringify(line));
};
151 changes: 151 additions & 0 deletions src/pages/api/sso/windrunner.ts
Original file line number Diff line number Diff line change
@@ -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<SsoUser | null> => {
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<string, unknown>,
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,
);
}
Loading
Loading