@passflow/core 0.30.2 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,90 @@
2
2
 
3
3
  ## Changelog
4
4
 
5
+ ### Version 0.32.0
6
+
7
+ - `passflow.withAuth(fetch, { origins })`, `passflow.attachAuth(axios, { origins })` and
8
+ `passflow.createClient(config, { origins })` add `Authorization: Bearer <access token>` to a request
9
+ for the page's own origin or a listed origin when the request has no `Authorization` header,
10
+ refreshing an expired token first. Other origins get no token. Before, they only handled step-up,
11
+ so a request without the header now carries one. See
12
+ [Calling your API with the access token](#calling-your-api-with-the-access-token).
13
+ - `WithAuthOptions` is exported.
14
+
15
+ ### Version 0.31.0
16
+
17
+ Matches the SDK to the server's real two-factor, step-up and sign-out answers.
18
+
19
+ **Breaking:**
20
+ - `getTwoFactorEnrollment()` returns `{ enrollment, totp_digits?, totp_period? }`, not the bare string.
21
+ - 2FA types follow the server: status has no `policy`; confirm is `{ enabled, recovery_codes? }`,
22
+ disable `{ disabled }`, regenerate `{ recovery_codes }`; `remaining_recovery_codes` is optional;
23
+ `requires_2fa` and `device_trusted` are gone (a `tfa_token` marks a pending second factor).
24
+ `getAvailableMethods()` and `getRegisteredMethods()` return the arrays, not the server's wrapper.
25
+ - `TwoFactorDeviceTrusted` is no longer emitted (`@deprecated`): device trust is a server cookie.
26
+ - A sign-up that signs the user in emits `Register` and then `SignIn`; `verifyV2` emits `SignIn`
27
+ after `TwoFactorVerified` when it completes a sign-in.
28
+ - After a hosted sign-in (`authRedirect()`), `logOut()` also ends the hosted login's session: after
29
+ the local sign-out it navigates to `/oidc/end_session` with `id_token_hint` and
30
+ `post_logout_redirect_uri` (default: where the sign-in landed; `logOut({ postLogoutRedirectUri })`
31
+ overrides it, and it must match a registered redirect URL). Code after `await logOut()` may not run.
32
+ - Stored tokens whose `aud` does not name this instance's app id no longer count as a session, and
33
+ this app's sign-out leaves another app's stored session in place.
34
+ - `session({ createSession, expiredSession })` now runs for every completed sign-in, including
35
+ `signIn`, `signUp`, `passkeyRegister` and v2 verify.
36
+ - Step-up offers exactly the factors in the server's `available_factors`, in its order
37
+ (`UpgradeChallenge.availableFactors?`); without the field it suggests TOTP before passkey.
38
+ - A 429 on a step-up round is `UpgradeTransportError` kind `rate_limited` (it was `fatal`), with the
39
+ server's message and `retryAfter` from `Retry-After`; the surfaces settle it as exhausted.
40
+ - Response types that strict TypeScript code reads now say what the server may leave out. Handle
41
+ `undefined` for these, and stop checking `success` where it is gone:
42
+ - `AppSettings`: `secret`, `active`, `redirect_urls`, `origins`, `defaults`,
43
+ `custom_sms_messages`, `invite_only_registration`, `create_tenant_on_registration` and
44
+ `debug_otp_code_allowed` are optional.
45
+ - `TwoFactorVerifyResponseV2.success` is removed (a v2 verify that returns tokens succeeded).
46
+ - `success` on `TwoFactorVerifyResponse` and `TwoFactorRecoveryResponse` is optional.
47
+ - `RegisteredTwoFactorMethod.id`, `.name` and `.created_at`, and
48
+ `TwoFactorChallengeResponse.alternative_methods`, are optional.
49
+ - The `TwoFactorRecoveryUsed` event payload's `remainingCodes` is optional.
50
+
51
+ **New:**
52
+ - `UpgradeSignInRequiredError` (`upgrade_sign_in_required`) and `isUpgradeSignInRequired(res)`: the
53
+ step-up 403's `sign_in_required: true` (`prompt=login`, `max_age=0`, an expired `max_age` with no
54
+ factor to meet it; from older servers, an empty `available_factors`) means no step-up can meet it
55
+ and the user must sign in again. No prompt opens; an open prompt is
56
+ closed through the new optional `onClosed`. An empty list with `sign_in_required: false` is
57
+ `UpgradeUnsatisfiableError`: no factor of this account reaches the level.
58
+ - `passflow.hostedUpgrade` refuses to re-prove a requirement it proved in the last 10 seconds (or
59
+ within its `max_age`, if shorter) with `UpgradeInsufficientError`, so a refused proof cannot loop.
60
+ A sign-in or sign-out clears it. Keep every elevation window at 10 seconds or more (see Known
61
+ limits).
62
+ - `PassflowPasswordChangeRequiredError` and `PASSWORD_CHANGE_REQUIRED_ERROR_ID` for a 403
63
+ `error.api.password.change.required`.
64
+ - `device_trust_available?` on the v2 challenge and the enrolment answer; `redirect_url?` and
65
+ `form_post?` on the v1 and v2 verify answers for a sign-in with an OIDC parent.
66
+
67
+ **Fixed:**
68
+ - The TOTP digit count is read from enrolment and the v2 challenge too, so an 8-digit enrolment works
69
+ on a fresh sign-in; the count resets with each new second-factor step.
70
+ - `verifyV2` completes the sign-in (it waited for a `success` field the server never sends).
71
+ - Recovery codes are checked only for their form; the server decides.
72
+ - `PassflowError.name` is `'PassflowError'`.
73
+
74
+ **Known limits:**
75
+ - The `hostedUpgrade` memory assumes the app's elevation window (`auth_assurance.elevation_max_age`)
76
+ is at least 10 seconds. Servers before src/v0.50.0 accept any window, so the 10 s minimum does not
77
+ apply on them. src/v0.50.0 (not yet released) refuses new windows under 10 seconds but keeps a
78
+ shorter one already stored. With a window under
79
+ 10 seconds, a re-challenge for the same requirement within 10 seconds of the proof is refused with
80
+ `UpgradeInsufficientError`, costing the user one extra sign-in. Keep every window at 10 seconds or
81
+ more, and re-save any shorter one.
82
+ - A stale session (`max_age` expired) asked for a level none of the account's factors reaches gets
83
+ `sign_in_required: true` first. After the fresh sign-in, the level refusal follows as
84
+ `UpgradeUnsatisfiableError`, so that sign-in cannot help.
85
+ - A cookie or BFF session that stores no ID token makes another app's session undetectable, so this
86
+ app's `logOut()` clears the shared delivery mode and session state. It fails safe: the other app is
87
+ signed out, never wrongly signed in.
88
+
5
89
  ### Version 0.30.1
