@ecomweb/storefront-kit 0.2.0
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/LICENSE +21 -0
- package/README.md +55 -0
- package/dist/api/client.js +162 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/index.js +7 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/proxy.js +145 -0
- package/dist/api/proxy.js.map +1 -0
- package/dist/api/response.js +55 -0
- package/dist/api/response.js.map +1 -0
- package/dist/api/server-client.js +159 -0
- package/dist/api/server-client.js.map +1 -0
- package/dist/auth/client-ip.js +44 -0
- package/dist/auth/client-ip.js.map +1 -0
- package/dist/auth/context.js +125 -0
- package/dist/auth/context.js.map +1 -0
- package/dist/auth/cookies.js +97 -0
- package/dist/auth/cookies.js.map +1 -0
- package/dist/auth/error-copy.js +49 -0
- package/dist/auth/error-copy.js.map +1 -0
- package/dist/auth/password-policy.js +29 -0
- package/dist/auth/password-policy.js.map +1 -0
- package/dist/auth/route-handlers.js +337 -0
- package/dist/auth/route-handlers.js.map +1 -0
- package/dist/auth/safe-redirect.js +20 -0
- package/dist/auth/safe-redirect.js.map +1 -0
- package/dist/auth/sdk.js +76 -0
- package/dist/auth/sdk.js.map +1 -0
- package/dist/auth/session-refresh.js +81 -0
- package/dist/auth/session-refresh.js.map +1 -0
- package/dist/auth/session.js +26 -0
- package/dist/auth/session.js.map +1 -0
- package/dist/auth/use-public-auth-config.js +29 -0
- package/dist/auth/use-public-auth-config.js.map +1 -0
- package/dist/cart/api.js +60 -0
- package/dist/cart/api.js.map +1 -0
- package/dist/cart/server-context.js +279 -0
- package/dist/cart/server-context.js.map +1 -0
- package/dist/cart/types.js +1 -0
- package/dist/cart/types.js.map +1 -0
- package/dist/cart/utils.js +49 -0
- package/dist/cart/utils.js.map +1 -0
- package/dist/checkout/get-payment-state.js +15 -0
- package/dist/checkout/get-payment-state.js.map +1 -0
- package/dist/checkout/initiate-gateway-payment.js +13 -0
- package/dist/checkout/initiate-gateway-payment.js.map +1 -0
- package/dist/checkout/order-handoff.js +61 -0
- package/dist/checkout/order-handoff.js.map +1 -0
- package/dist/checkout/payment-redirect.js +11 -0
- package/dist/checkout/payment-redirect.js.map +1 -0
- package/dist/checkout/payment-state-poll.js +45 -0
- package/dist/checkout/payment-state-poll.js.map +1 -0
- package/dist/checkout/start-gateway-redirect.js +16 -0
- package/dist/checkout/start-gateway-redirect.js.map +1 -0
- package/dist/checkout/stock-issues.js +35 -0
- package/dist/checkout/stock-issues.js.map +1 -0
- package/dist/checkout/success-state.js +15 -0
- package/dist/checkout/success-state.js.map +1 -0
- package/dist/checkout/types.js +1 -0
- package/dist/checkout/types.js.map +1 -0
- package/dist/checkout/use-checkout.js +256 -0
- package/dist/checkout/use-checkout.js.map +1 -0
- package/dist/checkout/utils.js +7 -0
- package/dist/checkout/utils.js.map +1 -0
- package/dist/config/index.js +7 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/log-level.js +8 -0
- package/dist/config/log-level.js.map +1 -0
- package/dist/config/mode.js +18 -0
- package/dist/config/mode.js.map +1 -0
- package/dist/config/public.js +115 -0
- package/dist/config/public.js.map +1 -0
- package/dist/config/schema.js +70 -0
- package/dist/config/schema.js.map +1 -0
- package/dist/config/server.js +68 -0
- package/dist/config/server.js.map +1 -0
- package/dist/config.d.ts +16 -0
- package/dist/config.js +15 -0
- package/dist/config.js.map +1 -0
- package/dist/currency.js +68 -0
- package/dist/currency.js.map +1 -0
- package/dist/index.d.ts +968 -0
- package/dist/index.js +146 -0
- package/dist/index.js.map +1 -0
- package/dist/interfaces/api.types.js +1 -0
- package/dist/interfaces/api.types.js.map +1 -0
- package/dist/interfaces/index.js +2 -0
- package/dist/interfaces/index.js.map +1 -0
- package/dist/logging.js +42 -0
- package/dist/logging.js.map +1 -0
- package/dist/middleware/create-storefront-middleware.js +175 -0
- package/dist/middleware/create-storefront-middleware.js.map +1 -0
- package/dist/middleware.d.ts +24 -0
- package/dist/middleware.js +9 -0
- package/dist/middleware.js.map +1 -0
- package/dist/mode-1ZKDELPZ.d.ts +16 -0
- package/dist/notices.js +31 -0
- package/dist/notices.js.map +1 -0
- package/dist/orders/api-client.js +32 -0
- package/dist/orders/api-client.js.map +1 -0
- package/dist/orders/derive-progress.js +36 -0
- package/dist/orders/derive-progress.js.map +1 -0
- package/dist/orders/index.js +6 -0
- package/dist/orders/index.js.map +1 -0
- package/dist/orders/types.js +13 -0
- package/dist/orders/types.js.map +1 -0
- package/dist/orders/use-order-status.js +137 -0
- package/dist/orders/use-order-status.js.map +1 -0
- package/dist/promotions/use-promotion-validation.js +106 -0
- package/dist/promotions/use-promotion-validation.js.map +1 -0
- package/dist/promotions/utils.js +40 -0
- package/dist/promotions/utils.js.map +1 -0
- package/dist/provider.js +25 -0
- package/dist/provider.js.map +1 -0
- package/dist/redirects/index.js +2 -0
- package/dist/redirects/index.js.map +1 -0
- package/dist/redirects/lookup-redirect.js +13 -0
- package/dist/redirects/lookup-redirect.js.map +1 -0
- package/dist/request/public-url.js +20 -0
- package/dist/request/public-url.js.map +1 -0
- package/dist/schema-CEMKsCwh.d.ts +52 -0
- package/dist/sdk.js +33 -0
- package/dist/sdk.js.map +1 -0
- package/dist/server/routes.js +56 -0
- package/dist/server/routes.js.map +1 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +19 -0
- package/dist/server.js.map +1 -0
- package/dist/shipping/format-shipping-option.js +12 -0
- package/dist/shipping/format-shipping-option.js.map +1 -0
- package/dist/shipping/location-areas.js +104 -0
- package/dist/shipping/location-areas.js.map +1 -0
- package/dist/shipping/messages.js +19 -0
- package/dist/shipping/messages.js.map +1 -0
- package/dist/shipping/shipping-calculation-reducer.js +75 -0
- package/dist/shipping/shipping-calculation-reducer.js.map +1 -0
- package/dist/shipping/use-shipping-calculation.js +84 -0
- package/dist/shipping/use-shipping-calculation.js.map +1 -0
- package/dist/shipping/utils.js +18 -0
- package/dist/shipping/utils.js.map +1 -0
- package/dist/storage.js +116 -0
- package/dist/storage.js.map +1 -0
- package/dist/store/store-context.js +72 -0
- package/dist/store/store-context.js.map +1 -0
- package/dist/store-scope/index.js +33 -0
- package/dist/store-scope/index.js.map +1 -0
- package/dist/store-scope/root.js +15 -0
- package/dist/store-scope/root.js.map +1 -0
- package/dist/store-scope/store-url.js +45 -0
- package/dist/store-scope/store-url.js.map +1 -0
- package/dist/stores/basic-settings.js +67 -0
- package/dist/stores/basic-settings.js.map +1 -0
- package/dist/stores/cached.js +20 -0
- package/dist/stores/cached.js.map +1 -0
- package/dist/stores/get-store-by-host.js +38 -0
- package/dist/stores/get-store-by-host.js.map +1 -0
- package/dist/stores/index.js +7 -0
- package/dist/stores/index.js.map +1 -0
- package/dist/stores/metadata.js +19 -0
- package/dist/stores/metadata.js.map +1 -0
- package/dist/stores/store-path.js +9 -0
- package/dist/stores/store-path.js.map +1 -0
- package/dist/stores/store-suspension.js +14 -0
- package/dist/stores/store-suspension.js.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { NextResponse } from "next/server";
|
|
2
|
+
import { createAuthApi } from "./sdk.js";
|
|
3
|
+
import { clientIpFrom } from "./client-ip.js";
|
|
4
|
+
import { safeRedirectPath } from "./safe-redirect.js";
|
|
5
|
+
import { publicNextUrl } from "../request/public-url.js";
|
|
6
|
+
import {
|
|
7
|
+
authCookiePath,
|
|
8
|
+
clearAuthCookies,
|
|
9
|
+
clearOAuthNonceCookie,
|
|
10
|
+
isHostMappedRequest,
|
|
11
|
+
oauthNonceCookieName,
|
|
12
|
+
readAuthCookies,
|
|
13
|
+
writeAuthCookies,
|
|
14
|
+
storeBasePathFor,
|
|
15
|
+
writeOAuthNonceCookie
|
|
16
|
+
} from "./cookies.js";
|
|
17
|
+
function fail(status, message, code) {
|
|
18
|
+
return NextResponse.json(
|
|
19
|
+
{ error: { message, code } },
|
|
20
|
+
{ status: status || 500 }
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
const AUTH_ACTION_METHOD = {
|
|
24
|
+
config: "GET",
|
|
25
|
+
session: "GET",
|
|
26
|
+
"google/url": "GET",
|
|
27
|
+
"google/complete": "GET",
|
|
28
|
+
register: "POST",
|
|
29
|
+
login: "POST",
|
|
30
|
+
"otp/request": "POST",
|
|
31
|
+
"otp/verify": "POST",
|
|
32
|
+
anonymous: "POST",
|
|
33
|
+
logout: "POST",
|
|
34
|
+
"logout-all": "POST",
|
|
35
|
+
"verify-email": "POST",
|
|
36
|
+
"resend-verification": "POST",
|
|
37
|
+
"forgot-password": "POST",
|
|
38
|
+
"reset-password": "POST",
|
|
39
|
+
"change-password": "POST",
|
|
40
|
+
"change-email": "POST",
|
|
41
|
+
"change-email/confirm": "POST"
|
|
42
|
+
};
|
|
43
|
+
const OAUTH_NONCE_PARAM = "sf_oauth";
|
|
44
|
+
const OAUTH_NEXT_PARAM = "next";
|
|
45
|
+
function withSession(storeRef, cookiePath, result, body = {}) {
|
|
46
|
+
const response = NextResponse.json({ identity: result.identity, ...body });
|
|
47
|
+
if (result.access_token && result.refresh_token) {
|
|
48
|
+
writeAuthCookies(
|
|
49
|
+
response,
|
|
50
|
+
storeRef,
|
|
51
|
+
{
|
|
52
|
+
access_token: result.access_token,
|
|
53
|
+
refresh_token: result.refresh_token
|
|
54
|
+
},
|
|
55
|
+
cookiePath
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return response;
|
|
59
|
+
}
|
|
60
|
+
function methodNotAllowed(allowed) {
|
|
61
|
+
return NextResponse.json(
|
|
62
|
+
{
|
|
63
|
+
error: {
|
|
64
|
+
message: `This action requires ${allowed}`,
|
|
65
|
+
code: "METHOD_NOT_ALLOWED"
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
{ status: 405, headers: { allow: allowed } }
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
async function handleAuthRoute(request, storeRef, segments) {
|
|
72
|
+
const action = segments.join("/");
|
|
73
|
+
const allowedMethod = AUTH_ACTION_METHOD[action];
|
|
74
|
+
if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);
|
|
75
|
+
if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);
|
|
76
|
+
const auth = createAuthApi(storeRef, clientIpFrom(request.headers));
|
|
77
|
+
const hostMapped = isHostMappedRequest(request);
|
|
78
|
+
const tokens = readAuthCookies(request.cookies, storeRef);
|
|
79
|
+
const cookiePath = authCookiePath(storeRef, hostMapped);
|
|
80
|
+
const body = request.method === "POST" ? await request.json().catch(() => ({})) : {};
|
|
81
|
+
switch (action) {
|
|
82
|
+
case "config": {
|
|
83
|
+
const res = await auth.getAuthConfig();
|
|
84
|
+
if (!res.success)
|
|
85
|
+
return fail(
|
|
86
|
+
res.error.statusCode,
|
|
87
|
+
res.error.message,
|
|
88
|
+
res.error.error
|
|
89
|
+
);
|
|
90
|
+
return NextResponse.json(res.data);
|
|
91
|
+
}
|
|
92
|
+
case "register": {
|
|
93
|
+
const payload = { ...body };
|
|
94
|
+
delete payload.anonymous_identity_id;
|
|
95
|
+
let anonymousIdentityId;
|
|
96
|
+
if (tokens) {
|
|
97
|
+
const current = await auth.me(tokens.access_token);
|
|
98
|
+
if (current.success && current.data?.is_anonymous) {
|
|
99
|
+
anonymousIdentityId = current.data.id;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const res = await auth.register({
|
|
103
|
+
...payload,
|
|
104
|
+
anonymous_identity_id: anonymousIdentityId
|
|
105
|
+
});
|
|
106
|
+
if (!res.success)
|
|
107
|
+
return fail(
|
|
108
|
+
res.error.statusCode,
|
|
109
|
+
res.error.message,
|
|
110
|
+
res.error.error
|
|
111
|
+
);
|
|
112
|
+
return NextResponse.json({ registered: true });
|
|
113
|
+
}
|
|
114
|
+
case "login": {
|
|
115
|
+
const res = await auth.login(body);
|
|
116
|
+
if (!res.success)
|
|
117
|
+
return fail(
|
|
118
|
+
res.error.statusCode,
|
|
119
|
+
res.error.message,
|
|
120
|
+
res.error.error
|
|
121
|
+
);
|
|
122
|
+
return withSession(storeRef, cookiePath, res.data);
|
|
123
|
+
}
|
|
124
|
+
case "otp/request": {
|
|
125
|
+
const res = await auth.requestOtp(body.email);
|
|
126
|
+
if (!res.success)
|
|
127
|
+
return fail(
|
|
128
|
+
res.error.statusCode,
|
|
129
|
+
res.error.message,
|
|
130
|
+
res.error.error
|
|
131
|
+
);
|
|
132
|
+
return NextResponse.json({ sent: true });
|
|
133
|
+
}
|
|
134
|
+
case "otp/verify": {
|
|
135
|
+
const res = await auth.verifyOtp(body);
|
|
136
|
+
if (!res.success)
|
|
137
|
+
return fail(
|
|
138
|
+
res.error.statusCode,
|
|
139
|
+
res.error.message,
|
|
140
|
+
res.error.error
|
|
141
|
+
);
|
|
142
|
+
return withSession(storeRef, cookiePath, res.data);
|
|
143
|
+
}
|
|
144
|
+
case "anonymous": {
|
|
145
|
+
const res = await auth.anonymous();
|
|
146
|
+
if (!res.success)
|
|
147
|
+
return fail(
|
|
148
|
+
res.error.statusCode,
|
|
149
|
+
res.error.message,
|
|
150
|
+
res.error.error
|
|
151
|
+
);
|
|
152
|
+
return withSession(storeRef, cookiePath, res.data);
|
|
153
|
+
}
|
|
154
|
+
case "session": {
|
|
155
|
+
if (!tokens) return NextResponse.json({ identity: null });
|
|
156
|
+
const res = await auth.me(tokens.access_token);
|
|
157
|
+
if (!res.success) return NextResponse.json({ identity: null });
|
|
158
|
+
return NextResponse.json({ identity: res.data });
|
|
159
|
+
}
|
|
160
|
+
case "logout": {
|
|
161
|
+
if (tokens) {
|
|
162
|
+
await auth.logout(tokens.access_token, tokens.refresh_token).catch(() => void 0);
|
|
163
|
+
}
|
|
164
|
+
const response = NextResponse.json({ ok: true });
|
|
165
|
+
clearAuthCookies(response, storeRef, cookiePath);
|
|
166
|
+
return response;
|
|
167
|
+
}
|
|
168
|
+
case "logout-all": {
|
|
169
|
+
if (!tokens) return fail(401, "No session");
|
|
170
|
+
const res = await auth.logoutAll(tokens.access_token);
|
|
171
|
+
if (!res.success)
|
|
172
|
+
return fail(
|
|
173
|
+
res.error.statusCode,
|
|
174
|
+
res.error.message,
|
|
175
|
+
res.error.error
|
|
176
|
+
);
|
|
177
|
+
const response = NextResponse.json({ ok: true });
|
|
178
|
+
clearAuthCookies(response, storeRef, cookiePath);
|
|
179
|
+
return response;
|
|
180
|
+
}
|
|
181
|
+
case "verify-email": {
|
|
182
|
+
const res = await auth.verifyEmail(body.token);
|
|
183
|
+
if (!res.success)
|
|
184
|
+
return fail(
|
|
185
|
+
res.error.statusCode,
|
|
186
|
+
res.error.message,
|
|
187
|
+
res.error.error
|
|
188
|
+
);
|
|
189
|
+
return NextResponse.json(res.data);
|
|
190
|
+
}
|
|
191
|
+
case "resend-verification": {
|
|
192
|
+
const res = await auth.resendVerification(body.email);
|
|
193
|
+
if (!res.success)
|
|
194
|
+
return fail(
|
|
195
|
+
res.error.statusCode,
|
|
196
|
+
res.error.message,
|
|
197
|
+
res.error.error
|
|
198
|
+
);
|
|
199
|
+
return NextResponse.json({ sent: true });
|
|
200
|
+
}
|
|
201
|
+
case "forgot-password": {
|
|
202
|
+
const res = await auth.forgotPassword(body.email);
|
|
203
|
+
if (!res.success)
|
|
204
|
+
return fail(
|
|
205
|
+
res.error.statusCode,
|
|
206
|
+
res.error.message,
|
|
207
|
+
res.error.error
|
|
208
|
+
);
|
|
209
|
+
return NextResponse.json({ sent: true });
|
|
210
|
+
}
|
|
211
|
+
case "reset-password": {
|
|
212
|
+
const res = await auth.resetPassword(body);
|
|
213
|
+
if (!res.success)
|
|
214
|
+
return fail(
|
|
215
|
+
res.error.statusCode,
|
|
216
|
+
res.error.message,
|
|
217
|
+
res.error.error
|
|
218
|
+
);
|
|
219
|
+
return NextResponse.json(res.data);
|
|
220
|
+
}
|
|
221
|
+
case "change-password": {
|
|
222
|
+
if (!tokens) return fail(401, "No session");
|
|
223
|
+
const res = await auth.changePassword(
|
|
224
|
+
tokens.access_token,
|
|
225
|
+
body
|
|
226
|
+
);
|
|
227
|
+
if (!res.success)
|
|
228
|
+
return fail(
|
|
229
|
+
res.error.statusCode,
|
|
230
|
+
res.error.message,
|
|
231
|
+
res.error.error
|
|
232
|
+
);
|
|
233
|
+
const response = NextResponse.json({ ok: true });
|
|
234
|
+
clearAuthCookies(response, storeRef, cookiePath);
|
|
235
|
+
return response;
|
|
236
|
+
}
|
|
237
|
+
case "change-email": {
|
|
238
|
+
if (!tokens) return fail(401, "No session");
|
|
239
|
+
const res = await auth.changeEmail(
|
|
240
|
+
tokens.access_token,
|
|
241
|
+
body
|
|
242
|
+
);
|
|
243
|
+
if (!res.success)
|
|
244
|
+
return fail(
|
|
245
|
+
res.error.statusCode,
|
|
246
|
+
res.error.message,
|
|
247
|
+
res.error.error
|
|
248
|
+
);
|
|
249
|
+
return NextResponse.json({ sent: true });
|
|
250
|
+
}
|
|
251
|
+
case "change-email/confirm": {
|
|
252
|
+
const res = await auth.confirmEmailChange(body.token);
|
|
253
|
+
if (!res.success)
|
|
254
|
+
return fail(
|
|
255
|
+
res.error.statusCode,
|
|
256
|
+
res.error.message,
|
|
257
|
+
res.error.error
|
|
258
|
+
);
|
|
259
|
+
return NextResponse.json(res.data);
|
|
260
|
+
}
|
|
261
|
+
case "google/url": {
|
|
262
|
+
const base = storeBasePathFor(request, storeRef);
|
|
263
|
+
const wanted = safeRedirectPath(
|
|
264
|
+
request.nextUrl.searchParams.get("redirect_to"),
|
|
265
|
+
publicNextUrl(request).toString()
|
|
266
|
+
);
|
|
267
|
+
const nonce = globalThis.crypto.randomUUID();
|
|
268
|
+
const carrier = new URLSearchParams({
|
|
269
|
+
[OAUTH_NONCE_PARAM]: nonce,
|
|
270
|
+
[OAUTH_NEXT_PARAM]: wanted
|
|
271
|
+
});
|
|
272
|
+
const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);
|
|
273
|
+
if (!res.success)
|
|
274
|
+
return fail(
|
|
275
|
+
res.error.statusCode,
|
|
276
|
+
res.error.message,
|
|
277
|
+
res.error.error
|
|
278
|
+
);
|
|
279
|
+
const response = NextResponse.json(res.data);
|
|
280
|
+
writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);
|
|
281
|
+
return response;
|
|
282
|
+
}
|
|
283
|
+
case "google/complete": {
|
|
284
|
+
const base = storeBasePathFor(request, storeRef);
|
|
285
|
+
const errorTarget = new URL(
|
|
286
|
+
`${base}/auth/error?error=oauth_failed`,
|
|
287
|
+
publicNextUrl(request).toString()
|
|
288
|
+
);
|
|
289
|
+
const code = request.nextUrl.searchParams.get("code");
|
|
290
|
+
const carrier = safeRedirectPath(
|
|
291
|
+
request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),
|
|
292
|
+
publicNextUrl(request).toString()
|
|
293
|
+
);
|
|
294
|
+
const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;
|
|
295
|
+
const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);
|
|
296
|
+
const expectedNonce = request.cookies.get(
|
|
297
|
+
oauthNonceCookieName(storeRef)
|
|
298
|
+
)?.value;
|
|
299
|
+
const nonceMatches = !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;
|
|
300
|
+
if (!code || !nonceMatches) {
|
|
301
|
+
const response2 = NextResponse.redirect(errorTarget);
|
|
302
|
+
clearOAuthNonceCookie(response2, storeRef, cookiePath);
|
|
303
|
+
return response2;
|
|
304
|
+
}
|
|
305
|
+
const res = await auth.exchangeGoogleCode(code);
|
|
306
|
+
if (!res.success || !res.data?.access_token || !res.data.refresh_token) {
|
|
307
|
+
const response2 = NextResponse.redirect(errorTarget);
|
|
308
|
+
clearOAuthNonceCookie(response2, storeRef, cookiePath);
|
|
309
|
+
return response2;
|
|
310
|
+
}
|
|
311
|
+
const target = safeRedirectPath(
|
|
312
|
+
carrierParams.get(OAUTH_NEXT_PARAM),
|
|
313
|
+
publicNextUrl(request).toString()
|
|
314
|
+
);
|
|
315
|
+
const response = NextResponse.redirect(
|
|
316
|
+
new URL(target === "/" ? `${base}/` : target, publicNextUrl(request).toString())
|
|
317
|
+
);
|
|
318
|
+
writeAuthCookies(
|
|
319
|
+
response,
|
|
320
|
+
storeRef,
|
|
321
|
+
{
|
|
322
|
+
access_token: res.data.access_token,
|
|
323
|
+
refresh_token: res.data.refresh_token
|
|
324
|
+
},
|
|
325
|
+
cookiePath
|
|
326
|
+
);
|
|
327
|
+
clearOAuthNonceCookie(response, storeRef, cookiePath);
|
|
328
|
+
return response;
|
|
329
|
+
}
|
|
330
|
+
default:
|
|
331
|
+
return fail(404, `Unknown auth action: ${action}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
export {
|
|
335
|
+
handleAuthRoute
|
|
336
|
+
};
|
|
337
|
+
//# sourceMappingURL=route-handlers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/route-handlers.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { createAuthApi } from \"./sdk\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { safeRedirectPath } from \"./safe-redirect\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n authCookiePath,\n clearAuthCookies,\n clearOAuthNonceCookie,\n isHostMappedRequest,\n oauthNonceCookieName,\n readAuthCookies,\n writeAuthCookies,\n storeBasePathFor,\n writeOAuthNonceCookie,\n} from \"./cookies\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangePasswordPayload,\n LoginPayload,\n RegisterPayload,\n ResetPasswordPayload,\n VerifyOtpPayload,\n} from \"@ecomweb/sdk\";\n\n/** Translates the SDK's ApiResponse into a JSON response, preserving the code. */\nfunction fail(status: number, message: string, code?: string) {\n return NextResponse.json(\n { error: { message, code } },\n { status: status || 500 }\n );\n}\n\n/**\n * The HTTP method each action answers on — one entry per action, no defaults.\n *\n * Every one of these used to answer GET as well as POST, and the session\n * cookies are `sameSite: \"lax\"`, which the browser DOES send on a cross-site\n * top-level navigation. A link on any page therefore reached `logout-all`, or\n * `google/complete` with a code of the attacker's choosing. The split is\n * enumerated rather than inferred so that adding an action forces a decision\n * here; an action missing from this map is a 404, not a silent GET.\n *\n * GET is limited to the two reads the client polls (`config`, `session`) and\n * the two halves of the OAuth hand-off: `google/url` is a read, and\n * `google/complete` is the browser's landing spot in a redirect chain, so it\n * cannot be anything else. It carries its own browser binding instead — see\n * the nonce cookie below.\n */\nconst AUTH_ACTION_METHOD = {\n config: \"GET\",\n session: \"GET\",\n \"google/url\": \"GET\",\n \"google/complete\": \"GET\",\n\n register: \"POST\",\n login: \"POST\",\n \"otp/request\": \"POST\",\n \"otp/verify\": \"POST\",\n anonymous: \"POST\",\n logout: \"POST\",\n \"logout-all\": \"POST\",\n \"verify-email\": \"POST\",\n \"resend-verification\": \"POST\",\n \"forgot-password\": \"POST\",\n \"reset-password\": \"POST\",\n \"change-password\": \"POST\",\n \"change-email\": \"POST\",\n \"change-email/confirm\": \"POST\",\n} as const satisfies Record<string, \"GET\" | \"POST\">;\n\ntype AuthAction = keyof typeof AUTH_ACTION_METHOD;\n\n/**\n * The query parameter carrying the OAuth nonce home.\n *\n * `redirect_to` is the only field that survives the round trip through the\n * signed `state` and back out as `next=`, and the backend requires it to be a\n * relative path, so the nonce travels inside it as a query parameter of a\n * path-only URL. The storefront is both the producer and the only consumer of\n * this shape.\n */\nconst OAUTH_NONCE_PARAM = \"sf_oauth\";\nconst OAUTH_NEXT_PARAM = \"next\";\n\n/** Tokens go into cookies and never into the response body. */\nfunction withSession(\n storeRef: string,\n cookiePath: string,\n result: AuthResult,\n body: Record<string, unknown> = {}\n) {\n const response = NextResponse.json({ identity: result.identity, ...body });\n\n if (result.access_token && result.refresh_token) {\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n },\n cookiePath\n );\n }\n\n return response;\n}\n\nfunction methodNotAllowed(allowed: \"GET\" | \"POST\") {\n return NextResponse.json(\n {\n error: {\n message: `This action requires ${allowed}`,\n code: \"METHOD_NOT_ALLOWED\",\n },\n },\n { status: 405, headers: { allow: allowed } }\n );\n}\n\nexport async function handleAuthRoute(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const action = segments.join(\"/\");\n const allowedMethod = AUTH_ACTION_METHOD[action as AuthAction];\n\n if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);\n if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);\n\n // The shopper's address, not this server's: the backend rate-limits per\n // `storeId:clientIp` and every one of these calls is made server-side.\n const auth = createAuthApi(storeRef, clientIpFrom(request.headers));\n const hostMapped = isHostMappedRequest(request);\n const tokens = readAuthCookies(request.cookies, storeRef);\n const cookiePath = authCookiePath(storeRef, hostMapped);\n\n const body: Record<string, any> =\n request.method === \"POST\" ? await request.json().catch(() => ({})) : {};\n\n switch (action) {\n case \"config\": {\n const res = await auth.getAuthConfig();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"register\": {\n // Never trust a browser-supplied `anonymous_identity_id`: the backend\n // only checks store_id / is_anonymous / !deleted_at, not ownership, so\n // forwarding it would let anyone who learns an anonymous UUID register\n // against it and inherit its cart and orders. Whatever the browser sent\n // is dropped and the id is derived from the httpOnly session instead.\n const payload: Record<string, any> = { ...body };\n delete payload.anonymous_identity_id;\n\n let anonymousIdentityId: string | undefined;\n\n if (tokens) {\n const current = await auth.me(tokens.access_token);\n if (current.success && current.data?.is_anonymous) {\n anonymousIdentityId = current.data.id;\n }\n }\n\n const res = await auth.register({\n ...payload,\n anonymous_identity_id: anonymousIdentityId,\n } as RegisterPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Register never returns tokens, by design.\n return NextResponse.json({ registered: true });\n }\n\n case \"login\": {\n const res = await auth.login(body as LoginPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"otp/request\": {\n const res = await auth.requestOtp(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"otp/verify\": {\n const res = await auth.verifyOtp(body as VerifyOtpPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"anonymous\": {\n const res = await auth.anonymous();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"session\": {\n if (!tokens) return NextResponse.json({ identity: null });\n const res = await auth.me(tokens.access_token);\n if (!res.success) return NextResponse.json({ identity: null });\n return NextResponse.json({ identity: res.data });\n }\n\n case \"logout\": {\n // Best-effort revoke: a failed call must still clear the browser's\n // cookies, or the shopper is stuck logged in against a dead session.\n if (tokens) {\n await auth\n .logout(tokens.access_token, tokens.refresh_token)\n .catch(() => undefined);\n }\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"logout-all\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.logoutAll(tokens.access_token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"verify-email\": {\n const res = await auth.verifyEmail(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"resend-verification\": {\n const res = await auth.resendVerification(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"forgot-password\": {\n const res = await auth.forgotPassword(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"reset-password\": {\n const res = await auth.resetPassword(body as ResetPasswordPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"change-password\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changePassword(\n tokens.access_token,\n body as ChangePasswordPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Changing a password revokes sessions server-side; drop the cookies too.\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"change-email\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changeEmail(\n tokens.access_token,\n body as ChangeEmailPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"change-email/confirm\": {\n const res = await auth.confirmEmailChange(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"google/url\": {\n // Proxied rather than called from the browser so the storefront API key\n // stays server-side.\n const base = storeBasePathFor(request, storeRef);\n const wanted = safeRedirectPath(\n request.nextUrl.searchParams.get(\"redirect_to\"),\n publicNextUrl(request).toString()\n );\n\n // The nonce is minted here, remembered in an httpOnly cookie, and rides\n // out inside `redirect_to`. `google/complete` refuses to issue a session\n // unless the two match, which is what makes that GET unforgeable.\n // `globalThis.crypto` rather than a node:crypto import: this module is\n // bundled for whichever runtime the route runs in.\n const nonce = globalThis.crypto.randomUUID();\n const carrier = new URLSearchParams({\n [OAUTH_NONCE_PARAM]: nonce,\n [OAUTH_NEXT_PARAM]: wanted,\n });\n\n const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n\n const response = NextResponse.json(res.data);\n writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);\n return response;\n }\n\n case \"google/complete\": {\n // The backend redirects the BROWSER here with a one-time code. It is\n // redeemed server-side so no token ever reaches the URL bar, history,\n // or a Referer header.\n const base = storeBasePathFor(request, storeRef);\n const errorTarget = new URL(\n `${base}/auth/error?error=oauth_failed`,\n publicNextUrl(request).toString()\n );\n\n const code = request.nextUrl.searchParams.get(\"code\");\n\n // Whatever came back in `next` is the carrier this route wrote in\n // `google/url`: a relative path plus the nonce. Both halves are\n // re-validated — the path against the origin, the nonce against the\n // cookie — before anything is issued.\n const carrier = safeRedirectPath(\n request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;\n const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);\n const expectedNonce = request.cookies.get(\n oauthNonceCookieName(storeRef)\n )?.value;\n\n const nonceMatches =\n !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;\n\n if (!code || !nonceMatches) {\n // A missing or mismatched nonce means this browser did not start the\n // flow: someone else's one-time code is being pushed into it. Refuse\n // before any token is exchanged, and burn the nonce either way.\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const res = await auth.exchangeGoogleCode(code);\n\n if (!res.success || !res.data?.access_token || !res.data.refresh_token) {\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const target = safeRedirectPath(\n carrierParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const response = NextResponse.redirect(\n new URL(target === \"/\" ? `${base}/` : target, publicNextUrl(request).toString())\n );\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: res.data.access_token,\n refresh_token: res.data.refresh_token,\n },\n cookiePath\n );\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n\n return response;\n }\n\n default:\n // Unreachable: AUTH_ACTION_METHOD is checked first, and every key it\n // holds has a case above. Kept so adding a key without a case is a\n // 404 rather than an undefined response.\n return fail(404, `Unknown auth action: ${action}`);\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,KAAK,QAAgB,SAAiB,MAAe;AAC5D,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,KAAK,EAAE;AAAA,IAC3B,EAAE,QAAQ,UAAU,IAAI;AAAA,EAC1B;AACF;AAkBA,MAAM,qBAAqB;AAAA,EACzB,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,cAAc;AAAA,EACd,mBAAmB;AAAA,EAEnB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,eAAe;AAAA,EACf,cAAc;AAAA,EACd,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,uBAAuB;AAAA,EACvB,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,wBAAwB;AAC1B;AAaA,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AAGzB,SAAS,YACP,UACA,YACA,QACA,OAAgC,CAAC,GACjC;AACA,QAAM,WAAW,aAAa,KAAK,EAAE,UAAU,OAAO,UAAU,GAAG,KAAK,CAAC;AAEzE,MAAI,OAAO,gBAAgB,OAAO,eAAe;AAC/C;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,QACE,cAAc,OAAO;AAAA,QACrB,eAAe,OAAO;AAAA,MACxB;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,iBAAiB,SAAyB;AACjD,SA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
+
let origin;
|
|
6
|
+
try {
|
|
7
|
+
resolved = new URL(candidate, base);
|
|
8
|
+
origin = new URL(base).origin;
|
|
9
|
+
} catch {
|
|
10
|
+
return DEFAULT_REDIRECT;
|
|
11
|
+
}
|
|
12
|
+
if (resolved.origin !== origin) return DEFAULT_REDIRECT;
|
|
13
|
+
const path = `${resolved.pathname}${resolved.search}${resolved.hash}`;
|
|
14
|
+
return path.startsWith("/") ? path : DEFAULT_REDIRECT;
|
|
15
|
+
}
|
|
16
|
+
export {
|
|
17
|
+
DEFAULT_REDIRECT,
|
|
18
|
+
safeRedirectPath
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=safe-redirect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/safe-redirect.ts"],"sourcesContent":["/**\n * The one post-auth redirect guard.\n *\n * Both places a shopper can name where to go after signing in — the `?next=`\n * on `/login` and `/register` (`components/auth/auth-form.tsx`) and the `next=`\n * that survives the Google round trip (`lib/auth/route-handlers.ts`) — resolve\n * the candidate here. A second copy is exactly how the two drifted apart in the\n * first place, so there is deliberately only one.\n *\n * The rule is \"resolve, then compare origins\", not \"reject a list of prefixes\":\n *\n * - `//evil.com` and `/\\evil.com` both resolve to `https://evil.com/`, the\n * second because the WHATWG parser normalises `\\` to `/` for special\n * schemes exactly as browsers do. A `startsWith(\"//\")` check catches the\n * first and misses the second.\n * - `http:/evil.com` resolves to `http://evil.com/` — a scheme-carrying value\n * that starts with neither `//` nor `http://`.\n * - `javascript:alert(1)` parses with an opaque origin (`\"null\"`), which is\n * never equal to the page origin.\n *\n * Comparing the resolved origin covers all of them without enumerating any.\n */\n\n/** Where a rejected or missing candidate goes. Relative, so it stays inside\n * whichever store path or custom domain the caller is already on. */\nexport const DEFAULT_REDIRECT = \"/\";\n\n/**\n * A same-origin, relative path safe to hand to `router.push()` or\n * `NextResponse.redirect(new URL(path, request.url))`.\n *\n * @param candidate the shopper-supplied value (`?next=`), or null/undefined\n * @param base an absolute URL of the current page — `window.location.origin`\n * in the browser, `request.url` on the server\n */\nexport function safeRedirectPath(\n candidate: string | null | undefined,\n base: string\n): string {\n if (!candidate) return DEFAULT_REDIRECT;\n\n let resolved: URL;\n let origin: string;\n\n try {\n resolved = new URL(candidate, base);\n origin = new URL(base).origin;\n } catch {\n return DEFAULT_REDIRECT;\n }\n\n // An opaque origin (data:, javascript:, blob:) serialises to \"null\" and can\n // never match; a different host or scheme is off-origin by definition.\n if (resolved.origin !== origin) return DEFAULT_REDIRECT;\n\n const path = `${resolved.pathname}${resolved.search}${resolved.hash}`;\n\n // `URL` always produces a rooted pathname for a hierarchical URL, but a\n // non-special scheme sharing the origin would not — belt and braces.\n return path.startsWith(\"/\") ? path : DEFAULT_REDIRECT;\n}\n"],"mappings":"AAyBO,MAAM,mBAAmB;AAUzB,SAAS,iBACd,WACA,MACQ;AACR,MAAI,CAAC,UAAW,QAAO;AAEvB,MAAI;AACJ,MAAI;AAEJ,MAAI;AACF,eAAW,IAAI,IAAI,WAAW,IAAI;AAClC,aAAS,IAAI,IAAI,IAAI,EAAE;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AAIA,MAAI,SAAS,WAAW,OAAQ,QAAO;AAEvC,QAAM,OAAO,GAAG,SAAS,QAAQ,GAAG,SAAS,MAAM,GAAG,SAAS,IAAI;AAInE,SAAO,KAAK,WAAW,GAAG,IAAI,OAAO;AACvC;","names":[]}
|
package/dist/auth/sdk.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { AuthApi } from "@ecomweb/sdk";
|
|
3
|
+
import { forwardingHeaders } from "./client-ip.js";
|
|
4
|
+
import { publicConfig } from "../config.js";
|
|
5
|
+
import { serverConfig } from "../config/server.js";
|
|
6
|
+
function backendBaseUrl() {
|
|
7
|
+
return publicConfig().apiUrl;
|
|
8
|
+
}
|
|
9
|
+
function storefrontApiKey() {
|
|
10
|
+
return serverConfig().platformApiKey;
|
|
11
|
+
}
|
|
12
|
+
async function send(method, url, data, options, clientIp) {
|
|
13
|
+
try {
|
|
14
|
+
const response = await fetch(`${backendBaseUrl()}${url}`, {
|
|
15
|
+
method,
|
|
16
|
+
headers: {
|
|
17
|
+
"Content-Type": "application/json",
|
|
18
|
+
"x-storefront-api-key": storefrontApiKey(),
|
|
19
|
+
...options?.headers ?? {},
|
|
20
|
+
// The backend's auth throttler keys on the shopper IP, which it only
|
|
21
|
+
// reads from `x-forwarded-for` when the forwarder secret rides along.
|
|
22
|
+
// Without both, every shopper of a store shares one bucket, because
|
|
23
|
+
// the only client the backend ever sees is this server. Spread last
|
|
24
|
+
// so nothing an SDK call passes can replace the validated values.
|
|
25
|
+
...forwardingHeaders(clientIp)
|
|
26
|
+
},
|
|
27
|
+
body: data === void 0 ? void 0 : JSON.stringify(data),
|
|
28
|
+
signal: options?.signal,
|
|
29
|
+
cache: "no-store"
|
|
30
|
+
});
|
|
31
|
+
const body = await response.json().catch(() => null);
|
|
32
|
+
if (!response.ok) {
|
|
33
|
+
return {
|
|
34
|
+
success: false,
|
|
35
|
+
error: {
|
|
36
|
+
message: body?.message ?? response.statusText,
|
|
37
|
+
statusCode: response.status,
|
|
38
|
+
// BusinessException serialises as { code, message, details,
|
|
39
|
+
// timestamp } with no global exception filter rewriting the
|
|
40
|
+
// shape (verified against src/common/exceptions/business.exception.ts
|
|
41
|
+
// in the api repo), so the stable AUTH_* code lands in `code`.
|
|
42
|
+
// `error` is checked too in case a future filter renames it.
|
|
43
|
+
error: body?.code ?? body?.error
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return { success: true, data: body };
|
|
48
|
+
} catch (error) {
|
|
49
|
+
return {
|
|
50
|
+
success: false,
|
|
51
|
+
error: {
|
|
52
|
+
message: error instanceof Error ? error.message : "Network error",
|
|
53
|
+
statusCode: 0
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function authHttpClient(clientIp) {
|
|
59
|
+
return {
|
|
60
|
+
get: (url, options) => send("GET", url, void 0, options, clientIp),
|
|
61
|
+
post: (url, data, options) => send("POST", url, data, options, clientIp),
|
|
62
|
+
put: (url, data, options) => send("PUT", url, data, options, clientIp),
|
|
63
|
+
patch: (url, data, options) => send("PATCH", url, data, options, clientIp),
|
|
64
|
+
delete: (url, options) => send("DELETE", url, void 0, options, clientIp)
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function createAuthApi(storeRef, clientIp) {
|
|
68
|
+
return new AuthApi(authHttpClient(clientIp), storeRef);
|
|
69
|
+
}
|
|
70
|
+
export {
|
|
71
|
+
authHttpClient,
|
|
72
|
+
backendBaseUrl,
|
|
73
|
+
createAuthApi,
|
|
74
|
+
storefrontApiKey
|
|
75
|
+
};
|
|
76
|
+
//# sourceMappingURL=sdk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(clientIp?: string): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n */\nexport function createAuthApi(storeRef: string, clientIp?: string): AuthAp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AK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,QAAQ;AAAA,IAClD,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AAMO,SAAS,cAAc,UAAkB,UAA4B;AAC1E,SAAO,IAAI,QAAQ,eAAe,QAAQ,GAAG,QAAQ;AACvD;","names":[]}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import {
|
|
2
|
+
accessCookieName,
|
|
3
|
+
refreshCookieName,
|
|
4
|
+
HOST_MAPPED_HEADER
|
|
5
|
+
} from "./cookies.js";
|
|
6
|
+
import { forwardedForHeader } from "./client-ip.js";
|
|
7
|
+
import { publicConfig } from "../config/public.js";
|
|
8
|
+
import { serverConfig } from "../config/server.js";
|
|
9
|
+
const REFRESH_WINDOW_SECONDS = 120;
|
|
10
|
+
const REFRESH_FETCH_TIMEOUT_MS = 2500;
|
|
11
|
+
function expiresWithin(token, seconds) {
|
|
12
|
+
try {
|
|
13
|
+
const payload = JSON.parse(
|
|
14
|
+
Buffer.from(token.split(".")[1], "base64").toString("utf8")
|
|
15
|
+
);
|
|
16
|
+
if (typeof payload.exp !== "number") return false;
|
|
17
|
+
return payload.exp - Math.floor(Date.now() / 1e3) < seconds;
|
|
18
|
+
} catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
async function refreshIfNearExpiry(req, storeRef) {
|
|
23
|
+
const access = req.cookies.get(accessCookieName(storeRef))?.value;
|
|
24
|
+
const refresh = req.cookies.get(refreshCookieName(storeRef))?.value;
|
|
25
|
+
if (!access || !refresh) return null;
|
|
26
|
+
if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;
|
|
27
|
+
try {
|
|
28
|
+
const res = await fetch(
|
|
29
|
+
`${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,
|
|
30
|
+
{
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: {
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
"x-storefront-api-key": serverConfig().platformApiKey,
|
|
35
|
+
// The backend throttles per `storeId:clientIp`; without this (the
|
|
36
|
+
// shopper IP plus the forwarder secret that makes the backend
|
|
37
|
+
// believe it) every shopper's refresh lands in one store-wide bucket.
|
|
38
|
+
...forwardedForHeader(req.headers)
|
|
39
|
+
},
|
|
40
|
+
body: JSON.stringify({ refresh_token: refresh }),
|
|
41
|
+
// This is a latency budget added to a page load the user did not
|
|
42
|
+
// ask for, not an API call worth waiting out — bound it so a slow
|
|
43
|
+
// (not down) API can't turn a fast page load into a stall. An
|
|
44
|
+
// abort rejects `fetch`, which the surrounding catch below
|
|
45
|
+
// treats the same as any other network failure: non-fatal,
|
|
46
|
+
// the request proceeds on the old token.
|
|
47
|
+
signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS)
|
|
48
|
+
}
|
|
49
|
+
);
|
|
50
|
+
if (!res.ok) return null;
|
|
51
|
+
const data = await res.json();
|
|
52
|
+
if (data?.access_token && data?.refresh_token) {
|
|
53
|
+
return {
|
|
54
|
+
access_token: data.access_token,
|
|
55
|
+
refresh_token: data.refresh_token
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
} catch {
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
function downstreamRequestHeaders(req, hostMapped, storeRef, rotated) {
|
|
63
|
+
const headers = new Headers(req.headers);
|
|
64
|
+
headers.set(HOST_MAPPED_HEADER, hostMapped ? "1" : "0");
|
|
65
|
+
if (rotated && storeRef) {
|
|
66
|
+
const jar = new Map(req.cookies.getAll().map((c) => [c.name, c.value]));
|
|
67
|
+
jar.set(accessCookieName(storeRef), rotated.access_token);
|
|
68
|
+
jar.set(refreshCookieName(storeRef), rotated.refresh_token);
|
|
69
|
+
headers.set(
|
|
70
|
+
"cookie",
|
|
71
|
+
[...jar].map(([name, value]) => `${name}=${value}`).join("; ")
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return headers;
|
|
75
|
+
}
|
|
76
|
+
export {
|
|
77
|
+
downstreamRequestHeaders,
|
|
78
|
+
expiresWithin,
|
|
79
|
+
refreshIfNearExpiry
|
|
80
|
+
};
|
|
81
|
+
//# sourceMappingURL=session-refresh.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef))?.value;\n const refresh = req.cookies.get(refreshCookieName(storeRef))?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": serverConfig().platformApiKey,\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n jar.set(accessCookieName(storeRef), rotated.access_token);\n jar.set(refreshCookieName(storeRef), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAQ7B,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AAY1B,SAAS,cAAc,OAAe,SAA0B;AACrE,MAAI;AACF,UAAM,UAAU,KAAK;AAAA,MACnB,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM;AAAA,IAC5D;AACA,QAAI,OAAO,QAAQ,QAAQ,SAAU,QAAO;AAC5C,WAAO,QAAQ,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAaA,eAAsB,oBACpB,KACA,UAC+B;AAC/B,QAAM,SAAS,IAAI,QAAQ,IAAI,iBAAiB,QAAQ,CAAC,GAAG;AAC5D,QAAM,UAAU,IAAI,QAAQ,IAAI,kBAAkB,QAAQ,CAAC,GAAG;AAE9D,MAAI,CAAC,UAA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,EAAE,KAAK,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { cache } from "react";
|
|
3
|
+
import { cookies, headers } from "next/headers";
|
|
4
|
+
import { readAuthCookies } from "./cookies.js";
|
|
5
|
+
import { clientIpFrom } from "./client-ip.js";
|
|
6
|
+
import { createAuthApi } from "./sdk.js";
|
|
7
|
+
const getServerIdentity = cache(
|
|
8
|
+
async (storeRef) => {
|
|
9
|
+
const jar = await cookies();
|
|
10
|
+
const tokens = readAuthCookies(jar, storeRef);
|
|
11
|
+
if (!tokens) return null;
|
|
12
|
+
const me = await createAuthApi(storeRef, clientIpFrom(await headers())).me(
|
|
13
|
+
tokens.access_token
|
|
14
|
+
);
|
|
15
|
+
return me.success ? me.data ?? null : null;
|
|
16
|
+
}
|
|
17
|
+
);
|
|
18
|
+
async function hasCustomerSession(storeRef) {
|
|
19
|
+
const identity = await getServerIdentity(storeRef);
|
|
20
|
+
return !!identity && !identity.is_anonymous;
|
|
21
|
+
}
|
|
22
|
+
export {
|
|
23
|
+
getServerIdentity,
|
|
24
|
+
hasCustomerSession
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n const jar = await cookies();\n const tokens = readAuthCookies(jar, storeRef);\n if (!tokens) return null;\n\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable — and the backend rate-limits this\n // call per `storeId:clientIp`, so it has to carry the shopper's address\n // like every other server-side auth call does.\n const me = await createAuthApi(storeRef, clientIpFrom(await headers())).me(\n tokens.access_token\n );\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AASvB,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAC3D,UAAM,MAAM,MAAM,QAAQ;AAC1B,UAAM,SAAS,gBAAgB,KAAK,QAAQ;AAC5C,QAAI,CAAC,OAAQ,QAAO;AAMpB,UAAM,KAAK,MAAM,cAAc,UAAU,aAAa,MAAM,QAAQ,CAAC,CAAC,EAAE;AAAA,MACtE,OAAO;AAAA,IACT;AACA,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
|