create-brainerce-store 1.31.0 → 1.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-brainerce-store",
3
- "version": "1.31.0",
3
+ "version": "1.31.2",
4
4
  "description": "Scaffold a production-ready e-commerce storefront connected to Brainerce",
5
5
  "bin": {
6
6
  "create-brainerce-store": "dist/index.js"
@@ -1,242 +1,242 @@
1
- // SECURITY: This BFF proxy intentionally has no application-level rate limiting.
2
- // Rate limiting is the deployer's responsibility — configure it at the platform
3
- // edge (Vercel Firewall, Cloudflare, nginx) or add a Redis-backed limiter
4
- // (e.g. @upstash/ratelimit) here before going to production. Auth endpoints
5
- // like customers/login and customers/register are the most important to cover.
6
- import { NextRequest, NextResponse } from 'next/server';
7
- import { cookies } from 'next/headers';
8
- import { checkCsrf } from '@/lib/csrf';
9
-
10
- const BACKEND_URL = (process.env.BRAINERCE_API_URL || 'https://api.brainerce.com').replace(
11
- /\/$/,
12
- ''
13
- );
14
-
15
- const TOKEN_COOKIE = 'brainerce_customer_token';
16
- const LOGGED_IN_COOKIE = 'brainerce_logged_in';
17
-
18
- const COOKIE_MAX_AGE = 7 * 24 * 60 * 60; // 7 days
19
- const BACKEND_TIMEOUT_MS = 15_000;
20
-
21
- /** Auth endpoints whose responses contain tokens to intercept */
22
- const AUTH_ENDPOINTS = ['customers/login', 'customers/register', 'customers/verify-email'];
23
-
24
- function isAuthEndpoint(path: string): boolean {
25
- return AUTH_ENDPOINTS.some((ep) => path.endsWith(ep));
26
- }
27
-
28
- function isSafePathSegment(segment: string): boolean {
29
- if (!segment) return false;
30
- if (segment === '.' || segment === '..') return false;
31
- if (segment.includes('/') || segment.includes('\\')) return false;
32
- if (segment.includes('\0')) return false;
33
- return true;
34
- }
35
-
36
- function isSecure(): boolean {
37
- return process.env.NODE_ENV === 'production';
38
- }
39
-
40
- function setAuthCookies(response: NextResponse, token: string): void {
41
- response.cookies.set(TOKEN_COOKIE, token, {
42
- httpOnly: true,
43
- secure: isSecure(),
44
- sameSite: 'lax',
45
- path: '/',
46
- maxAge: COOKIE_MAX_AGE,
47
- });
48
- response.cookies.set(LOGGED_IN_COOKIE, '1', {
49
- httpOnly: false,
50
- secure: isSecure(),
51
- sameSite: 'lax',
52
- path: '/',
53
- maxAge: COOKIE_MAX_AGE,
54
- });
55
- }
56
-
57
- function clearAuthCookies(response: NextResponse): void {
58
- response.cookies.delete(TOKEN_COOKIE);
59
- response.cookies.delete(LOGGED_IN_COOKIE);
60
- }
61
-
62
- async function proxyRequest(
63
- request: NextRequest,
64
- params: { path: string[] }
65
- ): Promise<NextResponse> {
66
- const method = request.method;
67
-
68
- // Reject path-traversal attempts before constructing the backend URL
69
- if (!params.path.every(isSafePathSegment)) {
70
- return NextResponse.json({ error: 'Invalid path' }, { status: 400 });
71
- }
72
-
73
- // CSRF protection for mutating requests
74
- if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
75
- const csrfError = checkCsrf(request);
76
- if (csrfError) return csrfError;
77
- }
78
-
79
- // Build backend URL from path segments
80
- const pathSegments = params.path.join('/');
81
- const backendUrl = new URL(`${BACKEND_URL}/${pathSegments}`);
82
-
83
- // Forward query parameters
84
- request.nextUrl.searchParams.forEach((value, key) => {
85
- backendUrl.searchParams.set(key, value);
86
- });
87
-
88
- // Build headers for backend request. Preserve the incoming Content-Type
89
- // (including the multipart boundary for file uploads); default to JSON
90
- // when absent. Overriding the Content-Type would strip the boundary and
91
- // corrupt multipart uploads on the backend.
92
- const incomingContentType = request.headers.get('content-type');
93
- const headers: Record<string, string> = {
94
- 'Content-Type': incomingContentType || 'application/json',
95
- };
96
-
97
- // Send the proxy's own origin (not the client-supplied Origin header).
98
- // The backend's BrowserOriginGuard only checks for presence of Origin/Referer,
99
- // so forwarding a client-controlled value adds spoofing surface for nothing.
100
- headers['Origin'] = request.nextUrl.origin;
101
-
102
- // Forward SDK version header if present
103
- const sdkVersion = request.headers.get('x-sdk-version');
104
- if (sdkVersion) {
105
- headers['X-SDK-Version'] = sdkVersion;
106
- }
107
-
108
- // Forward Accept-Language so the backend locale middleware can resolve translations
109
- const acceptLanguage = request.headers.get('accept-language');
110
- if (acceptLanguage) {
111
- headers['Accept-Language'] = acceptLanguage;
112
- }
113
-
114
- // Add auth token from httpOnly cookie
115
- const cookieStore = await cookies();
116
- const tokenCookie = cookieStore.get(TOKEN_COOKIE);
117
- if (tokenCookie?.value) {
118
- headers['Authorization'] = `Bearer ${tokenCookie.value}`;
119
- }
120
-
121
- // Forward request body for non-GET requests. Use ArrayBuffer so multipart
122
- // bodies (file uploads) pass through unchanged — `request.text()` works for
123
- // JSON but would break binary content.
124
- const isMultipart = incomingContentType?.includes('multipart/form-data') ?? false;
125
- let body: ArrayBuffer | string | undefined;
126
- if (method !== 'GET' && method !== 'HEAD') {
127
- try {
128
- body = isMultipart ? await request.arrayBuffer() : await request.text();
129
- } catch {
130
- // No body
131
- }
132
- }
133
-
134
- // Proxy the request to backend
135
- let backendResponse: Response;
136
- const abortController = new AbortController();
137
- const timeoutId = setTimeout(() => abortController.abort(), BACKEND_TIMEOUT_MS);
138
- try {
139
- backendResponse = await fetch(backendUrl.toString(), {
140
- method,
141
- headers,
142
- body,
143
- signal: abortController.signal,
144
- });
145
- } catch (error) {
146
- const isTimeout = (error as Error)?.name === 'AbortError';
147
- return NextResponse.json(
148
- { error: isTimeout ? 'Backend request timed out' : 'Backend service unavailable' },
149
- { status: isTimeout ? 504 : 502 }
150
- );
151
- } finally {
152
- clearTimeout(timeoutId);
153
- }
154
-
155
- // Read response body
156
- const responseText = await backendResponse.text();
157
-
158
- // For auth endpoints: intercept token, set cookie, strip token from response
159
- if (backendResponse.ok && method === 'POST' && isAuthEndpoint(pathSegments)) {
160
- try {
161
- const data = JSON.parse(responseText);
162
- if (data.token) {
163
- const token = data.token;
164
-
165
- // Strip token from client response
166
- const { token: _stripped, ...safeData } = data;
167
-
168
- const response = NextResponse.json(safeData, {
169
- status: backendResponse.status,
170
- });
171
- setAuthCookies(response, token);
172
- return response;
173
- }
174
- } catch {
175
- // Not JSON or no token field — pass through
176
- }
177
- }
178
-
179
- // Handle 401 responses: clear auth cookies
180
- if (backendResponse.status === 401 && tokenCookie?.value) {
181
- const response = new NextResponse(responseText, {
182
- status: backendResponse.status,
183
- headers: {
184
- 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
185
- },
186
- });
187
- clearAuthCookies(response);
188
- return response;
189
- }
190
-
191
- // Sanitize 5xx responses so backend internals don't leak to the client
192
- if (backendResponse.status >= 500) {
193
- console.error(`[proxy] backend ${backendResponse.status} on ${pathSegments}:`, responseText);
194
- return NextResponse.json(
195
- { error: 'Backend service error' },
196
- { status: backendResponse.status }
197
- );
198
- }
199
-
200
- // Pass through response as-is
201
- return new NextResponse(responseText, {
202
- status: backendResponse.status,
203
- headers: {
204
- 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
205
- },
206
- });
207
- }
208
-
209
- export async function GET(
210
- request: NextRequest,
211
- { params }: { params: Promise<{ path: string[] }> }
212
- ) {
213
- return proxyRequest(request, await params);
214
- }
215
-
216
- export async function POST(
217
- request: NextRequest,
218
- { params }: { params: Promise<{ path: string[] }> }
219
- ) {
220
- return proxyRequest(request, await params);
221
- }
222
-
223
- export async function PUT(
224
- request: NextRequest,
225
- { params }: { params: Promise<{ path: string[] }> }
226
- ) {
227
- return proxyRequest(request, await params);
228
- }
229
-
230
- export async function PATCH(
231
- request: NextRequest,
232
- { params }: { params: Promise<{ path: string[] }> }
233
- ) {
234
- return proxyRequest(request, await params);
235
- }
236
-
237
- export async function DELETE(
238
- request: NextRequest,
239
- { params }: { params: Promise<{ path: string[] }> }
240
- ) {
241
- return proxyRequest(request, await params);
242
- }
1
+ // SECURITY: This BFF proxy intentionally has no application-level rate limiting.
2
+ // Rate limiting is the deployer's responsibility — configure it at the platform
3
+ // edge (Vercel Firewall, Cloudflare, nginx) or add a Redis-backed limiter
4
+ // (e.g. @upstash/ratelimit) here before going to production. Auth endpoints
5
+ // like customers/login and customers/register are the most important to cover.
6
+ import { NextRequest, NextResponse } from 'next/server';
7
+ import { cookies } from 'next/headers';
8
+ import { checkCsrf } from '@/lib/csrf';
9
+
10
+ const BACKEND_URL = (process.env.BRAINERCE_API_URL || 'https://api.brainerce.com').replace(
11
+ /\/$/,
12
+ ''
13
+ );
14
+
15
+ const TOKEN_COOKIE = 'brainerce_customer_token';
16
+ const LOGGED_IN_COOKIE = 'brainerce_logged_in';
17
+
18
+ const COOKIE_MAX_AGE = 7 * 24 * 60 * 60; // 7 days
19
+ const BACKEND_TIMEOUT_MS = 15_000;
20
+
21
+ /** Auth endpoints whose responses contain tokens to intercept */
22
+ const AUTH_ENDPOINTS = ['customers/login', 'customers/register', 'customers/verify-email'];
23
+
24
+ function isAuthEndpoint(path: string): boolean {
25
+ return AUTH_ENDPOINTS.some((ep) => path.endsWith(ep));
26
+ }
27
+
28
+ function isSafePathSegment(segment: string): boolean {
29
+ if (!segment) return false;
30
+ if (segment === '.' || segment === '..') return false;
31
+ if (segment.includes('/') || segment.includes('\\')) return false;
32
+ if (segment.includes('\0')) return false;
33
+ return true;
34
+ }
35
+
36
+ function isSecure(): boolean {
37
+ return process.env.NODE_ENV === 'production';
38
+ }
39
+
40
+ function setAuthCookies(response: NextResponse, token: string): void {
41
+ response.cookies.set(TOKEN_COOKIE, token, {
42
+ httpOnly: true,
43
+ secure: isSecure(),
44
+ sameSite: 'lax',
45
+ path: '/',
46
+ maxAge: COOKIE_MAX_AGE,
47
+ });
48
+ response.cookies.set(LOGGED_IN_COOKIE, '1', {
49
+ httpOnly: false,
50
+ secure: isSecure(),
51
+ sameSite: 'lax',
52
+ path: '/',
53
+ maxAge: COOKIE_MAX_AGE,
54
+ });
55
+ }
56
+
57
+ function clearAuthCookies(response: NextResponse): void {
58
+ response.cookies.delete(TOKEN_COOKIE);
59
+ response.cookies.delete(LOGGED_IN_COOKIE);
60
+ }
61
+
62
+ async function proxyRequest(
63
+ request: NextRequest,
64
+ params: { path: string[] }
65
+ ): Promise<NextResponse> {
66
+ const method = request.method;
67
+
68
+ // Reject path-traversal attempts before constructing the backend URL
69
+ if (!params.path.every(isSafePathSegment)) {
70
+ return NextResponse.json({ error: 'Invalid path' }, { status: 400 });
71
+ }
72
+
73
+ // CSRF protection for mutating requests
74
+ if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
75
+ const csrfError = checkCsrf(request);
76
+ if (csrfError) return csrfError;
77
+ }
78
+
79
+ // Build backend URL from path segments
80
+ const pathSegments = params.path.join('/');
81
+ const backendUrl = new URL(`${BACKEND_URL}/${pathSegments}`);
82
+
83
+ // Forward query parameters
84
+ request.nextUrl.searchParams.forEach((value, key) => {
85
+ backendUrl.searchParams.set(key, value);
86
+ });
87
+
88
+ // Build headers for backend request. Preserve the incoming Content-Type
89
+ // (including the multipart boundary for file uploads); default to JSON
90
+ // when absent. Overriding the Content-Type would strip the boundary and
91
+ // corrupt multipart uploads on the backend.
92
+ const incomingContentType = request.headers.get('content-type');
93
+ const headers: Record<string, string> = {
94
+ 'Content-Type': incomingContentType || 'application/json',
95
+ };
96
+
97
+ // Send the proxy's own origin (not the client-supplied Origin header).
98
+ // The backend's BrowserOriginGuard only checks for presence of Origin/Referer,
99
+ // so forwarding a client-controlled value adds spoofing surface for nothing.
100
+ headers['Origin'] = request.nextUrl.origin;
101
+
102
+ // Forward SDK version header if present
103
+ const sdkVersion = request.headers.get('x-sdk-version');
104
+ if (sdkVersion) {
105
+ headers['X-SDK-Version'] = sdkVersion;
106
+ }
107
+
108
+ // Forward Accept-Language so the backend locale middleware can resolve translations
109
+ const acceptLanguage = request.headers.get('accept-language');
110
+ if (acceptLanguage) {
111
+ headers['Accept-Language'] = acceptLanguage;
112
+ }
113
+
114
+ // Add auth token from httpOnly cookie
115
+ const cookieStore = await cookies();
116
+ const tokenCookie = cookieStore.get(TOKEN_COOKIE);
117
+ if (tokenCookie?.value) {
118
+ headers['Authorization'] = `Bearer ${tokenCookie.value}`;
119
+ }
120
+
121
+ // Forward request body for non-GET requests. Use ArrayBuffer so multipart
122
+ // bodies (file uploads) pass through unchanged — `request.text()` works for
123
+ // JSON but would break binary content.
124
+ const isMultipart = incomingContentType?.includes('multipart/form-data') ?? false;
125
+ let body: ArrayBuffer | string | undefined;
126
+ if (method !== 'GET' && method !== 'HEAD') {
127
+ try {
128
+ body = isMultipart ? await request.arrayBuffer() : await request.text();
129
+ } catch {
130
+ // No body
131
+ }
132
+ }
133
+
134
+ // Proxy the request to backend
135
+ let backendResponse: Response;
136
+ const abortController = new AbortController();
137
+ const timeoutId = setTimeout(() => abortController.abort(), BACKEND_TIMEOUT_MS);
138
+ try {
139
+ backendResponse = await fetch(backendUrl.toString(), {
140
+ method,
141
+ headers,
142
+ body,
143
+ signal: abortController.signal,
144
+ });
145
+ } catch (error) {
146
+ const isTimeout = (error as Error)?.name === 'AbortError';
147
+ return NextResponse.json(
148
+ { error: isTimeout ? 'Backend request timed out' : 'Backend service unavailable' },
149
+ { status: isTimeout ? 504 : 502 }
150
+ );
151
+ } finally {
152
+ clearTimeout(timeoutId);
153
+ }
154
+
155
+ // Read response body
156
+ const responseText = await backendResponse.text();
157
+
158
+ // For auth endpoints: intercept token, set cookie, strip token from response
159
+ if (backendResponse.ok && method === 'POST' && isAuthEndpoint(pathSegments)) {
160
+ try {
161
+ const data = JSON.parse(responseText);
162
+ if (data.token) {
163
+ const token = data.token;
164
+
165
+ // Strip token from client response
166
+ const { token: _stripped, ...safeData } = data;
167
+
168
+ const response = NextResponse.json(safeData, {
169
+ status: backendResponse.status,
170
+ });
171
+ setAuthCookies(response, token);
172
+ return response;
173
+ }
174
+ } catch {
175
+ // Not JSON or no token field — pass through
176
+ }
177
+ }
178
+
179
+ // Handle 401 responses: clear auth cookies
180
+ if (backendResponse.status === 401 && tokenCookie?.value) {
181
+ const response = new NextResponse(responseText, {
182
+ status: backendResponse.status,
183
+ headers: {
184
+ 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
185
+ },
186
+ });
187
+ clearAuthCookies(response);
188
+ return response;
189
+ }
190
+
191
+ // Sanitize 5xx responses so backend internals don't leak to the client
192
+ if (backendResponse.status >= 500) {
193
+ console.error(`[proxy] backend ${backendResponse.status} on ${pathSegments}:`, responseText);
194
+ return NextResponse.json(
195
+ { error: 'Backend service error' },
196
+ { status: backendResponse.status }
197
+ );
198
+ }
199
+
200
+ // Pass through response as-is
201
+ return new NextResponse(responseText, {
202
+ status: backendResponse.status,
203
+ headers: {
204
+ 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
205
+ },
206
+ });
207
+ }
208
+
209
+ export async function GET(
210
+ request: NextRequest,
211
+ { params }: { params: Promise<{ path: string[] }> }
212
+ ) {
213
+ return proxyRequest(request, await params);
214
+ }
215
+
216
+ export async function POST(
217
+ request: NextRequest,
218
+ { params }: { params: Promise<{ path: string[] }> }
219
+ ) {
220
+ return proxyRequest(request, await params);
221
+ }
222
+
223
+ export async function PUT(
224
+ request: NextRequest,
225
+ { params }: { params: Promise<{ path: string[] }> }
226
+ ) {
227
+ return proxyRequest(request, await params);
228
+ }
229
+
230
+ export async function PATCH(
231
+ request: NextRequest,
232
+ { params }: { params: Promise<{ path: string[] }> }
233
+ ) {
234
+ return proxyRequest(request, await params);
235
+ }
236
+
237
+ export async function DELETE(
238
+ request: NextRequest,
239
+ { params }: { params: Promise<{ path: string[] }> }
240
+ ) {
241
+ return proxyRequest(request, await params);
242
+ }