Repository navigation
fix(uxcore): Bob on Windrunner, sign in on Windrunner with a KeepSimple account #263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bb8b6b1
fix(uxcore): point Bob links to windrunner.si/bob
manager 91a2703
feat(sso): sign in on Windrunner with a KeepSimple account
manager 28bda45
fix(sso): review round one for the Windrunner bridge
manager e33678e
fix(sso): review round two for the Windrunner bridge
manager File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| : undefined, | ||
| }; | ||
| console.log(JSON.stringify(line)); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| ); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.