@msm-platform/customer-react 0.3.1 → 0.4.1

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/portal.d.ts CHANGED
@@ -14,7 +14,7 @@ export declare function useCustomerPortal(options: {
14
14
  }): {
15
15
  basePath: string;
16
16
  sessionKey: import("./session").SessionState;
17
- notice: "app.loading" | "app.loadFailed" | "app.retry" | "app.signedOut" | "app.signedOutEverywhere" | "nav.label" | "nav.book" | "nav.signIn" | "nav.bookings" | "nav.passes" | "nav.details" | "nav.signOut" | "signIn.heading" | "signIn.intro" | "signIn.toRegister" | "register.heading" | "register.intro" | "register.name" | "register.toSignIn" | "signIn.phone" | "signIn.codeSent" | "signIn.code" | "signIn.sendCode" | "signIn.submit" | "register.submit" | "signIn.wait" | "signIn.differentNumber" | "signIn.cancel" | "signIn.error.tooMany" | "signIn.error.tooManyLater" | "signIn.error.paused" | "signIn.error.pausedLater" | "signIn.error.destination" | "signIn.error.badCode" | "register.error.badCode" | "signIn.error.invalid" | "signIn.error.refused" | "signIn.error.unreachable" | "signIn.error.failed" | "signIn.error.botCheck" | "signIn.error.botCheckUnavailable" | "signIn.error.notConfigured" | "wait.seconds.one" | "wait.seconds.other" | "wait.minutes.one" | "wait.minutes.other" | "wait.hours.one" | "wait.hours.other" | "bookings.heading" | "bookings.period" | "bookings.upcoming" | "bookings.past" | "bookings.emptyUpcoming" | "bookings.emptyPast" | "bookings.more" | "bookings.when" | "bookings.cancelled" | "bookings.cancelledLate" | "bookings.attended" | "bookings.noShow" | "bookings.lateFrom" | "bookings.started" | "bookings.cancel" | "bookings.confirmHeading" | "bookings.confirmLate" | "bookings.confirmCredit" | "bookings.confirm" | "bookings.keep" | "bookings.cancelling" | "bookings.doneOnTime" | "bookings.doneLate" | "bookings.cancelFailed" | "bookings.gone" | "businesses.heading" | "businesses.intro" | "businesses.empty" | "businesses.open" | "business.all" | "business.notFound" | "business.types" | "business.allTypes" | "business.resources" | "business.anyResource" | "business.typeMissing" | "business.minutes" | "business.week" | "business.previousWeek" | "business.nextWeek" | "business.weekOf" | "business.empty" | "business.seatsLeft.one" | "business.seatsLeft.other" | "business.full" | "business.openTime" | "business.with" | "business.book" | "book.heading" | "book.signInFirst" | "book.back" | "book.reserving" | "book.heldUntil" | "book.confirm" | "book.confirming" | "book.booked" | "book.toBookings" | "book.done" | "book.close" | "book.chooseType" | "book.noTypes" | "book.seeAll" | "book.chooseResource" | "book.anyResource" | "book.anyResourceHint" | "book.toTypes" | "book.otherResource" | "book.reserveAgain" | "book.full" | "book.slotTaken" | "book.limit" | "book.expired" | "book.notAllowed" | "book.unavailable" | "book.refused" | "book.failed" | "passes.heading" | "passes.empty" | "passes.unlimited" | "passes.credits" | "passes.validFrom" | "passes.validRange" | "passes.expired" | "details.heading" | "details.name" | "details.phone" | "details.email" | "details.none" | "details.readOnly" | "details.save" | "details.saving" | "details.saved" | "details.saveFailed" | "details.signOutEverywhere" | "details.signOutEverywhereHint" | "details.signOutEverywhereFailed" | undefined;
17
+ notice: "app.loading" | "app.loadFailed" | "app.retry" | "app.signedOut" | "app.signedOutEverywhere" | "image.logo" | "nav.label" | "nav.book" | "nav.signIn" | "nav.bookings" | "nav.passes" | "nav.details" | "nav.signOut" | "signIn.heading" | "signIn.intro" | "register.intro" | "register.name" | "signIn.phone" | "signIn.codeSent" | "signIn.code" | "signIn.sendCode" | "signIn.submit" | "register.submit" | "signIn.wait" | "signIn.differentNumber" | "signIn.cancel" | "signIn.error.tooMany" | "signIn.error.tooManyLater" | "signIn.error.paused" | "signIn.error.pausedLater" | "signIn.error.destination" | "signIn.error.badCode" | "register.error.expired" | "register.error.name" | "signIn.error.invalid" | "signIn.error.refused" | "signIn.error.unreachable" | "signIn.error.failed" | "signIn.error.botCheck" | "signIn.error.botCheckUnavailable" | "signIn.error.notConfigured" | "wait.seconds.one" | "wait.seconds.other" | "wait.minutes.one" | "wait.minutes.other" | "wait.hours.one" | "wait.hours.other" | "bookings.heading" | "bookings.period" | "bookings.upcoming" | "bookings.past" | "bookings.emptyUpcoming" | "bookings.emptyPast" | "bookings.more" | "bookings.when" | "bookings.cancelled" | "bookings.cancelledLate" | "bookings.attended" | "bookings.noShow" | "bookings.lateFrom" | "bookings.started" | "bookings.cancel" | "bookings.confirmHeading" | "bookings.confirmLate" | "bookings.confirmCredit" | "bookings.confirm" | "bookings.keep" | "bookings.cancelling" | "bookings.doneOnTime" | "bookings.doneLate" | "bookings.cancelFailed" | "bookings.gone" | "businesses.heading" | "businesses.intro" | "businesses.empty" | "businesses.open" | "business.all" | "business.notFound" | "business.types" | "business.allTypes" | "business.resources" | "business.anyResource" | "business.typeMissing" | "business.minutes" | "business.week" | "business.previousWeek" | "business.nextWeek" | "business.weekOf" | "business.empty" | "business.seatsLeft.one" | "business.seatsLeft.other" | "business.full" | "business.openTime" | "business.with" | "business.instructor" | "business.room" | "business.guests" | "business.book" | "book.heading" | "book.signInFirst" | "book.back" | "book.reserving" | "book.heldUntil" | "book.confirm" | "book.confirming" | "book.booked" | "book.toBookings" | "book.done" | "book.close" | "book.chooseType" | "book.noTypes" | "book.seeAll" | "book.chooseResource" | "book.anyResource" | "book.anyResourceHint" | "book.toTypes" | "book.otherResource" | "book.reserveAgain" | "book.full" | "book.slotTaken" | "book.limit" | "book.expired" | "book.notAllowed" | "book.unavailable" | "book.refused" | "book.failed" | "passes.heading" | "passes.empty" | "passes.unlimited" | "passes.credits" | "passes.validFrom" | "passes.validRange" | "passes.expired" | "details.heading" | "details.name" | "details.phone" | "details.email" | "details.none" | "details.readOnly" | "details.save" | "details.saving" | "details.saved" | "details.saveFailed" | "details.signOutEverywhere" | "details.signOutEverywhereHint" | "details.signOutEverywhereFailed" | undefined;
18
18
  portal: Portal;
19
19
  signedInAs: (next: string) => void;
20
20
  };
