@trymellon/js 2.2.1 → 2.3.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.
@@ -1,4 +1,4 @@
1
- type TryMellonErrorCode = 'NOT_SUPPORTED' | 'USER_CANCELLED' | 'PASSKEY_NOT_FOUND' | 'SESSION_EXPIRED' | 'NETWORK_FAILURE' | 'INVALID_ARGUMENT' | 'TIMEOUT' | 'ABORTED' | 'ABORT_ERROR' | 'CHALLENGE_MISMATCH' | 'UNKNOWN_ERROR';
1
+ type TryMellonErrorCode = 'NOT_SUPPORTED' | 'USER_CANCELLED' | 'PASSKEY_NOT_FOUND' | 'SESSION_EXPIRED' | 'NETWORK_FAILURE' | 'INVALID_ARGUMENT' | 'TIMEOUT' | 'ABORTED' | 'ABORT_ERROR' | 'CHALLENGE_MISMATCH' | 'TICKET_NOT_FOUND' | 'TICKET_EXPIRED' | 'TICKET_ALREADY_USED' | 'PIN_MISMATCH' | 'PIN_LOCKED' | 'BRIDGE_SESSION_EXPIRED' | 'UNKNOWN_ERROR';
2
2
  declare class TryMellonError extends Error {
3
3
  readonly code: TryMellonErrorCode;
4
4
  readonly details?: unknown;
@@ -26,11 +26,10 @@ interface TelemetrySender {
26
26
  type Branded<T, B> = T & {
27
27
  __brand: B;
28
28
  };
29
- type AppId = Branded<string, 'AppId'>;
30
29
  type ExternalUserId = Branded<string, 'ExternalUserId'>;
31
30
  type TryMellonConfig = {
32
31
  /** Application identifier (tenant). Required for API requests. */
33
- appId: string | AppId;
32
+ appId: string;
34
33
  /** API key for authentication. Required for API requests. */
35
34
  publishableKey: string;
36
35
  apiBaseUrl?: string;
@@ -61,6 +60,14 @@ type TryMellonConfig = {
61
60
  * Set this in Node or when the document origin is not the correct one (e.g. SSR).
62
61
  */
63
62
  origin?: string;
63
+ /**
64
+ * Optional storage for context hash (e.g. sessionStorage). If not set, browser sessionStorage or in-memory fallback is used.
65
+ * Injected for testability and SSR; must implement getItem/setItem.
66
+ */
67
+ contextHashStorage?: {
68
+ getItem(key: string): string | null;
69
+ setItem(key: string, value: string): void;
70
+ };
64
71
  };
65
72
  interface RegisterOptions {
66
73
  /**
@@ -108,19 +115,19 @@ type SuccessEventUserInfo = {
108
115
  /** Success payload: token always present (03-eventos-seguridad). Nonce when flow generates it. */
109
116
  type SuccessEventPayload = {
110
117
  type: 'success';
111
- operation: 'register' | 'authenticate';
118
+ operation: 'register' | 'authenticate' | 'enroll';
112
119
  token: string;
113
120
  user?: SuccessEventUserInfo;
114
121
  nonce?: string;
115
122
  };
116
123
  type EventPayload = {
117
124
  type: 'start';
118
- operation: 'register' | 'authenticate';
125
+ operation: 'register' | 'authenticate' | 'enroll';
119
126
  nonce?: string;
120
127
  } | SuccessEventPayload | {
121
128
  type: 'error';
122
129
  error: TryMellonError;
123
- operation?: 'register' | 'authenticate';
130
+ operation?: 'register' | 'authenticate' | 'enroll';
124
131
  nonce?: string;
125
132
  } | {
126
133
  type: 'cancelled';
@@ -143,6 +150,31 @@ type EmailFallbackVerifyResult = {
143
150
  /** Set when successUrl was passed and allowed by application allowlist */
144
151
  redirectUrl?: string;
145
152
  };
153
+ type EnrollOptions = {
154
+ ticketId: string;
155
+ signal?: AbortSignal;
156
+ };
157
+ /** Result of finish enrollment; aligns with backend envelope (session_token). */
158
+ type EnrollmentResult = {
159
+ sessionToken: string;
160
+ };
161
+ /** Backend response for POST /v1/enrollment/register/options. Validators use this shape. */
162
+ type EnrollmentStartResponse = {
163
+ session_id: string;
164
+ challenge: RegisterStartResponse['challenge'];
165
+ };
166
+ /** Backend response for POST /v1/enrollment/register. Validators use this shape. */
167
+ type EnrollmentFinishResponse = {
168
+ credential_id: string;
169
+ status: string;
170
+ session_token: string;
171
+ user: {
172
+ user_id: string;
173
+ external_user_id?: string;
174
+ email?: string;
175
+ metadata?: Record<string, unknown>;
176
+ };
177
+ };
146
178
  type RecoveryVerifyResponse = {
147
179
  challenge: Record<string, unknown>;
148
180
  recovery_session_id: string;
@@ -240,6 +272,62 @@ type CrossDeviceVerifyRegistrationRequest = {
240
272
  session_id: string;
241
273
  credential: RegisterFinishRequest['credential'];
242
274
  };
275
+ /** Response from GET context/:sessionId (auth or registration). Aligns with backend unwrapped result. */
276
+ type BridgeContextResponse = {
277
+ type: 'auth' | 'registration';
278
+ options: Record<string, unknown>;
279
+ application_name?: string;
280
+ };
281
+ /** Response from POST verify/:sessionId (challenge / options for WebAuthn). */
282
+ type BridgeChallengeResponse = {
283
+ session_id: string;
284
+ challenge?: string;
285
+ registration_options?: Record<string, unknown>;
286
+ authentication_options?: Record<string, unknown>;
287
+ };
288
+ /** Backend result of POST complete (enrollment). Validators use this shape. */
289
+ type BridgeCompleteEnrollmentResult = {
290
+ credential_id: string;
291
+ entity_id: string;
292
+ user_id: string;
293
+ session_token: string;
294
+ };
295
+ /** Backend result of POST complete (auth). */
296
+ type BridgeCompleteAuthResult = {
297
+ session_token: string;
298
+ };
299
+ /** Options for bridge flows: PIN callback, optional preset PIN, abort signal. */
300
+ type BridgeOptions = {
301
+ onPinRequired?: () => Promise<string>;
302
+ presencePin?: string;
303
+ signal?: AbortSignal;
304
+ };
305
+ /** Public result of bridge enrollment: sessionToken and optional credential/user/entity ids. */
306
+ type BridgeEnrollmentResult = {
307
+ sessionToken: string;
308
+ credentialId?: string;
309
+ userId?: string;
310
+ entityId?: string;
311
+ };
312
+ /** Public result of bridge auth: sessionToken only. */
313
+ type BridgeAuthResult = {
314
+ sessionToken: string;
315
+ };
316
+ /** Union: bridge completion returns enrollment or auth result. */
317
+ type BridgeResult = BridgeEnrollmentResult | BridgeAuthResult;
318
+ /** Status snapshot from GET .../status/:sessionId (polling or SSE event). Terminal: pin_verified | pin_locked | completed. */
319
+ type BridgeStatusSnapshot = {
320
+ status: 'pending' | 'pin_verified' | 'pin_locked' | 'completed';
321
+ ts?: string;
322
+ };
323
+ /** Options for complete(): BridgeOptions plus kind and enrollment-only fields. */
324
+ type BridgeCompleteOptions = BridgeOptions & {
325
+ kind: 'enrollment' | 'auth';
326
+ /** Required when completing enrollment bridge. */
327
+ ticketId?: string;
328
+ /** Required when completing enrollment bridge. */
329
+ entityId?: string;
330
+ };
243
331
  type RegisterStartRequest = {
244
332
  external_user_id: string;
245
333
  };
@@ -387,10 +475,10 @@ interface AuthenticateResult {
387
475
  }
388
476
  type SessionValidateResponse = {
389
477
  valid: boolean;
390
- user_id: string;
391
- external_user_id: string;
392
- tenant_id: string;
393
- app_id: string;
478
+ userId: string;
479
+ externalUserId: string;
480
+ tenantId: string;
481
+ appId: string;
394
482
  };
395
483
  type OnboardingStartRequest = {
396
484
  user_role: 'maintainer' | 'app_user';
@@ -458,6 +546,8 @@ type OnboardingRegisterResponseWithChallenge = OnboardingRegisterResponse & {
458
546
  challenge?: RegisterStartResponse['challenge'];
459
547
  };
460
548
 
549
+ /** Bridge kind: enrollment-bridge (registration flow) or auth-bridge (auth flow). */
550
+ type BridgeKind = 'enrollment' | 'auth';
461
551
  declare class ApiClient {
462
552
  private readonly httpClient;
463
553
  private readonly baseUrl;
@@ -504,6 +594,49 @@ declare class ApiClient {
504
594
  verifyCrossDeviceRegistration(request: CrossDeviceVerifyRegistrationRequest): Promise<Result<void, TryMellonError>>;
505
595
  verifyAccountRecoveryOtp(externalUserId: string, otp: string): Promise<Result<RecoveryVerifyResponse, TryMellonError>>;
506
596
  completeAccountRecovery(recoverySessionId: string, credential: Record<string, unknown>): Promise<Result<RecoveryCompleteResponse, TryMellonError>>;
597
+ startEnrollment(ticketId: string, contextHash: string, headers?: Record<string, string>): Promise<Result<EnrollmentStartResponse, TryMellonError>>;
598
+ finishEnrollment(ticketId: string, body: {
599
+ credential: unknown;
600
+ context_hash: string;
601
+ }, headers?: Record<string, string>): Promise<Result<EnrollmentFinishResponse, TryMellonError>>;
602
+ private bridgePrefix;
603
+ getBridgeContext(sessionId: string, kind: BridgeKind, headers?: Record<string, string>): Promise<Result<BridgeContextResponse, TryMellonError>>;
604
+ verifyBridgePin(sessionId: string, pin: string, kind: BridgeKind, headers?: Record<string, string>): Promise<Result<BridgeChallengeResponse, TryMellonError>>;
605
+ completeBridgeEnrollment(body: {
606
+ session_id: string;
607
+ ticket_id: string;
608
+ entity_id: string;
609
+ context_hash: string;
610
+ registration_response: {
611
+ id: string;
612
+ rawId: string;
613
+ response: {
614
+ clientDataJSON: string;
615
+ attestationObject: string;
616
+ };
617
+ type: string;
618
+ };
619
+ }, headers?: Record<string, string>): Promise<Result<BridgeCompleteEnrollmentResult, TryMellonError>>;
620
+ completeBridgeAuth(body: {
621
+ session_id: string;
622
+ credential: {
623
+ id: string;
624
+ rawId: string;
625
+ response: {
626
+ authenticatorData: string;
627
+ clientDataJSON: string;
628
+ signature: string;
629
+ userHandle?: string;
630
+ };
631
+ type: string;
632
+ };
633
+ }, headers?: Record<string, string>): Promise<Result<BridgeCompleteAuthResult, TryMellonError>>;
634
+ /**
635
+ * Full URL for GET bridge status (polling or EventSource). Same path as getBridgeStatus.
636
+ * Used by BridgeManager for SSE when EventSource is available (browser only; Node has no EventSource).
637
+ */
638
+ getBridgeStatusUrl(sessionId: string, kind: BridgeKind): string;
639
+ getBridgeStatus(sessionId: string, kind: BridgeKind, headers?: Record<string, string>): Promise<Result<BridgeStatusSnapshot, TryMellonError>>;
507
640
  }
508
641
 
509
642
  declare class OnboardingManager {
@@ -531,20 +664,35 @@ declare class TryMellon {
531
664
  private authService;
532
665
  private recoveryService;
533
666
  onboarding: OnboardingManager;
534
- /**
535
- * Creates a new TryMellon instance.
536
- * Validates config and returns a Result.
537
- * @param config SDK configuration
538
- */
667
+ private readonly enrollmentManager;
668
+ private readonly bridgeManager;
669
+ private readonly contextHashStorage;
670
+ private static validateConfig;
539
671
  static create(config: TryMellonConfig): Result<TryMellon, TryMellonError>;
540
672
  /**
541
673
  * @deprecated Use `TryMellon.create(config)` instead to handle validation errors safely.
542
674
  * This constructor will throw errors if configuration is invalid.
543
675
  */
544
676
  constructor(config: TryMellonConfig);
677
+ /**
678
+ * Bridge (KP-BRIDGE-04): complete enrollment or auth from a second device (e.g. mobile scanning desktop QR).
679
+ * Use kind 'enrollment' for enrollment-bridge sessions, 'auth' for auth-bridge sessions.
680
+ */
681
+ get bridge(): {
682
+ getContext(sessionId: string, kind: 'enrollment' | 'auth'): Promise<Result<BridgeContextResponse, TryMellonError>>;
683
+ verifyPin(sessionId: string, pin: string, kind: 'enrollment' | 'auth'): Promise<Result<BridgeChallengeResponse, TryMellonError>>;
684
+ complete(sessionId: string, options?: BridgeCompleteOptions): Promise<Result<BridgeResult, TryMellonError>>;
685
+ waitForResult(sessionId: string, options?: {
686
+ useSse?: boolean;
687
+ kind?: 'enrollment' | 'auth';
688
+ timeoutMs?: number;
689
+ }): Promise<Result<BridgeStatusSnapshot, TryMellonError>>;
690
+ };
545
691
  static isSupported(): boolean;
546
692
  register(options: RegisterOptions): Promise<Result<RegisterResult, TryMellonError>>;
547
693
  authenticate(options: AuthenticateOptions): Promise<Result<AuthenticateResult, TryMellonError>>;
694
+ enroll(options: EnrollOptions): Promise<Result<EnrollmentResult, TryMellonError>>;
695
+ getContextHash(): string;
548
696
  validateSession(sessionToken: string): Promise<Result<SessionValidateResponse, TryMellonError>>;
549
697
  getStatus(): Promise<ClientStatus>;
550
698
  on(event: TryMellonEvent, handler: EventHandler): () => void;
@@ -573,4 +721,4 @@ declare class TryMellon {
573
721
  };
574
722
  }
575
723
 
576
- export { type AuthenticateResult as A, type Result as R, TryMellon as T, type RegisterResult as a, TryMellonError as b, type RegisterOptions as c, type AuthenticateOptions as d, type TryMellonConfig as e };
724
+ export { type AuthenticateResult as A, type EnrollmentResult as E, type Result as R, TryMellon as T, type RegisterResult as a, TryMellonError as b, type RegisterOptions as c, type AuthenticateOptions as d, type EnrollOptions as e };
@@ -7,7 +7,7 @@ declare const INITIAL_UI_STATE: "IDLE";
7
7
  /** UI FSM types — presentation layer. No DOM/core deps (types only). Aligned to 01-arquitectura §4. */
8
8
 
9
9
  /** UI state machine states. */
10
- type UIState = 'IDLE' | 'EVALUATING_ENV' | 'READY' | 'READY_REGISTER' | 'READY_LOGIN' | 'AUTHENTICATING' | 'SUCCESS' | 'ERROR' | 'FALLBACK' | 'FALLBACK_EMAIL' | 'FALLBACK_QR';
10
+ type UIState = 'IDLE' | 'EVALUATING_ENV' | 'READY' | 'READY_REGISTER' | 'READY_LOGIN' | 'AUTHENTICATING' | 'SUCCESS' | 'ERROR' | 'FALLBACK' | 'FALLBACK_EMAIL' | 'FALLBACK_QR' | 'ENROLLMENT_READY' | 'ENROLLING' | 'ENROLLMENT_SUCCESS' | 'ENROLLMENT_ERROR';
11
11
  /** Component mode (mode attribute). */
12
12
  type UIMode = 'login' | 'register' | 'auto';
13
13
  /** Client status in UI layer (port/adapter map from core). */
@@ -54,6 +54,19 @@ type FSMEvent = {
54
54
  type: 'AUTH_FALLBACK_EMAIL';
55
55
  } | {
56
56
  type: 'AUTH_FALLBACK_QR';
57
+ } | {
58
+ type: 'ENROLLMENT_READY_SET';
59
+ payload?: {
60
+ ticketId?: string;
61
+ };
62
+ } | {
63
+ type: 'START_ENROLL';
64
+ } | {
65
+ type: 'ENROLL_SUCCESS';
66
+ } | {
67
+ type: 'ENROLL_ERROR';
68
+ } | {
69
+ type: 'ENROLL_RETRY';
57
70
  };
58
71
 
59
72
  /**
@@ -104,6 +117,8 @@ type ParsedAttributes = {
104
117
  buttonLabel?: string | null;
105
118
  /** Optional aria-label for the trigger button (default = TRIGGER_ARIA_LABEL). */
106
119
  buttonAriaLabel?: string | null;
120
+ /** When set, WC runs in enrollment mode: emits context-ready and exposes enroll(). */
121
+ ticketId?: string | null;
107
122
  };
108
123
  /** Modal display mode: overlay vs inline. */
109
124
  type ModalDisplayMode = 'modal' | 'inline';
@@ -158,13 +173,18 @@ type RenderOptions = {
158
173
  primaryButtonAriaLabel?: string;
159
174
  };
160
175
 
176
+ type EnrollOptions = {
177
+ ticketId: string;
178
+ signal?: AbortSignal;
179
+ };
180
+
161
181
  /**
162
182
  * Port: core event subscription and re-emission on host. Source of truth for modal WC event contract (names, detail types).
163
183
  * Contract only; implementation in adapters. No import from ../core.
164
184
  */
165
185
 
166
- /** Public auth operation for host (login | register). */
167
- type AuthOperation = TabKind;
186
+ /** Public auth operation for host (login | register | enroll). */
187
+ type AuthOperation = TabKind | 'enroll';
168
188
  /** Optional user info in mellon:success; minimal shape for host without coupling to core. */
169
189
  type MellonSuccessUserInfo = {
170
190
  userId: string;
@@ -216,10 +236,12 @@ interface CoreWithEvents {
216
236
  interface CoreEventsPort {
217
237
  subscribe(core: CoreWithEvents, host: HTMLElement): () => void;
218
238
  }
219
- /** Minimal core surface for UI: start auth and subscribe to events. */
239
+ /** Minimal core surface for UI: start auth, enrollment, context hash, and subscribe to events. */
220
240
  interface CoreAuthPort extends CoreWithEvents {
221
241
  authenticate(options?: CoreAuthOptions): void;
222
242
  register(options?: CoreAuthOptions): void;
243
+ enroll(options?: EnrollOptions): void;
244
+ getContextHash(): string;
223
245
  }
224
246
  /** Options when starting auth from UI. */
225
247
  interface CoreAuthOptions {
@@ -253,8 +275,13 @@ declare class AuthController {
253
275
  consumeCancelledDetailIfAuthenticating(): MellonOperationDetail | null;
254
276
  handleAuthSuccess(): void;
255
277
  handleAuthError(): void;
278
+ handleEnrollSuccess(): void;
279
+ handleEnrollError(): void;
256
280
  onStartEvent(detail: MellonOperationDetail | undefined): void;
257
281
  startAuthFromClick(core: CoreAuthPort | null, tab: TabKind, options?: CoreAuthOptions): void;
282
+ startEnrollment(core: CoreAuthPort | null, options: {
283
+ ticketId: string;
284
+ }): void;
258
285
  runEnvEval(params: Omit<RunEnvEvalParams, 'currentState'>): Promise<UIState | null>;
259
286
  reset(): void;
260
287
  setStateForRender(state: UIState): void;
@@ -340,6 +367,8 @@ declare abstract class AuthElementBase extends HTMLElement {
340
367
  declare class TryMellonAuthElement extends AuthElementBase {
341
368
  static get observedAttributes(): string[];
342
369
  protected _parsed: ParsedAttributes;
370
+ /** When set, WC is in enrollment mode: emits context-ready and exposes enroll(). */
371
+ get ticketId(): string | null;
343
372
  private _internalModal;
344
373
  /** Element that opened the modal; single source for focus restore on close. */
345
374
  private _focusRestoreTarget;
@@ -348,6 +377,12 @@ declare class TryMellonAuthElement extends AuthElementBase {
348
377
  /** Re-dispatch modal success on this element so host can listen on <trymellon-auth> (modal is in body, events don't bubble here). */
349
378
  private _onInternalModalSuccess;
350
379
  private _restoreFocusToTrigger;
380
+ /** When ticket-id is set and core is attached, emits mellon:context-ready with contextHash (composed: true). */
381
+ private _emitContextReadyIfEnrollment;
382
+ /**
383
+ * Starts enrollment (only when ticket-id is set). No-op if no ticketId or core. Success/error re-dispatched via mellon:success / mellon:error.
384
+ */
385
+ enroll(): void;
351
386
  connectedCallback(): void;
352
387
  private _registerInteractions;
353
388
  attributeChangedCallback(name: string, _oldValue: string | null, _newValue: string | null): void;