central-auth-js-sdk 1.0.13 → 1.2.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.
@@ -13,7 +13,13 @@ npm install central-auth-js-sdk
13
13
  Use in your app (with a bundler such as Vite, Webpack, or Parcel):
14
14
 
15
15
  ```javascript
16
- import { initializeAuth, startSignup, startLogin } from 'central-auth-js-sdk';
16
+ import {
17
+ initializeAuth,
18
+ startSignup,
19
+ startLogin,
20
+ autoResumeOAuthFlow,
21
+ hasPendingOAuthRedirect,
22
+ } from 'central-auth-js-sdk';
17
23
  import 'central-auth-js-sdk/styles.css';
18
24
  ```
19
25
 
@@ -37,6 +43,8 @@ You need:
37
43
  2. The **SDK CSS** loaded (so the UI looks correct).
38
44
  3. A call to **`startSignup`** or **`startLogin`** with at least `container` and **`env`** (which backend to use: `local`, `dev`, `staging`, or `prod`). **`appIdentifier`** is optional; include it only if your backend expects it for OAuth or login APIs.
39
45
 
46
+ For **Google/Microsoft OAuth**, also call **`initializeAuth`** once with **`defaultContainer`** and **`autoResumeOAuth: true`** (default). After the user returns from the provider, the SDK mounts the correct step automatically — see [§ 12 OAuth redirect & auto-resume](#12-oauth-redirect--auto-resume).
47
+
40
48
  **Minimal signup example:**
41
49
 
42
50
  ```html
@@ -76,27 +84,37 @@ You need:
76
84
 
77
85
  | Function | Purpose |
78
86
  |----------|--------|
79
- | **`initializeAuth(config)`** | (Optional) Set default config once; `startSignup` / `startLogin` can override per call. |
87
+ | **`initializeAuth(config)`** | (Optional) Set default config once; enables OAuth auto-resume when `defaultContainer` is set. |
80
88
  | **`startSignup(config)`** | Run the sign-up flow in the given container. |
81
89
  | **`startLogin(config)`** | Run the login flow in the given container. |
90
+ | **`autoResumeOAuthFlow(config)`** | After Google/Microsoft redirect, mount login or signup from URL params. No-op if URL has no OAuth params. |
91
+ | **`hasPendingOAuthRedirect()`** | Returns `true` when the current URL contains OAuth callback query params. |
92
+
93
+ Lower-level helpers (optional): `parseOAuthRedirect()`, `getOAuthRedirectFlowType()`, `markOAuthRedirectPending()`, `OAUTH_PENDING_CLASS`.
82
94
 
83
- You can use **only** `startSignup` and `startLogin` and pass full config each time. Or call **`initializeAuth`** once and then call **`auth.startSignup({})`** / **`auth.startLogin({})`** so they use the stored defaults.
95
+ You can use **only** `startSignup` and `startLogin` and pass full config each time. Or call **`initializeAuth`** once and then call **`auth.startSignup({})`** / **`auth.startLogin({})`** so they use the stored defaults. For social login, prefer **`initializeAuth`** with **`autoResumeOAuth: true`** so the post-OAuth page reload is handled automatically.
84
96
 
85
97
  ---
86
98
 
87
99
  ## 4. initializeAuth(config)
88
100
 
89
- Call once (e.g. at app load) to set defaults. Returns `{ startSignup, startLogin, getConfig }`.
101
+ Call once (e.g. at app load) to set defaults. Returns `{ startSignup, startLogin, autoResumeOAuthFlow, hasPendingOAuthRedirect, getConfig }`.
102
+
103
+ When **`autoResumeOAuth`** is `true` (default) and **`defaultContainer`** is set, the SDK automatically calls **`autoResumeOAuthFlow`** on page load if the URL contains OAuth callback params (e.g. after Google redirects back).
90
104
 
91
105
  | Parameter | Type | Default | Description |
92
106
  |-----------|------|---------|-------------|
93
107
  | `env` | string | `'local'` | Environment: `'local'` \| `'dev'` \| `'staging'` \| `'prod'`. SDK uses the predefined API URL for that env. |
94
108
  | `appIdentifier` | string | — | Optional. When provided, sent with OAuth and login-related API requests; omit to not send `app_identifier`. |
95
- | `defaultContainer` | string \| HTMLElement | — | Default container; can override in `startSignup` / `startLogin` |
109
+ | `defaultContainer` | string \| HTMLElement | — | Default container; can override in `startSignup` / `startLogin`. **Required for OAuth auto-resume.** |
110
+ | `autoResumeOAuth` | boolean | `true` | When `true` and `defaultContainer` is set, auto-mount login/signup after OAuth redirect. |
96
111
  | `loginMethods` | object | — | Default login methods (see Login config) |
97
112
  | `frsAsSecondFactor` | boolean | `false` | Default: require face verification after primary auth |
98
113
  | `enableFaceRegistration` | boolean | `true` | Whether sign-up includes face registration step |
114
+ | `onContinue` | function | — | Default callback when user clicks Continue on success (see [§ 9](#9-returning-to-the-parent-application)) |
99
115
  | `onBack` | function | — | Default callback when user clicks ← Back on the first screen of signup/login (see [§ 9](#9-returning-to-the-parent-application)) |
116
+ | `onLoginComplete` | function | — | Default login-complete callback |
117
+ | `onSignupComplete` | function | — | Default signup-complete callback |
100
118
 
101
119
  **Environments:** The SDK uses only `env` to choose the API base URL:
102
120
 
@@ -116,12 +134,15 @@ const auth = initializeAuth({
116
134
  env: 'dev', // uses https://central-auth-dev.soham.ai/apis
117
135
  appIdentifier: 'my-app',
118
136
  defaultContainer: '#auth-container',
137
+ autoResumeOAuth: true,
119
138
  loginMethods: {
120
139
  emailPassword: true,
121
140
  emailOtp: true,
122
141
  social: { google: true, microsoft: true },
123
142
  },
124
143
  frsAsSecondFactor: true,
144
+ onContinue: goToApp,
145
+ onBack: goToApp,
125
146
  });
126
147
 
127
148
  // Later:
@@ -268,7 +289,7 @@ Starts the **login flow**. If the parent enables **only one** login method, the
268
289
  | `env` | string | no | Environment: `'local'` \| `'dev'` \| `'staging'` \| `'prod'` (default from init or `'local'`) |
269
290
  | `appIdentifier` | string | no | Optional. When provided, sent with login/OAuth API requests; omit to not send. |
270
291
  | **`loginMethods`** | object | no | Which login methods are enabled (see below) |
271
- | `frsAsSecondFactor` | boolean | no | Require face verification after password/OTP/social |
292
+ | `frsAsSecondFactor` | boolean | no | Require face verification after password/OTP/social (client-side). Domain-based 2FA from the backend is handled automatically — see [§ 12](#12-oauth-redirect--auto-resume). |
272
293
  | **`onSignUp()`** | function | no | Called when user clicks **Sign up** on the login screen (e.g. unmount login and start signup in the **same container**). |
273
294
  | **`onLoginComplete(payload)`** | function | no | Called **once** when login completes. `payload`: `identifier` + any fields from final API (e.g. `access_token`, `refresh_token`). |
274
295
  | **`onContinue()`** | function | no | Called when user clicks **Continue to application** on the success screen. |
@@ -288,6 +309,13 @@ Starts the **login flow**. If the parent enables **only one** login method, the
288
309
 
289
310
  **Email + FRS:** On the face capture screen, if the user has no webcam, they can click **“No webcam? Sign in with OTP instead”**. The SDK sends an OTP to the email they entered and switches to the OTP step so they can complete login without face capture. No extra configuration is required.
290
311
 
312
+ **Phone face capture:** If the user has no webcam, they can click **“Use phone instead”** on the face screen. The SDK shows a QR code + PIN and polls the backend until a face image is captured on the phone.
313
+
314
+ **Backend-driven 2FA (face as second factor):** When your backend requires face verification (e.g. domain policy for `@gmail.com`), it returns `two_factor_required: true` and a short-lived `fr_token`. The SDK shows the face capture screen and submits the image with `fr_token` to complete login. This applies to:
315
+
316
+ - **Password / OTP login** — response from `POST /login/custom` or `POST /otp/verify`
317
+ - **Google / Microsoft login** — query params on the OAuth redirect URL (see [§ 12](#12-oauth-redirect--auto-resume))
318
+
291
319
  **Example — single method (no method picker):**
292
320
 
293
321
  ```javascript
@@ -376,12 +404,26 @@ instance.unmount();
376
404
  ## 8. Getting tokens and details back
377
405
 
378
406
  - **Signup:** Pass **`onSignupComplete(payload)`**. The SDK calls it once when signup finishes. `payload` includes `email`, `mobile`, `userId` and whatever your **final signup API** returns (e.g. `access_token`, `refresh_token`). Your backend should return these in the final signup response (e.g. `POST /signup/fr/enroll`).
379
- - **Login:** Pass **`onLoginComplete(payload)`**. The SDK calls it once when login finishes. `payload` includes `identifier` and whatever your **final login API** returns (e.g. `access_token`, `refresh_token`). Your backend should return these in the final login response (e.g. `POST /login/custom`, `POST /otp/verify`, etc.).
407
+ - **Login:** Pass **`onLoginComplete(payload)`**. The SDK calls it once when login finishes. `payload` includes `identifier` and whatever your **final login API** returns (e.g. `access_token`, `refresh_token`, `token`). Your backend should return these in the final login response (e.g. `POST /login/custom`, `POST /otp/verify`, `POST /login/google/fr/enroll`, etc.).
408
+ - **OAuth login complete:** When the backend redirects with `token=...` (JWT) and no further steps, the SDK lands on the success screen and includes `token`, `email`, `user_id`, etc. in the payload passed to **`onLoginComplete`**.
380
409
 
381
410
  You can also read **`instance.getState()`** after the flow completes; it includes **`signupResult`** or **`loginResult`** (the raw final API response).
382
411
 
383
412
  ---
384
413
 
414
+ ## 8.1 Troubleshooting Callbacks
415
+
416
+ If you are not receiving the `onLoginComplete` callback, check the following common issues:
417
+
418
+ 1. **Social Login (OAuth) Page Reloads:** Social login requires a full browser redirect. If you only pass `onLoginComplete` to `startLogin()`, it will be lost when the page reloads. You **must** pass `onLoginComplete` directly into `initializeAuth()` so the SDK can trigger it when it auto-resumes the OAuth flow.
419
+ 2. **Differing Payload Structures:** The `payload` object returned by `onLoginComplete(payload)` differs slightly depending on the method.
420
+ - Standard logins (Password/OTP/FRS) return the exact API response (e.g. `payload.access_token`).
421
+ - Social Login returns URL params (e.g. `payload.token`).
422
+ - Always check for both (e.g., `payload.token || payload.access_token`) to prevent undefined errors in your callback.
423
+ 3. **FRS Fallbacks:** If a user uses an FRS fallback ("Sign in with OTP instead" or "Use phone instead"), the SDK automatically handles the fallback and **still fires `onLoginComplete`** upon successful authentication. No separate callback handles these cases.
424
+
425
+ ---
426
+
385
427
  ## 9. Returning to the parent application
386
428
 
387
429
  The SDK does **not** automatically navigate your app when the user leaves auth. Your parent app is responsible for showing/hiding the auth container and routing the user back to your own UI. Use the callbacks below.
@@ -462,80 +504,67 @@ Returning to the parent app is **not automatic** beyond SDK unmount. Integrators
462
504
  ## 10. Full integration example
463
505
 
464
506
  ```javascript
465
- import { initializeAuth, startSignup, startLogin } from 'central-auth-js-sdk';
507
+ import { initializeAuth } from 'central-auth-js-sdk';
466
508
  import 'central-auth-js-sdk/styles.css';
467
509
 
510
+ let currentInstance = null;
511
+
512
+ function goToApp() {
513
+ if (currentInstance) currentInstance.unmount();
514
+ currentInstance = null;
515
+ document.getElementById('auth-container').style.display = 'none';
516
+ document.getElementById('app-root').style.display = 'block';
517
+ }
518
+
519
+ function saveToken(token) {
520
+ if (token) localStorage.setItem('access_token', token);
521
+ }
522
+
468
523
  const auth = initializeAuth({
469
524
  env: 'dev',
470
525
  appIdentifier: 'my-app',
471
526
  defaultContainer: '#auth-container',
527
+ autoResumeOAuth: true, // auto-mount after Google/Microsoft redirect
472
528
  loginMethods: {
473
529
  emailPassword: true,
474
530
  emailOtp: true,
475
531
  social: { google: true, microsoft: true },
476
532
  emailFrs: true,
477
533
  },
478
- frsAsSecondFactor: false,
534
+ onLoginComplete(payload) {
535
+ saveToken(payload.token || payload.access_token);
536
+ },
537
+ onSignupComplete(payload) {
538
+ saveToken(payload.access_token);
539
+ },
540
+ onContinue: goToApp,
541
+ onBack: goToApp,
479
542
  });
480
543
 
481
- let currentInstance = null;
482
-
483
- function goToApp() {
484
- if (currentInstance) currentInstance.unmount();
485
- currentInstance = null;
486
- document.getElementById('auth-container').style.display = 'none';
487
- document.getElementById('app-root').style.display = 'block';
488
- }
489
-
490
544
  function showSignup() {
491
545
  if (currentInstance) currentInstance.unmount();
492
546
  document.getElementById('auth-container').style.display = 'block';
547
+ document.getElementById('app-root').style.display = 'none';
493
548
  currentInstance = auth.startSignup({
494
- onSignupComplete(payload) {
495
- saveToken(payload.access_token);
496
- goToApp();
497
- },
498
- onContinue: goToApp,
499
- onBack: goToApp,
500
- onSwitchToLogin: showLoginFrs,
501
- });
502
- }
503
-
504
- function showLoginFrs() {
505
- if (currentInstance) currentInstance.unmount();
506
- document.getElementById('auth-container').style.display = 'block';
507
- currentInstance = auth.startLogin({
508
- loginMethods: { emailFrs: true },
509
- onLoginComplete(payload) {
510
- saveToken(payload.access_token);
511
- goToApp();
512
- },
513
- onContinue: goToApp,
514
- onBack: goToApp,
515
- onSignUp: showSignup,
549
+ onSwitchToLogin: () => showLogin({ emailFrs: true }),
516
550
  });
517
551
  }
518
552
 
519
553
  function showLogin(loginMethods = { emailPassword: true }) {
520
554
  if (currentInstance) currentInstance.unmount();
521
555
  document.getElementById('auth-container').style.display = 'block';
556
+ document.getElementById('app-root').style.display = 'none';
522
557
  currentInstance = auth.startLogin({
523
558
  loginMethods,
524
- onLoginComplete(payload) {
525
- saveToken(payload.access_token);
526
- goToApp();
527
- },
528
- onContinue: goToApp,
529
- onBack: goToApp,
530
559
  onSignUp: showSignup,
531
560
  });
532
561
  }
533
562
 
534
- function saveToken(token) {
535
- if (token) localStorage.setItem('access_token', token);
563
+ // If OAuth redirect params are present, initializeAuth already resumed the flow.
564
+ // Otherwise show your normal entry point:
565
+ if (!auth.hasPendingOAuthRedirect()) {
566
+ showLogin();
536
567
  }
537
-
538
- showLogin();
539
568
  ```
540
569
 
541
570
  ---
@@ -544,8 +573,137 @@ showLogin();
544
573
 
545
574
  - **CORS:** Your API must allow requests from your app’s origin (e.g. `Access-Control-Allow-Origin`).
546
575
  - **Signup:** The SDK calls your signup endpoints (e.g. `/signup/start`, `/signup/email/verify`, `/signup/fr/enroll`). The **final** response can include `access_token`, `refresh_token`, etc.; the SDK forwards them in `onSignupComplete(payload)` and `getState().signupResult`.
547
- - **Login:** The SDK calls your login endpoints (e.g. `/login/custom`, `/otp/verify`, `/login/email/fr`). The **final** response can include tokens; the SDK forwards them in `onLoginComplete(payload)` and `getState().loginResult`.
548
- - **OAuth:** For Google/Microsoft, configure your backend with the same redirect URI your app uses. The SDK reads `login_token` and `provider` from the URL after redirect and continues the flow.
576
+ - **Login:** The SDK calls your login endpoints (e.g. `/login/custom`, `/otp/verify`, `/login/email/fr`, `/login/google/fr/enroll`). The **final** response can include tokens; the SDK forwards them in `onLoginComplete(payload)` and `getState().loginResult`.
577
+ - **2FA (face verification):** When face verification is required, the backend returns (JSON body or OAuth redirect query params):
578
+
579
+ ```json
580
+ {
581
+ "success": true,
582
+ "two_factor_required": true,
583
+ "next_step": "FR_VERIFICATION",
584
+ "login_token": "...",
585
+ "fr_token": "...",
586
+ "fr_token_expires_in_s": 300,
587
+ "message": "Facial recognition verification required"
588
+ }
589
+ ```
590
+
591
+ The SDK shows the face capture screen and submits `fr_token` + face image to the appropriate endpoint (e.g. `POST /login/google/fr/enroll` for social, `POST /login/custom` with `fr_image` for password login).
592
+ - **OAuth:** Start Google/Microsoft login with `redirect_uri` pointing to the page where your SDK loads. After auth, the backend **302-redirects** to that URL with query params — see [§ 12](#12-oauth-redirect--auto-resume). The SDK reads those params and continues the flow (face verification, success, or error). Same behavior for Microsoft OAuth.
549
593
  - **app_identifier:** When the parent app passes **`appIdentifier`**, the SDK sends it as `app_identifier` on login-related requests (e.g. `/login/custom`, `/login/email/fr`, OAuth start URLs, social mobile/FR). If the parent omits it, the SDK does not send the parameter.
550
594
 
551
595
  For endpoint details and request/response shapes, see **API_INTEGRATION.md** and your backend docs.
596
+
597
+ ---
598
+
599
+ ## 12. OAuth redirect & auto-resume
600
+
601
+ Google and Microsoft login use a full-page redirect. When the user returns, the browser reloads your app with query params on the URL. **The SDK handles parsing, routing, and cleanup** — you do not need custom “if URL has `login_token` then …” logic in your app.
602
+
603
+ ### What the parent app must do
604
+
605
+ 1. Call **`initializeAuth({ defaultContainer, autoResumeOAuth: true, ... })`** once at app load, **or** call **`autoResumeOAuthFlow({ container, ... })`** when your app boots.
606
+ 2. Pass the same **`redirect_uri`** to OAuth start that your app uses as the return page (the SDK builds this as `window.location.origin + window.location.pathname` when the user clicks Google/Microsoft).
607
+ 3. Provide **`onContinue`**, **`onBack`**, and optionally **`onLoginComplete`** callbacks.
608
+
609
+ The SDK does **not** navigate your main app UI automatically. Hide/show your app shell in those callbacks (see [§ 9](#9-returning-to-the-parent-application)).
610
+
611
+ ### Optional: reduce “home screen flash” after OAuth
612
+
613
+ When OAuth params are detected, the SDK adds **`central-auth-oauth-pending`** to `<html>`. Hide your main UI while the SDK loads:
614
+
615
+ ```css
616
+ html.central-auth-oauth-pending [data-central-auth-main] {
617
+ display: none !important;
618
+ }
619
+ html.central-auth-oauth-pending [data-central-auth-sdk] {
620
+ display: flex !important;
621
+ }
622
+ ```
623
+
624
+ Mark your main content with `data-central-auth-main` and your auth container wrapper with `data-central-auth-sdk`.
625
+
626
+ For the earliest possible switch (before the SDK module loads), you can add a tiny inline script in `<head>` that sets the same class when OAuth params are present — the demo app uses this pattern.
627
+
628
+ ### Backend redirect examples
629
+
630
+ After Google auth, the backend redirects to your `redirect_uri` with query params:
631
+
632
+ **Login complete:**
633
+
634
+ ```
635
+ https://yourapp.com/auth?success=true&provider=google&token=eyJ...&user_id=...&email=...&entity_domain=gmail.com&message=Login+successful
636
+ ```
637
+
638
+ **2FA — face verification required:**
639
+
640
+ ```
641
+ https://yourapp.com/auth?success=true&two_factor_required=true&provider=google&next_step=FR_VERIFICATION&login_token=...&fr_token=...&fr_token_expires_in_s=300&message=Facial+recognition+verification+required&user_id=...&entity_domain=gmail.com
642
+ ```
643
+
644
+ **Signup — face enrollment required:**
645
+
646
+ ```
647
+ https://yourapp.com/auth?success=true&provider=google&next_step=FR_ENROLLMENT&login_token=...&user_id=...&entity_domain=gmail.com&message=Facial+recognition+enrollment+required
648
+ ```
649
+
650
+ **Signup — mobile verification:**
651
+
652
+ ```
653
+ https://yourapp.com/auth?success=true&provider=google&next_step=MOBILE_VERIFICATION&login_token=...&user_id=...
654
+ ```
655
+
656
+ **Error:**
657
+
658
+ ```
659
+ https://yourapp.com/auth?success=false&provider=google&error=Entity+not+found+for+email+domain+gmail.com
660
+ ```
661
+
662
+ ### How the SDK routes each case
663
+
664
+ | Redirect | SDK action |
665
+ |----------|------------|
666
+ | `two_factor_required=true` or `next_step=FR_VERIFICATION` | Login flow → **face capture** → `POST /login/{google\|microsoft}/fr/enroll` with `login_token`, `fr_token`, `fr_image` |
667
+ | `token=...` (login complete) | Login flow → **success screen** → `onLoginComplete` with JWT |
668
+ | `next_step=FR_ENROLLMENT` | Signup flow → **face enrollment** |
669
+ | `next_step=MOBILE_VERIFICATION` | Signup flow → **mobile entry** |
670
+ | `success=false` or `error=...` | Login flow → show error banner |
671
+ | Params cleaned from URL | SDK removes OAuth query params via `history.replaceState` (no reload) |
672
+
673
+ ### End-to-end flow (Google login + 2FA)
674
+
675
+ ```
676
+ User clicks "Continue with Google"
677
+ → GET /login/google/start?redirect_uri=...&app_identifier=...
678
+ → Google OAuth
679
+ → Backend 302 to your app with two_factor_required=true, login_token, fr_token, ...
680
+ → SDK auto-resumes (face capture screen)
681
+ → User captures face
682
+ → POST /login/google/fr/enroll
683
+ → Success screen
684
+ → User clicks Continue → onContinue() → your app
685
+ ```
686
+
687
+ ### Manual auto-resume (without initializeAuth)
688
+
689
+ ```javascript
690
+ import { autoResumeOAuthFlow, hasPendingOAuthRedirect } from 'central-auth-js-sdk';
691
+
692
+ if (hasPendingOAuthRedirect()) {
693
+ const resumed = autoResumeOAuthFlow({
694
+ container: '#auth-container',
695
+ env: 'dev',
696
+ appIdentifier: 'my-app',
697
+ onContinue: goToApp,
698
+ onBack: goToApp,
699
+ });
700
+ if (resumed) {
701
+ currentInstance = resumed.instance;
702
+ // resumed.flow is 'login' or 'signup'
703
+ }
704
+ }
705
+ ```
706
+
707
+ ### Persist `env` across OAuth reload
708
+
709
+ OAuth causes a **full page reload**, so in-memory state is lost. Store `env` (and `appIdentifier` if needed) in **`sessionStorage`** before redirecting to Google, and pass the same values to **`autoResumeOAuthFlow`** or **`initializeAuth`**. The demo app uses `sessionStorage` for this.
package/auth.js CHANGED
@@ -4,12 +4,23 @@
4
4
  */
5
5
 
6
6
  import { resolveApiBaseUrl } from './core/env-config.js';
7
+ import {
8
+ hasOAuthRedirect,
9
+ parseOAuthRedirect,
10
+ getOAuthRedirectFlowType,
11
+ markOAuthRedirectPending,
12
+ clearOAuthRedirectPendingMark,
13
+ } from './core/oauth-redirect.js';
7
14
  import { mount } from './signup.js';
8
15
  import { mountLogin } from './login.js';
9
16
 
10
17
  /** Default configuration stored after initializeAuth() */
11
18
  let defaultConfig = {};
12
19
 
20
+ const DEFAULT_SOCIAL_LOGIN_METHODS = {
21
+ social: { google: true, microsoft: true },
22
+ };
23
+
13
24
  /**
14
25
  * Merge config with defaults. Passed config overrides defaults.
15
26
  * @param {Object} overrides - config passed to startSignup / startLogin
@@ -42,38 +53,99 @@ function resolveContainer(container) {
42
53
  return el && el.nodeType === 1 ? el : null;
43
54
  }
44
55
 
56
+ /**
57
+ * Resume login or signup automatically after an OAuth redirect.
58
+ * No-op when the URL has no OAuth callback params.
59
+ *
60
+ * @param {Object} [config] - Merged with initializeAuth defaults
61
+ * @param {string|HTMLElement} [config.container] - Required unless defaultContainer was set in initializeAuth
62
+ * @returns {{ flow: 'login'|'signup', instance: Object }|null}
63
+ */
64
+ export function autoResumeOAuthFlow(config = {}) {
65
+ if (!hasOAuthRedirect()) return null;
66
+
67
+ markOAuthRedirectPending();
68
+
69
+ const merged = mergeConfig(config);
70
+ const container = config.container ?? merged.defaultContainer;
71
+ const el = resolveContainer(container);
72
+ if (!el) {
73
+ console.warn('[Central Auth SDK] autoResumeOAuthFlow: container is required (pass config.container or set defaultContainer in initializeAuth)');
74
+ return null;
75
+ }
76
+
77
+ const redirect = parseOAuthRedirect();
78
+ const flowType = getOAuthRedirectFlowType(redirect) || 'login';
79
+
80
+ let instance = null;
81
+ if (flowType === 'signup') {
82
+ instance = startSignup({ ...config, container: el });
83
+ } else {
84
+ instance = startLogin({
85
+ ...config,
86
+ container: el,
87
+ loginMethods: config.loginMethods ?? merged.loginMethods ?? DEFAULT_SOCIAL_LOGIN_METHODS,
88
+ });
89
+ }
90
+
91
+ if (instance) {
92
+ clearOAuthRedirectPendingMark();
93
+ return { flow: flowType, instance };
94
+ }
95
+ return null;
96
+ }
97
+
45
98
  /**
46
99
  * Initialize the SDK with optional default configuration.
47
100
  * Call this once (e.g. at app load) to set shared defaults; startSignup/startLogin can override per call.
48
101
  *
102
+ * When `autoResumeOAuth` is true (default) and `defaultContainer` is set, the SDK automatically
103
+ * mounts the correct flow after Google/Microsoft OAuth redirects back to your app.
104
+ *
49
105
  * @param {Object} config - Default static configuration
50
106
  * @param {string} [config.env='local'] - Environment: 'local' | 'dev' | 'staging' | 'prod' — SDK uses the predefined API URL for that env
51
107
  * @param {string} [config.appIdentifier] - Optional app identifier for OAuth / custom login; only sent when provided
52
108
  * @param {string|HTMLElement} [config.defaultContainer] - Default container for rendering (can be overridden in start*)
109
+ * @param {boolean} [config.autoResumeOAuth=true] - Auto-mount login/signup when OAuth redirect params are in the URL
53
110
  * @param {Object} [config.loginMethods] - Default enabled login methods (see startLogin)
54
111
  * @param {boolean} [config.frsAsSecondFactor] - Default for FRS as second factor (see startLogin)
55
112
  * @param {boolean} [config.enableFaceRegistration=true] - Whether sign-up flow includes face registration step
56
113
  * @param {Object} [config.theme] - Optional theme overrides (primaryColor, secondaryColor, backgroundColor, backgroundImage, cardColor, textColor, fontFamily, mode)
57
- * @returns {{ startSignup: Function, startLogin: Function, getConfig: Function }}
114
+ * @returns {{ startSignup: Function, startLogin: Function, autoResumeOAuthFlow: Function, hasPendingOAuthRedirect: Function, getConfig: Function }}
58
115
  */
59
116
  export function initializeAuth(config = {}) {
60
117
  defaultConfig = {
61
118
  env: 'local',
62
119
  appIdentifier: undefined,
63
120
  defaultContainer: null,
121
+ autoResumeOAuth: true,
64
122
  loginMethods: null,
65
123
  frsAsSecondFactor: false,
66
124
  enableFaceRegistration: true,
67
125
  theme: null,
68
126
  ...config,
69
127
  };
70
- return {
71
- startSignup: startSignup,
72
- startLogin: startLogin,
128
+
129
+ const api = {
130
+ startSignup,
131
+ startLogin,
132
+ autoResumeOAuthFlow,
133
+ hasPendingOAuthRedirect: hasOAuthRedirect,
73
134
  getConfig() {
74
135
  return { ...defaultConfig };
75
136
  },
76
137
  };
138
+
139
+ if (defaultConfig.autoResumeOAuth !== false && defaultConfig.defaultContainer && hasOAuthRedirect()) {
140
+ const run = () => { autoResumeOAuthFlow({}); };
141
+ if (typeof document !== 'undefined' && document.readyState === 'loading') {
142
+ document.addEventListener('DOMContentLoaded', run, { once: true });
143
+ } else {
144
+ run();
145
+ }
146
+ }
147
+
148
+ return api;
77
149
  }
78
150
 
79
151
  /**
@@ -100,6 +172,7 @@ export function startSignup(config = {}) {
100
172
  return null;
101
173
  }
102
174
  const options = {
175
+ env: merged.env,
103
176
  apiBaseUrl: resolveApiBaseUrl(merged),
104
177
  appIdentifier: merged.appIdentifier,
105
178
  enableFaceRegistration: merged.enableFaceRegistration,
@@ -145,6 +218,7 @@ export function startLogin(config = {}) {
145
218
  return null;
146
219
  }
147
220
  const options = {
221
+ env: merged.env,
148
222
  apiBaseUrl: resolveApiBaseUrl(merged),
149
223
  appIdentifier: merged.appIdentifier,
150
224
  loginMethods: merged.loginMethods,
package/core/api.js CHANGED
@@ -116,12 +116,13 @@ export function createApi(baseUrl = DEFAULT_BASE, options = {}) {
116
116
  return request('POST', '/login/google/mobile/verify', body);
117
117
  },
118
118
 
119
- async googleFrEnroll(loginToken, frImageFile1, frImageFile2 = null, appIdentifier) {
119
+ async googleFrEnroll(loginToken, frImageFile1, frImageFile2 = null, appIdentifier, frToken = null) {
120
120
  const fd = new FormData();
121
121
  fd.append('login_token', loginToken);
122
122
  fd.append('fr_image', frImageFile1);
123
123
  fd.append('fr_image2', frImageFile2 || frImageFile1);
124
124
  if (appIdentifier) fd.append('app_identifier', appIdentifier);
125
+ if (frToken) fd.append('fr_token', frToken);
125
126
  return request('POST', '/login/google/fr/enroll', fd);
126
127
  },
127
128
 
@@ -137,19 +138,20 @@ export function createApi(baseUrl = DEFAULT_BASE, options = {}) {
137
138
  return request('POST', '/login/microsoft/mobile/verify', body);
138
139
  },
139
140
 
140
- async microsoftFrEnroll(loginToken, frImageFile1, frImageFile2 = null, appIdentifier) {
141
+ async microsoftFrEnroll(loginToken, frImageFile1, frImageFile2 = null, appIdentifier, frToken = null) {
141
142
  const fd = new FormData();
142
143
  fd.append('login_token', loginToken);
143
144
  fd.append('fr_image', frImageFile1);
144
145
  fd.append('fr_image2', frImageFile2 || frImageFile1);
145
146
  if (appIdentifier) fd.append('app_identifier', appIdentifier);
147
+ if (frToken) fd.append('fr_token', frToken);
146
148
  return request('POST', '/login/microsoft/fr/enroll', fd);
147
149
  },
148
150
 
149
151
  // --- Login (custom, OTP, email+FR) ---
150
152
 
151
153
  /** POST /login/custom — Email or mobile + password; optional fr_image, fr_image2 for FRS. app_identifier only when provided. */
152
- async loginCustom(identifier, password, appIdentifier, frImageFiles = null) {
154
+ async loginCustom(identifier, password, appIdentifier, frImageFiles = null, frToken = null) {
153
155
  const body = { identifier, password };
154
156
  if (appIdentifier) body.app_identifier = appIdentifier;
155
157
  if (frImageFiles && frImageFiles.length) {
@@ -157,6 +159,7 @@ export function createApi(baseUrl = DEFAULT_BASE, options = {}) {
157
159
  fd.append('identifier', identifier);
158
160
  fd.append('password', password);
159
161
  if (appIdentifier) fd.append('app_identifier', appIdentifier);
162
+ if (frToken) fd.append('fr_token', frToken);
160
163
  fd.append('fr_image', frImageFiles[0]);
161
164
  fd.append('fr_image2', frImageFiles[1] || frImageFiles[0]);
162
165
  return request('POST', '/login/custom', fd);
@@ -170,13 +173,14 @@ export function createApi(baseUrl = DEFAULT_BASE, options = {}) {
170
173
  },
171
174
 
172
175
  /** POST /otp/verify — optional frImageFiles for 2FA */
173
- async otpVerify(identifier, domain, channel, otp, frImageFiles = null) {
176
+ async otpVerify(identifier, domain, channel, otp, frImageFiles = null, frToken = null) {
174
177
  if (frImageFiles && frImageFiles.length) {
175
178
  const fd = new FormData();
176
179
  fd.append('identifier', identifier);
177
180
  if (domain) fd.append('domain', domain);
178
181
  fd.append('channel', channel);
179
182
  fd.append('otp', otp);
183
+ if (frToken) fd.append('fr_token', frToken);
180
184
  fd.append('fr_image', frImageFiles[0]);
181
185
  fd.append('fr_image2', frImageFiles[1] || frImageFiles[0]);
182
186
  return request('POST', '/otp/verify', fd);
@@ -112,9 +112,10 @@ export class LoginFlowController {
112
112
  }
113
113
 
114
114
  /** After social OAuth callback: we're in social flow, optionally at FRS */
115
- setSocialCallback(provider) {
115
+ setSocialCallback(provider, { twoFactorRequired = false } = {}) {
116
116
  this.currentMethod = provider === 'microsoft' ? LOGIN_METHODS.SOCIAL_MICROSOFT : LOGIN_METHODS.SOCIAL_GOOGLE;
117
- this.steps = getStepsForMethod(this.currentMethod, this.config.frsAsSecondFactor);
117
+ const useFrs = twoFactorRequired || this.config.frsAsSecondFactor;
118
+ this.steps = getStepsForMethod(this.currentMethod, useFrs);
118
119
  this.stepIndex = 0;
119
120
  this._notify();
120
121
  }
@@ -12,6 +12,9 @@ export class LoginStateManager {
12
12
  faceCapture: null,
13
13
  loginToken: null,
14
14
  socialProvider: null,
15
+ frToken: null,
16
+ frTokenExpiresInS: null,
17
+ twoFactorMessage: '',
15
18
  error: '',
16
19
  };
17
20
  this.listeners = new Set();