create-brainerce-store 1.28.13 → 1.28.17

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.
Files changed (24) hide show
  1. package/dist/index.js +1 -1
  2. package/messages/en.json +390 -389
  3. package/messages/he.json +390 -389
  4. package/package.json +46 -46
  5. package/templates/nextjs/base/next.config.ts +47 -47
  6. package/templates/nextjs/base/src/app/api/auth/logout/route.ts +15 -15
  7. package/templates/nextjs/base/src/app/api/auth/oauth-callback/route.ts +66 -66
  8. package/templates/nextjs/base/src/app/api/auth/reset-password/route.ts +76 -76
  9. package/templates/nextjs/base/src/app/api/store/[...path]/route.ts +235 -229
  10. package/templates/nextjs/base/src/app/checkout/page.tsx +975 -975
  11. package/templates/nextjs/base/src/app/products/[slug]/page.tsx +73 -76
  12. package/templates/nextjs/base/src/app/products/[slug]/product-client-section.tsx +529 -501
  13. package/templates/nextjs/base/src/app/products/page.tsx +475 -482
  14. package/templates/nextjs/base/src/app/reset-password/page.tsx +138 -138
  15. package/templates/nextjs/base/src/components/auth/register-form.tsx +245 -245
  16. package/templates/nextjs/base/src/components/checkout/checkout-form.tsx +416 -416
  17. package/templates/nextjs/base/src/components/checkout/payment-step.tsx +656 -656
  18. package/templates/nextjs/base/src/components/seo/product-json-ld.tsx +88 -88
  19. package/templates/nextjs/base/src/lib/brainerce.ts.ejs +6 -2
  20. package/templates/nextjs/base/src/lib/csrf.ts +11 -11
  21. package/templates/nextjs/base/src/lib/nonce.ts +10 -10
  22. package/templates/nextjs/base/src/lib/safe-redirect.ts +45 -45
  23. package/templates/nextjs/base/src/lib/sanitize-html.ts +93 -93
  24. package/templates/nextjs/base/src/lib/validation.ts +37 -37
