@sparkvault/sdk-js 8.7.0 → 8.8.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.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 static readonly PENDING_KEY;
473
+ private static readonly PENDING_TTL_MS;
474
+ private markSignInPending;
475
+ private clearSignInPending;
476
+ /** True once (then cleared) if a recent sign-in is still awaiting its result. */
477
+ private consumeSignInPending;
478
+ /** Remove the result fragment from the URL bar (and history entry). */
479
+ private clearUrlFragment;
397
480
  private consumeRedirectResult;
398
481
  /**
399
482
  * Close the identity dialog/inline UI if open.
@@ -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,7 @@
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
15
  export declare class IdentityModule {
16
16
  private readonly config;
17
17
  private readonly api;
@@ -59,12 +59,18 @@ export declare class IdentityModule {
59
59
  /** Whether this browser exposes the FedCM API (`navigator.credentials` + IdentityCredential). */
60
60
  static isFedcmAvailable(): boolean;
61
61
  /**
62
- * Open the SparkVault sign-in popup and resolve with the verified identity.
62
+ * Sign in through the first-party SparkVault sign-in popup.
63
63
  *
64
64
  * 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.
65
+ * clicks. The popup runs the flow top-level on the Identity origin (so
66
+ * login's `__Host-` hub cookie is a first-party write and cross-domain SSO
67
+ * works) and posts the result back — the promise resolves with it.
68
+ *
69
+ * Resilience: pair this with `handleRedirectResult()` on page load. If the
70
+ * popup's result is ever lost (a mobile browser discards the backgrounded
71
+ * opener tab), the next load silently self-heals from the SSO session the
72
+ * login established. `flow: 'redirect'` opts a caller out of the popup into a
73
+ * same-tab navigation instead.
68
74
  *
69
75
  * @example
70
76
  * const result = await sv.products.identity.signIn();
@@ -72,9 +78,10 @@ export declare class IdentityModule {
72
78
  */
73
79
  signIn(options?: SignInOptions): Promise<SignInResult>;
74
80
  /**
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`).
81
+ * Core flow runner. Default mode (no `target`) opens the popup; `flow:
82
+ * 'redirect'` navigates the tab instead; local mode (`renderMode: 'local'` /
83
+ * `target`) renders into the current document and powers the
84
+ * SparkVault-hosted sign-in surfaces (see the internal `render`).
78
85
  */
79
86
  private runFlow;
80
87
  /**
@@ -109,13 +116,68 @@ export declare class IdentityModule {
109
116
  */
110
117
  decodeToken(token: string): TokenClaims;
111
118
  /**
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.
119
+ * Complete a sign-in on page load — the return leg of `signIn()`. Call once
120
+ * on every page load; it resolves `null` when there is nothing to do.
121
+ *
122
+ * It handles two cases:
123
+ * 1. A one-time code is in the URL fragment (`#sv_code=…`) — the popup's
124
+ * result was lost and self-heal navigated here, or `flow: 'redirect'`
125
+ * returned. Redeem it server-side and hand the full result to
126
+ * `onSuccess` (and resolve with it).
127
+ * 2. A sign-in was in flight but never delivered (a mobile browser
128
+ * discarded the backgrounded opener tab, killing the popup's
129
+ * postMessage) — silently re-mint from the SSO session the completed
130
+ * popup login established, by navigating this tab through the silent SSO
131
+ * endpoint and straight back with a code (case 1 on return). Nothing is
132
+ * shown; if there is no live session it comes back logged-out, no oracle.
133
+ *
134
+ * The code is one-time, PKCE-bound, and origin-locked — never the token. The
135
+ * host must still verify `result.token` server-side via the Identity JWKS.
136
+ *
137
+ * @example Call on page load; sign-in clicks stay unchanged.
138
+ * sv.products.identity.handleRedirectResult({
139
+ * onSuccess: (result) => createSession(result.token),
140
+ * }).catch((error) => showError(error));
141
+ */
142
+ handleRedirectResult(options?: RedirectResultOptions): Promise<SignInResult | null>;
143
+ /** Redeem a returned `#sv_code` (or surface a returned `#sv_error`). */
144
+ private consumeHandoffFragment;
145
+ /**
146
+ * Silently re-mint the sign-in result from the SSO session the completed
147
+ * popup login left behind. Navigates this tab through the silent SSO endpoint
148
+ * (a top-level GET, so the `SameSite=Lax` hub cookie rides along) which,
149
+ * PKCE-bound, returns a one-time code in the fragment — handled by case 1 on
150
+ * return. No-op (stays put) if session storage or WebCrypto is unavailable,
151
+ * so a hostile/degraded environment simply never recovers rather than
152
+ * erroring.
153
+ */
154
+ private startRecoveryBounce;
155
+ /**
156
+ * Explicit `flow: 'redirect'` — navigate this tab to the interactive sign-in
157
+ * page. Plain sign-in carries redirect_uri + state + PKCE challenge and
158
+ * returns via the fragment code; OIDC/simple modes navigate bare (their
159
+ * server-rendered pages drive the server-validated redirect back).
160
+ *
161
+ * @returns false when the return leg cannot be armed (no session storage or
162
+ * WebCrypto) — the caller surfaces an actionable error instead of a
163
+ * silent dead-end.
164
+ */
165
+ private startRedirectFlow;
166
+ /**
167
+ * Arm the PKCE + state return leg for a handoff navigation and return the URL
168
+ * to navigate to (redirect_uri = this exact page; query preserved for app
169
+ * state, fragment dropped since it is the result channel). Returns null when
170
+ * session storage or WebCrypto is unavailable so callers can degrade.
118
171
  */
172
+ private prepareHandoffNavigation;
173
+ private static readonly PENDING_KEY;
174
+ private static readonly PENDING_TTL_MS;
175
+ private markSignInPending;
176
+ private clearSignInPending;
177
+ /** True once (then cleared) if a recent sign-in is still awaiting its result. */
178
+ private consumeSignInPending;
179
+ /** Remove the result fragment from the URL bar (and history entry). */
180
+ private clearUrlFragment;
119
181
  private consumeRedirectResult;
120
182
  /**
121
183
  * 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;