feat: refactor authentication handling to use centralized Stalwart credentials management

This commit is contained in:
Linus Rath
2026-03-14 15:55:59 +01:00
parent 6fc27804d6
commit 85b5b3c4f1
7 changed files with 94 additions and 136 deletions
+5
View File
@@ -20,6 +20,11 @@ JMAP_SERVER_URL=https://your-jmap-server.com
# Set to "false" to disable if using a non-Stalwart JMAP server.
# STALWART_FEATURES=true
# If your reverse proxy doesn't forward Stalwart management API paths
# (/api/account/*, /api/principal/*), set this to the URL where Stalwart's
# HTTP listener is directly reachable. Defaults to JMAP_SERVER_URL if not set.
# STALWART_API_URL=https://admin.example.com
# =============================================================================
# OAuth / OpenID Connect (optional)
# =============================================================================
+5 -33
View File
@@ -1,34 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
/**
* Extract the user's JMAP server URL and auth header from the session cookie
* or from the Authorization header passed by the client.
*/
async function getCredentials(request: NextRequest): Promise<{ serverUrl: string; authHeader: string; username: string } | null> {
// Try Authorization header first (for bearer/basic auth forwarding)
const authHeader = request.headers.get('Authorization');
const serverUrl = request.headers.get('X-JMAP-Server-URL');
const username = request.headers.get('X-JMAP-Username');
if (authHeader && serverUrl && username) {
return { serverUrl, authHeader, username };
}
// Fall back to session cookie
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) return null;
const credentials = decryptSession(token);
if (!credentials) return null;
const basic = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
return { serverUrl: credentials.serverUrl, authHeader: basic, username: credentials.username };
}
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
/**
* GET /api/account/stalwart/auth
@@ -36,12 +8,12 @@ async function getCredentials(request: NextRequest): Promise<{ serverUrl: string
*/
export async function GET(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const response = await fetch(`${creds.serverUrl}/api/account/auth`, {
const response = await fetch(`${creds.apiUrl}/api/account/auth`, {
method: 'GET',
headers: { 'Authorization': creds.authHeader },
});
@@ -69,14 +41,14 @@ export async function GET(request: NextRequest) {
*/
export async function POST(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const body = await request.json();
const response = await fetch(`${creds.serverUrl}/api/account/auth`, {
const response = await fetch(`${creds.apiUrl}/api/account/auth`, {
method: 'POST',
headers: {
'Authorization': creds.authHeader,
+5 -27
View File
@@ -1,28 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
async function getCredentials(request: NextRequest): Promise<{ serverUrl: string; authHeader: string; username: string } | null> {
const authHeader = request.headers.get('Authorization');
const serverUrl = request.headers.get('X-JMAP-Server-URL');
const username = request.headers.get('X-JMAP-Username');
if (authHeader && serverUrl && username) {
return { serverUrl, authHeader, username };
}
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) return null;
const credentials = decryptSession(token);
if (!credentials) return null;
const basic = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
return { serverUrl: credentials.serverUrl, authHeader: basic, username: credentials.username };
}
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
/**
* GET /api/account/stalwart/crypto
@@ -30,12 +8,12 @@ async function getCredentials(request: NextRequest): Promise<{ serverUrl: string
*/
export async function GET(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const response = await fetch(`${creds.serverUrl}/api/account/crypto`, {
const response = await fetch(`${creds.apiUrl}/api/account/crypto`, {
method: 'GET',
headers: { 'Authorization': creds.authHeader },
});
@@ -63,14 +41,14 @@ export async function GET(request: NextRequest) {
*/
export async function POST(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const body = await request.json();
const response = await fetch(`${creds.serverUrl}/api/account/crypto`, {
const response = await fetch(`${creds.apiUrl}/api/account/crypto`, {
method: 'POST',
headers: {
'Authorization': creds.authHeader,
+4 -25
View File
@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession, encryptSession } from '@/lib/auth/crypto';
import { encryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE, SESSION_COOKIE_MAX_AGE } from '@/lib/auth/session-cookie';
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
const COOKIE_OPTIONS = {
httpOnly: true,
@@ -12,28 +13,6 @@ const COOKIE_OPTIONS = {
maxAge: SESSION_COOKIE_MAX_AGE,
};
async function getCredentials(request: NextRequest): Promise<{ serverUrl: string; authHeader: string; username: string; hasSessionCookie: boolean } | null> {
const authHeader = request.headers.get('Authorization');
const serverUrl = request.headers.get('X-JMAP-Server-URL');
const username = request.headers.get('X-JMAP-Username');
if (authHeader && serverUrl && username) {
const cookieStore = await cookies();
const hasSessionCookie = !!cookieStore.get(SESSION_COOKIE)?.value;
return { serverUrl, authHeader, username, hasSessionCookie };
}
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) return null;
const credentials = decryptSession(token);
if (!credentials) return null;
const basic = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
return { serverUrl: credentials.serverUrl, authHeader: basic, username: credentials.username, hasSessionCookie: true };
}
/**
* POST /api/account/stalwart/password
* Change user password via Stalwart PATCH /api/principal/{name}
@@ -42,7 +21,7 @@ async function getCredentials(request: NextRequest): Promise<{ serverUrl: string
*/
export async function POST(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
@@ -69,7 +48,7 @@ export async function POST(request: NextRequest) {
}
// Change password via Stalwart principal API
const response = await fetch(`${creds.serverUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
const response = await fetch(`${creds.apiUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
method: 'PATCH',
headers: {
'Authorization': creds.authHeader,
+5 -27
View File
@@ -1,28 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
async function getCredentials(request: NextRequest): Promise<{ serverUrl: string; authHeader: string; username: string } | null> {
const authHeader = request.headers.get('Authorization');
const serverUrl = request.headers.get('X-JMAP-Server-URL');
const username = request.headers.get('X-JMAP-Username');
if (authHeader && serverUrl && username) {
return { serverUrl, authHeader, username };
}
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) return null;
const credentials = decryptSession(token);
if (!credentials) return null;
const basic = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
return { serverUrl: credentials.serverUrl, authHeader: basic, username: credentials.username };
}
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
/**
* GET /api/account/stalwart/principal
@@ -30,12 +8,12 @@ async function getCredentials(request: NextRequest): Promise<{ serverUrl: string
*/
export async function GET(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const response = await fetch(`${creds.serverUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
const response = await fetch(`${creds.apiUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
method: 'GET',
headers: { 'Authorization': creds.authHeader },
});
@@ -64,7 +42,7 @@ export async function GET(request: NextRequest) {
*/
export async function PATCH(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
@@ -79,7 +57,7 @@ export async function PATCH(request: NextRequest) {
}
}
const response = await fetch(`${creds.serverUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
const response = await fetch(`${creds.apiUrl}/api/principal/${encodeURIComponent(creds.username)}`, {
method: 'PATCH',
headers: {
'Authorization': creds.authHeader,
+3 -24
View File
@@ -1,27 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { logger } from '@/lib/logger';
import { decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
async function getCredentials(request: NextRequest): Promise<{ serverUrl: string; authHeader: string } | null> {
const authHeader = request.headers.get('Authorization');
const serverUrl = request.headers.get('X-JMAP-Server-URL');
if (authHeader && serverUrl) {
return { serverUrl, authHeader };
}
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) return null;
const credentials = decryptSession(token);
if (!credentials) return null;
const basic = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
return { serverUrl: credentials.serverUrl, authHeader: basic };
}
import { getStalwartCredentials } from '@/lib/stalwart/credentials';
/**
* GET /api/account/stalwart/probe
@@ -29,7 +8,7 @@ async function getCredentials(request: NextRequest): Promise<{ serverUrl: string
*/
export async function GET(request: NextRequest) {
try {
const creds = await getCredentials(request);
const creds = await getStalwartCredentials(request);
if (!creds) {
return NextResponse.json({ isStalwart: false });
}
@@ -38,7 +17,7 @@ export async function GET(request: NextRequest) {
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(`${creds.serverUrl}/api/account/auth`, {
const response = await fetch(`${creds.apiUrl}/api/account/auth`, {
method: 'GET',
headers: { 'Authorization': creds.authHeader },
signal: controller.signal,
+67
View File
@@ -0,0 +1,67 @@
import { cookies } from 'next/headers';
import { NextRequest } from 'next/server';
import { decryptSession } from '@/lib/auth/crypto';
import { SESSION_COOKIE } from '@/lib/auth/session-cookie';
export interface StalwartCredentials {
/** URL for Stalwart management API calls (uses STALWART_API_URL if set, otherwise serverUrl) */
apiUrl: string;
/** URL of the JMAP server (for JMAP operations like password verification) */
serverUrl: string;
authHeader: string;
username: string;
hasSessionCookie: boolean;
}
/**
* Resolve the base URL for Stalwart management API requests.
*
* When the JMAP server sits behind a reverse proxy that only forwards
* JMAP paths, the `/api/account/*` and `/api/principal/*` management
* endpoints may not be exposed. In that case, operators can set
* `STALWART_API_URL` to point directly at the Stalwart HTTP listener
* (e.g. `https://admin.example.com`).
*/
function getStalwartApiUrl(jmapServerUrl: string): string {
return process.env.STALWART_API_URL || jmapServerUrl;
}
/**
* Extract credentials from the incoming request.
*
* Tries the explicit headers first (`Authorization`, `X-JMAP-Server-URL`,
* `X-JMAP-Username`), then falls back to the encrypted session cookie.
*/
export async function getStalwartCredentials(request: NextRequest): Promise<StalwartCredentials | null> {
const authHeader = request.headers.get('Authorization');
const serverUrl = request.headers.get('X-JMAP-Server-URL');
const username = request.headers.get('X-JMAP-Username');
if (authHeader && serverUrl && username) {
const cookieStore = await cookies();
const hasSessionCookie = !!cookieStore.get(SESSION_COOKIE)?.value;
return {
apiUrl: getStalwartApiUrl(serverUrl),
serverUrl,
authHeader,
username,
hasSessionCookie,
};
}
const cookieStore = await cookies();
const token = cookieStore.get(SESSION_COOKIE)?.value;
if (!token) return null;
const credentials = decryptSession(token);
if (!credentials) return null;
const basic = `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
return {
apiUrl: getStalwartApiUrl(credentials.serverUrl),
serverUrl: credentials.serverUrl,
authHeader: basic,
username: credentials.username,
hasSessionCookie: true,
};
}