-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
131 lines (108 loc) · 3.3 KB
/
proxy.ts
File metadata and controls
131 lines (108 loc) · 3.3 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
import { NextRequest, NextResponse } from "next/server";
import { redis } from "./lib/redis";
import { nanoid } from "nanoid";
const PRESENCE_TIMEOUT_MS = 60000;
export const proxy = async (req: NextRequest) => {
const pathname = req.nextUrl.pathname;
const roomMatch = pathname.match(/^\/room\/([^/]+)$/);
if (!roomMatch) return NextResponse.redirect(new URL("/", req.url));
const roomId = roomMatch[1];
const meta = await redis.hgetall<{
connected: string | string[];
createdAt: string | number;
}>(`meta:${roomId}`);
if (!meta) {
return NextResponse.redirect(new URL("/?error=room-not-found", req.url));
}
const connected: string[] = Array.isArray(meta.connected)
? meta.connected
: typeof meta.connected === "string"
? JSON.parse(meta.connected)
: [];
const [presenceData, usersData] = await Promise.all([
redis.hgetall<
Record<string, string | { username: string; lastSeen: number }>
>(`presence:${roomId}`),
redis.hgetall<Record<string, string>>(`users:${roomId}`),
]);
const existingToken = req.cookies.get("x-auth-token")?.value;
if (
existingToken &&
connected.includes(existingToken) &&
usersData?.[existingToken]
) {
return NextResponse.next();
}
const now = Date.now();
const activeTokens = new Set<string>();
const staleTokens: string[] = [];
for (const token of connected) {
const hasUser = usersData?.[token];
if (!hasUser) {
staleTokens.push(token);
continue;
}
const presence = presenceData?.[token];
if (presence) {
const parsed =
typeof presence === "string" ? JSON.parse(presence) : presence;
const isActive = now - parsed.lastSeen < PRESENCE_TIMEOUT_MS;
if (isActive) {
activeTokens.add(token);
} else {
staleTokens.push(token);
}
} else {
const roomCreatedAt =
typeof meta.createdAt === "string"
? parseInt(meta.createdAt)
: meta.createdAt;
const roomAge = now - (roomCreatedAt || now);
if (roomAge > PRESENCE_TIMEOUT_MS * 2) {
staleTokens.push(token);
} else {
activeTokens.add(token);
}
}
}
const remaining = await redis.ttl(`meta:${roomId}`);
if (staleTokens.length > 0) {
const cleanedConnected = connected.filter(
(token: string) => !staleTokens.includes(token),
);
await Promise.all([
redis.hset(`meta:${roomId}`, {
connected: JSON.stringify(cleanedConnected),
}),
remaining > 0
? redis.expire(`meta:${roomId}`, remaining)
: Promise.resolve(),
]);
}
if (activeTokens.size >= 2) {
return NextResponse.redirect(new URL("/?error=room-full", req.url));
}
const response = NextResponse.next();
const token = nanoid();
response.cookies.set("x-auth-token", token, {
path: "/",
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
});
const updatedConnected = connected.filter(
(t: string) => !staleTokens.includes(t),
);
await Promise.all([
redis.hset(`meta:${roomId}`, {
connected: JSON.stringify([...updatedConnected, token]),
}),
remaining > 0
? redis.expire(`meta:${roomId}`, remaining)
: Promise.resolve(),
]);
return response;
};
export const config = {
matcher: "/room/:path*",
};