-
Notifications
You must be signed in to change notification settings - Fork 245
/
index.js
93 lines (78 loc) · 2.83 KB
/
index.js
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
async function handleRequest(request, env) {
const { pathname } = new URL(request.url);
const [_, token, next, ...params] = pathname.split('/');
if (/^v\d+$/.test(token)) {
return proxy(request, env);
} else if (token === env.ACCESS_TOKEN) {
console.log('Accessing master handler');
var result;
if (request.method === 'DELETE') {
await deleteUser(next, env);
result = 'ok';
} else if (next === 'register' || next === 'reset') {
result = await registerUser(params[0], env);
}
if (!result) throw 'Invalid action';
return new Response(`${result}\n`, {
headers: { 'Content-Type': 'text/plain' }
});
}
throw 'Access forbidden';
}
async function proxy(request, env) {
const headers = new Headers(request.headers);
const authKey = 'Authorization';
const token = headers.get(authKey).split(' ').pop();
if (!token) throw 'Auth required';
// validate user
const users = await env.KV.get("users", { type: 'json' }) || {};
let name;
for (let key in users)
if (users[key].key === token)
name = key;
if (!name) throw 'Invalid token';
console.log(`User ${name} acepted.`);
// proxy the request
const url = new URL(request.url);
// 1. replace with the official host
url.host = 'api.openai.com';
// 2. replace with the real API key
headers.set(authKey, `Bearer ${env.OPENAPI_API_KEY}`);
// 3. issue the underlying request
// Only pass body if request method is not 'GET'
const requestBody = request.method !== 'GET' ? JSON.stringify(await request.json()) : null;
return fetch(url, {
method: request.method,
headers: headers,
body: requestBody,
});
}
async function registerUser(user, env) {
if (!user?.length) throw 'Invalid username1';
const users = await env.KV.get("users", { type: 'json' }) || {};
const key = generateAPIKey();
users[user] = { key };
await env.KV.put("users", JSON.stringify(users));
return key;
}
async function deleteUser(user, env) {
if (!user?.length) throw 'Invalid username2';
const users = await env.KV.get("users", { type: 'json' }) || {};
if (!users[user]) throw 'User not found';
delete users[user];
await env.KV.put("users", JSON.stringify(users));
}
function generateAPIKey() {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let apiKey = 'sk-cfw';
for (let i = 0; i < 45; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
apiKey += characters.charAt(randomIndex);
}
return apiKey;
}
export default {
async fetch(request, env) {
return handleRequest(request, env).catch(err => new Response(err || 'Unknown reason', { status: 403 }))
}
};