@msm-platform/customer-react 0.0.0-stage → 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.
@@ -0,0 +1,21 @@
1
+ import type { ReactNode } from "react";
2
+ import type { CustomerBrand } from "./client";
3
+ import type { CustomerScreen } from "./context";
4
+ export declare function BrandMark({ brand }: {
5
+ brand: CustomerBrand | undefined;
6
+ }): import("react").JSX.Element | null;
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
+ */
12
+ export declare function AccountLayout(props: {
13
+ brand: CustomerBrand | undefined;
14
+ screen: CustomerScreen;
15
+ signedIn: boolean;
16
+ /** The sign-in form is on screen, so the header offers no second one. */
17
+ signingIn: boolean;
18
+ onNavigate: (screen: CustomerScreen) => void;
19
+ onSignOut: () => void;
20
+ children: ReactNode;
21
+ }): import("react").JSX.Element;
@@ -0,0 +1,9 @@
1
+ import type { OwnBooking } from "../client";
2
+ export declare function Bookings(): import("react").JSX.Element;
3
+ export declare function LoadFailed({ onRetry }: {
4
+ onRetry: () => void;
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;
@@ -0,0 +1,2 @@
1
+ /** The customer's own details: the name is editable, phone and email are not. */
2
+ export declare function Details(): import("react").JSX.Element;
@@ -0,0 +1 @@
1
+ export declare function Passes(): import("react").JSX.Element;
@@ -0,0 +1,65 @@
1
+ import { type LimiterStore } from "./limits";
2
+ import type { BotCheckVerifier } from "./turnstile";
3
+ export { type LimiterStore, memoryLimiterStore, type RedisEvalClient, redisLimiterStore, } from "./limits";
4
+ 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
+ export interface CustomerHandlerOptions {
12
+ /** Where the handler is mounted, such as `/msm`; the screens' `basePath`. */
13
+ basePath: string;
14
+ /** MSM's engine, such as `https://api.example.com`. */
15
+ engineUrl: string;
16
+ /** The partner's website application client. The secret stays on this server. */
17
+ clientId: string;
18
+ clientSecret: string;
19
+ /**
20
+ * Keys that encrypt the session cookie, each at least 32 bytes, such as
21
+ * `openssl rand -base64 32`. The first encrypts and every one decrypts, so
22
+ * a new key goes first and the old one stays until its cookies expire.
23
+ */
24
+ 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
+ /**
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.
34
+ */
35
+ 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
+ fetch?: typeof globalThis.fetch;
47
+ }
48
+ /**
49
+ * The routes MSM's customer screens call under their `basePath`, for one
50
+ * catch-all route such as `app/msm/[...path]/route.ts`:
51
+ *
52
+ * - `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;
55
+ * - `POST auth/login` and `POST auth/register` `{challenge, code}` redeem it
56
+ * once, never retried, and set the encrypted session cookie;
57
+ * - `GET auth/session` and `POST auth/logout`;
58
+ * - `/engine/web/*`, except `/web/identity/*`, proxied to the engine with the
59
+ * client's credentials and the cookie's session.
60
+ *
61
+ * Every route needs the `X-MSM-BFF: 1` header the screens send. Browsers send
62
+ * a custom header cross-origin only after a CORS preflight, which this never
63
+ * approves, so another site cannot make these calls with the cookie.
64
+ */
65
+ export declare function createCustomerHandler(options: CustomerHandlerOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Counts attempts in fixed windows. `hit` adds one attempt to `key` and
3
+ * returns the window's count so far, this one included, and the milliseconds
4
+ * until the window ends. It must be atomic across every server instance that
5
+ * shares the store. A rejected or slow `hit` refuses the attempt (fail closed).
6
+ */
7
+ export interface LimiterStore {
8
+ hit(key: string, windowMs: number): Promise<{
9
+ count: number;
10
+ resetMs: number;
11
+ }>;
12
+ }
13
+ /**
14
+ * The part of a node-redis client (`createClient` from `redis`) the Redis
15
+ * store uses, so this package needs no Redis dependency of its own.
16
+ */
17
+ export interface RedisEvalClient {
18
+ eval(script: string, options: {
19
+ keys: string[];
20
+ arguments: string[];
21
+ }): Promise<unknown>;
22
+ }
23
+ /**
24
+ * A limiter store in Redis, shared by every instance of the partner's server.
25
+ * Each hit is one Lua script, so concurrent hits never lose a count.
26
+ */
27
+ export declare function redisLimiterStore(redis: RedisEvalClient): LimiterStore;
28
+ /**
29
+ * A limiter store in this process's memory. It counts per process, so use it
30
+ * only for development, tests or a server that runs as exactly one instance.
31
+ */
32
+ export declare function memoryLimiterStore(): LimiterStore;
33
+ /**
34
+ * The limiter key for a phone, as the engine reads it: spaces, parentheses
35
+ * and hyphens dropped, then `+` and 7 to 15 digits (E.164). Null for anything
36
+ * the engine would refuse, which is refused before any count.
37
+ */
38
+ export declare function phoneKey(phone: string): string | null;
39
+ /**
40
+ * The limiter key for a client address: an IPv4 address as is, an IPv6
41
+ * address by its /64 (one host usually holds the whole /64), and an
42
+ * IPv4-mapped IPv6 address as its IPv4 address. Null when it is neither.
43
+ */
44
+ export declare function ipKey(address: string): string | null;
@@ -0,0 +1,37 @@
1
+ /** The cookie that holds a signed-in customer's encrypted session. */
2
+ export declare const customerSessionCookie = "__Host-msm_customer_session";
3
+ /** A customer's engine session, as the cookie holds it. Server-side only. */
4
+ export interface CustomerSession {
5
+ sessionId: string;
6
+ sessionToken: string;
7
+ /** When the session reaches its maximum age (ISO 8601). */
8
+ expiresAt: string;
9
+ }
10
+ /**
11
+ * Checks the partner's session keys, newest first: each is a secret string of
12
+ * at least 32 bytes, such as `openssl rand -base64 32`.
13
+ */
14
+ export declare function sessionKeyList(keys: string | readonly string[]): string[];
15
+ /**
16
+ * AES-256-GCM keys derived with HKDF-SHA256 from the partner's keys, so any
17
+ * long random string works as a key. The first encrypts; every one decrypts.
18
+ */
19
+ export declare function sessionCipher(keys: readonly string[]): {
20
+ seal(session: CustomerSession): Promise<string>;
21
+ /** The cookie's session, or null when no key opens it or it has expired. */
22
+ open(value: string | undefined): Promise<CustomerSession | null>;
23
+ };
24
+ /**
25
+ * The signed-in customer's session for the partner's own server code, such as
26
+ * a page that books through the customer SDK with `sessionHeaders`. It shares
27
+ * the screens' sign-in. Pass the `__Host-msm_customer_session` cookie's value
28
+ * (`customerSessionCookie`) and the handler's `sessionKeys`.
29
+ *
30
+ * It returns null when the cookie is missing, no key opens it, or the session
31
+ * has reached its `expiresAt`. It does not ask the engine, so a session
32
+ * revoked elsewhere or ended for idleness still reads as signed in until the
33
+ * engine answers 401; a caller that needs certainty calls the engine.
34
+ */
35
+ export declare function readCustomerSession(cookieValue: string | undefined, options: {
36
+ sessionKeys: string | readonly string[];
37
+ }): Promise<CustomerSession | null>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Checks the bot-check token the screens send with `botCheckToken` when they
3
+ * ask for a code. Resolve true when it passes and false when it does not;
4
+ * reject when the check cannot be made, which refuses the request with 503
5
+ * (fail closed).
6
+ */
7
+ export type BotCheckVerifier = (token: string, context: {
8
+ ip: string;
9
+ request: Request;
10
+ }) => Promise<boolean>;
11
+ /**
12
+ * Cloudflare Turnstile's server-side check (siteverify) with the partner's
13
+ * secret key. In development use Cloudflare's test keys: the secret
14
+ * `1x0000000000000000000000000000000AA` passes every token and
15
+ * `2x0000000000000000000000000000000AA` fails every one.
16
+ */
17
+ export declare function turnstile(options: {
18
+ secretKey: string;
19
+ /** Milliseconds to wait for siteverify; default 5000. */
20
+ timeoutMs?: number;
21
+ fetch?: typeof globalThis.fetch;
22
+ }): BotCheckVerifier;
package/dist/server.js ADDED
@@ -0,0 +1,442 @@
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
+ // src/server/session.ts
77
+ var l = "__Host-msm_customer_session", u = new TextEncoder(), d = 12;
78
+ function f(e) {
79
+ let t = (typeof e == "string" ? [e] : [...e]).map((e) => e.trim());
80
+ 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`.");
82
+ return t;
83
+ }
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"]);
87
+ return crypto.subtle.deriveKey({
88
+ name: "HKDF",
89
+ hash: "SHA-256",
90
+ salt: /* @__PURE__ */ new Uint8Array(),
91
+ info: u.encode("msm customer session v1")
92
+ }, t, {
93
+ name: "AES-GCM",
94
+ length: 256
95
+ }, !1, ["encrypt", "decrypt"]);
96
+ })), r = u.encode(l);
97
+ return {
98
+ async seal(e) {
99
+ let [t] = await n(), i = crypto.getRandomValues(new Uint8Array(d)), a = await crypto.subtle.encrypt({
100
+ name: "AES-GCM",
101
+ iv: i,
102
+ additionalData: r
103
+ }, t, u.encode(JSON.stringify({
104
+ sessionId: e.sessionId,
105
+ sessionToken: e.sessionToken,
106
+ expiresAt: e.expiresAt
107
+ }))), o = new Uint8Array(d + a.byteLength);
108
+ return o.set(i), o.set(new Uint8Array(a), d), g(o);
109
+ },
110
+ 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()) {
115
+ let t;
116
+ try {
117
+ t = await crypto.subtle.decrypt({
118
+ name: "AES-GCM",
119
+ iv: i,
120
+ additionalData: r
121
+ }, e, a);
122
+ } catch {
123
+ continue;
124
+ }
125
+ let n = h(new TextDecoder().decode(t));
126
+ return n && Date.parse(n.expiresAt) > Date.now() ? n : null;
127
+ }
128
+ return null;
129
+ }
130
+ };
131
+ }
132
+ function m(e, t) {
133
+ return p(f(t.sessionKeys)).open(e);
134
+ }
135
+ function h(e) {
136
+ try {
137
+ let t = JSON.parse(e);
138
+ if (typeof t.sessionId == "string" && typeof t.sessionToken == "string" && typeof t.expiresAt == "string") return {
139
+ sessionId: t.sessionId,
140
+ sessionToken: t.sessionToken,
141
+ expiresAt: t.expiresAt
142
+ };
143
+ } catch {}
144
+ return null;
145
+ }
146
+ function g(e) {
147
+ let t = "";
148
+ for (let n of e) t += String.fromCharCode(n);
149
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
150
+ }
151
+ function _(e) {
152
+ if (!/^[A-Za-z0-9_-]+$/.test(e)) return null;
153
+ try {
154
+ let t = atob(e.replace(/-/g, "+").replace(/_/g, "/"));
155
+ return Uint8Array.from(t, (e) => e.charCodeAt(0));
156
+ } catch {
157
+ return null;
158
+ }
159
+ }
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
+ // 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([
190
+ "GET",
191
+ "HEAD",
192
+ "POST",
193
+ "PUT",
194
+ "PATCH",
195
+ "DELETE"
196
+ ]), E = [
197
+ "accept",
198
+ "content-type",
199
+ "accept-language"
200
+ ], D = "Path=/; HttpOnly; Secure; SameSite=Lax", O = class extends Error {
201
+ status;
202
+ code;
203
+ retryAfterSeconds;
204
+ constructor(e, t, n, r) {
205
+ super(n), this.status = e, this.code = t, this.retryAfterSeconds = r;
206
+ }
207
+ };
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) {
224
+ 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}`;
231
+ 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));
237
+ }
238
+ 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", {
241
+ body: {
242
+ phone: n,
243
+ name: t.name
244
+ },
245
+ signal: h()
246
+ }).then(j));
247
+ }
248
+ 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", {
250
+ body: {
251
+ challenge: t,
252
+ code: r
253
+ },
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)}` });
259
+ }
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, {
262
+ status: 204,
263
+ headers: {
264
+ "set-cookie": g,
265
+ "cache-control": "no-store"
266
+ }
267
+ });
268
+ throw new O(404, "NotFound", "Not found.");
269
+ }
270
+ 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;
284
+ 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.");
301
+ } catch {
302
+ throw new O(503, "LimiterUnavailable", "Sign-in is unavailable. Try again shortly.");
303
+ } finally {
304
+ clearTimeout(r);
305
+ }
306
+ if (i.count > t) throw new O(429, "TooManyAttempts", "Try again later.", Math.max(1, Math.ceil(i.resetMs / 1e3)));
307
+ }
308
+ async function w(t, n, r, i) {
309
+ let a = r.slice(7);
310
+ if (!A(a) || !T.has(t.method)) throw new O(404, "NotFound", "Not found.");
311
+ let o = new Headers();
312
+ for (let e of E) {
313
+ let n = t.headers.get(e);
314
+ n && o.set(e, n);
315
+ }
316
+ i && o.set("x-session-token", i.sessionToken);
317
+ let s = t.method !== "GET" && t.method !== "HEAD" ? await P(t) : void 0, c;
318
+ try {
319
+ c = (await m.request(t.method.toLowerCase(), `${a}${n.search}`, {
320
+ headers: o,
321
+ ...s && s.byteLength > 0 && { body: s },
322
+ bodySerializer: (e) => e,
323
+ parseAs: "stream",
324
+ redirect: "manual",
325
+ signal: AbortSignal.timeout(C)
326
+ })).response;
327
+ } catch (t) {
328
+ if (!(t instanceof e)) throw t;
329
+ c = t.response;
330
+ }
331
+ let l = c.status === 401 || c.ok && t.method === "DELETE" && a === "/web/me/sessions" && i !== null, u = new Headers({ "cache-control": "no-store" });
332
+ for (let e of ["content-type", "retry-after"]) {
333
+ let t = c.headers.get(e);
334
+ t && u.set(e, t);
335
+ }
336
+ l && u.set("set-cookie", g);
337
+ let d = t.method === "HEAD" || [
338
+ 204,
339
+ 205,
340
+ 304
341
+ ].includes(c.status);
342
+ return new Response(d ? null : await c.arrayBuffer(), {
343
+ status: c.status,
344
+ headers: u
345
+ });
346
+ }
347
+ async function k(e) {
348
+ await m.POST("/web/identity/logout", {
349
+ body: { sessionToken: e.sessionToken },
350
+ signal: h()
351
+ }).catch(() => {});
352
+ }
353
+ function F() {
354
+ return M(401, {
355
+ code: "NotAuthenticated",
356
+ message: "Sign in again."
357
+ }, { "set-cookie": g });
358
+ }
359
+ return async function(t) {
360
+ try {
361
+ return await _(t);
362
+ } catch (t) {
363
+ if (t instanceof O) return M(t.status, {
364
+ code: t.code,
365
+ message: t.message
366
+ }, t.retryAfterSeconds ? { "retry-after": String(t.retryAfterSeconds) } : {});
367
+ if (t instanceof e && (t.status >= 400 && t.status < 500 || t.status === 503 && t.code)) {
368
+ let e = t.response.headers.get("retry-after");
369
+ return M(t.status, {
370
+ code: t.code ?? "EngineRejected",
371
+ message: t.message
372
+ }, e ? { "retry-after": e } : {});
373
+ }
374
+ return M(502, {
375
+ code: "EngineUnavailable",
376
+ message: "The engine could not complete the request."
377
+ });
378
+ }
379
+ };
380
+ }
381
+ function A(e) {
382
+ if (/%2f|%5c|\/\//i.test(e)) return !1;
383
+ let t;
384
+ try {
385
+ t = decodeURIComponent(e);
386
+ } catch {
387
+ return !1;
388
+ }
389
+ return !/(^|\/)\.\.?(\/|$)|\\/.test(t) && /^\/web\//.test(t) && !/^\/web\/identity(\/|$)/i.test(t);
390
+ }
391
+ var j = ({ data: e }) => {
392
+ if (e === void 0) throw Error("Engine returned no body.");
393
+ return e;
394
+ };
395
+ function M(e, t, n = {}) {
396
+ return new Response(JSON.stringify(t), {
397
+ status: e,
398
+ headers: {
399
+ "content-type": "application/json",
400
+ "cache-control": "no-store",
401
+ ...n
402
+ }
403
+ });
404
+ }
405
+ function N(e) {
406
+ for (let t of e.headers.get("cookie")?.split(";") ?? []) {
407
+ let e = t.indexOf("=");
408
+ if (e > 0 && t.slice(0, e).trim() === "__Host-msm_customer_session") return t.slice(e + 1).trim() || void 0;
409
+ }
410
+ }
411
+ async function P(e) {
412
+ if (Number(e.headers.get("content-length")) > w) throw F();
413
+ if (!e.body) return /* @__PURE__ */ new Uint8Array();
414
+ let t = e.body.getReader(), n = [], r = 0;
415
+ for (;;) {
416
+ let { done: e, value: i } = await t.read();
417
+ if (e) break;
418
+ if (r += i.byteLength, r > w) throw await t.cancel().catch(() => {}), F();
419
+ n.push(i);
420
+ }
421
+ let i = new Uint8Array(r), a = 0;
422
+ for (let e of n) i.set(e, a), a += e.byteLength;
423
+ return i;
424
+ }
425
+ var F = () => new O(413, "PayloadTooLarge", "Request body is too large.");
426
+ async function I(e, t) {
427
+ let n;
428
+ try {
429
+ n = JSON.parse(new TextDecoder().decode(await P(e)));
430
+ } catch (e) {
431
+ if (e instanceof O) throw e;
432
+ n = void 0;
433
+ }
434
+ let r = typeof n == "object" && n;
435
+ if (!r || t.some((e) => typeof r[e] != "string")) throw new O(400, "InvalidRequest", `Expected ${t.join(", ")}.`);
436
+ return r;
437
+ }
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 };
@@ -0,0 +1,14 @@
1
+ import { type ReactNode } from "react";
2
+ import { type CustomerBotCheck, type CustomerBrand } from "./client";
3
+ import { type MessageKey } from "./i18n";
4
+ /** Phone sign-in and registration through the server half's auth routes. */
5
+ export declare function SignIn(props: {
6
+ basePath: string;
7
+ brand: CustomerBrand | undefined;
8
+ /** Required by the types; plain JavaScript may still leave it out. */
9
+ botCheck: CustomerBotCheck | undefined;
10
+ notice: MessageKey | undefined;
11
+ onSignedIn: (sessionKey: string) => void;
12
+ /** What the customer is signing in for, such as the time they chose. */
13
+ children?: ReactNode;
14
+ }): import("react").JSX.Element;