@clerk/nextjs
Version:
Clerk SDK for NextJS
206 lines • 8.91 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var utils_exports = {};
__export(utils_exports, {
assertAuthStatus: () => assertAuthStatus,
assertKey: () => assertKey,
assertTokenSignature: () => assertTokenSignature,
decorateRequest: () => decorateRequest,
decryptClerkRequestData: () => decryptClerkRequestData,
encryptClerkRequestData: () => encryptClerkRequestData,
handleMultiDomainAndProxy: () => handleMultiDomainAndProxy,
redirectAdapter: () => redirectAdapter,
setRequestHeadersOnNextResponse: () => setRequestHeadersOnNextResponse
});
module.exports = __toCommonJS(utils_exports);
var import_internal = require("@clerk/backend/internal");
var import_keys = require("@clerk/shared/keys");
var import_logger = require("@clerk/shared/logger");
var import_proxy = require("@clerk/shared/proxy");
var import_utils = require("@clerk/shared/utils");
var import_server = require("next/server");
var import_constants = require("../constants");
var import_feature_flags = require("../utils/feature-flags");
var import_crypto_es = require("../vendor/crypto-es");
var import_constants2 = require("./constants");
var import_errors = require("./errors");
var import_errorThrower = require("./errorThrower");
var import_headers_utils = require("./headers-utils");
const OVERRIDE_HEADERS = "x-middleware-override-headers";
const MIDDLEWARE_HEADER_PREFIX = "x-middleware-request";
const setRequestHeadersOnNextResponse = (res, req, newHeaders) => {
if (!res.headers.get(OVERRIDE_HEADERS)) {
res.headers.set(OVERRIDE_HEADERS, [...req.headers.keys()]);
req.headers.forEach((val, key) => {
res.headers.set(`${MIDDLEWARE_HEADER_PREFIX}-${key}`, val);
});
}
Object.entries(newHeaders).forEach(([key, val]) => {
res.headers.set(OVERRIDE_HEADERS, `${res.headers.get(OVERRIDE_HEADERS)},${key}`);
res.headers.set(`${MIDDLEWARE_HEADER_PREFIX}-${key}`, val);
});
};
function decorateRequest(req, res, requestState, requestData, keylessMode) {
const { reason, message, status, token } = requestState;
if (!res) {
res = import_server.NextResponse.next();
}
if (res.headers.get(import_constants.constants.Headers.NextRedirect)) {
return res;
}
let rewriteURL;
if (res.headers.get(import_constants.constants.Headers.NextResume) === "1") {
res.headers.delete(import_constants.constants.Headers.NextResume);
rewriteURL = new URL(req.url);
}
const rewriteURLHeader = res.headers.get(import_constants.constants.Headers.NextRewrite);
if (rewriteURLHeader) {
const reqURL = new URL(req.url);
rewriteURL = new URL(rewriteURLHeader);
if (rewriteURL.origin !== reqURL.origin) {
return res;
}
}
if (rewriteURL) {
const clerkRequestData = encryptClerkRequestData(requestData, keylessMode);
setRequestHeadersOnNextResponse(res, req, {
[import_internal.constants.Headers.AuthStatus]: status,
[import_internal.constants.Headers.AuthToken]: token || "",
[import_internal.constants.Headers.AuthSignature]: token ? createTokenSignature(token, (requestData == null ? void 0 : requestData.secretKey) || import_constants2.SECRET_KEY || keylessMode.secretKey || "") : "",
[import_internal.constants.Headers.AuthMessage]: message || "",
[import_internal.constants.Headers.AuthReason]: reason || "",
[import_internal.constants.Headers.ClerkUrl]: req.clerkUrl.toString(),
...clerkRequestData ? { [import_internal.constants.Headers.ClerkRequestData]: clerkRequestData } : {}
});
res.headers.set(import_constants.constants.Headers.NextRewrite, rewriteURL.href);
}
return res;
}
const handleMultiDomainAndProxy = (clerkRequest, opts) => {
const relativeOrAbsoluteProxyUrl = (0, import_utils.handleValueOrFn)(opts == null ? void 0 : opts.proxyUrl, clerkRequest.clerkUrl, import_constants2.PROXY_URL);
let proxyUrl;
if (!!relativeOrAbsoluteProxyUrl && !(0, import_proxy.isHttpOrHttps)(relativeOrAbsoluteProxyUrl)) {
proxyUrl = new URL(relativeOrAbsoluteProxyUrl, clerkRequest.clerkUrl).toString();
} else {
proxyUrl = relativeOrAbsoluteProxyUrl;
}
const isSatellite = (0, import_utils.handleValueOrFn)(opts.isSatellite, new URL(clerkRequest.url), import_constants2.IS_SATELLITE);
const domain = (0, import_utils.handleValueOrFn)(opts.domain, new URL(clerkRequest.url), import_constants2.DOMAIN);
const signInUrl = (opts == null ? void 0 : opts.signInUrl) || import_constants2.SIGN_IN_URL;
if (isSatellite && !proxyUrl && !domain) {
throw new Error(import_errors.missingDomainAndProxy);
}
if (isSatellite && !(0, import_proxy.isHttpOrHttps)(signInUrl) && (0, import_keys.isDevelopmentFromSecretKey)(opts.secretKey || import_constants2.SECRET_KEY)) {
throw new Error(import_errors.missingSignInUrlInDev);
}
return {
proxyUrl,
isSatellite,
domain,
signInUrl
};
};
const redirectAdapter = (url) => {
return import_server.NextResponse.redirect(url, { headers: { [import_internal.constants.Headers.ClerkRedirectTo]: "true" } });
};
function assertAuthStatus(req, error) {
if (!(0, import_headers_utils.detectClerkMiddleware)(req)) {
throw new Error(error);
}
}
function assertKey(key, onError) {
if (!key) {
onError();
}
return key;
}
function createTokenSignature(token, key) {
return (0, import_crypto_es.HmacSHA1)(token, key).toString();
}
function assertTokenSignature(token, key, signature) {
if (!signature) {
throw new Error(import_errors.authSignatureInvalid);
}
const expectedSignature = createTokenSignature(token, key);
if (expectedSignature !== signature) {
throw new Error(import_errors.authSignatureInvalid);
}
}
const KEYLESS_ENCRYPTION_KEY = "clerk_keyless_dummy_key";
function encryptClerkRequestData(requestData, keylessMode) {
const isEmpty = (obj) => {
if (!obj) {
return true;
}
return !Object.values(obj).some((v) => v !== void 0);
};
if (isEmpty(requestData) && isEmpty(keylessMode)) {
return;
}
if (requestData.secretKey && !import_constants2.ENCRYPTION_KEY) {
import_logger.logger.warnOnce(
"Clerk: Missing `CLERK_ENCRYPTION_KEY`. Required for propagating `secretKey` middleware option. See docs: https://clerk.com/docs/references/nextjs/clerk-middleware#dynamic-keys"
);
return;
}
const maybeKeylessEncryptionKey = (0, import_utils.isProductionEnvironment)() ? import_constants2.ENCRYPTION_KEY || assertKey(import_constants2.SECRET_KEY, () => import_errorThrower.errorThrower.throwMissingSecretKeyError()) : import_constants2.ENCRYPTION_KEY || import_constants2.SECRET_KEY || KEYLESS_ENCRYPTION_KEY;
return import_crypto_es.AES.encrypt(JSON.stringify({ ...keylessMode, ...requestData }), maybeKeylessEncryptionKey).toString();
}
function decryptClerkRequestData(encryptedRequestData) {
if (!encryptedRequestData) {
return {};
}
const maybeKeylessEncryptionKey = (0, import_utils.isProductionEnvironment)() ? import_constants2.ENCRYPTION_KEY || import_constants2.SECRET_KEY : import_constants2.ENCRYPTION_KEY || import_constants2.SECRET_KEY || KEYLESS_ENCRYPTION_KEY;
try {
return decryptData(encryptedRequestData, maybeKeylessEncryptionKey);
} catch {
if (import_feature_flags.canUseKeyless) {
try {
return decryptData(encryptedRequestData, KEYLESS_ENCRYPTION_KEY);
} catch {
throwInvalidEncryptionKey();
}
}
throwInvalidEncryptionKey();
}
}
function throwInvalidEncryptionKey() {
if ((0, import_utils.isProductionEnvironment)()) {
throw new Error(import_errors.encryptionKeyInvalid);
}
throw new Error(import_errors.encryptionKeyInvalidDev);
}
function decryptData(data, key) {
const decryptedBytes = import_crypto_es.AES.decrypt(data, key);
const encoded = decryptedBytes.toString(import_crypto_es.Utf8);
return JSON.parse(encoded);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
assertAuthStatus,
assertKey,
assertTokenSignature,
decorateRequest,
decryptClerkRequestData,
encryptClerkRequestData,
handleMultiDomainAndProxy,
redirectAdapter,
setRequestHeadersOnNextResponse
});
//# sourceMappingURL=utils.js.map
;