-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathlink.ts
551 lines (501 loc) · 13.7 KB
/
link.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import {
createResponseWithCookies,
detectBot,
getFinalUrl,
isSupportedDeeplinkProtocol,
parse,
} from "@/lib/middleware/utils";
import { recordClick } from "@/lib/tinybird";
import { formatRedisLink } from "@/lib/upstash";
import {
DUB_HEADERS,
LEGAL_WORKSPACE_ID,
LOCALHOST_GEO_DATA,
LOCALHOST_IP,
isDubDomain,
isUnsupportedKey,
nanoid,
punyEncode,
} from "@dub/utils";
import { ipAddress } from "@vercel/functions";
import { cookies } from "next/headers";
import {
NextFetchEvent,
NextRequest,
NextResponse,
userAgent,
} from "next/server";
import { linkCache } from "../api/links/cache";
import { isCaseSensitiveDomain } from "../api/links/case-sensitivity";
import { clickCache } from "../api/links/click-cache";
import { getLinkViaEdge } from "../planetscale";
import { getDomainViaEdge } from "../planetscale/get-domain-via-edge";
import { getPartnerAndDiscount } from "../planetscale/get-partner-discount";
import { hasEmptySearchParams } from "./utils/has-empty-search-params";
import { resolveABTestURL } from "./utils/resolve-ab-test-url";
export default async function LinkMiddleware(
req: NextRequest,
ev: NextFetchEvent,
) {
let { domain, fullKey: originalKey } = parse(req);
if (!domain) {
return NextResponse.next();
}
if (domain === "dev.buff.ly") {
domain = "buff.ly";
}
// encode the key to ascii
// links on Dub are case insensitive by default
let key = punyEncode(originalKey);
if (!isCaseSensitiveDomain(domain)) {
key = key.toLowerCase();
}
const inspectMode = key.endsWith("+");
// if inspect mode is enabled, remove the trailing `+` from the key
if (inspectMode) {
key = key.slice(0, -1);
}
// if key is empty string, set to _root (root domain link)
if (key === "") {
key = "_root";
}
// we don't support .php links (too much bot traffic)
// hence we redirect to the root domain and add `dub-no-track` header to avoid tracking bot traffic
if (isUnsupportedKey(key)) {
return NextResponse.redirect(new URL("/?dub-no-track=1", req.url), {
headers: {
...DUB_HEADERS,
"X-Robots-Tag": "googlebot: noindex",
},
status: 302,
});
}
let cachedLink = await linkCache.get({ domain, key });
let isPartnerLink = Boolean(cachedLink?.programId && cachedLink?.partnerId);
if (!cachedLink) {
let linkData = await getLinkViaEdge({
domain,
key,
});
if (!linkData) {
// TODO: remove this once everything is migrated over
if (domain === "buff.ly") {
return NextResponse.rewrite(
new URL(`/api/links/crawl/bitly/${domain}/${key}`, req.url),
);
}
// check if domain has notFoundUrl configured
const domainData = await getDomainViaEdge(domain);
if (domainData?.notFoundUrl) {
return NextResponse.redirect(domainData.notFoundUrl, {
headers: {
...DUB_HEADERS,
"X-Robots-Tag": "googlebot: noindex",
// pass the Referer value to the not found URL
Referer: req.url,
},
status: 302,
});
} else {
return NextResponse.rewrite(new URL(`/${domain}/not-found`, req.url), {
headers: DUB_HEADERS,
});
}
}
isPartnerLink = Boolean(linkData.programId && linkData.partnerId);
// format link to fit the RedisLinkProps interface
cachedLink = formatRedisLink(linkData as any);
ev.waitUntil(
(async () => {
if (!isPartnerLink) {
linkCache.set(linkData as any);
return;
}
const { partner, discount } = await getPartnerAndDiscount({
programId: linkData.programId,
partnerId: linkData.partnerId,
});
// we'll use this data on /track/click
linkCache.set({
...(linkData as any),
...(partner && { partner }),
...(discount && { discount }),
});
})(),
);
}
const {
id: linkId,
password,
trackConversion,
proxy,
rewrite,
expiresAt,
ios,
android,
geo,
expiredUrl,
doIndex,
webhookIds,
testVariants,
testCompletedAt,
projectId: workspaceId,
} = cachedLink;
const testUrl = resolveABTestURL({
testVariants,
testCompletedAt,
});
const url = testUrl || cachedLink.url;
// by default, we only index default dub domain links (e.g. dub.sh)
// everything else is not indexed by default, unless the user has explicitly set it to be indexed
const shouldIndex = isDubDomain(domain) || doIndex === true;
// only show inspect modal if the link is not password protected
if (inspectMode && !password) {
return NextResponse.rewrite(
new URL(`/inspect/${domain}/${encodeURIComponent(key)}+`, req.url),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
},
);
}
// if the link is password protected
if (password) {
const pw =
req.nextUrl.searchParams.get("pw") ||
req.cookies.get(`dub_password_${linkId}`)?.value;
// rewrite to auth page (/password/[domain]/[key]) if:
// - no `pw` param is provided
// - the `pw` param is incorrect
// this will also ensure that no clicks are tracked unless the password is correct
if (!pw || (await getLinkViaEdge({ domain, key }))?.password !== pw) {
return NextResponse.rewrite(new URL(`/password/${linkId}`, req.url), {
headers: {
...DUB_HEADERS,
...(!shouldIndex && {
"X-Robots-Tag": "googlebot: noindex",
}),
},
});
} else if (pw) {
// strip it from the URL if it's correct
req.nextUrl.searchParams.delete("pw");
}
}
// if the link is banned
if (workspaceId === LEGAL_WORKSPACE_ID) {
return NextResponse.rewrite(new URL("/banned", req.url), {
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
});
}
// if the link has expired
if (expiresAt && new Date(expiresAt) < new Date()) {
if (expiredUrl) {
return NextResponse.redirect(expiredUrl, {
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
status: 302,
});
} else {
return NextResponse.rewrite(new URL(`/expired/${domain}`, req.url), {
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
});
}
}
const dubIdCookieName = `dub_id_${domain}_${key}`;
const cookieStore = cookies();
let clickId = cookieStore.get(dubIdCookieName)?.value;
if (!clickId) {
// if trackConversion is enabled, check if clickId is cached in Redis
if (trackConversion) {
const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
clickId = (await clickCache.get({ domain, key, ip })) || undefined;
}
// if there's still no clickId, generate a new one
if (!clickId) {
clickId = nanoid(16);
}
}
const cookieData = {
path: `/${originalKey}`,
dubIdCookieName,
dubIdCookieValue: clickId,
dubTestUrlValue: testUrl,
};
// for root domain links, if there's no destination URL, rewrite to placeholder page
if (!url) {
ev.waitUntil(
recordClick({
req,
clickId,
linkId,
domain,
key,
url,
webhookIds,
workspaceId,
trackConversion,
}),
);
return createResponseWithCookies(
NextResponse.rewrite(new URL(`/${domain}`, req.url), {
headers: {
...DUB_HEADERS,
// we only index root domain links if they're not subdomains
...(shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
}),
cookieData,
);
}
const isBot = detectBot(req);
const { country } =
process.env.VERCEL === "1" && req.geo ? req.geo : LOCALHOST_GEO_DATA;
// we only pass the clickId if:
// - trackConversion is enabled
// - not a partner link (TODO: add this later) !isPartnerLink
// - there is a clickId
const shouldPassClickId = trackConversion && clickId;
// rewrite to proxy page (/proxy/[domain]/[key]) if it's a bot and proxy is enabled
if (isBot && proxy) {
return createResponseWithCookies(
NextResponse.rewrite(
new URL(`/proxy/${domain}/${encodeURIComponent(key)}`, req.url),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
},
),
cookieData,
);
// rewrite to deeplink page if the link is a mailto: or tel:
} else if (isSupportedDeeplinkProtocol(url)) {
ev.waitUntil(
recordClick({
req,
clickId,
linkId,
domain,
key,
url,
webhookIds,
workspaceId,
trackConversion,
}),
);
return createResponseWithCookies(
NextResponse.rewrite(
new URL(
`/deeplink/${encodeURIComponent(
getFinalUrl(url, {
req,
...(shouldPassClickId && { clickId }),
...(isPartnerLink && { via: key }),
}),
)}`,
req.url,
),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
},
),
cookieData,
);
// rewrite to target URL if link cloaking is enabled
} else if (rewrite) {
ev.waitUntil(
recordClick({
req,
clickId,
linkId,
domain,
key,
url,
webhookIds,
workspaceId,
trackConversion,
}),
);
return createResponseWithCookies(
NextResponse.rewrite(
new URL(
`/cloaked/${encodeURIComponent(
getFinalUrl(url, {
req,
...(shouldPassClickId && { clickId }),
...(isPartnerLink && { via: key }),
}),
)}`,
req.url,
),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && {
"X-Robots-Tag": "googlebot: noindex",
}),
},
},
),
cookieData,
);
// redirect to iOS link if it is specified and the user is on an iOS device
} else if (ios && userAgent(req).os?.name === "iOS") {
ev.waitUntil(
recordClick({
req,
clickId,
linkId,
domain,
key,
url: ios,
webhookIds,
workspaceId,
trackConversion,
}),
);
return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(ios, {
req,
...(shouldPassClickId && { clickId }),
...(isPartnerLink && { via: key }),
}),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
status: key === "_root" ? 301 : 302,
},
),
cookieData,
);
// redirect to Android link if it is specified and the user is on an Android device
} else if (android && userAgent(req).os?.name === "Android") {
ev.waitUntil(
recordClick({
req,
clickId,
linkId,
domain,
key,
url: android,
webhookIds,
workspaceId,
trackConversion,
}),
);
return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(android, {
req,
...(shouldPassClickId && { clickId }),
...(isPartnerLink && { via: key }),
}),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
status: key === "_root" ? 301 : 302,
},
),
cookieData,
);
// redirect to geo-specific link if it is specified and the user is in the specified country
} else if (geo && country && country in geo) {
ev.waitUntil(
recordClick({
req,
clickId,
linkId,
domain,
key,
url: geo[country],
webhookIds,
workspaceId,
trackConversion,
}),
);
return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(geo[country], {
req,
...(shouldPassClickId && { clickId }),
...(isPartnerLink && { via: key }),
}),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
status: key === "_root" ? 301 : 302,
},
),
cookieData,
);
// regular redirect
} else {
ev.waitUntil(
recordClick({
req,
clickId,
linkId,
domain,
key,
url,
webhookIds,
workspaceId,
trackConversion,
}),
);
if (hasEmptySearchParams(url)) {
return createResponseWithCookies(
NextResponse.rewrite(new URL("/api/patch-redirect", req.url), {
request: {
headers: new Headers({
destination: getFinalUrl(url, {
req,
clickId: trackConversion ? clickId : undefined,
}),
}),
},
}),
cookieData,
);
}
return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(url, {
req,
...(shouldPassClickId && { clickId }),
...(isPartnerLink && { via: key }),
}),
{
headers: {
...DUB_HEADERS,
...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),
},
status: key === "_root" ? 301 : 302,
},
),
cookieData,
);
}
}