-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.prod.js
150 lines (132 loc) · 5.5 KB
/
api.prod.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
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
const NS = SUB;
const apiMethods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
const apiVersion = ["v1", "v2"];
const apiService = ["db", "search"];
const DEFAULT_SECURITY_HEADERS = {
/*
Secure your application with Content-Security-Policy headers.
Enabling these headers will permit content from a trusted domain and all its subdomains.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
"Content-Security-Policy": "default-src 'self' example.com *.example.com",
*/
/*
You can also set Strict-Transport-Security headers.
These are not automatically set because your website might get added to Chrome's HSTS preload list.
Here's the code if you want to apply it:
"Strict-Transport-Security" : "max-age=63072000; includeSubDomains; preload",
*/
/*
Permissions-Policy header provides the ability to allow or deny the use of browser features, such as opting out of FLoC - which you can use below:
"Permissions-Policy": "interest-cohort=()",
*/
/*
X-XSS-Protection header prevents a page from loading if an XSS attack is detected.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
*/
"X-XSS-Protection": "0; mode=block",
/*
X-Frame-Options header prevents click-jacking attacks.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
*/
"X-Frame-Options": "DENY",
/*
X-Content-Type-Options header prevents MIME-sniffing.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
*/
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Cross-Origin-Embedder-Policy": 'require-corp; report-to="default";',
"Cross-Origin-Opener-Policy": 'same-site; report-to="default";',
"Cross-Origin-Resource-Policy": "same-site",
};
const JSON_HEADERS = {
"Content-Type": "application/json; charset=utf-8",
};
const OPTIONS_HEADERS = {
"Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
};
Object.assign(JSON_HEADERS, DEFAULT_SECURITY_HEADERS);
Object.assign(OPTIONS_HEADERS, DEFAULT_SECURITY_HEADERS);
addEventListener("fetch", (event) =>
event.respondWith(handleRequest(event.request))
);
function JsonBody(value, key) {
const obj = {};
if (key) {
obj[key] = value;
} else {
obj["msg"] = value;
}
return JSON.stringify(obj, null, 2);
}
const initHeader = (code) => {
return { status: code, headers: JSON_HEADERS };
};
async function handleRequest(request) {
const method = request.method;
if (apiMethods.indexOf(method) !== -1) {
if (method === "OPTIONS") {
return new Response(null, { status: 204, headers: OPTIONS_HEADERS });
}
// path will be: /v1/db/:key
const url = new URL(request.url)
const { pathname } = url
const args = pathname.split("/");
const ver = args[1];
if (apiVersion.indexOf(ver) !== -1) {
const service = args[2];
if (apiService.indexOf(service) !== -1) {
const key = args[3];
const postBody = request.body
switch (service) {
case "db":
if (key) {
const dbErrMsg = `msg: POST/PUT object example {"value": "https://example.com"}`
const value = await NS.get(key)
switch (method) {
case "GET":
if (value) return new Response(JsonBody(value, key), initHeader(200))
return new Response(JsonBody(`Value of ${key} not found`), initHeader(404))
case "POST":
if (value) return new Response(JsonBody(`${key} already exists`), initHeader(409))
let postObj
try {
postObj = await request.json()
} catch (e) {
return new Response(dbErrMsg, initHeader(400))
}
if (postBody) {
if (postObj) {
const postVal = postObj["value"];
if (postVal) {
await NS.put(key, postVal)
return new Response(JsonBody(postVal, key), initHeader(201))
}
return new Response(JsonBody("value in POST object not found"), initHeader(404))
}
}
return new Response(dbErrMsg, initHeader(400))
default:
return new Response(JsonBody(`Method ${method} not allowed.`), { status: 405, headers: { Allow: "GET,POST,PUT,DELETE" } });
}
}
return new Response(JsonBody("Key not valid"), initHeader(403));
case "search":
if (method !== "GET") return new Response(JsonBody(`Method ${method} not allowed.`), { status: 405, headers: { Allow: "GET" } });
if (key) {
const list = await NS.list({ prefix: key })
const listKeys = list.keys
if (listKeys) return new Response(JSON.stringify(listKeys, null, 2), { status: 200 });
return new Response(JsonBody("List is empty"), { status: 404 });
}
return new Response(JsonBody("Key not valid"), initHeader(403));
default:
return new Response(JsonBody("Service mismatched"), initHeader(500));
}
}
return new Response(JsonBody("Service mismatched"), initHeader(500));
}
return new Response(JsonBody("API version mismatched"), initHeader(500));
}
return new Response(JsonBody(`Method ${method} not allowed.`), { status: 405, headers: OPTIONS_HEADERS });
}