Team Ai
Apppublic

Underground-Digital/Workflow-Engine

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
middleware.ts77 linesDownload Raw Back to web
1import type { NextRequest } from 'next/server'2import { NextResponse } from 'next/server'3 4const NECESSARY_DOMAIN = '*.sentry.io http://localhost:* http://127.0.0.1:* https://analytics.google.com googletagmanager.com *.googletagmanager.com https://www.google-analytics.com https://api.github.com'5 6export function middleware(request: NextRequest) {7  const isWhiteListEnabled = !!process.env.NEXT_PUBLIC_CSP_WHITELIST && process.env.NODE_ENV === 'production'8  if (!isWhiteListEnabled)9    return NextResponse.next()10 11  const whiteList = `${process.env.NEXT_PUBLIC_CSP_WHITELIST} ${NECESSARY_DOMAIN}`12  const nonce = Buffer.from(crypto.randomUUID()).toString('base64')13  const csp = `'nonce-${nonce}'`14 15  const scheme_source = 'data: mediastream: blob: filesystem:'16 17  const cspHeader = `18    default-src 'self' ${scheme_source} ${csp} ${whiteList};19    connect-src 'self' ${scheme_source} ${csp} ${whiteList};20    script-src 'self' ${scheme_source} ${csp} ${whiteList};21    style-src 'self' 'unsafe-inline' ${scheme_source} ${whiteList};22    worker-src 'self' ${scheme_source} ${csp} ${whiteList};23    media-src 'self' ${scheme_source} ${csp} ${whiteList};24    img-src 'self' ${scheme_source} ${csp} ${whiteList};25    font-src 'self';26    object-src 'none';27    base-uri 'self';28    form-action 'self';29    upgrade-insecure-requests;30`31  // Replace newline characters and spaces32  const contentSecurityPolicyHeaderValue = cspHeader33    .replace(/\s{2,}/g, ' ')34    .trim()35 36  const requestHeaders = new Headers(request.headers)37  requestHeaders.set('x-nonce', nonce)38 39  requestHeaders.set(40    'Content-Security-Policy',41    contentSecurityPolicyHeaderValue,42  )43 44  const response = NextResponse.next({45    request: {46      headers: requestHeaders,47    },48  })49  response.headers.set(50    'Content-Security-Policy',51    contentSecurityPolicyHeaderValue,52  )53 54  return response55}56 57export const config = {58  matcher: [59    /*60     * Match all request paths except for the ones starting with:61     * - api (API routes)62     * - _next/static (static files)63     * - _next/image (image optimization files)64     * - favicon.ico (favicon file)65     */66    {67      // source: '/((?!api|_next/static|_next/image|favicon.ico).*)',68      source: '/((?!_next/static|_next/image|favicon.ico).*)',69      // source: '/(.*)',70      // missing: [71      //   { type: 'header', key: 'next-router-prefetch' },72      //   { type: 'header', key: 'purpose', value: 'prefetch' },73      // ],74    },75  ],76}77