@@ -9,11 +9,32 @@ type Catalog = ReturnType<typeof useCatalog>;
9
9
  export declare function useCatalog(businessId: string): {
10
10
  business: {
11
11
  address: string | null;
12
+ brandColor: string | null;
13
+ cover: {
14
+ height: number;
15
+ small: {
16
+ height: number;
17
+ url: string;
18
+ width: number;
19
+ };
20
+ url: string;
21
+ width: number;
22
+ } | null;
23
+ description: string | null;
12
24
  displayName: string;
13
25
  email: string | null;
14
26
  id: string;
15
27
  latitude: number | null;
16
- logoAssetId: string | null;
28
+ logo: {
29
+ height: number;
30
+ small: {
31
+ height: number;
32
+ url: string;
33
+ width: number;
34
+ };
35
+ url: string;
36
+ width: number;
37
+ } | null;
17
38
  longitude: number | null;
18
39
  phone: string | null;
19
40
  timezone: string;
@@ -25,12 +46,31 @@ export declare function useCatalog(businessId: string): {
25
46
  displayName: string;
26
47
  durationMinutes: number;
27
48
  id: string;
28
- imageAssetId: string | null;
49
+ image: {
50
+ height: number;
51
+ small: {
52
+ height: number;
53
+ url: string;
54
+ width: number;
55
+ };
56
+ url: string;
57
+ width: number;
58
+ } | null;
29
59
  requiresAccess: boolean;
30
60
  resources: {
31
61
  description: string | null;
32
62
  displayName: string;
33
63
  id: string;
64
+ image: {
65
+ height: number;
66
+ small: {
67
+ height: number;
68
+ url: string;
69
+ width: number;
70
+ };
71
+ url: string;
72
+ width: number;
73
+ } | null;
34
74
  }[];
35
75
  timeSlotBooking: boolean;
36
76
  }[] | undefined;
@@ -47,6 +87,16 @@ export declare function resourcesOf(types: EventType[]): {
47
87
  description: string | null;
48
88
  displayName: string;
49
89
  id: string;
90
+ image: {
91
+ height: number;
92
+ small: {
93
+ height: number;
94
+ url: string;
95
+ width: number;
96
+ };
97
+ url: string;
98
+ width: number;
99
+ } | null;
50
100
  }[];
51
101
  /** The filters the business screen shows, when its host drives them. */
52
102
  export interface BusinessFilter {
@@ -67,7 +117,11 @@ export declare function Business(props: {
67
117
  onFilter?: ((filter: BusinessFilter) => void) | undefined;
68
118
  onChoose: (business: BusinessDto, candidate: Candidate) => void;
69
119
  }): import("react").JSX.Element | undefined;
70
- /** An event type's name, description and length, above its times. */
120
+ /** The business's logo beside its name and address, above its screen. */
121
+ export declare function BusinessHead({ business }: {
122
+ business: BusinessDto;
123
+ }): import("react").JSX.Element;
124
+ /** An event type's image, name, description and length, above its times. */
71
125
  export declare function TypeDetails({ type }: {
72
126
  type: EventType;
73
127
  }): import("react").JSX.Element;
@@ -77,4 +131,12 @@ export declare function Availability(props: {
77
131
  resourceId?: string | undefined;
78
132
  onChoose: (candidate: Candidate) => void;
79
133
  }): import("react").JSX.Element;
134
+ /**
135
+ * Who and where: a slot's resource when the customer chose it; an event's
136
+ * first person as its instructor, its places as the room and its other people
137
+ * as guest instructors, each in the event's order (#404).
138
+ */
139
+ export declare function CandidateResources({ candidate }: {
140
+ candidate: Candidate;
141
+ }): import("react").JSX.Element | null;
80
142
  export {};
@@ -27,12 +27,16 @@ export interface CustomerHandlerOptions {
27
27
  * The routes MSM's customer screens call under their `basePath`, for one
28
28
  * catch-all route such as `app/msm/[...path]/route.ts`:
29
29
  *
30
- * - `POST auth/initiate` `{phone, botCheckToken}` and
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;
34
- * - `POST auth/login` and `POST auth/register` `{challenge, code}` redeem it
35
- * once, never retried, and set the encrypted session cookie;
30
+ * - `POST auth/initiate` `{phone, botCheckToken}` asks the engine for a code
31
+ * with the token and `clientIp(request)`; the engine checks the bot check
32
+ * and limits per address and per phone;
33
+ * - `POST auth/login` `{challenge, code}` redeems it once, never retried.
34
+ * A customer gets the encrypted session cookie. A phone the engine asks to
35
+ * register gets it too when no name is needed, since the handler completes
36
+ * the registration at once; otherwise the answer is `nameRequired` and the
37
+ * engine's registration ticket goes into its own encrypted cookie;
38
+ * - `POST auth/register` `{name}` completes that registration with the
39
+ * ticket from the cookie and sets the session cookie;
36
40
  * - `GET auth/session` and `POST auth/logout`;
37
41
  * - `/engine/web/*`, except `/web/identity/*`, proxied to the engine with the
38
42
  * client's credentials and the cookie's session.
@@ -13,13 +13,27 @@ export interface CustomerSession {
13
13
  */
14
14
  export declare function sessionKeyList(keys: string | readonly string[]): string[];
15
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.
16
+ * The cookie that holds a pending registration's encrypted ticket, between
17
+ * a code the engine answered with `nameRequired` and the customer's name.
18
18
  */
19
+ export declare const customerRegistrationCookie = "__Host-msm_customer_registration";
20
+ /** A pending registration, as its cookie holds it. Server-side only. */
21
+ export interface PendingRegistration {
22
+ registrationTicket: string;
23
+ /** When the engine stops accepting the ticket (ISO 8601). */
24
+ expiresAt: string;
25
+ }
26
+ /** The session cookie's cipher. */
19
27
  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>;
28
+ seal(value: CustomerSession): Promise<string>;
29
+ /** The cookie's value, or null when no key opens it or it has expired. */
30
+ open(cookie: string | undefined): Promise<CustomerSession | null>;
31
+ };
32
+ /** The pending registration cookie's cipher. */
33
+ export declare function registrationCipher(keys: readonly string[]): {
34
+ seal(value: PendingRegistration): Promise<string>;
35
+ /** The cookie's value, or null when no key opens it or it has expired. */
36
+ open(cookie: string | undefined): Promise<PendingRegistration | null>;
23
37
  };
24
38
  /**
25
39
  * The signed-in customer's session for the partner's own server code, such as
package/dist/server.js CHANGED
@@ -7,8 +7,9 @@ function a(e) {
7
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`.");
8
8
  return t;
9
9
  }
10
- function o(e) {
11
- let t, a = () => t ??= Promise.all(e.map(async (e) => {
10
+ var o = "__Host-msm_customer_registration";
11
+ function s(e, t, n) {
12
+ let a, o = () => a ??= Promise.all(e.map(async (e) => {
12
13
  let t = await crypto.subtle.importKey("raw", r.encode(e), "HKDF", !1, ["deriveKey"]);
13
14
  return crypto.subtle.deriveKey({
14
15
  name: "HKDF",
@@ -19,62 +20,74 @@ function o(e) {
19
20
  name: "AES-GCM",
20
21
  length: 256
21
22
  }, !1, ["encrypt", "decrypt"]);
22
- })), o = r.encode(n);
23
+ })), s = r.encode(t);
23
24
  return {
24
25
  async seal(e) {
25
- let [t] = await a(), n = crypto.getRandomValues(new Uint8Array(i)), s = await crypto.subtle.encrypt({
26
+ let [t] = await o(), a = crypto.getRandomValues(new Uint8Array(i)), c = await crypto.subtle.encrypt({
26
27
  name: "AES-GCM",
27
- iv: n,
28
- additionalData: o
29
- }, t, r.encode(JSON.stringify({
30
- sessionId: e.sessionId,
31
- sessionToken: e.sessionToken,
32
- expiresAt: e.expiresAt
33
- }))), c = new Uint8Array(i + s.byteLength);
34
- return c.set(n), c.set(new Uint8Array(s), i), l(c);
28
+ iv: a,
29
+ additionalData: s
30
+ }, t, r.encode(JSON.stringify(n(e)))), l = new Uint8Array(i + c.byteLength);
31
+ return l.set(a), l.set(new Uint8Array(c), i), m(l);
35
32
  },
36
33
  async open(e) {
37
- let t = e ? u(e) : null;
34
+ let t = e ? h(e) : null;
38
35
  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()) {
36
+ let r = t.subarray(0, i), a = t.subarray(i);
37
+ for (let e of await o()) {
41
38
  let t;
42
39
  try {
43
40
  t = await crypto.subtle.decrypt({
44
41
  name: "AES-GCM",
45
- iv: n,
46
- additionalData: o
47
- }, e, r);
42
+ iv: r,
43
+ additionalData: s
44
+ }, e, a);
48
45
  } catch {
49
46
  continue;
50
47
  }
51
- let i = c(new TextDecoder().decode(t));
48
+ let i = d(new TextDecoder().decode(t), n);
52
49
  return i && Date.parse(i.expiresAt) > Date.now() ? i : null;
53
50
  }
54
51
  return null;
55
52
  }
56
53
  };
57
54
  }
58
- function s(e, t) {
59
- return o(a(t.sessionKeys)).open(e);
60
- }
61
55
  function c(e) {
62
- try {
63
- let t = JSON.parse(e);
64
- if (typeof t.sessionId == "string" && typeof t.sessionToken == "string" && typeof t.expiresAt == "string") return {
65
- sessionId: t.sessionId,
66
- sessionToken: t.sessionToken,
67
- expiresAt: t.expiresAt
68
- };
69
- } catch {}
70
- return null;
56
+ return s(e, n, f);
71
57
  }
72
58
  function l(e) {
59
+ return s(e, o, p);
60
+ }
61
+ function u(e, t) {
62
+ return c(a(t.sessionKeys)).open(e);
63
+ }
64
+ function d(e, t) {
65
+ try {
66
+ let n = JSON.parse(e);
67
+ return typeof n == "object" && n ? t(n) : null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+ function f(e) {
73
+ return typeof e.sessionId == "string" && typeof e.sessionToken == "string" && typeof e.expiresAt == "string" ? {
74
+ sessionId: e.sessionId,
75
+ sessionToken: e.sessionToken,
76
+ expiresAt: e.expiresAt
77
+ } : null;
78
+ }
79
+ function p(e) {
80
+ return typeof e.registrationTicket == "string" && typeof e.expiresAt == "string" ? {
81
+ registrationTicket: e.registrationTicket,
82
+ expiresAt: e.expiresAt
83
+ } : null;
84
+ }
85
+ function m(e) {
73
86
  let t = "";
74
87
  for (let n of e) t += String.fromCharCode(n);
75
88
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
76
89
  }
77
- function u(e) {
90
+ function h(e) {
78
91
  if (!/^[A-Za-z0-9_-]+$/.test(e)) return null;
79
92
  try {
80
93
  let t = atob(e.replace(/-/g, "+").replace(/_/g, "/"));
@@ -84,18 +97,18 @@ function u(e) {
84
97
  }
85
98
  }
86
99
  // src/server/index.ts
87
- var d = 1e4, f = 3e4, p = 1048576, m = /* @__PURE__ */ new Set([
100
+ var g = 1e4, _ = 3e4, v = 1048576, y = /* @__PURE__ */ new Set([
88
101
  "GET",
89
102
  "HEAD",
90
103
  "POST",
91
104
  "PUT",
92
105
  "PATCH",
93
106
  "DELETE"
94
- ]), h = [
107
+ ]), b = [
95
108
  "accept",
96
109
  "content-type",
97
110
  "accept-language"
98
- ], g = "Path=/; HttpOnly; Secure; SameSite=Lax", _ = class extends Error {
111
+ ], x = "Path=/; HttpOnly; Secure; SameSite=Lax", S = class extends Error {
99
112
  status;
100
113
  code;
101
114
  retryAfterSeconds;
@@ -103,72 +116,87 @@ var d = 1e4, f = 3e4, p = 1048576, m = /* @__PURE__ */ new Set([
103
116
  super(n), this.status = e, this.code = t, this.retryAfterSeconds = r;
104
117
  }
105
118
  };
106
- function v(r) {
119
+ function C(r) {
107
120
  if (typeof r.clientIp != "function") throw Error("customer-react/server: clientIp is required.");
108
121
  let i = r.basePath.replace(/\/$/, "");
109
122
  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({
123
+ let s = a(r.sessionKeys), u = c(s), d = l(s), f = t({
111
124
  baseUrl: r.engineUrl,
112
125
  clientId: r.clientId,
113
126
  clientSecret: r.clientSecret,
114
127
  ...r.fetch && { fetch: r.fetch }
115
- }), l = () => AbortSignal.timeout(d), u = `${n}=; ${g}; Max-Age=0`;
116
- async function p(e) {
128
+ }), p = () => AbortSignal.timeout(g), m = `${n}=; ${x}; Max-Age=0`, h = `${o}=; ${x}; Max-Age=0`;
129
+ async function v(e) {
117
130
  let t = new URL(e.url);
118
- if (t.pathname !== i && !t.pathname.startsWith(`${i}/`)) throw new _(404, "NotFound", "Not found.");
131
+ if (t.pathname !== i && !t.pathname.startsWith(`${i}/`)) throw new S(404, "NotFound", "Not found.");
119
132
  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}`;
124
- if (o === "POST /auth/initiate") {
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));
133
- }
134
- if (o === "POST /auth/register/initiate") {
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", {
133
+ if (e.headers.get("x-msm-bff") !== "1") throw new S(403, "BffHeaderRequired", "Missing X-MSM-BFF header.");
134
+ let a = await u.open(O(e, n));
135
+ if (r.startsWith("/engine/")) return N(e, t, r, a);
136
+ let s = `${e.method} ${r}`;
137
+ if (s === "POST /auth/initiate") {
138
+ let t = await j(e, ["phone", "botCheckToken"]), n = await M(e, t);
139
+ return E(200, await f.POST("/web/identity/initiateLogin", {
141
140
  body: {
142
141
  phone: t.phone,
143
- name: t.name,
144
142
  ...n
145
143
  },
146
- signal: l()
147
- }).then(b));
144
+ signal: p()
145
+ }).then(T));
148
146
  }
149
- if (o === "POST /auth/login" || o === "POST /auth/register") {
150
- let { challenge: t, code: i } = await T(e, ["challenge", "code"]), o = await c.POST(r === "/auth/login" ? "/web/identity/customerLogin" : "/web/identity/registerCustomer", {
147
+ if (s === "POST /auth/login") {
148
+ let { challenge: t, code: n } = await j(e, ["challenge", "code"]), r = await f.POST("/web/identity/customerLogin", {
151
149
  body: {
152
150
  challenge: t,
153
- code: i
151
+ code: n
154
152
  },
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)}` });
153
+ signal: p()
154
+ }).then(T);
155
+ if (r.result === "session") return C(a, r);
156
+ let { registrationTicket: i } = r;
157
+ return r.nameRequired ? E(200, { result: "nameRequired" }, { "set-cookie": `${o}=${await d.seal({
158
+ registrationTicket: i,
159
+ expiresAt: r.registrationExpiresAt
160
+ })}; ${x}; Max-Age=${D(r.registrationExpiresAt)}` }) : C(a, await A({ registrationTicket: i }));
160
161
  }
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, {
162
+ if (s === "POST /auth/register") {
163
+ let t = await d.open(O(e, o));
164
+ if (!t) return E(401, {
165
+ code: "NotAuthenticated",
166
+ message: "No registration is pending."
167
+ }, { "set-cookie": h });
168
+ let { name: n } = await j(e, ["name"]);
169
+ return C(a, await A({
170
+ registrationTicket: t.registrationTicket,
171
+ name: n
172
+ }));
173
+ }
174
+ if (s === "GET /auth/session") return a ? E(200, { sessionKey: a.sessionId }) : F();
175
+ if (s === "POST /auth/logout") return a && await P(a), new Response(null, {
163
176
  status: 204,
164
- headers: {
165
- "set-cookie": u,
166
- "cache-control": "no-store"
167
- }
177
+ headers: [
178
+ ["set-cookie", m],
179
+ ["set-cookie", h],
180
+ ["cache-control", "no-store"]
181
+ ]
168
182
  });
169
- throw new _(404, "NotFound", "Not found.");
183
+ throw new S(404, "NotFound", "Not found.");
184
+ }
185
+ async function C(e, t) {
186
+ e && await P(e);
187
+ let r = await u.seal(t);
188
+ return E(200, {
189
+ result: "session",
190
+ sessionKey: t.sessionId
191
+ }, [["set-cookie", `${n}=${r}; ${x}; Max-Age=${D(t.expiresAt)}`], ["set-cookie", h]]);
170
192
  }
171
- async function v(e, t) {
193
+ function A(e) {
194
+ return f.POST("/web/identity/completeRegistration", {
195
+ body: e,
196
+ signal: p()
197
+ }).then(T);
198
+ }
199
+ async function M(e, t) {
172
200
  let n;
173
201
  try {
174
202
  n = await r.clientIp(e);
@@ -176,86 +204,86 @@ function v(r) {
176
204
  n = null;
177
205
  }
178
206
  let i = n?.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
179
- if (!i) throw new _(503, "ClientIpUnavailable", "The client's address is unknown.");
207
+ if (!i) throw new S(503, "ClientIpUnavailable", "The client's address is unknown.");
180
208
  return {
181
209
  botCheckToken: t.botCheckToken,
182
210
  clientIp: i
183
211
  };
184
212
  }
185
- async function w(t, n, r, i) {
213
+ async function N(t, n, r, i) {
186
214
  let a = r.slice(7);
187
- if (!y(a) || !m.has(t.method)) throw new _(404, "NotFound", "Not found.");
215
+ if (!w(a) || !y.has(t.method)) throw new S(404, "NotFound", "Not found.");
188
216
  let o = new Headers();
189
- for (let e of h) {
217
+ for (let e of b) {
190
218
  let n = t.headers.get(e);
191
219
  n && o.set(e, n);
192
220
  }
193
221
  i && o.set("x-session-token", i.sessionToken);
194
- let s = t.method !== "GET" && t.method !== "HEAD" ? await C(t) : void 0, l;
222
+ let s = t.method !== "GET" && t.method !== "HEAD" ? await k(t) : void 0, c;
195
223
  try {
196
- l = (await c.request(t.method.toLowerCase(), `${a}${n.search}`, {
224
+ c = (await f.request(t.method.toLowerCase(), `${a}${n.search}`, {
197
225
  headers: o,
198
226
  ...s && s.byteLength > 0 && { body: s },
199
227
  bodySerializer: (e) => e,
200
228
  parseAs: "stream",
201
229
  redirect: "manual",
202
- signal: AbortSignal.timeout(f)
230
+ signal: AbortSignal.timeout(_)
203
231
  })).response;
204
232
  } catch (t) {
205
233
  if (!(t instanceof e)) throw t;
206
- l = t.response;
234
+ c = t.response;
207
235
  }
208
- let d = l.status === 401 || l.ok && t.method === "DELETE" && a === "/web/me/sessions" && i !== null, p = new Headers({ "cache-control": "no-store" });
236
+ let l = c.status === 401 || c.ok && t.method === "DELETE" && a === "/web/me/sessions" && i !== null, u = new Headers({ "cache-control": "no-store" });
209
237
  for (let e of ["content-type", "retry-after"]) {
210
- let t = l.headers.get(e);
211
- t && p.set(e, t);
238
+ let t = c.headers.get(e);
239
+ t && u.set(e, t);
212
240
  }
213
- d && p.set("set-cookie", u);
214
- let g = t.method === "HEAD" || [
241
+ l && u.set("set-cookie", m);
242
+ let d = t.method === "HEAD" || [
215
243
  204,
216
244
  205,
217
245
  304
218
- ].includes(l.status);
219
- return new Response(g ? null : await l.arrayBuffer(), {
220
- status: l.status,
221
- headers: p
246
+ ].includes(c.status);
247
+ return new Response(d ? null : await c.arrayBuffer(), {
248
+ status: c.status,
249
+ headers: u
222
250
  });
223
251
  }
224
- async function E(e) {
225
- await c.POST("/web/identity/logout", {
252
+ async function P(e) {
253
+ await f.POST("/web/identity/logout", {
226
254
  body: { sessionToken: e.sessionToken },
227
- signal: l()
255
+ signal: p()
228
256
  }).catch(() => {});
229
257
  }
230
- function D() {
231
- return x(401, {
258
+ function F() {
259
+ return E(401, {
232
260
  code: "NotAuthenticated",
233
261
  message: "Sign in again."
234
- }, { "set-cookie": u });
262
+ }, { "set-cookie": m });
235
263
  }
236
264
  return async function(t) {
237
265
  try {
238
- return await p(t);
266
+ return await v(t);
239
267
  } catch (t) {
240
- if (t instanceof _) return x(t.status, {
268
+ if (t instanceof S) return E(t.status, {
241
269
  code: t.code,
242
270
  message: t.message
243
271
  }, t.retryAfterSeconds ? { "retry-after": String(t.retryAfterSeconds) } : {});
244
272
  if (t instanceof e && (t.status >= 400 && t.status < 500 || t.status === 503 && t.code)) {
245
- let e = t.response.headers.get("retry-after");
246
- return x(t.status, {
273
+ let e = new Headers(), n = t.response.headers.get("retry-after");
274
+ return n && e.set("retry-after", n), t.status === 401 && e.set("set-cookie", h), E(t.status, {
247
275
  code: t.code ?? "EngineRejected",
248
276
  message: t.message
249
- }, e ? { "retry-after": e } : {});
277
+ }, e);
250
278
  }
251
- return x(502, {
279
+ return E(502, {
252
280
  code: "EngineUnavailable",
253
281
  message: "The engine could not complete the request."
254
282
  });
255
283
  }
256
284
  };
257
285
  }
258
- function y(e) {
286
+ function w(e) {
259
287
  if (/%2f|%5c|\/\//i.test(e)) return !1;
260
288
  let t;
261
289
  try {
@@ -265,51 +293,49 @@ function y(e) {
265
293
  }
266
294
  return !/(^|\/)\.\.?(\/|$)|\\/.test(t) && /^\/web\//.test(t) && !/^\/web\/identity(\/|$)/i.test(t);
267
295
  }
268
- var b = ({ data: e }) => {
296
+ var T = ({ data: e }) => {
269
297
  if (e === void 0) throw Error("Engine returned no body.");
270
298
  return e;
271
299
  };
272
- function x(e, t, n = {}) {
273
- return new Response(JSON.stringify(t), {
300
+ function E(e, t, n = {}) {
301
+ let r = new Headers(n);
302
+ return r.set("content-type", "application/json"), r.set("cache-control", "no-store"), new Response(JSON.stringify(t), {
274
303
  status: e,
275
- headers: {
276
- "content-type": "application/json",
277
- "cache-control": "no-store",
278
- ...n
279
- }
304
+ headers: r
280
305
  });
281
306
  }
282
- function S(e) {
283
- for (let t of e.headers.get("cookie")?.split(";") ?? []) {
284
- let e = t.indexOf("=");
285
- if (e > 0 && t.slice(0, e).trim() === "__Host-msm_customer_session") return t.slice(e + 1).trim() || void 0;
307
+ var D = (e) => Math.max(0, Math.floor((Date.parse(e) - Date.now()) / 1e3));
308
+ function O(e, t) {
309
+ for (let n of e.headers.get("cookie")?.split(";") ?? []) {
310
+ let e = n.indexOf("=");
311
+ if (e > 0 && n.slice(0, e).trim() === t) return n.slice(e + 1).trim() || void 0;
286
312
  }
287
313
  }
288
- async function C(e) {
289
- if (Number(e.headers.get("content-length")) > p) throw w();
314
+ async function k(e) {
315
+ if (Number(e.headers.get("content-length")) > v) throw A();
290
316
  if (!e.body) return /* @__PURE__ */ new Uint8Array();
291
317
  let t = e.body.getReader(), n = [], r = 0;
292
318
  for (;;) {
293
319
  let { done: e, value: i } = await t.read();
294
320
  if (e) break;
295
- if (r += i.byteLength, r > p) throw await t.cancel().catch(() => {}), w();
321
+ if (r += i.byteLength, r > v) throw await t.cancel().catch(() => {}), A();
296
322
  n.push(i);
297
323
  }
298
324
  let i = new Uint8Array(r), a = 0;
299
325
  for (let e of n) i.set(e, a), a += e.byteLength;
300
326
  return i;
301
327
  }
302
- var w = () => new _(413, "PayloadTooLarge", "Request body is too large.");
303
- async function T(e, t) {
328
+ var A = () => new S(413, "PayloadTooLarge", "Request body is too large.");
329
+ async function j(e, t) {
304
330
  let n;
305
331
  try {
306
- n = JSON.parse(new TextDecoder().decode(await C(e)));
332
+ n = JSON.parse(new TextDecoder().decode(await k(e)));
307
333
  } catch (e) {
308
- if (e instanceof _) throw e;
334
+ if (e instanceof S) throw e;
309
335
  n = void 0;
310
336
  }
311
337
  let r = typeof n == "object" && n;
312
- if (!r || t.some((e) => typeof r[e] != "string")) throw new _(400, "InvalidRequest", `Expected ${t.join(", ")}.`);
338
+ if (!r || t.some((e) => typeof r[e] != "string")) throw new S(400, "InvalidRequest", `Expected ${t.join(", ")}.`);
313
339
  return r;
314
340
  }
315
- export { v as createCustomerHandler, n as customerSessionCookie, s as readCustomerSession };
341
+ export { C as createCustomerHandler, n as customerSessionCookie, u as readCustomerSession };