Update index.ts
This commit is contained in:
parent
34dce0acac
commit
c61cb7edc7
27
src/index.ts
27
src/index.ts
|
|
@ -1,9 +1,6 @@
|
||||||
export interface Env {
|
export interface Env {
|
||||||
/** KV namespace holding the guestbook entries + rate-limit keys. */
|
|
||||||
GUESTBOOK: KVNamespace;
|
GUESTBOOK: KVNamespace;
|
||||||
/** Origin allowed to call the API (CORS). Defaults to "*". */
|
ALLOWED_ORIGINS?: string;
|
||||||
ALLOWED_ORIGIN?: string;
|
|
||||||
/** Turnstile secret key. When unset, the captcha check is skipped. */
|
|
||||||
TURNSTILE_SECRET?: string;
|
TURNSTILE_SECRET?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -34,8 +31,17 @@ const LIMITS = {
|
||||||
website: 200,
|
website: 200,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
function corsHeaders(env: Env): Record<string, string> {
|
function corsHeaders(request: Request, env: Env): Record<string, string> {
|
||||||
const origin = env.ALLOWED_ORIGIN || "*";
|
const requestOrigin = request.headers.get("Origin") ?? "";
|
||||||
|
|
||||||
|
const allowedOrigins =
|
||||||
|
env.ALLOWED_ORIGINS?.split(",").map(o => o.trim()) ?? ["*"];
|
||||||
|
|
||||||
|
const origin =
|
||||||
|
allowedOrigins.includes(requestOrigin) || allowedOrigins.includes("*")
|
||||||
|
? requestOrigin
|
||||||
|
: allowedOrigins[0];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"Access-Control-Allow-Origin": origin,
|
"Access-Control-Allow-Origin": origin,
|
||||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||||
|
|
@ -44,13 +50,18 @@ function corsHeaders(env: Env): Record<string, string> {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function json(data: unknown, status: number, env: Env): Response {
|
function json(
|
||||||
|
data: unknown,
|
||||||
|
status: number,
|
||||||
|
request: Request,
|
||||||
|
env: Env
|
||||||
|
): Response {
|
||||||
return new Response(JSON.stringify(data), {
|
return new Response(JSON.stringify(data), {
|
||||||
status,
|
status,
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json; charset=utf-8",
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
"Cache-Control": "no-store",
|
"Cache-Control": "no-store",
|
||||||
...corsHeaders(env),
|
...corsHeaders(request, env),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue