-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
middleware.ts
210 lines (181 loc) · 6.29 KB
/
middleware.ts
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
import { get } from "@vercel/edge-config";
import { collectEvents } from "next-collect/server";
import { cookies } from "next/headers";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { getLocale } from "@calcom/features/auth/lib/getLocale";
import { extendEventData, nextCollectBasicSettings } from "@calcom/lib/telemetry";
import { csp } from "@lib/csp";
import { abTestMiddlewareFactory } from "./abTest/middlewareFactory";
const safeGet = async <T = any>(key: string): Promise<T | undefined> => {
try {
return get<T>(key);
} catch (error) {
// Don't crash if EDGE_CONFIG env var is missing
}
};
const middleware = async (req: NextRequest): Promise<NextResponse<unknown>> => {
const url = req.nextUrl;
const requestHeaders = new Headers(req.headers);
requestHeaders.set("x-url", req.url);
if (!url.pathname.startsWith("/api")) {
//
// NOTE: When tRPC hits an error a 500 is returned, when this is received
// by the application the user is automatically redirected to /auth/login.
//
// - For this reason our matchers are sufficient for an app-wide maintenance page.
//
// Check whether the maintenance page should be shown
const isInMaintenanceMode = await safeGet<boolean>("isInMaintenanceMode");
// If is in maintenance mode, point the url pathname to the maintenance page
if (isInMaintenanceMode) {
req.nextUrl.pathname = `/maintenance`;
return NextResponse.rewrite(req.nextUrl);
}
}
const routingFormRewriteResponse = routingForms.handleRewrite(url);
if (routingFormRewriteResponse) {
return responseWithHeaders({ url, res: routingFormRewriteResponse, req });
}
if (url.pathname.startsWith("/api/trpc/")) {
requestHeaders.set("x-cal-timezone", req.headers.get("x-vercel-ip-timezone") ?? "");
}
if (url.pathname.startsWith("/api/auth/signup")) {
const isSignupDisabled = await safeGet<boolean>("isSignupDisabled");
// If is in maintenance mode, point the url pathname to the maintenance page
if (isSignupDisabled) {
// TODO: Consider using responseWithHeaders here
return NextResponse.json({ error: "Signup is disabled" }, { status: 503 });
}
}
if (url.pathname.startsWith("/auth/login") || url.pathname.startsWith("/login")) {
// Use this header to actually enforce CSP, otherwise it is running in Report Only mode on all pages.
requestHeaders.set("x-csp-enforce", "true");
}
if (url.pathname.startsWith("/future/apps/installed")) {
const returnTo = req.cookies.get("return-to")?.value;
if (returnTo !== undefined) {
requestHeaders.set("Set-Cookie", "return-to=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT");
let validPathname = returnTo;
try {
validPathname = new URL(returnTo).pathname;
} catch (e) {}
const nextUrl = url.clone();
nextUrl.pathname = validPathname;
// TODO: Consider using responseWithHeaders here
return NextResponse.redirect(nextUrl, { headers: requestHeaders });
}
}
if (url.pathname.startsWith("/future/auth/logout")) {
cookies().set("next-auth.session-token", "", {
path: "/",
expires: new Date(0),
});
}
requestHeaders.set("x-pathname", url.pathname);
const locale = await getLocale(req);
requestHeaders.set("x-locale", locale);
const res = NextResponse.next({
request: {
headers: requestHeaders,
},
});
return responseWithHeaders({ url, res, req });
};
const routingForms = {
handleRewrite: (url: URL) => {
// Don't 404 old routing_forms links
if (url.pathname.startsWith("/apps/routing_forms")) {
url.pathname = url.pathname.replace(/^\/apps\/routing_forms($|\/)/, "/apps/routing-forms/");
return NextResponse.rewrite(url);
}
},
};
const embeds = {
addResponseHeaders: ({ url, res }: { url: URL; res: NextResponse }) => {
if (!url.pathname.endsWith("/embed")) {
return res;
}
const isCOEPEnabled = url.searchParams.get("flag.coep") === "true";
if (isCOEPEnabled) {
res.headers.set("Cross-Origin-Embedder-Policy", "require-corp");
}
return res;
},
};
const contentSecurityPolicy = {
addResponseHeaders: ({ res, req }: { res: NextResponse; req: NextRequest }) => {
const { nonce } = csp(req, res ?? null);
if (!process.env.CSP_POLICY) {
res.headers.set("x-csp", "not-opted-in");
} else if (!res.headers.get("x-csp")) {
// If x-csp not set by gSSP, then it's initialPropsOnly
res.headers.set("x-csp", "initialPropsOnly");
} else {
res.headers.set("x-csp", nonce ?? "");
}
return res;
},
};
function responseWithHeaders({ url, res, req }: { url: URL; res: NextResponse; req: NextRequest }) {
const resWithCSP = contentSecurityPolicy.addResponseHeaders({ res, req });
const resWithEmbeds = embeds.addResponseHeaders({ url, res: resWithCSP });
return resWithEmbeds;
}
export const config = {
// Next.js Doesn't support spread operator in config matcher, so, we must list all paths explicitly here.
// https://github.com/vercel/next.js/discussions/42458
matcher: [
"/403",
"/500",
"/d/:path*",
"/more/:path*",
"/maintenance/:path*",
"/enterprise/:path*",
"/upgrade/:path*",
"/connect-and-join/:path*",
"/insights/:path*",
"/:path*/embed",
"/api/auth/signup",
"/api/trpc/:path*",
"/login",
"/auth/login",
"/future/auth/login",
/**
* Paths required by routingForms.handle
*/
"/apps/routing_forms/:path*",
"/event-types",
"/future/event-types/",
"/apps/installed/:category/",
"/future/apps/installed/:category/",
"/apps/:slug/",
"/future/apps/:slug/",
"/apps/:slug/setup/",
"/future/apps/:slug/setup/",
"/apps/categories/",
"/future/apps/categories/",
"/apps/categories/:category/",
"/future/apps/categories/:category/",
"/workflows/:path*",
"/getting-started/:path*",
"/apps",
"/bookings/:status/",
"/video/:path*",
"/teams",
"/future/teams/",
"/settings/:path*",
"/reschedule/:path*",
"/availability/:path*",
"/org/:path*",
"/team/:path*",
"/:user/:type/",
"/:user/",
],
};
export default collectEvents({
middleware: abTestMiddlewareFactory(middleware),
...nextCollectBasicSettings,
cookieName: "__clnds",
extend: extendEventData,
});