Clean up middleware, add security-headers to non-Zammad pages
This commit is contained in:
parent
027aac3a92
commit
8c6e954fdf
9 changed files with 81 additions and 62 deletions
|
|
@ -202,7 +202,7 @@ export const Sidebar: FC<SidebarProps> = ({
|
||||||
|
|
||||||
fetchCounts();
|
fetchCounts();
|
||||||
|
|
||||||
const interval = setInterval(fetchCounts, 10000);
|
const interval = setInterval(fetchCounts, 30000);
|
||||||
|
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ export const TicketDetail: FC<TicketDetailProps> = ({ id }) => {
|
||||||
|
|
||||||
fetchTicketArticles();
|
fetchTicketArticles();
|
||||||
|
|
||||||
const interval = setInterval(fetchTicketArticles, 2000);
|
const interval = setInterval(fetchTicketArticles, 5000);
|
||||||
|
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, [id]);
|
}, [id]);
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import { AdapterDateFns } from "@mui/x-date-pickers-pro/AdapterDateFnsV3";
|
||||||
import { LocalizationProvider } from "@mui/x-date-pickers-pro";
|
import { LocalizationProvider } from "@mui/x-date-pickers-pro";
|
||||||
import { LicenseInfo } from "@mui/x-license";
|
import { LicenseInfo } from "@mui/x-license";
|
||||||
import { locales, LeafcutterProvider } from "@link-stack/leafcutter-ui";
|
import { locales, LeafcutterProvider } from "@link-stack/leafcutter-ui";
|
||||||
import { CSRFProvider } from "./CSRFProvider";
|
import { ZammadLoginProvider } from "./ZammadLoginProvider";
|
||||||
|
|
||||||
LicenseInfo.setLicenseKey(
|
LicenseInfo.setLicenseKey(
|
||||||
"c787ac6613c5f2aa0494c4285fe3e9f2Tz04OTY1NyxFPTE3NDYzNDE0ODkwMDAsUz1wcm8sTE09c3Vic2NyaXB0aW9uLEtWPTI=",
|
"c787ac6613c5f2aa0494c4285fe3e9f2Tz04OTY1NyxFPTE3NDYzNDE0ODkwMDAsUz1wcm8sTE09c3Vic2NyaXB0aW9uLEtWPTI=",
|
||||||
|
|
@ -22,7 +22,7 @@ export const MultiProvider: FC<PropsWithChildren> = ({ children }) => {
|
||||||
return (
|
return (
|
||||||
<SessionProvider>
|
<SessionProvider>
|
||||||
<CssBaseline />
|
<CssBaseline />
|
||||||
<CSRFProvider>
|
<ZammadLoginProvider>
|
||||||
<CookiesProvider>
|
<CookiesProvider>
|
||||||
<LocalizationProvider dateAdapter={AdapterDateFns}>
|
<LocalizationProvider dateAdapter={AdapterDateFns}>
|
||||||
<I18n locale={locale} messages={messages[locale]}>
|
<I18n locale={locale} messages={messages[locale]}>
|
||||||
|
|
@ -30,7 +30,7 @@ export const MultiProvider: FC<PropsWithChildren> = ({ children }) => {
|
||||||
</I18n>
|
</I18n>
|
||||||
</LocalizationProvider>
|
</LocalizationProvider>
|
||||||
</CookiesProvider>
|
</CookiesProvider>
|
||||||
</CSRFProvider>
|
</ZammadLoginProvider>
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -4,25 +4,19 @@ import { FC, PropsWithChildren, useEffect } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useSession } from "next-auth/react";
|
import { useSession } from "next-auth/react";
|
||||||
|
|
||||||
export const CSRFProvider: FC<PropsWithChildren> = ({ children }) => {
|
export const ZammadLoginProvider: FC<PropsWithChildren> = ({ children }) => {
|
||||||
const { data: session, status, update } = useSession();
|
const { data: session, status, update } = useSession();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const checkSession = async () => {
|
const checkSession = async () => {
|
||||||
console.log("Checking session status...");
|
|
||||||
console.log(status);
|
|
||||||
if (status === "authenticated") {
|
if (status === "authenticated") {
|
||||||
const response = await fetch("/api/v1/users/me", {
|
const response = await fetch("/api/v1/users/me", {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.status !== 200 && !!router) {
|
if (response.status !== 200) {
|
||||||
console.log("redirecting");
|
|
||||||
window.location.href = "/auth/sso";
|
window.location.href = "/auth/sso";
|
||||||
} else {
|
|
||||||
const token = response.headers.get("CSRF-Token");
|
|
||||||
update({ zammadCsrfToken: token });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
@ -101,30 +101,19 @@ export const authOptions: NextAuthOptions = {
|
||||||
callbacks: {
|
callbacks: {
|
||||||
signIn: async ({ user }) => {
|
signIn: async ({ user }) => {
|
||||||
const roles = (await getUserRoles(user.email)) ?? [];
|
const roles = (await getUserRoles(user.email)) ?? [];
|
||||||
return (
|
return roles.includes("admin") || roles.includes("agent");
|
||||||
roles.includes("admin") ||
|
|
||||||
roles.includes("agent") ||
|
|
||||||
process.env.SETUP_MODE === "true"
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
session: async ({ session, token }) => {
|
session: async ({ session, token }) => {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
session.user.roles = token.roles ?? [];
|
session.user.roles = token.roles ?? [];
|
||||||
// @ts-ignore
|
|
||||||
session.user.leafcutter = token.leafcutter; // remove
|
|
||||||
// @ts-ignore
|
|
||||||
session.user.zammadCsrfToken = token.zammadCsrfToken;
|
|
||||||
|
|
||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
jwt: async ({ token, user, trigger, session }) => {
|
jwt: async ({ token, user }) => {
|
||||||
if (user) {
|
if (user) {
|
||||||
token.roles = (await getUserRoles(user.email)) ?? [];
|
token.roles = (await getUserRoles(user.email)) ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session && trigger === "update") {
|
|
||||||
token.zammadCsrfToken = session.zammadCsrfToken;
|
|
||||||
}
|
|
||||||
return token;
|
return token;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import { getServerSession } from "app/_lib/authentication";
|
import { getServerSession } from "app/_lib/authentication";
|
||||||
import { redirect } from "next/navigation";
|
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
const getHeaders = async () => {
|
const getHeaders = async () => {
|
||||||
|
|
@ -8,8 +7,6 @@ const getHeaders = async () => {
|
||||||
const headers = {
|
const headers = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Accept: "application/json",
|
Accept: "application/json",
|
||||||
// @ts-ignore
|
|
||||||
"X-CSRF-Token": session.user.zammadCsrfToken,
|
|
||||||
"X-Browser-Fingerprint": `${session.expires}`,
|
"X-Browser-Fingerprint": `${session.expires}`,
|
||||||
Cookie: allCookies
|
Cookie: allCookies
|
||||||
.map((cookie: any) => `${cookie.name}=${cookie.value}`)
|
.map((cookie: any) => `${cookie.name}=${cookie.value}`)
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,8 @@ import { AppRouterCacheProvider } from "@mui/material-nextjs/v14-appRouter";
|
||||||
import { MultiProvider } from "./_components/MultiProvider";
|
import { MultiProvider } from "./_components/MultiProvider";
|
||||||
import "./_styles/global.css";
|
import "./_styles/global.css";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "CDR Link",
|
title: "CDR Link",
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -10,11 +10,12 @@ const rewriteURL = (
|
||||||
const destinationURL = request.url.replace(originBaseURL, destinationBaseURL);
|
const destinationURL = request.url.replace(originBaseURL, destinationBaseURL);
|
||||||
console.log(`Rewriting ${request.url} to ${destinationURL}`);
|
console.log(`Rewriting ${request.url} to ${destinationURL}`);
|
||||||
const requestHeaders = new Headers(request.headers);
|
const requestHeaders = new Headers(request.headers);
|
||||||
|
requestHeaders.delete("x-forwarded-user");
|
||||||
|
requestHeaders.delete("connection");
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(headers)) {
|
for (const [key, value] of Object.entries(headers)) {
|
||||||
requestHeaders.set(key, value as string);
|
requestHeaders.set(key, value as string);
|
||||||
}
|
}
|
||||||
requestHeaders.delete("connection");
|
|
||||||
|
|
||||||
return NextResponse.rewrite(new URL(destinationURL), {
|
return NextResponse.rewrite(new URL(destinationURL), {
|
||||||
request: { headers: requestHeaders },
|
request: { headers: requestHeaders },
|
||||||
|
|
@ -24,11 +25,9 @@ const rewriteURL = (
|
||||||
const checkRewrites = async (request: NextRequestWithAuth) => {
|
const checkRewrites = async (request: NextRequestWithAuth) => {
|
||||||
const linkBaseURL = process.env.LINK_URL ?? "http://localhost:3000";
|
const linkBaseURL = process.env.LINK_URL ?? "http://localhost:3000";
|
||||||
const zammadURL = process.env.ZAMMAD_URL ?? "http://zammad-nginx:8080";
|
const zammadURL = process.env.ZAMMAD_URL ?? "http://zammad-nginx:8080";
|
||||||
const opensearchDashboardsURL =
|
|
||||||
process.env.OPENSEARCH_DASHBOARDS_URL ?? "http://macmini:5601";
|
|
||||||
const zammadPaths = [
|
const zammadPaths = [
|
||||||
"/zammad",
|
"/zammad",
|
||||||
"/api/v1",
|
|
||||||
"/auth/sso",
|
"/auth/sso",
|
||||||
"/assets",
|
"/assets",
|
||||||
"/mobile",
|
"/mobile",
|
||||||
|
|
@ -39,28 +38,50 @@ const checkRewrites = async (request: NextRequestWithAuth) => {
|
||||||
const email = token?.email?.toLowerCase() ?? "unknown";
|
const email = token?.email?.toLowerCase() ?? "unknown";
|
||||||
let headers = { "x-forwarded-user": email };
|
let headers = { "x-forwarded-user": email };
|
||||||
|
|
||||||
if (request.nextUrl.pathname.startsWith("/dashboards")) {
|
if (request.nextUrl.pathname.startsWith("/zammad")) {
|
||||||
const roles: string[] = (token?.roles as string[]) ?? [];
|
|
||||||
const leafcutterRole = roles.includes("admin")
|
|
||||||
? "leafcutter_admin"
|
|
||||||
: "leafcutter_user";
|
|
||||||
headers["x-forwarded-roles"] = leafcutterRole;
|
|
||||||
// headers["secruitytenant"] = "global";
|
|
||||||
// headers["x-forwarded-for"] = 'link';
|
|
||||||
|
|
||||||
return rewriteURL(
|
|
||||||
request,
|
|
||||||
`${linkBaseURL}/dashboards`,
|
|
||||||
opensearchDashboardsURL,
|
|
||||||
headers,
|
|
||||||
);
|
|
||||||
} else if (request.nextUrl.pathname.startsWith("/zammad")) {
|
|
||||||
return rewriteURL(request, `${linkBaseURL}/zammad`, zammadURL, headers);
|
return rewriteURL(request, `${linkBaseURL}/zammad`, zammadURL, headers);
|
||||||
} else if (zammadPaths.some((p) => request.nextUrl.pathname.startsWith(p))) {
|
} else if (zammadPaths.some((p) => request.nextUrl.pathname.startsWith(p))) {
|
||||||
return rewriteURL(request, linkBaseURL, zammadURL, headers);
|
return rewriteURL(request, linkBaseURL, zammadURL, headers);
|
||||||
}
|
} else {
|
||||||
|
const isDev = process.env.NODE_ENV === "development";
|
||||||
|
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
|
||||||
|
const cspHeader = `
|
||||||
|
default-src 'self';
|
||||||
|
connect-src 'self';
|
||||||
|
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' ${isDev ? "'unsafe-eval'" : ""};
|
||||||
|
style-src 'self' 'unsafe-inline';
|
||||||
|
img-src 'self' blob: data:;
|
||||||
|
font-src 'self';
|
||||||
|
object-src 'none';
|
||||||
|
base-uri 'self';
|
||||||
|
form-action 'self';
|
||||||
|
frame-ancestors 'none';
|
||||||
|
upgrade-insecure-requests;
|
||||||
|
`;
|
||||||
|
const contentSecurityPolicyHeaderValue = cspHeader
|
||||||
|
.replace(/\s{2,}/g, " ")
|
||||||
|
.trim();
|
||||||
|
|
||||||
return NextResponse.next();
|
const requestHeaders = new Headers(request.headers);
|
||||||
|
requestHeaders.set("x-nonce", nonce);
|
||||||
|
requestHeaders.set(
|
||||||
|
"Content-Security-Policy",
|
||||||
|
contentSecurityPolicyHeaderValue,
|
||||||
|
);
|
||||||
|
|
||||||
|
const response = NextResponse.next({
|
||||||
|
request: {
|
||||||
|
headers: requestHeaders,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
response.headers.set(
|
||||||
|
"Content-Security-Policy",
|
||||||
|
contentSecurityPolicyHeaderValue,
|
||||||
|
);
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export default withAuth(checkRewrites, {
|
export default withAuth(checkRewrites, {
|
||||||
|
|
@ -69,12 +90,11 @@ export default withAuth(checkRewrites, {
|
||||||
},
|
},
|
||||||
callbacks: {
|
callbacks: {
|
||||||
authorized: ({ token, req }) => {
|
authorized: ({ token, req }) => {
|
||||||
const path = req.nextUrl.pathname;
|
|
||||||
|
|
||||||
if (process.env.SETUP_MODE === "true") {
|
if (process.env.SETUP_MODE === "true") {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const path = req.nextUrl.pathname;
|
||||||
const roles: any = token?.roles ?? [];
|
const roles: any = token?.roles ?? [];
|
||||||
|
|
||||||
if (path.startsWith("/admin") && !roles.includes("admin")) {
|
if (path.startsWith("/admin") && !roles.includes("admin")) {
|
||||||
|
|
@ -91,7 +111,9 @@ export default withAuth(checkRewrites, {
|
||||||
});
|
});
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: [
|
matcher: ["/((?!ws|wss|api|_next/static|_next/image|favicon.ico).*)"],
|
||||||
"/((?!ws|wss|api/v1|api/signal|api/whatsapp|api/facebook|_next/static|_next/image|favicon.ico).*)",
|
missing: [
|
||||||
|
{ type: "header", key: "next-router-prefetch" },
|
||||||
|
{ type: "header", key: "purpose", value: "prefetch" },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -8,22 +8,37 @@ const nextConfig = {
|
||||||
"@link-stack/bridge-ui",
|
"@link-stack/bridge-ui",
|
||||||
"mui-chips-input",
|
"mui-chips-input",
|
||||||
],
|
],
|
||||||
publicRuntimeConfig: {
|
headers: async () => {
|
||||||
linkURL: process.env.LINK_URL ?? "http://localhost:3000",
|
return [
|
||||||
bridgeURL: process.env.BRIDGE_URL ?? "http://localhost:8002",
|
{
|
||||||
labelStudioURL: process.env.LABEL_STUDIO_URL ?? "http://localhost:8006",
|
source: "/((?!zammad).*)",
|
||||||
muiLicenseKey: process.env.MUI_LICENSE_KEY ?? "",
|
headers: [
|
||||||
|
{
|
||||||
|
key: "Strict-Transport-Security",
|
||||||
|
value: "max-age=63072000; includeSubDomains; preload",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Frame-Options",
|
||||||
|
value: "DENY",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Content-Type-Options",
|
||||||
|
value: "nosniff",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
},
|
},
|
||||||
rewrites: async () => {
|
rewrites: async () => {
|
||||||
return {
|
return {
|
||||||
beforeFiles: [
|
beforeFiles: [
|
||||||
{
|
{
|
||||||
source: "/api/v1/:path*",
|
source: "/api/v1/:path*",
|
||||||
destination: `http://zammad-nginx:8080/api/v1/:path*`,
|
destination: `${process.env.ZAMMAD_URL ?? "http://zammad-nginx:8080"}/api/v1/:path*`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
source: "/ws",
|
source: "/ws",
|
||||||
destination: `http://zammad-nginx:8080/ws`,
|
destination: `${process.env.ZAMMAD_URL ?? "http://zammad-nginx:8080"}/ws`,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue