@feelflow/ffid-sdk 5.12.0 → 5.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as FFIDSubscriptionStatus, a as FFIDConfig, b as FFIDApiResponse, c as FFIDSessionResponse, d as FFIDRedirectResult, e as FFIDError, f as FFIDSubscriptionCheckResponse, g as FFIDCheckServiceAccessParams, h as FFIDServiceAccessDecision, i as FFIDProfileCallOptions, j as FFIDUserProfile, k as FFIDUpdateUserProfileRequest, l as FFIDAnalyticsConfig, m as FFIDVerifyAccessTokenOptions, n as FFIDOAuthUserInfo, o as FFIDInquiryCreateParams, p as FFIDInquiryCreateResponse, q as FFIDAuthMode, r as FFIDLogger, s as FFIDCacheAdapter, t as FFIDUser, u as FFIDOrganization, v as FFIDSubscription, w as FFIDSubscriptionContextValue, E as EffectiveSubscriptionStatus, x as FFIDOAuthUserInfoSubscription, y as FFIDAnnouncementsClientConfig, L as ListAnnouncementsOptions, z as FFIDAnnouncementsApiResponse, A as AnnouncementListResponse, B as FFIDAnnouncementsLogger } from './index-DqsWKU16.cjs';
2
- export { C as Announcement, D as AnnouncementStatus, G as AnnouncementType, H as EFFECTIVE_SUBSCRIPTION_STATUSES, I as FFIDAnnouncementBadge, J as FFIDAnnouncementList, K as FFIDAnnouncementsError, M as FFIDAnnouncementsErrorCode, N as FFIDAnnouncementsServerResponse, O as FFIDCacheConfig, P as FFIDContextValue, Q as FFIDInquiryCategory, R as FFIDInquiryCategorySite2026, S as FFIDInquiryForm, T as FFIDInquiryFormCategoryItem, U as FFIDInquiryFormClassNames, V as FFIDInquiryFormLegalLayout, W as FFIDInquiryFormOrganization, X as FFIDInquiryFormPlaceholderContext, Y as FFIDInquiryFormPrefill, Z as FFIDInquiryFormProps, _ as FFIDInquiryFormSubmitData, $ as FFIDInquiryFormSubmitResult, a0 as FFIDJwtClaims, a1 as FFIDLoginButton, a2 as FFIDOAuthTokenResponse, a3 as FFIDOAuthUserInfoMemberRole, a4 as FFIDOrganizationSwitcher, a5 as FFIDRedirectErrorCode, a6 as FFIDSeatModel, a7 as FFIDServiceAccessDenialReason, a8 as FFIDServiceAccessFailPolicy, a9 as FFIDSubscriptionBadge, aa as FFIDTokenIntrospectionResponse, ab as FFIDUserMenu, ac as FFID_INQUIRY_CATEGORIES, ad as FFID_INQUIRY_CATEGORIES_SITE_2026, ae as UseFFIDAnnouncementsOptions, af as UseFFIDAnnouncementsReturn, ag as isFFIDInquiryCategorySite2026, ah as useFFIDAnnouncements } from './index-DqsWKU16.cjs';
1
+ import { F as FFIDSubscriptionStatus, a as FFIDConfig, b as FFIDApiResponse, c as FFIDSessionResponse, d as FFIDRedirectResult, e as FFIDError, f as FFIDSubscriptionCheckResponse, g as FFIDCheckServiceAccessParams, h as FFIDServiceAccessDecision, i as FFIDAnalyticsConfig, j as FFIDVerifyAccessTokenOptions, k as FFIDOAuthUserInfo, l as FFIDInquiryCreateParams, m as FFIDInquiryCreateResponse, n as FFIDAuthMode, o as FFIDLogger, p as FFIDCacheAdapter, q as FFIDUser, r as FFIDOrganization, s as FFIDSubscription, t as FFIDSubscriptionContextValue, E as EffectiveSubscriptionStatus, u as FFIDOAuthUserInfoSubscription, v as FFIDAnnouncementsClientConfig, L as ListAnnouncementsOptions, w as FFIDAnnouncementsApiResponse, A as AnnouncementListResponse, x as FFIDAnnouncementsLogger } from './index-CsVJTuPv.cjs';
2
+ export { y as Announcement, z as AnnouncementStatus, B as AnnouncementType, C as EFFECTIVE_SUBSCRIPTION_STATUSES, D as FFIDAnnouncementBadge, G as FFIDAnnouncementList, H as FFIDAnnouncementsError, I as FFIDAnnouncementsErrorCode, J as FFIDAnnouncementsServerResponse, K as FFIDCacheConfig, M as FFIDContextValue, N as FFIDInquiryCategory, O as FFIDInquiryCategorySite2026, P as FFIDInquiryForm, Q as FFIDInquiryFormCategoryItem, R as FFIDInquiryFormClassNames, S as FFIDInquiryFormLegalLayout, T as FFIDInquiryFormOrganization, U as FFIDInquiryFormPlaceholderContext, V as FFIDInquiryFormPrefill, W as FFIDInquiryFormProps, X as FFIDInquiryFormSubmitData, Y as FFIDInquiryFormSubmitResult, Z as FFIDJwtClaims, _ as FFIDLoginButton, $ as FFIDOAuthTokenResponse, a0 as FFIDOAuthUserInfoMemberRole, a1 as FFIDOrganizationSwitcher, a2 as FFIDRedirectErrorCode, a3 as FFIDSeatModel, a4 as FFIDServiceAccessDenialReason, a5 as FFIDServiceAccessFailPolicy, a6 as FFIDSubscriptionBadge, a7 as FFIDTokenIntrospectionResponse, a8 as FFIDUserMenu, a9 as FFID_INQUIRY_CATEGORIES, aa as FFID_INQUIRY_CATEGORIES_SITE_2026, ab as UseFFIDAnnouncementsOptions, ac as UseFFIDAnnouncementsReturn, ad as isFFIDInquiryCategorySite2026, ae as useFFIDAnnouncements } from './index-CsVJTuPv.cjs';
3
3
  export { A as ALL_DENIED_EXCEPT_NECESSARY, i as CONSENT_COOKIE_NAME, j as CONSENT_DISMISSAL_TIMESTAMP_KEY, l as COOKIE_VERSION, D as DEFAULT_CONSENT_ERROR_MESSAGES, o as FFIDAnalyticsProvider, p as FFIDAnalyticsProviderProps, c as FFIDConsentCategories, r as FFIDConsentCategoryCode, e as FFIDConsentCategoryMetadata, w as FFIDConsentError, x as FFIDConsentErrorCode, y as FFIDConsentMergeStrategy, B as FFIDConsentMergeWarning, E as FFIDConsentMergeWarningEvent, F as FFIDConsentResult, I as FFIDConsentSource, a as FFIDConsentState, d as FFIDConsentSyncResult, M as FFIDCookieBanner, N as FFIDCookieBannerClassNames, O as FFIDCookieBannerProps, Q as FFIDCookieLink, R as FFIDCookieLinkProps, f as FFIDCookiePolicy, T as FFIDCookieSettings, U as FFIDCookieSettingsClassNames, V as FFIDCookieSettingsProps, _ as FFID_CONSENT_ERROR_CODES, ae as UseFFIDConsentPreferencesReturn, af as UseFFIDConsentReturn, ag as clearConsentDismissalTimestamp, aj as decodeConsentCookie, al as encodeConsentCookie, an as readConsentCookie, ao as readConsentDismissalTimestamp, aq as useFFIDConsent, ar as useFFIDConsentPreferences, as as writeConsentCookie, at as writeConsentDismissalTimestamp } from './FFIDCookieLink-D1WwE_ZO.cjs';
4
4
  import * as react_jsx_runtime from 'react/jsx-runtime';
5
5
  import { ReactNode, ComponentType, FC } from 'react';
@@ -122,6 +122,35 @@ declare function storeCodeVerifier(verifier: string, logger?: PKCELogger): boole
122
122
  */
123
123
  declare function retrieveCodeVerifier(logger?: PKCELogger): string | null;
124
124
 
125
+ /** Logger interface matching FFIDLogger for optional warning output */
126
+ interface StateLogger {
127
+ warn: (...args: unknown[]) => void;
128
+ }
129
+ /**
130
+ * Store the OAuth `state` for later retrieval.
131
+ *
132
+ * Writes to both sessionStorage (primary) and localStorage (fallback for iOS
133
+ * WebKit sessionStorage eviction during external OAuth bounces). Returns true
134
+ * if at least one write succeeded.
135
+ *
136
+ * @param state - The OAuth state value to store
137
+ * @param logger - Optional logger for warning on storage failure
138
+ * @returns true if stored in at least one storage, false otherwise
139
+ */
140
+ declare function storeState(state: string, logger?: StateLogger): boolean;
141
+ /**
142
+ * Retrieve and remove the OAuth `state`.
143
+ *
144
+ * Reads from sessionStorage first, falls back to localStorage (with 5-minute TTL).
145
+ * Removes from all storages after retrieval (one-time use). Returns null if no
146
+ * state is stored, the fallback is stale (>5 min), or storage is unavailable.
147
+ *
148
+ * @param logger - Optional logger for warning on storage failure
149
+ */
150
+ declare function retrieveState(logger?: StateLogger): string | null;
151
+
152
+ declare function cleanupStateStorage(logger?: StateLogger): void;
153
+
125
154
  /**
126
155
  * Billing checkout / portal session types.
127
156
  *
@@ -651,6 +680,307 @@ interface FFIDRetryPaymentSummary {
651
680
  failures: FFIDRetryPaymentFailure[];
652
681
  }
653
682
 
683
+ /**
684
+ * Login history types (ext API).
685
+ *
686
+ * Mirrors the data shape returned by `GET /api/v1/users/ext/me/login-history`
687
+ * (and its cookie counterpart `/api/v1/users/me/login-history`), which is
688
+ * derived from `audit_logs` rows. Field names are `camelCase` to match the
689
+ * route's `data` payload.
690
+ */
691
+ /**
692
+ * A single login-history entry.
693
+ *
694
+ * Each entry corresponds to one auth audit event (sign-in / sign-out /
695
+ * password-reset). Failed attempts are flagged via {@link isSuspicious}.
696
+ */
697
+ interface FFIDLoginHistoryEntry {
698
+ /** Audit log entry id (UUID). */
699
+ id: string;
700
+ /** ISO 8601 timestamp of the event. */
701
+ timestamp: string;
702
+ /** Source IP address, or `null` when not recorded. */
703
+ ipAddress: string | null;
704
+ /** User agent string, or `null` when not recorded. */
705
+ userAgent: string | null;
706
+ /** Audit action (e.g. `auth.signin`, `auth.signout`, `auth.password_reset`). */
707
+ action: string;
708
+ /** Whether the auth event succeeded or failed. */
709
+ result: 'success' | 'failure';
710
+ /** `true` for failed attempts (currently equivalent to `result === 'failure'`). */
711
+ isSuspicious: boolean;
712
+ }
713
+ /**
714
+ * Response payload from `getLoginHistory`.
715
+ *
716
+ * `total` is the number of entries returned (not a global count) — it equals
717
+ * `history.length`, matching the route's `{ history, total }` envelope.
718
+ */
719
+ interface FFIDLoginHistoryResponse {
720
+ /** Recent login-history entries, newest first. */
721
+ history: FFIDLoginHistoryEntry[];
722
+ /** Number of entries returned (equal to `history.length`). */
723
+ total: number;
724
+ }
725
+
726
+ /**
727
+ * Types for the organization verified-domains ext API.
728
+ *
729
+ * Mirrors the `VerifiedDomain` row shape returned by the FFID server route
730
+ * `GET /api/v1/organizations/ext/domains` (data field of the response).
731
+ *
732
+ * @see Issue #3783 (non-contract SDK coverage)
733
+ * @see Issue #3757 (verified-domain claims)
734
+ */
735
+ /** A single organization verified-domain claim. */
736
+ interface FFIDOrganizationDomain {
737
+ /** Domain claim ID (UUID) */
738
+ id: string;
739
+ /** Owning organization ID (UUID) */
740
+ organizationId: string;
741
+ /** Claimed domain (normalized, e.g. `example.com`) */
742
+ domain: string;
743
+ /** Token to publish as a DNS TXT record to prove ownership */
744
+ verificationToken: string;
745
+ /** When ownership was verified, or `null` while the claim is still pending */
746
+ verifiedAt: string | null;
747
+ /** User ID (UUID) that verified the claim, or `null` while pending */
748
+ verifiedBy: string | null;
749
+ /** Whether same-domain users can discover & request to join (only meaningful once verified) */
750
+ discoverable: boolean;
751
+ /** When the claim was created */
752
+ createdAt: string;
753
+ /** When the claim was last updated */
754
+ updatedAt: string;
755
+ }
756
+ /** Response from getOrganizationDomains (ext). */
757
+ interface FFIDOrganizationDomainsResponse {
758
+ domains: FFIDOrganizationDomain[];
759
+ }
760
+
761
+ /**
762
+ * Organization billing notification preference types (ext API).
763
+ *
764
+ * Mirrors the FFID backend `billing_notification_preferences` shape exposed via
765
+ * `GET /api/v1/organizations/ext/notification-preferences` and the matching
766
+ * `PATCH`. Keys use the backend's snake_case casing because they map directly to
767
+ * the stored JSONB column.
768
+ */
769
+ /**
770
+ * An organization's billing notification preferences.
771
+ *
772
+ * `payment_failed` is a legal obligation and is always `true` — the server
773
+ * forces it on read and write regardless of the requested value.
774
+ */
775
+ interface FFIDOrganizationNotificationPreferences {
776
+ /** Whether renewal reminder notifications are enabled */
777
+ renewal_reminders: boolean;
778
+ /** Whether monthly usage/summary notifications are enabled */
779
+ monthly_summary: boolean;
780
+ /** Always true — payment failure notifications cannot be disabled (legal obligation) */
781
+ payment_failed: boolean;
782
+ }
783
+ /** Response from getNotificationPreferences / updateNotificationPreferences (ext) */
784
+ interface FFIDOrganizationNotificationPreferencesResponse {
785
+ preferences: FFIDOrganizationNotificationPreferences;
786
+ }
787
+ /**
788
+ * Request payload for updateNotificationPreferences (ext).
789
+ *
790
+ * Partial of the writable keys — only the supplied keys are updated. Omitted
791
+ * keys are reset to their default (`true`) on the server. `payment_failed` is
792
+ * not writable: it is always forced to `true`.
793
+ */
794
+ type FFIDUpdateNotificationPreferencesRequest = Partial<Pick<FFIDOrganizationNotificationPreferences, 'renewal_reminders' | 'monthly_summary'>>;
795
+
796
+ /**
797
+ * Invitation status returned by the ext invite endpoint.
798
+ *
799
+ * A freshly created invitation is always `pending`; the broader union is
800
+ * included to match the route's `status` field (sourced from the invitations
801
+ * table) so consumers can narrow safely.
802
+ */
803
+ type FFIDInvitationStatus = 'pending' | 'accepted' | 'expired' | 'cancelled';
804
+ /** Request body for inviteMember (ext) */
805
+ interface FFIDInviteMemberRequest {
806
+ /** Email address to invite */
807
+ email: string;
808
+ /** Role to assign on acceptance (defaults to `member` server-side) */
809
+ role?: FFIDAssignableMemberRole;
810
+ }
811
+ /**
812
+ * Response from inviteMember (ext).
813
+ *
814
+ * Matches the `/api/v1/organizations/ext/invite` route data exactly:
815
+ * `{ id, email, role, status, expiresAt }`.
816
+ */
817
+ interface FFIDInviteMemberResponse {
818
+ /** Invitation ID (UUID) */
819
+ id: string;
820
+ /** Invited email address (normalized server-side) */
821
+ email: string;
822
+ /** Role assigned to the invitation */
823
+ role: FFIDMemberRole;
824
+ /** Invitation lifecycle status (always `pending` on creation) */
825
+ status: FFIDInvitationStatus;
826
+ /** ISO 8601 timestamp when the invitation expires */
827
+ expiresAt: string;
828
+ }
829
+
830
+ /**
831
+ * Types for the user-scoped organization membership methods (ext API).
832
+ *
833
+ * Backs `leaveOrganization` — a DESTRUCTIVE self-leave operation against
834
+ * `DELETE /api/v1/users/ext/me/organizations/:organizationId`.
835
+ */
836
+ /**
837
+ * Parameters for `leaveOrganization`.
838
+ *
839
+ * `userId` is REQUIRED in `service-key` auth mode (there is no ambient user on
840
+ * a service credential, so the leaving user must be named explicitly). In
841
+ * `token` / `cookie` modes it is derived server-side from the credential and
842
+ * may be omitted; if provided in those modes it is ignored by the server.
843
+ */
844
+ interface FFIDLeaveOrganizationParams {
845
+ /** The organization the user is leaving (UUID). */
846
+ organizationId: string;
847
+ /**
848
+ * The leaving user's id (UUID). Required for `service-key` mode; optional
849
+ * (and server-ignored) for `token` / `cookie` modes.
850
+ */
851
+ userId?: string;
852
+ }
853
+ /**
854
+ * Response from `leaveOrganization` (ext).
855
+ *
856
+ * Matches the route's success `data` shape `{ message }`.
857
+ */
858
+ interface FFIDLeaveOrganizationResponse {
859
+ /** Human-readable confirmation message (Japanese). */
860
+ message: string;
861
+ }
862
+
863
+ /**
864
+ * User profile types (ext API: `GET` / `PUT /api/v1/users/ext/me`).
865
+ *
866
+ * Extracted from `./index.ts` to keep the types barrel under the file-size
867
+ * limit, consistent with the per-domain extraction already used for
868
+ * `service-access`, `organization-members`, `contract-resources`, etc. The
869
+ * barrel re-exports these so the public import path (`@feelflow/ffid-sdk`)
870
+ * is unchanged.
871
+ */
872
+ /**
873
+ * User profile for the authenticated user (returned by `getProfile` / `updateProfile`).
874
+ *
875
+ * Mirrors the FFID backend `UserProfile` shape exposed via
876
+ * `GET /api/v1/users/ext/me` and `PUT /api/v1/users/ext/me`.
877
+ */
878
+ interface FFIDUserProfile {
879
+ /** User ID (UUID) */
880
+ id: string;
881
+ /** Email address */
882
+ email: string;
883
+ /** Display name (nullable when not set) */
884
+ displayName: string | null;
885
+ /** Avatar URL (nullable when not set) */
886
+ avatarUrl: string | null;
887
+ /** Phone number (nullable when not set) */
888
+ phone: string | null;
889
+ /** Company name (nullable when not set) */
890
+ companyName: string | null;
891
+ /** Department (nullable when not set) */
892
+ department: string | null;
893
+ /** Job title (nullable when not set) */
894
+ jobTitle: string | null;
895
+ /** IANA timezone (e.g. 'Asia/Tokyo') */
896
+ timezone: string;
897
+ /** Locale (e.g. 'ja', 'en') */
898
+ locale: string;
899
+ /** Arbitrary user preferences bag */
900
+ preferences: Record<string, unknown>;
901
+ /** Account creation timestamp (ISO 8601) */
902
+ createdAt: string;
903
+ /** Profile last-updated timestamp (ISO 8601) */
904
+ updatedAt: string;
905
+ }
906
+ /**
907
+ * Per-call options for profile methods (`getProfile` / `updateProfile`).
908
+ *
909
+ * Supply `accessToken` to forward an end-user Bearer token for the single call
910
+ * without mutating client-level auth state. Designed for server runtimes (Cloudflare
911
+ * Workers, Edge, Node) that receive a user-scoped Bearer per request and want to
912
+ * act as that user against `/api/v1/users/ext/me`.
913
+ *
914
+ * When `accessToken` is supplied with a non-empty value, it overrides the client's
915
+ * configured auth mode: authentication for that request uses only
916
+ * `Authorization: Bearer <accessToken>` (no service key, no cookie, no token-store
917
+ * lookup, no auto-refresh on 401). Non-auth headers such as `Content-Type` are
918
+ * still attached. SDK metadata headers (`User-Agent` / `X-FFID-SDK-Version`) are
919
+ * attached on non-browser runtimes only (Node.js / Cloudflare Workers / Edge /
920
+ * Deno); browsers receive an empty object to avoid iOS WebKit `fetch()` breakage
921
+ * (see #2417).
922
+ *
923
+ * Runtime semantics:
924
+ * - `accessToken` omitted (or `undefined`) → no override, configured `authMode` is used
925
+ * - `accessToken` is empty string / whitespace-only → rejected as `VALIDATION_ERROR`
926
+ * before any network call (prevents silent impersonation fallback when a caller
927
+ * extracts a missing/blank `Authorization` header into this field)
928
+ * - `accessToken` is a non-empty string → override activated
929
+ */
930
+ interface FFIDProfileCallOptions {
931
+ /**
932
+ * End-user Bearer token forwarded for this single request.
933
+ *
934
+ * Must be a non-empty string when supplied. Passing `''` or a whitespace-only
935
+ * string is treated as a caller error and surfaces as `VALIDATION_ERROR` —
936
+ * this guards against the common footgun where a server runtime extracts the
937
+ * Bearer from an incoming request without checking the header is present.
938
+ */
939
+ accessToken?: string;
940
+ }
941
+ /**
942
+ * Request payload for `updateProfile`.
943
+ *
944
+ * Mirrors the FFID backend `UpdateUserProfileRequest` shape. All fields are
945
+ * optional — only the supplied keys will be updated (partial update semantics).
946
+ *
947
+ * Per-field value semantics:
948
+ * - `undefined` / key omitted → field is untouched (partial update)
949
+ * - `null` → clears the field (stores SQL NULL in the DB)
950
+ * - `""` (empty string) → stored as a literal empty string, **not** treated as
951
+ * a clear. Use `null` when you want the DB value to become NULL
952
+ *
953
+ * `timezone` and `locale` are intentionally modeled as non-null in this
954
+ * request type (application-level invariant — the DB columns have DEFAULT
955
+ * values but no NOT NULL constraint, yet the server-side normalization
956
+ * pipeline assumes a string is always present). Pass a string to update the
957
+ * value, or omit the key to leave the current value in place. Do not pass
958
+ * `null` to clear — there is no meaningful "no timezone" state for a user.
959
+ *
960
+ * `preferences: null` is accepted and clears the column. Subsequent reads
961
+ * return `{}` because the FFID backend normalizes a null `preferences` column
962
+ * to an empty object (`toUserProfile` helper) before serializing the response —
963
+ * the SDK itself does not transform the payload.
964
+ */
965
+ interface FFIDUpdateUserProfileRequest {
966
+ /** Display name (null clears the field) */
967
+ displayName?: string | null;
968
+ /** Phone number (null clears the field) */
969
+ phone?: string | null;
970
+ /** Company name (null clears the field) */
971
+ companyName?: string | null;
972
+ /** Department (null clears the field) */
973
+ department?: string | null;
974
+ /** Job title (null clears the field) */
975
+ jobTitle?: string | null;
976
+ /** IANA timezone (non-null; omit the key to leave unchanged) */
977
+ timezone?: string;
978
+ /** Locale (non-null; omit the key to leave unchanged) */
979
+ locale?: string;
980
+ /** Arbitrary user preferences bag (null clears the column; reads return {}) */
981
+ preferences?: Record<string, unknown> | null;
982
+ }
983
+
654
984
  /** OTP / magic link methods - sendOtp / verifyOtp */