6
90
 
7
91
  - Fixed: `setAppId()` on an instance built with an `appId` now changes the `X-Passflow-ClientID`
@@ -160,6 +244,17 @@ const simpleSignOut = async () => {
160
244
  };
161
245
  ```
162
246
 
247
+ After a hosted sign-in (`authRedirect()`), `logOut()` also ends the hosted login's own session.
248
+ Otherwise the next hosted sign-in would go through with no password. Once the local sign-out and
249
+ its `SignOut` event have run, the page leaves for the server's `/oidc/end_session`, which returns
250
+ the browser to `postLogoutRedirectUri`. By default that is the address the hosted sign-in landed
251
+ on, and it must match one of the app's registered redirect URLs. Code after `await logOut()` may
252
+ not run then. A sign-in made in the app itself never navigates.
253
+
254
+ ```javascript
255
+ await passflow.logOut({ postLogoutRedirectUri: "https://app.example.com/signed-out" });
256
+ ```
257
+
163
258
  ### Quick Passwordless Authentication
164
259
 
165
260
  ```javascript
@@ -665,10 +760,12 @@ expired or spent code throws a `PassflowError` with an `error.otp.*` id, and an
665
760
  throws `error.not.found`. To send a fresh code, call the original method again; the new step has a
666
761
  new `challenge_id`.
667
762
 
668
- - **Register or SignIn.** `verifyEmailCode` emits `Register` for a challenge this `Passflow`
669
- instance got from `signUp`, and `SignIn` for one from `signIn` or `resetPassword`. Challenges are
670
- remembered in memory only, so a code entered in another tab, after a reload, or on a recreated
671
- instance emits `SignIn`, even for a sign-up. It emits no `SignInStart` or `RegisterStart`.
763
+ - **Register or SignIn.** `verifyEmailCode` emits `Register` then `SignIn` for a challenge this
764
+ `Passflow` instance got from `signUp`, and `SignIn` alone for one from `signIn` or
765
+ `resetPassword`. Challenges are remembered in memory only, so a code entered in another tab, after
766
+ a reload, or on a recreated instance emits `SignIn` alone, even for a sign-up. `verifyEmailCode`
767
+ emits no `SignInStart` or `RegisterStart`. `signUp` and `passkeyRegister` that sign the user in at
768
+ once also emit `Register` then `SignIn`.
672
769
  - **No `challenge_id`.** The code budget is spent and the server emailed a link instead. There is
673
770
  nothing to call: show `message` and let the user follow the link.
674
771
  - **Password reset.** `resetPassword(newPassword, scopes?, resetToken?)` takes the reset token as
