forked from Commitlabs-Org/Commitlabs-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiResponse.ts
More file actions
186 lines (162 loc) · 4.77 KB
/
Copy pathapiResponse.ts
File metadata and controls
186 lines (162 loc) · 4.77 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
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import { randomBytes } from "crypto";
import { NextRequest, NextResponse } from "next/server";
type NextRouteHandler = (
req: NextRequest,
ctx?: unknown,
) => NextResponse | Promise<NextResponse>;
export interface OkResponse<T> {
success: true;
data: T;
meta?: {
correlationId?: string;
timestamp?: string;
[key: string]: unknown;
};
}
export interface FailResponse {
success: false;
error: {
code: string;
message: string;
correlationId?: string;
timestamp?: string;
details?: unknown;
retryAfterSeconds?: number;
};
}
export type ApiResponse<T> = OkResponse<T> | FailResponse;
export function getCorrelationId(req: NextRequest): string {
return (
req.headers.get("x-correlation-id") ??
req.headers.get("x-request-id") ??
randomBytes(16).toString("hex")
);
}
export function ok<T>(
data: T,
metaOrStatus?: Record<string, unknown> | number,
status = 200,
correlationId?: string,
): NextResponse<OkResponse<T>> {
let resolvedMeta: Record<string, unknown> | undefined;
let resolvedStatus = status;
if (typeof metaOrStatus === "number") {
resolvedStatus = metaOrStatus;
} else {
resolvedMeta = metaOrStatus;
}
const meta =
correlationId || resolvedMeta
? {
...(correlationId ? { correlationId } : {}),
timestamp: new Date().toISOString(),
...(resolvedMeta ?? {}),
}
: undefined;
const response = NextResponse.json<OkResponse<T>>(
{
success: true,
data,
...(meta ? { meta } : {}),
},
{ status: resolvedStatus },
);
if (correlationId) {
response.headers.set("x-correlation-id", correlationId);
response.headers.set("x-request-id", correlationId);
}
return response;
}
export function methodNotAllowed(allowed: string[]): NextRouteHandler {
const allowHeader = allowed.join(", ");
return (): NextResponse<FailResponse> =>
NextResponse.json(
{
success: false,
error: {
code: "METHOD_NOT_ALLOWED",
message: `Method Not Allowed. Supported methods: ${allowHeader}`,
},
},
{
status: 405,
headers: { Allow: allowHeader },
},
);
}
export function fail(
code: string,
message: string,
details?: unknown,
status = 500,
retryAfterOrCorrelationId?: number | string,
correlationIdArg?: string,
): NextResponse<FailResponse> {
const retryAfterSeconds =
typeof retryAfterOrCorrelationId === "number"
? retryAfterOrCorrelationId
: undefined;
const correlationId =
typeof retryAfterOrCorrelationId === "string"
? retryAfterOrCorrelationId
: correlationIdArg;
const response = NextResponse.json<FailResponse>(
{
success: false,
error: {
code,
message,
...(correlationId ? { correlationId } : {}),
timestamp: new Date().toISOString(),
...(details !== undefined ? { details } : {}),
...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
},
},
{
status,
headers:
retryAfterSeconds !== undefined
? { "Retry-After": String(retryAfterSeconds) }
: undefined,
},
);
if (correlationId) {
response.headers.set("x-correlation-id", correlationId);
response.headers.set("x-request-id", correlationId);
}
return response;
}
/**
* Appends standard security headers to an HTTP Response.
*
* Headers added:
* - Content-Security-Policy: Configurable via cspDirectives argument (default: "default-src 'self'")
* - X-Content-Type-Options: "nosniff"
* - X-Frame-Options: "DENY"
* - X-XSS-Protection: "1; mode=block"
* - Strict-Transport-Security: "max-age=31536000; includeSubDomains" (Applied unconditionally as HSTS is standard for secure apps)
* - Referrer-Policy: "strict-origin-when-cross-origin"
*
* @param response - The HTTP Response object to which headers will be attached.
* @param cspDirectives - Optional custom Content-Security-Policy directive string. Defaults to "default-src 'self'".
* @returns The modified Response object.
*/
export function attachSecurityHeaders(response: Response, cspDirectives?: string): Response {
const headers = response.headers;
// Content-Security-Policy
const csp = cspDirectives || "default-src 'self'";
headers.set('Content-Security-Policy', csp);
// X-Content-Type-Options
headers.set('X-Content-Type-Options', 'nosniff');
// X-Frame-Options
headers.set('X-Frame-Options', 'DENY');
// X-XSS-Protection
headers.set('X-XSS-Protection', '1; mode=block');
// Strict-Transport-Security
if (!response.url.startsWith('http://')) {
headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
// Referrer-Policy
headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
return response;
}