@@ -1,229 +1,235 @@
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
89
- const headers: Record<string, string> = {
90
- 'Content-Type': 'application/json',
91
- };
92
-
93
- // Send the proxy's own origin (not the client-supplied Origin header).
94
- // The backend's BrowserOriginGuard only checks for presence of Origin/Referer,
95
- // so forwarding a client-controlled value adds spoofing surface for nothing.
96
- headers['Origin'] = request.nextUrl.origin;
97
-
98
- // Forward SDK version header if present
99
- const sdkVersion = request.headers.get('x-sdk-version');
100
- if (sdkVersion) {
101
- headers['X-SDK-Version'] = sdkVersion;
102
- }
103
-
104
- // Add auth token from httpOnly cookie
105
- const cookieStore = await cookies();
106
- const tokenCookie = cookieStore.get(TOKEN_COOKIE);
107
- if (tokenCookie?.value) {
108
- headers['Authorization'] = `Bearer ${tokenCookie.value}`;
109
- }
110
-
111
- // Forward request body for non-GET requests
112
- let body: string | undefined;
113
- if (method !== 'GET' && method !== 'HEAD') {
114
- try {
115
- body = await request.text();
116
- } catch {
117
- // No body
118
- }
119
- }
120
-
121
- // Proxy the request to backend
122
- let backendResponse: Response;
123
- const abortController = new AbortController();
124
- const timeoutId = setTimeout(() => abortController.abort(), BACKEND_TIMEOUT_MS);
125
- try {
126
- backendResponse = await fetch(backendUrl.toString(), {
127
- method,
128
- headers,
129
- body,
130
- signal: abortController.signal,
131
- });
132
- } catch (error) {
133
- const isTimeout = (error as Error)?.name === 'AbortError';
134
- return NextResponse.json(
135
- { error: isTimeout ? 'Backend request timed out' : 'Backend service unavailable' },
136
- { status: isTimeout ? 504 : 502 }
137
- );
138
- } finally {
139
- clearTimeout(timeoutId);
140
- }
141
-
142
- // Read response body
143
- const responseText = await backendResponse.text();
144
-
145
- // For auth endpoints: intercept token, set cookie, strip token from response
146
- if (backendResponse.ok && method === 'POST' && isAuthEndpoint(pathSegments)) {
147
- try {
148
- const data = JSON.parse(responseText);
149
- if (data.token) {
150
- const token = data.token;
151
-
152
- // Strip token from client response
153
- const { token: _stripped, ...safeData } = data;
154
-
155
- const response = NextResponse.json(safeData, {
156
- status: backendResponse.status,
157
- });
158
- setAuthCookies(response, token);
159
- return response;
160
- }
161
- } catch {
162
- // Not JSON or no token field — pass through
163
- }
164
- }
165
-
166
- // Handle 401 responses: clear auth cookies
167
- if (backendResponse.status === 401 && tokenCookie?.value) {
168
- const response = new NextResponse(responseText, {
169
- status: backendResponse.status,
170
- headers: {
171
- 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
172
- },
173
- });
174
- clearAuthCookies(response);
175
- return response;
176
- }
177
-
178
- // Sanitize 5xx responses so backend internals don't leak to the client
179
- if (backendResponse.status >= 500) {
180
- console.error(`[proxy] backend ${backendResponse.status} on ${pathSegments}:`, responseText);
181
- return NextResponse.json(
182
- { error: 'Backend service error' },
183
- { status: backendResponse.status }
184
- );
185
- }
186
-
187
- // Pass through response as-is
188
- return new NextResponse(responseText, {
189
- status: backendResponse.status,
190
- headers: {
191
- 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
192
- },
193
- });
194
- }
195
-
196
- export async function GET(
197
- request: NextRequest,
198
- { params }: { params: Promise<{ path: string[] }> }
199
- ) {
200
- return proxyRequest(request, await params);
201
- }
202
-
203
- export async function POST(
204
- request: NextRequest,
205
- { params }: { params: Promise<{ path: string[] }> }
206
- ) {
207
- return proxyRequest(request, await params);
208
- }
209
-
210
- export async function PUT(
211
- request: NextRequest,
212
- { params }: { params: Promise<{ path: string[] }> }
213
- ) {
214
- return proxyRequest(request, await params);
215
- }
216
-
217
- export async function PATCH(
218
- request: NextRequest,
219
- { params }: { params: Promise<{ path: string[] }> }
220
- ) {
221
- return proxyRequest(request, await params);
222
- }
223
-
224
- export async function DELETE(
225
- request: NextRequest,
226
- { params }: { params: Promise<{ path: string[] }> }
227
- ) {
228
- return proxyRequest(request, await params);
229
- }
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
89
+ const headers: Record<string, string> = {
90
+ 'Content-Type': 'application/json',
91
+ };
92
+
93
+ // Send the proxy's own origin (not the client-supplied Origin header).
94
+ // The backend's BrowserOriginGuard only checks for presence of Origin/Referer,
95
+ // so forwarding a client-controlled value adds spoofing surface for nothing.
96
+ headers['Origin'] = request.nextUrl.origin;
97
+
98
+ // Forward SDK version header if present
99
+ const sdkVersion = request.headers.get('x-sdk-version');
100
+ if (sdkVersion) {
101
+ headers['X-SDK-Version'] = sdkVersion;
102
+ }
103
+
104
+ // Forward Accept-Language so the backend locale middleware can resolve translations
105
+ const acceptLanguage = request.headers.get('accept-language');
106
+ if (acceptLanguage) {
107
+ headers['Accept-Language'] = acceptLanguage;
108
+ }
109
+
110
+ // Add auth token from httpOnly cookie
111
+ const cookieStore = await cookies();
112
+ const tokenCookie = cookieStore.get(TOKEN_COOKIE);
113
+ if (tokenCookie?.value) {
114
+ headers['Authorization'] = `Bearer ${tokenCookie.value}`;
115
+ }
116
+
117
+ // Forward request body for non-GET requests
118
+ let body: string | undefined;
119
+ if (method !== 'GET' && method !== 'HEAD') {
120
+ try {
121
+ body = await request.text();
122
+ } catch {
123
+ // No body
124
+ }
125
+ }
126
+
127
+ // Proxy the request to backend
128
+ let backendResponse: Response;
129
+ const abortController = new AbortController();
130
+ const timeoutId = setTimeout(() => abortController.abort(), BACKEND_TIMEOUT_MS);
131
+ try {
132
+ backendResponse = await fetch(backendUrl.toString(), {
133
+ method,
134
+ headers,
135
+ body,
136
+ signal: abortController.signal,
137
+ });
138
+ } catch (error) {
139
+ const isTimeout = (error as Error)?.name === 'AbortError';
140
+ return NextResponse.json(
141
+ { error: isTimeout ? 'Backend request timed out' : 'Backend service unavailable' },
142
+ { status: isTimeout ? 504 : 502 }
143
+ );
144
+ } finally {
145
+ clearTimeout(timeoutId);
146
+ }
147
+
148
+ // Read response body
149
+ const responseText = await backendResponse.text();
150
+
151
+ // For auth endpoints: intercept token, set cookie, strip token from response
152
+ if (backendResponse.ok && method === 'POST' && isAuthEndpoint(pathSegments)) {
153
+ try {
154
+ const data = JSON.parse(responseText);
155
+ if (data.token) {
156
+ const token = data.token;
157
+
158
+ // Strip token from client response
159
+ const { token: _stripped, ...safeData } = data;
160
+
161
+ const response = NextResponse.json(safeData, {
162
+ status: backendResponse.status,
163
+ });
164
+ setAuthCookies(response, token);
165
+ return response;
166
+ }
167
+ } catch {
168
+ // Not JSON or no token field — pass through
169
+ }
170
+ }
171
+
172
+ // Handle 401 responses: clear auth cookies
173
+ if (backendResponse.status === 401 && tokenCookie?.value) {
174
+ const response = new NextResponse(responseText, {
175
+ status: backendResponse.status,
176
+ headers: {
177
+ 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
178
+ },
179
+ });
180
+ clearAuthCookies(response);
181
+ return response;
182
+ }
183
+
184
+ // Sanitize 5xx responses so backend internals don't leak to the client
185
+ if (backendResponse.status >= 500) {
186
+ console.error(`[proxy] backend ${backendResponse.status} on ${pathSegments}:`, responseText);
187
+ return NextResponse.json(
188
+ { error: 'Backend service error' },
189
+ { status: backendResponse.status }
190
+ );
191
+ }
192
+
193
+ // Pass through response as-is
194
+ return new NextResponse(responseText, {
195
+ status: backendResponse.status,
196
+ headers: {
197
+ 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json',
198
+ },
199
+ });
200
+ }
201
+
202
+ export async function GET(
203
+ request: NextRequest,
204
+ { params }: { params: Promise<{ path: string[] }> }
205
+ ) {
206
+ return proxyRequest(request, await params);
207
+ }
208
+
209
+ export async function POST(
210
+ request: NextRequest,
211
+ { params }: { params: Promise<{ path: string[] }> }
212
+ ) {
213
+ return proxyRequest(request, await params);
214
+ }
215
+
216
+ export async function PUT(
217
+ request: NextRequest,
218
+ { params }: { params: Promise<{ path: string[] }> }
219
+ ) {
220
+ return proxyRequest(request, await params);
221
+ }
222
+
223
+ export async function PATCH(
224
+ request: NextRequest,
225
+ { params }: { params: Promise<{ path: string[] }> }
226
+ ) {
227
+ return proxyRequest(request, await params);
228
+ }
229
+
230
+ export async function DELETE(
231
+ request: NextRequest,
232
+ { params }: { params: Promise<{ path: string[] }> }
233
+ ) {
234
+ return proxyRequest(request, await params);
235
+ }