server/utils/response.ts

83 lines
2.6 KiB
TypeScript
Raw Normal View History

import { config } from "~packages/config-manager";
2024-04-08 05:28:18 +02:00
export const response = (
data: BodyInit | null = null,
2024-04-07 07:30:49 +02:00
status = 200,
headers: Record<string, string> = {},
2023-10-02 02:07:29 +02:00
) => {
2024-04-08 05:28:18 +02:00
return new Response(data, {
2024-04-07 07:30:49 +02:00
headers: {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Strict-Transport-Security": "max-age=3153600",
2024-04-07 07:30:49 +02:00
"X-Permitted-Cross-Domain-Policies": "none",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Headers":
"Authorization,Content-Type,Idempotency-Key",
"Access-Control-Allow-Methods": "POST,PUT,DELETE,GET,PATCH,OPTIONS",
"Access-Control-Allow-Origin": "*",
"Access-Control-Expose-Headers":
"Link,X-RateLimit-Reset,X-RateLimit-Limit,X-RateLimit-Remaining,X-Request-Id,Idempotency-Key",
2024-04-07 13:51:41 +02:00
"Content-Security-Policy":
2024-04-07 14:02:11 +02:00
"default-src 'none'; frame-ancestors 'none'; form-action 'none'",
2024-04-07 07:30:49 +02:00
...headers,
},
status,
});
2023-09-13 02:29:13 +02:00
};
2023-09-12 22:48:10 +02:00
2024-04-08 05:28:18 +02:00
export const clientResponse = (
data: BodyInit | null = null,
status = 200,
headers: Record<string, string> = {},
) => {
return response(data, status, {
"Content-Security-Policy":
"default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src *; font-src 'self'; connect-src 'self'; media-src *; object-src 'none'; prefetch-src 'none'; child-src 'none'; frame-src 'none'; worker-src 'self'; frame-ancestors 'none'; form-action 'self'; upgrade-insecure-requests; block-all-mixed-content; base-uri 'self'; manifest-src 'self'",
"Access-Control-Allow-Origin": "null",
2024-04-08 05:28:18 +02:00
...headers,
});
};
export const jsonResponse = (
data: object,
status = 200,
headers: Record<string, string> = {},
) => {
return response(JSON.stringify(data), status, {
"Content-Type": "application/json",
...headers,
});
};
2023-09-13 07:33:08 +02:00
export const xmlResponse = (data: string, status = 200) => {
2024-04-08 05:28:18 +02:00
return response(data, status, {
"Content-Type": "application/xml",
2024-04-07 07:30:49 +02:00
});
2023-09-13 07:33:08 +02:00
};
2023-09-12 22:48:10 +02:00
export const errorResponse = (error: string, status = 500) => {
2024-04-07 07:30:49 +02:00
return jsonResponse(
{
error: error,
},
status,
);
2023-09-13 02:29:13 +02:00
};
2024-04-08 05:28:18 +02:00
export const redirect = (url: string | URL, status = 302) => {
return response(null, status, {
Location: url.toString(),
});
};
export const proxyUrl = (url: string | null) => {
return url
? new URL(
`/media/proxy?url=${encodeURIComponent(url)}`,
config.http.base_url,
).toString()
: url;
};