@msm-platform/customer-react 0.2.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/CHANGELOG.md CHANGED
@@ -4,6 +4,12 @@ All notable changes to `@msm-platform/customer-react`. The format follows [Keep
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.3.0] - 2026-11-15
8
+
9
+ ### Changed
10
+
11
+ - **Breaking:** the engine checks the bot check and limits code requests now, so the server half only forwards the screens' `botCheckToken` and `clientIp(request)` to it. `createCustomerHandler` no longer takes `limiter`, `botCheck`, `limits` or `limiterPrefix`, and `redisLimiterStore`, `memoryLimiterStore`, `turnstile`, `LimiterStore`, `RedisEvalClient` and `BotCheckVerifier` are removed: delete them from your options and imports. Your server needs no Redis and no Turnstile secret; MSM keeps the widget's secret and hands over its site key for the screens' `botCheck` prop. `clientIp` stays required, and a code request without an address still answers 503 `ClientIpUnavailable`. The engine's refusals reach the screens unchanged: 403 `BotCheckFailed`, 429 `TooManyAttempts` with `Retry-After`, 503 `BotCheckUnavailable` or `LimiterUnavailable`. A code request without `botCheckToken` is now 400 `InvalidRequest` instead of 403, and the phone's format is checked by the engine (400 `ValidationFailed`) instead of before the call. It needs the engine release that checks the token: an older engine refuses the forwarded fields with 400.
12
+
7
13
  ## [0.2.0] - 2026-11-14
8
14
 
9
15
  ### Added
package/README.md CHANGED
@@ -10,7 +10,7 @@ It depends on `@msm-platform/customer-sdk`, which the server half calls the engi
10
10
 
11
11
  ## Public API
12
12
 
