Files
SRCmail/app/api/jitsi/token/route.ts
T
Bernd Rodler 150adf5a27
PR Verify / verify (pull_request) Successful in 1m0s
fix(jitsi): read session from stalwart auth context, not basic-auth session cookie
In OAuth/OIDC-only mode the webmail never sets the basic-auth session cookie
(sessionCookieName(0)); the login stores auth in the jmap_stalwart_ctx cookie
via /api/auth/stalwart-context. The route was 401-ing for every real user.
2026-08-31 01:24:54 +02:00

74 lines
2.5 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { createHmac } from 'node:crypto';
import { readStalwartAuthContext } from '@/lib/stalwart/auth-context';
import { logger } from '@/lib/logger';
const JITSI_URL = (process.env.JITSI_URL || 'https://meet.src-advisory.com').replace(/\/+$/, '');
function base64url(input: Buffer): string {
return input.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function b64u(input: string): string {
return Buffer.from(input).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export async function POST(request: NextRequest) {
try {
const appId = process.env.JITSI_APP_ID;
const appSecret = process.env.JITSI_APP_SECRET;
if (!appId || !appSecret) {
return NextResponse.json({ error: 'Jitsi is not configured' }, { status: 503 });
}
// In OAuth/OIDC mode the session lives in the `jmap_stalwart_ctx` cookie
// (written by /api/auth/stalwart-context), not the basic-auth session
// cookie. The username there is the primary identity email.
const ctx = await readStalwartAuthContext(0);
const email = ctx?.username;
if (!email) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json().catch(() => ({}));
const room = typeof body.room === 'string' ? body.room.trim() : '';
if (!room || !/^[a-z0-9-]{1,100}$/i.test(room)) {
return NextResponse.json({ error: 'Invalid room name' }, { status: 400 });
}
const domain = new URL(JITSI_URL).hostname;
const now = Math.floor(Date.now() / 1000);
const header = { alg: 'HS256', typ: 'JWT' };
const payload = {
iss: 'bulwark-webmail',
sub: domain,
aud: appId,
room,
iat: now,
exp: now + 86400,
context: {
user: {
email,
name: email.split('@')[0],
},
},
};
const signingInput = `${b64u(JSON.stringify(header))}.${b64u(JSON.stringify(payload))}`;
const signature = createHmac('sha256', appSecret).update(signingInput).digest();
const token = `${signingInput}.${base64url(signature)}`;
logger.info('Jitsi token issued', { room, email });
return NextResponse.json({
token,
room,
url: `${JITSI_URL}/${encodeURIComponent(room)}`,
});
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
logger.error('Jitsi token issuance failed', { error: message });
return NextResponse.json({ error: message }, { status: 500 });
}
}