655
985
 
656
986
  /** Response from sendOtp */
@@ -716,6 +1046,45 @@ interface ContractWizardSubscriptionOptions {
716
1046
  organizationId?: string;
717
1047
  }
718
1048
 
1049
+ /** Login history methods - getLoginHistory (ext API) */
1050
+
1051
+ /** Parameters accepted by `getLoginHistory`. */
1052
+ interface FFIDGetLoginHistoryParams {
1053
+ /**
1054
+ * Target user id (UUID).
1055
+ *
1056
+ * **Required in `service-key` auth mode** — an `X-Service-Api-Key` request
1057
+ * has no ambient user, so the server requires `?userId=` to know whose
1058
+ * history to return. In `token` / `cookie` auth modes the user is derived
1059
+ * server-side from the credential, so `userId` is ignored if supplied.
1060
+ */
1061
+ userId?: string;
1062
+ /**
1063
+ * Maximum number of entries to return. Clamped server-side to the route's
1064
+ * ceiling (20); omit to use the default.
1065
+ */
1066
+ limit?: number;
1067
+ }
1068
+
1069
+ /** OAuth token operations - exchangeCodeForTokens / refreshAccessToken / signOutToken */
1070
+
1071
+ /**
1072
+ * Optional OAuth `state` validation for {@link exchangeCodeForTokens}.
1073
+ *
1074
+ * If a `state` is supplied on EITHER side — `expectedState` (the value persisted
1075
+ * at `redirectToAuthorize`) or `actualState` (the value returned on the callback
1076
+ * URL) — both must be present and equal before any token exchange. A mismatch
1077
+ * OR an omitted counterpart fails closed (no exchange) to defend against CSRF
1078
+ * (RFC 6749 §10.12 / #3841). Validation is skipped only when BOTH are omitted
1079
+ * (backward compatible — callers that don't opt in are unaffected).
1080
+ */
1081
+ interface ExchangeCodeForTokensOptions {
1082
+ /** Stored state from `redirectToAuthorize` (e.g. `retrieveState()`) */
1083
+ expectedState?: string;
1084
+ /** State returned on the OAuth callback URL */
1085
+ actualState?: string;
1086
+ }
1087
+
719
1088
  /** Redirect and URL generation - redirectToLogin / redirectToAuthorize / redirectToLogout / getLoginUrl / getSignupUrl / getLogoutUrl */
