Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LocalizedStringProvider: nonce parameter for Content Security Policy #6219

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 36 additions & 0 deletions examples/next-app-csp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions examples/next-app-csp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
36 changes: 36 additions & 0 deletions examples/next-app-csp/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import {
LocalizedStringProvider,
createLocalizedStringDictionary,
} from "@adobe/react-spectrum/i18n";

const dictionary = createLocalizedStringDictionary([
"@react-spectrum/datepicker",
]);

export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const nonce = headers().get("x-nonce");
console.log("nonce", nonce);
return (
<html lang="en">
<body>
<LocalizedStringProvider
locale="en"
dictionary={dictionary}
nonce={nonce ?? ""}
/>
{children}
</body>
</html>
);
}
19 changes: 19 additions & 0 deletions examples/next-app-csp/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use client";

import {Provider, defaultTheme, DatePicker} from '@adobe/react-spectrum';
import {useRouter} from 'next/navigation';

declare module '@adobe/react-spectrum' {
interface RouterConfig {
routerOptions: NonNullable<Parameters<ReturnType<typeof useRouter>['push']>[1]>
}
}

export default function Home() {
let router = useRouter();
return (
<Provider theme={defaultTheme} locale="en" router={{navigate: router.push}}>
<DatePicker label="Date" />
</Provider>
)
}
61 changes: 61 additions & 0 deletions examples/next-app-csp/middleware.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { NextResponse } from "next/server";

export function middleware(request: Request) {
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const cspHeader = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https: http: 'unsafe-inline' ${
process.env.NODE_ENV === "production" ? "" : `'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;
`;
// 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" },
],
},
],
};
20 changes: 20 additions & 0 deletions examples/next-app-csp/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const localesPlugin = require('@react-aria/optimize-locales-plugin');
const glob = require('glob');

/** @type {import('next').NextConfig} */
const nextConfig = {
webpack(config, { isServer }) {
if (!isServer) {
// Don't include any locale strings in the client JS bundle.
config.plugins.push(localesPlugin.webpack({ locales: [] }));
}
return config;
},
transpilePackages: [
'@adobe/react-spectrum',
'@react-spectrum/*',
'@spectrum-icons/*',
].flatMap(spec => glob.sync(`${spec}`, { cwd: 'node_modules/' })),
}

module.exports = nextConfig
33 changes: 33 additions & 0 deletions examples/next-app-csp/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "next-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.0.3"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"glob": "^10.3.12"
},
"workspaces": [
"../../packages/react-aria-components",
"../../packages/react-aria",
"../../packages/react-stately",
"../../packages/*/*"
],
"resolutions": {
"react": "link:../../node_modules/react",
"react-dom": "link:../../node_modules/react-dom"
}
}
3 changes: 3 additions & 0 deletions examples/next-app-csp/postcss.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": []
}
27 changes: 27 additions & 0 deletions examples/next-app-csp/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
9 changes: 6 additions & 3 deletions packages/@react-aria/i18n/src/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ type PackageLocalizedStrings = {

interface PackageLocalizationProviderProps {
locale: string,
strings: PackageLocalizedStrings
strings: PackageLocalizedStrings,
nonce?: string
}

/**
Expand All @@ -32,8 +33,10 @@ export function PackageLocalizationProvider(props: PackageLocalizationProviderPr
return null;
}

let {locale, strings} = props;
return <script dangerouslySetInnerHTML={{__html: getPackageLocalizationScript(locale, strings)}} />;
let {nonce, locale, strings} = props;
// suppressHydrationWarning is necessary because the browser
// remove the nonce parameter from the DOM before hydration
return <script nonce={typeof window === 'undefined' ? nonce : ''} suppressHydrationWarning dangerouslySetInnerHTML={{__html: getPackageLocalizationScript(locale, strings)}} />;
}

/**
Expand Down
7 changes: 4 additions & 3 deletions scripts/buildI18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ export default PackageLocalizedStrings;

index += `});

function LocalizedStringProvider({locale, dictionary: dict = dictionary}) {
function LocalizedStringProvider({locale, dictionary: dict = dictionary, nonce}) {
let strings = dict.getStringsForLocale(locale);
return createElement(PackageLocalizationProvider, {locale, strings});
return createElement(PackageLocalizationProvider, {locale, strings, nonce});
}

function getLocalizationScript(locale, dict = dictionary) {
Expand Down Expand Up @@ -126,7 +126,8 @@ import type {LocalizedStringDictionary} from '@internationalized/string';

interface LocalizedStringProviderProps {
locale: string,
dictionary?: LocalizedStringDictionary
dictionary?: LocalizedStringDictionary,
nonce?: string
}

export declare function LocalizedStringProvider(props: LocalizedStringProviderProps): React.JSX.Element;
Expand Down