@passflow/core 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import K from "axios";
2
- import { v4 as kt } from "uuid";
3
- import { startAuthentication as wt, startRegistration as St } from "@simplewebauthn/browser";
4
- const bt = "0.18.0", Tt = {
5
- version: bt
6
- }, V = "X-Passflow-Clientid", D = "Authorization", _t = "X-Passflow-DeviceId", Et = "X-Passflow-DeviceType", It = Tt.version, Hs = ["id", "offline", "openid"], At = ["id", "offline", "tenant", "email", "oidc", "openid", "access:tenant:all"], Le = "https://auth.passflow.cloud", zs = "default", Ct = 500, Rt = 600, Ft = 100, Pt = 6e4, $e = 30, Mt = 3, Dt = 30, Ut = 200, xt = (r) => {
1
+ import B from "axios";
2
+ import { v4 as _t } from "uuid";
3
+ import { startAuthentication as Et, startRegistration as It } from "@simplewebauthn/browser";
4
+ const At = "0.19.0", Ct = {
5
+ version: At
6
+ }, V = "X-Passflow-Clientid", D = "Authorization", Rt = "X-Passflow-DeviceId", Pt = "X-Passflow-DeviceType", Ft = Ct.version, ei = ["id", "offline", "openid"], Mt = ["id", "offline", "tenant", "email", "oidc", "openid", "access:tenant:all"], qe = "https://auth.passflow.cloud", ti = "default", Ut = 500, Dt = 600, xt = 100, Ot = 6e4, Ne = 30, Lt = 3, $t = 30, qt = 200, Nt = (r) => {
7
7
  const e = [];
8
8
  let t;
9
9
  for (t in r) {
@@ -18,14 +18,14 @@ const bt = "0.18.0", Tt = {
18
18
  }
19
19
  return { raw: r, tenants: e };
20
20
  };
21
- function Ot(r) {
21
+ function Vt(r) {
22
22
  if (typeof window < "u" && typeof window.atob == "function")
23
23
  return window.atob(r);
24
24
  if (typeof Buffer < "u")
25
25
  return Buffer.from(r, "base64").toString("utf-8");
26
26
  throw new Error("No Base64 decoding method available in this environment");
27
27
  }
28
- class Lt {
28
+ class Kt {
29
29
  constructor(e) {
30
30
  this.storageManager = e;
31
31
  }
@@ -54,19 +54,19 @@ class Lt {
54
54
  return T(t);
55
55
  }
56
56
  }
57
- function C(r, e = $e) {
57
+ function C(r, e = Ne) {
58
58
  return Math.floor(Date.now() / 1e3) + e > r.exp;
59
59
  }
60
60
  function T(r) {
61
61
  const e = r.split(".")[1];
62
62
  if (!e) throw new Error("Invalid token string");
63
- const t = e.replace(/-/g, "+").replace(/_/g, "/"), s = t + "=".repeat((4 - t.length % 4) % 4), i = Ot(s), n = decodeURIComponent(
63
+ const t = e.replace(/-/g, "+").replace(/_/g, "/"), s = t + "=".repeat((4 - t.length % 4) % 4), i = Vt(s), n = decodeURIComponent(
64
64
  i.split("").map((a) => "%" + ("00" + a.charCodeAt(0).toString(16)).slice(-2)).join("")
65
65
  ), o = JSON.parse(n);
66
- return o.membership = o.passflow_tm && o.type !== "invite" ? xt(o.passflow_tm) : void 0, o;
66
+ return o.membership = o.passflow_tm && o.type !== "invite" ? Nt(o.passflow_tm) : void 0, o;
67
67
  }
68
- var b = /* @__PURE__ */ ((r) => (r.id_token = "id_token", r.access_token = "access", r.refresh_token = "refresh", r.invite_token = "invite", r.reset_token = "reset", r.web_cookie = "web-cookie", r.management = "management", r.signin = "signin", r.actor = "actor", r.two_factor = "2fa", r))(b || {}), A = /* @__PURE__ */ ((r) => (r.JsonBody = "json_body", r.Cookie = "cookie", r.Mobile = "mobile", r.BFF = "bff", r))(A || {}), qe = /* @__PURE__ */ ((r) => (r.Unknown = "unknown", r.Valid = "valid", r.Invalid = "invalid", r))(qe || {});
69
- class Ne {
68
+ var b = /* @__PURE__ */ ((r) => (r.id_token = "id_token", r.access_token = "access", r.refresh_token = "refresh", r.invite_token = "invite", r.reset_token = "reset", r.web_cookie = "web-cookie", r.management = "management", r.signin = "signin", r.actor = "actor", r.two_factor = "2fa", r))(b || {}), A = /* @__PURE__ */ ((r) => (r.JsonBody = "json_body", r.Cookie = "cookie", r.Mobile = "mobile", r.BFF = "bff", r))(A || {}), Ve = /* @__PURE__ */ ((r) => (r.Unknown = "unknown", r.Valid = "valid", r.Invalid = "invalid", r))(Ve || {});
69
+ class Ke {
70
70
  constructor(e) {
71
71
  this.storageManager = e, this.mode = "json_body", this.sessionState = "unknown", this.isInitializedFlag = !1, this.STORAGE_PREFIX = "passflow_", this.DELIVERY_MODE_KEY = `${this.STORAGE_PREFIX}delivery_mode`, this.SESSION_STATE_KEY = `${this.STORAGE_PREFIX}session_state`, this.loadPersistedMode(), this.loadPersistedSessionState();
72
72
  }
@@ -176,7 +176,7 @@ class Ne {
176
176
  loadPersistedSessionState() {
177
177
  try {
178
178
  const e = this.storageManager.storage.getItem(this.SESSION_STATE_KEY);
179
- e && Object.values(qe).includes(e) && (this.sessionState = e);
179
+ e && Object.values(Ve).includes(e) && (this.sessionState = e);
180
180
  } catch {
181
181
  }
182
182
  }
@@ -217,7 +217,7 @@ class Ne {
217
217
  }
218
218
  }
219
219
  }
220
- class ke {
220
+ class Se {
221
221
  constructor({ storage: e, prefix: t } = {}) {
222
222
  this.keyStoragePrefix = "", this.scopes = `${this.keyStoragePrefix}tokens_scopes`, this.deviceId = `${this.keyStoragePrefix}passflowDeviceId`, this.invitationToken = `${this.keyStoragePrefix}passflowInvitationToken`, this.previousRedirectUrl = `${this.keyStoragePrefix}passflowPreviousRedirectUrl`, this.STORAGE_PREFIX = "passflow_", this.ID_TOKEN_KEY = `${this.STORAGE_PREFIX}id_token`, this.CSRF_TOKEN_KEY = `${this.STORAGE_PREFIX}csrf_token`, this.DELIVERY_MODE_KEY = `${this.STORAGE_PREFIX}delivery_mode`, this.storage = e ?? localStorage, this.keyStoragePrefix = t ? `${t}_` : "";
223
223
  }
@@ -400,9 +400,9 @@ class ke {
400
400
  return `${this.keyStoragePrefix}${e}`;
401
401
  }
402
402
  }
403
- class Ve {
403
+ class Be {
404
404
  constructor(e) {
405
- this.storageManager = e ?? new ke();
405
+ this.storageManager = e ?? new Se();
406
406
  }
407
407
  getDeviceId() {
408
408
  const e = this.storageManager.getDeviceId();
@@ -413,19 +413,19 @@ class Ve {
413
413
  return e;
414
414
  }
415
415
  generateUniqueDeviceId() {
416
- return kt();
416
+ return _t();
417
417
  }
418
418
  }
419
- class Be extends Error {
419
+ class Ge extends Error {
420
420
  constructor(e = "Authentication popup was closed") {
421
421
  super(e), this.name = "PopupClosedError";
422
422
  }
423
423
  }
424
- class $t {
424
+ class Bt {
425
425
  constructor() {
426
426
  this.passkeys = {
427
- startRegistration: (e) => St({ optionsJSON: e }),
428
- startAuthentication: (e) => wt({ optionsJSON: e })
427
+ startRegistration: (e) => It({ optionsJSON: e }),
428
+ startAuthentication: (e) => Et({ optionsJSON: e })
429
429
  };
430
430
  }
431
431
  // ----------------------------------------------------------------
@@ -557,15 +557,15 @@ class $t {
557
557
  'openAuthUrl: "deeplink" mode is not supported on web. Use "popup" or "redirect" instead, or provide a native platform adapter.'
558
558
  )
559
559
  );
560
- const i = t.width ?? Ct, n = t.height ?? Rt, o = t.expectedReturnOrigin ?? window.location.origin, a = window.open(e, "_blank", `width=${i},height=${n}`);
561
- return a ? new Promise((h, p) => {
560
+ const i = t.width ?? Ut, n = t.height ?? Dt, o = t.expectedReturnOrigin ?? window.location.origin, a = window.open(e, "_blank", `width=${i},height=${n}`);
561
+ return a ? new Promise((h, u) => {
562
562
  const m = Date.now(), d = setInterval(() => {
563
563
  if (a.closed) {
564
- clearInterval(d), p(new Be());
564
+ clearInterval(d), u(new Ge());
565
565
  return;
566
566
  }
567
- if (Date.now() - m > Pt) {
568
- clearInterval(d), a.close(), p(new Error("Authentication popup timed out"));
567
+ if (Date.now() - m > Ot) {
568
+ clearInterval(d), a.close(), u(new Error("Authentication popup timed out"));
569
569
  return;
570
570
  }
571
571
  try {
@@ -575,7 +575,7 @@ class $t {
575
575
  }
576
576
  } catch {
577
577
  }
578
- }, Ft);
578
+ }, xt);
579
579
  }) : (window.location.href = e, new Promise(() => {
580
580
  }));
581
581
  }
@@ -633,94 +633,94 @@ class $t {
633
633
  return "web";
634
634
  }
635
635
  }
636
- const Y = new $t(), qt = /^[0-9]+$/, Ee = Object.freeze({ unorderable: !1, zero: !1 }), Nt = (r) => qt.test(r) ? Number.parseInt(r, 10) : void 0, te = (r) => {
636
+ const Y = new Bt(), Gt = /^[0-9]+$/, Ae = Object.freeze({ unorderable: !1, zero: !1 }), jt = (r) => Gt.test(r) ? Number.parseInt(r, 10) : void 0, re = (r) => {
637
637
  if (!r)
638
- return Ee;
638
+ return Ae;
639
639
  const e = r.split(/\s+/).filter((i) => i !== "");
640
640
  if (e.length === 0)
641
- return Ee;
641
+ return Ae;
642
642
  const t = [];
643
643
  for (const i of e) {
644
- const n = Nt(i);
644
+ const n = jt(i);
645
645
  n !== void 0 && t.push(n);
646
646
  }
647
647
  if (t.length === 0)
648
648
  return { raw: r, unorderable: !0, zero: !1 };
649
649
  const s = Math.min(...t);
650
650
  return s === 0 ? { raw: r, unorderable: !1, zero: !0 } : { level: s, raw: r, unorderable: !1, zero: !1 };
651
- }, Vt = (r) => te(r).level, Bt = "insufficient_user_authentication", Kt = "upgrade_required", Ie = /([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g, jt = (r) => r.replace(/\\(.)/g, "$1"), Ke = (r) => {
651
+ }, Ht = (r) => re(r).level, zt = "insufficient_user_authentication", Yt = "upgrade_required", Ce = /([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g, Wt = (r) => r.replace(/\\(.)/g, "$1"), je = (r) => {
652
652
  const e = {};
653
- Ie.lastIndex = 0;
654
- for (const t of r.matchAll(Ie)) {
653
+ Ce.lastIndex = 0;
654
+ for (const t of r.matchAll(Ce)) {
655
655
  const s = t[1];
656
656
  if (!s)
657
657
  continue;
658
658
  const i = t[2], n = t[3];
659
- e[s.toLowerCase()] = i !== void 0 ? jt(i) : n ?? "";
659
+ e[s.toLowerCase()] = i !== void 0 ? Wt(i) : n ?? "";
660
660
  }
661
661
  return e;
662
- }, je = (r) => {
662
+ }, He = (r) => {
663
663
  if (r == null || r === "")
664
664
  return { kind: "absent" };
665
665
  const e = typeof r == "number" ? r : Number.parseInt(String(r), 10);
666
666
  return Number.isFinite(e) && e > 0 ? { kind: "valid", value: e } : { kind: "invalid", raw: r };
667
- }, Ge = (r) => {
668
- const e = je(r);
667
+ }, ze = (r) => {
668
+ const e = He(r);
669
669
  return e.kind === "valid" ? e.value : void 0;
670
- }, Gt = (r, e) => {
670
+ }, Xt = (r, e) => {
671
671
  if (!r || !/(^|[\s,])Bearer\b/i.test(r))
672
672
  return;
673
- const t = Ke(r);
674
- if (t.error === Bt)
673
+ const t = je(r);
674
+ if (t.error === zt)
675
675
  return {
676
676
  acrValues: t.acr_values || void 0,
677
- maxAge: Ge(t.max_age),
677
+ maxAge: ze(t.max_age),
678
678
  status: e
679
679
  };
680
- }, Ht = (r, e) => {
680
+ }, Jt = (r, e) => {
681
681
  if (!r || typeof r != "object")
682
682
  return;
683
683
  const t = r;
684
- if (t.error === Kt)
684
+ if (t.error === Yt)
685
685
  return {
686
686
  acrValues: typeof t.acr_values == "string" && t.acr_values ? t.acr_values : void 0,
687
- maxAge: Ge(t.max_age),
687
+ maxAge: ze(t.max_age),
688
688
  status: e
689
689
  };
690
- }, Ae = (r, e, t) => ({
690
+ }, Re = (r, e, t) => ({
691
691
  channel: r,
692
- acr: te(e.acrValues),
693
- maxAge: je(t),
692
+ acr: re(e.acrValues),
693
+ maxAge: He(t),
694
694
  raw: e.acrValues
695
- }), zt = (r) => r ? Ke(r) : {}, we = (r, e) => {
695
+ }), Zt = (r) => r ? je(r) : {}, be = (r, e) => {
696
696
  const { status: t } = r;
697
697
  if (t !== 401 && t !== 403)
698
698
  return { diagnostics: [] };
699
- const s = e?.requireChallengeChannel === "header", i = r.getHeader("www-authenticate"), n = Gt(i, t), o = s ? void 0 : Ht(r.body, t), a = [], h = (u, y) => {
700
- a.push({ status: t, url: "", reason: u, ...y ? { detail: y } : {} });
699
+ const s = e?.requireChallengeChannel === "header", i = r.getHeader("www-authenticate"), n = Xt(i, t), o = s ? void 0 : Jt(r.body, t), a = [], h = (p, y) => {
700
+ a.push({ status: t, url: "", reason: p, ...y ? { detail: y } : {} });
701
701
  };
702
702
  if (!n && !o)
703
703
  return s && h("header-required-but-absent", i ? { header: i } : void 0), { diagnostics: a };
704
- const p = [];
705
- if (n && p.push(Ae("header", n, zt(i).max_age)), o) {
706
- const u = r.body;
707
- p.push(Ae("body", o, u?.max_age));
708
- }
709
- const m = (u) => u;
710
- for (const u of p)
711
- u.acr.unorderable && h("channels-unorderable", { [m(u.channel)]: u.raw }), u.acr.zero && h("zero-constraint-ignored", { field: "acr_values", [m(u.channel)]: u.raw }), u.maxAge.kind === "invalid" && h("zero-constraint-ignored", { field: "max_age", [m(u.channel)]: String(u.maxAge.raw) });
712
- const d = p.filter((u) => u.acr.level !== void 0);
704
+ const u = [];
705
+ if (n && u.push(Re("header", n, Zt(i).max_age)), o) {
706
+ const p = r.body;
707
+ u.push(Re("body", o, p?.max_age));
708
+ }
709
+ const m = (p) => p;
710
+ for (const p of u)
711
+ p.acr.unorderable && h("channels-unorderable", { [m(p.channel)]: p.raw }), p.acr.zero && h("zero-constraint-ignored", { field: "acr_values", [m(p.channel)]: p.raw }), p.maxAge.kind === "invalid" && h("zero-constraint-ignored", { field: "max_age", [m(p.channel)]: String(p.maxAge.raw) });
712
+ const d = u.filter((p) => p.acr.level !== void 0);
713
713
  let g, f;
714
- for (const u of d) {
715
- const y = u.acr.level;
716
- g === void 0 || y > g ? (g = y, f = u.raw) : y === g && u.channel === "header" && (f = u.raw);
714
+ for (const p of d) {
715
+ const y = p.acr.level;
716
+ g === void 0 || y > g ? (g = y, f = p.raw) : y === g && p.channel === "header" && (f = p.raw);
717
717
  }
718
718
  let v;
719
- for (const u of p)
720
- u.maxAge.kind === "valid" && (v === void 0 || u.maxAge.value < v) && (v = u.maxAge.value);
721
- if (p.length === 2) {
722
- const [u, y] = p, I = u.acr.level !== void 0 && y.acr.level !== void 0 && u.acr.level !== y.acr.level, W = u.maxAge.kind === "valid" && y.maxAge.kind === "valid" && u.maxAge.value !== y.maxAge.value;
723
- (I || W) && h("channels-disagree", { header: u.raw ?? y.raw, body: y.raw ?? u.raw });
719
+ for (const p of u)
720
+ p.maxAge.kind === "valid" && (v === void 0 || p.maxAge.value < v) && (v = p.maxAge.value);
721
+ if (u.length === 2) {
722
+ const [p, y] = u, I = p.acr.level !== void 0 && y.acr.level !== void 0 && p.acr.level !== y.acr.level, W = p.maxAge.kind === "valid" && y.maxAge.kind === "valid" && p.maxAge.value !== y.maxAge.value;
723
+ (I || W) && h("channels-disagree", { header: p.raw ?? y.raw, body: y.raw ?? p.raw });
724
724
  }
725
725
  return {
726
726
  challenge: {
@@ -728,19 +728,19 @@ const Y = new $t(), qt = /^[0-9]+$/, Ee = Object.freeze({ unorderable: !1, zero:
728
728
  requiredLevel: g,
729
729
  maxAge: v,
730
730
  status: t,
731
- channels: p.map((u) => u.channel)
731
+ channels: u.map((p) => p.channel)
732
732
  },
733
733
  diagnostics: a
734
734
  };
735
- }, Yt = (r, e, t) => we({ status: r, getHeader: e, body: t }).challenge, He = "__passflowUpgradeTransaction", ze = "__passflowUpgradeReplayed", Ye = (r, e) => typeof r == "object" && r !== null && r[e] === !0, We = (r) => ({
735
+ }, Qt = (r, e, t) => be({ status: r, getHeader: e, body: t }).challenge, Ye = "__passflowUpgradeTransaction", We = "__passflowUpgradeReplayed", Xe = (r, e) => typeof r == "object" && r !== null && r[e] === !0, Je = (r) => ({
736
736
  ...r ?? {},
737
- [He]: !0
738
- }), Xe = (r) => Ye(r, He), Wt = (r) => ({
737
+ [Ye]: !0
738
+ }), Ze = (r) => Xe(r, Ye), er = (r) => ({
739
739
  ...r,
740
- [ze]: !0
741
- }), Xt = (r) => Ye(r, ze);
742
- var M = /* @__PURE__ */ ((r) => (r.GET = "get", r.POST = "post", r.PUT = "put", r.PATCH = "patch", r.DELETE = "delete", r))(M || {}), l = /* @__PURE__ */ ((r) => (r.signin = "/auth/login", r.signup = "/auth/register", r.signInWithProvider = "/auth/federated/start/", r.passwordless = "/auth/passwordless/start", r.passwordlessComplete = "/auth/passwordless/complete", r.logout = "/user/logout", r.refresh = "/auth/refresh", r.validateSession = "/user/me", r.sendPasswordResetEmail = "/auth/password/reset", r.resetPassword = "/auth/password/change", r.appSettings = "/app/settings", r.passkeyRegisterStart = "/auth/passkey/register/start", r.passkeyRegisterComplete = "/auth/passkey/register/complete", r.passkeyAuthenticateStart = "/auth/passkey/authenticate/start", r.passkeyAuthenticateComplete = "/auth/passkey/authenticate/complete", r.passkeyValidate = "/auth/validate", r.settingsAll = "/settings", r.settingsPasswordPolicy = "/settings/password", r.settingsPasskey = "/settings/passkey", r.userPasskey = "/user/passkey", r.addUserPasskey = "/user/passkey/add/start", r.completeAddUserPasskey = "/user/passkey/add/complete", r.joinInvitation = "/user/tenant/join", r.tenantPath = "/user/tenant", r.invitationsPath = "/user/tenant/:tenantID/invitations", r.requestInvitation = "/user/invite", r.invitationDelete = "/user/invite/:invitationID", r.invitationResend = "/user/invite/:invitationID/resend", r.invitationGetLink = "/user/invite/:invitationID/link", r.twoFactor = "/user/2fa", r.twoFactorStatus = "/user/2fa/status", r.twoFactorSetupBegin = "/user/2fa/setup/begin", r.twoFactorSetupConfirm = "/user/2fa/setup/confirm", r.twoFactorVerify = "/auth/2fa/verify", r.twoFactorRecovery = "/auth/2fa/recovery", r.twoFactorRegenerateCodes = "/user/2fa/recovery-codes/regenerate", r.twoFactorSetupMagicLink = "/auth/2fa-setup", r.TwoFactorMethodsAvailable = "/v2/user/2fa/methods/available", r.TwoFactorMethodsRegistered = "/v2/user/2fa/methods", r.TwoFactorSetupStart = "/v2/user/2fa/setup/start", r.TwoFactorSetupComplete = "/v2/user/2fa/setup/complete", r.TwoFactorMethodRemove = "/v2/user/2fa/methods/:id", r.TwoFactorChallenge = "/v2/auth/2fa/challenge", r.TwoFactorVerifyV2 = "/v2/auth/2fa/verify", r.TwoFactorAlternative = "/v2/auth/2fa/alternative", r.TwoFactorTrustedDevices = "/v2/user/2fa/trusted-devices", r.TwoFactorTrustedDeviceRevoke = "/v2/user/2fa/trusted-devices/:id", r.cliAuthStatus = "/cli/auth/status/:sessionId", r.cliAuthComplete = "/cli/auth/complete", r.upgradeStart = "/auth/upgrade/start", r))(l || {}), F = /* @__PURE__ */ ((r) => (r.passkeyRegisterStart = "/admin/auth/passkey/register/start", r.passkeyRegisterComplete = "/admin/auth/passkey/register/complete", r.passkeyAuthenticateStart = "/admin/auth/passkey/authenticate/start", r.passkeyAuthenticateComplete = "/admin/auth/passkey/authenticate/complete", r.passkeyValidate = "/admin/auth/validate", r.logout = "/admin/auth/logout", r))(F || {});
743
- const Je = (r) => {
740
+ [We]: !0
741
+ }), tr = (r) => Xe(r, We);
742
+ var U = /* @__PURE__ */ ((r) => (r.GET = "get", r.POST = "post", r.PUT = "put", r.PATCH = "patch", r.DELETE = "delete", r))(U || {}), l = /* @__PURE__ */ ((r) => (r.signin = "/auth/login", r.signup = "/auth/register", r.pkceExchange = "/auth/pkce_exchange", r.signInWithProvider = "/auth/federated/start/", r.passwordless = "/auth/passwordless/start", r.passwordlessComplete = "/auth/passwordless/complete", r.logout = "/user/logout", r.refresh = "/auth/refresh", r.validateSession = "/user/me", r.sendPasswordResetEmail = "/auth/password/reset", r.resetPassword = "/auth/password/change", r.appSettings = "/app/settings", r.passkeyRegisterStart = "/auth/passkey/register/start", r.passkeyRegisterComplete = "/auth/passkey/register/complete", r.passkeyAuthenticateStart = "/auth/passkey/authenticate/start", r.passkeyAuthenticateComplete = "/auth/passkey/authenticate/complete", r.passkeyValidate = "/auth/validate", r.settingsAll = "/settings", r.settingsPasswordPolicy = "/settings/password", r.settingsPasskey = "/settings/passkey", r.userPasskey = "/user/passkey", r.addUserPasskey = "/user/passkey/add/start", r.completeAddUserPasskey = "/user/passkey/add/complete", r.joinInvitation = "/user/tenant/join", r.tenantPath = "/user/tenant", r.invitationsPath = "/user/tenant/:tenantID/invitations", r.requestInvitation = "/user/invite", r.invitationDelete = "/user/invite/:invitationID", r.invitationResend = "/user/invite/:invitationID/resend", r.invitationGetLink = "/user/invite/:invitationID/link", r.twoFactor = "/user/2fa", r.twoFactorStatus = "/user/2fa/status", r.twoFactorSetupBegin = "/user/2fa/setup/begin", r.twoFactorSetupConfirm = "/user/2fa/setup/confirm", r.twoFactorVerify = "/auth/2fa/verify", r.twoFactorRecovery = "/auth/2fa/recovery", r.twoFactorRegenerateCodes = "/user/2fa/recovery-codes/regenerate", r.twoFactorSetupMagicLink = "/auth/2fa-setup", r.TwoFactorMethodsAvailable = "/v2/user/2fa/methods/available", r.TwoFactorMethodsRegistered = "/v2/user/2fa/methods", r.TwoFactorSetupStart = "/v2/user/2fa/setup/start", r.TwoFactorSetupComplete = "/v2/user/2fa/setup/complete", r.TwoFactorMethodRemove = "/v2/user/2fa/methods/:id", r.TwoFactorChallenge = "/v2/auth/2fa/challenge", r.TwoFactorVerifyV2 = "/v2/auth/2fa/verify", r.TwoFactorAlternative = "/v2/auth/2fa/alternative", r.TwoFactorTrustedDevices = "/v2/user/2fa/trusted-devices", r.TwoFactorTrustedDeviceRevoke = "/v2/user/2fa/trusted-devices/:id", r.cliAuthStatus = "/cli/auth/status/:sessionId", r.cliAuthComplete = "/cli/auth/complete", r.upgradeStart = "/auth/upgrade/start", r))(l || {}), P = /* @__PURE__ */ ((r) => (r.passkeyRegisterStart = "/admin/auth/passkey/register/start", r.passkeyRegisterComplete = "/admin/auth/passkey/register/complete", r.passkeyAuthenticateStart = "/admin/auth/passkey/authenticate/start", r.passkeyAuthenticateComplete = "/admin/auth/passkey/authenticate/complete", r.passkeyValidate = "/admin/auth/validate", r.logout = "/admin/auth/logout", r))(P || {});
743
+ const Qe = (r) => {
744
744
  if (!r)
745
745
  return null;
746
746
  try {
@@ -755,21 +755,21 @@ class w extends Error {
755
755
  super(), this.id = e?.id ?? "unknown", this.message = e?.message ?? e ?? "Something went wrong", this.status = e?.status ?? 500, this.location = e?.location ?? "unknown", this.time = e?.time ?? (/* @__PURE__ */ new Date()).toISOString();
756
756
  }
757
757
  }
758
- var Jt = /* @__PURE__ */ ((r) => (r.google = "google", r.facebook = "facebook", r))(Jt || {}), Zt = /* @__PURE__ */ ((r) => (r.web = "web", r.ios = "ios", r.android = "android", r))(Zt || {});
759
- function Ys(r) {
758
+ var rr = /* @__PURE__ */ ((r) => (r.google = "google", r.facebook = "facebook", r))(rr || {}), sr = /* @__PURE__ */ ((r) => (r.web = "web", r.ios = "ios", r.android = "android", r))(sr || {});
759
+ function ri(r) {
760
760
  return r;
761
761
  }
762
- function P(r, e) {
762
+ function F(r, e) {
763
763
  let t = r;
764
764
  return Object.entries(e).forEach(([s, i]) => {
765
765
  t = t.replace(`:${s}`, i);
766
766
  }), t;
767
767
  }
768
- var Qt = /* @__PURE__ */ ((r) => (r.Disabled = "disabled", r.Optional = "optional", r.Required = "required", r))(Qt || {});
769
- const er = 3, tr = 1e3, rr = (r) => (e) => {
768
+ var ir = /* @__PURE__ */ ((r) => (r.Disabled = "disabled", r.Optional = "optional", r.Required = "required", r))(ir || {});
769
+ const nr = 3, or = 1e3, ar = (r) => (e) => {
770
770
  const t = r.headers?.[e] ?? r.headers?.[e.toLowerCase()];
771
771
  return Array.isArray(t) ? t.join(", ") : t;
772
- }, Ze = (r) => Yt(r.status, rr(r), r.data), sr = (r) => Ze(r) !== void 0;
772
+ }, et = (r) => Qt(r.status, ar(r), r.data), cr = (r) => et(r) !== void 0;
773
773
  class E {
774
774
  constructor(e, t, s) {
775
775
  this.refreshPromise = null, this.isRefreshing = !1, this.defaultHeaders = {
@@ -777,18 +777,18 @@ class E {
777
777
  "Content-Type": "application/json"
778
778
  }, this.nonAccessTokenEndpoints = ["/auth/", "/settings", "/settings/"], this.protectedEndpoints = ["logout", "refresh", "upgrade"];
779
779
  const { url: i, appId: n, keyStoragePrefix: o } = e;
780
- this._platform = e.platform ?? Y, this.url = i || Le, this.upgradeDomain = Je(i), this.storageManager = t ?? new ke({
780
+ this._platform = e.platform ?? Y, this.url = i || qe, this.upgradeDomain = Qe(i), this.storageManager = t ?? new Se({
781
781
  prefix: o ?? ""
782
- }), this.deviceService = s ?? new Ve(this.storageManager), this.tokenService = new Lt(this.storageManager), this.tokenDeliveryManager = new Ne(this.storageManager), n && (this.appId = n, this.defaultHeaders = {
782
+ }), this.deviceService = s ?? new Be(this.storageManager), this.tokenService = new Kt(this.storageManager), this.tokenDeliveryManager = new Ke(this.storageManager), n && (this.appId = n, this.defaultHeaders = {
783
783
  ...this.defaultHeaders,
784
784
  [V]: n
785
785
  });
786
786
  const a = this.deviceService.getDeviceId();
787
787
  this.defaultHeaders = {
788
788
  ...this.defaultHeaders,
789
- [_t]: a,
790
- [Et]: this._platform.getDeviceType()
791
- }, this.detectCookieSupport(), this.instance = K.create({
789
+ [Rt]: a,
790
+ [Pt]: this._platform.getDeviceType()
791
+ }, this.detectCookieSupport(), this.instance = B.create({
792
792
  baseURL: this.url,
793
793
  headers: { ...this.defaultHeaders }
794
794
  }), this.instance.interceptors.request.use(async (h) => {
@@ -806,10 +806,10 @@ class E {
806
806
  }
807
807
  return h;
808
808
  }
809
- const p = this.storageManager.getTokens();
810
- if (p?.access_token) {
811
- const m = T(p.access_token);
812
- if (C(m, $e) && p.refresh_token)
809
+ const u = this.storageManager.getTokens();
810
+ if (u?.access_token) {
811
+ const m = T(u.access_token);
812
+ if (C(m, Ne) && u.refresh_token)
813
813
  try {
814
814
  if (this.refreshPromise) {
815
815
  const d = await this.refreshPromise;
@@ -825,17 +825,17 @@ class E {
825
825
  } catch (d) {
826
826
  return this.refreshPromise = null, this.isRefreshing = !1, this.storageManager.deleteTokens(), Promise.reject(d);
827
827
  }
828
- return h.headers[D] = `Bearer ${p.access_token}`, h;
828
+ return h.headers[D] = `Bearer ${u.access_token}`, h;
829
829
  }
830
830
  return h;
831
831
  }), this.instance.interceptors.response.use(
832
832
  (h) => h,
833
833
  async (h) => {
834
834
  if (h.response?.status === 401 && !this.isUpgradeTransactionError(h) && this.tokenDeliveryManager.setSessionInvalid(), h.response && this.upgradeHandler) {
835
- const p = Ze(h.response);
836
- if (p)
835
+ const u = et(h.response);
836
+ if (u)
837
837
  try {
838
- return await this.upgradeHandler(h, p);
838
+ return await this.upgradeHandler(h, u);
839
839
  } catch (m) {
840
840
  if (m !== h)
841
841
  throw m;
@@ -854,7 +854,7 @@ class E {
854
854
  * speak upgrade vocabulary", which is unsound in both directions.
855
855
  */
856
856
  isUpgradeTransactionError(e) {
857
- return Xe(e.config) || e.response !== void 0 && sr(e.response);
857
+ return Ze(e.config) || e.response !== void 0 && cr(e.response);
858
858
  }
859
859
  /**
860
860
  * Installs (or clears) the handler consulted when a response carries an
@@ -929,17 +929,17 @@ class E {
929
929
  if (!["GET", "HEAD", "OPTIONS"].includes(s || ""))
930
930
  return Promise.reject(e);
931
931
  const n = t._retryCount || 0;
932
- if (n >= er)
932
+ if (n >= nr)
933
933
  return Promise.reject(e);
934
- let o = tr * Math.pow(2, n);
934
+ let o = or * Math.pow(2, n);
935
935
  const a = e.response?.headers?.["retry-after"];
936
936
  if (a) {
937
937
  const h = Number.parseInt(a, 10);
938
938
  if (!Number.isNaN(h))
939
939
  o = h * 1e3;
940
940
  else {
941
- const p = new Date(a);
942
- Number.isNaN(p.getTime()) || (o = Math.max(0, p.getTime() - Date.now()));
941
+ const u = new Date(a);
942
+ Number.isNaN(u.getTime()) || (o = Math.max(0, u.getTime() - Date.now()));
943
943
  }
944
944
  }
945
945
  return await new Promise((h) => setTimeout(h, o)), t._retryCount = n + 1, this.instance.request(t);
@@ -972,19 +972,19 @@ class E {
972
972
  })).data;
973
973
  }
974
974
  get(e, t) {
975
- return this.send(M.GET, e, t);
975
+ return this.send(U.GET, e, t);
976
976
  }
977
977
  post(e, t, s) {
978
- return this.send(M.POST, e, { data: t, ...s });
978
+ return this.send(U.POST, e, { data: t, ...s });
979
979
  }
980
980
  put(e, t, s) {
981
- return this.send(M.PUT, e, { data: t, ...s });
981
+ return this.send(U.PUT, e, { data: t, ...s });
982
982
  }
983
983
  patch(e, t, s) {
984
- return this.send(M.PATCH, e, { data: t, ...s });
984
+ return this.send(U.PATCH, e, { data: t, ...s });
985
985
  }
986
986
  delete(e, t) {
987
- return this.send(M.DELETE, e, t);
987
+ return this.send(U.DELETE, e, t);
988
988
  }
989
989
  /**
990
990
  * Update the appId and propagate it to axios headers.
@@ -999,7 +999,7 @@ class E {
999
999
  }, this.instance.defaults.headers.common[V] = e;
1000
1000
  }
1001
1001
  }
1002
- class ir {
1002
+ class hr {
1003
1003
  constructor(e, t, s) {
1004
1004
  this.axiosClient = new E(e, t, s);
1005
1005
  }
@@ -1010,8 +1010,8 @@ class ir {
1010
1010
  return this.axiosClient.get(l.appSettings);
1011
1011
  }
1012
1012
  }
1013
- const q = { withCredentials: !0 };
1014
- class nr {
1013
+ const M = { withCredentials: !0 };
1014
+ class dr {
1015
1015
  constructor(e, t, s) {
1016
1016
  this.axiosClient = new E(e, t, s);
1017
1017
  }
@@ -1048,7 +1048,7 @@ class nr {
1048
1048
  return this.axiosClient.post(
1049
1049
  l.refresh,
1050
1050
  n,
1051
- i ? We(o) : o
1051
+ i ? Je(o) : o
1052
1052
  );
1053
1053
  }
1054
1054
  signIn(e, t, s) {
@@ -1060,7 +1060,7 @@ class nr {
1060
1060
  return this.axiosClient.post(
1061
1061
  l.signin,
1062
1062
  i,
1063
- q
1063
+ M
1064
1064
  );
1065
1065
  }
1066
1066
  signUp(e) {
@@ -1072,7 +1072,15 @@ class nr {
1072
1072
  return this.axiosClient.post(
1073
1073
  l.signup,
1074
1074
  i,
1075
- q
1075
+ M
1076
+ );
1077
+ }
1078
+ /** Redeems the code a PKCE sign-in answered with for the tokens it stands for. */
1079
+ pkceExchange(e, t) {
1080
+ return this.axiosClient.post(
1081
+ l.pkceExchange,
1082
+ { authz_code: e, verifier: t },
1083
+ M
1076
1084
  );
1077
1085
  }
1078
1086
  passwordlessSignIn(e, t, s) {
@@ -1091,11 +1099,11 @@ class nr {
1091
1099
  return this.axiosClient.post(
1092
1100
  l.passwordlessComplete,
1093
1101
  e,
1094
- q
1102
+ M
1095
1103
  );
1096
1104
  }
1097
1105
  logOut(e, t, s = !1) {
1098
- const i = s ? void 0 : { refresh_token: t, device: e }, n = s ? F.logout : l.logout;
1106
+ const i = s ? void 0 : { refresh_token: t, device: e }, n = s ? P.logout : l.logout;
1099
1107
  return this.axiosClient.post(n, i);
1100
1108
  }
1101
1109
  validateSession() {
@@ -1107,12 +1115,13 @@ class nr {
1107
1115
  e
1108
1116
  );
1109
1117
  }
1110
- resetPassword(e, t, s) {
1111
- const i = {
1118
+ resetPassword(e, t, s, i) {
1119
+ const n = {
1112
1120
  password: e,
1113
- scopes: t
1121
+ scopes: t,
1122
+ ...i ? { code_challenge: i } : {}
1114
1123
  };
1115
- return this.axiosClient.post(l.resetPassword, i, {
1124
+ return this.axiosClient.post(l.resetPassword, n, {
1116
1125
  headers: {
1117
1126
  [D]: `Bearer ${s}`,
1118
1127
  [V]: void 0
@@ -1125,7 +1134,7 @@ class nr {
1125
1134
  create_tenant: n ?? !1,
1126
1135
  device: t,
1127
1136
  os: s
1128
- }, a = i ? F.passkeyRegisterStart : l.passkeyRegisterStart;
1137
+ }, a = i ? P.passkeyRegisterStart : l.passkeyRegisterStart;
1129
1138
  return this.axiosClient.post(a, o);
1130
1139
  }
1131
1140
  passkeyRegisterComplete(e, t, s, i = !1) {
@@ -1133,11 +1142,11 @@ class nr {
1133
1142
  challenge_id: s,
1134
1143
  device: t,
1135
1144
  passkey_data: e
1136
- }, o = i ? F.passkeyRegisterComplete : l.passkeyRegisterComplete;
1145
+ }, o = i ? P.passkeyRegisterComplete : l.passkeyRegisterComplete;
1137
1146
  return this.axiosClient.post(
1138
1147
  o,
1139
1148
  n,
1140
- q
1149
+ M
1141
1150
  );
1142
1151
  }
1143
1152
  passkeyAuthenticateStart(e, t, s, i = !1) {
@@ -1146,7 +1155,7 @@ class nr {
1146
1155
  user_id: e.user_id ?? "",
1147
1156
  device: t,
1148
1157
  os: s
1149
- }, o = i ? F.passkeyAuthenticateStart : l.passkeyAuthenticateStart;
1158
+ }, o = i ? P.passkeyAuthenticateStart : l.passkeyAuthenticateStart;
1150
1159
  return this.axiosClient.post(
1151
1160
  o,
1152
1161
  n
@@ -1157,11 +1166,11 @@ class nr {
1157
1166
  challenge_id: s,
1158
1167
  device: t,
1159
1168
  passkey_data: e
1160
- }, o = i ? F.passkeyAuthenticateComplete : l.passkeyAuthenticateComplete;
1169
+ }, o = i ? P.passkeyAuthenticateComplete : l.passkeyAuthenticateComplete;
1161
1170
  return this.axiosClient.post(
1162
1171
  o,
1163
1172
  n,
1164
- q
1173
+ M
1165
1174
  );
1166
1175
  }
1167
1176
  passkeyValidate(e, t, s, i = !1, n) {
@@ -1171,12 +1180,12 @@ class nr {
1171
1180
  challenge_id: s
1172
1181
  };
1173
1182
  let a = l.passkeyValidate;
1174
- !n && i && (a = F.passkeyValidate);
1183
+ !n && i && (a = P.passkeyValidate);
1175
1184
  const h = n ? { [V]: n } : {};
1176
1185
  return this.axiosClient.post(a, o, { headers: h });
1177
1186
  }
1178
1187
  }
1179
- class Ws {
1188
+ class si {
1180
1189
  constructor(e, t, s) {
1181
1190
  this.axiosClient = new E(e, t, s);
1182
1191
  }
@@ -1184,14 +1193,14 @@ class Ws {
1184
1193
  this.axiosClient.setAppId(e);
1185
1194
  }
1186
1195
  getCLIAuthStatus(e) {
1187
- const t = P(l.cliAuthStatus, { sessionId: e });
1196
+ const t = F(l.cliAuthStatus, { sessionId: e });
1188
1197
  return this.axiosClient.get(t);
1189
1198
  }
1190
1199
  completeCLIAuth(e) {
1191
1200
  return this.axiosClient.post(l.cliAuthComplete, e);
1192
1201
  }
1193
1202
  }
1194
- class or {
1203
+ class lr {
1195
1204
  constructor(e, t, s) {
1196
1205
  this.axiosClient = new E(e, t, s);
1197
1206
  }
@@ -1217,7 +1226,7 @@ class or {
1217
1226
  getInvitations(e) {
1218
1227
  const t = {};
1219
1228
  e.groupID && (t.group_id = e.groupID.toString()), e.skip !== void 0 && (t.skip = e.skip.toString()), e.limit !== void 0 && (t.limit = e.limit.toString());
1220
- const s = P(l.invitationsPath, {
1229
+ const s = F(l.invitationsPath, {
1221
1230
  tenantID: e.tenantID
1222
1231
  });
1223
1232
  return this.axiosClient.get(s, { params: t }).then((i) => ({
@@ -1231,7 +1240,7 @@ class or {
1231
1240
  * @returns Promise with success response
1232
1241
  */
1233
1242
  deleteInvitation(e) {
1234
- const t = P(l.invitationDelete, {
1243
+ const t = F(l.invitationDelete, {
1235
1244
  invitationID: e
1236
1245
  });
1237
1246
  return this.axiosClient.delete(t);
@@ -1242,7 +1251,7 @@ class or {
1242
1251
  * @returns Promise with success response
1243
1252
  */
1244
1253
  resendInvitation(e) {
1245
- const t = P(l.invitationResend, {
1254
+ const t = F(l.invitationResend, {
1246
1255
  invitationID: e
1247
1256
  });
1248
1257
  return this.axiosClient.post(t, {});
@@ -1253,13 +1262,13 @@ class or {
1253
1262
  * @returns Promise with the link
1254
1263
  */
1255
1264
  getInvitationLink(e) {
1256
- const t = P(l.invitationGetLink, {
1265
+ const t = F(l.invitationGetLink, {
1257
1266
  invitationID: e
1258
1267
  });
1259
1268
  return this.axiosClient.get(t);
1260
1269
  }
1261
1270
  }
1262
- class ar {
1271
+ class ur {
1263
1272
  constructor(e, t, s) {
1264
1273
  this.axiosClient = new E(e, t, s);
1265
1274
  }
@@ -1276,7 +1285,7 @@ class ar {
1276
1285
  return this.axiosClient.get(l.settingsPasskey);
1277
1286
  }
1278
1287
  }
1279
- class cr {
1288
+ class pr {
1280
1289
  constructor(e, t, s) {
1281
1290
  this.axiosClient = new E(e, t, s);
1282
1291
  }
@@ -1509,11 +1518,11 @@ class cr {
1509
1518
  return this.axiosClient.delete(i);
1510
1519
  }
1511
1520
  }
1512
- const pe = (r) => r ? { headers: { Authorization: `Bearer ${r}` } } : {}, ie = (r) => ({
1521
+ const ge = (r) => r ? { headers: { Authorization: `Bearer ${r}` } } : {}, ne = (r) => ({
1513
1522
  withCredentials: !0,
1514
- ...pe(r)
1523
+ ...ge(r)
1515
1524
  });
1516
- class hr {
1525
+ class fr {
1517
1526
  constructor(e, t, s) {
1518
1527
  this.axiosClient = new E(e, t, s);
1519
1528
  }
@@ -1556,7 +1565,7 @@ class hr {
1556
1565
  return this.axiosClient.post(
1557
1566
  l.twoFactorVerify,
1558
1567
  { code: s, ...i ? { trust_device: !0 } : {} },
1559
- ie(t)
1568
+ ne(t)
1560
1569
  );
1561
1570
  }
1562
1571
  /**
@@ -1569,7 +1578,7 @@ class hr {
1569
1578
  return this.axiosClient.post(
1570
1579
  l.twoFactorRecovery,
1571
1580
  { recovery_code: s, ...i ? { trust_device: !0 } : {} },
1572
- ie(t)
1581
+ ne(t)
1573
1582
  );
1574
1583
  }
1575
1584
  /**
@@ -1719,7 +1728,7 @@ class hr {
1719
1728
  * DELETE /v2/user/2fa/methods/:id
1720
1729
  */
1721
1730
  removeMethod(e) {
1722
- const t = P(l.TwoFactorMethodRemove, { id: e });
1731
+ const t = F(l.TwoFactorMethodRemove, { id: e });
1723
1732
  return this.axiosClient.delete(t);
1724
1733
  }
1725
1734
  /**
@@ -1731,7 +1740,7 @@ class hr {
1731
1740
  return this.axiosClient.post(
1732
1741
  l.TwoFactorChallenge,
1733
1742
  e,
1734
- pe(t)
1743
+ ge(t)
1735
1744
  );
1736
1745
  }
1737
1746
  /**
@@ -1746,7 +1755,7 @@ class hr {
1746
1755
  return this.axiosClient.post(
1747
1756
  l.TwoFactorVerifyV2,
1748
1757
  { ...i, ...s ? { trust_device: !0 } : {} },
1749
- ie(t)
1758
+ ne(t)
1750
1759
  );
1751
1760
  }
1752
1761
  /**
@@ -1758,7 +1767,7 @@ class hr {
1758
1767
  return this.axiosClient.post(
1759
1768
  l.TwoFactorAlternative,
1760
1769
  e,
1761
- pe(t)
1770
+ ge(t)
1762
1771
  );
1763
1772
  }
1764
1773
  /**
@@ -1780,11 +1789,11 @@ class hr {
1780
1789
  * The server answers 404 when the user has no such device.
1781
1790
  */
1782
1791
  revokeTrustedDevice(e) {
1783
- const t = P(l.TwoFactorTrustedDeviceRevoke, { id: e });
1792
+ const t = F(l.TwoFactorTrustedDeviceRevoke, { id: e });
1784
1793
  return this.axiosClient.delete(t);
1785
1794
  }
1786
1795
  }
1787
- class dr {
1796
+ class gr {
1788
1797
  constructor(e, t, s) {
1789
1798
  this.axiosClient = new E(e, t, s);
1790
1799
  }
@@ -1806,11 +1815,11 @@ class dr {
1806
1815
  return this.axiosClient.post(
1807
1816
  l.upgradeStart,
1808
1817
  e,
1809
- We({})
1818
+ Je({})
1810
1819
  );
1811
1820
  }
1812
1821
  }
1813
- class lr {
1822
+ class vr {
1814
1823
  constructor(e, t, s) {
1815
1824
  this.axiosClient = new E(e, t, s);
1816
1825
  }
@@ -1855,8 +1864,27 @@ class lr {
1855
1864
  });
1856
1865
  }
1857
1866
  }
1867
+ const X = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", mr = 32, tt = (r) => {
1868
+ let e = "";
1869
+ for (let t = 0; t < r.length; t += 3) {
1870
+ const s = r[t], i = r[t + 1], n = r[t + 2];
1871
+ e += X.charAt(s >> 2), e += X.charAt((s & 3) << 4 | (i ?? 0) >> 4), i !== void 0 && (e += X.charAt((i & 15) << 2 | (n ?? 0) >> 6)), n !== void 0 && (e += X.charAt(n & 63));
1872
+ }
1873
+ return e;
1874
+ }, rt = () => {
1875
+ const r = globalThis.crypto;
1876
+ if (!r?.subtle)
1877
+ throw new Error("PKCE needs the Web Crypto API, which is available only in a secure context (https or localhost)");
1878
+ return r;
1879
+ }, yr = async (r) => {
1880
+ const e = await rt().subtle.digest("SHA-256", new TextEncoder().encode(r));
1881
+ return tt(new Uint8Array(e));
1882
+ }, kr = async () => {
1883
+ const r = tt(rt().getRandomValues(new Uint8Array(mr)));
1884
+ return { verifier: r, challenge: await yr(r) };
1885
+ };
1858
1886
  var c = /* @__PURE__ */ ((r) => (r.SignIn = "signin", r.SignInStart = "signin:start", r.Register = "register", r.RegisterStart = "register:start", r.SignOut = "signout", r.SessionRestored = "session:restored", r.SessionExpired = "session:expired", r.Error = "error", r.Refresh = "refresh", r.RefreshStart = "refresh:start", r.TokenCacheExpired = "token-cache-expired", r.TwoFactorRequired = "2fa:required", r.TwoFactorSetupStarted = "2fa:setup_started", r.TwoFactorEnabled = "2fa:enabled", r.TwoFactorDisabled = "2fa:disabled", r.TwoFactorVerified = "2fa:verified", r.TwoFactorRecoveryUsed = "2fa:recovery_used", r.TwoFactorRecoveryCodesLow = "2fa:recovery_low", r.TwoFactorRecoveryCodesExhausted = "2fa:recovery_exhausted", r.TwoFactorSetupMagicLinkValidated = "2fa:magic_link_validated", r.TwoFactorSetupMagicLinkFailed = "2fa:magic_link_failed", r.TwoFactorChallengeReceived = "two_factor_challenge_received", r.TwoFactorMethodSwitched = "two_factor_method_switched", r.TwoFactorDeviceTrusted = "two_factor_device_trusted", r))(c || {});
1859
- class ur {
1887
+ class wr {
1860
1888
  constructor() {
1861
1889
  this.subscribers = /* @__PURE__ */ new Map();
1862
1890
  }
@@ -1910,18 +1938,18 @@ const k = {
1910
1938
  twoFactorNotEnabled: "error.2fa.not_enabled",
1911
1939
  notImplemented: "error.not.implemented",
1912
1940
  tokenInvalid: "error.api.request.token.invalid"
1913
- }, pr = Object.freeze([
1941
+ }, Sr = Object.freeze([
1914
1942
  k.twoFactorCodeInvalid,
1915
1943
  k.twoFactorNotEnabled,
1916
1944
  k.challengeInvalid,
1917
1945
  k.challengeSessionMismatch,
1918
1946
  k.challengeTooManyAttempts
1919
- ]), fr = Object.freeze([k.tokenInvalid]), gr = Object.freeze([
1947
+ ]), br = Object.freeze([k.tokenInvalid]), Tr = Object.freeze([
1920
1948
  "wrong_code",
1921
1949
  "challenge_spent",
1922
1950
  "not_registered",
1923
1951
  "prepare_not_required"
1924
- ]), vr = (r) => gr.includes(r), mr = {
1952
+ ]), _r = (r) => Tr.includes(r), Er = {
1925
1953
  wrong_code: "That code was not accepted. Try again.",
1926
1954
  challenge_spent: "That verification challenge is no longer valid. Start again.",
1927
1955
  exhausted: "Too many attempts. Try again later.",
@@ -1936,17 +1964,17 @@ const k = {
1936
1964
  };
1937
1965
  class _ extends Error {
1938
1966
  constructor(e) {
1939
- super(e.message || mr[e.kind]), this.name = "UpgradeTransportError", this.code = "upgrade_transport", this.kind = e.kind, this.status = e.status, this.errorId = e.errorId, this.retryable = vr(e.kind), e.cause !== void 0 && (this.cause = e.cause);
1967
+ super(e.message || Er[e.kind]), this.name = "UpgradeTransportError", this.code = "upgrade_transport", this.kind = e.kind, this.status = e.status, this.errorId = e.errorId, this.retryable = _r(e.kind), e.cause !== void 0 && (this.cause = e.cause);
1940
1968
  }
1941
1969
  }
1942
- const yr = Object.freeze([
1970
+ const Ir = Object.freeze([
1943
1971
  "upgrade_transport",
1944
1972
  "upgrade_insufficient",
1945
1973
  "upgrade_unavailable",
1946
1974
  "upgrade_session_changed",
1947
1975
  "upgrade_cancelled",
1948
1976
  "upgrade_unsatisfiable"
1949
- ]), Qe = (r) => typeof r == "object" && r !== null && typeof r.code == "string" && yr.includes(r.code), kr = (r) => r instanceof _ || typeof r == "object" && r !== null && r.code === "upgrade_transport", wr = (r) => {
1977
+ ]), st = (r) => typeof r == "object" && r !== null && typeof r.code == "string" && Ir.includes(r.code), Ar = (r) => r instanceof _ || typeof r == "object" && r !== null && r.code === "upgrade_transport", Cr = (r) => {
1950
1978
  if (typeof r != "object" || r === null)
1951
1979
  return { hasResponse: !1, message: typeof r == "string" ? r : void 0 };
1952
1980
  const e = r, t = e.response, s = t?.data, i = typeof s?.error?.id == "string" ? s.error.id : void 0;
@@ -1956,7 +1984,7 @@ const yr = Object.freeze([
1956
1984
  message: typeof e.message == "string" ? e.message : void 0,
1957
1985
  hasResponse: t !== void 0 || typeof e.status == "number"
1958
1986
  };
1959
- }, Sr = (r, e) => {
1987
+ }, Rr = (r, e) => {
1960
1988
  switch (r) {
1961
1989
  case k.twoFactorCodeInvalid:
1962
1990
  return "wrong_code";
@@ -2005,13 +2033,13 @@ const yr = Object.freeze([
2005
2033
  default:
2006
2034
  return;
2007
2035
  }
2008
- }, br = (r, e) => r === void 0 ? "network" : r === 501 ? "unavailable" : r === 400 ? "fatal" : r === 401 || r === 403 ? e === "start" ? "challenge_spent" : "session_changed" : r >= 500 ? "network" : "fatal", Ce = (r, e) => {
2036
+ }, Pr = (r, e) => r === void 0 ? "network" : r === 501 ? "unavailable" : r === 400 ? "fatal" : r === 401 || r === 403 ? e === "start" ? "challenge_spent" : "session_changed" : r >= 500 ? "network" : "fatal", Pe = (r, e) => {
2009
2037
  if (r instanceof _)
2010
2038
  return r;
2011
- const t = wr(r);
2039
+ const t = Cr(r);
2012
2040
  if (!t.hasResponse)
2013
2041
  return new _({ kind: "network", message: t.message, cause: r });
2014
- const s = Sr(t.errorId, e) ?? br(t.status, e);
2042
+ const s = Rr(t.errorId, e) ?? Pr(t.status, e);
2015
2043
  return new _({
2016
2044
  kind: s,
2017
2045
  message: t.message,
@@ -2019,62 +2047,80 @@ const yr = Object.freeze([
2019
2047
  errorId: t.errorId,
2020
2048
  cause: r
2021
2049
  });
2022
- }, Xs = (r) => r.errorId !== void 0 && pr.includes(r.errorId), Tr = (r) => r.errorId !== void 0 && fr.includes(r.errorId);
2023
- class j extends Error {
2050
+ }, ii = (r) => r.errorId !== void 0 && Sr.includes(r.errorId), Fr = (r) => r.errorId !== void 0 && br.includes(r.errorId);
2051
+ class G extends Error {
2024
2052
  constructor(e, t, s) {
2025
2053
  super(s ?? "The session was elevated, but this action requires a higher assurance level"), this.name = "UpgradeInsufficientError", this.code = "upgrade_insufficient", this.obtained = e, this.required = t;
2026
2054
  }
2027
2055
  }
2028
- class G extends Error {
2056
+ class j extends Error {
2029
2057
  constructor(e = "Step-up verification is not available on this deployment") {
2030
2058
  super(e), this.name = "UpgradeUnavailableError", this.code = "upgrade_unavailable";
2031
2059
  }
2032
2060
  }
2033
- class $ extends Error {
2061
+ class q extends Error {
2034
2062
  constructor(e = "The session changed during verification") {
2035
2063
  super(e), this.name = "UpgradeSessionChangedError", this.code = "upgrade_session_changed";
2036
2064
  }
2037
2065
  }
2038
- const _r = (r) => {
2066
+ const Mr = (r) => {
2039
2067
  if (!(!r || typeof r.sub != "string" || r.sub === ""))
2040
2068
  return typeof r.sid == "string" && r.sid !== "" ? { sub: r.sub, sid: r.sid } : { sub: r.sub };
2041
- }, Er = (r, e) => !e || e.sub !== r.sub ? !1 : r.sid !== void 0 && e.sid !== void 0 ? r.sid === e.sid : !0;
2042
- function X(r) {
2069
+ }, Ur = (r, e) => !e || e.sub !== r.sub ? !1 : r.sid !== void 0 && e.sid !== void 0 ? r.sid === e.sid : !0;
2070
+ function J(r) {
2043
2071
  if (!r || typeof r != "string") return !1;
2044
2072
  const e = r.split(".");
2045
2073
  if (e.length !== 3) return !1;
2046
2074
  const t = /^[A-Za-z0-9_-]+$/;
2047
2075
  return e.every((s) => t.test(s) && s.length > 0);
2048
2076
  }
2049
- function Ir(r) {
2050
- return r.replace(/<[^>]*>/g, "").substring(0, Ut);
2077
+ function Dr(r) {
2078
+ return r.replace(/<[^>]*>/g, "").substring(0, qt);
2051
2079
  }
2052
- function ne(r) {
2080
+ function oe(r) {
2053
2081
  if (!r || typeof r != "string") return !1;
2054
2082
  const e = r.trim();
2055
2083
  return e.length === 0 ? !1 : /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
2056
2084
  }
2057
- function oe(r) {
2085
+ function ae(r) {
2058
2086
  if (!r || typeof r != "string") return !1;
2059
2087
  const e = r.trim();
2060
2088
  return /^\+[1-9]\d{1,14}$/.test(e);
2061
2089
  }
2062
- function Ar(r) {
2090
+ function xr(r) {
2063
2091
  if (!r || typeof r != "string") return !1;
2064
2092
  const e = r.trim();
2065
- return e.length < Mt || e.length > Dt ? !1 : /^[a-zA-Z0-9_-]+$/.test(e);
2093
+ return e.length < Lt || e.length > $t ? !1 : /^[a-zA-Z0-9_-]+$/.test(e);
2066
2094
  }
2067
- function J(r, e = 6) {
2095
+ function Z(r, e = 6) {
2068
2096
  return !r || typeof r != "string" ? !1 : (e === 8 ? /^\d{8}$/ : /^\d{6}$/).test(r);
2069
2097
  }
2070
- function Cr(r) {
2098
+ function Or(r) {
2071
2099
  if (!r || typeof r != "string") return null;
2072
2100
  const e = r.toUpperCase().replace(/\s+/g, "");
2073
2101
  return /^[A-Z0-9-]{4,16}$/.test(e) ? e : null;
2074
2102
  }
2075
- class Rr {
2076
- constructor(e, t, s, i, n, o, a, h, p, m, d, g = Y) {
2077
- this.authApi = e, this.deviceService = t, this.storageManager = s, this.subscribeStore = i, this.tokenCacheService = n, this.scopes = o, this.createTenantForNewUser = a, this.url = h, this.sessionCallbacks = p, this.appId = m, this.platform = g, this.tokenExchangeConfig = d, this.tokenDeliveryManager = new Ne(s), d?.enabled && this.tokenDeliveryManager.setMode(A.BFF), this.initializeSession();
2103
+ class Lr {
2104
+ error(e, ...t) {
2105
+ console.error(e, ...t);
2106
+ }
2107
+ warn(e, ...t) {
2108
+ console.warn(e, ...t);
2109
+ }
2110
+ info(e, ...t) {
2111
+ console.info(e, ...t);
2112
+ }
2113
+ debug(e, ...t) {
2114
+ console.debug(e, ...t);
2115
+ }
2116
+ }
2117
+ function it() {
2118
+ return new Lr();
2119
+ }
2120
+ const ce = "passflow_2fa_pkce", $r = 300 * 1e3;
2121
+ class qr {
2122
+ constructor(e, t, s, i, n, o, a, h, u, m, d, g = Y, f) {
2123
+ this.authApi = e, this.deviceService = t, this.storageManager = s, this.subscribeStore = i, this.tokenCacheService = n, this.scopes = o, this.createTenantForNewUser = a, this.url = h, this.sessionCallbacks = u, this.appId = m, this.platform = g, this.readPkceEnabled = f, this.tokenExchangeConfig = d, this.tokenDeliveryManager = new Ke(s), d?.enabled && this.tokenDeliveryManager.setMode(A.BFF), this.initializeSession();
2078
2124
  }
2079
2125
  /**
2080
2126
  * Initialize session state on page load for cookie/BFF mode
@@ -2114,6 +2160,8 @@ class Rr {
2114
2160
  * In BFF mode, forwards tokens to BFF server
2115
2161
  */
2116
2162
  async processAuthResponse(e, t) {
2163
+ if (e.code && !e.access_token)
2164
+ throw new Error("A PKCE authorization code was not exchanged, so there are no tokens to apply");
2117
2165
  this.tokenExchangeConfig?.enabled || "token_delivery" in e && e.token_delivery && this.tokenDeliveryManager.setMode(e.token_delivery), this.tokenDeliveryManager.setSessionValid(), this.tokenDeliveryManager.isBFFMode() && this.tokenExchangeConfig?.callbackUrl && await this.forwardTokensToBFF(e), e.scopes = t, this.storageManager.saveTokens(e, this.tokenDeliveryManager.getMode()), this.tokenCacheService.setTokensCache(e), e.csrf_token && this.storageManager.setCsrfToken(e.csrf_token);
2118
2166
  }
2119
2167
  /**
@@ -2125,15 +2173,99 @@ class Rr {
2125
2173
  * a session, so on `true` the caller returns it as it is — without
2126
2174
  * `processAuthResponse`, a `SignIn`/`Register` event or a session check.
2127
2175
  * The `TwoFactorRequired` event is what the TwoFactorService listens to, so
2128
- * its verify and recovery calls can carry the token.
2176
+ * its verify and recovery calls can carry the token. On a PKCE sign-in the
2177
+ * server keeps the login's challenge, so the second factor's answer is a code:
2178
+ * the verifier stays here for `completePkceSignIn`, off the public event.
2129
2179
  */
2130
- handlePendingSecondFactor(e, t) {
2131
- return e.requires_2fa !== !0 && !e.tfa_token ? !1 : (this.subscribeStore.notify(c.TwoFactorRequired, {
2180
+ handlePendingSecondFactor(e, t, s, i) {
2181
+ return e.requires_2fa !== !0 && !e.tfa_token ? !1 : (s ? this.rememberPkceSignIn(s.verifier, i) : this.forgetPkceSignIn(), this.subscribeStore.notify(c.TwoFactorRequired, {
2132
2182
  email: t || "",
2133
2183
  challengeId: e.challenge_id || "",
2134
2184
  tfaToken: e.tfa_token || ""
2135
2185
  }), !0);
2136
2186
  }
2187
+ /**
2188
+ * Keeps the verifier in memory, which is where it is read from first. The copy
2189
+ * in sessionStorage is only for a redirect or reload during the second factor,
2190
+ * which would otherwise lose the sign-in.
2191
+ */
2192
+ rememberPkceSignIn(e, t) {
2193
+ if (this.pendingPkce = { verifier: e, scopes: t, expiresAt: Date.now() + $r }, !(typeof sessionStorage > "u"))
2194
+ try {
2195
+ sessionStorage.setItem(ce, JSON.stringify(this.pendingPkce));
2196
+ } catch {
2197
+ }
2198
+ }
2199
+ readPendingPkce() {
2200
+ if (!this.pendingPkce && typeof sessionStorage < "u")
2201
+ try {
2202
+ const e = sessionStorage.getItem(ce);
2203
+ this.pendingPkce = e ? JSON.parse(e) : void 0;
2204
+ } catch {
2205
+ this.pendingPkce = void 0;
2206
+ }
2207
+ return this.pendingPkce && Date.now() >= this.pendingPkce.expiresAt && this.forgetPkceSignIn(), this.pendingPkce;
2208
+ }
2209
+ /** Whether a PKCE sign-in is waiting for the code its second factor answers with. */
2210
+ hasPendingPkceSignIn() {
2211
+ return this.readPendingPkce() !== void 0;
2212
+ }
2213
+ /** Drops the verifier of a pending sign-in. `TwoFactorService` calls this with its own state. */
2214
+ forgetPkceSignIn() {
2215
+ if (this.pendingPkce = void 0, !(typeof sessionStorage > "u"))
2216
+ try {
2217
+ sessionStorage.removeItem(ce);
2218
+ } catch {
2219
+ }
2220
+ }
2221
+ /**
2222
+ * The proof key for a sign-in on a PKCE app, undefined on any other app.
2223
+ *
2224
+ * It is sent whether or not the sign-in has a parent: the parent is added to
2225
+ * the request outside this SDK, so it is not visible here, and `pkce.Challenge`
2226
+ * on the server wants it under a device parent and ignores it under an OIDC one.
2227
+ * When the setting cannot be read the sign-in goes out without a challenge, and
2228
+ * a PKCE app refuses it with its own error.
2229
+ */
2230
+ async startPkce() {
2231
+ let e = !1;
2232
+ try {
2233
+ e = await this.readPkceEnabled?.() ?? !1;
2234
+ } catch (t) {
2235
+ it().warn("Passflow: could not read the app settings, so this sign-in sends no PKCE challenge", t);
2236
+ return;
2237
+ }
2238
+ return e ? kr() : void 0;
2239
+ }
2240
+ /**
2241
+ * Swaps a code in a sign-in's answer for what the code stands for; any other
2242
+ * answer passes through. That can still be a 2FA token: the server re-runs its
2243
+ * gate at the exchange unless the code records a passed second factor.
2244
+ */
2245
+ async exchangeCode(e, t) {
2246
+ return !e.code || !t ? e : await this.authApi.pkceExchange(e.code, t.verifier);
2247
+ }
2248
+ /**
2249
+ * Finishes a PKCE sign-in whose code came from its second factor: redeems the
2250
+ * code with the first factor's verifier and applies the tokens. `TwoFactorService`
2251
+ * is the caller, and clears the pending state once this has succeeded.
2252
+ */
2253
+ async completePkceSignIn(e) {
2254
+ const t = this.readPendingPkce();
2255
+ if (!t)
2256
+ throw new Error("The sign-in answered with a PKCE code, but its verifier is gone");
2257
+ const s = await this.authApi.pkceExchange(e, t.verifier);
2258
+ return await this.processAuthResponse(s, t.scopes ?? this.scopes), s;
2259
+ }
2260
+ /**
2261
+ * Applies tokens that were issued outside this service, honouring the delivery
2262
+ * mode: this is the one place they reach the BFF and browser storage, so no
2263
+ * caller saves them itself. An answer that carries no tokens is left alone.
2264
+ */
2265
+ async applyTokens(e) {
2266
+ const t = e;
2267
+ !t.access_token && !t.id_token && !t.token_delivery || await this.processAuthResponse(t, t.scopes ?? this.readPendingPkce()?.scopes ?? this.scopes);
2268
+ }
2137
2269
  /**
2138
2270
  * Forward tokens to BFF server for httpOnly cookie storage
2139
2271
  */
@@ -2159,7 +2291,7 @@ class Rr {
2159
2291
  throw new Error(`BFF token storage failed: ${t.status}`);
2160
2292
  }
2161
2293
  async signIn(e) {
2162
- if ("email" in e && e.email && !ne(e.email)) {
2294
+ if ("email" in e && e.email && !oe(e.email)) {
2163
2295
  const i = new Error("Invalid email format"), n = {
2164
2296
  message: "Invalid email format",
2165
2297
  originalError: i,
@@ -2167,7 +2299,7 @@ class Rr {
2167
2299
  };
2168
2300
  throw this.subscribeStore.notify(c.Error, n), i;
2169
2301
  }
2170
- if ("username" in e && e.username && !Ar(e.username)) {
2302
+ if ("username" in e && e.username && !xr(e.username)) {
2171
2303
  const i = new Error(
2172
2304
  "Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens"
2173
2305
  ), n = {
@@ -2177,7 +2309,7 @@ class Rr {
2177
2309
  };
2178
2310
  throw this.subscribeStore.notify(c.Error, n), i;
2179
2311
  }
2180
- if ("phone" in e && e.phone && !oe(e.phone)) {
2312
+ if ("phone" in e && e.phone && !ae(e.phone)) {
2181
2313
  const i = new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"), n = {
2182
2314
  message: "Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",
2183
2315
  originalError: i,
@@ -2189,11 +2321,14 @@ class Rr {
2189
2321
  const t = this.deviceService.getDeviceId(), s = this.platform.getDeviceType();
2190
2322
  e.scopes = e.scopes ?? this.scopes;
2191
2323
  try {
2192
- const i = await this.authApi.signIn(e, t, s);
2193
- return this.handlePendingSecondFactor(i, e.email) || (await this.processAuthResponse(i, e.scopes), this.subscribeStore.notify(c.SignIn, {
2194
- tokens: i,
2324
+ const i = await this.startPkce(), n = await this.authApi.signIn(i ? { ...e, code_challenge: i.challenge } : e, t, s);
2325
+ if (this.handlePendingSecondFactor(n, e.email, i, e.scopes))
2326
+ return n;
2327
+ const o = await this.exchangeCode(n, i);
2328
+ return this.handlePendingSecondFactor(o, e.email) || (await this.processAuthResponse(o, e.scopes), this.subscribeStore.notify(c.SignIn, {
2329
+ tokens: o,
2195
2330
  parsedTokens: this.tokenCacheService.getParsedTokens()
2196
- }), await this.submitSessionCheck()), i;
2331
+ }), await this.submitSessionCheck()), o;
2197
2332
  } catch (i) {
2198
2333
  const n = {
2199
2334
  message: i instanceof Error ? i.message : "Sign in failed",
@@ -2204,7 +2339,7 @@ class Rr {
2204
2339
  }
2205
2340
  }
2206
2341
  async signUp(e) {
2207
- if (e.user.email && !ne(e.user.email)) {
2342
+ if (e.user.email && !oe(e.user.email)) {
2208
2343
  const t = new Error("Invalid email format"), s = {
2209
2344
  message: "Invalid email format",
2210
2345
  originalError: t,
@@ -2212,7 +2347,7 @@ class Rr {
2212
2347
  };
2213
2348
  throw this.subscribeStore.notify(c.Error, s), t;
2214
2349
  }
2215
- if (e.user.phone_number && !oe(e.user.phone_number)) {
2350
+ if (e.user.phone_number && !ae(e.user.phone_number)) {
2216
2351
  const t = new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"), s = {
2217
2352
  message: "Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",
2218
2353
  originalError: t,
@@ -2222,11 +2357,14 @@ class Rr {
2222
2357
  }
2223
2358
  this.subscribeStore.notify(c.RegisterStart, { email: e.user.email }), e.scopes = e.scopes ?? this.scopes, e.create_tenant = this.createTenantForNewUser;
2224
2359
  try {
2225
- const t = await this.authApi.signUp(e);
2226
- return this.handlePendingSecondFactor(t, e.user.email) || (await this.processAuthResponse(t, e.scopes), this.subscribeStore.notify(c.Register, {
2227
- tokens: t,
2360
+ const t = await this.startPkce(), s = await this.authApi.signUp(t ? { ...e, code_challenge: t.challenge } : e);
2361
+ if (this.handlePendingSecondFactor(s, e.user.email, t, e.scopes))
2362
+ return s;
2363
+ const i = await this.exchangeCode(s, t);
2364
+ return this.handlePendingSecondFactor(i, e.user.email) || (await this.processAuthResponse(i, e.scopes), this.subscribeStore.notify(c.Register, {
2365
+ tokens: i,
2228
2366
  parsedTokens: this.tokenCacheService.getParsedTokens()
2229
- }), await this.submitSessionCheck()), t;
2367
+ }), await this.submitSessionCheck()), i;
2230
2368
  } catch (t) {
2231
2369
  const s = {
2232
2370
  message: t instanceof Error ? t.message : "Sign up failed",
@@ -2237,7 +2375,7 @@ class Rr {
2237
2375
  }
2238
2376
  }
2239
2377
  async passwordlessSignIn(e) {
2240
- if (e.email && !ne(e.email)) {
2378
+ if (e.email && !oe(e.email)) {
2241
2379
  const i = new Error("Invalid email format"), n = {
2242
2380
  message: "Invalid email format",
2243
2381
  originalError: i,
@@ -2245,7 +2383,7 @@ class Rr {
2245
2383
  };
2246
2384
  throw this.subscribeStore.notify(c.Error, n), i;
2247
2385
  }
2248
- if (e.phone && !oe(e.phone)) {
2386
+ if (e.phone && !ae(e.phone)) {
2249
2387
  const i = new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"), n = {
2250
2388
  message: "Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",
2251
2389
  originalError: i,
@@ -2301,7 +2439,7 @@ class Rr {
2301
2439
  } catch {
2302
2440
  }
2303
2441
  }
2304
- this.storageManager.deleteTokens(), this.storageManager.clearIdToken(), this.storageManager.clearCsrfToken(), this.tokenDeliveryManager.reset(), this.subscribeStore.notify(c.SignOut, {});
2442
+ this.forgetPkceSignIn(), this.storageManager.deleteTokens(), this.storageManager.clearIdToken(), this.storageManager.clearCsrfToken(), this.tokenDeliveryManager.reset(), this.subscribeStore.notify(c.SignOut, {});
2305
2443
  }
2306
2444
  /**
2307
2445
  * The session and user identity this client currently holds, or `undefined`
@@ -2313,13 +2451,12 @@ class Rr {
2313
2451
  * nothing to read and the answer is `undefined`.
2314
2452
  */
2315
2453
  readSessionPin() {
2316
- const e = this.storageManager.getToken(b.access_token);
2317
- if (e)
2318
- try {
2319
- return _r(T(e));
2320
- } catch {
2321
- return;
2322
- }
2454
+ try {
2455
+ const e = this.storageManager.getToken(b.access_token);
2456
+ return e ? Mr(T(e)) : void 0;
2457
+ } catch {
2458
+ return;
2459
+ }
2323
2460
  }
2324
2461
  /**
2325
2462
  * Refuses to APPLY tokens that belong to a different principal (§13.4
@@ -2343,10 +2480,10 @@ class Rr {
2343
2480
  * state — two different axes.
2344
2481
  */
2345
2482
  assertSessionPin(e) {
2346
- if (e && !Er(e, this.readSessionPin()))
2483
+ if (e && !Ur(e, this.readSessionPin()))
2347
2484
  throw console.warn(
2348
2485
  "[passflow] the session or user changed while a step-up upgrade was in flight; the elevated tokens were discarded and the live session was left untouched."
2349
- ), new $("The session changed during verification, so the elevated tokens were discarded");
2486
+ ), new q("The session changed during verification, so the elevated tokens were discarded");
2350
2487
  }
2351
2488
  /**
2352
2489
  * Refreshes the session, optionally committing an assurance upgrade.
@@ -2436,13 +2573,13 @@ class Rr {
2436
2573
  message: n instanceof Error ? n.message : "Token refresh failed",
2437
2574
  originalError: n,
2438
2575
  code: n instanceof w ? n.id : void 0,
2439
- details: K.isAxiosError(n) && n.response ? {
2576
+ details: B.isAxiosError(n) && n.response ? {
2440
2577
  status: n.response.status,
2441
2578
  data: n.response.data
2442
2579
  } : void 0
2443
2580
  };
2444
2581
  this.subscribeStore.notify(c.Error, o);
2445
- const a = K.isAxiosError(n) && n.response?.status && n.response.status >= 400 && n.response.status < 500;
2582
+ const a = B.isAxiosError(n) && n.response?.status && n.response.status >= 400 && n.response.status < 500;
2446
2583
  throw a && !e && (this.tokenCacheService.tokenExpiredFlag = !0, this.tokenCacheService.setTokensCache(void 0), this.storageManager.deleteTokens(), this.subscribeStore.notify(c.SessionExpired, { reason: "refresh_failed" })), n instanceof w ? n : a && !e ? new Error(`Getting unknown error message from server with code:${n.response?.status}`) : n;
2447
2584
  }
2448
2585
  }
@@ -2462,11 +2599,17 @@ class Rr {
2462
2599
  this.subscribeStore.notify(c.SignInStart, {});
2463
2600
  const i = new URLSearchParams(this.platform.getCurrentUrl()?.search ?? "").get("token") ?? void 0, n = t ?? this.scopes;
2464
2601
  try {
2465
- const o = await this.authApi.resetPassword(e, n, i);
2466
- return this.handlePendingSecondFactor(o) || (await this.processAuthResponse(o, n), this.subscribeStore.notify(c.SignIn, {
2467
- tokens: o,
2602
+ const o = await this.startPkce(), a = o ? await this.authApi.resetPassword(e, n, i, o.challenge) : await this.authApi.resetPassword(e, n, i);
2603
+ if (this.handlePendingSecondFactor(a, void 0, o, n))
2604
+ return a;
2605
+ const h = await this.exchangeCode(a, o);
2606
+ if (this.handlePendingSecondFactor(h))
2607
+ return h;
2608
+ const u = a.redirect_url ? { ...h, redirect_url: a.redirect_url } : h;
2609
+ return await this.processAuthResponse(u, n), this.subscribeStore.notify(c.SignIn, {
2610
+ tokens: u,
2468
2611
  parsedTokens: this.tokenCacheService.getParsedTokens()
2469
- }), await this.submitSessionCheck()), o;
2612
+ }), await this.submitSessionCheck(), u;
2470
2613
  } catch (o) {
2471
2614
  const a = {
2472
2615
  message: o instanceof Error ? o.message : "Password reset failed",
@@ -2482,20 +2625,23 @@ class Rr {
2482
2625
  const t = this.deviceService.getDeviceId(), s = this.platform.getDeviceType();
2483
2626
  e.scopes = e.scopes ?? this.scopes, e.create_tenant = this.createTenantForNewUser;
2484
2627
  try {
2485
- const { challenge_id: i, publicKey: n } = await this.authApi.passkeyRegisterStart(e, t, s, !this.appId);
2486
- n.user.id = this.platform.btoa(n.user.id);
2487
- const o = await this.platform.passkeys.startRegistration(n);
2488
- if (!o) throw new Error("Passkey registration was not completed");
2489
- const a = await this.authApi.passkeyRegisterComplete(
2490
- o,
2628
+ const i = await this.startPkce(), { challenge_id: n, publicKey: o } = await this.authApi.passkeyRegisterStart(
2629
+ i ? { ...e, code_challenge: i.challenge } : e,
2491
2630
  t,
2492
- i,
2631
+ s,
2493
2632
  !this.appId
2494
2633
  );
2495
- return this.handlePendingSecondFactor(a) || (await this.processAuthResponse(a, e.scopes), this.subscribeStore.notify(c.Register, {
2496
- tokens: a,
2634
+ o.user.id = this.platform.btoa(o.user.id);
2635
+ const a = await this.platform.passkeys.startRegistration(o);
2636
+ if (!a) throw new Error("Passkey registration was not completed");
2637
+ const h = await this.authApi.passkeyRegisterComplete(a, t, n, !this.appId);
2638
+ if (this.handlePendingSecondFactor(h, void 0, i, e.scopes))
2639
+ return h;
2640
+ const u = await this.exchangeCode(h, i);
2641
+ return this.handlePendingSecondFactor(u) || (await this.processAuthResponse(u, e.scopes), this.subscribeStore.notify(c.Register, {
2642
+ tokens: u,
2497
2643
  parsedTokens: this.tokenCacheService.getParsedTokens()
2498
- }), await this.submitSessionCheck()), a;
2644
+ }), await this.submitSessionCheck()), u;
2499
2645
  } catch (i) {
2500
2646
  const n = {
2501
2647
  message: i instanceof Error ? i.message : "Passkey registration failed",
@@ -2511,18 +2657,21 @@ class Rr {
2511
2657
  const t = this.deviceService.getDeviceId(), s = this.platform.getDeviceType();
2512
2658
  e.scopes = e.scopes ?? this.scopes;
2513
2659
  try {
2514
- const { challenge_id: i, publicKey: n } = await this.authApi.passkeyAuthenticateStart(e, t, s, !this.appId), o = await this.platform.passkeys.startAuthentication(n);
2515
- if (!o) throw new Error("Passkey authentication was not completed");
2516
- const a = await this.authApi.passkeyAuthenticateComplete(
2517
- o,
2660
+ const i = await this.startPkce(), { challenge_id: n, publicKey: o } = await this.authApi.passkeyAuthenticateStart(
2661
+ i ? { ...e, code_challenge: i.challenge } : e,
2518
2662
  t,
2519
- i,
2663
+ s,
2520
2664
  !this.appId
2521
- );
2522
- return this.handlePendingSecondFactor(a) || "access_token" in a && (await this.processAuthResponse(a, e.scopes), this.subscribeStore.notify(c.SignIn, {
2523
- tokens: a,
2665
+ ), a = await this.platform.passkeys.startAuthentication(o);
2666
+ if (!a) throw new Error("Passkey authentication was not completed");
2667
+ const h = await this.authApi.passkeyAuthenticateComplete(a, t, n, !this.appId);
2668
+ if (this.handlePendingSecondFactor(h, void 0, i, e.scopes))
2669
+ return h;
2670
+ const u = await this.exchangeCode(h, i);
2671
+ return this.handlePendingSecondFactor(u) || "access_token" in u && (await this.processAuthResponse(u, e.scopes), this.subscribeStore.notify(c.SignIn, {
2672
+ tokens: u,
2524
2673
  parsedTokens: this.tokenCacheService.getParsedTokens()
2525
- }), await this.submitSessionCheck()), a;
2674
+ }), await this.submitSessionCheck()), u;
2526
2675
  } catch (i) {
2527
2676
  const n = {
2528
2677
  message: i instanceof Error ? i.message : "Passkey authentication failed",
@@ -2555,9 +2704,9 @@ class Rr {
2555
2704
  }), o = new URLSearchParams(n.callbackHash.replace(/^#/, ""));
2556
2705
  if (this.handlePendingSecondFactor({ tfa_token: o.get("tfa_token") ?? void 0 }))
2557
2706
  return;
2558
- const a = new URLSearchParams(n.callbackSearch), h = a.get("access_token") || "", p = a.get("refresh_token") || "", m = a.get("id_token") || "", d = {
2707
+ const a = new URLSearchParams(n.callbackSearch), h = a.get("access_token") || "", u = a.get("refresh_token") || "", m = a.get("id_token") || "", d = {
2559
2708
  access_token: h,
2560
- refresh_token: p || void 0,
2709
+ refresh_token: u || void 0,
2561
2710
  id_token: m || void 0,
2562
2711
  scopes: t
2563
2712
  };
@@ -2568,7 +2717,7 @@ class Rr {
2568
2717
  } catch (n) {
2569
2718
  const o = {
2570
2719
  message: n instanceof Error ? n.message : "Authentication failed",
2571
- code: n instanceof Be ? "POPUP_CLOSED" : "AUTH_FAILED",
2720
+ code: n instanceof Ge ? "POPUP_CLOSED" : "AUTH_FAILED",
2572
2721
  originalError: n
2573
2722
  };
2574
2723
  this.subscribeStore.notify(c.Error, o);
@@ -2588,8 +2737,8 @@ class Rr {
2588
2737
  appId: n ?? this.appId ?? "",
2589
2738
  redirectto: s ?? this.platform.getCurrentUrl()?.href ?? "",
2590
2739
  scopes: a.join(",")
2591
- }, p = new URLSearchParams(h);
2592
- return o.search = p.toString(), o.toString();
2740
+ }, u = new URLSearchParams(h);
2741
+ return o.search = u.toString(), o.toString();
2593
2742
  } catch (t) {
2594
2743
  const s = {
2595
2744
  message: t instanceof Error ? t.message : "Failed to create auth redirect URL",
@@ -2669,7 +2818,7 @@ class Rr {
2669
2818
  }
2670
2819
  }
2671
2820
  }
2672
- class Fr {
2821
+ class Nr {
2673
2822
  constructor(e) {
2674
2823
  this.invitationApi = e;
2675
2824
  }
@@ -2714,24 +2863,7 @@ class Fr {
2714
2863
  return this.invitationApi.getInvitationLink(e);
2715
2864
  }
2716
2865
  }
2717
- class Pr {
2718
- error(e, ...t) {
2719
- console.error(e, ...t);
2720
- }
2721
- warn(e, ...t) {
2722
- console.warn(e, ...t);
2723
- }
2724
- info(e, ...t) {
2725
- console.info(e, ...t);
2726
- }
2727
- debug(e, ...t) {
2728
- console.debug(e, ...t);
2729
- }
2730
- }
2731
- function Mr() {
2732
- return new Pr();
2733
- }
2734
- class Dr {
2866
+ class Vr {
2735
2867
  constructor(e) {
2736
2868
  this.data = this.normalize(e);
2737
2869
  }
@@ -2801,9 +2933,9 @@ class Dr {
2801
2933
  return this.data;
2802
2934
  }
2803
2935
  }
2804
- class Ur {
2936
+ class Kr {
2805
2937
  constructor(e, t, s) {
2806
- this.tenantApi = e, this.scopes = t, this.logger = s || Mr();
2938
+ this.tenantApi = e, this.scopes = t, this.logger = s || it();
2807
2939
  }
2808
2940
  /**
2809
2941
  * Handle Passflow API errors
@@ -2812,7 +2944,7 @@ class Ur {
2812
2944
  * @throws Formatted error with Passflow API error details
2813
2945
  */
2814
2946
  handlePassflowError(e, t) {
2815
- if (K.isAxiosError(e) && e.response?.data) {
2947
+ if (B.isAxiosError(e) && e.response?.data) {
2816
2948
  const s = e.response.data;
2817
2949
  if (typeof s == "object" && s !== null && "error" in s && typeof s.error == "object" && s.error !== null) {
2818
2950
  const i = s.error;
@@ -2873,7 +3005,7 @@ class Ur {
2873
3005
  async getTenantUserMembership(e) {
2874
3006
  try {
2875
3007
  const t = await this.tenantApi.getTenantDetails(e);
2876
- return new Dr(t);
3008
+ return new Vr(t);
2877
3009
  } catch (t) {
2878
3010
  this.handlePassflowError(t, `Get tenant user membership failed for tenant ID ${e}`);
2879
3011
  }
@@ -3171,7 +3303,7 @@ class Ur {
3171
3303
  }
3172
3304
  }
3173
3305
  }
3174
- class xr {
3306
+ class Br {
3175
3307
  constructor(e, t, s, i = Y) {
3176
3308
  this.storageManager = e, this.authApi = t, this.subscribeStore = s, this.platform = i, this.checkInterval = null, this.CHECK_INTERVAL = 6e4, this.unsubscribeForeground = null, this.unsubscribeUnload = null, this.isRefreshing = !1, this.tokenExpiredFlag = !1, this.storageManager = e, this.authApi = t, this.setupLifecycleListeners();
3177
3309
  }
@@ -3270,19 +3402,19 @@ class xr {
3270
3402
  return C(e);
3271
3403
  }
3272
3404
  }
3273
- class Or {
3274
- constructor(e, t) {
3275
- this.twoFactorApi = e, this.subscribeStore = t, this.PARTIAL_AUTH_TIMEOUT_MS = 300 * 1e3, this.SESSION_STORAGE_KEY = "passflow_2fa_challenge", this.totpDigits = 6;
3276
- const s = {
3277
- onAuthChange: (i, n) => {
3278
- if (i === c.TwoFactorRequired) {
3279
- const o = n;
3280
- this.setPartialAuthState(o.email, o.challengeId, o.tfaToken);
3405
+ class Gr {
3406
+ constructor(e, t, s) {
3407
+ this.twoFactorApi = e, this.subscribeStore = t, this.signInCompleter = s, this.PARTIAL_AUTH_TIMEOUT_MS = 300 * 1e3, this.SESSION_STORAGE_KEY = "passflow_2fa_challenge", this.totpDigits = 6;
3408
+ const i = {
3409
+ onAuthChange: (n, o) => {
3410
+ if (n === c.TwoFactorRequired) {
3411
+ const a = o;
3412
+ this.setPartialAuthState(a.email, a.challengeId, a.tfaToken);
3281
3413
  }
3282
- (i === c.SignIn || i === c.Register) && this.clearPartialAuthState();
3414
+ (n === c.SignIn || n === c.Register) && this.clearPartialAuthState();
3283
3415
  }
3284
3416
  };
3285
- this.subscribeStore.subscribe(s, [
3417
+ this.subscribeStore.subscribe(i, [
3286
3418
  c.TwoFactorRequired,
3287
3419
  c.SignIn,
3288
3420
  c.Register
@@ -3328,7 +3460,7 @@ class Or {
3328
3460
  * Returns recovery codes that MUST be displayed to user
3329
3461
  */
3330
3462
  async confirmSetup(e) {
3331
- if (!J(e, this.totpDigits))
3463
+ if (!Z(e, this.totpDigits))
3332
3464
  throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);
3333
3465
  try {
3334
3466
  const t = await this.twoFactorApi.confirmSetup({ code: e });
@@ -3349,7 +3481,7 @@ class Or {
3349
3481
  * @param options.trustDevice - ask the server to trust this device for later sign-ins
3350
3482
  */
3351
3483
  async verify(e, t) {
3352
- if (!J(e, this.totpDigits))
3484
+ if (!Z(e, this.totpDigits))
3353
3485
  throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);
3354
3486
  if (this.recoverPartialAuthState(), !this.isVerificationRequired())
3355
3487
  throw new Error("2FA verification expired or not required. User must sign in first.");
@@ -3360,8 +3492,8 @@ class Or {
3360
3492
  code: e,
3361
3493
  tfa_token: this.partialAuthState.tfaToken,
3362
3494
  ...t?.trustDevice ? { trust_device: !0 } : {}
3363
- });
3364
- return this.clearPartialAuthState(), this.subscribeStore.notify(c.TwoFactorVerified, { tokens: s }), s;
3495
+ }), i = await this.finishSignIn(s);
3496
+ return this.subscribeStore.notify(c.TwoFactorVerified, { tokens: i }), i;
3365
3497
  } catch (s) {
3366
3498
  this.emitErrorAndThrow(s, "Verify 2FA code");
3367
3499
  }
@@ -3374,19 +3506,21 @@ class Or {
3374
3506
  */
3375
3507
  async useRecoveryCode(e, t) {
3376
3508
  try {
3377
- const s = Cr(e);
3509
+ const s = Or(e);
3378
3510
  if (!s)
3379
3511
  throw new Error("Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).");
3380
3512
  if (this.recoverPartialAuthState(), !this.isVerificationRequired())
3381
3513
  throw new Error("2FA verification expired or not required. User must sign in first.");
3382
3514
  if (!this.partialAuthState?.tfaToken)
3383
3515
  throw new Error("No TFA token found. User must sign in first.");
3384
- const i = await this.twoFactorApi.useRecoveryCode({
3385
- recovery_code: s,
3386
- tfa_token: this.partialAuthState.tfaToken,
3387
- ...t?.trustDevice ? { trust_device: !0 } : {}
3388
- });
3389
- return this.clearPartialAuthState(), i.remaining_recovery_codes === 0 ? this.subscribeStore.notify(c.TwoFactorRecoveryCodesExhausted, { tokens: i }) : i.remaining_recovery_codes <= 2 && this.subscribeStore.notify(c.TwoFactorRecoveryCodesLow, {
3516
+ const i = await this.finishSignIn(
3517
+ await this.twoFactorApi.useRecoveryCode({
3518
+ recovery_code: s,
3519
+ tfa_token: this.partialAuthState.tfaToken,
3520
+ ...t?.trustDevice ? { trust_device: !0 } : {}
3521
+ })
3522
+ );
3523
+ return i.remaining_recovery_codes === 0 ? this.subscribeStore.notify(c.TwoFactorRecoveryCodesExhausted, { tokens: i }) : i.remaining_recovery_codes <= 2 && this.subscribeStore.notify(c.TwoFactorRecoveryCodesLow, {
3390
3524
  tokens: i,
3391
3525
  remainingCodes: i.remaining_recovery_codes
3392
3526
  }), this.subscribeStore.notify(c.TwoFactorRecoveryUsed, {
@@ -3401,7 +3535,7 @@ class Or {
3401
3535
  * Disable 2FA (requires TOTP verification)
3402
3536
  */
3403
3537
  async disable(e) {
3404
- if (!J(e, this.totpDigits))
3538
+ if (!Z(e, this.totpDigits))
3405
3539
  throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);
3406
3540
  try {
3407
3541
  const t = await this.twoFactorApi.disable({ code: e });
@@ -3414,7 +3548,7 @@ class Or {
3414
3548
  * Regenerate recovery codes
3415
3549
  */
3416
3550
  async regenerateRecoveryCodes(e) {
3417
- if (!J(e, this.totpDigits))
3551
+ if (!Z(e, this.totpDigits))
3418
3552
  throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);
3419
3553
  try {
3420
3554
  const t = await this.twoFactorApi.regenerateRecoveryCodes({ code: e }), s = [...t.recovery_codes];
@@ -3452,12 +3586,34 @@ class Or {
3452
3586
  * Called on logout or successful verification
3453
3587
  */
3454
3588
  clearPartialAuthState() {
3455
- if (this.partialAuthState = void 0, typeof sessionStorage < "u")
3589
+ if (this.partialAuthState = void 0, this.signInCompleter?.forgetPkceSignIn(), typeof sessionStorage < "u")
3456
3590
  try {
3457
3591
  sessionStorage.removeItem(this.SESSION_STORAGE_KEY);
3458
3592
  } catch {
3459
3593
  }
3460
3594
  }
3595
+ /**
3596
+ * Ends the pending sign-in with the second factor's answer. On a PKCE app that
3597
+ * answer is a code, redeemed and replaced by the tokens, so no caller or
3598
+ * subscriber ever gets a code where tokens belong. Tokens are applied once, by
3599
+ * the completer, in the app's delivery mode. The pending state goes only after
3600
+ * that has worked, except when no verifier can ever redeem the code.
3601
+ */
3602
+ async finishSignIn(e) {
3603
+ const { code: t, ...s } = e;
3604
+ if (t && !this.signInCompleter?.hasPendingPkceSignIn()) {
3605
+ this.clearPartialAuthState();
3606
+ const n = new Error("The sign-in answered with a PKCE code, but its verifier is gone");
3607
+ throw n.id = "PKCE_VERIFIER_MISSING", n;
3608
+ }
3609
+ let i = e;
3610
+ if (t && this.signInCompleter) {
3611
+ const n = await this.signInCompleter.completePkceSignIn(t);
3612
+ i = { ...s, ...n };
3613
+ } else
3614
+ await this.signInCompleter?.applyTokens(i);
3615
+ return this.clearPartialAuthState(), i;
3616
+ }
3461
3617
  /**
3462
3618
  * The 2FA token of the sign-in waiting on its second factor, if any.
3463
3619
  */
@@ -3639,12 +3795,15 @@ class Or {
3639
3795
  async verifyV2(e) {
3640
3796
  try {
3641
3797
  const t = await this.twoFactorApi.verifyV2(e, this.pendingTfaToken());
3642
- return t.success && (this.clearPartialAuthState(), this.subscribeStore.notify(c.TwoFactorVerified, {
3798
+ if (!t.success)
3799
+ return t;
3800
+ const s = await this.finishSignIn(t);
3801
+ return this.subscribeStore.notify(c.TwoFactorVerified, {
3643
3802
  tokens: {
3644
- access_token: t.access_token,
3645
- refresh_token: t.refresh_token
3803
+ access_token: s.access_token,
3804
+ refresh_token: s.refresh_token
3646
3805
  }
3647
- }), t.device_trusted && this.subscribeStore.notify(c.TwoFactorDeviceTrusted, {})), t;
3806
+ }), s.device_trusted && this.subscribeStore.notify(c.TwoFactorDeviceTrusted, {}), s;
3648
3807
  } catch (t) {
3649
3808
  this.emitErrorAndThrow(t, "Verify 2FA challenge");
3650
3809
  }
@@ -3687,7 +3846,7 @@ class Or {
3687
3846
  }
3688
3847
  }
3689
3848
  }
3690
- class Lr {
3849
+ class jr {
3691
3850
  constructor(e, t, s = Y) {
3692
3851
  this.userAPI = e, this.deviceService = t, this.platform = s;
3693
3852
  }
@@ -3739,74 +3898,74 @@ class Lr {
3739
3898
  return await this.userAPI.addUserPasskeyComplete(h, i, o);
3740
3899
  }
3741
3900
  }
3742
- class U extends Error {
3901
+ class x extends Error {
3743
3902
  constructor(e, t, s = !1) {
3744
3903
  super(t), this.name = "UpgradeFactorError", this.factor = e, this.cancelled = s;
3745
3904
  }
3746
3905
  }
3747
- const et = (r, e) => {
3906
+ const nt = (r, e) => {
3748
3907
  const t = e?.trim();
3749
3908
  if (!t)
3750
- throw new U(r, "A verification code is required");
3909
+ throw new x(r, "A verification code is required");
3751
3910
  return t;
3752
- }, $r = {
3911
+ }, Hr = {
3753
3912
  type: "totp",
3754
3913
  requiresPrepare: !1,
3755
3914
  input: "code",
3756
- assert: async ({ code: r }) => ({ code: et("totp", r) })
3757
- }, qr = {
3915
+ assert: async ({ code: r }) => ({ code: nt("totp", r) })
3916
+ }, zr = {
3758
3917
  type: "recovery_codes",
3759
3918
  requiresPrepare: !1,
3760
3919
  input: "code",
3761
- assert: async ({ code: r }) => ({ code: et("recovery_codes", r) })
3762
- }, Nr = {
3920
+ assert: async ({ code: r }) => ({ code: nt("recovery_codes", r) })
3921
+ }, Yr = {
3763
3922
  type: "passkey",
3764
3923
  requiresPrepare: !0,
3765
3924
  input: "none",
3766
3925
  assert: async ({ prepared: r, platform: e }) => {
3767
3926
  if (!r?.webauthn)
3768
- throw new U("passkey", "The upgrade challenge carried no WebAuthn options");
3927
+ throw new x("passkey", "The upgrade challenge carried no WebAuthn options");
3769
3928
  const t = e.passkeys;
3770
3929
  if (!t)
3771
- throw new U("passkey", "This platform does not support passkeys");
3930
+ throw new x("passkey", "This platform does not support passkeys");
3772
3931
  let s;
3773
3932
  try {
3774
3933
  s = await t.startAuthentication(r.webauthn);
3775
3934
  } catch (i) {
3776
- throw new U("passkey", i?.message || "Passkey verification was cancelled", !0);
3935
+ throw new x("passkey", i?.message || "Passkey verification was cancelled", !0);
3777
3936
  }
3778
3937
  if (!s)
3779
- throw new U("passkey", "Passkey verification was cancelled", !0);
3938
+ throw new x("passkey", "Passkey verification was cancelled", !0);
3780
3939
  return { challenge_id: r.challengeId, credential: s };
3781
3940
  }
3782
- }, Se = Object.freeze([
3783
- $r,
3784
- Nr,
3785
- qr
3786
- ]), Vr = (r = Se) => new Map(r.map((e) => [e.type, e])), Br = 3, Kr = {
3941
+ }, Te = Object.freeze([
3942
+ Hr,
3943
+ Yr,
3944
+ zr
3945
+ ]), Wr = (r = Te) => new Map(r.map((e) => [e.type, e])), Xr = 3, Jr = {
3787
3946
  passkey: 0,
3788
3947
  totp: 1,
3789
3948
  email_otp: 2,
3790
3949
  sms_otp: 3,
3791
3950
  recovery_codes: 9
3792
- }, jr = (r) => r.requiredLevel ?? Vt(r.acrValues), Re = (r, e) => {
3793
- const t = Kr[r.type] ?? 5, s = e !== void 0 && e >= Br, i = r.type === "passkey";
3951
+ }, Zr = (r) => r.requiredLevel ?? Ht(r.acrValues), Fe = (r, e) => {
3952
+ const t = Jr[r.type] ?? 5, s = e !== void 0 && e >= Xr, i = r.type === "passkey";
3794
3953
  return (s && !i ? 100 : 0) + t;
3795
- }, Gr = (r, e) => {
3796
- const t = jr(e);
3797
- return [...r].sort((s, i) => Re(s, t) - Re(i, t));
3954
+ }, Qr = (r, e) => {
3955
+ const t = Zr(e);
3956
+ return [...r].sort((s, i) => Fe(s, t) - Fe(i, t));
3798
3957
  };
3799
- class O extends Error {
3958
+ class L extends Error {
3800
3959
  constructor(e) {
3801
3960
  super("Upgrade authentication was cancelled"), this.code = "upgrade_cancelled", this.name = "UpgradeCancelledError", e !== void 0 && (this.cause = e);
3802
3961
  }
3803
3962
  }
3804
- class ee extends Error {
3963
+ class te extends Error {
3805
3964
  constructor(e = "No available authentication factor can satisfy this challenge") {
3806
3965
  super(e), this.code = "upgrade_unsatisfiable", this.name = "UpgradeUnsatisfiableError";
3807
3966
  }
3808
3967
  }
3809
- const Hr = 4, zr = 3e4, Yr = () => {
3968
+ const es = 4, ts = 3e4, rs = () => {
3810
3969
  let r = () => {
3811
3970
  }, e = () => {
3812
3971
  };
@@ -3817,7 +3976,7 @@ const Hr = 4, zr = 3e4, Yr = () => {
3817
3976
  acrValues: r.acrValues,
3818
3977
  level: r.requiredLevel,
3819
3978
  maxAge: r.maxAge
3820
- }), Wr = (r, e) => e.level === void 0 ? !0 : r.level === void 0 ? !1 : r.level >= e.level, Xr = (r, e) => {
3979
+ }), ss = (r, e) => e.level === void 0 ? !0 : r.level === void 0 ? !1 : r.level >= e.level, is = (r, e) => {
3821
3980
  const t = r.requiredLevel === void 0 ? e.requiredLevel : e.requiredLevel === void 0 ? r.requiredLevel : Math.max(r.requiredLevel, e.requiredLevel), s = t === void 0 ? r.acrValues ?? e.acrValues : t === r.requiredLevel ? r.acrValues : e.acrValues, i = r.maxAge === void 0 ? e.maxAge : e.maxAge === void 0 ? r.maxAge : Math.min(r.maxAge, e.maxAge), n = Array.from(/* @__PURE__ */ new Set([...r.channels ?? [], ...e.channels ?? []]));
3822
3981
  return {
3823
3982
  acrValues: s,
@@ -3826,13 +3985,13 @@ const Hr = 4, zr = 3e4, Yr = () => {
3826
3985
  status: r.status,
3827
3986
  ...n.length > 0 ? { channels: n } : {}
3828
3987
  };
3829
- }, Jr = (r, e) => {
3988
+ }, ns = (r, e) => {
3830
3989
  const t = e.requiredLevel !== void 0 && (r.requiredLevel === void 0 || e.requiredLevel > r.requiredLevel), s = e.maxAge !== void 0 && (r.maxAge === void 0 || e.maxAge < r.maxAge);
3831
3990
  return t || s;
3832
3991
  };
3833
- class Zr {
3992
+ class os {
3834
3993
  constructor(e) {
3835
- this.state = "idle", this.inFlight = null, this.requirement = null, this.selected = null, this.rankedRequirement = null, this.registrations = [], this.proof = null, this.pruned = /* @__PURE__ */ new Set(), this.openPrompt = null, this.transport = e.transport, this.prompt = e.prompt, this.platform = e.platform, this.available = e.factors ?? Se, this.registry = Vr(this.available), this.maxAttempts = e.maxAttempts ?? Hr, this.readObtainedBar = e.readObtainedBar, this.onFlightSettled = e.onFlightSettled, this.settleTimeoutMs = e.replaySettleTimeoutMs ?? zr;
3994
+ this.state = "idle", this.inFlight = null, this.requirement = null, this.selected = null, this.rankedRequirement = null, this.registrations = [], this.proof = null, this.pruned = /* @__PURE__ */ new Set(), this.openPrompt = null, this.transport = e.transport, this.prompt = e.prompt, this.platform = e.platform, this.available = e.factors ?? Te, this.registry = Wr(this.available), this.maxAttempts = e.maxAttempts ?? es, this.readObtainedBar = e.readObtainedBar, this.onFlightSettled = e.onFlightSettled, this.settleTimeoutMs = e.replaySettleTimeoutMs ?? ts;
3836
3995
  }
3837
3996
  /** The current lifecycle state. Read-only. */
3838
3997
  get currentState() {
@@ -3871,7 +4030,7 @@ class Zr {
3871
4030
  const s = t.kind === "imperative" && t.requested !== void 0, n = {
3872
4031
  demanded: t.kind === "imperative" && t.requested ? t.requested : H(e),
3873
4032
  statedBar: s,
3874
- settlement: Yr(),
4033
+ settlement: rs(),
3875
4034
  reported: !1,
3876
4035
  entry: {
3877
4036
  ...t,
@@ -3899,13 +4058,13 @@ class Zr {
3899
4058
  this.requirement = e;
3900
4059
  return;
3901
4060
  }
3902
- const s = Jr(t, e);
3903
- this.requirement = Xr(t, e), s && this.state === "collecting" && this.selected === null && this.openPrompt?.onRequirementRaised?.({ challenge: this.requirement, factors: this.offeredFactors() });
4061
+ const s = ns(t, e);
4062
+ this.requirement = is(t, e), s && this.state === "collecting" && this.selected === null && this.openPrompt?.onRequirementRaised?.({ challenge: this.requirement, factors: this.offeredFactors() });
3904
4063
  }
3905
4064
  /** The factors to offer right now: ranked for the merged bar, minus what the server refused. */
3906
4065
  offeredFactors() {
3907
4066
  const e = this.available.filter((s) => !this.pruned.has(s.type)), t = this.requirement;
3908
- return t ? Gr(e, t) : e;
4067
+ return t ? Qr(e, t) : e;
3909
4068
  }
3910
4069
  /** The waiter's inbound edge. Idempotent — a second call is ignored. */
3911
4070
  receiveReport(e, t) {
@@ -3973,8 +4132,8 @@ class Zr {
3973
4132
  */
3974
4133
  release(e, t) {
3975
4134
  if (e.entry.kind === "imperative") {
3976
- if (e.statedBar && !Wr(t, e.demanded)) {
3977
- this.receiveReport(e, { outcome: "insufficient", obtained: t, required: e.demanded }), e.settlement.reject(new j(t, e.demanded));
4135
+ if (e.statedBar && !ss(t, e.demanded)) {
4136
+ this.receiveReport(e, { outcome: "insufficient", obtained: t, required: e.demanded }), e.settlement.reject(new G(t, e.demanded));
3978
4137
  return;
3979
4138
  }
3980
4139
  this.receiveReport(e, { outcome: "replayed", obtained: t }), e.settlement.resolve({ waiter: e.entry, obtained: t });
@@ -4049,26 +4208,26 @@ class Zr {
4049
4208
  for (let t = 0; t < this.maxAttempts; t++) {
4050
4209
  const s = this.offeredFactors();
4051
4210
  if (s.length === 0)
4052
- return { status: "failed", reason: new ee() };
4211
+ return { status: "failed", reason: new te() };
4053
4212
  const i = this.requirement;
4054
4213
  let n;
4055
4214
  try {
4056
4215
  n = await this.collect(i, s, e);
4057
4216
  } catch (a) {
4058
- return { status: "failed", reason: new O(a) };
4217
+ return { status: "failed", reason: new L(a) };
4059
4218
  }
4060
4219
  if (n.type === "cancel")
4061
- return { status: "failed", reason: new O() };
4220
+ return { status: "failed", reason: new L() };
4062
4221
  const o = this.registry.get(n.factor);
4063
4222
  if (!o) {
4064
- e = new ee(`Unknown authentication factor: ${n.factor}`), this.state = "collecting", this.selected = null;
4223
+ e = new te(`Unknown authentication factor: ${n.factor}`), this.state = "collecting", this.selected = null;
4065
4224
  continue;
4066
4225
  }
4067
4226
  try {
4068
4227
  return await this.proveAndCommit(o, n.code), { status: "proven", obtained: this.readObtainedBar?.() ?? H(this.rankedRequirement ?? i) };
4069
4228
  } catch (a) {
4070
- if (a instanceof U && a.cancelled)
4071
- return { status: "failed", reason: new O() };
4229
+ if (a instanceof x && a.cancelled)
4230
+ return { status: "failed", reason: new L() };
4072
4231
  const h = this.classifyProofFailure(a);
4073
4232
  if (h)
4074
4233
  return { status: "failed", reason: h };
@@ -4097,12 +4256,12 @@ class Zr {
4097
4256
  }
4098
4257
  /** Maps a proof failure to a terminal reason, or `undefined` when the user may retry. */
4099
4258
  classifyProofFailure(e) {
4100
- if (e instanceof j || e instanceof G || e instanceof $)
4259
+ if (e instanceof G || e instanceof j || e instanceof q)
4101
4260
  return e;
4102
4261
  if (e instanceof _)
4103
4262
  switch (e.kind) {
4104
4263
  case "unavailable":
4105
- return new G(e.message);
4264
+ return new j(e.message);
4106
4265
  case "exhausted":
4107
4266
  case "attempts_exhausted":
4108
4267
  case "fatal":
@@ -4110,7 +4269,7 @@ class Zr {
4110
4269
  case "network":
4111
4270
  return e;
4112
4271
  case "session_changed":
4113
- return new $(e.message);
4272
+ return new q(e.message);
4114
4273
  default:
4115
4274
  return;
4116
4275
  }
@@ -4121,14 +4280,14 @@ class Zr {
4121
4280
  await this.transport.commit(e.type, i);
4122
4281
  }
4123
4282
  }
4124
- const tt = "https://passflow-relative.invalid", Qr = () => {
4283
+ const ot = "https://passflow-relative.invalid", as = () => {
4125
4284
  const r = globalThis, e = r.document?.baseURI;
4126
4285
  if (typeof e == "string" && e !== "")
4127
4286
  return e;
4128
4287
  const t = r.location?.href;
4129
- return typeof t == "string" && t !== "" && t !== "about:blank" ? t : tt;
4130
- }, Fe = (r, e = Qr()) => {
4131
- const t = e === tt;
4288
+ return typeof t == "string" && t !== "" && t !== "about:blank" ? t : ot;
4289
+ }, Me = (r, e = as()) => {
4290
+ const t = e === ot;
4132
4291
  let s;
4133
4292
  try {
4134
4293
  s = new URL(e).origin;
@@ -4153,32 +4312,32 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4153
4312
  relativeToBase: s !== void 0 && i.origin === s,
4154
4313
  sentinelBase: t
4155
4314
  };
4156
- }, ae = (r, e) => typeof e == "string" ? [r.toLowerCase(), e] : void 0, es = (r) => {
4315
+ }, he = (r, e) => typeof e == "string" ? [r.toLowerCase(), e] : void 0, cs = (r) => {
4157
4316
  const e = [];
4158
4317
  if (r == null)
4159
4318
  return Object.freeze(e);
4160
4319
  const t = r;
4161
4320
  if (typeof t.forEach == "function" && typeof t.entries == "function")
4162
4321
  return r.forEach((s, i) => {
4163
- const n = ae(i, s);
4322
+ const n = he(i, s);
4164
4323
  n && e.push(n);
4165
4324
  }), Object.freeze(e);
4166
4325
  if (Array.isArray(r)) {
4167
4326
  for (const s of r)
4168
4327
  if (Array.isArray(s) && s.length >= 2) {
4169
- const i = ae(String(s[0]), s[1]);
4328
+ const i = he(String(s[0]), s[1]);
4170
4329
  i && e.push(i);
4171
4330
  }
4172
4331
  return Object.freeze(e);
4173
4332
  }
4174
4333
  if (typeof r == "object")
4175
4334
  for (const [s, i] of Object.entries(r)) {
4176
- const n = Array.isArray(i) ? i.join(", ") : i, o = ae(s, n);
4335
+ const n = Array.isArray(i) ? i.join(", ") : i, o = he(s, n);
4177
4336
  o && e.push(o);
4178
4337
  }
4179
4338
  return Object.freeze(e);
4180
- }, rt = (r) => {
4181
- const e = r.base === void 0 ? Fe(r.url) : Fe(r.url, r.base), t = {
4339
+ }, at = (r) => {
4340
+ const e = r.base === void 0 ? Me(r.url) : Me(r.url, r.base), t = {
4182
4341
  raw: r.url,
4183
4342
  href: e.href,
4184
4343
  dispatchUrl: e.sentinelBase || !e.resolved ? r.url : e.href,
@@ -4187,25 +4346,25 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4187
4346
  resolved: e.resolved,
4188
4347
  relativeToBase: e.relativeToBase,
4189
4348
  method: (r.method ?? "GET").toUpperCase(),
4190
- headers: es(r.headers),
4349
+ headers: cs(r.headers),
4191
4350
  bodyKind: r.bodyKind,
4192
4351
  ..."body" in r ? { body: r.body } : {}
4193
4352
  };
4194
4353
  return Object.freeze(t);
4195
- }, st = (r, e) => {
4354
+ }, ct = (r, e) => {
4196
4355
  if (!e || e.from === e.to)
4197
4356
  return r;
4198
4357
  let t = !1;
4199
4358
  const s = r.map(([i, n]) => i === "authorization" && n === e.from ? (t = !0, [i, e.to]) : [i, n]);
4200
4359
  return t ? Object.freeze(s) : r;
4201
- }, it = (r) => {
4360
+ }, ht = (r) => {
4202
4361
  const e = {};
4203
4362
  for (const [t, s] of r)
4204
4363
  e[t] = s;
4205
4364
  return e;
4206
- }, ts = new Set(
4207
- Se.filter((r) => !r.requiresPrepare).map((r) => r.type)
4208
- ), rs = (r) => {
4365
+ }, hs = new Set(
4366
+ Te.filter((r) => !r.requiresPrepare).map((r) => r.type)
4367
+ ), ds = (r) => {
4209
4368
  if (!r || typeof r != "object" || !r.challenge_id || !r.expires_at)
4210
4369
  throw new _({
4211
4370
  kind: "protocol",
@@ -4218,16 +4377,16 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4218
4377
  webauthn: r.webauthn,
4219
4378
  codeSentTo: r.code_sent_to
4220
4379
  };
4221
- }, Pe = (r) => Qe(r) && !kr(r), ss = (r) => ({
4380
+ }, Ue = (r) => st(r) && !Ar(r), ls = (r) => ({
4222
4381
  async prepare(e) {
4223
- if (!ts.has(e))
4382
+ if (!hs.has(e))
4224
4383
  try {
4225
4384
  const t = r.relyingPartyId?.(), s = await r.startUpgrade(t ? { method: e, relying_party_id: t } : { method: e });
4226
- return rs(s);
4385
+ return ds(s);
4227
4386
  } catch (t) {
4228
- if (Pe(t))
4387
+ if (Ue(t))
4229
4388
  throw t;
4230
- const s = Ce(t, "start");
4389
+ const s = Pe(t, "start");
4231
4390
  if (s.kind === "prepare_not_required")
4232
4391
  return;
4233
4392
  throw s;
@@ -4240,42 +4399,42 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4240
4399
  try {
4241
4400
  await r.commitRefresh({ type: e, assertion: t });
4242
4401
  } catch (i) {
4243
- if (Pe(i))
4402
+ if (Ue(i))
4244
4403
  throw i;
4245
- const n = Ce(i, "refresh");
4246
- throw n.status === 401 && Tr(n) && r.markSessionInvalid?.(), n;
4404
+ const n = Pe(i, "refresh");
4405
+ throw n.status === 401 && Fr(n) && r.markSessionInvalid?.(), n;
4247
4406
  }
4248
4407
  }
4249
- }), nt = (r) => typeof r == "function" ? r() : r, Me = (r) => {
4408
+ }), dt = (r) => typeof r == "function" ? r() : r, De = (r) => {
4250
4409
  try {
4251
4410
  return new URL(r);
4252
4411
  } catch {
4253
4412
  return;
4254
4413
  }
4255
- }, fe = (r, e) => {
4414
+ }, ve = (r, e) => {
4256
4415
  if (!e || e === "/")
4257
4416
  return !0;
4258
4417
  const t = e.replace(/\/+$/, "");
4259
4418
  return r === t || r.startsWith(`${t}/`);
4260
- }, is = (r, e) => !e || r.origin === void 0 ? !1 : r.origin === e.origin && fe(r.pathname, e.pathPrefix), ns = (r, e) => {
4419
+ }, us = (r, e) => !e || r.origin === void 0 ? !1 : r.origin === e.origin && ve(r.pathname, e.pathPrefix), ps = (r, e) => {
4261
4420
  for (const t of e) {
4262
4421
  if (t === "")
4263
4422
  continue;
4264
4423
  if (t.startsWith("/")) {
4265
- if (r.relativeToBase && fe(r.pathname, t))
4424
+ if (r.relativeToBase && ve(r.pathname, t))
4266
4425
  return !0;
4267
4426
  continue;
4268
4427
  }
4269
- const s = Me(t) ?? Me(`https://${t}`);
4270
- if (!(!s || r.origin === void 0) && r.origin === s.origin && fe(r.pathname, s.pathname))
4428
+ const s = De(t) ?? De(`https://${t}`);
4429
+ if (!(!s || r.origin === void 0) && r.origin === s.origin && ve(r.pathname, s.pathname))
4271
4430
  return !0;
4272
4431
  }
4273
4432
  return !1;
4274
- }, De = (r, e, t) => is(r, e.passflow) || ns(r, e.backend) ? t ? t(r.href) !== !1 : !0 : !1, ot = (r) => {
4433
+ }, xe = (r, e, t) => us(r, e.passflow) || ps(r, e.backend) ? t ? t(r.href) !== !1 : !0 : !1, lt = (r) => {
4275
4434
  const e = r.detail, t = e?.message ?? `[passflow] upgrade challenge not actioned: ${r.reason}`;
4276
4435
  console.warn(t, { status: r.status, url: r.url, reason: r.reason, detail: e });
4277
- }, os = (r, e) => {
4278
- const t = e.onUpgradeDiagnostic ?? ot;
4436
+ }, fs = (r, e) => {
4437
+ const t = e.onUpgradeDiagnostic ?? lt;
4279
4438
  return (s, i) => {
4280
4439
  t({
4281
4440
  status: r.status,
@@ -4284,12 +4443,12 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4284
4443
  detail: { method: r.request.method, ...i ?? {} }
4285
4444
  });
4286
4445
  };
4287
- }, ge = (r, e, t) => {
4288
- const s = t.onUpgradeDiagnostic ?? ot;
4446
+ }, me = (r, e, t) => {
4447
+ const s = t.onUpgradeDiagnostic ?? lt;
4289
4448
  for (const i of r)
4290
4449
  s({ ...i, url: e.request.href, detail: { method: e.request.method, ...i.detail ?? {} } });
4291
- }, as = /\bjson\b/i, ve = async (r, e) => {
4292
- const t = e.requireChallengeChannel === "header", s = r.getHeader("content-type") ?? "", i = !t && as.test(s);
4450
+ }, gs = /\bjson\b/i, ye = async (r, e) => {
4451
+ const t = e.requireChallengeChannel === "header", s = r.getHeader("content-type") ?? "", i = !t && gs.test(s);
4293
4452
  let n;
4294
4453
  if (i)
4295
4454
  try {
@@ -4298,23 +4457,23 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4298
4457
  n = void 0;
4299
4458
  }
4300
4459
  const o = i ? { status: r.status, getHeader: (a) => r.getHeader(a) ?? void 0, body: n } : { status: r.status, getHeader: (a) => r.getHeader(a) ?? void 0 };
4301
- return we(o, { requireChallengeChannel: e.requireChallengeChannel });
4302
- }, cs = (r) => we(
4460
+ return be(o, { requireChallengeChannel: e.requireChallengeChannel });
4461
+ }, vs = (r) => be(
4303
4462
  { status: r.status, getHeader: (e) => r.getHeader(e) ?? void 0 },
4304
4463
  { requireChallengeChannel: "header" }
4305
- ).challenge, hs = (r, e) => e.passflow === null ? `[passflow] a 401/403 from ${r} carried an upgrade challenge, but no Passflow endpoint is configured — set \`url\` on the Passflow config.` : `[passflow] a 401/403 from ${r} carried an upgrade challenge, but that URL is not covered by the provider's \`backend\` prop — add it there to enable step-up for this API.`, ds = (r, e) => r instanceof O ? { kind: "cancelled" } : r instanceof ee ? { kind: "unsatisfiable" } : r instanceof G ? { kind: "unavailable" } : r instanceof $ ? { kind: "session-changed" } : r instanceof j ? { kind: "insufficient", obtained: r.obtained, required: r.required } : r instanceof _ ? r.kind === "exhausted" || r.kind === "attempts_exhausted" ? { kind: "exhausted", error: r } : r.kind === "unavailable" ? { kind: "unavailable" } : r.kind === "session_changed" ? { kind: "session-changed" } : { kind: "transport-failure", status: r.status, retryable: r.retryable, error: r } : {
4464
+ ).challenge, ms = (r, e) => e.passflow === null ? `[passflow] a 401/403 from ${r} carried an upgrade challenge, but no Passflow endpoint is configured — set \`url\` on the Passflow config.` : `[passflow] a 401/403 from ${r} carried an upgrade challenge, but that URL is not covered by the provider's \`backend\` prop — add it there to enable step-up for this API.`, ys = (r, e) => r instanceof L ? { kind: "cancelled" } : r instanceof te ? { kind: "unsatisfiable" } : r instanceof j ? { kind: "unavailable" } : r instanceof q ? { kind: "session-changed" } : r instanceof G ? { kind: "insufficient", obtained: r.obtained, required: r.required } : r instanceof _ ? r.kind === "exhausted" || r.kind === "attempts_exhausted" ? { kind: "exhausted", error: r } : r.kind === "unavailable" ? { kind: "unavailable" } : r.kind === "session_changed" ? { kind: "session-changed" } : { kind: "transport-failure", status: r.status, retryable: r.retryable, error: r } : {
4306
4465
  kind: "transport-failure",
4307
4466
  retryable: !1,
4308
4467
  error: r instanceof Error ? r : new Error(String(r))
4309
- }, ls = async (r, e, t, s) => {
4468
+ }, ks = async (r, e, t, s) => {
4310
4469
  if (r.status !== 401 && r.status !== 403)
4311
4470
  return { kind: "replayed", response: r };
4312
- const { challenge: i, diagnostics: n } = await ve(r, e);
4313
- if (ge(n, r, e), !i)
4471
+ const { challenge: i, diagnostics: n } = await ye(r, e);
4472
+ if (me(n, r, e), !i)
4314
4473
  return { kind: "replayed", response: r };
4315
4474
  const o = H(i);
4316
4475
  return s("elevated-insufficient", { obtained: t, required: o }), { kind: "insufficient", obtained: t, required: o, response: r };
4317
- }, us = async (r, e) => {
4476
+ }, ws = async (r, e) => {
4318
4477
  if (!e)
4319
4478
  return { aborted: !1, value: await r };
4320
4479
  if (e.aborted)
@@ -4330,32 +4489,32 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4330
4489
  } finally {
4331
4490
  t && e.removeEventListener?.("abort", t);
4332
4491
  }
4333
- }, at = async (r, e) => {
4492
+ }, ut = async (r, e) => {
4334
4493
  if (r.status !== 401 && r.status !== 403)
4335
4494
  return { kind: "not-a-challenge" };
4336
4495
  if (r.markers.upgradeTransaction)
4337
4496
  return { kind: "not-a-challenge" };
4338
- const t = os(r, e);
4497
+ const t = fs(r, e);
4339
4498
  if (r.markers.replayed) {
4340
- if (!De(r.request, e.scope, e.shouldIntercept))
4499
+ if (!xe(r.request, e.scope, e.shouldIntercept))
4341
4500
  return { kind: "not-a-challenge" };
4342
- const { challenge: y, diagnostics: I } = await ve(r, e);
4343
- if (ge(I, r, e), !y)
4501
+ const { challenge: y, diagnostics: I } = await ye(r, e);
4502
+ if (me(I, r, e), !y)
4344
4503
  return { kind: "not-a-challenge" };
4345
- const W = e.readObtainedBar?.() ?? {}, _e = H(y);
4346
- return t("elevated-insufficient", { obtained: W, required: _e }), { kind: "insufficient", obtained: W, required: _e, response: r };
4504
+ const W = e.readObtainedBar?.() ?? {}, Ie = H(y);
4505
+ return t("elevated-insufficient", { obtained: W, required: Ie }), { kind: "insufficient", obtained: W, required: Ie, response: r };
4347
4506
  }
4348
- if (!De(r.request, e.scope, e.shouldIntercept))
4349
- return cs(r) ? (t("challenge-out-of-scope", {
4507
+ if (!xe(r.request, e.scope, e.shouldIntercept))
4508
+ return vs(r) ? (t("challenge-out-of-scope", {
4350
4509
  header: r.getHeader("www-authenticate") ?? void 0,
4351
- message: hs(r.request.href, e.scope)
4510
+ message: ms(r.request.href, e.scope)
4352
4511
  }), { kind: "out-of-scope" }) : { kind: "not-a-challenge" };
4353
- const { challenge: s, diagnostics: i } = await ve(r, e);
4354
- if (ge(i, r, e), !s) {
4355
- const u = r.getHeader("www-authenticate");
4512
+ const { challenge: s, diagnostics: i } = await ye(r, e);
4513
+ if (me(i, r, e), !s) {
4514
+ const p = r.getHeader("www-authenticate");
4356
4515
  return e.requireChallengeChannel !== "header" && t("no-channel", {
4357
- ...u ? { header: u } : {},
4358
- message: r.responseType === "cors" && !u ? `[passflow] a cross-origin ${r.status} from ${r.request.href} carried no readable challenge: \`WWW-Authenticate\` is not CORS-safelisted, so add \`Access-Control-Expose-Headers: WWW-Authenticate\` on that server, or have it emit the \`upgrade_required\` JSON body.` : `[passflow] a ${r.status} from ${r.request.href} carried no upgrade challenge on either channel; treated as an ordinary ${r.status}.`
4516
+ ...p ? { header: p } : {},
4517
+ message: r.responseType === "cors" && !p ? `[passflow] a cross-origin ${r.status} from ${r.request.href} carried no readable challenge: \`WWW-Authenticate\` is not CORS-safelisted, so add \`Access-Control-Expose-Headers: WWW-Authenticate\` on that server, or have it emit the \`upgrade_required\` JSON body.` : `[passflow] a ${r.status} from ${r.request.href} carried no upgrade challenge on either channel; treated as an ordinary ${r.status}.`
4359
4518
  }), { kind: "not-a-challenge" };
4360
4519
  }
4361
4520
  if (r.replayable === !1)
@@ -4365,45 +4524,45 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4365
4524
  const n = e.authorizationSwap?.(), o = { kind: "request", url: r.request.href, method: r.request.method };
4366
4525
  let a, h;
4367
4526
  try {
4368
- a = Promise.resolve(e.elevate(s, o)), h = await us(a, r.signal);
4369
- } catch (u) {
4370
- return ds(u);
4527
+ a = Promise.resolve(e.elevate(s, o)), h = await ws(a, r.signal);
4528
+ } catch (p) {
4529
+ return ys(p);
4371
4530
  }
4372
4531
  if (h.aborted)
4373
4532
  return a?.then(
4374
- (u) => u?.waiter.report({ outcome: "failed" }),
4533
+ (p) => p?.waiter.report({ outcome: "failed" }),
4375
4534
  () => {
4376
4535
  }
4377
4536
  ), { kind: "aborted", reason: h.reason };
4378
- const p = h.value;
4537
+ const u = h.value;
4379
4538
  if (r.signal?.aborted)
4380
- return p?.waiter.report({ outcome: "failed" }), { kind: "aborted", reason: r.signal.reason };
4381
- const m = p?.obtained ?? e.readObtainedBar?.() ?? H(s), d = e.authorizationSwap?.(), g = d ? { from: n?.from ?? d.from, to: d.to } : void 0;
4539
+ return u?.waiter.report({ outcome: "failed" }), { kind: "aborted", reason: r.signal.reason };
4540
+ const m = u?.obtained ?? e.readObtainedBar?.() ?? H(s), d = e.authorizationSwap?.(), g = d ? { from: n?.from ?? d.from, to: d.to } : void 0;
4382
4541
  r.markers.replayed = !0;
4383
4542
  let f;
4384
4543
  try {
4385
4544
  f = await r.replay(g ? { authorizationSwap: g } : void 0);
4386
- } catch (u) {
4387
- if (u instanceof j)
4388
- return p?.waiter.report({ outcome: "insufficient", obtained: u.obtained, required: u.required }), r.signal?.aborted ? { kind: "aborted", reason: r.signal.reason } : { kind: "insufficient", obtained: u.obtained, required: u.required };
4389
- if (p?.waiter.report({ outcome: "failed" }), r.signal?.aborted)
4545
+ } catch (p) {
4546
+ if (p instanceof G)
4547
+ return u?.waiter.report({ outcome: "insufficient", obtained: p.obtained, required: p.required }), r.signal?.aborted ? { kind: "aborted", reason: r.signal.reason } : { kind: "insufficient", obtained: p.obtained, required: p.required };
4548
+ if (u?.waiter.report({ outcome: "failed" }), r.signal?.aborted)
4390
4549
  return { kind: "aborted", reason: r.signal.reason };
4391
- throw u;
4550
+ throw p;
4392
4551
  }
4393
- const v = await ls(f, e, m, t);
4394
- return v.kind === "insufficient" ? p?.waiter.report({ outcome: "insufficient", obtained: v.obtained, required: v.required }) : p?.waiter.report({ outcome: "replayed", obtained: m }), v;
4395
- }, ps = (r) => {
4552
+ const v = await ks(f, e, m, t);
4553
+ return v.kind === "insufficient" ? u?.waiter.report({ outcome: "insufficient", obtained: v.obtained, required: v.required }) : u?.waiter.report({ outcome: "replayed", obtained: m }), v;
4554
+ }, Ss = (r) => {
4396
4555
  switch (r.kind) {
4397
4556
  case "cancelled":
4398
- return new O();
4557
+ return new L();
4399
4558
  case "unsatisfiable":
4400
- return new ee();
4559
+ return new te();
4401
4560
  case "unavailable":
4402
- return new G();
4561
+ return new j();
4403
4562
  case "session-changed":
4404
- return new $();
4563
+ return new q();
4405
4564
  case "insufficient":
4406
- return new j(r.obtained, r.required);
4565
+ return new G(r.obtained, r.required);
4407
4566
  case "exhausted":
4408
4567
  return r.error;
4409
4568
  case "transport-failure":
@@ -4411,7 +4570,7 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4411
4570
  default:
4412
4571
  return;
4413
4572
  }
4414
- }, fs = (r, e, t) => {
4573
+ }, bs = (r, e, t) => {
4415
4574
  switch (r.kind) {
4416
4575
  case "replayed":
4417
4576
  return { settle: "resolve", value: r.response.raw };
@@ -4422,47 +4581,47 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4422
4581
  case "aborted":
4423
4582
  return { settle: "reject", error: r.reason };
4424
4583
  case "cancelled":
4425
- return t.onCancel === "reject" ? { settle: "reject", error: new O() } : { settle: "resolve", value: ce(e, r) };
4584
+ return t.onCancel === "reject" ? { settle: "reject", error: new L() } : { settle: "resolve", value: de(e, r) };
4426
4585
  case "insufficient":
4427
- return { settle: "resolve", value: ce(r.response?.raw ?? e, r) };
4586
+ return { settle: "resolve", value: de(r.response?.raw ?? e, r) };
4428
4587
  default:
4429
- return { settle: "resolve", value: ce(e, r) };
4588
+ return { settle: "resolve", value: de(e, r) };
4430
4589
  }
4431
- }, gs = (r, e) => {
4590
+ }, Ts = (r, e) => {
4432
4591
  switch (r.kind) {
4433
4592
  case "replayed":
4434
4593
  return r.response.rejected ? { settle: "reject", error: r.response.raw ?? e } : { settle: "resolve", value: r.response.raw };
4435
4594
  case "aborted":
4436
4595
  return { settle: "reject", error: r.reason };
4437
4596
  default:
4438
- return { settle: "reject", error: ps(r) ?? e };
4597
+ return { settle: "reject", error: Ss(r) ?? e };
4439
4598
  }
4440
- }, ct = /* @__PURE__ */ new WeakSet(), ht = /* @__PURE__ */ new WeakSet(), dt = /* @__PURE__ */ new WeakSet(), lt = /* @__PURE__ */ new WeakSet(), ut = /* @__PURE__ */ new WeakSet(), pt = /* @__PURE__ */ new WeakSet(), ft = /* @__PURE__ */ new WeakSet(), ce = (r, e) => {
4599
+ }, pt = /* @__PURE__ */ new WeakSet(), ft = /* @__PURE__ */ new WeakSet(), gt = /* @__PURE__ */ new WeakSet(), vt = /* @__PURE__ */ new WeakSet(), mt = /* @__PURE__ */ new WeakSet(), yt = /* @__PURE__ */ new WeakSet(), kt = /* @__PURE__ */ new WeakSet(), de = (r, e) => {
4441
4600
  switch (e.kind) {
4442
4601
  case "cancelled":
4443
- ct.add(r);
4602
+ pt.add(r);
4444
4603
  break;
4445
4604
  case "exhausted":
4446
- ht.add(r);
4605
+ ft.add(r);
4447
4606
  break;
4448
4607
  case "insufficient":
4449
- dt.add(r);
4608
+ gt.add(r);
4450
4609
  break;
4451
4610
  case "unsatisfiable":
4452
- lt.add(r);
4611
+ vt.add(r);
4453
4612
  break;
4454
4613
  case "unavailable":
4455
- ut.add(r);
4614
+ mt.add(r);
4456
4615
  break;
4457
4616
  case "session-changed":
4458
- pt.add(r);
4617
+ yt.add(r);
4459
4618
  break;
4460
4619
  case "transport-failure":
4461
- ft.add(r);
4620
+ kt.add(r);
4462
4621
  break;
4463
4622
  }
4464
4623
  return r;
4465
- }, Js = (r) => ct.has(r), Zs = (r) => ht.has(r), Qs = (r) => dt.has(r), ei = (r) => lt.has(r), ti = (r) => ut.has(r), ri = (r) => pt.has(r), si = (r) => ft.has(r), vs = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]), re = (r) => typeof r == "object" && r !== null && typeof r.url == "string" && typeof r.clone == "function" && "method" in r, ms = (r) => typeof r == "string" ? r : re(r) ? r.url : String(r), ys = (r, e) => (e?.method ?? (re(r) ? r.method : void 0) ?? "GET").toUpperCase(), ks = (r) => r == null ? "none" : typeof r == "string" ? "reusable" : typeof r.getReader == "function" ? "one-shot" : "reusable", ws = (r) => {
4624
+ }, ni = (r) => pt.has(r), oi = (r) => ft.has(r), ai = (r) => gt.has(r), ci = (r) => vt.has(r), hi = (r) => mt.has(r), di = (r) => yt.has(r), li = (r) => kt.has(r), _s = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]), se = (r) => typeof r == "object" && r !== null && typeof r.url == "string" && typeof r.clone == "function" && "method" in r, Es = (r) => typeof r == "string" ? r : se(r) ? r.url : String(r), Is = (r, e) => (e?.method ?? (se(r) ? r.method : void 0) ?? "GET").toUpperCase(), As = (r) => r == null ? "none" : typeof r == "string" ? "reusable" : typeof r.getReader == "function" ? "one-shot" : "reusable", Cs = (r) => {
4466
4625
  if (typeof r == "string")
4467
4626
  return r.length;
4468
4627
  const e = r;
@@ -4470,7 +4629,7 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4470
4629
  return e.size;
4471
4630
  if (typeof e?.byteLength == "number")
4472
4631
  return e.byteLength;
4473
- }, Q = (r, e, t) => r === void 0 || r === "always" ? !0 : r === "idempotent-only" ? vs.has(e.method) : typeof r == "function" ? r(e) : !(r.maxBodyBytes !== void 0 && t !== void 0 && t > r.maxBodyBytes), N = (r, e, t, s, i) => ({
4632
+ }, ee = (r, e, t) => r === void 0 || r === "always" ? !0 : r === "idempotent-only" ? _s.has(e.method) : typeof r == "function" ? r(e) : !(r.maxBodyBytes !== void 0 && t !== void 0 && t > r.maxBodyBytes), N = (r, e, t, s, i) => ({
4474
4633
  replayable: !1,
4475
4634
  bodyKind: r,
4476
4635
  reason: e,
@@ -4478,12 +4637,12 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4478
4637
  forwardInit: i,
4479
4638
  snapshot: s,
4480
4639
  replay: () => Promise.reject(new Error(`This request cannot be replayed: ${e}`))
4481
- }), gt = (r, e) => it(st(r.headers, e?.authorizationSwap)), he = (r) => {
4640
+ }), wt = (r, e) => ht(ct(r.headers, e?.authorizationSwap)), le = (r) => {
4482
4641
  if (!r || !("headers" in r))
4483
4642
  return r;
4484
4643
  const { headers: e, ...t } = r;
4485
4644
  return t;
4486
- }, Ss = (r, e) => e && "headers" in e && e.headers !== void 0 ? e.headers : re(r) ? r.headers : void 0, bs = (r) => {
4645
+ }, Rs = (r, e) => e && "headers" in e && e.headers !== void 0 ? e.headers : se(r) ? r.headers : void 0, Ps = (r) => {
4487
4646
  if (r === null || typeof r == "string")
4488
4647
  return r;
4489
4648
  if (typeof FormData < "u" && r instanceof FormData) {
@@ -4493,12 +4652,12 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4493
4652
  return e;
4494
4653
  }
4495
4654
  return typeof URLSearchParams < "u" && r instanceof URLSearchParams ? new URLSearchParams(r) : r instanceof ArrayBuffer ? r.slice(0) : ArrayBuffer.isView(r) ? new Uint8Array(r.buffer, r.byteOffset, r.byteLength).slice() : r;
4496
- }, Ue = (r, e, t) => new Request(r, { headers: gt(e, t) }), Ts = (r, e, t) => {
4497
- const s = ms(r), i = ys(r, e), n = Ss(r, e), o = (d, g) => rt({ url: s, method: i, headers: n, bodyKind: d, ...g === void 0 ? {} : { body: g } });
4498
- if (re(r)) {
4655
+ }, Oe = (r, e, t) => new Request(r, { headers: wt(e, t) }), Fs = (r, e, t) => {
4656
+ const s = Es(r), i = Is(r, e), n = Rs(r, e), o = (d, g) => at({ url: s, method: i, headers: n, bodyKind: d, ...g === void 0 ? {} : { body: g } });
4657
+ if (se(r)) {
4499
4658
  if (r.body === null || r.body === void 0) {
4500
4659
  const v = o("none");
4501
- return Q(t, { url: s, method: i, bodyKind: "none" }) ? {
4660
+ return ee(t, { url: s, method: i, bodyKind: "none" }) ? {
4502
4661
  replayable: !0,
4503
4662
  bodyKind: "none",
4504
4663
  forwardInput: r,
@@ -4507,11 +4666,11 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4507
4666
  // The snapshot's effective header set is applied to the `Request` and
4508
4667
  // `init.headers` is dropped, so `fetch` has only one set to choose
4509
4668
  // from. See `replayHeaders` for why that matters.
4510
- replay: (y, I) => y(Ue(r, v, I), he(e))
4669
+ replay: (y, I) => y(Oe(r, v, I), le(e))
4511
4670
  } : N("none", "the replay policy refused this request", r, v, e);
4512
4671
  }
4513
4672
  const d = o("request-clone");
4514
- if (!Q(t, { url: s, method: i, bodyKind: "request-clone" }))
4673
+ if (!ee(t, { url: s, method: i, bodyKind: "request-clone" }))
4515
4674
  return N("request-clone", "the replay policy refused this request", r, d, e);
4516
4675
  let f;
4517
4676
  try {
@@ -4525,15 +4684,15 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4525
4684
  forwardInput: r,
4526
4685
  forwardInit: e,
4527
4686
  snapshot: d,
4528
- replay: (v, u) => v(Ue(f, d, u), he(e))
4687
+ replay: (v, p) => v(Oe(f, d, p), le(e))
4529
4688
  };
4530
4689
  }
4531
- const a = ks(e?.body);
4690
+ const a = As(e?.body);
4532
4691
  if (a === "one-shot")
4533
4692
  return N("one-shot", "a streaming request body is consumed by the first send", r, o("one-shot"), e);
4534
- if (!Q(t, { url: s, method: i, bodyKind: a }, ws(e?.body)))
4693
+ if (!ee(t, { url: s, method: i, bodyKind: a }, Cs(e?.body)))
4535
4694
  return N(a, "the replay policy refused this request", r, o(a), e);
4536
- const p = e && "body" in e ? bs(e.body ?? null) : void 0, m = o(a, p);
4695
+ const u = e && "body" in e ? Ps(e.body ?? null) : void 0, m = o(a, u);
4537
4696
  return {
4538
4697
  replayable: !0,
4539
4698
  bodyKind: a,
@@ -4558,22 +4717,22 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4558
4717
  // unchanged, so an abort during the replay behaves identically to an abort
4559
4718
  // during the original.
4560
4719
  replay: (d, g) => d(m.dispatchUrl, {
4561
- ...he(e),
4562
- ...p === void 0 ? {} : { body: p },
4563
- headers: gt(m, g),
4720
+ ...le(e),
4721
+ ...u === void 0 ? {} : { body: u },
4722
+ headers: wt(m, g),
4564
4723
  method: m.method
4565
4724
  })
4566
4725
  };
4567
- }, se = (r) => typeof r == "object" && r !== null, _s = (r) => (e) => {
4568
- if (!se(r))
4726
+ }, ie = (r) => typeof r == "object" && r !== null, Ms = (r) => (e) => {
4727
+ if (!ie(r))
4569
4728
  return;
4570
4729
  const s = r[e] ?? r[e.toLowerCase()] ?? (typeof r.get == "function" ? r.get(e) : void 0);
4571
4730
  return Array.isArray(s) ? s.join(", ") : typeof s == "string" ? s : void 0;
4572
- }, Es = (r) => {
4731
+ }, Us = (r) => {
4573
4732
  const e = r?.url ?? "", t = r?.baseURL;
4574
4733
  return !t || /^([a-z][a-z\d+\-.]*:)?\/\//i.test(e) ? e : `${t.replace(/\/+$/, "")}/${e.replace(/^\/+/, "")}`;
4575
- }, Is = (r) => (r?.method ?? "GET").toUpperCase(), As = (r) => r == null ? "none" : se(r) && (typeof r.pipe == "function" || typeof r.getReader == "function") ? "one-shot" : "reusable", Cs = (r, e, t) => {
4576
- const s = it(st(e.headers, t?.authorizationSwap)), i = e.dispatchUrl === e.href && e.resolved;
4734
+ }, Ds = (r) => (r?.method ?? "GET").toUpperCase(), xs = (r) => r == null ? "none" : ie(r) && (typeof r.pipe == "function" || typeof r.getReader == "function") ? "one-shot" : "reusable", Os = (r, e, t) => {
4735
+ const s = ht(ct(e.headers, t?.authorizationSwap)), i = e.dispatchUrl === e.href && e.resolved;
4577
4736
  return {
4578
4737
  ...r,
4579
4738
  ...i ? { baseURL: void 0 } : {},
@@ -4582,56 +4741,56 @@ const tt = "https://passflow-relative.invalid", Qr = () => {
4582
4741
  headers: s,
4583
4742
  ..."body" in e ? { data: e.body } : {}
4584
4743
  };
4585
- }, me = (r, e, t, s, i, n) => {
4586
- const o = e ?? r?.config, a = As(o?.data), h = n ?? rt({
4587
- url: Es(o),
4588
- method: Is(o),
4744
+ }, ke = (r, e, t, s, i, n) => {
4745
+ const o = e ?? r?.config, a = xs(o?.data), h = n ?? at({
4746
+ url: Us(o),
4747
+ method: Ds(o),
4589
4748
  headers: o?.headers,
4590
4749
  bodyKind: a,
4591
4750
  body: o?.data
4592
- }), p = { url: h.href, method: h.method, bodyKind: a }, m = a !== "one-shot" && Q(i.replay, p);
4751
+ }), u = { url: h.href, method: h.method, bodyKind: a }, m = a !== "one-shot" && ee(i.replay, u);
4593
4752
  return {
4594
4753
  status: r?.status ?? 0,
4595
- getHeader: _s(r?.headers),
4754
+ getHeader: Ms(r?.headers),
4596
4755
  // Pre-read by axios into `data`; nothing is consumed by reading it again,
4597
4756
  // and the core still decides whether reading it is in scope.
4598
4757
  readBody: async () => r?.data,
4599
4758
  request: h,
4600
4759
  replay: async (d) => {
4601
- const g = Wt(Cs(o ?? {}, h, d));
4760
+ const g = er(Os(o ?? {}, h, d));
4602
4761
  try {
4603
4762
  const f = await s(g);
4604
- return me(f, f?.config ?? g, f, s, i, h);
4763
+ return ke(f, f?.config ?? g, f, s, i, h);
4605
4764
  } catch (f) {
4606
- const v = se(f) ? f : {};
4607
- if (!v.response || typeof v.response.status != "number" || Qe(f))
4765
+ const v = ie(f) ? f : {};
4766
+ if (!v.response || typeof v.response.status != "number" || st(f))
4608
4767
  throw f;
4609
- return { ...me(v.response, v.config ?? g, f, s, i, h), rejected: !0 };
4768
+ return { ...ke(v.response, v.config ?? g, f, s, i, h), rejected: !0 };
4610
4769
  }
4611
4770
  },
4612
4771
  markers: {
4613
- ...Xe(o) ? { upgradeTransaction: !0 } : {},
4614
- ...Xt(o) ? { replayed: !0 } : {}
4772
+ ...Ze(o) ? { upgradeTransaction: !0 } : {},
4773
+ ...tr(o) ? { replayed: !0 } : {}
4615
4774
  },
4616
4775
  raw: t,
4617
4776
  replayable: m,
4618
4777
  replayUnsupportedReason: a === "one-shot" ? "a streaming request body is consumed by the first send" : "the replay policy refused this request",
4619
4778
  signal: o?.signal
4620
4779
  };
4621
- }, vt = (r, e) => async (t) => {
4622
- const s = nt(r), i = se(t) ? t : {}, n = me(i.response, i.config, i.response, e, s), o = await at(n, s), a = gs(o, t);
4780
+ }, St = (r, e) => async (t) => {
4781
+ const s = dt(r), i = ie(t) ? t : {}, n = ke(i.response, i.config, i.response, e, s), o = await ut(n, s), a = Ts(o, t);
4623
4782
  if (a.settle === "reject")
4624
4783
  throw a.error;
4625
4784
  return a.value;
4626
- }, Rs = (r, e, t) => {
4627
- const s = r.request, i = typeof s == "function" ? (a) => s.call(r, a) : () => Promise.reject(new Error("Passflow: this client exposes no request() to replay through.")), n = r.interceptors.response.use(void 0, vt(e, i));
4785
+ }, Ls = (r, e, t) => {
4786
+ const s = r.request, i = typeof s == "function" ? (a) => s.call(r, a) : () => Promise.reject(new Error("Passflow: this client exposes no request() to replay through.")), n = r.interceptors.response.use(void 0, St(e, i));
4628
4787
  let o = !1;
4629
4788
  return () => {
4630
4789
  o || (o = !0, r.interceptors.response.eject(n));
4631
4790
  };
4632
4791
  };
4633
- let de = 0;
4634
- const Fs = (r, e) => {
4792
+ let ue = 0;
4793
+ const $s = (r, e) => {
4635
4794
  const t = e?.signal ?? (typeof r == "object" && r !== null ? r.signal : void 0) ?? void 0;
4636
4795
  if (t)
4637
4796
  return {
@@ -4646,9 +4805,9 @@ const Fs = (r, e) => {
4646
4805
  removeEventListener: (s, i) => t.removeEventListener(s, i)
4647
4806
  } : {}
4648
4807
  };
4649
- }, Ps = (r) => (e) => r.headers?.get(e), mt = (r, e, t, s, i) => ({
4808
+ }, qs = (r) => (e) => r.headers?.get(e), bt = (r, e, t, s, i) => ({
4650
4809
  status: r.status,
4651
- getHeader: Ps(r),
4810
+ getHeader: qs(r),
4652
4811
  // A CLONE, always. The response the caller receives must still have an unread
4653
4812
  // body, and the core calls this only when the scope and the channel policy
4654
4813
  // both permit a body read.
@@ -4661,7 +4820,7 @@ const Fs = (r, e) => {
4661
4820
  request: e.snapshot,
4662
4821
  replay: async (n) => {
4663
4822
  const o = await e.replay(t, n);
4664
- return mt(o, e, t, s, i);
4823
+ return bt(o, e, t, s, i);
4665
4824
  },
4666
4825
  markers: s,
4667
4826
  raw: r,
@@ -4669,89 +4828,89 @@ const Fs = (r, e) => {
4669
4828
  replayUnsupportedReason: e.reason,
4670
4829
  signal: i,
4671
4830
  responseType: r.type
4672
- }), le = (r, e) => {
4831
+ }), pe = (r, e) => {
4673
4832
  const t = (s, i) => {
4674
- de += 1;
4833
+ ue += 1;
4675
4834
  try {
4676
4835
  return r(s, i);
4677
4836
  } finally {
4678
- de -= 1;
4837
+ ue -= 1;
4679
4838
  }
4680
4839
  };
4681
4840
  return async (s, i) => {
4682
- if (de > 0)
4841
+ if (ue > 0)
4683
4842
  return t(s, i);
4684
- const n = nt(e), o = Ts(s, i, n.replay), a = await t(o.forwardInput, o.forwardInit), h = mt(a, o, t, {}, Fs(s, i)), p = await at(h, n), m = fs(p, a, n);
4843
+ const n = dt(e), o = Fs(s, i, n.replay), a = await t(o.forwardInput, o.forwardInit), h = bt(a, o, t, {}, $s(s, i)), u = await ut(h, n), m = bs(u, a, n);
4685
4844
  if (m.settle === "reject")
4686
4845
  throw m.error;
4687
4846
  return m.value;
4688
4847
  };
4689
- }, Ms = (r, e) => {
4690
- const t = K.create(r);
4848
+ }, Ns = (r, e) => {
4849
+ const t = B.create(r);
4691
4850
  return e(t), t;
4692
- }, ii = 10, Ds = 20;
4693
- class Us extends Error {
4851
+ }, ui = 10, Vs = 20;
4852
+ class Ks extends Error {
4694
4853
  constructor(e) {
4695
4854
  super(
4696
4855
  `Passflow fetch middleware '${e}' resolved without calling next(). Every registered middleware must delegate exactly once; swallowing a request would drop a caller's fetch inside the Passflow wrapper.`
4697
4856
  ), this.name = "FetchMiddlewareContractError", this.middlewareName = e;
4698
4857
  }
4699
4858
  }
4700
- let x = [], xs = 0, z = !1, B, L;
4701
- const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof globalThis > "u" ? void 0 : globalThis, ye = async (r, e, t, s) => {
4859
+ let O = [], Bs = 0, z = !1, K, $;
4860
+ const Tt = (r, e) => r.priority - e.priority || r.seq - e.seq, _e = () => typeof globalThis > "u" ? void 0 : globalThis, we = async (r, e, t, s) => {
4702
4861
  if (e >= r.length) {
4703
- const h = B;
4862
+ const h = K;
4704
4863
  if (!h)
4705
4864
  throw new Error("Passflow fetch registry: no captured fetch to delegate to.");
4706
4865
  return h(t, s);
4707
4866
  }
4708
4867
  const i = r[e];
4709
4868
  if (!i)
4710
- return ye(r, r.length, t, s);
4869
+ return we(r, r.length, t, s);
4711
4870
  let n = !1;
4712
- const o = (h, p) => (n = !0, ye(r, e + 1, h, p)), a = await i.middleware(o, t, s);
4871
+ const o = (h, u) => (n = !0, we(r, e + 1, h, u)), a = await i.middleware(o, t, s);
4713
4872
  if (!n)
4714
- throw new Us(i.name);
4873
+ throw new Ks(i.name);
4715
4874
  return a;
4716
- }, Os = () => {
4717
- const r = be();
4875
+ }, Gs = () => {
4876
+ const r = _e();
4718
4877
  if (!r || typeof r.fetch != "function")
4719
4878
  return !1;
4720
- const e = r.fetch.bind(r), t = (s, i) => ye([...x].sort(yt), 0, s, i);
4721
- return B = e, L = t, r.fetch = t, z = !0, !0;
4722
- }, Ls = () => {
4723
- const r = be();
4724
- !r || !L || r.fetch === L && (B && (r.fetch = B), z = !1, L = void 0, B = void 0);
4725
- }, $s = (r, e) => {
4726
- if (!z && !Os())
4879
+ const e = r.fetch.bind(r), t = (s, i) => we([...O].sort(Tt), 0, s, i);
4880
+ return K = e, $ = t, r.fetch = t, z = !0, !0;
4881
+ }, js = () => {
4882
+ const r = _e();
4883
+ !r || !$ || r.fetch === $ && (K && (r.fetch = K), z = !1, $ = void 0, K = void 0);
4884
+ }, Hs = (r, e) => {
4885
+ if (!z && !Gs())
4727
4886
  return () => {
4728
4887
  };
4729
4888
  const t = {
4730
4889
  middleware: r,
4731
4890
  name: e.name,
4732
4891
  priority: e.priority,
4733
- seq: xs++
4892
+ seq: Bs++
4734
4893
  };
4735
- x.push(t);
4894
+ O.push(t);
4736
4895
  let s = !1;
4737
4896
  return () => {
4738
- s || (s = !0, x = x.filter((i) => i !== t), x.length === 0 && Ls());
4897
+ s || (s = !0, O = O.filter((i) => i !== t), O.length === 0 && js());
4739
4898
  };
4740
- }, ni = () => {
4741
- const r = be();
4899
+ }, pi = () => {
4900
+ const r = _e();
4742
4901
  return {
4743
4902
  installed: z,
4744
- names: [...x].sort(yt).map((e) => e.name),
4745
- foreignPatch: z && !!r && !!L && r.fetch !== L
4903
+ names: [...O].sort(Tt).map((e) => e.name),
4904
+ foreignPatch: z && !!r && !!$ && r.fetch !== $
4746
4905
  };
4747
- }, qs = (r) => r === void 0 ? [] : (Array.isArray(r) ? r : [r]).filter((e) => e !== ""), Ns = (r) => {
4906
+ }, zs = (r) => r === void 0 ? [] : (Array.isArray(r) ? r : [r]).filter((e) => e !== ""), Ys = (r) => {
4748
4907
  let e;
4749
4908
  const t = (d) => d !== void 0 && e === d, s = (d) => {
4750
4909
  const g = () => {
4751
4910
  if (!t(d()))
4752
4911
  throw new _({ kind: "session_changed" });
4753
4912
  };
4754
- return ss({
4913
+ return ls({
4755
4914
  ...r,
4756
4915
  relyingPartyId: () => e?.options.relyingPartyId ?? r.relyingPartyId?.(),
4757
4916
  startUpgrade: (f) => (g(), r.startUpgrade(f)),
@@ -4763,8 +4922,8 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4763
4922
  } : {}
4764
4923
  });
4765
4924
  }, i = (d, g) => {
4766
- const f = {}, u = {
4767
- controller: new Zr({
4925
+ const f = {}, p = {
4926
+ controller: new os({
4768
4927
  transport: s(() => f.current),
4769
4928
  prompt: d.prompt,
4770
4929
  platform: r.platform,
@@ -4774,18 +4933,18 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4774
4933
  ...d.onFlightSettled ? { onFlightSettled: d.onFlightSettled } : {}
4775
4934
  }),
4776
4935
  options: d,
4777
- scope: { passflow: r.passflowDomain, backend: qs(d.backend) },
4936
+ scope: { passflow: r.passflowDomain, backend: zs(d.backend) },
4778
4937
  generation: g
4779
4938
  };
4780
- return f.current = u, u;
4939
+ return f.current = p, p;
4781
4940
  }, n = async (d, g) => {
4782
4941
  const f = e;
4783
4942
  if (!f)
4784
- throw new G("Step-up verification is not enabled on this Passflow instance");
4943
+ throw new j("Step-up verification is not enabled on this Passflow instance");
4785
4944
  f.controller.active || (f.pin = r.readSessionPin?.());
4786
4945
  const v = await f.controller.elevate(d, g);
4787
4946
  if (!t(f))
4788
- throw new $();
4947
+ throw new q();
4789
4948
  return v;
4790
4949
  }, o = () => {
4791
4950
  const d = e, g = d?.scope ?? { passflow: r.passflowDomain, backend: [] }, f = d?.options;
@@ -4803,16 +4962,16 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4803
4962
  };
4804
4963
  let a;
4805
4964
  return Object.defineProperties(async (d) => {
4806
- const g = d?.acrValues === void 0 ? void 0 : te(d.acrValues).level, f = {
4965
+ const g = d?.acrValues === void 0 ? void 0 : re(d.acrValues).level, f = {
4807
4966
  status: 401,
4808
4967
  ...d?.acrValues === void 0 ? {} : { acrValues: d.acrValues },
4809
4968
  ...g === void 0 ? {} : { requiredLevel: g },
4810
4969
  ...d?.maxAge === void 0 ? {} : { maxAge: d.maxAge }
4811
- }, v = d?.acrValues !== void 0 || d?.maxAge !== void 0, u = {
4970
+ }, v = d?.acrValues !== void 0 || d?.maxAge !== void 0, p = {
4812
4971
  ...d?.acrValues === void 0 ? {} : { acrValues: d.acrValues },
4813
4972
  ...g === void 0 ? {} : { level: g },
4814
4973
  ...d?.maxAge === void 0 ? {} : { maxAge: d.maxAge }
4815
- }, I = (await n(f, { kind: "imperative", ...v ? { requested: u } : {} })).obtained.acrValues;
4974
+ }, I = (await n(f, { kind: "imperative", ...v ? { requested: p } : {} })).obtained.acrValues;
4816
4975
  return { status: "elevated", ...I === void 0 ? {} : { acr: I } };
4817
4976
  }, {
4818
4977
  enable: { value: (d) => {
@@ -4820,11 +4979,11 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4820
4979
  const g = [];
4821
4980
  if (r.attachInternalSeam) {
4822
4981
  const v = r.attachInternalSeam;
4823
- v((u) => vt(o, u)), g.push(() => v(void 0));
4982
+ v((p) => St(o, p)), g.push(() => v(void 0));
4824
4983
  }
4825
4984
  d.interceptFetch && g.push(
4826
- $s((v, u, y) => le(v, o)(u, y), {
4827
- priority: Ds,
4985
+ Hs((v, p, y) => pe(v, o)(p, y), {
4986
+ priority: Vs,
4828
4987
  name: "passflow-upgrade"
4829
4988
  })
4830
4989
  ), r.onSessionChange && g.push(
@@ -4857,19 +5016,19 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4857
5016
  enumerable: !0,
4858
5017
  value: (d) => {
4859
5018
  if (d)
4860
- return le(d, o);
5019
+ return pe(d, o);
4861
5020
  const g = typeof globalThis > "u" ? void 0 : globalThis;
4862
5021
  if (!g || typeof g.fetch != "function")
4863
5022
  throw new Error("Passflow: withAuth() needs a fetch to wrap — this runtime has none.");
4864
- return le(g.fetch.bind(g), o);
5023
+ return pe(g.fetch.bind(g), o);
4865
5024
  }
4866
5025
  },
4867
5026
  attachAuth: {
4868
5027
  enumerable: !0,
4869
- value: (d) => Rs(d, o)
5028
+ value: (d) => Ls(d, o)
4870
5029
  }
4871
5030
  });
4872
- }, Te = class Te {
5031
+ }, Ee = class Ee {
4873
5032
  constructor(e) {
4874
5033
  this.doRefreshTokens = !1, this.session = async ({
4875
5034
  createSession: n,
@@ -4879,10 +5038,10 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4879
5038
  this.createSessionCallback = n, this.expiredSessionCallback = o, this.doRefreshTokens = a, await this.submitSessionCheck();
4880
5039
  };
4881
5040
  const { url: t, appId: s, scopes: i } = e;
4882
- this.url = t || Le, this.appId = s, this.platform = e.platform ?? Y, this.storageManager = new ke({
5041
+ this.url = t || qe, this.appId = s, this.platform = e.platform ?? Y, this.storageManager = new Se({
4883
5042
  prefix: e.keyStoragePrefix ?? "",
4884
5043
  storage: this.platform.storage
4885
- }), this.deviceService = new Ve(this.storageManager), this.authApi = new nr(e, this.storageManager, this.deviceService), this.appApi = new ir(e, this.storageManager, this.deviceService), this.userApi = new lr(e, this.storageManager, this.deviceService), this.settingApi = new ar(e, this.storageManager, this.deviceService), this.tenantApi = new cr(e, this.storageManager, this.deviceService), this.invitationApi = new or(e, this.storageManager, this.deviceService), this.twoFactorApi = new hr(e, this.storageManager, this.deviceService), this.upgradeApi = new dr(e, this.storageManager, this.deviceService), this.upgradeDomain = Je(e.url), this.subscribeStore = new ur(), this.tokenCacheService = new xr(this.storageManager, this.authApi, this.subscribeStore, this.platform), this.scopes = i ?? At, this.createTenantForNewUser = e.createTenantForNewUser ?? !1, this.authService = new Rr(
5044
+ }), this.deviceService = new Be(this.storageManager), this.authApi = new dr(e, this.storageManager, this.deviceService), this.appApi = new hr(e, this.storageManager, this.deviceService), this.userApi = new vr(e, this.storageManager, this.deviceService), this.settingApi = new ur(e, this.storageManager, this.deviceService), this.tenantApi = new pr(e, this.storageManager, this.deviceService), this.invitationApi = new lr(e, this.storageManager, this.deviceService), this.twoFactorApi = new fr(e, this.storageManager, this.deviceService), this.upgradeApi = new gr(e, this.storageManager, this.deviceService), this.upgradeDomain = Qe(e.url), this.subscribeStore = new wr(), this.tokenCacheService = new Br(this.storageManager, this.authApi, this.subscribeStore, this.platform), this.scopes = i ?? Mt, this.createTenantForNewUser = e.createTenantForNewUser ?? !1, this.authService = new qr(
4886
5045
  this.authApi,
4887
5046
  this.deviceService,
4888
5047
  this.storageManager,
@@ -4897,8 +5056,9 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4897
5056
  },
4898
5057
  this.appId ?? "",
4899
5058
  e.tokenExchange,
4900
- this.platform
4901
- ), this.userService = new Lr(this.userApi, this.deviceService, this.platform), this.tenantService = new Ur(this.tenantApi, this.scopes), this.tenant = this.tenantService, this.invitationService = new Fr(this.invitationApi), this.twoFactorService = new Or(this.twoFactorApi, this.subscribeStore), this.twoFactor = this.twoFactorService, this.upgrade = Ns({
5059
+ this.platform,
5060
+ () => this.readPkceEnabled()
5061
+ ), this.userService = new jr(this.userApi, this.deviceService, this.platform), this.tenantService = new Kr(this.tenantApi, this.scopes), this.tenant = this.tenantService, this.invitationService = new Nr(this.invitationApi), this.twoFactorService = new Gr(this.twoFactorApi, this.subscribeStore, this.authService), this.twoFactor = this.twoFactorService, this.upgrade = Ys({
4902
5062
  // The prepare round. The commit round is `/auth/refresh`, which must go
4903
5063
  // through AuthService: it is the only path that STORES the rotated tokens,
4904
5064
  // so posting directly would elevate the session on the server and leave
@@ -4933,6 +5093,22 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4933
5093
  get origin() {
4934
5094
  return this.platform.getCurrentUrl()?.origin ?? "";
4935
5095
  }
5096
+ /**
5097
+ * Whether the current app wants PKCE. A sign-in asks before a passkey ceremony,
5098
+ * where a round-trip eats into the browser's user-gesture window, so the answer
5099
+ * is kept for the appId. A failed read is not kept: the next sign-in asks again.
5100
+ */
5101
+ readPkceEnabled() {
5102
+ if (!this.appId)
5103
+ return Promise.resolve(!1);
5104
+ if (!this.pkceEnabledRead) {
5105
+ const e = this.appApi.getAppSettings().then((t) => t.pkce_enabled);
5106
+ this.pkceEnabledRead = e, e.catch(() => {
5107
+ this.pkceEnabledRead === e && (this.pkceEnabledRead = void 0);
5108
+ });
5109
+ }
5110
+ return this.pkceEnabledRead;
5111
+ }
4936
5112
  /**
4937
5113
  * Update the appId and propagate it to all API clients.
4938
5114
  * This ensures that all future API requests use the new appId in their headers.
@@ -4946,7 +5122,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
4946
5122
  * ```
4947
5123
  */
4948
5124
  setAppId(e) {
4949
- this.appId = e, this.authApi.setAppId(e), this.appApi.setAppId(e), this.userApi.setAppId(e), this.settingApi.setAppId(e), this.tenantApi.setAppId(e), this.invitationApi.setAppId(e), this.twoFactorApi.setAppId(e), this.upgradeApi.setAppId(e), this.authService;
5125
+ this.appId = e, this.pkceEnabledRead = void 0, this.authApi.setAppId(e), this.appApi.setAppId(e), this.userApi.setAppId(e), this.settingApi.setAppId(e), this.tenantApi.setAppId(e), this.invitationApi.setAppId(e), this.twoFactorApi.setAppId(e), this.upgradeApi.setAppId(e), this.authService;
4950
5126
  }
4951
5127
  /**
4952
5128
  * Wraps a `fetch`, returning a new function with step-up handling attached.
@@ -5006,7 +5182,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
5006
5182
  * ```
5007
5183
  */
5008
5184
  createClient(e) {
5009
- return Ms(e, (t) => this.upgrade.attachAuth(t));
5185
+ return Ns(e, (t) => this.upgrade.attachAuth(t));
5010
5186
  }
5011
5187
  /**
5012
5188
  * The assurance bar the session currently holds, read from the `acr` claim of
@@ -5023,7 +5199,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
5023
5199
  const t = T(e), s = typeof t.acr == "string" ? t.acr : void 0;
5024
5200
  if (!s)
5025
5201
  return;
5026
- const i = te(s).level;
5202
+ const i = re(s).level;
5027
5203
  return i === void 0 ? { acrValues: s } : { acrValues: s, level: i };
5028
5204
  } catch {
5029
5205
  return;
@@ -5162,8 +5338,8 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
5162
5338
  const e = this.platform.getCurrentUrl();
5163
5339
  let t = new URLSearchParams(e?.search ?? ""), s = !1;
5164
5340
  if (!t.get("access_token") && e?.hash) {
5165
- const p = new URLSearchParams(e.hash.substring(1));
5166
- p.get("access_token") && (t = p, s = !0);
5341
+ const u = new URLSearchParams(e.hash.substring(1));
5342
+ u.get("access_token") && (t = u, s = !0);
5167
5343
  }
5168
5344
  if (!t.get("access_token") && this.adoptTwoFactorTokenFromUrl(e)) {
5169
5345
  this.error = void 0;
@@ -5172,28 +5348,28 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
5172
5348
  const i = t.get("access_token"), n = t.get("refresh_token"), o = t.get("id_token"), a = t.get("scopes")?.split(",") ?? this.scopes;
5173
5349
  let h;
5174
5350
  if (i) {
5175
- if (!X(i)) {
5176
- const p = {
5351
+ if (!J(i)) {
5352
+ const u = {
5177
5353
  message: "Invalid access token format received",
5178
5354
  code: "INVALID_TOKEN_FORMAT"
5179
5355
  };
5180
- this.subscribeStore.notify(c.Error, p), this.cleanupUrlParams(s, e);
5356
+ this.subscribeStore.notify(c.Error, u), this.cleanupUrlParams(s, e);
5181
5357
  return;
5182
5358
  }
5183
- if (n && !X(n)) {
5184
- const p = {
5359
+ if (n && !J(n)) {
5360
+ const u = {
5185
5361
  message: "Invalid refresh token format received",
5186
5362
  code: "INVALID_TOKEN_FORMAT"
5187
5363
  };
5188
- this.subscribeStore.notify(c.Error, p), this.cleanupUrlParams(s, e);
5364
+ this.subscribeStore.notify(c.Error, u), this.cleanupUrlParams(s, e);
5189
5365
  return;
5190
5366
  }
5191
- if (o && !X(o)) {
5192
- const p = {
5367
+ if (o && !J(o)) {
5368
+ const u = {
5193
5369
  message: "Invalid ID token format received",
5194
5370
  code: "INVALID_TOKEN_FORMAT"
5195
5371
  };
5196
- this.subscribeStore.notify(c.Error, p), this.cleanupUrlParams(s, e);
5372
+ this.subscribeStore.notify(c.Error, u), this.cleanupUrlParams(s, e);
5197
5373
  return;
5198
5374
  }
5199
5375
  return h = {
@@ -5218,7 +5394,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
5218
5394
  if (!s) return !1;
5219
5395
  t.delete("tfa_token");
5220
5396
  const i = t.toString();
5221
- if (this.platform.replaceUrl(e.pathname + e.search + (i ? `#${i}` : "")), !X(s)) {
5397
+ if (this.platform.replaceUrl(e.pathname + e.search + (i ? `#${i}` : "")), !J(s)) {
5222
5398
  const n = {
5223
5399
  message: "Invalid 2FA token format received",
5224
5400
  code: "INVALID_TOKEN_FORMAT"
@@ -5230,7 +5406,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
5230
5406
  checkErrorsFromURL() {
5231
5407
  const t = new URLSearchParams(this.platform.getCurrentUrl()?.search ?? "").get("error");
5232
5408
  if (t) {
5233
- const s = Ir(t);
5409
+ const s = Dr(t);
5234
5410
  return new Error(s);
5235
5411
  }
5236
5412
  }
@@ -5933,7 +6109,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
5933
6109
  async joinInvitation(e, t) {
5934
6110
  try {
5935
6111
  const s = await this.tenant.joinInvitation(e, t);
5936
- return s.scopes = t ?? this.scopes, this.storageManager.saveTokens(s), this.tokenCacheService.setTokensCache(s), s;
6112
+ return s.scopes = t ?? this.scopes, await this.authService.applyTokens(s), s;
5937
6113
  } catch (s) {
5938
6114
  this.handleError(s, "Join invitation");
5939
6115
  }
@@ -6227,7 +6403,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
6227
6403
  async verifyTwoFactor(e, t) {
6228
6404
  try {
6229
6405
  const s = await this.twoFactorService.verify(e, t);
6230
- return this.storageManager.saveTokens(s), this.tokenCacheService.setTokensCache(s), this.subscribeStore.notify(c.SignIn, {
6406
+ return this.subscribeStore.notify(c.SignIn, {
6231
6407
  tokens: s,
6232
6408
  parsedTokens: this.tokenCacheService.getParsedTokens()
6233
6409
  }), await this.submitSessionCheck(), s;
@@ -6255,7 +6431,7 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
6255
6431
  async useTwoFactorRecoveryCode(e, t) {
6256
6432
  try {
6257
6433
  const s = await this.twoFactorService.useRecoveryCode(e, t);
6258
- return this.storageManager.saveTokens(s), this.tokenCacheService.setTokensCache(s), this.subscribeStore.notify(c.SignIn, {
6434
+ return this.subscribeStore.notify(c.SignIn, {
6259
6435
  tokens: s,
6260
6436
  parsedTokens: this.tokenCacheService.getParsedTokens()
6261
6437
  }), await this.submitSessionCheck(), s;
@@ -6456,8 +6632,8 @@ const yt = (r, e) => r.priority - e.priority || r.seq - e.seq, be = () => typeof
6456
6632
  this.twoFactorService.clearMagicLinkSession();
6457
6633
  }
6458
6634
  };
6459
- Te.version = It;
6460
- let xe = Te;
6635
+ Ee.version = Ft;
6636
+ let Le = Ee;
6461
6637
  class S extends Error {
6462
6638
  constructor(e) {
6463
6639
  super(e.message), this.name = "M2MError", this.code = e.code, this.status = e.status ?? 400, this.errorUri = e.errorUri, this.rateLimitInfo = e.rateLimitInfo, this.headers = e.headers, this.cause = e.cause, this.timestamp = (/* @__PURE__ */ new Date()).toISOString(), Error.captureStackTrace && Error.captureStackTrace(this, S);
@@ -6553,7 +6729,7 @@ class S extends Error {
6553
6729
  return this.status && (e += ` (HTTP ${this.status})`), e;
6554
6730
  }
6555
6731
  }
6556
- class Oe extends S {
6732
+ class $e extends S {
6557
6733
  constructor(e, t) {
6558
6734
  super({
6559
6735
  code: "temporarily_unavailable",
@@ -6563,7 +6739,7 @@ class Oe extends S {
6563
6739
  }), this.name = "M2MNetworkError";
6564
6740
  }
6565
6741
  }
6566
- class Z extends S {
6742
+ class Q extends S {
6567
6743
  constructor(e, t) {
6568
6744
  super({
6569
6745
  code: "invalid_request",
@@ -6573,7 +6749,7 @@ class Z extends S {
6573
6749
  }), this.name = "M2MTokenParseError";
6574
6750
  }
6575
6751
  }
6576
- class ue extends S {
6752
+ class fe extends S {
6577
6753
  constructor(e) {
6578
6754
  super({
6579
6755
  code: "invalid_request",
@@ -6582,7 +6758,7 @@ class ue extends S {
6582
6758
  }), this.name = "M2MConfigError";
6583
6759
  }
6584
6760
  }
6585
- const oi = {
6761
+ const fi = {
6586
6762
  InvalidRequest: "invalid_request",
6587
6763
  InvalidClient: "invalid_client",
6588
6764
  InvalidGrant: "invalid_grant",
@@ -6606,7 +6782,7 @@ const oi = {
6606
6782
  /** Content-Type for token requests */
6607
6783
  CONTENT_TYPE: "application/x-www-form-urlencoded"
6608
6784
  };
6609
- class Vs {
6785
+ class Ws {
6610
6786
  constructor() {
6611
6787
  this.cache = /* @__PURE__ */ new Map();
6612
6788
  }
@@ -6624,7 +6800,7 @@ class Vs {
6624
6800
  return this.cache.delete(e), Promise.resolve();
6625
6801
  }
6626
6802
  }
6627
- const Bs = {
6803
+ const Xs = {
6628
6804
  shouldRetry(r, e) {
6629
6805
  return e >= 3 ? !1 : r.code === "server_error" || r.code === "temporarily_unavailable" || r.code === "rate_limit_exceeded" || r.status !== void 0 && r.status >= 500;
6630
6806
  },
@@ -6632,7 +6808,7 @@ const Bs = {
6632
6808
  return Math.pow(2, r - 1) * 1e3;
6633
6809
  }
6634
6810
  };
6635
- class ai {
6811
+ class gi {
6636
6812
  /**
6637
6813
  * Create a new M2M client
6638
6814
  *
@@ -6650,11 +6826,11 @@ class ai {
6650
6826
  */
6651
6827
  constructor(e) {
6652
6828
  if (!e.url)
6653
- throw new ue("M2M client requires a URL");
6829
+ throw new fe("M2M client requires a URL");
6654
6830
  if (!e.clientId)
6655
- throw new ue("M2M client requires a clientId");
6831
+ throw new fe("M2M client requires a clientId");
6656
6832
  if (!e.clientSecret)
6657
- throw new ue("M2M client requires a clientSecret");
6833
+ throw new fe("M2M client requires a clientSecret");
6658
6834
  const t = e.url.replace(/\/$/, "");
6659
6835
  this.config = {
6660
6836
  url: t,
@@ -6672,7 +6848,7 @@ class ai {
6672
6848
  onTokenRequest: e.onTokenRequest,
6673
6849
  onTokenResponse: e.onTokenResponse,
6674
6850
  onError: e.onError
6675
- }, this.cache = e.cache ?? new Vs(), this.retryStrategy = e.retryStrategy ?? Bs, this.tokenEndpoint = `${t}${R.TOKEN_ENDPOINT}`;
6851
+ }, this.cache = e.cache ?? new Ws(), this.retryStrategy = e.retryStrategy ?? Xs, this.tokenEndpoint = `${t}${R.TOKEN_ENDPOINT}`;
6676
6852
  }
6677
6853
  /**
6678
6854
  * Get the cache key for this client
@@ -6771,8 +6947,8 @@ class ai {
6771
6947
  });
6772
6948
  clearTimeout(i);
6773
6949
  const o = {};
6774
- n.headers.forEach((h, p) => {
6775
- o[p.toLowerCase()] = h;
6950
+ n.headers.forEach((h, u) => {
6951
+ o[u.toLowerCase()] = h;
6776
6952
  });
6777
6953
  const a = await n.json();
6778
6954
  if (!n.ok) {
@@ -6792,7 +6968,7 @@ class ai {
6792
6968
  }
6793
6969
  return a;
6794
6970
  } catch (n) {
6795
- throw clearTimeout(i), n instanceof Error && n.name === "AbortError" ? new Oe(`Request timed out after ${this.config.timeout}ms`) : n instanceof TypeError && n.message.includes("fetch") ? new Oe(`Network error: ${n.message}`, n) : n instanceof S ? n : S.fromError(n instanceof Error ? n : new Error(String(n)));
6971
+ throw clearTimeout(i), n instanceof Error && n.name === "AbortError" ? new $e(`Request timed out after ${this.config.timeout}ms`) : n instanceof TypeError && n.message.includes("fetch") ? new $e(`Network error: ${n.message}`, n) : n instanceof S ? n : S.fromError(n instanceof Error ? n : new Error(String(n)));
6796
6972
  }
6797
6973
  }
6798
6974
  /**
@@ -6887,14 +7063,14 @@ class ai {
6887
7063
  try {
6888
7064
  const t = e.split(".");
6889
7065
  if (t.length !== 3)
6890
- throw new Z("Invalid JWT format: expected 3 parts");
7066
+ throw new Q("Invalid JWT format: expected 3 parts");
6891
7067
  const s = t[1];
6892
7068
  if (!s)
6893
- throw new Z("Invalid JWT format: missing payload");
7069
+ throw new Q("Invalid JWT format: missing payload");
6894
7070
  const i = atob(s.replace(/-/g, "+").replace(/_/g, "/")), n = JSON.parse(i);
6895
7071
  return n.scopes && typeof n.scopes == "string" ? n.scopes = n.scopes.split(" ") : n.scopes || (n.scopes = []), n;
6896
7072
  } catch (t) {
6897
- throw t instanceof Z ? t : new Z(`Failed to parse token: ${t instanceof Error ? t.message : "Unknown error"}`);
7073
+ throw t instanceof Q ? t : new Q(`Failed to parse token: ${t instanceof Error ? t.message : "Unknown error"}`);
6898
7074
  }
6899
7075
  }
6900
7076
  /**
@@ -6982,108 +7158,108 @@ class ai {
6982
7158
  export {
6983
7159
  V as APP_ID_HEADER_KEY,
6984
7160
  D as AUTHORIZATION_HEADER_KEY,
6985
- ir as AppAPI,
6986
- nr as AuthAPI,
6987
- Rr as AuthService,
6988
- Ws as CLIAuthAPI,
6989
- zs as DEFAULT_GROUP_NAME,
6990
- At as DEFAULT_SCOPES,
6991
- Se as DEFAULT_UPGRADE_FACTORS,
6992
- _t as DEVICE_ID_HEADER_KEY,
6993
- Et as DEVICE_TYPE_HEADER_KEY,
6994
- Ut as ERROR_MESSAGE_MAX_LENGTH,
6995
- ii as FETCH_PRIORITY_OIDC,
6996
- Ds as FETCH_PRIORITY_UPGRADE,
6997
- Us as FetchMiddlewareContractError,
6998
- Bt as INSUFFICIENT_USER_AUTHENTICATION,
6999
- or as InvitationAPI,
7000
- Fr as InvitationService,
7001
- ai as M2MClient,
7002
- ue as M2MConfigError,
7161
+ hr as AppAPI,
7162
+ dr as AuthAPI,
7163
+ qr as AuthService,
7164
+ si as CLIAuthAPI,
7165
+ ti as DEFAULT_GROUP_NAME,
7166
+ Mt as DEFAULT_SCOPES,
7167
+ Te as DEFAULT_UPGRADE_FACTORS,
7168
+ Rt as DEVICE_ID_HEADER_KEY,
7169
+ Pt as DEVICE_TYPE_HEADER_KEY,
7170
+ qt as ERROR_MESSAGE_MAX_LENGTH,
7171
+ ui as FETCH_PRIORITY_OIDC,
7172
+ Vs as FETCH_PRIORITY_UPGRADE,
7173
+ Ks as FetchMiddlewareContractError,
7174
+ zt as INSUFFICIENT_USER_AUTHENTICATION,
7175
+ lr as InvitationAPI,
7176
+ Nr as InvitationService,
7177
+ gi as M2MClient,
7178
+ fe as M2MConfigError,
7003
7179
  S as M2MError,
7004
- oi as M2MErrorCodes,
7005
- Oe as M2MNetworkError,
7006
- Z as M2MTokenParseError,
7180
+ fi as M2MErrorCodes,
7181
+ $e as M2MNetworkError,
7182
+ Q as M2MTokenParseError,
7007
7183
  R as M2M_DEFAULTS,
7008
- Hs as MINIMAL_DEFAULT_SCOPES,
7009
- Zt as OS,
7010
- Le as PASSFLOW_CLOUD_URL,
7011
- Rt as POPUP_HEIGHT,
7012
- Ft as POPUP_POLL_INTERVAL_MS,
7013
- Pt as POPUP_TIMEOUT_MS,
7014
- Ct as POPUP_WIDTH,
7015
- xe as Passflow,
7016
- F as PassflowAdminEndpointPaths,
7184
+ ei as MINIMAL_DEFAULT_SCOPES,
7185
+ sr as OS,
7186
+ qe as PASSFLOW_CLOUD_URL,
7187
+ Dt as POPUP_HEIGHT,
7188
+ xt as POPUP_POLL_INTERVAL_MS,
7189
+ Ot as POPUP_TIMEOUT_MS,
7190
+ Ut as POPUP_WIDTH,
7191
+ Le as Passflow,
7192
+ P as PassflowAdminEndpointPaths,
7017
7193
  l as PassflowEndpointPaths,
7018
7194
  w as PassflowError,
7019
7195
  c as PassflowEvent,
7020
- Be as PopupClosedError,
7021
- Jt as Providers,
7022
- pr as RECOVERABLE_COMMIT_ERROR_IDS,
7023
- M as RequestMethod,
7024
- It as SDK_VERSION,
7025
- fr as SESSION_INVALIDATING_COMMIT_ERROR_IDS,
7026
- qe as SessionState,
7027
- ar as SettingAPI,
7028
- $e as TOKEN_EXPIRY_BUFFER_SECONDS,
7029
- cr as TenantAPI,
7030
- Ur as TenantService,
7031
- Dr as TenantUserMembership,
7032
- xr as TokenCacheService,
7196
+ Ge as PopupClosedError,
7197
+ rr as Providers,
7198
+ Sr as RECOVERABLE_COMMIT_ERROR_IDS,
7199
+ U as RequestMethod,
7200
+ Ft as SDK_VERSION,
7201
+ br as SESSION_INVALIDATING_COMMIT_ERROR_IDS,
7202
+ Ve as SessionState,
7203
+ ur as SettingAPI,
7204
+ Ne as TOKEN_EXPIRY_BUFFER_SECONDS,
7205
+ pr as TenantAPI,
7206
+ Kr as TenantService,
7207
+ Vr as TenantUserMembership,
7208
+ Br as TokenCacheService,
7033
7209
  A as TokenDeliveryMode,
7034
7210
  b as TokenType,
7035
- hr as TwoFactorApiClient,
7036
- Qt as TwoFactorPolicy,
7037
- Or as TwoFactorService,
7038
- Kt as UPGRADE_REQUIRED,
7039
- Dt as USERNAME_MAX_LENGTH,
7040
- Mt as USERNAME_MIN_LENGTH,
7041
- dr as UpgradeAPI,
7042
- O as UpgradeCancelledError,
7043
- Zr as UpgradeController,
7211
+ fr as TwoFactorApiClient,
7212
+ ir as TwoFactorPolicy,
7213
+ Gr as TwoFactorService,
7214
+ Yt as UPGRADE_REQUIRED,
7215
+ $t as USERNAME_MAX_LENGTH,
7216
+ Lt as USERNAME_MIN_LENGTH,
7217
+ gr as UpgradeAPI,
7218
+ L as UpgradeCancelledError,
7219
+ os as UpgradeController,
7044
7220
  k as UpgradeErrorIds,
7045
- U as UpgradeFactorError,
7046
- j as UpgradeInsufficientError,
7047
- $ as UpgradeSessionChangedError,
7221
+ x as UpgradeFactorError,
7222
+ G as UpgradeInsufficientError,
7223
+ q as UpgradeSessionChangedError,
7048
7224
  _ as UpgradeTransportError,
7049
- G as UpgradeUnavailableError,
7050
- ee as UpgradeUnsatisfiableError,
7051
- lr as UserAPI,
7052
- Lr as UserService,
7053
- $t as WebAdapter,
7054
- Ce as classifyUpgradeError,
7055
- Vr as factorRegistry,
7056
- ni as fetchRegistryState,
7057
- Ys as getOSFromDeviceType,
7058
- Tr as invalidatesSessionOnCommit,
7059
- Xs as isRecoverableCommitFailure,
7060
- vr as isRetryableUpgradeKind,
7225
+ j as UpgradeUnavailableError,
7226
+ te as UpgradeUnsatisfiableError,
7227
+ vr as UserAPI,
7228
+ jr as UserService,
7229
+ Bt as WebAdapter,
7230
+ Pe as classifyUpgradeError,
7231
+ Wr as factorRegistry,
7232
+ pi as fetchRegistryState,
7233
+ ri as getOSFromDeviceType,
7234
+ Fr as invalidatesSessionOnCommit,
7235
+ ii as isRecoverableCommitFailure,
7236
+ _r as isRetryableUpgradeKind,
7061
7237
  C as isTokenExpired,
7062
- Js as isUpgradeCancelled,
7063
- Zs as isUpgradeExhausted,
7064
- Qs as isUpgradeInsufficient,
7065
- ri as isUpgradeSessionChanged,
7066
- kr as isUpgradeTransportError,
7067
- si as isUpgradeTransportFailure,
7068
- ti as isUpgradeUnavailable,
7069
- ei as isUpgradeUnsatisfiable,
7070
- ne as isValidEmail,
7071
- X as isValidJWTFormat,
7072
- oe as isValidPhoneNumber,
7073
- Ar as isValidUsername,
7074
- Ht as parseChallengeBody,
7075
- Gt as parseChallengeHeader,
7238
+ ni as isUpgradeCancelled,
7239
+ oi as isUpgradeExhausted,
7240
+ ai as isUpgradeInsufficient,
7241
+ di as isUpgradeSessionChanged,
7242
+ Ar as isUpgradeTransportError,
7243
+ li as isUpgradeTransportFailure,
7244
+ hi as isUpgradeUnavailable,
7245
+ ci as isUpgradeUnsatisfiable,
7246
+ oe as isValidEmail,
7247
+ J as isValidJWTFormat,
7248
+ ae as isValidPhoneNumber,
7249
+ xr as isValidUsername,
7250
+ Jt as parseChallengeBody,
7251
+ Xt as parseChallengeHeader,
7076
7252
  T as parseToken,
7077
- Yt as parseUpgradeChallenge,
7078
- Nr as passkeyFactor,
7079
- P as pathWithParams,
7080
- qr as recoveryCodesFactor,
7081
- $s as registerFetchMiddleware,
7082
- Vt as requiredAcrLevel,
7083
- Je as resolveUpgradeDomain,
7084
- Ir as sanitizeErrorMessage,
7085
- Gr as selectFactors,
7086
- $r as totpFactor,
7253
+ Qt as parseUpgradeChallenge,
7254
+ Yr as passkeyFactor,
7255
+ F as pathWithParams,
7256
+ zr as recoveryCodesFactor,
7257
+ Hs as registerFetchMiddleware,
7258
+ Ht as requiredAcrLevel,
7259
+ Qe as resolveUpgradeDomain,
7260
+ Dr as sanitizeErrorMessage,
7261
+ Qr as selectFactors,
7262
+ Hr as totpFactor,
7087
7263
  Y as webAdapter
7088
7264
  };
7089
7265
  //# sourceMappingURL=index.mjs.map