720
1089
 
721
1090
  /**
@@ -755,7 +1124,7 @@ declare function createFFIDClient(config: FFIDConfig): {
755
1124
  getLogoutUrl: (postLogoutRedirectUri?: string) => string;
756
1125
  getSignupUrl: (redirectUrl?: string) => string;
757
1126
  createError: (code: string, message: string) => FFIDError;
758
- exchangeCodeForTokens: (code: string, codeVerifier?: string) => Promise<FFIDApiResponse<void>>;
1127
+ exchangeCodeForTokens: (code: string, codeVerifier?: string, opts?: ExchangeCodeForTokensOptions) => Promise<FFIDApiResponse<void>>;
759
1128
  refreshAccessToken: () => Promise<FFIDApiResponse<void>>;
760
1129
  checkSubscription: (params: {
761
1130
  userId?: string;
@@ -781,6 +1150,23 @@ declare function createFFIDClient(config: FFIDConfig): {
781
1150
  }) => Promise<FFIDApiResponse<FFIDRemoveMemberResponse>>;
782
1151
  getProfile: (options?: FFIDProfileCallOptions) => Promise<FFIDApiResponse<FFIDUserProfile>>;
783
1152
  updateProfile: (data: FFIDUpdateUserProfileRequest, options?: FFIDProfileCallOptions) => Promise<FFIDApiResponse<FFIDUserProfile>>;
1153
+ getLoginHistory: (params?: FFIDGetLoginHistoryParams) => Promise<FFIDApiResponse<FFIDLoginHistoryResponse>>;
1154
+ getOrganizationDomains: (params: {
1155
+ organizationId: string;
1156
+ }) => Promise<FFIDApiResponse<FFIDOrganizationDomainsResponse>>;
1157
+ getNotificationPreferences: (params: {
1158
+ organizationId: string;
1159
+ }) => Promise<FFIDApiResponse<FFIDOrganizationNotificationPreferencesResponse>>;
1160
+ updateNotificationPreferences: (params: {
1161
+ organizationId: string;
1162
+ preferences: FFIDUpdateNotificationPreferencesRequest;
1163
+ }) => Promise<FFIDApiResponse<FFIDOrganizationNotificationPreferencesResponse>>;
1164
+ inviteMember: (params: {
1165
+ organizationId: string;
1166
+ email: string;
1167
+ role?: FFIDAssignableMemberRole;
1168
+ }) => Promise<FFIDApiResponse<FFIDInviteMemberResponse>>;
1169
+ leaveOrganization: (params: FFIDLeaveOrganizationParams) => Promise<FFIDApiResponse<FFIDLeaveOrganizationResponse>>;
784
1170
  getAnalyticsConfig: (serviceCode: string, options?: FFIDProfileCallOptions) => Promise<FFIDApiResponse<FFIDAnalyticsConfig>>;
785
1171
  createCheckoutSession: (params: FFIDCreateCheckoutParams) => Promise<FFIDApiResponse<FFIDCheckoutSessionResponse>>;
786
1172
  createPortalSession: (params: FFIDCreatePortalParams) => Promise<FFIDApiResponse<FFIDPortalSessionResponse>>;
@@ -857,6 +1243,52 @@ declare class FFIDSDKError extends Error {
857
1243
  constructor(code: string, message: string);
858
1244
  }
859
1245
 
1246
+ /**
1247
+ * OAuth redirect callback handler
1248
+ *
1249
+ * `handleRedirectCallback` is the convenience counterpart to
1250
+ * `redirectToAuthorize`: it reads `code` + `state` from the callback URL,
1251
+ * validates the OAuth `state` against the value persisted at authorize time
1252
+ * (CSRF protection, RFC 6749 §10.12), retrieves the PKCE verifier, exchanges
1253
+ * the code for tokens, and cleans the params out of the URL on success.
1254
+ */
1255
+
1256
+ /**
1257
+ * Minimal client surface required by {@link handleRedirectCallback}.
1258
+ * A full {@link FFIDClient} satisfies this structurally.
1259
+ */
1260
+ type HandleRedirectCallbackClient = Pick<FFIDClient, 'exchangeCodeForTokens' | 'createError' | 'logger'>;
1261
+ /** Options for {@link handleRedirectCallback} */
1262
+ interface HandleRedirectCallbackOptions {
1263
+ /**
1264
+ * Callback URL (or query string) to read `code` / `state` from. Accepts an
1265
+ * absolute URL, a relative URL, or a bare query string. Defaults to
1266
+ * `window.location.search` in the browser.
1267
+ */
1268
+ url?: string;
1269
+ }
1270
+ /**
1271
+ * Complete an OAuth authorization-code redirect.
1272
+ *
1273
+ * Behavior:
1274
+ * 1. Reads `code` + `state` from `options.url ?? window.location.search`.
1275
+ * 2. CSRF guard: if a `state` exists on EITHER side (a stored state from
1276
+ * authorize OR a `state` on the callback URL), the two MUST match — mismatch,
1277
+ * a missing stored state, or an **omitted** callback `state` all **fail closed**
1278
+ * (returns an error, performs no exchange). Validation is skipped ONLY when
1279
+ * neither side has any state (a genuine no-state flow). Omitting the callback
1280
+ * `state` does NOT bypass the check (#3841).
1281
+ * 3. Retrieves the PKCE verifier and exchanges the code for tokens.
1282
+ * 4. On success, removes `code` + `state` from the browser URL.
1283
+ *
1284
+ * SSR-safe: when there is no `window` and no `options.url`, no exchange is
1285
+ * attempted and an error result is returned.
1286
+ *
1287
+ * @param client - FFID client (or any object exposing exchangeCodeForTokens / createError / logger)
1288
+ * @param options - Optional callback URL override
1289
+ */
1290
+ declare function handleRedirectCallback(client: HandleRedirectCallbackClient, options?: HandleRedirectCallbackOptions): Promise<FFIDApiResponse<void>>;
1291
+
860
1292
  /**
861
1293
  * Redirect URI normalization (SDK copy)
862
1294
  *
@@ -1565,4 +1997,4 @@ declare function createInquiryMethods(deps: InquiryMethodsDeps): {
1565
1997
  };
1566
1998
  type FFIDInquiryClient = ReturnType<typeof createInquiryMethods>;
1567
1999
 
1568
- export { ACCESS_GRANTING_EFFECTIVE_STATUSES, AnnouncementListResponse, BLOCKING_EFFECTIVE_STATUSES, type ComputeEffectiveStatusInput, type ContractWizardFlowType, type ContractWizardResubscribeOptions, type ContractWizardSubscribeOptions, type ContractWizardSubscriptionOptions, DEFAULT_API_BASE_URL, DEFAULT_OAUTH_SCOPES, EffectiveSubscriptionStatus, type FFIDAddMemberParams, type FFIDAddMemberRequest, type FFIDAddMemberResponse, FFIDAnnouncementsApiResponse, type FFIDAnnouncementsClient, FFIDAnnouncementsClientConfig, FFIDAnnouncementsLogger, FFIDApiResponse, type FFIDAssignableMemberRole, type FFIDBillingInterval, FFIDCacheAdapter, type FFIDCancelPendingDowngradeResponse, type FFIDCancelSubscriptionParams, type FFIDCancelSubscriptionResponse, type FFIDChangePlanParams, type FFIDChangePlanResponse, FFIDCheckServiceAccessParams, type FFIDCheckoutSessionResponse, type FFIDClient, FFIDConfig, type FFIDCreateCheckoutParams, type FFIDCreatePortalParams, FFIDError, type FFIDInquiryClient, FFIDInquiryCreateParams, FFIDInquiryCreateResponse, type FFIDListMembersResponse, type FFIDListPlansResponse, FFIDLogger, type FFIDMemberRole, type FFIDMemberStatus, type FFIDNewsletterBodySource, type FFIDNewsletterCampaignStatus, type FFIDNewsletterClient, type FFIDNewsletterConfirmParams, type FFIDNewsletterConfirmResponse, type FFIDNewsletterDispatchParams, type FFIDNewsletterDispatchResponse, type FFIDNewsletterSegment, type FFIDNewsletterSubscribeParams, type FFIDNewsletterSubscribeResponse, type FFIDNewsletterType, type FFIDNewsletterUnsubscribeParams, type FFIDNewsletterUnsubscribeResponse, FFIDOAuthUserInfo, FFIDOAuthUserInfoSubscription, FFIDOrganization, type FFIDOrganizationMember, type FFIDOtpSendResponse, type FFIDOtpVerifyResponse, type FFIDPasswordResetConfirmResponse, type FFIDPasswordResetResponse, type FFIDPasswordResetVerifyResponse, type FFIDPlanChangeLineItem, type FFIDPlanChangePreview, type FFIDPlanChangePreviewResponse, type FFIDPlanInfo, type FFIDPortalSessionResponse, type FFIDPreviewPlanChangeParams, type FFIDPreviewSeatChangeParams, FFIDProfileCallOptions, FFIDProvider, type FFIDProviderProps, FFIDRedirectResult, type FFIDRemoveMemberResponse, type FFIDResetSessionResponse, FFIDSDKError, type FFIDSeatChangeLineItem, type FFIDSeatChangePreview, type FFIDSeatChangePreviewResponse, FFIDServiceAccessDecision, type FFIDServiceInfo, FFIDSessionResponse, type FFIDSubscribeParams, type FFIDSubscribeResponse, FFIDSubscription, FFIDSubscriptionCheckResponse, FFIDSubscriptionContextValue, type FFIDSubscriptionDetail, FFIDSubscriptionStatus, type FFIDSubscriptionSummary, type FFIDSupportedCurrency, type FFIDUpdateMemberRoleResponse, FFIDUpdateUserProfileRequest, FFIDUser, FFIDUserProfile, FFIDVerifyAccessTokenOptions, FFID_ANNOUNCEMENTS_ERROR_CODES, FFID_NEWSLETTER_DISPATCH_MAX_RECIPIENTS, FFID_NEWSLETTER_TYPES, type KVNamespaceLike, ListAnnouncementsOptions, type NormalizeRedirectUriResult, type RedirectToAuthorizeOptions, type TokenData, type TokenStore, type UseFFIDReturn, type UseRequireActiveSubscriptionOptions, type UseRequireActiveSubscriptionReturn, type WithFFIDAuthOptions, type WithSubscriptionOptions, computeEffectiveStatusFromSession, createFFIDAnnouncementsClient, createFFIDClient, createKVCacheAdapter, createMemoryCacheAdapter, createTokenStore, generateCodeChallenge, generateCodeVerifier, hasAccessFromUserinfo, isBlockedFromUserinfo, normalizeRedirectUri, retrieveCodeVerifier, storeCodeVerifier, useFFID, useRequireActiveSubscription, useSubscription, withFFIDAuth, withSubscription };
2000
+ export { ACCESS_GRANTING_EFFECTIVE_STATUSES, AnnouncementListResponse, BLOCKING_EFFECTIVE_STATUSES, type ComputeEffectiveStatusInput, type ContractWizardFlowType, type ContractWizardResubscribeOptions, type ContractWizardSubscribeOptions, type ContractWizardSubscriptionOptions, DEFAULT_API_BASE_URL, DEFAULT_OAUTH_SCOPES, EffectiveSubscriptionStatus, type ExchangeCodeForTokensOptions, type FFIDAddMemberParams, type FFIDAddMemberRequest, type FFIDAddMemberResponse, FFIDAnnouncementsApiResponse, type FFIDAnnouncementsClient, FFIDAnnouncementsClientConfig, FFIDAnnouncementsLogger, FFIDApiResponse, type FFIDAssignableMemberRole, type FFIDBillingInterval, FFIDCacheAdapter, type FFIDCancelPendingDowngradeResponse, type FFIDCancelSubscriptionParams, type FFIDCancelSubscriptionResponse, type FFIDChangePlanParams, type FFIDChangePlanResponse, FFIDCheckServiceAccessParams, type FFIDCheckoutSessionResponse, type FFIDClient, FFIDConfig, type FFIDCreateCheckoutParams, type FFIDCreatePortalParams, FFIDError, type FFIDInquiryClient, FFIDInquiryCreateParams, FFIDInquiryCreateResponse, type FFIDInvitationStatus, type FFIDInviteMemberRequest, type FFIDInviteMemberResponse, type FFIDLeaveOrganizationParams, type FFIDLeaveOrganizationResponse, type FFIDListMembersResponse, type FFIDListPlansResponse, FFIDLogger, type FFIDLoginHistoryEntry, type FFIDLoginHistoryResponse, type FFIDMemberRole, type FFIDMemberStatus, type FFIDNewsletterBodySource, type FFIDNewsletterCampaignStatus, type FFIDNewsletterClient, type FFIDNewsletterConfirmParams, type FFIDNewsletterConfirmResponse, type FFIDNewsletterDispatchParams, type FFIDNewsletterDispatchResponse, type FFIDNewsletterSegment, type FFIDNewsletterSubscribeParams, type FFIDNewsletterSubscribeResponse, type FFIDNewsletterType, type FFIDNewsletterUnsubscribeParams, type FFIDNewsletterUnsubscribeResponse, FFIDOAuthUserInfo, FFIDOAuthUserInfoSubscription, FFIDOrganization, type FFIDOrganizationDomain, type FFIDOrganizationDomainsResponse, type FFIDOrganizationMember, type FFIDOrganizationNotificationPreferences, type FFIDOrganizationNotificationPreferencesResponse, type FFIDOtpSendResponse, type FFIDOtpVerifyResponse, type FFIDPasswordResetConfirmResponse, type FFIDPasswordResetResponse, type FFIDPasswordResetVerifyResponse, type FFIDPlanChangeLineItem, type FFIDPlanChangePreview, type FFIDPlanChangePreviewResponse, type FFIDPlanInfo, type FFIDPortalSessionResponse, type FFIDPreviewPlanChangeParams, type FFIDPreviewSeatChangeParams, type FFIDProfileCallOptions, FFIDProvider, type FFIDProviderProps, FFIDRedirectResult, type FFIDRemoveMemberResponse, type FFIDResetSessionResponse, FFIDSDKError, type FFIDSeatChangeLineItem, type FFIDSeatChangePreview, type FFIDSeatChangePreviewResponse, FFIDServiceAccessDecision, type FFIDServiceInfo, FFIDSessionResponse, type FFIDSubscribeParams, type FFIDSubscribeResponse, FFIDSubscription, FFIDSubscriptionCheckResponse, FFIDSubscriptionContextValue, type FFIDSubscriptionDetail, FFIDSubscriptionStatus, type FFIDSubscriptionSummary, type FFIDSupportedCurrency, type FFIDUpdateMemberRoleResponse, type FFIDUpdateNotificationPreferencesRequest, type FFIDUpdateUserProfileRequest, FFIDUser, type FFIDUserProfile, FFIDVerifyAccessTokenOptions, FFID_ANNOUNCEMENTS_ERROR_CODES, FFID_NEWSLETTER_DISPATCH_MAX_RECIPIENTS, FFID_NEWSLETTER_TYPES, type HandleRedirectCallbackClient, type HandleRedirectCallbackOptions, type KVNamespaceLike, ListAnnouncementsOptions, type NormalizeRedirectUriResult, type RedirectToAuthorizeOptions, type TokenData, type TokenStore, type UseFFIDReturn, type UseRequireActiveSubscriptionOptions, type UseRequireActiveSubscriptionReturn, type WithFFIDAuthOptions, type WithSubscriptionOptions, cleanupStateStorage as clearState, computeEffectiveStatusFromSession, createFFIDAnnouncementsClient, createFFIDClient, createKVCacheAdapter, createMemoryCacheAdapter, createTokenStore, generateCodeChallenge, generateCodeVerifier, handleRedirectCallback, hasAccessFromUserinfo, isBlockedFromUserinfo, normalizeRedirectUri, retrieveCodeVerifier, retrieveState, storeCodeVerifier, storeState, useFFID, useRequireActiveSubscription, useSubscription, withFFIDAuth, withSubscription };