@sparkvault/sdk-js 8.7.0 → 8.8.1

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.ts CHANGED
@@ -118,6 +118,13 @@ interface VerifyOptions {
118
118
  chrome?: 'card' | 'bare';
119
119
  /** Auth context for OIDC/simple mode flows (used by hosted login) */
120
120
  authContext?: AuthContext;
121
+ /**
122
+ * How sign-in leaves this page. `'auto'` (default) and `'popup'` open the
123
+ * first-party popup; `'redirect'` navigates this tab to the sign-in page
124
+ * instead (its return leg is `handleRedirectResult()`) — the opt-out for
125
+ * hosts that prefer a full-page redirect over a popup on mobile.
126
+ */
127
+ flow?: 'auto' | 'popup' | 'redirect';
121
128
  /**
122
129
  * Rendering strategy (internal). `'local'` renders the flow directly in this
123
130
  * document — used inside the popup that runs the flow, and forced for inline
@@ -196,6 +203,20 @@ interface VerifyResult {
196
203
  type SignInOptions = Omit<VerifyOptions, 'target' | 'renderMode' | 'chrome'>;
197
204
  /** The verified identity returned by `signIn()`. */
198
205
  type SignInResult = VerifyResult;
206
+ /**
207
+ * Options for `handleRedirectResult()` — call once on every page load. It
208
+ * redeems a returned sign-in code (from `flow: 'redirect'` or the silent SSO
209
+ * self-heal) and, when a popup result was lost, triggers that self-heal. It
210
+ * no-ops otherwise.
211
+ */
212
+ interface RedirectResultOptions {
213
+ /** Called with the verified result when a returned sign-in code is redeemed */
214
+ onSuccess?: (result: VerifyResult) => void;
215
+ /** Called when redeeming a returned sign-in code failed */
216
+ onError?: (error: Error) => void;
217
+ /** Called when the person cancelled sign-in on the hosted page */
218
+ onCancel?: () => void;
219
+ }
199
220
  interface TokenClaims {
200
221
  /** Issuer */
201
222
  iss: string;
@@ -337,12 +358,18 @@ declare class IdentityModule {
337
358
  /** Whether this browser exposes the FedCM API (`navigator.credentials` + IdentityCredential). */
338
359
  static isFedcmAvailable(): boolean;
339
360
  /**
340
- * Open the SparkVault sign-in popup and resolve with the verified identity.
361
+ * Sign in through the first-party SparkVault sign-in popup.
341
362
  *
342
363
  * This is the single programmatic entry point; `attach()` binds it to element
343
- * clicks. There is no inline/in-page mode — sign-in always runs in the
344
- * first-party popup on the Identity origin, so login's `__Host-` hub cookie is
345
- * a first-party write and cross-domain SSO works.
364
+ * clicks. The popup runs the flow top-level on the Identity origin (so
365
+ * login's `__Host-` hub cookie is a first-party write and cross-domain SSO
366
+ * works) and posts the result back — the promise resolves with it.
367
+ *
368
+ * Resilience: pair this with `handleRedirectResult()` on page load. If the
369
+ * popup's result is ever lost (a mobile browser discards the backgrounded
370
+ * opener tab), the next load silently self-heals from the SSO session the
371
+ * login established. `flow: 'redirect'` opts a caller out of the popup into a
372
+ * same-tab navigation instead.
346
373
  *
347
374
  * @example
348
375
  * const result = await sv.products.identity.signIn();
@@ -350,9 +377,10 @@ declare class IdentityModule {
350
377
  */
351
378
  signIn(options?: SignInOptions): Promise<SignInResult>;
352
379
  /**
353
- * Core flow runner. Dialog mode (no `target`) opens the popup; local mode
354
- * (`renderMode: 'local'` / `target`) renders into the current document and
355
- * powers the SparkVault-hosted sign-in surfaces (see the internal `render`).
380
+ * Core flow runner. Default mode (no `target`) opens the popup; `flow:
381
+ * 'redirect'` navigates the tab instead; local mode (`renderMode: 'local'` /
382
+ * `target`) renders into the current document and powers the
383
+ * SparkVault-hosted sign-in surfaces (see the internal `render`).
356
384
  */
357
385
  private runFlow;
358
386
  /**
@@ -387,13 +415,68 @@ declare class IdentityModule {
387
415
  */
388
416
  decodeToken(token: string): TokenClaims;
389
417
  /**
390
- * Complete full-page redirect results produced by social-login flows.
391
- * The Identity Product redirects back with `#token=...` so the token does
392
- * not hit server logs. Consume it once, run the unverified client-side decode
393
- * (issuer/audience/expiry/alg sanity-check — NOT signature verification), then
394
- * remove it from the URL bar. The host must still verify the token server-side
395
- * via the Identity JWKS before trusting any claim.
396
- */
418
+ * Complete a sign-in on page load — the return leg of `signIn()`. Call once
419
+ * on every page load; it resolves `null` when there is nothing to do.
420
+ *
421
+ * It handles two cases:
422
+ * 1. A one-time code is in the URL fragment (`#sv_code=…`) — the popup's
423
+ * result was lost and self-heal navigated here, or `flow: 'redirect'`
424
+ * returned. Redeem it server-side and hand the full result to
425
+ * `onSuccess` (and resolve with it).
426
+ * 2. A sign-in was in flight but never delivered (a mobile browser
427
+ * discarded the backgrounded opener tab, killing the popup's
428
+ * postMessage) — silently re-mint from the SSO session the completed
429
+ * popup login established, by navigating this tab through the silent SSO
430
+ * endpoint and straight back with a code (case 1 on return). Nothing is
431
+ * shown; if there is no live session it comes back logged-out, no oracle.
432
+ *
433
+ * The code is one-time, PKCE-bound, and origin-locked — never the token. The
434
+ * host must still verify `result.token` server-side via the Identity JWKS.
435
+ *
436
+ * @example Call on page load; sign-in clicks stay unchanged.
437
+ * sv.products.identity.handleRedirectResult({
438
+ * onSuccess: (result) => createSession(result.token),
439
+ * }).catch((error) => showError(error));
440
+ */
441
+ handleRedirectResult(options?: RedirectResultOptions): Promise<SignInResult | null>;
442
+ /** Redeem a returned `#sv_code` (or surface a returned `#sv_error`). */
443
+ private consumeHandoffFragment;
444
+ /**
445
+ * Silently re-mint the sign-in result from the SSO session the completed
446
+ * popup login left behind. Navigates this tab through the silent SSO endpoint
447
+ * (a top-level GET, so the `SameSite=Lax` hub cookie rides along) which,
448
+ * PKCE-bound, returns a one-time code in the fragment — handled by case 1 on
449
+ * return. No-op (stays put) if session storage or WebCrypto is unavailable,
450
+ * so a hostile/degraded environment simply never recovers rather than
451
+ * erroring.
452
+ */
453
+ private startRecoveryBounce;
454
+ /**
455
+ * Explicit `flow: 'redirect'` — navigate this tab to the interactive sign-in
456
+ * page. Plain sign-in carries redirect_uri + state + PKCE challenge and
457
+ * returns via the fragment code; OIDC/simple modes navigate bare (their
458
+ * server-rendered pages drive the server-validated redirect back).
459
+ *
460
+ * @returns false when the return leg cannot be armed (no session storage or
461
+ * WebCrypto) — the caller surfaces an actionable error instead of a
462
+ * silent dead-end.
463
+ */
464
+ private startRedirectFlow;
465
+ /**
466
+ * Arm the PKCE + state return leg for a handoff navigation and return the URL
467
+ * to navigate to (redirect_uri = this exact page; query preserved for app
468
+ * state, fragment dropped since it is the result channel). Returns null when
469
+ * session storage or WebCrypto is unavailable so callers can degrade.
470
+ */
471
+ private prepareHandoffNavigation;
472
+ private markSignInPending;
473
+ private clearSignInPending;
474
+ /** True once (then cleared) if a recent sign-in is still awaiting its result. */
475
+ private consumeSignInPending;
476
+ /** Remove the result fragment from the URL bar (and history entry). */
477
+ private clearUrlFragment;
478
+ /** Drop the one-shot PKCE state/verifier a redirect bounce staged. */
479
+ private clearOneShotAuthState;
397
480
  private consumeRedirectResult;
398
481
  /**
399
482
  * Close the identity dialog/inline UI if open.
@@ -1826,6 +1909,15 @@ declare class SparkVault {
1826
1909
  * });
1827
1910
  */
1828
1911
  static init(config: SparkVaultConfig): SparkVault;
1912
+ /**
1913
+ * Whether a sign-in needs completing on this page load — a returned handoff
1914
+ * fragment, or a popup whose result was lost (a mobile opener-tab discard).
1915
+ * Side effect-free and instance-free, so a host that defers SDK init for
1916
+ * performance can cheaply decide whether to boot the SDK and call
1917
+ * `products.identity.handleRedirectResult()` on a given load, without reaching
1918
+ * into the SDK's internal storage keys.
1919
+ */
1920
+ static isRecoveryPending(): boolean;
1829
1921
  /** Get the SDK version */
1830
1922
  static get version(): string;
1831
1923
  }
@@ -7,7 +7,7 @@
7
7
  import type { ResolvedConfig } from '../../config';
8
8
  import { SparkVaultApi } from '../../api-base';
9
9
  import { SparkVaultError } from '../../errors';
10
- import type { SdkConfig, OtpSendResponse, OtpVerifyResponse, PasskeyChallengeResponse, PasskeyVerifyResponse, SecondFactorVerifyResponse, SparkLinkSendResponse, BackupSendResponse, BackupVerifyResponse, Recommendation, RecommendationKey, AuthContext, VerifyResult } from './types';
10
+ import type { SdkConfig, OtpSendResponse, OtpVerifyResponse, PasskeyChallengeResponse, PasskeyVerifyResponse, SecondFactorVerifyResponse, SparkLinkSendResponse, BackupSendResponse, BackupVerifyResponse, Recommendation, RecommendationKey, AuthContext, VerifyResult, RedeemHandoffResponse } from './types';
11
11
  export declare class IdentityApi extends SparkVaultApi {
12
12
  private readonly config;
13
13
  /** Cached config promise - allows preloading and deduplication */
@@ -47,6 +47,14 @@ export declare class IdentityApi extends SparkVaultApi {
47
47
  identity_valid: boolean;
48
48
  has_passkey: boolean;
49
49
  }>;
50
+ /**
51
+ * Redeem a one-time sign-in code (with its PKCE verifier) for the sign-in
52
+ * result — the shared return leg for `flow: 'redirect'` and the silent SSO
53
+ * self-heal. The code arrives in the URL fragment after the hosted page
54
+ * navigates back; it is single-use, 60s-lived, and bound to this page's
55
+ * origin server-side.
56
+ */
57
+ redeemHandoffCode(code: string, codeVerifier: string): Promise<RedeemHandoffResponse>;
50
58
  /**
51
59
  * Build auth context params for API requests (OIDC/simple mode).
52
60
  * Converts AuthContext to snake_case params expected by backend.
@@ -52,7 +52,6 @@ export declare class DialogLauncher {
52
52
  /** Tear down the bridge modal and close any popup it opened. */
53
53
  close(): void;
54
54
  private openPopup;
55
- private buildPopupUrl;
56
55
  private handleResult;
57
56
  private handleError;
58
57
  /** Create the bridge modal (once) and render its single happy-path body. */
@@ -11,7 +11,16 @@
11
11
  * sv.products.identity.attach('.login-btn');
12
12
  */
13
13
  import type { ResolvedConfig } from '../../config';
14
- import type { VerifyOptions, VerifyResult, SignInOptions, SignInResult, TokenClaims, AttachOptions, PortalUrlOptions } from './types';
14
+ import type { VerifyOptions, VerifyResult, SignInOptions, SignInResult, TokenClaims, AttachOptions, PortalUrlOptions, RedirectResultOptions } from './types';
15
+ /**
16
+ * Whether `handleRedirectResult()` has anything to do on this load — a returned
17
+ * sign-in fragment to consume, or a pending sign-in to self-heal. Public + side
18
+ * effect-free (peeks, never consumes) so a host that defers SDK init for
19
+ * performance can cheaply decide whether to boot the SDK on a given page load,
20
+ * WITHOUT reaching into the SDK's internal storage keys. Exposed as
21
+ * `SparkVault.isRecoveryPending()`.
22
+ */
23
+ export declare function isSignInRecoveryPending(): boolean;
15
24
  export declare class IdentityModule {
16
25
  private readonly config;
17
26
  private readonly api;
@@ -59,12 +68,18 @@ export declare class IdentityModule {
59
68
  /** Whether this browser exposes the FedCM API (`navigator.credentials` + IdentityCredential). */
60
69
  static isFedcmAvailable(): boolean;
61
70
  /**
62
- * Open the SparkVault sign-in popup and resolve with the verified identity.
71
+ * Sign in through the first-party SparkVault sign-in popup.
63
72
  *
64
73
  * This is the single programmatic entry point; `attach()` binds it to element
65
- * clicks. There is no inline/in-page mode — sign-in always runs in the
66
- * first-party popup on the Identity origin, so login's `__Host-` hub cookie is
67
- * a first-party write and cross-domain SSO works.
74
+ * clicks. The popup runs the flow top-level on the Identity origin (so
75
+ * login's `__Host-` hub cookie is a first-party write and cross-domain SSO
76
+ * works) and posts the result back — the promise resolves with it.
77
+ *
78
+ * Resilience: pair this with `handleRedirectResult()` on page load. If the
79
+ * popup's result is ever lost (a mobile browser discards the backgrounded
80
+ * opener tab), the next load silently self-heals from the SSO session the
81
+ * login established. `flow: 'redirect'` opts a caller out of the popup into a
82
+ * same-tab navigation instead.
68
83
  *
69
84
  * @example
70
85
  * const result = await sv.products.identity.signIn();
@@ -72,9 +87,10 @@ export declare class IdentityModule {
72
87
  */
73
88
  signIn(options?: SignInOptions): Promise<SignInResult>;
74
89
  /**
75
- * Core flow runner. Dialog mode (no `target`) opens the popup; local mode
76
- * (`renderMode: 'local'` / `target`) renders into the current document and
77
- * powers the SparkVault-hosted sign-in surfaces (see the internal `render`).
90
+ * Core flow runner. Default mode (no `target`) opens the popup; `flow:
91
+ * 'redirect'` navigates the tab instead; local mode (`renderMode: 'local'` /
92
+ * `target`) renders into the current document and powers the
93
+ * SparkVault-hosted sign-in surfaces (see the internal `render`).
78
94
  */
79
95
  private runFlow;
80
96
  /**
@@ -109,13 +125,68 @@ export declare class IdentityModule {
109
125
  */
110
126
  decodeToken(token: string): TokenClaims;
111
127
  /**
112
- * Complete full-page redirect results produced by social-login flows.
113
- * The Identity Product redirects back with `#token=...` so the token does
114
- * not hit server logs. Consume it once, run the unverified client-side decode
115
- * (issuer/audience/expiry/alg sanity-check — NOT signature verification), then
116
- * remove it from the URL bar. The host must still verify the token server-side
117
- * via the Identity JWKS before trusting any claim.
128
+ * Complete a sign-in on page load — the return leg of `signIn()`. Call once
129
+ * on every page load; it resolves `null` when there is nothing to do.
130
+ *
131
+ * It handles two cases:
132
+ * 1. A one-time code is in the URL fragment (`#sv_code=…`) — the popup's
133
+ * result was lost and self-heal navigated here, or `flow: 'redirect'`
134
+ * returned. Redeem it server-side and hand the full result to
135
+ * `onSuccess` (and resolve with it).
136
+ * 2. A sign-in was in flight but never delivered (a mobile browser
137
+ * discarded the backgrounded opener tab, killing the popup's
138
+ * postMessage) — silently re-mint from the SSO session the completed
139
+ * popup login established, by navigating this tab through the silent SSO
140
+ * endpoint and straight back with a code (case 1 on return). Nothing is
141
+ * shown; if there is no live session it comes back logged-out, no oracle.
142
+ *
143
+ * The code is one-time, PKCE-bound, and origin-locked — never the token. The
144
+ * host must still verify `result.token` server-side via the Identity JWKS.
145
+ *
146
+ * @example Call on page load; sign-in clicks stay unchanged.
147
+ * sv.products.identity.handleRedirectResult({
148
+ * onSuccess: (result) => createSession(result.token),
149
+ * }).catch((error) => showError(error));
150
+ */
151
+ handleRedirectResult(options?: RedirectResultOptions): Promise<SignInResult | null>;
152
+ /** Redeem a returned `#sv_code` (or surface a returned `#sv_error`). */
153
+ private consumeHandoffFragment;
154
+ /**
155
+ * Silently re-mint the sign-in result from the SSO session the completed
156
+ * popup login left behind. Navigates this tab through the silent SSO endpoint
157
+ * (a top-level GET, so the `SameSite=Lax` hub cookie rides along) which,
158
+ * PKCE-bound, returns a one-time code in the fragment — handled by case 1 on
159
+ * return. No-op (stays put) if session storage or WebCrypto is unavailable,
160
+ * so a hostile/degraded environment simply never recovers rather than
161
+ * erroring.
162
+ */
163
+ private startRecoveryBounce;
164
+ /**
165
+ * Explicit `flow: 'redirect'` — navigate this tab to the interactive sign-in
166
+ * page. Plain sign-in carries redirect_uri + state + PKCE challenge and
167
+ * returns via the fragment code; OIDC/simple modes navigate bare (their
168
+ * server-rendered pages drive the server-validated redirect back).
169
+ *
170
+ * @returns false when the return leg cannot be armed (no session storage or
171
+ * WebCrypto) — the caller surfaces an actionable error instead of a
172
+ * silent dead-end.
173
+ */
174
+ private startRedirectFlow;
175
+ /**
176
+ * Arm the PKCE + state return leg for a handoff navigation and return the URL
177
+ * to navigate to (redirect_uri = this exact page; query preserved for app
178
+ * state, fragment dropped since it is the result channel). Returns null when
179
+ * session storage or WebCrypto is unavailable so callers can degrade.
118
180
  */
181
+ private prepareHandoffNavigation;
182
+ private markSignInPending;
183
+ private clearSignInPending;
184
+ /** True once (then cleared) if a recent sign-in is still awaiting its result. */
185
+ private consumeSignInPending;
186
+ /** Remove the result fragment from the URL bar (and history entry). */
187
+ private clearUrlFragment;
188
+ /** Drop the one-shot PKCE state/verifier a redirect bounce staged. */
189
+ private clearOneShotAuthState;
119
190
  private consumeRedirectResult;
120
191
  /**
121
192
  * Close the identity dialog/inline UI if open.
@@ -44,6 +44,13 @@ export interface VerifyOptions {
44
44
  chrome?: 'card' | 'bare';
45
45
  /** Auth context for OIDC/simple mode flows (used by hosted login) */
46
46
  authContext?: AuthContext;
47
+ /**
48
+ * How sign-in leaves this page. `'auto'` (default) and `'popup'` open the
49
+ * first-party popup; `'redirect'` navigates this tab to the sign-in page
50
+ * instead (its return leg is `handleRedirectResult()`) — the opt-out for
51
+ * hosts that prefer a full-page redirect over a popup on mobile.
52
+ */
53
+ flow?: 'auto' | 'popup' | 'redirect';
47
54
  /**
48
55
  * Rendering strategy (internal). `'local'` renders the flow directly in this
49
56
  * document — used inside the popup that runs the flow, and forced for inline
@@ -124,6 +131,29 @@ export interface VerifyResult {
124
131
  export type SignInOptions = Omit<VerifyOptions, 'target' | 'renderMode' | 'chrome'>;
125
132
  /** The verified identity returned by `signIn()`. */
126
133
  export type SignInResult = VerifyResult;
134
+ /**
135
+ * Options for `handleRedirectResult()` — call once on every page load. It
136
+ * redeems a returned sign-in code (from `flow: 'redirect'` or the silent SSO
137
+ * self-heal) and, when a popup result was lost, triggers that self-heal. It
138
+ * no-ops otherwise.
139
+ */
140
+ export interface RedirectResultOptions {
141
+ /** Called with the verified result when a returned sign-in code is redeemed */
142
+ onSuccess?: (result: VerifyResult) => void;
143
+ /** Called when redeeming a returned sign-in code failed */
144
+ onError?: (error: Error) => void;
145
+ /** Called when the person cancelled sign-in on the hosted page */
146
+ onCancel?: () => void;
147
+ }
148
+ /** Raw wire shape of POST /signin/redeem (snake_case, mirrors /sso/continue). */
149
+ export interface RedeemHandoffResponse {
150
+ token: string;
151
+ identity: string;
152
+ identity_type: VerifiedIdentityType;
153
+ svid?: string | null;
154
+ session_id?: string | null;
155
+ refresh_token?: string | null;
156
+ }
127
157
  /** Raw recommendation as the API returns it (snake_case). */
128
158
  export interface RawRecommendation {
129
159
  type: string;
@@ -7,6 +7,8 @@
7
7
  export { CooldownTimer, ExpirationTimer } from './utils/cooldown-timer';
8
8
  export type { CooldownTimerConfig, ExpirationTimerConfig } from './utils/cooldown-timer';
9
9
  export { arrayBufferToBase64url, base64urlToArrayBuffer, base64urlToString, } from '../../utils/base64url';
10
+ import type { ResolvedConfig } from '../../config';
11
+ import type { VerifyOptions } from './types';
10
12
  /**
11
13
  * Extract the root (registrable) domain from a hostname for cross-subdomain cookies.
12
14
  * Returns the domain prefixed with a dot (e.g., ".client.com") or null when
@@ -37,3 +39,34 @@ export declare function setCookie(name: string, value: string, days: number): vo
37
39
  * Used for OAuth CSRF protection
38
40
  */
39
41
  export declare function generateState(): string;
42
+ /**
43
+ * Generate a PKCE code_verifier (RFC 7636): 32 random bytes, base64url —
44
+ * 43 URL-safe characters.
45
+ */
46
+ export declare function generateCodeVerifier(): string;
47
+ /**
48
+ * Compute the S256 PKCE code_challenge for a verifier:
49
+ * base64url(SHA-256(verifier)).
50
+ */
51
+ export declare function computeS256Challenge(codeVerifier: string): Promise<string>;
52
+ /** Extra query params for the redirect sign-in mode. */
53
+ export interface SigninUrlRedirectExtras {
54
+ redirectUri: string;
55
+ state: string;
56
+ codeChallenge: string;
57
+ }
58
+ /**
59
+ * Build the sign-in page URL on the Identity origin. Single source for BOTH
60
+ * delivery modes: the popup (opener + postMessage) and the same-tab redirect
61
+ * (redirect_uri + state + code_challenge → one-time code in the fragment).
62
+ */
63
+ export declare function buildSigninUrl(config: ResolvedConfig, options: VerifyOptions, extras?: SigninUrlRedirectExtras): string;
64
+ /**
65
+ * Warm the connection to another origin by injecting `<link rel="preconnect">`
66
+ * hints (one plain for top-level navigations, one `crossorigin` for CORS
67
+ * fetches). The sign-in popup/redirect and every flow API call reuse the open
68
+ * connection, which removes the cold-connection stall mobile browsers hit on
69
+ * the first navigation to the Identity origin. No-op off-DOM, for the page's
70
+ * own origin, and when the hints already exist.
71
+ */
72
+ export declare function ensurePreconnect(baseUrl: string): void;