-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathuseAdmin.ts
More file actions
420 lines (365 loc) · 11.6 KB
/
Copy pathuseAdmin.ts
File metadata and controls
420 lines (365 loc) · 11.6 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
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
import { useEffect, useMemo, useState } from "react";
import type { ServerData } from "@/hooks/useSSRData";
import { useList, type BaseServer } from "@/hooks/useList";
import type { BanFilter } from "@/components/ServerListView";
import {
API_PATHS,
adminIPBanPath,
adminLeasePath,
encodeLeaseID,
} from "@/lib/apiPaths";
import { APIClientError, apiClient } from "@/lib/apiClient";
import { parseLeaseMetadata } from "@/lib/metadata";
export type ApprovalMode = "auto" | "manual";
type LeaseAction = "approve" | "deny" | "ban";
type ApprovalModeResponse = {
approval_mode?: ApprovalMode;
};
type LandingPageSettingsResponse = {
enabled?: boolean;
};
type AdminSnapshotResponse = {
approval_mode?: ApprovalMode;
landing_page_enabled?: boolean;
leases?: ServerData[];
udp?: { enabled: boolean; max_leases: number };
};
type LeaseActionResult = ApprovalModeResponse;
export interface AdminServer extends BaseServer {
peerId: string;
isBanned: boolean;
bps: number;
isApproved: boolean;
isDenied: boolean;
ip: string;
displayIP: string;
isIPBanned: boolean;
transport: string;
udpPort: number;
}
export interface UDPSettings {
enabled: boolean;
maxLeases: number;
}
const ADMIN_ERROR_MESSAGE_BY_CODE: Record<string, string> = {
invalid_mode: "Invalid approval mode. Choose auto or manual and retry.",
invalid_lease_id: "Selected lease identifier is invalid. Refresh and try again.",
lease_rejected: "Request was rejected by policy. Review conflicts and retry.",
ip_banned: "Request denied because the source IP is banned.",
unauthorized: "Admin authorization failed. Sign in again and retry.",
method_not_allowed: "This action is not supported by the current server version.",
};
function toAdminErrorMessage(error: unknown, fallback: string): string {
if (error instanceof APIClientError) {
const mappedMessage = ADMIN_ERROR_MESSAGE_BY_CODE[error.code];
if (mappedMessage) {
return mappedMessage;
}
if (error.status === 401 || error.status === 403) {
return "Admin authorization failed. Sign in again and retry.";
}
if (error.status === 409) {
return "Request was rejected by policy. Refresh and retry.";
}
const message = error.message.trim();
return message || fallback;
}
if (error instanceof Error) {
const message = error.message.trim();
return message || fallback;
}
return fallback;
}
function toAdminServer(
row: ServerData,
index: number
): AdminServer {
const metadata = parseLeaseMetadata(row.Metadata);
const hostname = row.Hostname || "";
return {
id: index + 1,
name: row.Name || hostname || "(unnamed)",
description: metadata.description,
tags: metadata.tags,
thumbnail: metadata.thumbnail,
owner: metadata.owner,
online: (row.Ready || 0) > 0,
dns: hostname,
link: hostname ? `https://${hostname}/` : "",
lastUpdated: row.LastSeenAt || undefined,
firstSeen: row.FirstSeenAt || undefined,
peerId: row.ID,
isBanned: row.IsBanned || false,
bps: row.BPS || 0,
isApproved: row.IsApproved || false,
isDenied: row.IsDenied || false,
ip: row.ClientIP || "",
displayIP: row.ReportedIP || row.ClientIP || "",
isIPBanned: row.IsIPBanned || false,
transport: row.Transport || "tcp",
udpPort: row.UDPPort || 0,
};
}
function normalizeApprovalMode(value: string | undefined): ApprovalMode {
return value === "manual" ? "manual" : "auto";
}
function dedupeStrings(values: string[]): string[] {
const seen = new Set<string>();
const output: string[] = [];
values.forEach((value) => {
if (seen.has(value)) {
return;
}
seen.add(value);
output.push(value);
});
return output;
}
interface AdminSnapshot {
serverData: ServerData[];
approvalMode: ApprovalMode;
landingPageEnabled: boolean;
udpSettings: UDPSettings;
}
async function loadAdminSnapshot(): Promise<AdminSnapshot> {
const snapshot = await apiClient.get<AdminSnapshotResponse>(API_PATHS.admin.snapshot);
const normalizedLeases = Array.isArray(snapshot?.leases) ? snapshot.leases : [];
return {
serverData: normalizedLeases,
approvalMode: normalizeApprovalMode(snapshot?.approval_mode),
landingPageEnabled: snapshot?.landing_page_enabled ?? true,
udpSettings: {
enabled: snapshot?.udp?.enabled ?? false,
maxLeases: snapshot?.udp?.max_leases ?? 0,
},
};
}
export function useAdmin() {
const [serverData, setServerData] = useState<ServerData[]>([]);
const [approvalMode, setApprovalMode] = useState<ApprovalMode>("auto");
const [landingPageEnabled, setLandingPageEnabled] = useState(true);
const [udpSettings, setUDPSettings] = useState<UDPSettings>({ enabled: false, maxLeases: 0 });
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [banFilter, setBanFilter] = useState<BanFilter>("all");
const applySnapshot = (snapshot: AdminSnapshot) => {
setServerData(snapshot.serverData);
setApprovalMode(snapshot.approvalMode);
setLandingPageEnabled(snapshot.landingPageEnabled);
setUDPSettings(snapshot.udpSettings);
};
const fetchData = async () => {
setError("");
try {
applySnapshot(await loadAdminSnapshot());
} catch (err: unknown) {
setError(toAdminErrorMessage(err, "Failed to load admin data"));
}
};
useEffect(() => {
let mounted = true;
const loadInitialData = async () => {
setError("");
setLoading(true);
try {
const snapshot = await loadAdminSnapshot();
if (!mounted) {
return;
}
applySnapshot(snapshot);
} catch (err: unknown) {
if (!mounted) {
return;
}
setError(toAdminErrorMessage(err, "Failed to load admin data"));
} finally {
if (mounted) {
setLoading(false);
}
}
};
void loadInitialData();
return () => {
mounted = false;
};
}, []);
const servers: AdminServer[] = useMemo(() => {
return serverData.map((row, index) => toAdminServer(row, index));
}, [serverData]);
const additionalFilter = (server: AdminServer) => {
switch (banFilter) {
case "banned":
return server.isBanned;
case "active":
return !server.isBanned;
default:
return true;
}
};
const listState = useList({
servers,
storageKey: "adminFavorites",
additionalFilter,
});
const runAdminAction = async (action: () => Promise<void>) => {
setError("");
try {
await action();
await fetchData();
} catch (err: unknown) {
const message = toAdminErrorMessage(err, "Action failed");
console.error(err);
setError(message);
throw err;
}
};
const updateLeaseAction = async (
peerId: string,
action: LeaseAction,
enabled: boolean
) => {
if (!peerId) {
throw new Error("Missing lease ID");
}
const encodedLeaseID = encodeLeaseID(peerId);
const method = enabled ? apiClient.post : apiClient.delete;
await method<LeaseActionResult>(adminLeasePath(encodedLeaseID, action));
};
const handleBanFilterChange = (value: BanFilter) => {
setBanFilter(value);
};
const handleBanStatus = (peerId: string, isBan: boolean) =>
runAdminAction(() => updateLeaseAction(peerId, "ban", isBan));
const handleBPSChange = async (peerId: string, bps: number) => {
if (!peerId) {
throw new Error("Missing lease ID");
}
const encodedLeaseID = encodeLeaseID(peerId);
const normalizedBPS = Math.max(0, Math.trunc(bps));
const previousBPS = serverData.find((row) => row.ID === peerId)?.BPS ?? 0;
setServerData((prev) =>
prev.map((row) =>
row.ID === peerId ? { ...row, BPS: normalizedBPS } : row
)
);
try {
await runAdminAction(async () => {
if (!Number.isFinite(normalizedBPS) || normalizedBPS <= 0) {
await apiClient.delete<LeaseActionResult>(
adminLeasePath(encodedLeaseID, "bps")
);
return;
}
await apiClient.post<LeaseActionResult>(
adminLeasePath(encodedLeaseID, "bps"),
{ bps: normalizedBPS }
);
});
} catch (err) {
setServerData((prev) =>
prev.map((row) =>
row.ID === peerId ? { ...row, BPS: previousBPS } : row
)
);
throw err;
}
};
const handleApprovalModeChange = async (mode: ApprovalMode) => {
await runAdminAction(async () => {
const response = await apiClient.post<ApprovalModeResponse>(
API_PATHS.admin.approvalMode,
{ mode }
);
const nextMode = normalizeApprovalMode(response?.approval_mode ?? mode);
setApprovalMode(nextMode);
});
};
const handleUDPSettingsChange = async (settings: UDPSettings) => {
await runAdminAction(async () => {
const response = await apiClient.post<{ enabled: boolean; max_leases: number }>(
API_PATHS.admin.udpSettings,
{ enabled: settings.enabled, max_leases: settings.maxLeases }
);
setUDPSettings({
enabled: response?.enabled ?? settings.enabled,
maxLeases: response?.max_leases ?? settings.maxLeases,
});
});
};
const handleLandingPageEnabledChange = async (enabled: boolean) => {
await runAdminAction(async () => {
const response = await apiClient.post<LandingPageSettingsResponse>(
API_PATHS.admin.landingPage,
{ enabled }
);
setLandingPageEnabled(response?.enabled ?? enabled);
});
};
const handleApproveStatus = (peerId: string, approve: boolean) =>
runAdminAction(() => updateLeaseAction(peerId, "approve", approve));
const handleDenyStatus = (peerId: string, deny: boolean) =>
runAdminAction(() => updateLeaseAction(peerId, "deny", deny));
const handleIPBanStatus = (ip: string, isBan: boolean) =>
runAdminAction(async () => {
const normalizedIP = ip.trim();
if (!normalizedIP) {
throw new Error("Missing IP address");
}
if (isBan) {
await apiClient.post<LeaseActionResult>(adminIPBanPath(normalizedIP));
return;
}
await apiClient.delete<LeaseActionResult>(adminIPBanPath(normalizedIP));
});
const runBulkLeaseAction = async (peerIds: string[], action: LeaseAction) => {
const normalizedPeerIDs = dedupeStrings(peerIds.filter((peerId) => peerId.length > 0));
if (normalizedPeerIDs.length === 0) {
throw new Error("No valid leases selected");
}
const results = await Promise.allSettled(
normalizedPeerIDs.map((peerId) =>
apiClient.post<LeaseActionResult>(
adminLeasePath(encodeLeaseID(peerId), action)
)
)
);
const failed = results.find(
(
result
): result is PromiseRejectedResult =>
result.status === "rejected"
);
if (failed) {
throw failed.reason instanceof Error
? failed.reason
: new Error(String(failed.reason));
}
};
const handleBulkAction = (peerIds: string[], action: LeaseAction) =>
runAdminAction(() => runBulkLeaseAction(peerIds, action));
const handleBulkApprove = (peerIds: string[]) => handleBulkAction(peerIds, "approve");
const handleBulkDeny = (peerIds: string[]) => handleBulkAction(peerIds, "deny");
const handleBulkBan = (peerIds: string[]) => handleBulkAction(peerIds, "ban");
return {
servers,
...listState,
banFilter,
approvalMode,
landingPageEnabled,
udpSettings,
loading,
error,
handleBanFilterChange,
handleBanStatus,
handleBPSChange,
handleApprovalModeChange,
handleLandingPageEnabledChange,
handleUDPSettingsChange,
handleApproveStatus,
handleDenyStatus,
handleIPBanStatus,
handleBulkApprove,
handleBulkDeny,
handleBulkBan,
};
}