@passflow/core 0.14.0 → 0.15.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.
Files changed (57) hide show
  1. package/dist/index.cjs +2 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.mjs +2767 -1054
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/lib/api/auth.d.ts +17 -2
  6. package/dist/lib/api/auth.d.ts.map +1 -1
  7. package/dist/lib/api/axios-client.d.ts +47 -2
  8. package/dist/lib/api/axios-client.d.ts.map +1 -1
  9. package/dist/lib/api/index.d.ts +1 -0
  10. package/dist/lib/api/index.d.ts.map +1 -1
  11. package/dist/lib/api/model.d.ts +67 -2
  12. package/dist/lib/api/model.d.ts.map +1 -1
  13. package/dist/lib/api/upgrade.d.ts +39 -0
  14. package/dist/lib/api/upgrade.d.ts.map +1 -0
  15. package/dist/lib/index.d.ts +4 -0
  16. package/dist/lib/index.d.ts.map +1 -1
  17. package/dist/lib/interceptors/fetch-registry.d.ts +96 -0
  18. package/dist/lib/interceptors/fetch-registry.d.ts.map +1 -0
  19. package/dist/lib/passflow.d.ts +103 -1
  20. package/dist/lib/passflow.d.ts.map +1 -1
  21. package/dist/lib/services/auth-service.d.ts +51 -2
  22. package/dist/lib/services/auth-service.d.ts.map +1 -1
  23. package/dist/lib/upgrade/acr.d.ts +85 -0
  24. package/dist/lib/upgrade/acr.d.ts.map +1 -0
  25. package/dist/lib/upgrade/axios-adapter.d.ts +81 -0
  26. package/dist/lib/upgrade/axios-adapter.d.ts.map +1 -0
  27. package/dist/lib/upgrade/challenge.d.ts +158 -3
  28. package/dist/lib/upgrade/challenge.d.ts.map +1 -1
  29. package/dist/lib/upgrade/client.d.ts +29 -0
  30. package/dist/lib/upgrade/client.d.ts.map +1 -0
  31. package/dist/lib/upgrade/controller.d.ts +366 -25
  32. package/dist/lib/upgrade/controller.d.ts.map +1 -1
  33. package/dist/lib/upgrade/core.d.ts +353 -0
  34. package/dist/lib/upgrade/core.d.ts.map +1 -0
  35. package/dist/lib/upgrade/errors.d.ts +208 -0
  36. package/dist/lib/upgrade/errors.d.ts.map +1 -0
  37. package/dist/lib/upgrade/facade.d.ts +183 -0
  38. package/dist/lib/upgrade/facade.d.ts.map +1 -0
  39. package/dist/lib/upgrade/fetch-adapter.d.ts +30 -0
  40. package/dist/lib/upgrade/fetch-adapter.d.ts.map +1 -0
  41. package/dist/lib/upgrade/index.d.ts +15 -0
  42. package/dist/lib/upgrade/index.d.ts.map +1 -1
  43. package/dist/lib/upgrade/markers.d.ts +64 -0
  44. package/dist/lib/upgrade/markers.d.ts.map +1 -0
  45. package/dist/lib/upgrade/replay.d.ts +132 -0
  46. package/dist/lib/upgrade/replay.d.ts.map +1 -0
  47. package/dist/lib/upgrade/select.d.ts.map +1 -1
  48. package/dist/lib/upgrade/session.d.ts +72 -0
  49. package/dist/lib/upgrade/session.d.ts.map +1 -0
  50. package/dist/lib/upgrade/snapshot.d.ts +196 -0
  51. package/dist/lib/upgrade/snapshot.d.ts.map +1 -0
  52. package/dist/lib/upgrade/transport.d.ts +69 -0
  53. package/dist/lib/upgrade/transport.d.ts.map +1 -0
  54. package/dist/tsconfig.build.tsbuildinfo +1 -1
  55. package/package.json +3 -3
  56. package/dist/index.js +0 -2
  57. package/dist/index.js.map +0 -1
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The request snapshot: ONE normalised, immutable description of the request
3
+ * that carried a challenge, captured before dispatch.
4
+ *
5
+ * ## Why this module exists
6
+ *
7
+ * Every authorization decision the upgrade feature makes — is this URL in scope,
8
+ * what does the diagnostic name, what does the replay re-send — must be made on
9
+ * the SAME description of the request, and that description must be the one the
10
+ * platform will actually act on. Three defects in this feature were the same
11
+ * defect from three angles:
12
+ *
13
+ * 1. the scope check hand-parsed the caller's URL *string*, while the browser
14
+ * normalises it before dispatch;
15
+ * 2. the challenge context re-read the caller's live `input` at challenge
16
+ * time, while the replay was pinned to the plan-time URL and body;
17
+ * 3. the replay could re-send a different header set than the one that was
18
+ * examined.
19
+ *
20
+ * So the request is normalised and frozen ONCE, here, and the snapshot is the
21
+ * only thing the scope check, the challenge context, the diagnostics and the
22
+ * replay are given. Nothing downstream holds a live reference to the caller's
23
+ * `Request`, `RequestInit` or axios config.
24
+ *
25
+ * ## The normalisation rule, and why it is the platform's own parser
26
+ *
27
+ * **Resolve with `new URL(raw, base)` and compare `origin` on the result.**
28
+ *
29
+ * WHATWG URL parsing is not a string scan. For a special scheme it converts
30
+ * backslashes to forward slashes and strips ASCII tab (0x09), LF (0x0A) and CR
31
+ * (0x0D) *before* parsing. A scope check that inspects the raw string therefore
32
+ * sees a same-origin relative path where the browser resolves a foreign origin:
33
+ * `'/\\evil.example/x'`, `'/\t/evil.example/x'` and `'\\\\evil.example/x'` all
34
+ * resolve to `https://evil.example` (§13.4's SF-3, SF-4, SF-7). Each one would
35
+ * attach a step-up-elevated credential to a request leaving for an
36
+ * attacker-controlled host.
37
+ *
38
+ * **The percent-encoded forms are the mirror image, and they are POSITIVES.**
39
+ * `'/%5Cevil.example/x'`, `'/%09/evil.example/x'` and `'/%2F%2Fevil.example/x'`
40
+ * all resolve to the page's OWN origin and must stay in scope (SF-9..SF-12):
41
+ * the parser decodes nothing that could change the authority, so `%5C` is not a
42
+ * backslash, `%09` stays an ordinary path character and `%2F%2F` does not begin
43
+ * an authority. They are legitimate same-origin requests with odd-looking paths.
44
+ *
45
+ * That asymmetry is the entire argument for resolving rather than filtering. A
46
+ * list of rejected characters is a denylist against a parser, and the parser is
47
+ * the authority: it is bypassed by the raw forms, whose bytes it rewrites before
48
+ * it parses them, AND it is wrong in the opposite direction on the encoded
49
+ * forms, which it refuses as hostile when the platform treats them as plain
50
+ * path text. Resolving first gets both directions — and the vectors nobody has
51
+ * thought of yet — for free.
52
+ *
53
+ * The operative consequence for anyone editing this file: hand the input to
54
+ * `new URL` **undecoded and un-normalised**. Any decoding, trimming or
55
+ * rewriting before that call reintroduces one half of the defect or the other.
56
+ *
57
+ * Off the browser there is no document, so there is no "same origin" to resolve
58
+ * against. A relative URL is then resolved against a RESERVED sentinel origin
59
+ * (`.invalid` is reserved by RFC 2606 and can never be a real host), which keeps
60
+ * exactly one code path: a URL that resolves to the sentinel's origin is a
61
+ * genuinely relative one, and anything that steers the authority elsewhere —
62
+ * `//evil.example/x` included — resolves away from it and is no longer relative.
63
+ * The sentinel is `https:` precisely because it must be a SPECIAL scheme: the
64
+ * backslash and tab rules above apply only to special schemes, so a custom
65
+ * scheme would be a different parser and would miss the vectors.
66
+ */
67
+ import type { BodyKind } from './replay';
68
+ /** One captured header. Lower-cased name, value verbatim. */
69
+ export type SnapshotHeader = readonly [name: string, value: string];
70
+ /**
71
+ * The frozen description of one request.
72
+ *
73
+ * Immutable by construction: `Object.freeze` on the snapshot and on its header
74
+ * list, and the body already captured by value where the shape is mutable. It
75
+ * carries no live reference to anything the caller can still change.
76
+ */
77
+ export type RequestSnapshot = {
78
+ /** Exactly what the caller passed, for diagnostics only. NEVER for a decision. */
79
+ readonly raw: string;
80
+ /**
81
+ * The absolute, platform-normalised URL the request will actually be sent to,
82
+ * or `raw` when it could not be resolved at all (a malformed URL).
83
+ *
84
+ * This is the value every decision and the replay use.
85
+ */
86
+ readonly href: string;
87
+ /**
88
+ * The URL to actually DISPATCH a replay to.
89
+ *
90
+ * Identical to `href` wherever a real base existed — a browser, or any host
91
+ * that resolved the URL absolutely — which is the case every decision cares
92
+ * about. It falls back to `raw` only when resolution used the reserved
93
+ * sentinel base, i.e. a relative URL on a host with no document: the
94
+ * sentinel's origin is a reserved name that resolves to nothing, so sending
95
+ * `href` there would send the request into a hole. The transport's own base
96
+ * (axios' `baseURL`, the runtime's fetch base) then resolves the captured
97
+ * string, exactly as it did for the original send.
98
+ *
99
+ * It is still a captured STRING, never the caller's object, so the TOCTOU
100
+ * this module exists to close stays closed on that path too.
101
+ */
102
+ readonly dispatchUrl: string;
103
+ /** The resolved origin, or `undefined` when the URL could not be resolved. */
104
+ readonly origin?: string;
105
+ /** The resolved pathname, or the raw path when the URL could not be resolved. */
106
+ readonly pathname: string;
107
+ /** False when the URL could not be parsed even against the base. */
108
+ readonly resolved: boolean;
109
+ /**
110
+ * True when the resolved origin is the base's own — the page's origin on a
111
+ * browser, the sentinel's off it, which means "genuinely relative".
112
+ *
113
+ * This is what a same-origin path-prefix pattern (`backend: '/api'`) tests,
114
+ * and it is the one bit that makes `'/\\evil.example/x'` fail where `'/api/x'`
115
+ * passes.
116
+ */
117
+ readonly relativeToBase: boolean;
118
+ /** Upper-cased, with the same precedence the transport itself applies. */
119
+ readonly method: string;
120
+ /** The effective header set, captured once. Frozen. */
121
+ readonly headers: readonly SnapshotHeader[];
122
+ /** How the body can be re-sent, which is what decides replayability. */
123
+ readonly bodyKind: BodyKind;
124
+ /**
125
+ * The already-captured body. `undefined` means "the caller passed no body
126
+ * key", which is distinct from an explicit `null`.
127
+ */
128
+ readonly body?: unknown;
129
+ };
130
+ /**
131
+ * The reserved origin a relative URL is resolved against when there is no
132
+ * document. RFC 2606 reserves `.invalid`, so no real deployment can collide
133
+ * with it, and `https:` keeps the parser on its special-scheme rules.
134
+ */
135
+ export declare const RELATIVE_BASE = "https://passflow-relative.invalid";
136
+ /** What a URL normalised to. Pure: it takes the base, it does not read one. */
137
+ export type NormalisedUrl = {
138
+ href: string;
139
+ origin?: string;
140
+ pathname: string;
141
+ resolved: boolean;
142
+ relativeToBase: boolean;
143
+ /** True when no real base existed and the reserved sentinel was used. */
144
+ sentinelBase: boolean;
145
+ };
146
+ /**
147
+ * Resolves one URL with the platform's own parser.
148
+ *
149
+ * `base` defaults to the document base (or the sentinel off the browser). The
150
+ * ONLY comparison any caller may make afterwards is on `origin` — never on the
151
+ * raw string.
152
+ */
153
+ export declare const normaliseUrl: (raw: string, base?: string) => NormalisedUrl;
154
+ /**
155
+ * Captures a header bag by value.
156
+ *
157
+ * Every shape the two transports produce arrives here: a DOM `Headers`, an
158
+ * `AxiosHeaders`, a plain object, an entry array, or an array-valued node bag.
159
+ * Copying is the point — the caller may still hold and mutate the original.
160
+ */
161
+ export declare const captureHeaders: (headers: unknown) => readonly SnapshotHeader[];
162
+ /** Reads a captured header. Case is already normalised, so this is exact. */
163
+ export declare const snapshotHeader: (snapshot: RequestSnapshot, name: string) => string | undefined;
164
+ /** What a caller must supply to take a snapshot. Everything else is derived. */
165
+ export type RequestSnapshotInit = {
166
+ url: string;
167
+ method?: string;
168
+ headers?: unknown;
169
+ bodyKind: BodyKind;
170
+ /** Pass the key only when the caller supplied a body, so `undefined` stays meaningful. */
171
+ body?: unknown;
172
+ /** Overrides the document base. Tests and non-browser hosts only. */
173
+ base?: string;
174
+ };
175
+ /**
176
+ * Takes the snapshot. Call it ONCE per request, BEFORE dispatch.
177
+ *
178
+ * Frozen on the way out: a snapshot that could be edited after the scope
179
+ * decision would reintroduce the very TOCTOU this module removes.
180
+ */
181
+ export declare const createRequestSnapshot: (init: RequestSnapshotInit) => RequestSnapshot;
182
+ /**
183
+ * Applies the §5.5 credential swap to a captured header set, by EXACT match.
184
+ *
185
+ * Equality with the token we hold is what proves the header was ours; any other
186
+ * value is forwarded untouched, because rewriting a header we do not own would
187
+ * be a security bug. Returns the same frozen array when nothing changed, so the
188
+ * common path allocates nothing.
189
+ */
190
+ export declare const swapAuthorization: (headers: readonly SnapshotHeader[], swap?: {
191
+ from: string;
192
+ to: string;
193
+ }) => readonly SnapshotHeader[];
194
+ /** The captured headers as the plain object both transports accept. */
195
+ export declare const headersToObject: (headers: readonly SnapshotHeader[]) => Record<string, string>;
196
+ //# sourceMappingURL=snapshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshot.d.ts","sourceRoot":"","sources":["../../../lib/upgrade/snapshot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,6DAA6D;AAC7D,MAAM,MAAM,cAAc,GAAG,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,kFAAkF;IAClF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,8EAA8E;IAC9E,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,iFAAiF;IACjF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,oEAAoE;IACpE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B;;;;;;;OAOG;IACH,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;IACjC,0EAA0E;IAC1E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,uDAAuD;IACvD,QAAQ,CAAC,OAAO,EAAE,SAAS,cAAc,EAAE,CAAC;IAC5C,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,sCAAsC,CAAC;AAuBjE,+EAA+E;AAC/E,MAAM,MAAM,aAAa,GAAG;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,OAAO,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;IACxB,yEAAyE;IACzE,YAAY,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,GAAI,KAAK,MAAM,EAAE,OAAM,MAAyB,KAAG,aAgC3E,CAAC;AAMF;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,SAAS,OAAO,KAAG,SAAS,cAAc,EA4CxE,CAAC;AAEF,6EAA6E;AAC7E,eAAO,MAAM,cAAc,GAAI,UAAU,eAAe,EAAE,MAAM,MAAM,KAAG,MAAM,GAAG,SAQjF,CAAC;AAEF,gFAAgF;AAChF,MAAM,MAAM,mBAAmB,GAAG;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,QAAQ,EAAE,QAAQ,CAAC;IACnB,0FAA0F;IAC1F,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,qEAAqE;IACrE,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,GAAI,MAAM,mBAAmB,KAAG,eAkBjE,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAC5B,SAAS,SAAS,cAAc,EAAE,EAClC,OAAO;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,KAClC,SAAS,cAAc,EAazB,CAAC;AAEF,uEAAuE;AACvE,eAAO,MAAM,eAAe,GAAI,SAAS,SAAS,cAAc,EAAE,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAMzF,CAAC"}
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The HTTP adapter behind the `UpgradeTransport` port.
3
+ *
4
+ * It owns no axios instance. Both rounds arrive as narrow, function-shaped
5
+ * dependencies, which keeps HTTP vocabulary one level away from the controller
6
+ * and lets every test here be a synchronous fake instead of an HTTP mock.
7
+ *
8
+ * It is also STATELESS by design: no cached challenge id, no cached prepare
9
+ * result, no attempt counter. A challenge is single-use and the server consumes
10
+ * it atomically, so there is nothing a second attempt could legitimately reuse.
11
+ * Statelessness is the whole of this module's obligation to "never reuse a spent
12
+ * challenge_id", and it is checkable by calling `prepare()` twice.
13
+ */
14
+ import type { UpgradeRefreshField, UpgradeStartWire } from '../api/model';
15
+ import type { UpgradeTransport } from './controller';
16
+ import { type UpgradePrepared } from './factors';
17
+ import type { UpgradeSessionPin } from './session';
18
+ export type UpgradeTransportDeps = {
19
+ /** `POST /auth/upgrade/start`. Returns the raw snake_case body; rejects with `PassflowError`. */
20
+ startUpgrade(payload: {
21
+ method: string;
22
+ relying_party_id?: string;
23
+ }): Promise<UpgradeStartWire>;
24
+ /**
25
+ * `POST /auth/refresh` carrying `upgrade`. Resolves once the elevated tokens
26
+ * are STORED.
27
+ *
28
+ * `pin` is the session and user identity the flight began under (§13.4
29
+ * revision 6). The host verifies it immediately before it applies the rotated
30
+ * tokens and discards them on mismatch — the check has to live inside the
31
+ * token-applying path, because that is the only place it cannot be bypassed
32
+ * by another entry point. The transport only carries the value; the facade
33
+ * supplies it, since the flight's start is what it is pinned to.
34
+ */
35
+ commitRefresh(upgrade: UpgradeRefreshField, pin?: UpgradeSessionPin): Promise<void>;
36
+ /** Reports whether this delivery mode can carry an upgrade at all. BFF cannot. */
37
+ canCommit(): {
38
+ ok: true;
39
+ } | {
40
+ ok: false;
41
+ reason: string;
42
+ };
43
+ /** Optional relying-party id for passkey upgrades; forwarded verbatim. */
44
+ relyingPartyId?: () => string | undefined;
45
+ /**
46
+ * Invalidates the session. Called ONLY for a commit 401 whose error id
47
+ * positively means the session died (`invalidatesSessionOnCommit`) — a
48
+ * genuine expiry during an elevation is still an expiry, and the transport is
49
+ * the only code that can tell, because it knows it issued the request and can
50
+ * read the error id. Everything else, including an id this SDK does not
51
+ * recognise, leaves the session alone.
52
+ */
53
+ markSessionInvalid?: () => void;
54
+ };
55
+ /**
56
+ * Normalises the prepare round's wire body.
57
+ *
58
+ * `webauthn` is passed through by reference, never re-serialised: the ceremony
59
+ * hands those exact bytes to the authenticator and the server re-parses them on
60
+ * the way back.
61
+ *
62
+ * A missing `challenge_id` or `expires_at` is a protocol violation, not an
63
+ * optional field. Producing `challengeId: undefined` would surface two round
64
+ * trips later as an opaque 401 with nothing to point at.
65
+ */
66
+ export declare const toPrepared: (wire: UpgradeStartWire) => UpgradePrepared;
67
+ /** Builds the transport. Returns the port type, so the controller stays HTTP-agnostic. */
68
+ export declare const createUpgradeTransport: (deps: UpgradeTransportDeps) => UpgradeTransport;
69
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../lib/upgrade/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAE1E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAQrD,OAAO,EAA0E,KAAK,eAAe,EAAE,MAAM,WAAW,CAAC;AACzH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAEnD,MAAM,MAAM,oBAAoB,GAAG;IACjC,iGAAiG;IACjG,YAAY,CAAC,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAChG;;;;;;;;;;OAUG;IACH,aAAa,CAAC,OAAO,EAAE,mBAAmB,EAAE,GAAG,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACpF,kFAAkF;IAClF,SAAS,IAAI;QAAE,EAAE,EAAE,IAAI,CAAA;KAAE,GAAG;QAAE,EAAE,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1D,0EAA0E;IAC1E,cAAc,CAAC,EAAE,MAAM,MAAM,GAAG,SAAS,CAAC;IAC1C;;;;;;;OAOG;IACH,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAC;CACjC,CAAC;AAUF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU,GAAI,MAAM,gBAAgB,KAAG,eAenD,CAAC;AAYF,0FAA0F;AAC1F,eAAO,MAAM,sBAAsB,GAAI,MAAM,oBAAoB,KAAG,gBA6ElE,CAAC"}
@@ -1 +1 @@
1
- {"root":["../lib/index.ts","../lib/passflow.ts","../lib/store.ts","../lib/api/app.ts","../lib/api/auth.ts","../lib/api/axios-client.ts","../lib/api/cli-auth.ts","../lib/api/index.ts","../lib/api/invitation.ts","../lib/api/model.ts","../lib/api/setting.ts","../lib/api/tenant.ts","../lib/api/two-factor.ts","../lib/api/user.ts","../lib/constants/index.ts","../lib/device/index.ts","../lib/m2m/client.ts","../lib/m2m/errors.ts","../lib/m2m/index.ts","../lib/m2m/types.ts","../lib/platform/index.ts","../lib/platform/types.ts","../lib/platform/web-adapter.ts","../lib/services/auth-service.ts","../lib/services/index.ts","../lib/services/invitation-service.ts","../lib/services/logger.ts","../lib/services/tenant-service.ts","../lib/services/tenant-user-membership.ts","../lib/services/token-cache-service.ts","../lib/services/two-factor-service.ts","../lib/services/user-service.ts","../lib/storage/index.ts","../lib/token/delivery-manager.ts","../lib/token/index.ts","../lib/token/membership.ts","../lib/token/service.ts","../lib/token/token.ts","../lib/types/index.ts","../lib/upgrade/challenge.ts","../lib/upgrade/controller.ts","../lib/upgrade/factors.ts","../lib/upgrade/index.ts","../lib/upgrade/select.ts","../lib/utils/validation.ts"],"version":"5.9.3"}
1
+ {"root":["../lib/index.ts","../lib/passflow.ts","../lib/store.ts","../lib/api/app.ts","../lib/api/auth.ts","../lib/api/axios-client.ts","../lib/api/cli-auth.ts","../lib/api/index.ts","../lib/api/invitation.ts","../lib/api/model.ts","../lib/api/setting.ts","../lib/api/tenant.ts","../lib/api/two-factor.ts","../lib/api/upgrade.ts","../lib/api/user.ts","../lib/constants/index.ts","../lib/device/index.ts","../lib/interceptors/fetch-registry.ts","../lib/m2m/client.ts","../lib/m2m/errors.ts","../lib/m2m/index.ts","../lib/m2m/types.ts","../lib/platform/index.ts","../lib/platform/types.ts","../lib/platform/web-adapter.ts","../lib/services/auth-service.ts","../lib/services/index.ts","../lib/services/invitation-service.ts","../lib/services/logger.ts","../lib/services/tenant-service.ts","../lib/services/tenant-user-membership.ts","../lib/services/token-cache-service.ts","../lib/services/two-factor-service.ts","../lib/services/user-service.ts","../lib/storage/index.ts","../lib/token/delivery-manager.ts","../lib/token/index.ts","../lib/token/membership.ts","../lib/token/service.ts","../lib/token/token.ts","../lib/types/index.ts","../lib/upgrade/acr.ts","../lib/upgrade/axios-adapter.ts","../lib/upgrade/challenge.ts","../lib/upgrade/client.ts","../lib/upgrade/controller.ts","../lib/upgrade/core.ts","../lib/upgrade/errors.ts","../lib/upgrade/facade.ts","../lib/upgrade/factors.ts","../lib/upgrade/fetch-adapter.ts","../lib/upgrade/index.ts","../lib/upgrade/markers.ts","../lib/upgrade/replay.ts","../lib/upgrade/select.ts","../lib/upgrade/session.ts","../lib/upgrade/snapshot.ts","../lib/upgrade/transport.ts","../lib/utils/validation.ts"],"version":"5.9.3"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@passflow/core",
3
3
  "description": "Passflow JS SDK",
4
- "version": "0.14.0",
4
+ "version": "0.15.0",
5
5
  "type": "module",
6
- "main": "./dist/index.js",
6
+ "main": "./dist/index.cjs",
7
7
  "module": "./dist/index.mjs",
8
8
  "types": "./dist/lib/index.d.ts",
9
9
  "exports": {
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "require": {
16
16
  "types": "./dist/lib/index.d.ts",
17
- "default": "./dist/index.js"
17
+ "default": "./dist/index.cjs"
18
18
  }
19
19
  }
20
20
  },
package/dist/index.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("axios"),Ae=require("uuid"),Y=require("@simplewebauthn/browser"),Ce="0.14.0",Re={version:Ce},b="X-Passflow-Clientid",I="Authorization",H="X-Passflow-DeviceId",j="X-Passflow-DeviceType",z=Re.version,Me=["id","offline","openid"],X=["id","offline","tenant","email","oidc","openid","access:tenant:all"],L="https://auth.passflow.cloud",Fe="default",W=500,J=600,Z=100,Q=6e4,N=30,ee=3,te=30,re=200,Pe=i=>{const e=[];let t;for(t in i){const r=i[t];if(r===void 0)continue;const s={tenant:{id:r.tenant_id,name:r.tenant_name}};s.groups=r.groups?Object.keys(r.groups).map(o=>{const n=r.groups[o]||[];return{group:{id:o,name:r.group_names?.[o]??"unknown"},roles:n}}):[],s.tenantRoles=s.groups?.find(o=>o.group.id===r.root_group_id),e.push(s)}return{raw:i,tenants:e}};function De(i){if(typeof window<"u"&&typeof window.atob=="function")return window.atob(i);if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf-8");throw new Error("No Base64 decoding method available in this environment")}class Ue{constructor(e){this.storageManager=e}isTokenTypeExpired(e){const t=this.storageManager.getToken(e);if(!t)return!0;const r=v(t);return r?y(r):!0}parseTokenType(e){const t=this.storageManager.getToken(e);if(t)return v(t)}}function y(i,e=N){return Math.floor(Date.now()/1e3)+e>i.exp}function v(i){const e=i.split(".")[1];if(!e)throw new Error("Invalid token string");const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),s=De(r),o=decodeURIComponent(s.split("").map(h=>"%"+("00"+h.charCodeAt(0).toString(16)).slice(-2)).join("")),n=JSON.parse(o);return n.membership=n.passflow_tm&&n.type!=="invite"?Pe(n.passflow_tm):void 0,n}var k=(i=>(i.id_token="id_token",i.access_token="access",i.refresh_token="refresh",i.invite_token="invite",i.reset_token="reset",i.web_cookie="web-cookie",i.management="management",i.signin="signin",i.actor="actor",i.two_factor="2fa",i))(k||{}),m=(i=>(i.JsonBody="json_body",i.Cookie="cookie",i.Mobile="mobile",i.BFF="bff",i))(m||{}),K=(i=>(i.Unknown="unknown",i.Valid="valid",i.Invalid="invalid",i))(K||{});class se{constructor(e){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()}setMode(e){this.mode=e,this.isInitializedFlag=!0,this.persistMode()}getMode(){return this.mode}isCookieMode(){return this.mode==="cookie"}isJsonMode(){return this.mode==="json_body"}isMobileMode(){return this.mode==="mobile"}isBFFMode(){return this.mode==="bff"}isInitialized(){return this.isInitializedFlag}setSessionValid(){this.sessionState="valid",this.persistSessionState()}setSessionInvalid(){this.sessionState="invalid",this.persistSessionState()}setSessionUnknown(){this.sessionState="unknown",this.persistSessionState()}isSessionValid(){return this.sessionState==="valid"}isSessionUnknown(){return this.sessionState==="unknown"}isSessionInvalid(){return this.sessionState==="invalid"}getSessionState(){return this.sessionState}reset(){this.mode="json_body",this.sessionState="unknown",this.isInitializedFlag=!1,this.clearPersistedMode(),this.clearPersistedSessionState()}loadPersistedMode(){try{const e=this.storageManager.storage.getItem(this.DELIVERY_MODE_KEY);e&&Object.values(m).includes(e)&&(this.mode=e,this.isInitializedFlag=!0)}catch{}}loadPersistedSessionState(){try{const e=this.storageManager.storage.getItem(this.SESSION_STATE_KEY);e&&Object.values(K).includes(e)&&(this.sessionState=e)}catch{}}persistMode(){try{this.storageManager.storage.setItem(this.DELIVERY_MODE_KEY,this.mode)}catch{}}persistSessionState(){try{this.storageManager.storage.setItem(this.SESSION_STATE_KEY,this.sessionState)}catch{}}clearPersistedMode(){try{this.storageManager.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}clearPersistedSessionState(){try{this.storageManager.storage.removeItem(this.SESSION_STATE_KEY)}catch{}}}class V{constructor({storage:e,prefix:t}={}){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}_`:""}saveTokens(e,t){const{id_token:r,access_token:s,refresh_token:o,scopes:n}=e;t===m.Cookie||t===m.BFF?r&&this.storage.setItem(this.ID_TOKEN_KEY,r):(r&&this.storage.setItem(this.getKeyForTokenType(k.id_token),r),s&&this.storage.setItem(this.getKeyForTokenType(k.access_token),s),o&&this.storage.setItem(this.getKeyForTokenType(k.refresh_token),o),n&&this.storage.setItem(this.scopes,n.join(",")))}getToken(e){const t=this.getKeyForTokenType(e);return this.storage.getItem(t)??void 0}getTokens(){const e=this.getDeliveryMode();if(e===m.Cookie||e===m.BFF){const r=this.storage.getItem(this.ID_TOKEN_KEY);return r?{id_token:r}:void 0}const t=this.storage.getItem(this.getKeyForTokenType(k.access_token));if(t)return{access_token:t,id_token:this.storage.getItem(this.getKeyForTokenType(k.id_token))??void 0,refresh_token:this.storage.getItem(this.getKeyForTokenType(k.refresh_token))??void 0,scopes:this.storage.getItem(this.scopes)?.split(",")??void 0}}getScopes(){return this.storage.getItem(this.scopes)?.split(",")??void 0}hasJsonModeTokens(){return!!this.storage.getItem(this.getKeyForTokenType(k.access_token))}hasCookieModeIdToken(){return!!this.storage.getItem(this.ID_TOKEN_KEY)}deleteToken(e){const t=this.getKeyForTokenType(e);this.storage.removeItem(t)}deleteTokens(){this.storage.removeItem(this.getKeyForTokenType(k.id_token)),this.storage.removeItem(this.getKeyForTokenType(k.access_token)),this.storage.removeItem(this.getKeyForTokenType(k.refresh_token)),this.storage.removeItem(this.scopes),this.clearIdToken(),this.clearDeliveryMode(),this.clearCsrfToken()}getDeviceId(){return this.storage.getItem(this.deviceId)??void 0}setDeviceId(e){this.storage.setItem(this.deviceId,e)}deleteDeviceId(){this.storage.removeItem(this.deviceId)}setInvitationToken(e){this.storage.setItem(this.invitationToken,e)}getInvitationToken(){return this.storage.getItem(this.invitationToken)??void 0}deleteInvitationToken(){this.storage.removeItem(this.invitationToken)}setPreviousRedirectUrl(e){this.storage.setItem(this.previousRedirectUrl,e)}getPreviousRedirectUrl(){return this.storage.getItem(this.previousRedirectUrl)??void 0}deletePreviousRedirectUrl(){this.storage.removeItem(this.previousRedirectUrl)}setDeliveryMode(e){try{this.storage.setItem(this.DELIVERY_MODE_KEY,e)}catch{}}getDeliveryMode(){try{const e=this.storage.getItem(this.DELIVERY_MODE_KEY);if(e&&Object.values(m).includes(e))return e}catch{}}clearDeliveryMode(){try{this.storage.removeItem(this.DELIVERY_MODE_KEY)}catch{}}getIdToken(){try{return this.storage.getItem(this.ID_TOKEN_KEY)??void 0}catch{return}}setIdToken(e){try{this.storage.setItem(this.ID_TOKEN_KEY,e)}catch{}}clearIdToken(){try{this.storage.removeItem(this.ID_TOKEN_KEY)}catch{}}getCsrfToken(){try{return this.storage.getItem(this.CSRF_TOKEN_KEY)??void 0}catch{return}}setCsrfToken(e){try{this.storage.setItem(this.CSRF_TOKEN_KEY,e)}catch{}}clearCsrfToken(){try{this.storage.removeItem(this.CSRF_TOKEN_KEY)}catch{}}getKeyForTokenType(e){return`${this.keyStoragePrefix}${e}`}}class ie{constructor(e){this.storageManager=e??new V}getDeviceId(){const e=this.storageManager.getDeviceId();if(!e){const t=this.generateUniqueDeviceId();return this.storageManager.setDeviceId(t),t}return e}generateUniqueDeviceId(){return Ae.v4()}}class G extends Error{constructor(e="Authentication popup was closed"){super(e),this.name="PopupClosedError"}}class oe{constructor(){this.passkeys={startRegistration:e=>Y.startRegistration({optionsJSON:e}),startAuthentication:e=>Y.startAuthentication({optionsJSON:e})}}get storage(){return typeof localStorage>"u"?{getItem:()=>null,setItem:()=>{},removeItem:()=>{}}:localStorage}getCurrentUrl(){return typeof window>"u"?null:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,hostname:window.location.hostname}}replaceUrl(e){typeof window>"u"||window.history.replaceState({},document.title,e)}navigateTo(e){typeof window>"u"||(window.location.href=e)}onForeground(e){if(typeof document>"u")return()=>{};const t=()=>{document.hidden||e()};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}onBackground(e){if(typeof document>"u")return()=>{};const t=()=>{document.hidden&&e()};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}onBeforeUnload(e){return typeof window>"u"?()=>{}:(window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e))}isInForeground(){return typeof document>"u"?!0:!document.hidden}openAuthUrl(e,t={}){const r=t.mode??"popup";if(r==="redirect")return window.location.href=e,new Promise(()=>{});if(r==="deeplink")return Promise.reject(new Error('openAuthUrl: "deeplink" mode is not supported on web. Use "popup" or "redirect" instead, or provide a native platform adapter.'));const s=t.width??W,o=t.height??J,n=t.expectedReturnOrigin??window.location.origin,h=window.open(e,"_blank",`width=${s},height=${o}`);return h?new Promise((d,u)=>{const g=Date.now(),f=setInterval(()=>{if(h.closed){clearInterval(f),u(new G);return}if(Date.now()-g>Q){clearInterval(f),h.close(),u(new Error("Authentication popup timed out"));return}try{if(h.location.href.startsWith(n)){const x=h.location.search,be=h.location.hash;clearInterval(f),h.close(),d({callbackSearch:x,callbackHash:be})}}catch{}},Z)}):(window.location.href=e,new Promise(()=>{}))}btoa(e){return btoa(e)}atob(e){if(typeof window<"u"&&typeof window.atob=="function")return window.atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf-8");throw new Error("No Base64 decoding method available in this environment")}cookiesSupported(){if(typeof document>"u")return!1;try{document.cookie="passflow_test=1; SameSite=Lax";const e=document.cookie.indexOf("passflow_test=1")!==-1;return document.cookie="passflow_test=; expires=Thu, 01 Jan 1970 00:00:00 UTC",e}catch{return!1}}getDeviceType(){return"web"}}const A=new oe,xe="insufficient_user_authentication",Oe="upgrade_required",B=/([A-Za-z0-9!#$%&'*+\-.^_`|~]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))/g,$e=i=>i.replace(/\\(.)/g,"$1"),Le=i=>{const e={};B.lastIndex=0;for(const t of i.matchAll(B)){const r=t[1];if(!r)continue;const s=t[2],o=t[3];e[r.toLowerCase()]=s!==void 0?$e(s):o??""}return e},ne=i=>{const e=typeof i=="number"?i:Number.parseInt(String(i??""),10);return Number.isFinite(e)&&e>0?e:void 0},Ne=(i,e)=>{if(!i||!/(^|[\s,])Bearer\b/i.test(i))return;const t=Le(i);if(t.error===xe)return{acrValues:t.acr_values||void 0,maxAge:ne(t.max_age),status:e}},Ke=(i,e)=>{if(!i||typeof i!="object")return;const t=i;if(t.error===Oe)return{acrValues:typeof t.acr_values=="string"&&t.acr_values?t.acr_values:void 0,maxAge:ne(t.max_age),status:e}},Ve=(i,e,t)=>{if(!(i!==401&&i!==403))return Ne(e("www-authenticate"),i)??Ke(t,i)};var _=(i=>(i.GET="get",i.POST="post",i.PUT="put",i.PATCH="patch",i.DELETE="delete",i))(_||{}),c=(i=>(i.signin="/auth/login",i.signup="/auth/register",i.signInWithProvider="/auth/federated/start/",i.passwordless="/auth/passwordless/start",i.passwordlessComplete="/auth/passwordless/complete",i.logout="/user/logout",i.refresh="/auth/refresh",i.validateSession="/user/me",i.sendPasswordResetEmail="/auth/password/reset",i.resetPassword="/auth/password/change",i.appSettings="/app/settings",i.passkeyRegisterStart="/auth/passkey/register/start",i.passkeyRegisterComplete="/auth/passkey/register/complete",i.passkeyAuthenticateStart="/auth/passkey/authenticate/start",i.passkeyAuthenticateComplete="/auth/passkey/authenticate/complete",i.passkeyValidate="/auth/validate",i.settingsAll="/settings",i.settingsPasswordPolicy="/settings/password",i.settingsPasskey="/settings/passkey",i.userPasskey="/user/passkey",i.addUserPasskey="/user/passkey/add/start",i.completeAddUserPasskey="/user/passkey/add/complete",i.joinInvitation="/user/tenant/join",i.tenantPath="/user/tenant",i.invitationsPath="/user/tenant/:tenantID/invitations",i.requestInvitation="/user/invite",i.invitationDelete="/user/invite/:invitationID",i.invitationResend="/user/invite/:invitationID/resend",i.invitationGetLink="/user/invite/:invitationID/link",i.twoFactor="/user/2fa",i.twoFactorStatus="/user/2fa/status",i.twoFactorSetupBegin="/user/2fa/setup/begin",i.twoFactorSetupConfirm="/user/2fa/setup/confirm",i.twoFactorVerify="/auth/2fa/verify",i.twoFactorRecovery="/auth/2fa/recovery",i.twoFactorRegenerateCodes="/user/2fa/recovery-codes/regenerate",i.twoFactorSetupMagicLink="/auth/2fa-setup",i.TwoFactorMethodsAvailable="/v2/user/2fa/methods/available",i.TwoFactorMethodsRegistered="/v2/user/2fa/methods",i.TwoFactorSetupStart="/v2/user/2fa/setup/start",i.TwoFactorSetupComplete="/v2/user/2fa/setup/complete",i.TwoFactorMethodRemove="/v2/user/2fa/methods/:id",i.TwoFactorChallenge="/v2/auth/2fa/challenge",i.TwoFactorVerifyV2="/v2/auth/2fa/verify",i.TwoFactorAlternative="/v2/auth/2fa/alternative",i.TwoFactorTrustedDevices="/v2/user/2fa/trusted-devices",i.TwoFactorTrustedDeviceRevoke="/v2/user/2fa/trusted-devices/:id",i.cliAuthStatus="/cli/auth/status/:sessionId",i.cliAuthComplete="/cli/auth/complete",i))(c||{}),w=(i=>(i.passkeyRegisterStart="/admin/auth/passkey/register/start",i.passkeyRegisterComplete="/admin/auth/passkey/register/complete",i.passkeyAuthenticateStart="/admin/auth/passkey/authenticate/start",i.passkeyAuthenticateComplete="/admin/auth/passkey/authenticate/complete",i.passkeyValidate="/admin/auth/validate",i.logout="/admin/auth/logout",i))(w||{});class l extends Error{constructor(e){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??new Date().toISOString()}}var ae=(i=>(i.google="google",i.facebook="facebook",i))(ae||{}),ce=(i=>(i.web="web",i.ios="ios",i.android="android",i))(ce||{});function Ge(i){return i}function T(i,e){let t=i;return Object.entries(e).forEach(([r,s])=>{t=t.replace(`:${r}`,s)}),t}var he=(i=>(i.Disabled="disabled",i.Optional="optional",i.Required="required",i))(he||{});const qe=3,Ye=1e3,Be=i=>Ve(i.status,e=>{const t=i.headers?.[e]??i.headers?.[e.toLowerCase()];return Array.isArray(t)?t.join(", "):t},i.data)!==void 0;class E{constructor(e,t,r){this.refreshPromise=null,this.isRefreshing=!1,this.defaultHeaders={Accept:"application/json","Content-Type":"application/json"},this.nonAccessTokenEndpoints=["/auth/","/settings","/settings/"],this.protectedEndpoints=["logout","refresh"];const{url:s,appId:o,keyStoragePrefix:n}=e;this._platform=e.platform??A,this.url=s||L,this.storageManager=t??new V({prefix:n??""}),this.deviceService=r??new ie(this.storageManager),this.tokenService=new Ue(this.storageManager),this.tokenDeliveryManager=new se(this.storageManager),o&&(this.appId=o,this.defaultHeaders={...this.defaultHeaders,[b]:o});const h=this.deviceService.getDeviceId();this.defaultHeaders={...this.defaultHeaders,[H]:h,[j]:this._platform.getDeviceType()},this.detectCookieSupport(),this.instance=U.create({baseURL:this.url,headers:{...this.defaultHeaders}}),this.instance.interceptors.request.use(async d=>{if(this.isNonAuthEndpoint(d.url))return d;if(this.tokenDeliveryManager.isCookieMode()){d.withCredentials=!0;const g=this.storageManager.getCsrfToken();return g&&(d.headers["X-CSRF-Token"]=g),d}if(d.url?.includes("refresh")){if(this.isRefreshing){const g=new AbortController;return g.abort(),d.signal=g.signal,d}return d}const u=this.storageManager.getTokens();if(u?.access_token){const g=v(u.access_token);if(y(g,N)&&u.refresh_token)try{if(this.refreshPromise){const f=await this.refreshPromise;return f?.data?.access_token&&(d.headers[I]=`Bearer ${f.data.access_token}`),d}this.refreshPromise=this.refreshTokens();try{const f=await this.refreshPromise;return f?.data?.access_token&&(d.headers[I]=`Bearer ${f.data.access_token}`),d}finally{this.refreshPromise=null}}catch(f){return this.refreshPromise=null,this.isRefreshing=!1,this.storageManager.deleteTokens(),Promise.reject(f)}return d.headers[I]=`Bearer ${u.access_token}`,d}return d}),this.instance.interceptors.response.use(d=>d,async d=>(d.response?.status===401&&!Be(d.response)&&this.tokenDeliveryManager.setSessionInvalid(),d.response?.status===429?await this.handleRateLimitError(d):this.handleAxiosError(d)))}get origin(){return this._platform.getCurrentUrl()?.origin??""}isProtectedEndpoint(e){return this.protectedEndpoints.some(t=>e?.includes(t))}isNonAuthEndpoint(e){return this.nonAccessTokenEndpoints.some(t=>e?.includes(t))&&!this.isProtectedEndpoint(e)}detectCookieSupport(){if(!this._platform.cookiesSupported()&&this.tokenDeliveryManager.isCookieMode())throw new Error("Passflow SDK: Cookie delivery mode is configured but cookies are not supported in this environment. Use a platform adapter that supports cookies or configure the server to use JSON token delivery.")}async refreshTokens(){if(this.tokenDeliveryManager.isCookieMode()){const e=await this.instance.post(c.refresh,{},{withCredentials:!0});return this.tokenDeliveryManager.setSessionValid(),e.data.csrf_token&&this.storageManager.setCsrfToken(e.data.csrf_token),e.data.id_token&&this.storageManager.setIdToken(e.data.id_token),e}else{const e=this.storageManager.getTokens(),t=this.storageManager.getScopes();if(!e?.refresh_token)throw new Error("No refresh token available");this.isRefreshing=!0;const r={refresh_token:e.refresh_token,scopes:t},s=await this.instance.post(c.refresh,r,{headers:{[I]:`Bearer ${e.refresh_token}`}});return s.data&&this.storageManager.saveTokens(s.data),this.isRefreshing=!1,s}}async handleRateLimitError(e){const t=e.config;if(!t)return Promise.reject(e);const r=t.method?.toUpperCase();if(!["GET","HEAD","OPTIONS"].includes(r||""))return Promise.reject(e);const o=t._retryCount||0;if(o>=qe)return Promise.reject(e);let n=Ye*Math.pow(2,o);const h=e.response?.headers?.["retry-after"];if(h){const d=Number.parseInt(h,10);if(!Number.isNaN(d))n=d*1e3;else{const u=new Date(h);Number.isNaN(u.getTime())||(n=Math.max(0,u.getTime()-Date.now()))}}return await new Promise(d=>setTimeout(d,n)),t._retryCount=o+1,this.instance.request(t)}async handleAxiosError(e){if(!e.response)return Promise.reject(e);const t=e.response.status,r=e.response.data;if("error"in r&&typeof r.error=="object"&&r.error!==null){const{error:s}=r;return Promise.reject(new l(s))}return Promise.reject(new l({id:`error.http.${t}`,message:e.message||"An error occurred",status:t,location:e.config?.url||"unknown",time:new Date().toISOString()}))}async send(e,t,r){return(await this.instance.request({method:e,url:t,...r})).data}get(e,t){return this.send(_.GET,e,t)}post(e,t,r){return this.send(_.POST,e,{data:t,...r})}put(e,t,r){return this.send(_.PUT,e,{data:t,...r})}patch(e,t,r){return this.send(_.PATCH,e,{data:t,...r})}delete(e,t){return this.send(_.DELETE,e,t)}setAppId(e){this.appId=e,this.defaultHeaders={...this.defaultHeaders,[b]:e},this.instance.defaults.headers.common[b]=e}}class de{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getAppSettings(){return this.axiosClient.get(c.appSettings)}}class ue{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}refreshToken(e,t,r){const s={access:r,scopes:t};return this.axiosClient.post(c.refresh,s,{headers:{[I]:`Bearer ${e}`}})}signIn(e,t,r){const s={...e,device:t,os:r};return this.axiosClient.post(c.signin,s)}signUp(e){const{create_tenant:t,anonymous:r}=e,s={...e,create_tenant:t??!1,anonymous:r??!1};return this.axiosClient.post(c.signup,s)}passwordlessSignIn(e,t,r){const{create_tenant:s}=e,o={...e,create_tenant:s??!1,device:t,os:r};return this.axiosClient.post(c.passwordless,o)}passwordlessSignInComplete(e){return this.axiosClient.post(c.passwordlessComplete,e)}logOut(e,t,r=!1){const s=r?void 0:{refresh_token:t,device:e},o=r?w.logout:c.logout;return this.axiosClient.post(o,s)}validateSession(){return this.axiosClient.get(c.validateSession)}sendPasswordResetEmail(e){return this.axiosClient.post(c.sendPasswordResetEmail,e)}resetPassword(e,t,r){const s={password:e,scopes:t};return this.axiosClient.post(c.resetPassword,s,{headers:{[I]:`Bearer ${r}`,[b]:void 0}})}passkeyRegisterStart(e,t,r,s=!1){const{create_tenant:o}=e,n={...e,create_tenant:o??!1,device:t,os:r},h=s?w.passkeyRegisterStart:c.passkeyRegisterStart;return this.axiosClient.post(h,n)}passkeyRegisterComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},n=s?w.passkeyRegisterComplete:c.passkeyRegisterComplete;return this.axiosClient.post(n,o)}passkeyAuthenticateStart(e,t,r,s=!1){const o={...e,user_id:e.user_id??"",device:t,os:r},n=s?w.passkeyAuthenticateStart:c.passkeyAuthenticateStart;return this.axiosClient.post(n,o)}passkeyAuthenticateComplete(e,t,r,s=!1){const o={challenge_id:r,device:t,passkey_data:e},n=s?w.passkeyAuthenticateComplete:c.passkeyAuthenticateComplete;return this.axiosClient.post(n,o)}passkeyValidate(e,t,r,s=!1,o){const n={otp:e,device:t,challenge_id:r};let h=c.passkeyValidate;!o&&s&&(h=w.passkeyValidate);const d=o?{[b]:o}:{};return this.axiosClient.post(h,n,{headers:d})}}class He{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getCLIAuthStatus(e){const t=T(c.cliAuthStatus,{sessionId:e});return this.axiosClient.get(t)}completeCLIAuth(e){return this.axiosClient.post(c.cliAuthComplete,e)}}class le{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}requestInviteLink(e){return this.axiosClient.post(c.requestInvitation,e)}getInvitations(e){const t={};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());const r=T(c.invitationsPath,{tenantID:e.tenantID});return this.axiosClient.get(r,{params:t}).then(s=>({invites:s.invites,nextPageSkip:s.next_page_skip}))}deleteInvitation(e){const t=T(c.invitationDelete,{invitationID:e});return this.axiosClient.delete(t)}resendInvitation(e){const t=T(c.invitationResend,{invitationID:e});return this.axiosClient.post(t,{})}getInvitationLink(e){const t=T(c.invitationGetLink,{invitationID:e});return this.axiosClient.get(t)}}class pe{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getSettingsAll(){return this.axiosClient.get(c.settingsAll)}getPasswordPolicySettings(){return this.axiosClient.get(c.settingsPasswordPolicy)}getPasskeySettings(){return this.axiosClient.get(c.settingsPasskey)}}class ge{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}joinInvitation(e,t){const r={invite_token:e,scopes:t};return this.axiosClient.post(c.joinInvitation,r)}createTenant(e){const t={name:e};return this.axiosClient.post(c.tenantPath,t)}getTenantDetails(e){const t=`${c.tenantPath}/${e}`;return this.axiosClient.get(t)}updateTenant(e,t){const r=`${c.tenantPath}/${e}`,s={name:t};return this.axiosClient.put(r,s)}deleteTenant(e){const t=`${c.tenantPath}/${e}`;return this.axiosClient.delete(t)}getUserTenantMembership(){return this.axiosClient.get(c.tenantPath)}createGroup(e,t){const r=`${c.tenantPath}/${e}/group`,s={name:t};return this.axiosClient.post(r,s)}getGroupInfo(e,t){const r=`${c.tenantPath}/${e}/group/${t}`;return this.axiosClient.get(r)}updateGroup(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}`,o={name:r};return this.axiosClient.put(s,o)}deleteGroup(e,t){const r=`${c.tenantPath}/${e}/group/${t}`;return this.axiosClient.delete(r)}addUserToGroup(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/add`,n={user_id:r,role:s};return this.axiosClient.post(o,n)}removeUserRolesFromGroup(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/remove_roles`,n={user_id:r,roles:s};return this.axiosClient.post(o,n)}changeUserRoles(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/change`,n={user_id:r,roles:s};return this.axiosClient.post(o,n)}deleteUserFromGroup(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/${r}`;return this.axiosClient.delete(s)}getRolesForTenant(e){const t=`${c.tenantPath}/${e}/role`;return this.axiosClient.get(t)}createRoleForTenant(e,t){const r=`${c.tenantPath}/${e}/role`,s={name:t};return this.axiosClient.post(r,s)}updateRole(e,t,r){const s=`${c.tenantPath}/${e}/role/${t}`,o={name:r};return this.axiosClient.put(s,o)}deleteRole(e,t){const r=`${c.tenantPath}/${e}/role/${t}`;return this.axiosClient.delete(r)}deleteUserFromTenant(e,t){const r=`${c.tenantPath}/${e}/user/${t}`;return this.axiosClient.delete(r)}getGroupInvitations(e,t,r,s){const o=`${c.tenantPath}/${e}/group/${t}/invitations`;return this.axiosClient.get(o,{params:{limit:r,skip:s}})}getTenantInvitations(e,t,r){const s=`${c.tenantPath}/${e}/invitations`;return this.axiosClient.get(s,{params:{limit:t,skip:r}})}invalidateInviteById(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/invite/${r}`;return this.axiosClient.delete(s)}invalidateInviteByEmail(e,t,r){const s=`${c.tenantPath}/${e}/group/${t}/invite/email/${r}`;return this.axiosClient.delete(s)}}class fe{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getStatus(){return this.axiosClient.get(c.twoFactorStatus)}beginSetup(){return this.axiosClient.post(c.twoFactorSetupBegin,{})}confirmSetup(e){return this.axiosClient.post(c.twoFactorSetupConfirm,e)}verify(e){const{tfa_token:t,code:r}=e;return this.axiosClient.post(c.twoFactorVerify,{code:r},{headers:{Authorization:`Bearer ${t}`}})}useRecoveryCode(e){const{tfa_token:t,recovery_code:r}=e;return this.axiosClient.post(c.twoFactorRecovery,{recovery_code:r},{headers:{Authorization:`Bearer ${t}`}})}disable(e){return this.axiosClient.delete(c.twoFactor,{data:e})}regenerateRecoveryCodes(e){return this.axiosClient.post(c.twoFactorRegenerateCodes,e)}validateTwoFactorSetupMagicLink(e){const t=`${c.twoFactorSetupMagicLink}/${e}`;return this.axiosClient.get(t,{transformRequest:[(r,s)=>(s&&delete s.Authorization,r)]}).then(r=>{const s=r;return{success:!0,sessionToken:s.session_token,userId:s.user_id,expiresIn:s.expires_in,appId:s.app_id}}).catch(r=>{if(r.response){const s=r.response.status,o=r.response.data||{},n=r.response.headers?.["retry-after"]?parseInt(r.response.headers["retry-after"],10):void 0;return{success:!1,error:{code:o.error||this.mapStatusToErrorCode(s),message:o.message||this.getDefaultErrorMessage(s),retryAfter:n}}}return{success:!1,error:{code:"SERVER_ERROR",message:r instanceof Error?r.message:"Unable to connect to the server. Please check your connection."}}})}mapStatusToErrorCode(e){switch(e){case 400:return"INVALID_TOKEN";case 404:return"REVOKED_TOKEN";case 410:return"EXPIRED_TOKEN";case 429:return"RATE_LIMITED";default:return"SERVER_ERROR"}}getDefaultErrorMessage(e){switch(e){case 400:return"The provided magic link is invalid or malformed.";case 404:return"This magic link has been revoked or does not exist.";case 410:return"This magic link has expired. Please request a new one from your administrator.";case 429:return"Too many validation attempts. Please try again later.";default:return"An error occurred while validating the magic link."}}getAvailableMethods(){return this.axiosClient.get(c.TwoFactorMethodsAvailable)}getRegisteredMethods(){return this.axiosClient.get(c.TwoFactorMethodsRegistered)}startMethodSetup(e,t){return this.axiosClient.post(c.TwoFactorSetupStart,{...t,method:e})}completeMethodSetup(e,t){return this.axiosClient.post(c.TwoFactorSetupComplete,{...t,method:e})}removeMethod(e){const t=T(c.TwoFactorMethodRemove,{id:e});return this.axiosClient.delete(t)}requestChallenge(e){return this.axiosClient.post(c.TwoFactorChallenge,e)}verifyV2(e){return this.axiosClient.post(c.TwoFactorVerifyV2,e)}switchToAlternative(e){return this.axiosClient.post(c.TwoFactorAlternative,e)}getTrustedDevices(){return this.axiosClient.get(c.TwoFactorTrustedDevices)}revokeTrustedDevice(e){const t=T(c.TwoFactorTrustedDeviceRevoke,{id:e});return this.axiosClient.delete(t)}}class ke{constructor(e,t,r){this.axiosClient=new E(e,t,r)}setAppId(e){this.axiosClient.setAppId(e)}getUserPasskeys(){return this.axiosClient.get(c.userPasskey)}renameUserPasskey(e,t){return this.axiosClient.patch(`${c.userPasskey}/${t}`,{name:e})}deleteUserPasskey(e){return this.axiosClient.delete(`${c.userPasskey}/${e}`)}addUserPasskeyStart({relyingPartyId:e,deviceId:t,os:r,passkeyDisplayName:s,passkeyUsername:o}){const n={passkey_display_name:s,passkey_username:o,relying_party_id:e,deviceId:t,os:r};return this.axiosClient.post(c.addUserPasskey,n)}addUserPasskeyComplete(e,t,r){return this.axiosClient.post(c.completeAddUserPasskey,{challenge_id:r,device:t,passkey_data:e})}}var a=(i=>(i.SignIn="signin",i.SignInStart="signin:start",i.Register="register",i.RegisterStart="register:start",i.SignOut="signout",i.SessionRestored="session:restored",i.SessionExpired="session:expired",i.Error="error",i.Refresh="refresh",i.RefreshStart="refresh:start",i.TokenCacheExpired="token-cache-expired",i.TwoFactorRequired="2fa:required",i.TwoFactorSetupStarted="2fa:setup_started",i.TwoFactorEnabled="2fa:enabled",i.TwoFactorDisabled="2fa:disabled",i.TwoFactorVerified="2fa:verified",i.TwoFactorRecoveryUsed="2fa:recovery_used",i.TwoFactorRecoveryCodesLow="2fa:recovery_low",i.TwoFactorRecoveryCodesExhausted="2fa:recovery_exhausted",i.TwoFactorSetupMagicLinkValidated="2fa:magic_link_validated",i.TwoFactorSetupMagicLinkFailed="2fa:magic_link_failed",i.TwoFactorChallengeReceived="two_factor_challenge_received",i.TwoFactorMethodSwitched="two_factor_method_switched",i.TwoFactorDeviceTrusted="two_factor_device_trusted",i))(a||{});class je{constructor(){this.subscribers=new Map}subscribe(e,t){if(t?.length){const r=new Set(t);this.subscribers.set(e,r)}else this.subscribers.set(e,null)}unsubscribe(e,t){if(!t?.length){this.subscribers.delete(e);return}const r=this.subscribers.get(e);r&&(t.forEach(s=>r.delete(s)),r.size===0&&this.subscribers.delete(e))}notify(e,t){this.subscribers.forEach((r,s)=>{(!r||r.has(e))&&s.onAuthChange?.(e,t)})}}function M(i){if(!i||typeof i!="string")return!1;const e=i.split(".");if(e.length!==3)return!1;const t=/^[A-Za-z0-9_-]+$/;return e.every(r=>t.test(r)&&r.length>0)}function ve(i){return i.replace(/<[^>]*>/g,"").substring(0,re)}function F(i){if(!i||typeof i!="string")return!1;const e=i.trim();return e.length===0?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function P(i){if(!i||typeof i!="string")return!1;const e=i.trim();return/^\+[1-9]\d{1,14}$/.test(e)}function me(i){if(!i||typeof i!="string")return!1;const e=i.trim();return e.length<ee||e.length>te?!1:/^[a-zA-Z0-9_-]+$/.test(e)}function R(i,e=6){return!i||typeof i!="string"?!1:(e===8?/^\d{8}$/:/^\d{6}$/).test(i)}function ze(i){if(!i||typeof i!="string")return null;const e=i.toUpperCase().replace(/\s+/g,"");return/^[A-Z0-9-]{4,16}$/.test(e)?e:null}class ye{constructor(e,t,r,s,o,n,h,d,u,g,f,x=A){this.authApi=e,this.deviceService=t,this.storageManager=r,this.subscribeStore=s,this.tokenCacheService=o,this.scopes=n,this.createTenantForNewUser=h,this.url=d,this.sessionCallbacks=u,this.appId=g,this.platform=x,this.tokenExchangeConfig=f,this.tokenDeliveryManager=new se(r),f?.enabled&&this.tokenDeliveryManager.setMode(m.BFF),this.initializeSession()}async initializeSession(){(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode())&&await this.restoreSession()}async restoreSession(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.statusUrl)try{const e=await fetch(this.tokenExchangeConfig.statusUrl,{method:"GET",credentials:"include"});return e.ok&&(await e.json()).authenticated?(this.tokenDeliveryManager.setSessionValid(),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}if(!this.tokenDeliveryManager.isCookieMode())return!1;try{const e=await this.authApi.validateSession();return e.valid?(this.tokenDeliveryManager.setSessionValid(),e.user&&this.subscribeStore.notify(a.SessionRestored,e.user),!0):(this.tokenDeliveryManager.setSessionInvalid(),!1)}catch{return this.tokenDeliveryManager.setSessionInvalid(),!1}}async processAuthResponse(e,t){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)}async forwardTokensToBFF(e){if(!this.tokenExchangeConfig?.callbackUrl)return;const t=await fetch(this.tokenExchangeConfig.callbackUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:e.access_token,refresh_token:e.refresh_token,id_token:e.id_token,expires_in:e.expires_in})});if(!t.ok)throw new Error(`BFF token storage failed: ${t.status}`)}async signIn(e){if("email"in e&&e.email&&!F(e.email)){const s=new Error("Invalid email format"),o={message:"Invalid email format",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(a.Error,o),s}if("username"in e&&e.username&&!me(e.username)){const s=new Error("Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens"),o={message:"Invalid username format. Username must be 3-30 characters and contain only letters, numbers, underscores, and hyphens",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(a.Error,o),s}if("phone"in e&&e.phone&&!P(e.phone)){const s=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),o={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(a.Error,o),s}this.subscribeStore.notify(a.SignInStart,{email:e.email});const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();e.scopes=e.scopes??this.scopes;try{const s=await this.authApi.signIn(e,t,r);return"requires_2fa"in s&&s.requires_2fa===!0||"tfa_token"in s&&s.tfa_token?(this.subscribeStore.notify(a.TwoFactorRequired,{email:e.email||"",challengeId:s.challenge_id||"",tfaToken:s.tfa_token||""}),s):(await this.processAuthResponse(s,e.scopes),this.subscribeStore.notify(a.SignIn,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),s)}catch(s){const o={message:s instanceof Error?s.message:"Sign in failed",originalError:s,code:s instanceof l?s.id:void 0};throw this.subscribeStore.notify(a.Error,o),s}}async signUp(e){if(e.user.email&&!F(e.user.email)){const t=new Error("Invalid email format"),r={message:"Invalid email format",originalError:t,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(a.Error,r),t}if(e.user.phone_number&&!P(e.user.phone_number)){const t=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),r={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:t,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(a.Error,r),t}this.subscribeStore.notify(a.RegisterStart,{email:e.user.email}),e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{const t=await this.authApi.signUp(e);return await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(a.Register,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){const r={message:t instanceof Error?t.message:"Sign up failed",originalError:t,code:t instanceof l?t.id:void 0};throw this.subscribeStore.notify(a.Error,r),t}}async passwordlessSignIn(e){if(e.email&&!F(e.email)){const s=new Error("Invalid email format"),o={message:"Invalid email format",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(a.Error,o),s}if(e.phone&&!P(e.phone)){const s=new Error("Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)"),o={message:"Invalid phone number format. Phone must be in E.164 format (e.g., +12345678901)",originalError:s,code:"VALIDATION_ERROR"};throw this.subscribeStore.notify(a.Error,o),s}this.subscribeStore.notify(a.SignInStart,{email:e.email}),e.scopes=e.scopes??this.scopes;const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();try{return await this.authApi.passwordlessSignIn(e,t,r)}catch(s){const o={message:s instanceof Error?s.message:"Failed to send passwordless sign-in link",originalError:s,code:s instanceof l?s.id:void 0};throw this.subscribeStore.notify(a.Error,o),s}}async passwordlessSignInComplete(e){this.subscribeStore.notify(a.SignInStart,{}),e.scopes=e.scopes??this.scopes,e.device=this.deviceService.getDeviceId();try{const t=await this.authApi.passwordlessSignInComplete(e);return await this.processAuthResponse(t,e.scopes),this.subscribeStore.notify(a.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){const r={message:t instanceof Error?t.message:"Passwordless sign in failed",originalError:t,code:t instanceof l?t.id:void 0};throw this.subscribeStore.notify(a.Error,r),t}}async logOut(){if(this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.logoutUrl)try{(await fetch(this.tokenExchangeConfig.logoutUrl,{method:"POST",credentials:"include"})).ok}catch{}else{const e=this.storageManager.getToken(k.refresh_token),t=this.storageManager.getDeviceId();try{if((await this.authApi.logOut(t,e,!this.appId)).status!=="ok")throw new Error("Logout failed")}catch{}}this.storageManager.deleteTokens(),this.storageManager.clearIdToken(),this.storageManager.clearCsrfToken(),this.tokenDeliveryManager.reset(),this.subscribeStore.notify(a.SignOut,{})}async refreshToken(){if(this.subscribeStore.notify(a.RefreshStart,{}),this.tokenDeliveryManager.isBFFMode()&&this.tokenExchangeConfig?.refreshUrl)try{const r=await fetch(this.tokenExchangeConfig.refreshUrl,{method:"POST",credentials:"include"});if(!r.ok)throw this.tokenDeliveryManager.setSessionInvalid(),new Error("BFF token refresh failed");const s=await r.json();return this.tokenDeliveryManager.setSessionValid(),s.id_token&&this.storageManager.setIdToken(s.id_token),this.subscribeStore.notify(a.Refresh,{tokens:s,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,s}catch(r){this.tokenDeliveryManager.setSessionInvalid();const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r};throw this.subscribeStore.notify(a.Error,s),r}if(this.tokenDeliveryManager.isCookieMode())try{const r=await this.authApi.refreshToken("",this.scopes);return this.tokenDeliveryManager.setSessionValid(),await this.processAuthResponse(r,this.scopes),this.subscribeStore.notify(a.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,r}catch(r){this.tokenDeliveryManager.setSessionInvalid();const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r,code:r instanceof l?r.id:void 0};throw this.subscribeStore.notify(a.Error,s),r}const e=this.storageManager.getTokens();if(e){if(!e?.refresh_token){const r=new Error("No refresh token found"),s={message:"No refresh token found",originalError:r};throw this.subscribeStore.notify(a.Error,s),r}}else{const r=new Error("No tokens found"),s={message:"No tokens found",originalError:r};throw this.subscribeStore.notify(a.Error,s),r}const t=e?.scopes??this.scopes;try{const r=await this.authApi.refreshToken(e?.refresh_token??"",t,e?.access_token);return r.scopes=t,this.storageManager.saveTokens(r),this.tokenCacheService.setTokensCache(r),this.subscribeStore.notify(a.Refresh,{tokens:r,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!1}),this.tokenCacheService.isRefreshing=!1,this.tokenCacheService.tokenExpiredFlag=!1,this.tokenCacheService.startTokenCheck(),r}catch(r){const s={message:r instanceof Error?r.message:"Token refresh failed",originalError:r,code:r instanceof l?r.id:void 0,details:U.isAxiosError(r)&&r.response?{status:r.response.status,data:r.response.data}:void 0};this.subscribeStore.notify(a.Error,s);const o=U.isAxiosError(r)&&r.response?.status&&r.response.status>=400&&r.response.status<500;throw o&&(this.tokenCacheService.tokenExpiredFlag=!0,this.tokenCacheService.setTokensCache(void 0),this.storageManager.deleteTokens(),this.subscribeStore.notify(a.SessionExpired,{reason:"refresh_failed"})),r instanceof l?r:o?new Error(`Getting unknown error message from server with code:${r.response?.status}`):r}}async sendPasswordResetEmail(e){try{return await this.authApi.sendPasswordResetEmail(e)}catch(t){const r={message:t instanceof Error?t.message:"Failed to send password reset email",originalError:t,code:t instanceof l?t.id:void 0};throw this.subscribeStore.notify(a.Error,r),t}}async resetPassword(e,t){this.subscribeStore.notify(a.SignInStart,{});const s=new URLSearchParams(this.platform.getCurrentUrl()?.search??"").get("token")??void 0,o=t??this.scopes;try{const n=await this.authApi.resetPassword(e,o,s);return await this.processAuthResponse(n,o),this.subscribeStore.notify(a.SignIn,{tokens:n,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),n}catch(n){const h={message:n instanceof Error?n.message:"Password reset failed",originalError:n,code:n instanceof l?n.id:void 0};throw this.subscribeStore.notify(a.Error,h),n}}async passkeyRegister(e){if(!this.platform.passkeys)throw new Error("Passkeys are not supported on this platform");this.subscribeStore.notify(a.RegisterStart,{});const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();e.scopes=e.scopes??this.scopes,e.create_tenant=this.createTenantForNewUser;try{const{challenge_id:s,publicKey:o}=await this.authApi.passkeyRegisterStart(e,t,r,!this.appId);o.user.id=this.platform.btoa(o.user.id);const n=await this.platform.passkeys.startRegistration(o);if(!n)throw new Error("Passkey registration was not completed");const h=await this.authApi.passkeyRegisterComplete(n,t,s,!this.appId);return await this.processAuthResponse(h,e.scopes),this.subscribeStore.notify(a.Register,{tokens:h,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),h}catch(s){const o={message:s instanceof Error?s.message:"Passkey registration failed",originalError:s,code:s instanceof l?s.id:void 0};throw this.subscribeStore.notify(a.Error,o),s}}async passkeyAuthenticate(e){if(!this.platform.passkeys)throw new Error("Passkeys are not supported on this platform");this.subscribeStore.notify(a.SignInStart,{});const t=this.deviceService.getDeviceId(),r=this.platform.getDeviceType();e.scopes=e.scopes??this.scopes;try{const{challenge_id:s,publicKey:o}=await this.authApi.passkeyAuthenticateStart(e,t,r,!this.appId),n=await this.platform.passkeys.startAuthentication(o);if(!n)throw new Error("Passkey authentication was not completed");const h=await this.authApi.passkeyAuthenticateComplete(n,t,s,!this.appId);return"access_token"in h&&(await this.processAuthResponse(h,e.scopes),this.subscribeStore.notify(a.SignIn,{tokens:h,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck()),h}catch(s){const o={message:s instanceof Error?s.message:"Passkey authentication failed",originalError:s,code:s instanceof l?s.id:void 0};throw this.subscribeStore.notify(a.Error,o),s}}createFederatedAuthUrl(e){const t=`/auth/federated/start/${e.provider}`;if(!this.appId)throw new Error("AppId is required for federated auth");const s={scopes:(e.scopes??this.scopes).join(" "),redirect_url:e.redirect_url??this.platform.getCurrentUrl()?.origin??"",appId:this.appId,...e.invite_token?{invite_token:e.invite_token}:{},...e.create_tenant?{create_tenant:e.create_tenant.toString()}:{},...e.device?{device:e.device}:{}},o=new URL(t,this.url),n=new URLSearchParams(s);return o.search=n.toString(),o.toString()}async federatedAuthWithPopup(e){this.subscribeStore.notify(a.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r});try{const o=await this.platform.openAuthUrl(s,{mode:"popup",expectedReturnOrigin:this.platform.getCurrentUrl()?.origin??""}),n=new URLSearchParams(o.callbackSearch),h=n.get("access_token")||"",d=n.get("refresh_token")||"",u=n.get("id_token")||"",g={access_token:h,refresh_token:d||void 0,id_token:u||void 0,scopes:t};await this.processAuthResponse(g,t),this.subscribeStore.notify(a.SignIn,{tokens:g,parsedTokens:this.tokenCacheService.getParsedTokens()}),this.platform.navigateTo(this.platform.getCurrentUrl()?.origin??"")}catch(o){const n={message:o instanceof Error?o.message:"Authentication failed",code:o instanceof G?"POPUP_CLOSED":"AUTH_FAILED",originalError:o};this.subscribeStore.notify(a.Error,n)}}federatedAuthWithRedirect(e){this.subscribeStore.notify(a.SignInStart,{provider:e.provider});const t=e.scopes??this.scopes,r=this.deviceService.getDeviceId(),s=this.createFederatedAuthUrl({...e,scopes:t,device:r});this.platform.navigateTo(s)}authRedirectUrl(e={}){try{const{url:t,redirectUrl:r,scopes:s,appId:o}=e??{},n=new URL(t??this.url);n.pathname=(n.pathname.endsWith("/")?n.pathname:n.pathname+"/")+"web";const h=s??this.scopes,d={appId:o??this.appId??"",redirectto:r??this.platform.getCurrentUrl()?.href??"",scopes:h.join(",")},u=new URLSearchParams(d);return n.search=u.toString(),n.toString()}catch(t){const r={message:t instanceof Error?t.message:"Failed to create auth redirect URL",originalError:t};throw this.subscribeStore.notify(a.Error,r),t}}authRedirect(e={}){try{this.platform.navigateTo(this.authRedirectUrl(e))}catch(t){const r={message:t instanceof Error?t.message:"Failed to redirect to auth page",originalError:t};throw this.subscribeStore.notify(a.Error,r),t}}isAuthenticated(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){const t=!!e?.id_token||!!this.storageManager.getIdToken(),r=this.tokenDeliveryManager.isSessionValid(),s=this.tokenDeliveryManager.isSessionUnknown();return t&&(r||s)}return!e||!e.access_token?!1:!y(e.access_token)||e.refresh_token!==void 0&&!y(e.refresh_token)}catch(t){const r={message:t instanceof Error?t.message:"Failed to check authentication status",originalError:t};return this.subscribeStore.notify(a.Error,r),!1}}async submitSessionCheck(e=!1){let t,r;try{t=await this.getTokens(e),r=this.tokenCacheService.getParsedTokens()}catch(s){const o={message:s instanceof Error||s instanceof l?s.message:"Session check failed",originalError:s};this.subscribeStore.notify(a.Error,o),t=void 0}return t&&this.sessionCallbacks.createSession&&await this.sessionCallbacks.createSession({tokens:t,parsedTokens:r}),!t&&this.sessionCallbacks.expiredSession&&await this.sessionCallbacks.expiredSession(),t}async getTokens(e){try{if(this.tokenDeliveryManager.isCookieMode()||this.tokenDeliveryManager.isBFFMode()){const s=this.storageManager.getTokens();return s?.id_token?this.tokenDeliveryManager.isSessionInvalid()&&e?await this.refreshToken():s:void 0}const t=this.storageManager.getTokens();if(!t||!t.access_token)return;const r=v(t.access_token);return y(r)?e?await this.refreshToken():void 0:t}catch(t){const r={message:t instanceof Error?t.message:"Failed to get tokens",originalError:t};this.subscribeStore.notify(a.Error,r);return}}}class Se{constructor(e){this.invitationApi=e}requestInviteLink(e){return this.invitationApi.requestInviteLink(e)}getInvitations(e){return this.invitationApi.getInvitations(e)}deleteInvitation(e){return this.invitationApi.deleteInvitation(e)}resendInvitation(e){return this.invitationApi.resendInvitation(e)}getInvitationLink(e){return this.invitationApi.getInvitationLink(e)}}class Xe{error(e,...t){console.error(e,...t)}warn(e,...t){console.warn(e,...t)}info(e,...t){console.info(e,...t)}debug(e,...t){console.debug(e,...t)}}function We(){return new Xe}class we{constructor(e){this.data=this.normalize(e)}normalize(e){const t=new Map,r=new Map,s=new Map,o=[];return e.groups?.forEach(n=>{r.set(n.id,{id:n.id,name:n.name,default:n.default??!1,updated_at:n.updated_at,created_at:n.created_at})}),e.roles?.forEach(n=>{s.set(n.id,{id:n.id,tenant_id:n.tenant_id,name:n.name})}),e.users_in_groups?.forEach(n=>{const h=n.user;h&&!t.has(h.id)&&t.set(h.id,{id:h.id,name:h.name??null,email:h.email??null,phone:h.phone??null}),h&&n.group_id&&r.has(n.group_id)&&o.push({userId:h.id,groupId:n.group_id,roleIds:n.roles?.map(d=>d.id)??[]})}),{tenant_id:e.tenant_id,tenant_name:e.tenant_name,users:Array.from(t.values()),groups:Array.from(r.values()),roles:Array.from(s.values()),memberships:o,usersById:t,groupsById:r,rolesById:s}}getUsersInGroup(e){return this.data.memberships.filter(t=>t.groupId===e).map(t=>this.data.usersById.get(t.userId)).filter(t=>t!==void 0)}getGroupsForUser(e){return this.data.memberships.filter(t=>t.userId===e).map(t=>this.data.groupsById.get(t.groupId)).filter(t=>t!==void 0)}getUserRolesInGroup(e,t){const r=this.data.memberships.find(s=>s.userId===e&&s.groupId===t);return r?r.roleIds.map(s=>this.data.rolesById.get(s)).filter(s=>s!==void 0):[]}getData(){return this.data}}class Te{constructor(e,t,r){this.tenantApi=e,this.scopes=t,this.logger=r||We()}handlePassflowError(e,t){if(U.isAxiosError(e)&&e.response?.data){const r=e.response.data;if(typeof r=="object"&&r!==null&&"error"in r&&typeof r.error=="object"&&r.error!==null){const s=r.error;throw this.logger.error(`${t}: ${s.id} - ${s.message} (Status: ${s.status})`),new Error(`Passflow API Error: ${s.id} - ${s.message} (Status: ${s.status})`)}}throw this.logger.error(`${t}:`,e),e instanceof Error?e:new Error(String(e))}async joinInvitation(e,t){try{const r=t??this.scopes;return await this.tenantApi.joinInvitation(e,r)}catch(r){this.handlePassflowError(r,"Join invitation failed")}}async createTenant(e){try{return await this.tenantApi.createTenant(e)}catch(t){this.handlePassflowError(t,"Tenant creation failed")}}async getTenantDetails(e){try{return await this.tenantApi.getTenantDetails(e)}catch(t){this.handlePassflowError(t,`Get tenant details failed for tenant ID ${e}`)}}async getTenantUserMembership(e){try{const t=await this.tenantApi.getTenantDetails(e);return new we(t)}catch(t){this.handlePassflowError(t,`Get tenant user membership failed for tenant ID ${e}`)}}async updateTenant(e,t){try{return await this.tenantApi.updateTenant(e,t)}catch(r){this.handlePassflowError(r,`Update tenant failed for tenant ID ${e}`)}}async deleteTenant(e){try{return await this.tenantApi.deleteTenant(e)}catch(t){this.handlePassflowError(t,`Delete tenant failed for tenant ID ${e}`)}}async getUserTenantMembership(){try{return await this.tenantApi.getUserTenantMembership()}catch(e){this.handlePassflowError(e,"Get user tenant memberships failed")}}async createGroup(e,t){try{return await this.tenantApi.createGroup(e,t)}catch(r){this.handlePassflowError(r,`Group creation failed for tenant ID ${e}`)}}async getGroupInfo(e,t){try{return await this.tenantApi.getGroupInfo(e,t)}catch(r){this.handlePassflowError(r,`Get group info failed for tenant ID ${e}, group ID ${t}`)}}async updateGroup(e,t,r){try{return await this.tenantApi.updateGroup(e,t,r)}catch(s){this.handlePassflowError(s,`Update group failed for tenant ID ${e}, group ID ${t}`)}}async deleteGroup(e,t){try{return await this.tenantApi.deleteGroup(e,t)}catch(r){this.handlePassflowError(r,`Delete group failed for tenant ID ${e}, group ID ${t}`)}}async addUserToGroup(e,t,r,s){try{return await this.tenantApi.addUserToGroup(e,t,r,s)}catch(o){this.handlePassflowError(o,`Add user to group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async removeUserRolesFromGroup(e,t,r,s){try{return await this.tenantApi.removeUserRolesFromGroup(e,t,r,s)}catch(o){this.handlePassflowError(o,`Remove user roles from group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async changeUserRoles(e,t,r,s){try{return await this.tenantApi.changeUserRoles(e,t,r,s)}catch(o){this.handlePassflowError(o,`Change user roles failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async deleteUserFromGroup(e,t,r){try{return await this.tenantApi.deleteUserFromGroup(e,t,r)}catch(s){this.handlePassflowError(s,`Delete user from group failed for tenant ID ${e}, group ID ${t}, user ID ${r}`)}}async getRolesForTenant(e){try{return await this.tenantApi.getRolesForTenant(e)}catch(t){this.handlePassflowError(t,`Get roles for tenant failed for tenant ID ${e}`)}}async createRoleForTenant(e,t){try{return await this.tenantApi.createRoleForTenant(e,t)}catch(r){this.handlePassflowError(r,`Create role for tenant failed for tenant ID ${e}`)}}async updateRole(e,t,r){try{return await this.tenantApi.updateRole(e,t,r)}catch(s){this.handlePassflowError(s,`Update role failed for tenant ID ${e}, role ID ${t}`)}}async deleteRole(e,t){try{return await this.tenantApi.deleteRole(e,t)}catch(r){this.handlePassflowError(r,`Delete role failed for tenant ID ${e}, role ID ${t}`)}}async deleteUserFromTenant(e,t){try{return await this.tenantApi.deleteUserFromTenant(e,t)}catch(r){this.handlePassflowError(r,`Delete user from tenant failed for tenant ID ${e}, user ID ${t}`)}}async getGroupInvitations(e,t,r,s){try{return await this.tenantApi.getGroupInvitations(e,t,r,s)}catch(o){this.handlePassflowError(o,`Get group invitations failed for tenant ID ${e}, group ID ${t}`)}}async getTenantInvitations(e,t,r){try{return await this.tenantApi.getTenantInvitations(e,t,r)}catch(s){this.handlePassflowError(s,`Get tenant invitations failed for tenant ID ${e}`)}}async invalidateInviteById(e,t,r){try{return await this.tenantApi.invalidateInviteById(e,t,r)}catch(s){this.handlePassflowError(s,`Invalidate invite by ID failed for tenant ID ${e}, group ID ${t}, invite ID ${r}`)}}async invalidateInviteByEmail(e,t,r){try{return await this.tenantApi.invalidateInviteByEmail(e,t,r)}catch(s){this.handlePassflowError(s,`Invalidate invite by email failed for tenant ID ${e}, group ID ${t}, email ${r}`)}}}class Ee{constructor(e,t,r,s=A){this.storageManager=e,this.authApi=t,this.subscribeStore=r,this.platform=s,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()}initialize(){try{const e=this.storageManager.getTokens();if(!e)return;if(!e.access_token){this.setTokensCache(e),this.startTokenCheck();return}const t=v(e.access_token);y(t)?(this.tokenExpiredFlag=!0,this.stopTokenCheck(),this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!0})):(this.setTokensCache(e),this.startTokenCheck())}catch(e){const t={message:e instanceof Error?e.message:"Failed to get tokens",originalError:e};this.subscribeStore.notify(a.Error,t),this.setTokensCache(void 0)}}async refreshTokensCache(e){if(!this.isRefreshing)try{this.isRefreshing=!0,this.subscribeStore.notify(a.RefreshStart,{});const t=await this.authApi.refreshToken(e?.refresh_token??"",e.scopes??[],e.access_token);this.setTokensCache(t),this.subscribeStore.notify(a.Refresh,{tokens:t,parsedTokens:this.getParsedTokens()}),this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!1}),this.tokenExpiredFlag=!1,this.startTokenCheck()}catch(t){const r={message:t instanceof Error?t.message:"Failed to get tokens",originalError:t};this.subscribeStore.notify(a.Error,r),this.tokenExpiredFlag=!0,this.setTokensCache(void 0),this.stopTokenCheck(),this.storageManager.deleteTokens(),this.subscribeStore.notify(a.SessionExpired,{reason:"refresh_failed"})}finally{this.isRefreshing=!1}}startTokenCheck(){this.checkInterval&&clearInterval(this.checkInterval),!this.tokenExpiredFlag&&(this.setupLifecycleListeners(),this.checkInterval=setInterval(()=>{this.platform.isInForeground()&&(this.isRefreshing||this.tokenExpiredFlag||this.isExpired()&&!this.tokenExpiredFlag&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck()))},this.CHECK_INTERVAL))}setupLifecycleListeners(){this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null),this.unsubscribeForeground=this.platform.onForeground(()=>{this.checkInterval&&!this.isRefreshing&&!this.tokenExpiredFlag&&this.isExpired()&&(this.tokenExpiredFlag=!0,this.subscribeStore.notify(a.TokenCacheExpired,{isExpired:!0}),this.stopTokenCheck())}),this.unsubscribeUnload||(this.unsubscribeUnload=this.platform.onBeforeUnload(()=>{this.destroy()}))}stopTokenCheck(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null),this.unsubscribeForeground&&(this.unsubscribeForeground(),this.unsubscribeForeground=null)}destroy(){this.stopTokenCheck(),this.unsubscribeUnload&&(this.unsubscribeUnload(),this.unsubscribeUnload=null)}setTokensCache(e){this.tokensCache=e,e?this.parsedTokensCache={access_token:e.access_token?v(e.access_token):void 0,id_token:e.id_token?v(e.id_token):void 0,refresh_token:e.refresh_token?v(e.refresh_token):void 0,scopes:e.scopes}:this.parsedTokensCache=void 0}getTokens(){return this.tokensCache}async getTokensWithRefresh(){try{if(!this.tokensCache)return this.tokensCache;if(!this.tokensCache.access_token)return this.tokensCache;const e=v(this.tokensCache.access_token);return y(e)&&!this.tokenExpiredFlag?(await this.refreshTokensCache(this.tokensCache),this.tokensCache):this.tokensCache}catch(e){const t={message:e instanceof Error?e.message:"Failed to get tokens",originalError:e};this.subscribeStore.notify(a.Error,t);return}}getParsedTokens(){return this.parsedTokensCache}isExpired(){if(!this.tokensCache)return!0;if(!this.tokensCache.access_token)return!1;const e=v(this.tokensCache.access_token);return y(e)}}class _e{constructor(e,t){this.twoFactorApi=e,this.subscribeStore=t,this.PARTIAL_AUTH_TIMEOUT_MS=300*1e3,this.SESSION_STORAGE_KEY="passflow_2fa_challenge",this.totpDigits=6;const r={onAuthChange:(s,o)=>{if(s===a.TwoFactorRequired){const n=o;this.setPartialAuthState(n.email,n.challengeId,n.tfaToken)}}};this.subscribeStore.subscribe(r,[a.TwoFactorRequired])}emitErrorAndThrow(e,t){const r=e,s={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:r?.id||void 0};throw this.subscribeStore.notify(a.Error,s),e}async getStatus(){try{const e=await this.twoFactorApi.getStatus();return e.totp_digits&&(this.totpDigits=e.totp_digits),e}catch(e){this.emitErrorAndThrow(e,"Get 2FA status")}}async beginSetup(){try{const e=await this.twoFactorApi.beginSetup();return e.totp_digits&&(this.totpDigits=e.totp_digits),this.subscribeStore.notify(a.TwoFactorSetupStarted,{secret:e.secret}),e}catch(e){this.emitErrorAndThrow(e,"Begin 2FA setup")}}async confirmSetup(e){if(!R(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.confirmSetup({code:e});return this.subscribeStore.notify(a.TwoFactorEnabled,{recoveryCodes:t.recovery_codes,clearRecoveryCodes:()=>{t.recovery_codes.length=0}}),t}catch(t){this.emitErrorAndThrow(t,"Confirm 2FA setup")}}async verify(e){if(!R(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw new Error("2FA verification expired or not required. User must sign in first.");if(!this.partialAuthState?.tfaToken)throw new Error("No TFA token found. User must sign in first.");try{const t=await this.twoFactorApi.verify({code:e,tfa_token:this.partialAuthState.tfaToken});return this.clearPartialAuthState(),this.subscribeStore.notify(a.TwoFactorVerified,{tokens:t}),t}catch(t){this.emitErrorAndThrow(t,"Verify 2FA code")}}async useRecoveryCode(e){try{const t=ze(e);if(!t)throw new Error("Invalid recovery code format. Expected format: XXXX-XXXX or XXXXXXXX (alphanumeric).");if(this.recoverPartialAuthState(),!this.isVerificationRequired())throw new Error("2FA verification expired or not required. User must sign in first.");if(!this.partialAuthState?.tfaToken)throw new Error("No TFA token found. User must sign in first.");const r=await this.twoFactorApi.useRecoveryCode({recovery_code:t,tfa_token:this.partialAuthState.tfaToken});return this.clearPartialAuthState(),r.remaining_recovery_codes===0?this.subscribeStore.notify(a.TwoFactorRecoveryCodesExhausted,{tokens:r}):r.remaining_recovery_codes<=2&&this.subscribeStore.notify(a.TwoFactorRecoveryCodesLow,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(a.TwoFactorRecoveryUsed,{tokens:r,remainingCodes:r.remaining_recovery_codes}),this.subscribeStore.notify(a.TwoFactorVerified,{tokens:r}),r}catch(t){this.emitErrorAndThrow(t,"Use recovery code")}}async disable(e){if(!R(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.disable({code:e});return this.subscribeStore.notify(a.TwoFactorDisabled,{}),t}catch(t){this.emitErrorAndThrow(t,"Disable 2FA")}}async regenerateRecoveryCodes(e){if(!R(e,this.totpDigits))throw new Error(`Invalid TOTP code format. Code must be exactly ${this.totpDigits} digits.`);try{const t=await this.twoFactorApi.regenerateRecoveryCodes({code:e}),r=[...t.recovery_codes];return t.recovery_codes=[],t.recovery_codes=r,t}catch(t){this.emitErrorAndThrow(t,"Regenerate recovery codes")}}isVerificationRequired(){return this.recoverPartialAuthState(),this.partialAuthState?Date.now()>this.partialAuthState.expiresAt?(this.clearPartialAuthState(),!1):!0:!1}setPartialAuthState(e,t,r){if(this.partialAuthState={email:e,challengeId:t,tfaToken:r,timestamp:Date.now(),expiresAt:Date.now()+this.PARTIAL_AUTH_TIMEOUT_MS},typeof sessionStorage<"u")try{sessionStorage.setItem(this.SESSION_STORAGE_KEY,JSON.stringify(this.partialAuthState))}catch{}}clearPartialAuthState(){if(this.partialAuthState=void 0,typeof sessionStorage<"u")try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}recoverPartialAuthState(){if(!this.partialAuthState&&!(typeof sessionStorage>"u"))try{const e=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e)return;const t=JSON.parse(e);Date.now()<t.expiresAt?this.partialAuthState=t:sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{try{sessionStorage.removeItem(this.SESSION_STORAGE_KEY)}catch{}}}async validateTwoFactorSetupMagicLink(e){const t=await this.twoFactorApi.validateTwoFactorSetupMagicLink(e);return t.success&&t.sessionToken&&t.userId?(this.magicLinkSession={sessionToken:t.sessionToken,userId:t.userId,appId:t.appId,scope:"2fa_setup",timestamp:Date.now(),expiresAt:Date.now()+(t.expiresIn||3600)*1e3},this.subscribeStore.notify(a.TwoFactorSetupMagicLinkValidated,{userId:t.userId,appId:t.appId,expiresIn:t.expiresIn||3600,sessionToken:t.sessionToken})):t.error&&this.subscribeStore.notify(a.TwoFactorSetupMagicLinkFailed,{error:t.error}),t}getMagicLinkSession(){return this.magicLinkSession?Date.now()>this.magicLinkSession.expiresAt?(this.clearMagicLinkSession(),null):this.magicLinkSession:null}clearMagicLinkSession(){this.magicLinkSession=void 0}hasMagicLinkSession(){return this.getMagicLinkSession()!==null}getMagicLinkSessionToken(){return this.getMagicLinkSession()?.sessionToken||null}getTotpDigits(){return this.totpDigits}async getAvailableMethods(){try{return await this.twoFactorApi.getAvailableMethods()}catch(e){this.emitErrorAndThrow(e,"Get available 2FA methods")}}async getRegisteredMethods(){try{return await this.twoFactorApi.getRegisteredMethods()}catch(e){this.emitErrorAndThrow(e,"Get registered 2FA methods")}}async startMethodSetup(e,t){try{const r=await this.twoFactorApi.startMethodSetup(e,t);return this.subscribeStore.notify(a.TwoFactorSetupStarted,{secret:"",method:e}),r}catch(r){this.emitErrorAndThrow(r,"Start 2FA method setup")}}async completeMethodSetup(e,t){try{const r=await this.twoFactorApi.completeMethodSetup(e,t);return this.subscribeStore.notify(a.TwoFactorEnabled,{recoveryCodes:[],clearRecoveryCodes:()=>{}}),r}catch(r){this.emitErrorAndThrow(r,"Complete 2FA method setup")}}async removeMethod(e){try{await this.twoFactorApi.removeMethod(e)}catch(t){this.emitErrorAndThrow(t,"Remove 2FA method")}}async requestChallenge(e){try{const t=await this.twoFactorApi.requestChallenge(e);return this.subscribeStore.notify(a.TwoFactorChallengeReceived,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(t){this.emitErrorAndThrow(t,"Request 2FA challenge")}}async verifyV2(e){try{const t=await this.twoFactorApi.verifyV2(e);return t.success&&(this.subscribeStore.notify(a.TwoFactorVerified,{tokens:{access_token:t.access_token,refresh_token:t.refresh_token}}),t.device_trusted&&this.subscribeStore.notify(a.TwoFactorDeviceTrusted,{})),t}catch(t){this.emitErrorAndThrow(t,"Verify 2FA challenge")}}async switchToAlternative(e){try{const t=await this.twoFactorApi.switchToAlternative(e);return this.subscribeStore.notify(a.TwoFactorMethodSwitched,{challengeId:t.challenge_id,method:t.method,alternativeMethods:t.alternative_methods}),t}catch(t){this.emitErrorAndThrow(t,"Switch to alternative 2FA method")}}async getTrustedDevices(){try{return await this.twoFactorApi.getTrustedDevices()}catch(e){this.emitErrorAndThrow(e,"Get trusted devices")}}async revokeTrustedDevice(e){try{await this.twoFactorApi.revokeTrustedDevice(e)}catch(t){this.emitErrorAndThrow(t,"Revoke trusted device")}}}class Ie{constructor(e,t,r=A){this.userAPI=e,this.deviceService=t,this.platform=r}getUserPasskeys(){return this.userAPI.getUserPasskeys()}renameUserPasskey(e,t){return this.userAPI.renameUserPasskey(e,t)}deleteUserPasskey(e){return this.userAPI.deleteUserPasskey(e)}async addUserPasskey({relyingPartyId:e,passkeyUsername:t,passkeyDisplayName:r}={}){if(!this.platform.passkeys)throw new Error("Passkeys are not supported on this platform");const s=this.deviceService.getDeviceId(),o=this.platform.getDeviceType(),{challenge_id:n,publicKey:h}=await this.userAPI.addUserPasskeyStart({relyingPartyId:(e||this.platform.getCurrentUrl()?.hostname)??"",deviceId:s,os:o,passkeyDisplayName:r,passkeyUsername:t});h.user.id=this.platform.btoa(h.user.id);const d=await this.platform.passkeys.startRegistration(h);if(!d)throw new Error("Passkey registration was not completed");return await this.userAPI.addUserPasskeyComplete(d,s,n)}}const q=class q{constructor(e){this.doRefreshTokens=!1,this.session=async({createSession:o,expiredSession:n,doRefresh:h=!1})=>{this.createSessionCallback=o,this.expiredSessionCallback=n,this.doRefreshTokens=h,await this.submitSessionCheck()};const{url:t,appId:r,scopes:s}=e;this.url=t||L,this.appId=r,this.platform=e.platform??A,this.storageManager=new V({prefix:e.keyStoragePrefix??"",storage:this.platform.storage}),this.deviceService=new ie(this.storageManager),this.authApi=new ue(e,this.storageManager,this.deviceService),this.appApi=new de(e,this.storageManager,this.deviceService),this.userApi=new ke(e,this.storageManager,this.deviceService),this.settingApi=new pe(e,this.storageManager,this.deviceService),this.tenantApi=new ge(e,this.storageManager,this.deviceService),this.invitationApi=new le(e,this.storageManager,this.deviceService),this.twoFactorApi=new fe(e,this.storageManager,this.deviceService),this.subscribeStore=new je,this.tokenCacheService=new Ee(this.storageManager,this.authApi,this.subscribeStore,this.platform),this.scopes=s??X,this.createTenantForNewUser=e.createTenantForNewUser??!1,this.authService=new ye(this.authApi,this.deviceService,this.storageManager,this.subscribeStore,this.tokenCacheService,this.scopes,this.createTenantForNewUser,this.url,{createSession:this.createSessionCallback,expiredSession:this.expiredSessionCallback},this.appId??"",e.tokenExchange,this.platform),this.userService=new Ie(this.userApi,this.deviceService,this.platform),this.tenantService=new Te(this.tenantApi,this.scopes),this.tenant=this.tenantService,this.invitationService=new Se(this.invitationApi),this.twoFactorService=new _e(this.twoFactorApi,this.subscribeStore),this.twoFactor=this.twoFactorService,e.parseQueryParams&&this.checkAndSetTokens(),this.setTokensToCacheFromLocalStorage()}get origin(){return this.platform.getCurrentUrl()?.origin??""}setAppId(e){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.authService}async submitSessionCheck(){let e,t;try{e=await this.authService.getTokens(this.doRefreshTokens),t=this.tokenCacheService.getParsedTokens()}catch(r){const s={message:r instanceof Error||r instanceof l?r.message:"Session check failed",originalError:r};this.subscribeStore.notify(a.Error,s),e=void 0}e&&this.createSessionCallback&&await this.createSessionCallback({tokens:e,parsedTokens:t}),!e&&this.expiredSessionCallback&&await this.expiredSessionCallback()}subscribe(e,t){this.subscribeStore.subscribe(e,t),this.tokenCacheService.initialize()}unsubscribe(e,t){this.subscribeStore.unsubscribe(e,t)}handleTokensRedirect(){return this.checkAndSetTokens()}checkAndSetTokens(){const e=this.platform.getCurrentUrl();let t=new URLSearchParams(e?.search??""),r=!1;if(!t.get("access_token")&&e?.hash){const u=new URLSearchParams(e.hash.substring(1));u.get("access_token")&&(t=u,r=!0)}const s=t.get("access_token"),o=t.get("refresh_token"),n=t.get("id_token"),h=t.get("scopes")?.split(",")??this.scopes;let d;if(s){if(!M(s)){const u={message:"Invalid access token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(a.Error,u),this.cleanupUrlParams(r,e);return}if(o&&!M(o)){const u={message:"Invalid refresh token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(a.Error,u),this.cleanupUrlParams(r,e);return}if(n&&!M(n)){const u={message:"Invalid ID token format received",code:"INVALID_TOKEN_FORMAT"};this.subscribeStore.notify(a.Error,u),this.cleanupUrlParams(r,e);return}return d={access_token:s,refresh_token:o??void 0,id_token:n??void 0,scopes:h},this.storageManager.clearDeliveryMode(),this.storageManager.saveTokens(d),this.tokenCacheService.setTokensCache(d),this.subscribeStore.notify(a.SignIn,{tokens:d,parsedTokens:this.getParsedTokens()}),this.submitSessionCheck(),this.cleanupUrlParams(r,e),this.error=void 0,d}else this.error=this.checkErrorsFromURL()}checkErrorsFromURL(){const t=new URLSearchParams(this.platform.getCurrentUrl()?.search??"").get("error");if(t){const r=ve(t);return new Error(r)}}cleanupUrlParams(e=!1,t=null){const r=t??this.platform.getCurrentUrl();if(r)if(e)this.platform.replaceUrl(r.pathname+r.search);else{const s=new URLSearchParams(r.search);s.delete("access_token"),s.delete("refresh_token"),s.delete("id_token"),s.delete("client_challenge"),s.size>0?this.platform.replaceUrl(`${r.pathname}?${s.toString()}`):this.platform.replaceUrl(r.pathname)}}setTokensToCacheFromLocalStorage(){let e=this.storageManager.getTokens();if(!e?.access_token&&this.storageManager.getDeliveryMode()){if(e?.id_token&&this.storageManager.hasCookieModeIdToken()){this.tokenCacheService.setTokensCache(e);return}if(this.storageManager.hasJsonModeTokens())this.storageManager.clearDeliveryMode(),e=this.storageManager.getTokens();else{this.storageManager.deleteTokens();return}}e&&this.tokenCacheService.setTokensCache(e)}getCachedTokens(){return this.tokenCacheService.getTokens()}getTokensWithRefresh(){return this.tokenCacheService.getTokensWithRefresh()}getParsedTokens(){return this.tokenCacheService.getParsedTokens()}areTokensExpired(){return this.tokenCacheService.isExpired()}isAuthenticated(){const e=this.storageManager.getTokens();if(!e||!e.access_token)return!1;const t=this.tokenCacheService.getParsedTokens();return t?this.authService.isAuthenticated(t):!1}async signIn(e){return await this.authService.signIn(e)}async signUp(e){return await this.authService.signUp(e)}passwordlessSignIn(e){return this.authService.passwordlessSignIn(e)}async passwordlessSignInComplete(e){return await this.authService.passwordlessSignInComplete(e)}handleError(e,t){const r={message:e instanceof Error?e.message:`${t} failed`,originalError:e,code:e instanceof l?e.id:void 0};throw this.subscribeStore.notify(a.Error,r),e}async logOut(){try{await this.authService.logOut(),this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.twoFactorService.clearPartialAuthState(),await this.submitSessionCheck(),this.subscribeStore.notify(a.SignOut,{})}catch(e){this.handleError(e,"Log out")}}federatedAuthWithPopup(e){this.authService.federatedAuthWithPopup(e)}federatedAuthWithRedirect(e){this.authService.federatedAuthWithRedirect(e)}reset(e){if(this.storageManager.deleteTokens(),this.tokenCacheService.setTokensCache(void 0),this.subscribeStore.notify(a.SignOut,{}),e){this.error=new Error(e);const t={message:e,code:"RESET_ERROR"};throw this.subscribeStore.notify(a.Error,t),this.error}}async refreshToken(){if(!this.tokenCacheService.parsedTokensCache?.refresh_token)throw new Error("No refresh token found");try{return await this.authService.refreshToken()}catch(e){throw e instanceof l||this.subscribeStore.notify(a.Error,{message:"Failed to refresh token",originalError:e}),e}}sendPasswordResetEmail(e){return this.authService.sendPasswordResetEmail(e)}async resetPassword(e,t){return await this.authService.resetPassword(e,t)}async getAppSettings(){try{return await this.appApi.getAppSettings()}catch(e){this.handleError(e,"Get app settings")}}async getSettingsAll(){try{return await this.settingApi.getSettingsAll()}catch(e){this.handleError(e,"Get all settings")}}async getPasswordPolicySettings(){try{return await this.settingApi.getPasswordPolicySettings()}catch(e){this.handleError(e,"Get password policy settings")}}async getPasskeySettings(){try{return await this.settingApi.getPasskeySettings()}catch(e){this.handleError(e,"Get passkey settings")}}async passkeyRegister(e){return await this.authService.passkeyRegister(e)}async passkeyAuthenticate(e){return await this.authService.passkeyAuthenticate(e)}setTokens(e){this.storageManager.saveTokens(e),this.tokenCacheService.setTokensCache(e),this.subscribeStore.notify(a.SignIn,{tokens:e,parsedTokens:this.tokenCacheService.getParsedTokens()})}async getTokens(e=!1){return await this.authService.getTokens(e)}getToken(e){return this.storageManager.getToken(e)}async getUserPasskeys(){try{return await this.userService.getUserPasskeys()}catch(e){this.handleError(e,"Get user passkeys")}}async renameUserPasskey(e,t){try{return await this.userService.renameUserPasskey(e,t)}catch(r){this.handleError(r,"Rename user passkey")}}async deleteUserPasskey(e){try{return await this.userService.deleteUserPasskey(e)}catch(t){this.handleError(t,"Delete user passkey")}}async addUserPasskey(e){try{return await this.userService.addUserPasskey(e)}catch(t){this.handleError(t,"Add user passkey")}}async joinInvitation(e,t){try{const r=await this.tenant.joinInvitation(e,t);return r.scopes=t??this.scopes,this.storageManager.saveTokens(r),this.tokenCacheService.setTokensCache(r),r}catch(r){this.handleError(r,"Join invitation")}}async createTenant(e,t){try{const r=await this.tenant.createTenant(e);return t&&await this.refreshToken(),r}catch(r){this.handleError(r,"Create tenant")}}async requestInviteLink(e){try{return e.send_to_email===void 0&&(e.send_to_email=!0),await this.invitationService.requestInviteLink(e)}catch(t){this.handleError(t,"Request invite link")}}async getInvitations(e){try{return await this.invitationService.getInvitations(e)}catch(t){this.handleError(t,"Get invitations")}}async deleteInvitation(e){try{return await this.invitationService.deleteInvitation(e)}catch(t){this.handleError(t,"Delete invitation")}}async resendInvitation(e){try{return await this.invitationService.resendInvitation(e)}catch(t){this.handleError(t,"Resend invitation")}}async getInvitationLink(e){try{return await this.invitationService.getInvitationLink(e)}catch(t){this.handleError(t,"Get invitation link")}}authRedirectUrl(e={}){return this.authService.authRedirectUrl(e)}authRedirect(e={}){this.authService.authRedirect(e)}getDeliveryMode(){return this.authService.tokenDeliveryManager.getMode()}async restoreSession(){return await this.authService.restoreSession()}async getTwoFactorStatus(){try{return await this.twoFactorService.getStatus()}catch(e){this.handleError(e,"Get 2FA status")}}async beginTwoFactorSetup(){try{return await this.twoFactorService.beginSetup()}catch(e){this.handleError(e,"Begin 2FA setup")}}async confirmTwoFactorSetup(e){try{return await this.twoFactorService.confirmSetup(e)}catch(t){this.handleError(t,"Confirm 2FA setup")}}async verifyTwoFactor(e){try{const t=await this.twoFactorService.verify(e);return this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.subscribeStore.notify(a.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){this.handleError(t,"Verify 2FA")}}async useTwoFactorRecoveryCode(e){try{const t=await this.twoFactorService.useRecoveryCode(e);return this.storageManager.saveTokens(t),this.tokenCacheService.setTokensCache(t),this.subscribeStore.notify(a.SignIn,{tokens:t,parsedTokens:this.tokenCacheService.getParsedTokens()}),await this.submitSessionCheck(),t}catch(t){this.handleError(t,"Use 2FA recovery code")}}async disableTwoFactor(e){try{return await this.twoFactorService.disable(e)}catch(t){this.handleError(t,"Disable 2FA")}}async regenerateTwoFactorRecoveryCodes(e){try{return await this.twoFactorService.regenerateRecoveryCodes(e)}catch(t){this.handleError(t,"Regenerate 2FA recovery codes")}}isTwoFactorVerificationRequired(){return this.twoFactorService.isVerificationRequired()}getTotpDigits(){return this.twoFactorService.getTotpDigits()}async validateTwoFactorSetupMagicLink(e){return await this.twoFactorService.validateTwoFactorSetupMagicLink(e)}getMagicLinkSession(){return this.twoFactorService.getMagicLinkSession()}hasMagicLinkSession(){return this.twoFactorService.hasMagicLinkSession()}clearMagicLinkSession(){this.twoFactorService.clearMagicLinkSession()}};q.version=z;let O=q;class p extends Error{constructor(e){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=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,p)}static fromOAuthError(e,t,r){const s=r?p.parseRateLimitHeaders(r):void 0;return new p({code:e.error,message:e.error_description??p.getDefaultMessage(e.error),status:t,errorUri:e.error_uri,rateLimitInfo:s,headers:r})}static fromError(e,t="server_error"){return new p({code:t,message:e.message||"An unexpected error occurred",status:500,cause:e})}static parseRateLimitHeaders(e){const t=e["x-ratelimit-limit"],r=e["x-ratelimit-remaining"],s=e["x-ratelimit-reset"]||e["retry-after"];if(t&&r&&s)return{limit:parseInt(t,10),remaining:parseInt(r,10),reset:parseInt(s,10)}}static getDefaultMessage(e){return{invalid_request:"The request is missing a required parameter or is otherwise malformed.",invalid_client:"Client authentication failed. Verify your client credentials.",invalid_grant:"The provided authorization grant is invalid or expired.",invalid_scope:"The requested scope is invalid, unknown, or exceeds the allowed scopes.",unauthorized_client:"The client is not authorized to use this grant type.",unsupported_grant_type:"The authorization grant type is not supported.",rate_limit_exceeded:"Too many requests. Please retry after the rate limit window resets.",server_error:"The authorization server encountered an unexpected error.",temporarily_unavailable:"The authorization server is temporarily unavailable. Please try again later."}[e]||"An unknown error occurred."}isRetryable(){return this.code==="server_error"||this.code==="temporarily_unavailable"||this.code==="rate_limit_exceeded"||this.status>=500}getRetryAfter(){if(this.rateLimitInfo?.reset){const e=Math.floor(Date.now()/1e3),t=this.rateLimitInfo.reset-e;return Math.max(t*1e3,1e3)}return 1e3}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,errorUri:this.errorUri,rateLimitInfo:this.rateLimitInfo,timestamp:this.timestamp}}toString(){let e=`M2MError [${this.code}]: ${this.message}`;return this.status&&(e+=` (HTTP ${this.status})`),e}}class $ extends p{constructor(e,t){super({code:"temporarily_unavailable",message:e,status:0,cause:t}),this.name="M2MNetworkError"}}class C extends p{constructor(e,t){super({code:"invalid_request",message:e,status:400,cause:t}),this.name="M2MTokenParseError"}}class D extends p{constructor(e){super({code:"invalid_request",message:e,status:400}),this.name="M2MConfigError"}}const Je={InvalidRequest:"invalid_request",InvalidClient:"invalid_client",InvalidGrant:"invalid_grant",InvalidScope:"invalid_scope",UnauthorizedClient:"unauthorized_client",UnsupportedGrantType:"unsupported_grant_type",RateLimitExceeded:"rate_limit_exceeded",ServerError:"server_error",TemporarilyUnavailable:"temporarily_unavailable"},S={TOKEN_ENDPOINT:"/oauth2/token",TIMEOUT:1e4,RETRIES:3,RETRY_DELAY:1e3,REFRESH_THRESHOLD:30,CONTENT_TYPE:"application/x-www-form-urlencoded"};class Ze{constructor(){this.cache=new Map}get(e){const t=this.cache.get(e);return t?Date.now()>=t.expiresAt?(this.cache.delete(e),Promise.resolve(null)):Promise.resolve(t.token):Promise.resolve(null)}set(e,t,r){return this.cache.set(e,{token:t,expiresAt:Date.now()+r*1e3}),Promise.resolve()}delete(e){return this.cache.delete(e),Promise.resolve()}}const Qe={shouldRetry(i,e){return e>=3?!1:i.code==="server_error"||i.code==="temporarily_unavailable"||i.code==="rate_limit_exceeded"||i.status!==void 0&&i.status>=500},getDelay(i){return Math.pow(2,i-1)*1e3}};class et{constructor(e){if(!e.url)throw new D("M2M client requires a URL");if(!e.clientId)throw new D("M2M client requires a clientId");if(!e.clientSecret)throw new D("M2M client requires a clientSecret");const t=e.url.replace(/\/$/,"");this.config={url:t,clientId:e.clientId,clientSecret:e.clientSecret,scopes:e.scopes,audience:e.audience,autoRefresh:e.autoRefresh??!1,refreshThreshold:e.refreshThreshold??S.REFRESH_THRESHOLD,timeout:e.timeout??S.TIMEOUT,retries:e.retries??S.RETRIES,retryDelay:e.retryDelay??S.RETRY_DELAY,retryStrategy:e.retryStrategy,cache:e.cache,onTokenRequest:e.onTokenRequest,onTokenResponse:e.onTokenResponse,onError:e.onError},this.cache=e.cache??new Ze,this.retryStrategy=e.retryStrategy??Qe,this.tokenEndpoint=`${t}${S.TOKEN_ENDPOINT}`}getCacheKey(e,t){const r=e?.sort().join(",")||"",s=t?.sort().join(",")||"";return`m2m:${this.config.clientId}:${r}:${s}`}async getToken(e){const t=e?.scopes??this.config.scopes,r=e?.audience??this.config.audience,s=this.getCacheKey(t,r);if(!e?.forceRefresh){const o=await this.cache.get(s);if(o&&!this.isTokenExpired(o))return o}return this.requestToken(t,r,s)}async getValidToken(){const e=this.config.scopes,t=this.config.audience,r=this.getCacheKey(e,t),s=await this.cache.get(r);if(s){if(this.config.autoRefresh&&this.isTokenExpired(s,this.config.refreshThreshold))return this.requestToken(e,t,r);if(!this.isTokenExpired(s))return s}return this.requestToken(e,t,r)}async requestToken(e,t,r){const s={grant_type:"client_credentials",client_id:this.config.clientId,client_secret:this.config.clientSecret};e&&e.length>0&&(s.scope=e.join(" ")),t&&t.length>0&&(s.audience=t.join(" ")),this.config.onTokenRequest&&this.config.onTokenRequest({clientId:this.config.clientId,scopes:e??[],audience:t??[],timestamp:new Date().toISOString()});const o=await this.executeWithRetry(()=>this.doTokenRequest(s));return o.issued_at=Math.floor(Date.now()/1e3),r&&await this.cache.set(r,o,o.expires_in),this.config.onTokenResponse&&this.config.onTokenResponse(o),o}async doTokenRequest(e){const t=new URLSearchParams;t.append("grant_type",e.grant_type),t.append("client_id",e.client_id),t.append("client_secret",e.client_secret),e.scope&&t.append("scope",e.scope),e.audience&&t.append("audience",e.audience);const r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout);try{const o=await fetch(this.tokenEndpoint,{method:"POST",headers:{"Content-Type":S.CONTENT_TYPE,Accept:"application/json"},body:t.toString(),signal:r.signal});clearTimeout(s);const n={};o.headers.forEach((d,u)=>{n[u.toLowerCase()]=d});const h=await o.json();if(!o.ok){const d=p.fromOAuthError({error:h.error||"server_error",error_description:h.error_description||h.message,error_uri:h.error_uri},o.status,n);throw this.config.onError&&this.config.onError({error:d.code,error_description:d.message}),d}return h}catch(o){throw clearTimeout(s),o instanceof Error&&o.name==="AbortError"?new $(`Request timed out after ${this.config.timeout}ms`):o instanceof TypeError&&o.message.includes("fetch")?new $(`Network error: ${o.message}`,o):o instanceof p?o:p.fromError(o instanceof Error?o:new Error(String(o)))}}async executeWithRetry(e){let t;for(let r=1;r<=this.config.retries;r++)try{return await e()}catch(s){if(!(s instanceof p))throw s;if(t=s,r<this.config.retries&&this.retryStrategy.shouldRetry({code:s.code,status:s.status},r)){const o=this.retryStrategy.getDelay(r);await this.sleep(o);continue}throw s}throw t??new p({code:"server_error",message:"Request failed after retries"})}sleep(e){return new Promise(t=>setTimeout(t,e))}getCachedToken(){const e=this.cache;if("cache"in e){const t=this.getCacheKey(this.config.scopes,this.config.audience);return e.cache.get(t)?.token??null}return null}isTokenExpired(e,t=0){if(!e)return!0;const r=Math.floor(Date.now()/1e3),o=(e.issued_at??r-e.expires_in)+e.expires_in;return r>=o-t}parseToken(e){try{const t=e.split(".");if(t.length!==3)throw new C("Invalid JWT format: expected 3 parts");const r=t[1];if(!r)throw new C("Invalid JWT format: missing payload");const s=atob(r.replace(/-/g,"+").replace(/_/g,"/")),o=JSON.parse(s);return o.scopes&&typeof o.scopes=="string"?o.scopes=o.scopes.split(" "):o.scopes||(o.scopes=[]),o}catch(t){throw t instanceof C?t:new C(`Failed to parse token: ${t instanceof Error?t.message:"Unknown error"}`)}}clearCache(){const e=this.getCacheKey(this.config.scopes,this.config.audience);this.cache.delete(e)}async revokeToken(){const e=this.getCachedToken();if(!e)return;const t=`${this.config.url}/oauth2/revoke`,r=new URLSearchParams;r.append("token",e.access_token),r.append("client_id",this.config.clientId),r.append("client_secret",this.config.clientSecret);try{const s=await fetch(t,{method:"POST",headers:{"Content-Type":S.CONTENT_TYPE},body:r.toString()});if(!s.ok&&s.status!==200){const o=await s.json().catch(()=>({}));throw p.fromOAuthError({error:o.error||"server_error",error_description:o.error_description||"Token revocation failed"},s.status)}this.clearCache()}catch(s){throw s instanceof p?s:p.fromError(s instanceof Error?s:new Error(String(s)))}}get url(){return this.config.url}get clientId(){return this.config.clientId}get scopes(){return this.config.scopes}get audience(){return this.config.audience}}exports.APP_ID_HEADER_KEY=b;exports.AUTHORIZATION_HEADER_KEY=I;exports.AppAPI=de;exports.AuthAPI=ue;exports.AuthService=ye;exports.CLIAuthAPI=He;exports.DEFAULT_GROUP_NAME=Fe;exports.DEFAULT_SCOPES=X;exports.DEVICE_ID_HEADER_KEY=H;exports.DEVICE_TYPE_HEADER_KEY=j;exports.ERROR_MESSAGE_MAX_LENGTH=re;exports.InvitationAPI=le;exports.InvitationService=Se;exports.M2MClient=et;exports.M2MConfigError=D;exports.M2MError=p;exports.M2MErrorCodes=Je;exports.M2MNetworkError=$;exports.M2MTokenParseError=C;exports.M2M_DEFAULTS=S;exports.MINIMAL_DEFAULT_SCOPES=Me;exports.OS=ce;exports.PASSFLOW_CLOUD_URL=L;exports.POPUP_HEIGHT=J;exports.POPUP_POLL_INTERVAL_MS=Z;exports.POPUP_TIMEOUT_MS=Q;exports.POPUP_WIDTH=W;exports.Passflow=O;exports.PassflowAdminEndpointPaths=w;exports.PassflowEndpointPaths=c;exports.PassflowError=l;exports.PassflowEvent=a;exports.PopupClosedError=G;exports.Providers=ae;exports.RequestMethod=_;exports.SDK_VERSION=z;exports.SessionState=K;exports.SettingAPI=pe;exports.TOKEN_EXPIRY_BUFFER_SECONDS=N;exports.TenantAPI=ge;exports.TenantService=Te;exports.TenantUserMembership=we;exports.TokenCacheService=Ee;exports.TokenDeliveryMode=m;exports.TokenType=k;exports.TwoFactorApiClient=fe;exports.TwoFactorPolicy=he;exports.TwoFactorService=_e;exports.USERNAME_MAX_LENGTH=te;exports.USERNAME_MIN_LENGTH=ee;exports.UserAPI=ke;exports.UserService=Ie;exports.WebAdapter=oe;exports.getOSFromDeviceType=Ge;exports.isTokenExpired=y;exports.isValidEmail=F;exports.isValidJWTFormat=M;exports.isValidPhoneNumber=P;exports.isValidUsername=me;exports.parseToken=v;exports.pathWithParams=T;exports.sanitizeErrorMessage=ve;exports.webAdapter=A;
2
- //# sourceMappingURL=index.js.map