forked from clerk/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
289 lines (244 loc) · 10 KB
/
Copy pathutils.ts
File metadata and controls
289 lines (244 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import type { AuthenticateRequestOptions, ClerkRequest, RequestState } from '@clerk/backend/internal';
import { constants } from '@clerk/backend/internal';
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 type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { constants as nextConstants } from '../constants';
import { DOMAIN, ENCRYPTION_KEY, IS_SATELLITE, PROXY_URL, SECRET_KEY, SIGN_IN_URL } from './constants';
import { authSignatureInvalid, encryptionKeyInvalid, missingDomainAndProxy, missingSignInUrlInDev } from './errors';
import { errorThrower } from './errorThrower';
import type { RequestLike } from './types';
export function getCustomAttributeFromRequest(req: RequestLike, key: string): string | null | undefined {
// @ts-expect-error - TS doesn't like indexing into RequestLike
return key in req ? req[key] : undefined;
}
export function getAuthKeyFromRequest(
req: RequestLike,
key: keyof typeof constants.Attributes,
): string | null | undefined {
return getCustomAttributeFromRequest(req, constants.Attributes[key]) || getHeader(req, constants.Headers[key]);
}
export function getHeader(req: RequestLike, name: string): string | null | undefined {
if (isNextRequest(req)) {
return req.headers.get(name);
}
// If no header has been determined for IncomingMessage case, check if available within private `socket` headers
// When deployed to vercel, req.headers for API routes is a `IncomingHttpHeaders` key-val object which does not follow
// the Headers spec so the name is no longer case-insensitive.
return req.headers[name] || req.headers[name.toLowerCase()] || (req.socket as any)?._httpMessage?.getHeader(name);
}
export function getCookie(req: RequestLike, name: string): string | undefined {
if (isNextRequest(req)) {
// Nextjs broke semver in the 13.0.0 -> 13.0.1 release, so even though
// this should be RequestCookie in all updated apps. In order to support apps
// using v13.0.0 still, we explicitly add the string type
// https://github.com/vercel/next.js/pull/41526
const reqCookieOrString = req.cookies.get(name) as ReturnType<NextRequest['cookies']['get']> | string | undefined;
if (!reqCookieOrString) {
return undefined;
}
return typeof reqCookieOrString === 'string' ? reqCookieOrString : reqCookieOrString.value;
}
return req.cookies[name];
}
function isNextRequest(val: unknown): val is NextRequest {
try {
const { headers, nextUrl, cookies } = (val || {}) as NextRequest;
return (
typeof headers?.get === 'function' &&
typeof nextUrl?.searchParams.get === 'function' &&
typeof cookies?.get === 'function'
);
} catch (e) {
return false;
}
}
const OVERRIDE_HEADERS = 'x-middleware-override-headers';
const MIDDLEWARE_HEADER_PREFIX = 'x-middleware-request' as string;
export const setRequestHeadersOnNextResponse = (
res: NextResponse | Response,
req: Request,
newHeaders: Record<string, string>,
) => {
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
res.headers.set(OVERRIDE_HEADERS, [...req.headers.keys()]);
req.headers.forEach((val, key) => {
res.headers.set(`${MIDDLEWARE_HEADER_PREFIX}-${key}`, val);
});
}
// Now that we have normalised res to include overrides, just append the new header
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);
});
};
// Auth result will be set as both a query param & header when applicable
export function decorateRequest(
req: ClerkRequest,
res: Response,
requestState: RequestState,
requestData: AuthenticateRequestOptions,
keylessMode: Pick<AuthenticateRequestOptions, 'publishableKey' | 'secretKey'>,
): Response {
const { reason, message, status, token } = requestState;
// pass-through case, convert to next()
if (!res) {
res = NextResponse.next();
}
// redirect() case, return early
if (res.headers.get(nextConstants.Headers.NextRedirect)) {
return res;
}
let rewriteURL;
// next() case, convert to a rewrite
if (res.headers.get(nextConstants.Headers.NextResume) === '1') {
res.headers.delete(nextConstants.Headers.NextResume);
rewriteURL = new URL(req.url);
}
// rewrite() case, set auth result only if origin remains the same
const rewriteURLHeader = res.headers.get(nextConstants.Headers.NextRewrite);
if (rewriteURLHeader) {
const reqURL = new URL(req.url);
rewriteURL = new URL(rewriteURLHeader);
// if the origin has changed, return early
if (rewriteURL.origin !== reqURL.origin) {
return res;
}
}
if (rewriteURL) {
const clerkRequestData = encryptClerkRequestData(requestData, keylessMode);
setRequestHeadersOnNextResponse(res, req, {
[constants.Headers.AuthStatus]: status,
[constants.Headers.AuthToken]: token || '',
[constants.Headers.AuthSignature]: token
? createTokenSignature(token, requestData?.secretKey || SECRET_KEY || keylessMode.secretKey || '')
: '',
[constants.Headers.AuthMessage]: message || '',
[constants.Headers.AuthReason]: reason || '',
[constants.Headers.ClerkUrl]: req.clerkUrl.toString(),
...(clerkRequestData ? { [constants.Headers.ClerkRequestData]: clerkRequestData } : {}),
});
res.headers.set(nextConstants.Headers.NextRewrite, rewriteURL.href);
}
return res;
}
export const apiEndpointUnauthorizedNextResponse = () => {
return NextResponse.json(null, { status: 401, statusText: 'Unauthorized' });
};
export const handleMultiDomainAndProxy = (clerkRequest: ClerkRequest, opts: AuthenticateRequestOptions) => {
const relativeOrAbsoluteProxyUrl = handleValueOrFn(opts?.proxyUrl, clerkRequest.clerkUrl, PROXY_URL);
let proxyUrl;
if (!!relativeOrAbsoluteProxyUrl && !isHttpOrHttps(relativeOrAbsoluteProxyUrl)) {
proxyUrl = new URL(relativeOrAbsoluteProxyUrl, clerkRequest.clerkUrl).toString();
} else {
proxyUrl = relativeOrAbsoluteProxyUrl;
}
const isSatellite = handleValueOrFn(opts.isSatellite, new URL(clerkRequest.url), IS_SATELLITE);
const domain = handleValueOrFn(opts.domain, new URL(clerkRequest.url), DOMAIN);
const signInUrl = opts?.signInUrl || SIGN_IN_URL;
if (isSatellite && !proxyUrl && !domain) {
throw new Error(missingDomainAndProxy);
}
if (isSatellite && !isHttpOrHttps(signInUrl) && isDevelopmentFromSecretKey(opts.secretKey || SECRET_KEY)) {
throw new Error(missingSignInUrlInDev);
}
return {
proxyUrl,
isSatellite,
domain,
signInUrl,
};
};
export const redirectAdapter = (url: string | URL) => {
return NextResponse.redirect(url, { headers: { [constants.Headers.ClerkRedirectTo]: 'true' } });
};
export function assertAuthStatus(req: RequestLike, error: string) {
const authStatus = getAuthKeyFromRequest(req, 'AuthStatus');
if (!authStatus) {
throw new Error(error);
}
}
export function assertKey(key: string | undefined, onError: () => never): string {
if (!key) {
onError();
}
return key;
}
/**
* 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();
}
/**
* Assert that the provided token generates a matching signature.
*/
export function assertTokenSignature(token: string, key: string, signature?: string | null) {
if (!signature) {
throw new Error(authSignatureInvalid);
}
const expectedSignature = createTokenSignature(token, key);
if (expectedSignature !== signature) {
throw new Error(authSignatureInvalid);
}
}
const KEYLESS_ENCRYPTION_KEY = 'clerk_keyless_dummy_key';
/**
* Encrypt request data propagated between server requests.
* @internal
**/
export function encryptClerkRequestData(
requestData: Partial<AuthenticateRequestOptions>,
keylessMode: Pick<AuthenticateRequestOptions, 'publishableKey' | 'secretKey'>,
) {
const isEmpty = (obj: Record<string, any> | undefined) => {
if (!obj) {
return true;
}
return !Object.values(obj).some(v => v !== undefined);
};
if (isEmpty(requestData) && isEmpty(keylessMode)) {
return;
}
if (requestData.secretKey && !ENCRYPTION_KEY) {
// TODO SDK-1833: change this to an error in the next major version of `@clerk/nextjs`
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 = isProductionEnvironment()
? ENCRYPTION_KEY || assertKey(SECRET_KEY, () => errorThrower.throwMissingSecretKeyError())
: ENCRYPTION_KEY || SECRET_KEY || KEYLESS_ENCRYPTION_KEY;
return AES.encrypt(JSON.stringify({ ...keylessMode, ...requestData }), maybeKeylessEncryptionKey).toString();
}
/**
* Decrypt request data propagated between server requests.
* @internal
*/
export function decryptClerkRequestData(
encryptedRequestData?: string | undefined | null,
): Partial<AuthenticateRequestOptions> {
if (!encryptedRequestData) {
return {};
}
const maybeKeylessEncryptionKey = isProductionEnvironment()
? ENCRYPTION_KEY || SECRET_KEY
: ENCRYPTION_KEY || SECRET_KEY || KEYLESS_ENCRYPTION_KEY;
try {
const decryptedBytes = AES.decrypt(encryptedRequestData, maybeKeylessEncryptionKey);
const encoded = decryptedBytes.toString(encUtf8);
return JSON.parse(encoded);
} catch (err) {
throw new Error(encryptionKeyInvalid);
}
}