@@ -681,7 +778,8 @@ A `required` app answers every sign-in with a `tfa_token`, also for a user who h
681
778
  Ask the server what this sign-in can do next before asking for a code:
682
779
 
683
780
  ```typescript
684
- switch (await passflow.getTwoFactorEnrollment()) {
781
+ const { enrollment } = await passflow.getTwoFactorEnrollment();
782
+ switch (enrollment) {
685
783
  case "verify": // the user has a factor
686
784
  await passflow.verifyTwoFactor(code);
687
785
  break;
@@ -699,6 +797,52 @@ switch (await passflow.getTwoFactorEnrollment()) {
699
797
  }
700
798
  ```
701
799
 
800
+ - **Trusted devices.** `device_trust_available` on the enrolment and on a v2 challenge says whether
801
+ to offer "trust this device" (`trust_device`) on this sign-in. Older servers leave it out: absent
802
+ means unknown, so hide the option only when it is `false`.
803
+ - **TOTP digits.** Read `getTwoFactorEnrollment()` before asking for the code. With a TOTP
804
+ enrolment it answers `totp_digits` (6 or 8) and `totp_period`, as does `requestChallenge`: size the
805
+ code input from `totp_digits`, and `verifyTwoFactor` then expects exactly that many digits. Until
806
+ an answer gives the count, `verifyTwoFactor` accepts 6 or 8 digits and the server decides. The
807
+ count lasts one sign-in.
808
+ - **Recovery codes** are 12 characters by default, issued as `XXXX-XXXX-XXXX`; apps choose 10–16
809
+ (only 12 is grouped with dashes). The server issues recovery codes
810
+ on every enrolment; `recovery_codes` on confirm is optional only so an older or different server
811
+ that omits it doesn't break the type. Older 8-character `XXXX-XXXX`
812
+ codes still work until they are regenerated. The SDK checks only the form (letters, digits and
813
+ optional dashes) and upper-cases the code; the server decides whether it is valid. `remaining_recovery_codes` may be
814
+ absent from the answer.
815
+ - **Step-up offers what the server lists.** The step-up 403 from `/auth/session/exchange` carries
816
+ `available_factors`, the factors this user can step up with, and the SDK offers exactly those in
817
+ that order. Without it (older servers), TOTP is suggested before passkey. When the list is empty,
818
+ no prompt opens and an open prompt is closed (its `onClosed` is called). The body's
819
+ `sign_in_required` says why:
820
+ - `true`: no step-up can meet the requirement, and the user must sign in again (`prompt=login`,
821
+ `max_age=0`, or an expired `max_age` with no factor to meet it). If the requested level is also
822
+ out of the account's reach, the next answer after that sign-in is the `false` case. The step-up
823
+ rejects with `UpgradeSignInRequiredError` (on a response, `isUpgradeSignInRequired(res)` is
824
+ true). Sign the user in again: an embedded app can call `authRedirect()`; the hosted login page
825
+ shows its own sign-in form instead.
826
+ - `false`: a step-up could meet it, but this account has no factor that reaches the level (for
827
+ example AAL3 needs a device-bound passkey). The step-up rejects with `UpgradeUnsatisfiableError`;
828
+ signing in again will not help.
829
+ - absent (older servers): an empty list counts as `true`.
830
+
831
+ A requirement like this that joins an open step-up ends it for every waiter, including one whose
832
+ own requirement the open prompt could have met: they all settle with the same error.
833
+
834
+ `UpgradeUnsatisfiableError` also means the server listed only factors this SDK cannot complete.
835
+ - **A hosted step-up is proved once per requirement.** `passflow.hostedUpgrade` remembers the
836
+ challenge it last proved on this page. An `elevate()` with a challenge that is not strictly
837
+ stronger (a higher level or a shorter `max_age`) rejects with `UpgradeInsufficientError`, with no
838
+ prompt and no request: the server refused a proof that met it, so prompting again would loop. Sign
839
+ the user in again instead. The proof counts for 10 seconds from its commit request (or the
840
+ requirement's `max_age`, if shorter): after that the same requirement prompts again. A sign-in or
841
+ sign-out clears it. Keep the app's elevation window (`auth_assurance.elevation_max_age`) at 10
842
+ seconds or more: a shorter window can lapse inside those 10 seconds, and the re-challenge is then
843
+ refused, costing one extra sign-in. Servers before src/v0.50.0 accept any window. src/v0.50.0 (not
844
+ yet released) refuses new windows under 10 seconds; after upgrading, re-save any shorter one
845
+ already stored.
702
846
  - **The server decides.** Setup calls in the wrong state answer 403 `error.2fa.enrollment.not_allowed`.
703
847
  - **The sign-in is over** on a 401 `error.tfa.token.invalid` or `error.otp.already.used`: sign in again.
704
848
  - **Rate limits are per user.** `sendTwoFactorSetupLink`, `beginTwoFactorEnrollment`,
@@ -776,6 +920,44 @@ with nothing saved. Verification needs the Web Crypto API (https or localhost).
776
920
  fragment) follows the same Simple-only rule and is verified the same way; on a PKCE app it requires a
