-
Notifications
You must be signed in to change notification settings - Fork 4
/
middleware.ts
66 lines (57 loc) · 2.08 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
import { NextRequest, NextResponse } from 'next/server'
import { ACTIVITIES_HOST, FORWARDED_HOST } from '@/lib/constants'
import { acceptContainsContentTypes } from '@/lib/utils/acceptContainsContentTypes'
export const config = {
matcher: ['/(@.*)']
}
export async function middleware(request: NextRequest) {
if (request.method === 'GET') {
const pathname = request.nextUrl.pathname
const acceptValue = request.headers.get('Accept')
if (
acceptValue &&
acceptContainsContentTypes(acceptValue, [
'application/activity+json',
'application/ld+json',
'application/json'
])
) {
// Actor route
if (/^\/@\w+$/.test(pathname)) {
const matches = pathname.match(/^\/@(?<username>\w+)/)
const apiUrl = request.nextUrl.clone()
apiUrl.pathname = `/api/users/${matches?.groups?.username}`
return NextResponse.rewrite(apiUrl)
}
// Actor status route
if (/^\/@\w+\/[\w-]+$/.test(pathname) && acceptValue) {
const matches = pathname.match(
/^\/@(?<username>\w+)\/(?<statusId>[\w-]+)/
)
const apiUrl = request.nextUrl.clone()
apiUrl.pathname = `/api/users/${matches?.groups?.username}/statuses/${matches?.groups?.statusId}`
return NextResponse.rewrite(apiUrl)
}
}
// Redirect actor with no host
if (request.nextUrl.pathname.startsWith('/@')) {
const pathname = request.nextUrl.pathname
const totalAt = pathname
.split('')
.reduce((count, char) => (char === '@' ? count + 1 : count), 0)
if (totalAt === 2) return NextResponse.next()
const headers = request.headers
const host =
headers.get(ACTIVITIES_HOST) ??
headers.get(FORWARDED_HOST) ??
headers.get('host') ??
request.nextUrl.host
const pathItems = pathname.split('/').slice(1)
pathItems[0] = `${pathItems[0]}@${host}`
const cloneUrl = request.nextUrl.clone()
cloneUrl.pathname = `/${pathItems.join('/')}`
return NextResponse.rewrite(cloneUrl)
}
return NextResponse.next()
}
}