forked from zizifn/edgetunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_middleware.ts
76 lines (73 loc) · 2.07 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
67
68
69
70
71
72
73
74
75
76
import { index401, page404 } from './util';
import { parse, stringify, validate } from 'uuid';
async function errorHandling(context: EventContext<any, any, any>) {
try {
return await context.next();
} catch (err) {
return new Response(`${err.message}\n${err.stack}`, { status: 500 });
}
}
async function authentication(
context: EventContext<
any,
any,
{
digestUUID: string;
}
>
) {
// context.data It’s an arbitrary object you can attach data to that will persist during the request. The most common use-cases are for middleware that handles auth and may need to set context.data.username or similar.
// if not set UUID, return 401 page
const userID = context.env['UUID'] || '';
let isVaildUser = validate(userID);
if (!isVaildUser) {
return new Response(index401, {
status: 401,
headers: {
'content-type': 'text/html; charset=utf-8',
},
});
}
// skip authentication
const url = new URL(context.request.url);
if (
// if url has uuid, skip auth
context.request.url.includes(userID)
) {
return context.next();
}
// static page
const basicAuth = context.request.headers.get('Authorization') || '';
const authString = basicAuth.split(' ')?.[1] || '';
if (!atob(authString).includes(userID)) {
return new Response(``, {
status: 401,
headers: {
'content-type': 'text/html; charset=utf-8',
'WWW-Authenticate': 'Basic',
},
});
} else {
const url = new URL(context.request.url);
if (url.pathname === '/') {
const wspath = `/vless/${userID}`;
return new Response(``, {
status: 302,
headers: {
'content-type': 'text/html; charset=utf-8',
Location: `./${userID}?wspath=${encodeURIComponent(wspath)}`,
},
});
}
if (url.pathname.startsWith('/assets')) {
return context.next();
}
return new Response(page404, {
status: 404,
headers: {
'content-type': 'text/html; charset=utf-8',
},
});
}
}
export const onRequest = [errorHandling, authentication];