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

fix(nextjs): Attempt to inline crypto-js through pre-compiling #5024

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
5 changes: 5 additions & 0 deletions .changeset/rich-trees-smoke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/nextjs': patch
---

Vendor `crypto-js` dependency to avoid bundling issues.
brkalow marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@
"@clerk/clerk-react": "workspace:^",
"@clerk/shared": "workspace:^",
"@clerk/types": "workspace:^",
"crypto-js": "4.2.0",
"server-only": "0.0.1",
"tslib": "catalog:repo"
},
"devDependencies": {
"@types/crypto-js": "4.2.2",
"crypto-js": "4.2.0",
"next": "^14.2.23"
},
"peerDependencies": {
Expand Down
6 changes: 2 additions & 4 deletions packages/nextjs/src/server/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ import { isDevelopmentFromSecretKey } from '@clerk/shared/keys';
import { logger } from '@clerk/shared/logger';
import { isHttpOrHttps } from '@clerk/shared/proxy';
import { handleValueOrFn, isProductionEnvironment } from '@clerk/shared/utils';
import AES from 'crypto-js/aes';
import encUtf8 from 'crypto-js/enc-utf8';
import hmacSHA1 from 'crypto-js/hmac-sha1';
import { NextResponse } from 'next/server';

import { constants as nextConstants } from '../constants';
import { canUseKeyless } from '../utils/feature-flags';
import { AES, encUtf8, hmacSHA1 } from '../vendor/crypto-js';
import { DOMAIN, ENCRYPTION_KEY, IS_SATELLITE, PROXY_URL, SECRET_KEY, SIGN_IN_URL } from './constants';
import {
authSignatureInvalid,
Expand All @@ -34,7 +32,7 @@ export const setRequestHeadersOnNextResponse = (
if (!res.headers.get(OVERRIDE_HEADERS)) {
// Emulate a user setting overrides by explicitly adding the required nextjs headers
// https://github.com/vercel/next.js/pull/41380
// @ts-expect-error
// @ts-expect-error -- property keys does not exist on type Headers
res.headers.set(OVERRIDE_HEADERS, [...req.headers.keys()]);
req.headers.forEach((val, key) => {
res.headers.set(`${MIDDLEWARE_HEADER_PREFIX}-${key}`, val);
Expand Down
7 changes: 7 additions & 0 deletions packages/nextjs/src/vendor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Vendored dependencies

The modules in this folder contain vendored dependencies that are built and inlined into the published package.

## crypto-js
brkalow marked this conversation as resolved.
Show resolved Hide resolved

Used as a synchronous replacement for the [Web Crypto APIs](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API). Currently, we use crypto-js to encrypt and decrypt data transferred between Next.js middleware and the application server.
brkalow marked this conversation as resolved.
Show resolved Hide resolved
brkalow marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 5 additions & 0 deletions packages/nextjs/src/vendor/crypto-js.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import AES from 'crypto-js/aes';
import encUtf8 from 'crypto-js/enc-utf8';
import hmacSHA1 from 'crypto-js/hmac-sha1';

export { AES, encUtf8, hmacSHA1 };
32 changes: 31 additions & 1 deletion packages/nextjs/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ export default defineConfig(overrideOptions => {
'!./src/**/*.test.{ts,tsx}',
'!./src/**/server-actions.ts',
'!./src/**/keyless-actions.ts',
'!./src/vendor/**',
],
// We want to preserve original file structure
// so that the "use client" directives are not lost
// and make debugging easier via node_modules easier
bundle: false,
clean: true,
minify: false,
noExternal: ['crypto-js'],
brkalow marked this conversation as resolved.
Show resolved Hide resolved
external: ['#safe-node-apis'],
sourcemap: true,
legacyOutput: true,
Expand All @@ -43,6 +45,9 @@ export default defineConfig(overrideOptions => {
outDir: './dist/cjs',
};

/**
* When server actions are built with sourcemaps, Next.js does not resolve the sourcemap URLs during build and so browser dev tools attempt to load source maps for these files from incorrect locations
*/
const serverActionsEsm: Options = {
...esm,
entry: ['./src/**/server-actions.ts', './src/**/keyless-actions.ts'],
Expand All @@ -55,6 +60,31 @@ export default defineConfig(overrideOptions => {
sourcemap: false,
};

/**
* We vendor certain dependencies to control the output and minimize transitive dependency surface area.
*/
const vendorsEsm: Options = {
...esm,
bundle: true,
minify: true,
entry: ['./src/vendor/**'],
jacekradko marked this conversation as resolved.
Show resolved Hide resolved
outDir: './dist/esm/vendor',
legacyOutput: false,
outExtension: () => ({
js: '.js',
}),
sourcemap: false,
};

const vendorsCjs: Options = {
...cjs,
bundle: true,
minify: true,
entry: ['./src/vendor/**'],
jacekradko marked this conversation as resolved.
Show resolved Hide resolved
outDir: './dist/cjs/vendor',
sourcemap: false,
};

const copyPackageJson = (format: 'esm' | 'cjs') => `cp ./package.${format}.json ./dist/${format}/package.json`;
// Tsup will not output the generated file in the same location as the source file
// So we need to move the server-actions.js file to the app-router folder manually
Expand All @@ -73,5 +103,5 @@ export default defineConfig(overrideOptions => {
moveKeylessActions('esm'),
moveKeylessActions('cjs'),
shouldPublish && 'pnpm publish:local',
])(esm, cjs, serverActionsEsm, serverActionsCjs);
])(esm, cjs, serverActionsEsm, serverActionsCjs, vendorsEsm, vendorsCjs);
});
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading