-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
82 lines (72 loc) · 2.21 KB
/
index.ts
File metadata and controls
82 lines (72 loc) · 2.21 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
export * from "@gcoredev/proxy-wasm-sdk-as/assembly/proxy"; // this exports the required functions for the proxy to interact with us.
import {
Context,
FilterHeadersStatusValues,
get_property,
registerRootContext,
RootContext,
send_http_response,
} from "@gcoredev/proxy-wasm-sdk-as/assembly";
import { getEnvVar } from "@gcoredev/proxy-wasm-sdk-as/assembly/fastedge";
const BAD_GATEWAY: u32 = 502;
const FORBIDDEN: u32 = 403;
const INTERNAL_SERVER_ERROR: u32 = 500;
class GeoBlockRoot extends RootContext {
createContext(context_id: u32): Context {
return new GeoBlock(context_id, this);
}
}
class GeoBlock extends Context {
allow: bool = true;
constructor(context_id: u32, root_context: GeoBlockRoot) {
super(context_id, root_context);
}
onRequestHeaders(a: u32, end_of_stream: bool): FilterHeadersStatusValues {
const blacklist = getEnvVar("BLACKLIST");
if (!blacklist) {
send_http_response(
INTERNAL_SERVER_ERROR,
"internal server error",
String.UTF8.encode("App misconfigured"),
[]
);
return FilterHeadersStatusValues.StopIteration;
}
const blacklistedCountries = blacklist
.split(",")
.map<string>((c) => c.trim());
if (blacklistedCountries.length === 0) {
send_http_response(
INTERNAL_SERVER_ERROR,
"internal server error",
String.UTF8.encode("App misconfigured"),
[]
);
return FilterHeadersStatusValues.StopIteration;
}
const country = get_property("request.country");
if (country.byteLength === 0) {
send_http_response(
BAD_GATEWAY,
"internal server error",
String.UTF8.encode("Missing country information"),
[]
);
return FilterHeadersStatusValues.StopIteration;
}
const countryStr = String.UTF8.decode(country);
if (blacklistedCountries.includes(countryStr)) {
send_http_response(
FORBIDDEN,
"forbidden",
String.UTF8.encode("Request blacklisted"),
[]
);
return FilterHeadersStatusValues.StopIteration;
}
return FilterHeadersStatusValues.Continue;
}
}
registerRootContext((context_id: u32) => {
return new GeoBlockRoot(context_id);
}, "geoblock");