13
- What the changelog treats as breaking to rename or remove: the exports of `.` and `./server` and the stylesheet `./style.css`; the props below, including `brand: {name, logo}`, `botCheck: {provider: "turnstile", siteKey}` and the `screen` values `businesses`, `{businessId}`, `{businessId, eventTypeId}`, `bookings`, `passes` and `details` (a new value is additive; renaming or removing one, or changing the default `businesses`, is breaking); the nine `--msm-customer-*` properties ([Theming](#theming)); the server half's options and routes, including the `botCheckToken` field; and `readCustomerSession`. Another bot-check provider would be an additive member of `botCheck`'s union; renaming `"turnstile"` or `botCheckToken` is breaking. The server half's `limiter`, `botCheck` and `clientIp` are required in every environment, and `createCustomerHandler` throws when one is missing.
13
+ What the changelog treats as breaking to rename or remove: the exports of `.` and `./server` and the stylesheet `./style.css`; the props below, including `brand: {name, logo}`, `botCheck: {provider: "turnstile", siteKey}` and the `screen` values `businesses`, `{businessId}`, `{businessId, eventTypeId}`, `bookings`, `passes` and `details` (a new value is additive; renaming or removing one, or changing the default `businesses`, is breaking); the nine `--msm-customer-*` properties ([Theming](#theming)); the server half's options and routes, including the `botCheckToken` field; and `readCustomerSession`. Another bot-check provider would be an additive member of `botCheck`'s union; renaming `"turnstile"` or `botCheckToken` is breaking. The server half's `clientIp` is required in every environment, and `createCustomerHandler` throws without it.
14
14
 
15
15
  ## The screens
16
16
 
@@ -77,14 +77,7 @@ A Fetch API handler, `Request` in and `Response` out, for the routes the screens
77
77
 
78
78
  ```ts
79
79
  // app/msm/[...path]/route.ts
80
- import {
81
- createCustomerHandler,
82
- redisLimiterStore,
83
- turnstile,
84
- } from "@msm-platform/customer-react/server";
85
- import { createClient } from "redis";
86
-
87
- const redis = await createClient({ url: process.env.REDIS_URL }).connect();
80
+ import { createCustomerHandler } from "@msm-platform/customer-react/server";
88
81
 
89
82
  const handler = createCustomerHandler({
90
83
  basePath: "/msm",
@@ -92,8 +85,6 @@ const handler = createCustomerHandler({
92
85
  clientId: process.env.MSM_CLIENT_ID!,
93
86
  clientSecret: process.env.MSM_CLIENT_SECRET!,
94
87
  sessionKeys: process.env.MSM_SESSION_KEYS!.split(","),
95
- limiter: redisLimiterStore(redis),
96
- botCheck: turnstile({ secretKey: process.env.TURNSTILE_SECRET_KEY! }),
97
88
  clientIp: (request) => yourTrustedClientIp(request),
98
89
  });
99
90
  export {
@@ -110,11 +101,9 @@ export {
110
101
  | `basePath` | Where the route is mounted; the screens' `basePath`. |
111
102
  | `engineUrl`, `clientId`, `clientSecret` | The engine and the partner's website application client. It calls the engine through `@msm-platform/customer-sdk` in server mode, so the secret never leaves this server. |
112
103
  | `sessionKeys` | One key or a list, each at least 32 bytes (`openssl rand -base64 32`). The first encrypts the cookie and every one decrypts, so to rotate put the new key first and keep the old one until its cookies expire. |
113
- | `limiter` | Required. A `LimiterStore`: `redisLimiterStore(redis)` for a node-redis client, or `memoryLimiterStore()` for development and tests (it counts per process). |
114
- | `botCheck` | Required. `turnstile({ secretKey })`, or any `(token, { ip, request }) => Promise<boolean>`. |
115
- | `clientIp` | Required. The client's address, from what your platform guarantees. Return null when unknown, which refuses code requests. |
116
- | `limits` | Code requests per phone (default 5 per 15 minutes) and per IP (default 5 per 10 minutes), counted together for sign-in and registration. |
117
- | `limiterPrefix` | The limiter's key prefix, default `msm:customer:limit:`, for a Redis shared with other apps. |
104
+ | `clientIp` | Required. The visitor's address, from what your platform guarantees; the engine limits code requests by it. Return null when unknown, which refuses code requests. |
105
+
106
+ MSM owns your website's Cloudflare Turnstile widget and keeps its secret: the engine verifies the screens' token with it and limits code requests per address and per phone, so this server needs no Redis and no Turnstile secret. MSM hands over the widget's site key, which is public, with the client credentials.
118
107
 
119
108
  **Never trust a header the client can set for `clientIp`.** The leftmost `X-Forwarded-For` entry is whatever the client sent, so anyone could pick a fresh address for every request. Use your platform's own client address, or the entry your trusted proxy appends, counted from the right.
120
109
 
@@ -122,16 +111,14 @@ export {
122
111
 
123
112
  Every route needs the `X-MSM-BFF: 1` header the screens send. Browsers send a custom header cross-origin only after a CORS preflight, which the handler never approves, so another site cannot call these routes with the customer's cookie.
124
113
 
125
- | Route | Behaviour |
126
- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
127
- | `POST auth/initiate` `{phone, botCheckToken}` | Sends a sign-in code. Before the engine is called: the phone must be E.164, then the bot check (403 `BotCheckFailed`, or 503 `BotCheckUnavailable` when it cannot be made), the per-IP limit and the per-phone limit (429 `TooManyAttempts` with `Retry-After`). A limiter error or a wait over 1 s refuses with 503 `LimiterUnavailable`. |
128
- | `POST auth/register/initiate` `{phone, name, botCheckToken}` | Sends a registration code, with the same checks and the same counters. |
129
- | `POST auth/login`, `POST auth/register` `{challenge, code}` | Redeems the code exactly once, never retried, and sets the session cookie. Returns `{sessionKey}`, the session's ID. |
130
- | `GET auth/session` | `{sessionKey}`, or 401. |
131
- | `POST auth/logout` | Revokes the session at the engine and clears the cookie. |
132
- | `/engine/web/*` | Proxied to the engine's `/web`, except `/web/identity/*`, with the client's credentials and the cookie's session. Only `Accept`, `Content-Type` and `Accept-Language` pass from the browser. A 401, or a successful `DELETE /engine/web/me/sessions` (sign out everywhere), clears the cookie. |
133
-
134
- Limiter keys hold SHA-256 hashes of the phone (as E.164) and the address (IPv4 as is, IPv6 by its /64), never the values themselves.
114
+ | Route | Behaviour |
115
+ | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
116
+ | `POST auth/initiate` `{phone, botCheckToken}` | Asks the engine for a sign-in code with the token and `clientIp(request)`; without an address it refuses with 503 `ClientIpUnavailable` and calls nothing. The engine checks the token (403 `BotCheckFailed`, or 503 `BotCheckUnavailable` when it cannot), then counts the address (429 `TooManyAttempts` with `Retry-After`, or 503 `LimiterUnavailable`) and the phone; its refusals pass through with their status, code and `Retry-After`. |
117
+ | `POST auth/register/initiate` `{phone, name, botCheckToken}` | Asks for a registration code the same way, against the same counts. |
118
+ | `POST auth/login`, `POST auth/register` `{challenge, code}` | Redeems the code exactly once, never retried, and sets the session cookie. Returns `{sessionKey}`, the session's ID. |
119
+ | `GET auth/session` | `{sessionKey}`, or 401. |
120
+ | `POST auth/logout` | Revokes the session at the engine and clears the cookie. |
121
+ | `/engine/web/*` | Proxied to the engine's `/web`, except `/web/identity/*`, with the client's credentials and the cookie's session. Only `Accept`, `Content-Type` and `Accept-Language` pass from the browser. A 401, or a successful `DELETE /engine/web/me/sessions` (sign out everywhere), clears the cookie. |
135
122
 
136
123
  ### Sessions
137
124
 
@@ -143,6 +130,6 @@ The session lives in no store: the cookie `__Host-msm_customer_session` (HttpOnl
143
130
 
144
131
  Every string comes from the typed catalog in `src/i18n.ts` (`t(key)`); a new locale is a `Messages` object, which TypeScript makes supply every key. Dates and times use `Intl` in `en-GB` and the business's timezone from `GET /web/businesses`, or the browser's for a business that list does not include.
145
132
 
146
- Tests: `pnpm exec vitest run packages/customer-react` from the root. The Redis store's tests use `REDIS_URL` when set, otherwise a throwaway `redis-server`.
133
+ Tests: `pnpm exec vitest run packages/customer-react` from the root.
147
134
 
148
135
  The build bundles the private `@msm-platform/ui` (the phone input) into `dist/index.js` and its styles into `dist/style.css`; `ui` is a devDependency and the packed manifest has none. `pnpm test:packages` installs the packed package outside the workspace beside only the customer SDK and React. Releases follow the repository's [release runbook](https://github.com/Sveittur/msm-platform/blob/main/docs/runbooks/customer-react.md), and every release's changes are in [CHANGELOG.md](CHANGELOG.md).
@@ -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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@msm-platform/customer-react",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "MSM's customer screens for React, and their server half for a partner's server",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@msm-platform/customer-sdk": "^0.1.1",
34
+ "@msm-platform/customer-sdk": "^0.2.0",
35
35
  "libphonenumber-js": "^1.13.15"
36
36
  },
37
37
  "peerDependencies": {
@@ -1,44 +0,0 @@
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;
@@ -1,22 +0,0 @@
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;