Skip to content

Commit

Permalink
fix(dcellar-web-ui): fix middleware not working
Browse files Browse the repository at this point in the history
  • Loading branch information
devinxl committed Nov 4, 2024
1 parent f31a743 commit 00c5616
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 17 deletions.
3 changes: 2 additions & 1 deletion apps/dcellar-web-ui/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ const nextConfig = {
reactStrictMode: false,
distDir: '.next',
webpack,
assetPrefix: process.env.NODE_ENV === 'production' ? '/static/dcellar-web-ui' : '',
// assetPrefix: process.env.NODE_ENV === 'production' ? '/static/dcellar-web-ui' : '',
assetPrefix: '',
pageExtensions: ['mdx', 'jsx', 'js', 'ts', 'tsx'],
generateBuildId: async () => {
return commitHash;
Expand Down
2 changes: 1 addition & 1 deletion apps/dcellar-web-ui/src/base/env.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { removeTrailingSlash } from '@/utils/string';
import getConfig from 'next/config';

const { publicRuntimeConfig, serverRuntimeConfig } = getConfig();
const { publicRuntimeConfig, serverRuntimeConfig } = getConfig() || {};
const {
NEXT_PUBLIC_ENV,
NEXT_PUBLIC_STATIC_HOST,
Expand Down
11 changes: 8 additions & 3 deletions apps/dcellar-web-ui/src/components/common/Ga4/index.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import Script from 'next/script';

interface IGtag {
id: string;
disabled?: boolean;
nonce?: string;
}

export const Ga4 = ({ id, disabled }: IGtag) => {
export const Ga4 = ({ id, disabled, nonce }: IGtag) => {
if (disabled) return null;

return (
<>
<script
<Script
id="ga4"
nonce={nonce}
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
Expand All @@ -19,7 +24,7 @@ export const Ga4 = ({ id, disabled }: IGtag) => {
`,
}}
/>
<script src={`https://www.googletagmanager.com/gtag/js?id=${id}`} async />
<Script src={`https://www.googletagmanager.com/gtag/js?id=${id}`} async nonce={nonce} />
</>
);
};
58 changes: 58 additions & 0 deletions apps/dcellar-web-ui/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from 'next/server';

const isDevelopment = process.env.NODE_ENV === 'development';
export function middleware(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' ${isDevelopment ? "'unsafe-eval'" : ''};
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
img-src 'self' blob: data: https: https://www.google-analytics.com https://www.googletagmanager.com;
font-src 'self' https://fonts.gstatic.com;
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
media-src 'self';
manifest-src 'self';
worker-src 'self' blob:;
upgrade-insecure-requests;
connect-src *;
frame-src 'self' https://verify.walletconnect.org https://verify.walletconnect.com;
`;

// Replace newline characters and spaces
const contentSecurityPolicyHeaderValue = cspHeader.replace(/\s{2,}/g, ' ').trim();

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 const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
{
source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
};
51 changes: 40 additions & 11 deletions apps/dcellar-web-ui/src/pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,61 @@ import { Ga4 } from '@/components/common/Ga4';
import { EthereumScript } from '@node-real/walletkit';
import { Head, Html, Main, NextScript } from 'next/document';
import * as flatted from 'flatted';
import Script from 'next/script';

export default function Document() {
export default function Document(props: any) {
const getNonce = (props: any): string | undefined => {
return props?.__NEXT_DATA__?.nonce || undefined;
};
return (
<Html lang="en" style={{ colorScheme: 'light' }} data-theme="light">
<Head>
<meta
name="google-site-verification"
content="9P1xIkjIzkjS3UiiTBjcjN5tfyh4Yk6FDKELgtTdMGE"
/>
<link rel="icon" href={`${assetPrefix}/favicon.ico`} />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
<link rel="icon" href={`${assetPrefix}/favicon.ico`} nonce={getNonce(props)} />
<link rel="preconnect" href="https://fonts.googleapis.com" nonce={getNonce(props)} />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin="anonymous"
nonce={getNonce(props)}
/>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Poppins:wght@400;500;600&display=swap"
rel="stylesheet"
nonce={getNonce(props)}
/>
<link href={`${assetPrefix}/wasm/main.wasm`} rel="prefetch" type="application/wasm" />
<Ga4 id={GA_ID} />
<script
<link
href={`${assetPrefix}/wasm/main.wasm`}
rel="prefetch"
type="application/wasm"
nonce={getNonce(props)}
/>
<Ga4 id={GA_ID} nonce={getNonce(props)} />
<Script
id="asset-prefix"
nonce={getNonce(props)}
dangerouslySetInnerHTML={{
__html: `window.__ASSET_PREFIX = ${flatted.stringify(assetPrefix)}`,
}}
></script>
<script defer src={`${assetPrefix}/js/iconfont_v0.1.12.min.js`}></script>
<script defer src={`${assetPrefix}/wasm/tinygo_wasm_exec_v1.js`}></script>
<script defer src={`${assetPrefix}/wasm/tinygo_init_v1.js`}></script>
/>
<Script
nonce={getNonce(props)}
defer
src={`${assetPrefix}/js/iconfont_v0.1.12.min.js`}
></Script>
<Script
nonce={getNonce(props)}
defer
src={`${assetPrefix}/wasm/tinygo_wasm_exec_v1.js`}
></Script>
<Script
nonce={getNonce(props)}
defer
src={`${assetPrefix}/wasm/tinygo_init_v1.js`}
></Script>
<EthereumScript />
</Head>
<body>
Expand Down
2 changes: 1 addition & 1 deletion apps/dcellar-web-ui/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@
"@/public/*": ["public/*"]
}
},
"include": ["next-env.d.ts", "typings.d.ts", "**/*.ts", "**/*.tsx"],
"include": ["next-env.d.ts", "typings.d.ts", "**/*.ts", "**/*.tsx", "src/middleware.ts"],
"exclude": ["node_modules", ".next"]
}

0 comments on commit 00c5616

Please sign in to comment.