777
921
  code.
778
922
 
923
+ ### Calling your API with the access token
924
+
925
+ `passflow.withAuth(fetch, options?)` returns a `fetch` that adds `Authorization: Bearer <access
926
+ token>` for you, and handles a step-up challenge on the answer. `passflow.attachAuth(axios, options?)`
927
+ and `passflow.createClient(axiosConfig?, options?)` do the same for axios, with a request interceptor
928
+ next to the step-up one; `attachAuth`'s disposer removes both.
929
+
930
+ ```javascript
931
+ const api = passflow.withAuth(fetch, { origins: ["https://api.example.com"] });
932
+ const res = await api("https://api.example.com/orders"); // carries the token
933
+ await api("/api/me"); // the page's own origin: carries the token
934
+ await api("https://cdn.example.net/data.json"); // any other origin: no token
935
+
936
+ const client = passflow.createClient({ baseURL: "https://api.example.com" }, { origins: ["https://api.example.com"] });
937
+ await client.get("/orders"); // carries the token
938
+ ```
939
+
940
+ - The token goes only to the page's own origin (`location.origin`) and to the origins in
941
+ `options.origins`. Origins are compared exactly, scheme, host and port: `https://api.example.com`
942
+ does not cover `http://api.example.com`, `https://api.example.com:8443` or
943
+ `https://api.example.com.evil.com`. A relative URL resolves against the page. On axios the check
944
+ uses the URL axios sends: a relative URL is joined to `baseURL`, an absolute one is judged by its own
945
+ origin, and with `allowAbsoluteUrls: false` an absolute one is joined to `baseURL` too. Outside a
946
+ browser page (SSR, React Native) only the listed origins get it. List http(s) origins only: an
947
+ `origins` entry that is not a URL, or has no origin to match (`capacitor://localhost`, `file:`, a
948
+ custom app scheme), throws.
949
+ - A request that already has an `Authorization` header goes out as you set it, including an axios
950
+ client default.
951
+ - An expired access token is refreshed first, as `getTokens(true)` does. With no signed-in user, or
952
+ when the refresh fails (the expired token is never sent), no header is added.
953
+ - On an axios instance you already own, a request interceptor you added before `attachAuth` runs
954
+ after the token one (axios runs request interceptors last-added first). If it rewrites `baseURL`
955
+ or `url`, the request goes where it points, with the token decided for the URL before the rewrite.
956
+ Add such interceptors after `attachAuth`, or set the header in them yourself.
957
+ - Requires axios 1.x. On 0.27.x the interceptor cannot see a client default
958
+ `defaults.headers.common.Authorization`, so the token replaces it.
959
+ - A cookie or BFF session holds no access token in the page, so nothing is added there.
960
+
779
961
  ### Token refresh across tabs
780
962
 
781
963
  Every refresh in a `Passflow` instance (`refreshToken()`, `getTokens(true)`,
@@ -964,6 +1146,13 @@ try {
964
1146
  }
965
1147
  ```
966
1148
 
1149
+ ### Password change required
1150
+
1151
+ A password sign-in for a user who must change the password first rejects with
1152
+ `PassflowPasswordChangeRequiredError` (a `PassflowError`, status 403, id
1153
+ `error.api.password.change.required`, exported as `PASSWORD_CHANGE_REQUIRED_ERROR_ID`). No token
1154
+ comes with it.
1155
+
967
1156
  ### Service unavailable
968
1157
 
969
1158
  In a browser, when the Passflow API cannot be reached or its gateway answers 502, 503 or 504 itself,
@@ -1024,7 +1213,7 @@ Configuration options:
1024
1213
  | `session({ createSession, expiredSession, doRefresh })` | Set up session management |
1025
1214
  | `signIn(payload)` | Sign in with email/password |
1026
1215
  | `signUp(payload)` | Register a new user |
1027
- | `logOut()` | Sign out the current user |
1216
+ | `logOut(options?)` | Sign out the current user |
1028
1217
  | `passwordlessSignIn(payload)` | Start passwordless authentication |
1029
1218
  | `passwordlessSignInComplete(payload)` | Complete passwordless authentication |
1030
1219
  | `federatedAuthWithPopup(provider, redirectUrl, scopes)` | Sign in with a provider using popup |