@msm-platform/customer-react 0.1.0 → 0.3.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/dist/layout.d.ts CHANGED
@@ -4,10 +4,17 @@ import type { CustomerScreen } from "./context";
4
4
  export declare function BrandMark({ brand }: {
5
5
  brand: CustomerBrand | undefined;
6
6
  }): import("react").JSX.Element | null;
7
- /** The signed-in shell: brand header, account navigation and the current screen. */
7
+ /**
8
+ * The shell around every screen, signed in or not: brand header with sign
9
+ * in or out, navigation between booking and the account screens, and the
10
+ * current screen. A business page counts as booking.
11
+ */
8
12
  export declare function AccountLayout(props: {
9
13
  brand: CustomerBrand | undefined;
10
14
  screen: CustomerScreen;
15
+ signedIn: boolean;
16
+ /** The sign-in form is on screen, so the header offers no second one. */
17
+ signingIn: boolean;
11
18
  onNavigate: (screen: CustomerScreen) => void;
12
19
  onSignOut: () => void;
13
20
  children: ReactNode;
@@ -1,4 +1,9 @@
1
+ import type { OwnBooking } from "../client";
1
2
  export declare function Bookings(): import("react").JSX.Element;
2
3
  export declare function LoadFailed({ onRetry }: {
3
4
  onRetry: () => void;
4
5
  }): import("react").JSX.Element;
6
+ export declare function BookingItem(props: {
7
+ booking: OwnBooking;
8
+ onCancelled: (booking: OwnBooking, late: boolean) => void;
9
+ }): import("react").JSX.Element;
@@ -0,0 +1,11 @@
1
+ import type { Business as BusinessDto, Candidate } from "../client";
2
+ /**
3
+ * A business: its details, its event types as filters, and a week of its
4
+ * availability, events with seats and open time slots in one list, in the
5
+ * business's timezone. Choosing a candidate starts booking it.
6
+ */
7
+ export declare function Business(props: {
8
+ businessId: string;
9
+ eventTypeId: string | undefined;
10
+ onChoose: (business: BusinessDto, candidate: Candidate) => void;
11
+ }): import("react").JSX.Element;
@@ -0,0 +1,2 @@
1
+ /** The partner's public businesses, each leading to its times. */
2
+ export declare function Businesses(): import("react").JSX.Element;
@@ -1,13 +1,4 @@
1
- import { type LimiterStore } from "./limits";
2
- import type { BotCheckVerifier } from "./turnstile";
3
- export { type LimiterStore, memoryLimiterStore, type RedisEvalClient, redisLimiterStore, } from "./limits";
4
1
  export { type CustomerSession, customerSessionCookie, readCustomerSession, } from "./session";
5
- export { type BotCheckVerifier, turnstile } from "./turnstile";
6
- /** At most `max` attempts per key in a fixed window of `windowMs`. */
7
- export interface Limit {
8
- max: number;
9
- windowMs: number;
10
- }
11
2
  export interface CustomerHandlerOptions {
12
3
  /** Where the handler is mounted, such as `/msm`; the screens' `basePath`. */
13
4
  basePath: string;
@@ -22,27 +13,14 @@ export interface CustomerHandlerOptions {
22
13
  * a new key goes first and the old one stays until its cookies expire.
23
14
  */
24
15
  sessionKeys: string | readonly string[];
25
- /** Counts code requests per IP and per phone; shared by every server instance. */
26
- limiter: LimiterStore;
27
- /** Checks the screens' `botCheckToken`, such as `turnstile({ secretKey })`. */
28
- botCheck: BotCheckVerifier;
29
16
  /**
30
- * The client's IP address. Read it from what your platform guarantees, such
31
- * as the address your trusted proxy appends: a header the client can set,
32
- * like the leftmost `X-Forwarded-For` entry, lets anyone pick their own
33
- * limit. Return null when it is unknown, which refuses code requests.
17
+ * The visitor's IP address, which the engine limits code requests by. Read
18
+ * it from what your platform guarantees, such as the address your trusted
19
+ * proxy appends: a header the visitor can set, like the leftmost
20
+ * `X-Forwarded-For` entry, lets anyone pick their own limit. Return null
21
+ * when it is unknown, which refuses code requests.
34
22
  */
35
23
  clientIp: (request: Request) => string | null | undefined | Promise<string | null | undefined>;
36
- /**
37
- * Code requests (sign-in and registration together) per phone, default 5
38
- * per 15 minutes, and per IP, default 5 per 10 minutes.
39
- */
40
- limits?: {
41
- phone?: Limit;
42
- ip?: Limit;
43
- };
44
- /** Prefix of the limiter's keys; default `msm:customer:limit:`. */
45
- limiterPrefix?: string;
46
24
  fetch?: typeof globalThis.fetch;
47
25
  }
48
26
  /**
@@ -50,8 +28,9 @@ export interface CustomerHandlerOptions {
50
28
  * catch-all route such as `app/msm/[...path]/route.ts`:
51
29
  *
52
30
  * - `POST auth/initiate` `{phone, botCheckToken}` and
53
- * `POST auth/register/initiate` `{phone, name, botCheckToken}` send a code
54
- * after the bot check and the per-IP and per-phone limits;
31
+ * `POST auth/register/initiate` `{phone, name, botCheckToken}` ask the
32
+ * engine for a code with the token and `clientIp(request)`; the engine
33
+ * checks the bot check and limits per address and per phone;
55
34
  * - `POST auth/login` and `POST auth/register` `{challenge, code}` redeem it
56
35
  * once, never retried, and set the encrypted session cookie;
57
36
  * - `GET auth/session` and `POST auth/logout`;
package/dist/server.js CHANGED
@@ -1,138 +1,64 @@
1
1
  import { CustomerApiError as e, createCustomerClient as t } from "@msm-platform/customer-sdk";
2
- // src/server/limits.ts
3
- var n = "\nlocal count = redis.call('INCR', KEYS[1])\nif count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end\nlocal ttl = redis.call('PTTL', KEYS[1])\nif ttl < 0 then\n redis.call('PEXPIRE', KEYS[1], ARGV[1])\n ttl = tonumber(ARGV[1])\nend\nreturn {count, ttl}\n";
4
- function r(e) {
5
- return { async hit(t, r) {
6
- let i = await e.eval(n, {
7
- keys: [t],
8
- arguments: [String(Math.max(1, Math.ceil(r)))]
9
- });
10
- if (!Array.isArray(i) || i.length !== 2) throw Error("Unexpected limiter reply from Redis.");
11
- return {
12
- count: Number(i[0]),
13
- resetMs: Number(i[1])
14
- };
15
- } };
16
- }
17
- function i() {
18
- let e = /* @__PURE__ */ new Map();
19
- return { async hit(t, n) {
20
- let r = Date.now();
21
- if (e.size > 1e4) for (let [t, n] of e) n.resetAt <= r && e.delete(t);
22
- let i = e.get(t);
23
- return (!i || i.resetAt <= r) && (i = {
24
- count: 0,
25
- resetAt: r + n
26
- }, e.set(t, i)), i.count++, {
27
- count: i.count,
28
- resetMs: i.resetAt - r
29
- };
30
- } };
31
- }
32
- function a(e) {
33
- let t = e.trim().replace(/[ ()-]/g, "");
34
- return /^\+[1-9]\d{6,14}$/.test(t) ? t : null;
35
- }
36
- function o(e) {
37
- let t = e.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
38
- if (s(t)) return t;
39
- let n = c(t);
40
- if (!n) return null;
41
- if (n.slice(0, 5).every((e) => e === 0) && n[5] === 65535) {
42
- let e = n[6] ?? 0, t = n[7] ?? 0;
43
- return [
44
- e >> 8,
45
- e & 255,
46
- t >> 8,
47
- t & 255
48
- ].join(".");
49
- }
50
- return `${n.slice(0, 4).map((e) => e.toString(16)).join(":")}::/64`;
51
- }
52
- function s(e) {
53
- let t = e.split(".");
54
- return t.length === 4 && t.every((e) => /^\d{1,3}$/.test(e) && Number(e) <= 255);
55
- }
56
- function c(e) {
57
- if (!e.includes(":")) return null;
58
- let t = e, n = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(t);
59
- if (n) {
60
- let [, e = "", r = ""] = n;
61
- if (!s(r)) return null;
62
- let [i = 0, a = 0, o = 0, c = 0] = r.split(".").map(Number);
63
- t = `${e}${(i << 8 | a).toString(16)}:${(o << 8 | c).toString(16)}`;
64
- }
65
- let r = t.split("::");
66
- if (r.length > 2) return null;
67
- let i = (e) => e ? e.split(":") : [], a = i(r[0]), o = i(r[1]), c = 8 - a.length - o.length;
68
- if (r.length === 1 ? c !== 0 : c < 1) return null;
69
- let l = [
70
- ...a,
71
- ...Array(r.length === 2 ? c : 0).fill("0"),
72
- ...o
73
- ];
74
- return l.every((e) => /^[0-9a-f]{1,4}$/i.test(e)) ? l.map((e) => Number.parseInt(e, 16)) : null;
75
- }
76
2
  // src/server/session.ts
77
- var l = "__Host-msm_customer_session", u = new TextEncoder(), d = 12;
78
- function f(e) {
3
+ var n = "__Host-msm_customer_session", r = new TextEncoder(), i = 12;
4
+ function a(e) {
79
5
  let t = (typeof e == "string" ? [e] : [...e]).map((e) => e.trim());
80
6
  if (t.length === 0) throw Error("customer-react/server: sessionKeys needs at least one key.");
81
- for (let e of t) if (u.encode(e).length < 32) throw Error("customer-react/server: each session key must be at least 32 bytes, such as `openssl rand -base64 32`.");
7
+ for (let e of t) if (r.encode(e).length < 32) throw Error("customer-react/server: each session key must be at least 32 bytes, such as `openssl rand -base64 32`.");
82
8
  return t;
83
9
  }
84
- function p(e) {
85
- let t, n = () => t ??= Promise.all(e.map(async (e) => {
86
- let t = await crypto.subtle.importKey("raw", u.encode(e), "HKDF", !1, ["deriveKey"]);
10
+ function o(e) {
11
+ let t, a = () => t ??= Promise.all(e.map(async (e) => {
12
+ let t = await crypto.subtle.importKey("raw", r.encode(e), "HKDF", !1, ["deriveKey"]);
87
13
  return crypto.subtle.deriveKey({
88
14
  name: "HKDF",
89
15
  hash: "SHA-256",
90
16
  salt: /* @__PURE__ */ new Uint8Array(),
91
- info: u.encode("msm customer session v1")
17
+ info: r.encode("msm customer session v1")
92
18
  }, t, {
93
19
  name: "AES-GCM",
94
20
  length: 256
95
21
  }, !1, ["encrypt", "decrypt"]);
96
- })), r = u.encode(l);
22
+ })), o = r.encode(n);
97
23
  return {
98
24
  async seal(e) {
99
- let [t] = await n(), i = crypto.getRandomValues(new Uint8Array(d)), a = await crypto.subtle.encrypt({
25
+ let [t] = await a(), n = crypto.getRandomValues(new Uint8Array(i)), s = await crypto.subtle.encrypt({
100
26
  name: "AES-GCM",
101
- iv: i,
102
- additionalData: r
103
- }, t, u.encode(JSON.stringify({
27
+ iv: n,
28
+ additionalData: o
29
+ }, t, r.encode(JSON.stringify({
104
30
  sessionId: e.sessionId,
105
31
  sessionToken: e.sessionToken,
106
32
  expiresAt: e.expiresAt
107
- }))), o = new Uint8Array(d + a.byteLength);
108
- return o.set(i), o.set(new Uint8Array(a), d), g(o);
33
+ }))), c = new Uint8Array(i + s.byteLength);
34
+ return c.set(n), c.set(new Uint8Array(s), i), l(c);
109
35
  },
110
36
  async open(e) {
111
- let t = e ? _(e) : null;
112
- if (!t || t.length <= d) return null;
113
- let i = t.subarray(0, d), a = t.subarray(d);
114
- for (let e of await n()) {
37
+ let t = e ? u(e) : null;
38
+ if (!t || t.length <= i) return null;
39
+ let n = t.subarray(0, i), r = t.subarray(i);
40
+ for (let e of await a()) {
115
41
  let t;
116
42
  try {
117
43
  t = await crypto.subtle.decrypt({
118
44
  name: "AES-GCM",
119
- iv: i,
120
- additionalData: r
121
- }, e, a);
45
+ iv: n,
46
+ additionalData: o
47
+ }, e, r);
122
48
  } catch {
123
49
  continue;
124
50
  }
125
- let n = h(new TextDecoder().decode(t));
126
- return n && Date.parse(n.expiresAt) > Date.now() ? n : null;
51
+ let i = c(new TextDecoder().decode(t));
52
+ return i && Date.parse(i.expiresAt) > Date.now() ? i : null;
127
53
  }
128
54
  return null;
129
55
  }
130
56
  };
131
57
  }
132
- function m(e, t) {
133
- return p(f(t.sessionKeys)).open(e);
58
+ function s(e, t) {
59
+ return o(a(t.sessionKeys)).open(e);
134
60
  }
135
- function h(e) {
61
+ function c(e) {
136
62
  try {
137
63
  let t = JSON.parse(e);
138
64
  if (typeof t.sessionId == "string" && typeof t.sessionToken == "string" && typeof t.expiresAt == "string") return {
@@ -143,12 +69,12 @@ function h(e) {
143
69
  } catch {}
144
70
  return null;
145
71
  }
146
- function g(e) {
72
+ function l(e) {
147
73
  let t = "";
148
74
  for (let n of e) t += String.fromCharCode(n);
149
75
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
150
76
  }
151
- function _(e) {
77
+ function u(e) {
152
78
  if (!/^[A-Za-z0-9_-]+$/.test(e)) return null;
153
79
  try {
154
80
  let t = atob(e.replace(/-/g, "+").replace(/_/g, "/"));
@@ -157,47 +83,19 @@ function _(e) {
157
83
  return null;
158
84
  }
159
85
  }
160
- // src/server/turnstile.ts
161
- var v = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
162
- function y(e) {
163
- if (!e.secretKey?.trim()) throw Error("customer-react/server: turnstile needs its secretKey.");
164
- let t = e.fetch ?? globalThis.fetch;
165
- return async (n, { ip: r }) => {
166
- let i = new URLSearchParams({
167
- secret: e.secretKey,
168
- response: n,
169
- remoteip: r
170
- }), a = await t(v, {
171
- method: "POST",
172
- body: i,
173
- signal: AbortSignal.timeout(e.timeoutMs ?? 5e3)
174
- });
175
- if (!a.ok) throw Error(`Turnstile siteverify answered ${a.status}.`);
176
- return (await a.json()).success === !0;
177
- };
178
- }
179
86
  // src/server/index.ts
180
- var b = {
181
- phone: {
182
- max: 5,
183
- windowMs: 9e5
184
- },
185
- ip: {
186
- max: 5,
187
- windowMs: 6e5
188
- }
189
- }, x = 1e3, S = 1e4, C = 3e4, w = 1048576, T = /* @__PURE__ */ new Set([
87
+ var d = 1e4, f = 3e4, p = 1048576, m = /* @__PURE__ */ new Set([
190
88
  "GET",
191
89
  "HEAD",
192
90
  "POST",
193
91
  "PUT",
194
92
  "PATCH",
195
93
  "DELETE"
196
- ]), E = [
94
+ ]), h = [
197
95
  "accept",
198
96
  "content-type",
199
97
  "accept-language"
200
- ], D = "Path=/; HttpOnly; Secure; SameSite=Lax", O = class extends Error {
98
+ ], g = "Path=/; HttpOnly; Secure; SameSite=Lax", _ = class extends Error {
201
99
  status;
202
100
  code;
203
101
  retryAfterSeconds;
@@ -205,180 +103,159 @@ var b = {
205
103
  super(n), this.status = e, this.code = t, this.retryAfterSeconds = r;
206
104
  }
207
105
  };
208
- function k(n) {
209
- if (!n.limiter) throw Error("customer-react/server: limiter is required, such as redisLimiterStore(redis).");
210
- if (typeof n.botCheck != "function") throw Error("customer-react/server: botCheck is required, such as turnstile({ secretKey }).");
211
- if (typeof n.clientIp != "function") throw Error("customer-react/server: clientIp is required.");
212
- let r = n.basePath.replace(/\/$/, "");
213
- if (!r.startsWith("/") || r.startsWith("//")) throw Error("customer-react/server: basePath must be a path, such as /msm.");
214
- let i = p(f(n.sessionKeys)), { limiter: s, botCheck: c } = n, u = {
215
- phone: n.limits?.phone ?? b.phone,
216
- ip: n.limits?.ip ?? b.ip
217
- }, d = n.limiterPrefix ?? "msm:customer:limit:", m = t({
218
- baseUrl: n.engineUrl,
219
- clientId: n.clientId,
220
- clientSecret: n.clientSecret,
221
- ...n.fetch && { fetch: n.fetch }
222
- }), h = () => AbortSignal.timeout(S), g = `${l}=; ${D}; Max-Age=0`;
223
- async function _(e) {
106
+ function v(r) {
107
+ if (typeof r.clientIp != "function") throw Error("customer-react/server: clientIp is required.");
108
+ let i = r.basePath.replace(/\/$/, "");
109
+ if (!i.startsWith("/") || i.startsWith("//")) throw Error("customer-react/server: basePath must be a path, such as /msm.");
110
+ let s = o(a(r.sessionKeys)), c = t({
111
+ baseUrl: r.engineUrl,
112
+ clientId: r.clientId,
113
+ clientSecret: r.clientSecret,
114
+ ...r.fetch && { fetch: r.fetch }
115
+ }), l = () => AbortSignal.timeout(d), u = `${n}=; ${g}; Max-Age=0`;
116
+ async function p(e) {
224
117
  let t = new URL(e.url);
225
- if (t.pathname !== r && !t.pathname.startsWith(`${r}/`)) throw new O(404, "NotFound", "Not found.");
226
- let n = t.pathname.slice(r.length);
227
- if (e.headers.get("x-msm-bff") !== "1") throw new O(403, "BffHeaderRequired", "Missing X-MSM-BFF header.");
228
- let a = await i.open(N(e));
229
- if (n.startsWith("/engine/")) return w(e, t, n, a);
230
- let o = `${e.method} ${n}`;
118
+ if (t.pathname !== i && !t.pathname.startsWith(`${i}/`)) throw new _(404, "NotFound", "Not found.");
119
+ let r = t.pathname.slice(i.length);
120
+ if (e.headers.get("x-msm-bff") !== "1") throw new _(403, "BffHeaderRequired", "Missing X-MSM-BFF header.");
121
+ let a = await s.open(S(e));
122
+ if (r.startsWith("/engine/")) return w(e, t, r, a);
123
+ let o = `${e.method} ${r}`;
231
124
  if (o === "POST /auth/initiate") {
232
- let t = await v(e, await I(e, ["phone"]));
233
- return M(200, await m.POST("/web/identity/initiateLogin", {
234
- body: { phone: t },
235
- signal: h()
236
- }).then(j));
125
+ let t = await T(e, ["phone", "botCheckToken"]), n = await v(e, t);
126
+ return x(200, await c.POST("/web/identity/initiateLogin", {
127
+ body: {
128
+ phone: t.phone,
129
+ ...n
130
+ },
131
+ signal: l()
132
+ }).then(b));
237
133
  }
238
134
  if (o === "POST /auth/register/initiate") {
239
- let t = await I(e, ["phone", "name"]), n = await v(e, t);
240
- return M(200, await m.POST("/web/identity/initiateRegistration", {
135
+ let t = await T(e, [
136
+ "phone",
137
+ "name",
138
+ "botCheckToken"
139
+ ]), n = await v(e, t);
140
+ return x(200, await c.POST("/web/identity/initiateRegistration", {
241
141
  body: {
242
- phone: n,
243
- name: t.name
142
+ phone: t.phone,
143
+ name: t.name,
144
+ ...n
244
145
  },
245
- signal: h()
246
- }).then(j));
146
+ signal: l()
147
+ }).then(b));
247
148
  }
248
149
  if (o === "POST /auth/login" || o === "POST /auth/register") {
249
- let { challenge: t, code: r } = await I(e, ["challenge", "code"]), o = await m.POST(n === "/auth/login" ? "/web/identity/customerLogin" : "/web/identity/registerCustomer", {
150
+ let { challenge: t, code: i } = await T(e, ["challenge", "code"]), o = await c.POST(r === "/auth/login" ? "/web/identity/customerLogin" : "/web/identity/registerCustomer", {
250
151
  body: {
251
152
  challenge: t,
252
- code: r
153
+ code: i
253
154
  },
254
- signal: h()
255
- }).then(j);
256
- a && await k(a);
257
- let s = Math.floor((Date.parse(o.expiresAt) - Date.now()) / 1e3), c = await i.seal(o);
258
- return M(200, { sessionKey: o.sessionId }, { "set-cookie": `${l}=${c}; ${D}; Max-Age=${Math.max(0, s)}` });
155
+ signal: l()
156
+ }).then(b);
157
+ a && await E(a);
158
+ let u = Math.floor((Date.parse(o.expiresAt) - Date.now()) / 1e3), d = await s.seal(o);
159
+ return x(200, { sessionKey: o.sessionId }, { "set-cookie": `${n}=${d}; ${g}; Max-Age=${Math.max(0, u)}` });
259
160
  }
260
- if (o === "GET /auth/session") return a ? M(200, { sessionKey: a.sessionId }) : F();
261
- if (o === "POST /auth/logout") return a && await k(a), new Response(null, {
161
+ if (o === "GET /auth/session") return a ? x(200, { sessionKey: a.sessionId }) : D();
162
+ if (o === "POST /auth/logout") return a && await E(a), new Response(null, {
262
163
  status: 204,
263
164
  headers: {
264
- "set-cookie": g,
165
+ "set-cookie": u,
265
166
  "cache-control": "no-store"
266
167
  }
267
168
  });
268
- throw new O(404, "NotFound", "Not found.");
169
+ throw new _(404, "NotFound", "Not found.");
269
170
  }
270
171
  async function v(e, t) {
271
- let r = a(t.phone);
272
- if (!r) throw new O(400, "InvalidRequest", "Expected a phone number with its country code, such as +3545551234.");
273
- let i;
274
- try {
275
- let t = await n.clientIp(e);
276
- i = t ? o(t) : null;
277
- } catch {
278
- i = null;
279
- }
280
- if (!i) throw new O(503, "ClientIpUnavailable", "The client's address is unknown.");
281
- let s = t.botCheckToken;
282
- if (typeof s != "string" || !s) throw new O(403, "BotCheckFailed", "The bot check did not pass.");
283
- let l;
172
+ let n;
284
173
  try {
285
- l = await c(s, {
286
- ip: i,
287
- request: e
288
- });
289
- } catch {
290
- throw new O(503, "BotCheckUnavailable", "The bot check is unavailable. Try again shortly.");
291
- }
292
- if (!l) throw new O(403, "BotCheckFailed", "The bot check did not pass.");
293
- return await y(`ip:${await L(i)}`, u.ip), await y(`phone:${await L(r)}`, u.phone), r;
294
- }
295
- async function y(e, { max: t, windowMs: n }) {
296
- let r, i;
297
- try {
298
- if (i = await Promise.race([s.hit(`${d}${e}`, n), new Promise((e, t) => {
299
- r = setTimeout(() => t(/* @__PURE__ */ Error("Limiter timed out.")), x);
300
- })]), !Number.isFinite(i?.count)) throw Error("Bad limiter reply.");
174
+ n = await r.clientIp(e);
301
175
  } catch {
302
- throw new O(503, "LimiterUnavailable", "Sign-in is unavailable. Try again shortly.");
303
- } finally {
304
- clearTimeout(r);
176
+ n = null;
305
177
  }
306
- if (i.count > t) throw new O(429, "TooManyAttempts", "Try again later.", Math.max(1, Math.ceil(i.resetMs / 1e3)));
178
+ let i = n?.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
179
+ if (!i) throw new _(503, "ClientIpUnavailable", "The client's address is unknown.");
180
+ return {
181
+ botCheckToken: t.botCheckToken,
182
+ clientIp: i
183
+ };
307
184
  }
308
185
  async function w(t, n, r, i) {
309
186
  let a = r.slice(7);
310
- if (!A(a) || !T.has(t.method)) throw new O(404, "NotFound", "Not found.");
187
+ if (!y(a) || !m.has(t.method)) throw new _(404, "NotFound", "Not found.");
311
188
  let o = new Headers();
312
- for (let e of E) {
189
+ for (let e of h) {
313
190
  let n = t.headers.get(e);
314
191
  n && o.set(e, n);
315
192
  }
316
193
  i && o.set("x-session-token", i.sessionToken);
317
- let s = t.method !== "GET" && t.method !== "HEAD" ? await P(t) : void 0, c;
194
+ let s = t.method !== "GET" && t.method !== "HEAD" ? await C(t) : void 0, l;
318
195
  try {
319
- c = (await m.request(t.method.toLowerCase(), `${a}${n.search}`, {
196
+ l = (await c.request(t.method.toLowerCase(), `${a}${n.search}`, {
320
197
  headers: o,
321
198
  ...s && s.byteLength > 0 && { body: s },
322
199
  bodySerializer: (e) => e,
323
200
  parseAs: "stream",
324
201
  redirect: "manual",
325
- signal: AbortSignal.timeout(C)
202
+ signal: AbortSignal.timeout(f)
326
203
  })).response;
327
204
  } catch (t) {
328
205
  if (!(t instanceof e)) throw t;
329
- c = t.response;
206
+ l = t.response;
330
207
  }
331
- let l = c.status === 401 || c.ok && t.method === "DELETE" && a === "/web/me/sessions" && i !== null, u = new Headers({ "cache-control": "no-store" });
208
+ let d = l.status === 401 || l.ok && t.method === "DELETE" && a === "/web/me/sessions" && i !== null, p = new Headers({ "cache-control": "no-store" });
332
209
  for (let e of ["content-type", "retry-after"]) {
333
- let t = c.headers.get(e);
334
- t && u.set(e, t);
210
+ let t = l.headers.get(e);
211
+ t && p.set(e, t);
335
212
  }
336
- l && u.set("set-cookie", g);
337
- let d = t.method === "HEAD" || [
213
+ d && p.set("set-cookie", u);
214
+ let g = t.method === "HEAD" || [
338
215
  204,
339
216
  205,
340
217
  304
341
- ].includes(c.status);
342
- return new Response(d ? null : await c.arrayBuffer(), {
343
- status: c.status,
344
- headers: u
218
+ ].includes(l.status);
219
+ return new Response(g ? null : await l.arrayBuffer(), {
220
+ status: l.status,
221
+ headers: p
345
222
  });
346
223
  }
347
- async function k(e) {
348
- await m.POST("/web/identity/logout", {
224
+ async function E(e) {
225
+ await c.POST("/web/identity/logout", {
349
226
  body: { sessionToken: e.sessionToken },
350
- signal: h()
227
+ signal: l()
351
228
  }).catch(() => {});
352
229
  }
353
- function F() {
354
- return M(401, {
230
+ function D() {
231
+ return x(401, {
355
232
  code: "NotAuthenticated",
356
233
  message: "Sign in again."
357
- }, { "set-cookie": g });
234
+ }, { "set-cookie": u });
358
235
  }
359
236
  return async function(t) {
360
237
  try {
361
- return await _(t);
238
+ return await p(t);
362
239
  } catch (t) {
363
- if (t instanceof O) return M(t.status, {
240
+ if (t instanceof _) return x(t.status, {
364
241
  code: t.code,
365
242
  message: t.message
366
243
  }, t.retryAfterSeconds ? { "retry-after": String(t.retryAfterSeconds) } : {});
367
244
  if (t instanceof e && (t.status >= 400 && t.status < 500 || t.status === 503 && t.code)) {
368
245
  let e = t.response.headers.get("retry-after");
369
- return M(t.status, {
246
+ return x(t.status, {
370
247
  code: t.code ?? "EngineRejected",
371
248
  message: t.message
372
249
  }, e ? { "retry-after": e } : {});
373
250
  }
374
- return M(502, {
251
+ return x(502, {
375
252
  code: "EngineUnavailable",
376
253
  message: "The engine could not complete the request."
377
254
  });
378
255
  }
379
256
  };
380
257
  }
381
- function A(e) {
258
+ function y(e) {
382
259
  if (/%2f|%5c|\/\//i.test(e)) return !1;
383
260
  let t;
384
261
  try {
@@ -388,11 +265,11 @@ function A(e) {
388
265
  }
389
266
  return !/(^|\/)\.\.?(\/|$)|\\/.test(t) && /^\/web\//.test(t) && !/^\/web\/identity(\/|$)/i.test(t);
390
267
  }
391
- var j = ({ data: e }) => {
268
+ var b = ({ data: e }) => {
392
269
  if (e === void 0) throw Error("Engine returned no body.");
393
270
  return e;
394
271
  };
395
- function M(e, t, n = {}) {
272
+ function x(e, t, n = {}) {
396
273
  return new Response(JSON.stringify(t), {
397
274
  status: e,
398
275
  headers: {
@@ -402,41 +279,37 @@ function M(e, t, n = {}) {
402
279
  }
403
280
  });
404
281
  }
405
- function N(e) {
282
+ function S(e) {
406
283
  for (let t of e.headers.get("cookie")?.split(";") ?? []) {
407
284
  let e = t.indexOf("=");
408
285
  if (e > 0 && t.slice(0, e).trim() === "__Host-msm_customer_session") return t.slice(e + 1).trim() || void 0;
409
286
  }
410
287
  }
411
- async function P(e) {
412
- if (Number(e.headers.get("content-length")) > w) throw F();
288
+ async function C(e) {
289
+ if (Number(e.headers.get("content-length")) > p) throw w();
413
290
  if (!e.body) return /* @__PURE__ */ new Uint8Array();
414
291
  let t = e.body.getReader(), n = [], r = 0;
415
292
  for (;;) {
416
293
  let { done: e, value: i } = await t.read();
417
294
  if (e) break;
418
- if (r += i.byteLength, r > w) throw await t.cancel().catch(() => {}), F();
295
+ if (r += i.byteLength, r > p) throw await t.cancel().catch(() => {}), w();
419
296
  n.push(i);
420
297
  }
421
298
  let i = new Uint8Array(r), a = 0;
422
299
  for (let e of n) i.set(e, a), a += e.byteLength;
423
300
  return i;
424
301
  }
425
- var F = () => new O(413, "PayloadTooLarge", "Request body is too large.");
426
- async function I(e, t) {
302
+ var w = () => new _(413, "PayloadTooLarge", "Request body is too large.");
303
+ async function T(e, t) {
427
304
  let n;
428
305
  try {
429
- n = JSON.parse(new TextDecoder().decode(await P(e)));
306
+ n = JSON.parse(new TextDecoder().decode(await C(e)));
430
307
  } catch (e) {
431
- if (e instanceof O) throw e;
308
+ if (e instanceof _) throw e;
432
309
  n = void 0;
433
310
  }
434
311
  let r = typeof n == "object" && n;
435
- if (!r || t.some((e) => typeof r[e] != "string")) throw new O(400, "InvalidRequest", `Expected ${t.join(", ")}.`);
312
+ if (!r || t.some((e) => typeof r[e] != "string")) throw new _(400, "InvalidRequest", `Expected ${t.join(", ")}.`);
436
313
  return r;
437
314
  }
438
- async function L(e) {
439
- let t = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
440
- return Array.from(new Uint8Array(t), (e) => e.toString(16).padStart(2, "0")).join("");
441
- }
442
- export { k as createCustomerHandler, l as customerSessionCookie, i as memoryLimiterStore, m as readCustomerSession, r as redisLimiterStore, y as turnstile };
315
+ export { v as createCustomerHandler, n as customerSessionCookie, s as readCustomerSession };