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.
2 changes: 1 addition & 1 deletion integration/tests/next-build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
// Get the indicator from the build output
const indicator = getIndicator(app.buildOutput, type);

const pageLine = app.buildOutput.split('\n').find(msg => msg.includes(page));
const pageLine = app.buildOutput.split('\n').find(msg => msg.includes(` ${page}`));

expect(pageLine).toContain(indicator);
});
Expand Down
3 changes: 1 addition & 2 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,11 @@
"@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-es": "^2.1.0",
"next": "^14.2.23"
},
"peerDependencies": {
Expand Down
10 changes: 4 additions & 6 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, HmacSHA1, Utf8 } 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 Expand Up @@ -160,7 +158,7 @@ export function assertKey(key: string | undefined, onError: () => never): string
* Compute a cryptographic signature from a session token and provided secret key. Used to validate that the token has not been modified when transferring between middleware and the Next.js origin.
*/
function createTokenSignature(token: string, key: string): string {
return hmacSHA1(token, key).toString();
return HmacSHA1(token, key).toString();
}

/**
Expand Down Expand Up @@ -258,6 +256,6 @@ function throwInvalidEncryptionKey(): never {

function decryptData(data: string, key: string) {
const decryptedBytes = AES.decrypt(data, key);
const encoded = decryptedBytes.toString(encUtf8);
const encoded = decryptedBytes.toString(Utf8);
return JSON.parse(encoded);
}
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

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.
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-es/lib/aes';
Copy link
Member

@jacekradko jacekradko Jan 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we rename this file to crypto-es.js ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, good call

import { Utf8 } from 'crypto-es/lib/core';
import { HmacSHA1 } from 'crypto-es/lib/sha1';

export { AES, HmacSHA1, Utf8 };
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'],
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/*.js'],
outDir: './dist/esm/vendor',
legacyOutput: false,
outExtension: () => ({
js: '.js',
}),
sourcemap: false,
};

const vendorsCjs: Options = {
...cjs,
bundle: true,
minify: true,
entry: ['./src/vendor/*.js'],
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);
});
21 changes: 9 additions & 12 deletions pnpm-lock.yaml

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

Loading