-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
259 lines (243 loc) · 9.27 KB
/
worker.js
File metadata and controls
259 lines (243 loc) · 9.27 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
export default {
async fetch(request, env, ctx) {
if (request.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE,GET,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
"Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers") ?? "Accept, Authorization, Content-Type, Origin",
"Allow": "DELETE, GET, POST, OPTIONS",
}
});
}
const auth = request.headers.get("Authorization");
if (!auth || !auth.startsWith("Bearer ")) {
return makeErrorResponse(401, "Missing auth");
}
const token = auth.substring("Bearer ".length);
const db = env.d1;
if (request.method === "POST") {
if (verify(token, env["CLIENT_DB_TOKEN"])) {
const body = await request.json();
if (body.duration === 0) {
// unban or untimeout
await deleteBannedMessages(db, body.channelId, body.userId);
} else {
// ban or timeout
await handleBannedMessages(db, body);
}
return new Response(null, { status: 204 });
} else {
return makeErrorResponse(403, "Invalid auth");
}
} else if (request.method === "GET") {
const params = new URL(request.url).searchParams;
const channelId = params.get("channel");
if (channelId) {
const { modId, scopes } = await verifyToken(env, token);
if (!modId) {
return makeErrorResponse(403, "Invalid auth");
}
if (!scopes.includes("moderator:read:shield_mode")) {
return makeErrorResponse(403, "Invalid scopes");
}
if (await isMod(env, channelId, modId, token)) {
const resp = await getBannedMessages(db, channelId, "1" === params.get("sort"));
return Response.json(resp, {
headers: {
"Access-Control-Allow-Origin": "*",
}
});
} else {
return makeErrorResponse(403, "Insufficient auth");
}
} else {
const { modId, scopes } = await verifyToken(env, token);
if (modId) {
if (!scopes.includes("user:read:moderated_channels")) {
return makeErrorResponse(403, "Invalid scopes");
}
const channels = await getModChannels(env, modId, token);
if (!channels) {
return Response.json([], {
headers: {
"Access-Control-Allow-Origin": "*",
}
});
}
const { results } = await db.prepare("SELECT channel_id, channel_name, image_url FROM auths WHERE authorized_at > 0 AND channel_id IN (" + channels.join(",") + ")").all();
return Response.json(results, {
headers: {
"Access-Control-Allow-Origin": "*",
}
});
} else {
return makeErrorResponse(403, "Invalid auth");
}
}
} else if (request.method === "DELETE") {
const url = new URL(request.url);
const channelId = url.searchParams.get("channel");
const userId = url.searchParams.get("user");
if (channelId && userId) {
const { modId, scopes } = await verifyToken(env, token);
if (!modId) {
return makeErrorResponse(403, "Invalid auth");
}
if (!scopes.includes("moderator:read:shield_mode")) {
return makeErrorResponse(403, "Invalid scopes");
}
if (await isMod(env, channelId, modId, token)) {
await deleteBannedMessages(db, channelId, userId);
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
}
});
} else {
return makeErrorResponse(403, "Insufficient auth");
}
} else {
return makeErrorResponse(400, "Invalid request");
}
} else if (request.method == "PUT") {
if (verify(token, env["CLIENT_DB_TOKEN"])) {
const body = await request.json();
const authAt = body.added ? body.timestamp : 0;
const revokeAt = body.added ? 0 : body.timestamp;
await db.prepare("REPLACE INTO auths (channel_id, channel_name, authorized_at, revoked_at, image_url) VALUES (?1, ?2, ?3, ?4, ?5)")
.bind(body.channelId, body.channelName, authAt, revokeAt, body.imageUrl ?? "")
.run();
return new Response(null, { status: 204 });
} else {
return makeErrorResponse(403, "Invalid auth");
}
}
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
}
});
},
};
function makeErrorResponse(code, message) {
return new Response(JSON.stringify({ error: message }), {
status: code,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
}
});
}
function verify(actual, expected) {
const encoder = new TextEncoder();
const a = encoder.encode(actual);
const b = encoder.encode(expected);
return a.length === b.length && crypto.subtle.timingSafeEqual(a, b);
}
async function verifyToken(env, token) {
let body;
try {
const resp = await fetch("https://id.twitch.tv/oauth2/validate", {
method: "GET",
headers: {
"Authorization": "OAuth " + token
}
});
body = await resp.json();
} catch (error) {
body = {};
}
if (body["client_id"] != env["CLIENT_ID"]) return { modId: null, scopes: [] };
return {
modId: body["user_id"],
scopes: body["scopes"] ?? []
};
}
async function isMod(env, channel, user, token) {
const resp = await fetch("https://api.twitch.tv/helix/moderation/shield_mode?broadcaster_id=" + channel + "&moderator_id=" + user, {
method: "GET",
headers: {
"Client-Id": env["CLIENT_ID"],
"Authorization": "Bearer " + token
}
});
const body = await resp.json();
return !!body["data"];
}
async function getModChannels(env, user, token) {
const channels = new Set();
let cursor = "";
do {
const resp = await fetch("https://api.twitch.tv/helix/moderation/channels?first=100&user_id=" + user + "&after=" + cursor, {
method: "GET",
headers: {
"Client-Id": env["CLIENT_ID"],
"Authorization": "Bearer " + token
}
});
const body = await resp.json();
if (body.data) {
body.data.forEach((chan) => {
channels.add(chan["broadcaster_id"]);
});
}
cursor = body.pagination ? body.pagination.cursor : null;
} while (cursor && channels.size < 1000);
channels.add(user);
return Array.from(channels);
}
async function handleBannedMessages(db, data) {
await db.prepare("REPLACE INTO bans (channel_id, user_id, mod_id, mod_login, source_room_id, source_room_login, timestamp, duration, reason, user_login, channel_login) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)")
.bind(data.channelId, data.userId, data.moderatorId, data.moderatorLogin, data.sourceRoomId, data.sourceRoomLogin, data.timestamp, data.duration, data.reason, data.userLogin, data.channelLogin)
.run();
const stmt = db.prepare("INSERT INTO banned_messages (channel, user, username, room_id, room_login, ts, message, fragments, emotes) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)");
await db.batch(data.messages.map((msg) => stmt.bind(data.channelId, data.userId, data.userLogin, msg.sourceId ?? "", msg.sourceLogin ?? "", msg.ts ?? "", msg.text, JSON.stringify(msg.fragments ?? []), JSON.stringify(msg.emotes ?? {}))));
}
async function getBannedMessages(db, channel, oldestFirst) {
const sort = oldestFirst ? "ASC" : "DESC";
const query = db.prepare(`SELECT * FROM (bans LEFT JOIN banned_messages ON bans.channel_id = banned_messages.channel AND bans.user_id = banned_messages.user) WHERE bans.channel_id = ?1 ORDER BY bans.timestamp ${sort}, banned_messages.ts LIMIT 250`).bind(channel);
const { results } = await query.all();
const map = new Map();
for (const row of results) {
let obj = map.get(row["user_id"]);
if (!obj) {
if (map.size >= 100) break;
obj = {
channelLogin: row["channel_login"],
userId: row["user_id"],
userName: row["username"] ?? row["user_login"],
modId: row["mod_id"],
modLogin: row["mod_login"],
sourceId: row["source_room_id"],
sourceLogin: row["source_room_login"],
duration: row["duration"],
reason: row["reason"] ?? "",
timestamp: row["timestamp"],
messages: []
};
map.set(row["user_id"], obj);
}
if (row.message) {
const roomId = row["room_id"] ?? "";
const roomLogin = row["room_login"] ?? "";
obj.messages.push({
text: row["message"],
sourceId: roomId ? roomId : channel,
sourceLogin: roomLogin ? roomLogin : row["channel_login"],
timestamp: row["ts"],
fragments: row["fragments"] ? JSON.parse(row["fragments"]) : [{ text: row["message"] }],
emotes: row["emotes"] ? JSON.parse(row["emotes"]) : {},
});
}
}
return Array.from(map.values());
}
async function deleteBannedMessages(db, channel, user) {
await db.batch([
db.prepare("DELETE FROM bans WHERE channel_id = ?1 AND user_id = ?2").bind(channel, user),
db.prepare("DELETE FROM banned_messages WHERE channel = ?1 AND user = ?2").bind(channel, user),
]);
}