feat: add non-interactive SSO login flow for embedded/iframe deployments (closes #69)

This commit is contained in:
Linus Rath
2026-03-21 20:45:19 +01:00
parent 7c3c3b5f7b
commit 83a0a1e235
18 changed files with 674 additions and 123 deletions
+35
View File
@@ -48,3 +48,38 @@ export function decryptSession(token: string): { serverUrl: string; username: st
return null;
}
}
export function encryptPayload(payload: Record<string, unknown>): string {
const key = getKey();
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(ALGORITHM, key, iv);
const json = JSON.stringify(payload);
const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, encrypted]).toString('base64');
}
export function decryptPayload(token: string): Record<string, unknown> | null {
try {
const key = getKey();
const data = Buffer.from(token, 'base64');
if (data.length < IV_LENGTH + TAG_LENGTH) return null;
const iv = data.subarray(0, IV_LENGTH);
const tag = data.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
const encrypted = data.subarray(IV_LENGTH + TAG_LENGTH);
const decipher = createDecipheriv(ALGORITHM, key, iv);
decipher.setAuthTag(tag);
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
return JSON.parse(decrypted.toString('utf8'));
} catch (error) {
logger.warn('Payload decryption failed', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return null;
}
}
+40
View File
@@ -0,0 +1,40 @@
const PARENT_ORIGIN = typeof window !== 'undefined'
? (document.querySelector('meta[name="parent-origin"]')?.getAttribute('content') || '')
: '';
export function isEmbedded(): boolean {
try {
return window.self !== window.top;
} catch {
return true;
}
}
export function notifyParent(type: string, payload: Record<string, unknown> = {}) {
if (!isEmbedded()) return;
const targetOrigin = PARENT_ORIGIN || '*';
try {
window.parent.postMessage({ source: 'bulwark', type, ...payload }, targetOrigin);
} catch {
// Cross-origin postMessage may fail in restricted contexts
}
}
export function listenFromParent(
handler: (msg: { type: string; [k: string]: unknown }) => void,
allowedOrigin?: string,
): () => void {
const listener = (event: MessageEvent) => {
// Validate origin if configured
if (allowedOrigin && event.origin !== allowedOrigin) return;
// Only accept messages from the portal
if (!event.data || event.data.source !== 'portal') return;
handler(event.data);
};
window.addEventListener('message', listener);
return () => window.removeEventListener('message', listener);
}
+11
View File
@@ -0,0 +1,11 @@
const COOKIE_SAME_SITE = (process.env.COOKIE_SAME_SITE || 'lax') as 'lax' | 'none' | 'strict';
export function getCookieOptions() {
return {
httpOnly: true,
secure: COOKIE_SAME_SITE === 'none' ? true : process.env.NODE_ENV === 'production',
sameSite: COOKIE_SAME_SITE,
path: '/',
maxAge: 30 * 24 * 60 * 60,
};
}
+18
View File
@@ -0,0 +1,18 @@
import { randomBytes, createHash } from 'node:crypto';
function base64urlEncode(buffer: Buffer): string {
return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function generateCodeVerifierServer(): string {
return base64urlEncode(randomBytes(32));
}
export function generateCodeChallengeServer(verifier: string): string {
const hash = createHash('sha256').update(verifier).digest();
return base64urlEncode(hash);
}
export function generateStateServer(): string {
return base64urlEncode(randomBytes(32));
}
+88
View File
@@ -0,0 +1,88 @@
import { logger } from '@/lib/logger';
import { discoverOAuth } from '@/lib/oauth/discovery';
import type { OAuthMetadata } from '@/lib/oauth/discovery';
const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '';
export function getRequiredConfig() {
const clientId = process.env.OAUTH_CLIENT_ID;
const serverUrl = process.env.JMAP_SERVER_URL || process.env.NEXT_PUBLIC_JMAP_SERVER_URL;
const issuerUrl = process.env.OAUTH_ISSUER_URL;
if (!clientId || !serverUrl) {
throw new Error(`OAuth misconfigured: ${[!clientId && 'OAUTH_CLIENT_ID', !serverUrl && 'JMAP_SERVER_URL'].filter(Boolean).join(', ')} not set`);
}
const discoveryUrl = issuerUrl?.trim() || serverUrl;
if (issuerUrl !== undefined && !issuerUrl.trim()) {
logger.warn('OAUTH_ISSUER_URL is set but empty, falling back to JMAP_SERVER_URL for discovery');
}
return { clientId, serverUrl, discoveryUrl };
}
export async function getTokenEndpoint(): Promise<string> {
const { discoveryUrl } = getRequiredConfig();
const metadata = await discoverOAuth(discoveryUrl);
if (!metadata?.token_endpoint) {
throw new Error('OAuth token endpoint not found');
}
return metadata.token_endpoint;
}
export async function getMetadata(): Promise<OAuthMetadata | null> {
const { discoveryUrl } = getRequiredConfig();
return discoverOAuth(discoveryUrl);
}
export function buildOAuthParams(base: Record<string, string>): URLSearchParams {
const { clientId } = getRequiredConfig();
const params = new URLSearchParams({ ...base, client_id: clientId });
if (CLIENT_SECRET) {
params.set('client_secret', CLIENT_SECRET);
}
return params;
}
export interface TokenResult {
access_token: string;
expires_in: number;
refresh_token?: string;
}
export async function exchangeCodeForTokens(
code: string,
codeVerifier: string,
redirectUri: string,
): Promise<TokenResult> {
const tokenEndpoint = await getTokenEndpoint();
const params = buildOAuthParams({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier,
});
const tokenResponse = await fetch(tokenEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params.toString(),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
logger.error('Token exchange failed', { status: tokenResponse.status, error: errorText });
throw new Error('Token exchange failed');
}
const tokens = await tokenResponse.json();
if (!tokens.access_token) {
logger.error('Token response missing access_token', { response: JSON.stringify(tokens).substring(0, 500) });
throw new Error('Invalid token response');
}
return {
access_token: tokens.access_token,
expires_in: tokens.expires_in || 3600,
refresh_token: tokens.refresh_token,
};
}