@trymellon/js 1.4.9 → 1.5.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/angular.cjs +1 -1
- package/dist/angular.cjs.map +1 -1
- package/dist/angular.d.cts +1 -1
- package/dist/angular.d.ts +1 -1
- package/dist/angular.js +1 -1
- package/dist/angular.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -1
- package/dist/index.d.ts +42 -1
- package/dist/index.global.js +2 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/{trymellon-DfbkkIz8.d.cts → trymellon-BkIVfr7x.d.cts} +42 -1
- package/dist/{trymellon-DfbkkIz8.d.ts → trymellon-BkIVfr7x.d.ts} +42 -1
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -128,6 +128,43 @@ type EmailFallbackVerifyOptions = {
|
|
|
128
128
|
type EmailFallbackVerifyResult = {
|
|
129
129
|
sessionToken: string;
|
|
130
130
|
};
|
|
131
|
+
type RecoveryVerifyResponse = {
|
|
132
|
+
challenge: Record<string, unknown>;
|
|
133
|
+
recovery_session_id: string;
|
|
134
|
+
};
|
|
135
|
+
type RecoveryCompleteResponse = {
|
|
136
|
+
status: string;
|
|
137
|
+
session_token: string;
|
|
138
|
+
user: {
|
|
139
|
+
user_id: string;
|
|
140
|
+
external_user_id?: string;
|
|
141
|
+
email?: string;
|
|
142
|
+
metadata?: Record<string, unknown>;
|
|
143
|
+
};
|
|
144
|
+
credential_id: string;
|
|
145
|
+
};
|
|
146
|
+
type RecoverAccountOptions = {
|
|
147
|
+
/** The external user ID of the account being recovered. */
|
|
148
|
+
externalUserId: string | ExternalUserId;
|
|
149
|
+
/**
|
|
150
|
+
* @deprecated Use `externalUserId` instead.
|
|
151
|
+
*/
|
|
152
|
+
external_user_id?: string | ExternalUserId;
|
|
153
|
+
/** The 6-digit OTP sent via email. */
|
|
154
|
+
otp: string;
|
|
155
|
+
};
|
|
156
|
+
interface RecoverAccountResult {
|
|
157
|
+
success: true;
|
|
158
|
+
credentialId: string;
|
|
159
|
+
status: string;
|
|
160
|
+
sessionToken: string;
|
|
161
|
+
user: {
|
|
162
|
+
userId: string;
|
|
163
|
+
externalUserId?: string;
|
|
164
|
+
email?: string;
|
|
165
|
+
metadata?: Record<string, unknown>;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
131
168
|
type OnboardingStartOptions = {
|
|
132
169
|
user_role: 'maintainer' | 'app_user';
|
|
133
170
|
};
|
|
@@ -217,7 +254,8 @@ type RegisterStartRequest = {
|
|
|
217
254
|
external_user_id: string;
|
|
218
255
|
};
|
|
219
256
|
type AuthStartRequest = {
|
|
220
|
-
|
|
257
|
+
/** Omit for discoverable (resident) passkeys; server returns allowCredentials: [] */
|
|
258
|
+
external_user_id?: string;
|
|
221
259
|
};
|
|
222
260
|
type RegisterFinishRequest = {
|
|
223
261
|
session_id: string;
|
|
@@ -461,6 +499,8 @@ declare class ApiClient {
|
|
|
461
499
|
getCrossDeviceContext(sessionId: string): Promise<Result<CrossDeviceContextResult, TryMellonError>>;
|
|
462
500
|
verifyCrossDeviceAuth(request: CrossDeviceVerifyRequest): Promise<Result<void, TryMellonError>>;
|
|
463
501
|
verifyCrossDeviceRegistration(request: CrossDeviceVerifyRegistrationRequest): Promise<Result<void, TryMellonError>>;
|
|
502
|
+
verifyAccountRecoveryOtp(externalUserId: string, otp: string): Promise<Result<RecoveryVerifyResponse, TryMellonError>>;
|
|
503
|
+
completeAccountRecovery(recoverySessionId: string, credential: Record<string, unknown>): Promise<Result<RecoveryCompleteResponse, TryMellonError>>;
|
|
464
504
|
}
|
|
465
505
|
|
|
466
506
|
declare class OnboardingManager {
|
|
@@ -522,6 +562,7 @@ declare class TryMellon {
|
|
|
522
562
|
}, TryMellonError>>;
|
|
523
563
|
approve: (sessionId: string) => Promise<Result<void, TryMellonError>>;
|
|
524
564
|
};
|
|
565
|
+
recoverAccount: (options: RecoverAccountOptions) => Promise<Result<RecoverAccountResult, TryMellonError>>;
|
|
525
566
|
};
|
|
526
567
|
}
|
|
527
568
|
|
package/dist/index.d.ts
CHANGED
|
@@ -128,6 +128,43 @@ type EmailFallbackVerifyOptions = {
|
|
|
128
128
|
type EmailFallbackVerifyResult = {
|
|
129
129
|
sessionToken: string;
|
|
130
130
|
};
|
|
131
|
+
type RecoveryVerifyResponse = {
|
|
132
|
+
challenge: Record<string, unknown>;
|
|
133
|
+
recovery_session_id: string;
|
|
134
|
+
};
|
|
135
|
+
type RecoveryCompleteResponse = {
|
|
136
|
+
status: string;
|
|
137
|
+
session_token: string;
|
|
138
|
+
user: {
|
|
139
|
+
user_id: string;
|
|
140
|
+
external_user_id?: string;
|
|
141
|
+
email?: string;
|
|
142
|
+
metadata?: Record<string, unknown>;
|
|
143
|
+
};
|
|
144
|
+
credential_id: string;
|
|
145
|
+
};
|
|
146
|
+
type RecoverAccountOptions = {
|
|
147
|
+
/** The external user ID of the account being recovered. */
|
|
148
|
+
externalUserId: string | ExternalUserId;
|
|
149
|
+
/**
|
|
150
|
+
* @deprecated Use `externalUserId` instead.
|
|
151
|
+
*/
|
|
152
|
+
external_user_id?: string | ExternalUserId;
|
|
153
|
+
/** The 6-digit OTP sent via email. */
|
|
154
|
+
otp: string;
|
|
155
|
+
};
|
|
156
|
+
interface RecoverAccountResult {
|
|
157
|
+
success: true;
|
|
158
|
+
credentialId: string;
|
|
159
|
+
status: string;
|
|
160
|
+
sessionToken: string;
|
|
161
|
+
user: {
|
|
162
|
+
userId: string;
|
|
163
|
+
externalUserId?: string;
|
|
164
|
+
email?: string;
|
|
165
|
+
metadata?: Record<string, unknown>;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
131
168
|
type OnboardingStartOptions = {
|
|
132
169
|
user_role: 'maintainer' | 'app_user';
|
|
133
170
|
};
|
|
@@ -217,7 +254,8 @@ type RegisterStartRequest = {
|
|
|
217
254
|
external_user_id: string;
|
|
218
255
|
};
|
|
219
256
|
type AuthStartRequest = {
|
|
220
|
-
|
|
257
|
+
/** Omit for discoverable (resident) passkeys; server returns allowCredentials: [] */
|
|
258
|
+
external_user_id?: string;
|
|
221
259
|
};
|
|
222
260
|
type RegisterFinishRequest = {
|
|
223
261
|
session_id: string;
|
|
@@ -461,6 +499,8 @@ declare class ApiClient {
|
|
|
461
499
|
getCrossDeviceContext(sessionId: string): Promise<Result<CrossDeviceContextResult, TryMellonError>>;
|
|
462
500
|
verifyCrossDeviceAuth(request: CrossDeviceVerifyRequest): Promise<Result<void, TryMellonError>>;
|
|
463
501
|
verifyCrossDeviceRegistration(request: CrossDeviceVerifyRegistrationRequest): Promise<Result<void, TryMellonError>>;
|
|
502
|
+
verifyAccountRecoveryOtp(externalUserId: string, otp: string): Promise<Result<RecoveryVerifyResponse, TryMellonError>>;
|
|
503
|
+
completeAccountRecovery(recoverySessionId: string, credential: Record<string, unknown>): Promise<Result<RecoveryCompleteResponse, TryMellonError>>;
|
|
464
504
|
}
|
|
465
505
|
|
|
466
506
|
declare class OnboardingManager {
|
|
@@ -522,6 +562,7 @@ declare class TryMellon {
|
|
|
522
562
|
}, TryMellonError>>;
|
|
523
563
|
approve: (sessionId: string) => Promise<Result<void, TryMellonError>>;
|
|
524
564
|
};
|
|
565
|
+
recoverAccount: (options: RecoverAccountOptions) => Promise<Result<RecoverAccountResult, TryMellonError>>;
|
|
525
566
|
};
|
|
526
567
|
}
|
|
527
568
|
|
package/dist/index.global.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var TryMellon=(function(exports){'use strict';var g=e=>({ok:true,value:e}),a=e=>({ok:false,error:e});var P=class e extends Error{code;details;isTryMellonError=true;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e);}},Pe={NOT_SUPPORTED:"WebAuthn is not supported in this environment",USER_CANCELLED:"User cancelled the operation",PASSKEY_NOT_FOUND:"Passkey not found",SESSION_EXPIRED:"Session has expired",NETWORK_FAILURE:"Network request failed",INVALID_ARGUMENT:"Invalid argument provided",TIMEOUT:"Operation timed out",ABORTED:"Operation was aborted",ABORT_ERROR:"Operation aborted by user or timeout",CHALLENGE_MISMATCH:"This link was already used or expired. Please try again from your computer.",UNKNOWN_ERROR:"An unknown error occurred"};function R(e,r,t){return new P(e,r??Pe[e],t)}function w(e){return e instanceof P||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===true}function N(){return R("NOT_SUPPORTED")}function De(){return R("USER_CANCELLED")}function Me(e){return R("NETWORK_FAILURE",void 0,{cause:e?.message,originalError:e})}function we(){return R("TIMEOUT")}function b(e,r){return R("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function ye(e){return R("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function $(e){return R("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function X(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw b(r,"must use http or https protocol")}catch(t){throw w(t)?t:b(r,"must be a valid URL")}}function I(e,r,t,n){if(!Number.isFinite(e))throw b(r,"must be a finite number");if(e<t||e>n)throw b(r,`must be between ${t} and ${n}`)}function U(e,r){if(typeof e!="string"||e.length===0)throw b(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw b(r,"must be a valid base64url string")}var Ne={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function f(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=Ne[r]??"UNKNOWN_ERROR";return R(n,t,{originalError:e})}return e instanceof Error?R("UNKNOWN_ERROR",e.message,{originalError:e}):R("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l(e){return typeof e=="string"}function _(e){return typeof e=="number"&&Number.isFinite(e)}function F(e){return typeof e=="boolean"}function C(e){return Array.isArray(e)}function i(e,r){return a(R("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function p(e,r){return e[r]}function Y(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!y(t))return i("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"rp");if(!y(n)||!l(n.name)||!l(n.id))return i("Invalid API response: challenge.rp must have name and id strings",{originalData:e});let s=p(t,"user");if(!y(s)||!l(s.id)||!l(s.name)||!l(s.displayName))return i("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:e});let o=p(t,"challenge");if(!l(o))return i("Invalid API response: challenge.challenge must be string",{originalData:e});let u=p(t,"pubKeyCredParams");if(!C(u))return i("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let c of u)if(!y(c)||c.type!=="public-key"||!_(c.alg))return i("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});let m=t.timeout;if(m!==void 0&&!_(m))return i("Invalid API response: challenge.timeout must be number",{originalData:e});let d=t.excludeCredentials;if(d!==void 0){if(!C(d))return i("Invalid API response: excludeCredentials must be array",{originalData:e});for(let c of d)if(!y(c)||c.type!=="public-key"||!l(c.id))return i("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let h=t.authenticatorSelection;return h!==void 0&&!y(h)?i("Invalid API response: authenticatorSelection must be object",{originalData:e}):g({session_id:r,challenge:{rp:n,user:s,challenge:o,pubKeyCredParams:u,...m!==void 0&&{timeout:m},...d!==void 0&&{excludeCredentials:d},...h!==void 0&&{authenticatorSelection:h}}})}function G(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id");if(!l(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=p(e,"challenge");if(!y(t))return i("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=p(t,"challenge"),s=p(t,"rpId"),o=t.allowCredentials;if(!l(n))return i("Invalid API response: challenge.challenge must be string",{originalData:e});if(!l(s))return i("Invalid API response: challenge.rpId must be string",{originalData:e});if(o!==void 0&&!C(o))return i("Invalid API response: allowCredentials must be array",{originalData:e});if(o){for(let d of o)if(!y(d)||d.type!=="public-key"||!l(d.id))return i("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let u=t.timeout;if(u!==void 0&&!_(u))return i("Invalid API response: challenge.timeout must be number",{originalData:e});let m=t.userVerification;return m!==void 0&&!["required","preferred","discouraged"].includes(String(m))?i("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):g({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:o??[],...u!==void 0&&{timeout:u},...m!==void 0&&{userVerification:m}}})}function z(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"credential_id"),t=p(e,"status"),n=p(e,"session_token"),s=p(e,"user");if(!l(r))return i("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!l(t))return i("Invalid API response: status must be string",{field:"status",originalData:e});if(!l(n))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!y(s))return i("Invalid API response: user must be object",{field:"user",originalData:e});let o=p(s,"user_id"),u=p(s,"external_user_id");if(!l(o)||!l(u))return i("Invalid API response: user must have user_id and external_user_id strings",{originalData:e});let m=s.email,d=s.metadata;return m!==void 0&&!l(m)?i("Invalid API response: user.email must be string",{originalData:e}):d!==void 0&&(typeof d!="object"||d===null)?i("Invalid API response: user.metadata must be object",{originalData:e}):g({credential_id:r,status:t,session_token:n,user:{user_id:o,external_user_id:u,...m!==void 0&&{email:m},...d!==void 0&&{metadata:d}}})}function J(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"authenticated"),t=p(e,"session_token"),n=p(e,"user"),s=p(e,"signals");if(!F(r))return i("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!l(t))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!y(n))return i("Invalid API response: user must be object",{field:"user",originalData:e});let o=p(n,"user_id"),u=p(n,"external_user_id");return !l(o)||!l(u)?i("Invalid API response: user must have user_id and external_user_id strings",{originalData:e}):s!==void 0&&!y(s)?i("Invalid API response: signals must be object",{originalData:e}):g({authenticated:r,session_token:t,user:{user_id:o,external_user_id:u,...n.email!==void 0&&{email:n.email},...n.metadata!==void 0&&{metadata:n.metadata}},signals:s})}function Z(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"valid"),t=p(e,"user_id"),n=p(e,"external_user_id"),s=p(e,"tenant_id"),o=p(e,"app_id");return F(r)?l(t)?l(n)?l(s)?l(o)?g({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:o}):i("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):i("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):i("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):i("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):i("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function Q(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"sessionToken");return l(r)?g({sessionToken:r}):i("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var Ue=["pending_passkey","pending_data","completed"],Fe=["pending_data","completed"];function ee(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return l(r)?l(t)?_(n)?g({session_id:r,onboarding_url:t,expires_in:n}):i("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):i("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):i("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function re(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"status"),t=p(e,"onboarding_url"),n=p(e,"expires_in");return !l(r)||!Ue.includes(r)?i("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):l(t)?_(n)?g({status:r,onboarding_url:t,expires_in:n}):i("Invalid API response: expires_in must be number",{originalData:e}):i("Invalid API response: onboarding_url must be string",{originalData:e})}function te(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"onboarding_url");if(!l(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return i("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!l(n))return i("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,o;if(s!==void 0){let u=Le(s);if(!u.ok)return u;o=u.value;}return g({session_id:r,status:"pending_passkey",onboarding_url:n,...o!==void 0&&{challenge:o}})}function Le(e){if(!y(e))return i("Invalid API response: challenge must be object",{originalData:e});let r=p(e,"rp"),t=p(e,"user"),n=p(e,"challenge"),s=p(e,"pubKeyCredParams");if(!y(r)||!l(r.name)||!l(r.id))return i("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!y(t)||!l(t.id)||!l(t.name)||!l(t.displayName))return i("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!l(n))return i("Invalid API response: challenge.challenge must be string",{originalData:e});if(!C(s))return i("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let o of s)if(!y(o)||o.type!=="public-key"||!_(o.alg))return i("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return g({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function ne(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id");return l(r)?!l(t)||!Fe.includes(t)?i("Invalid API response: status must be pending_data|completed",{originalData:e}):l(n)?l(s)?g({session_id:r,status:t,user_id:n,tenant_id:s}):i("Invalid API response: tenant_id must be string",{originalData:e}):i("Invalid API response: user_id must be string",{originalData:e}):i("Invalid API response: session_id must be string",{originalData:e})}function se(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=p(e,"session_id"),t=p(e,"status"),n=p(e,"user_id"),s=p(e,"tenant_id"),o=p(e,"session_token");return l(r)?t!=="completed"?i("Invalid API response: status must be completed",{originalData:e}):!l(n)||!l(s)||!l(o)?i("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):g({session_id:r,status:"completed",user_id:n,tenant_id:s,session_token:o}):i("Invalid API response: session_id must be string",{originalData:e})}function Ke(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&r.rp!=null&&typeof r.rp=="object"&&r.user!=null&&typeof r.user=="object"&&Array.isArray(r.pubKeyCredParams)}function qe(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function L(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=e.session_id,t=e.qr_url,n=e.expires_at;return !l(r)||!l(t)||!l(n)?i("Invalid API response: missing required fields",{originalData:e}):g({session_id:r,qr_url:t,expires_at:n})}function ie(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=e.status;return !l(r)||!["pending","authenticated","completed"].includes(r)?i("Invalid API response: invalid status",{originalData:e}):g({status:r,user_id:e.user_id,session_token:e.session_token})}function oe(e){if(!y(e))return i("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return y(n)?t==="registration"?Ke(n)?g({type:"registration",options:n}):i("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):qe(n)?g({type:"auth",options:n}):i("Invalid API response: auth options must have challenge and rpId",{originalData:e}):i("Invalid API response: options are required",{originalData:e})}var K=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n;}mergeHeaders(r){return {...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,o=await this.httpClient.post(s,t,this.mergeHeaders());return o.ok?n(o.value):a(o.error)}async get(r,t,n){let s=`${this.baseUrl}${r}`,o=await this.httpClient.get(s,this.mergeHeaders(n));return o.ok?t(o.value):a(o.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,Y)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,G)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,z)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,J)}async validateSession(r){return this.get("/v1/sessions/validate",Z,{Authorization:`Bearer ${r}`})}async startEmailFallback(r){let t=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(t,{userId:r.userId,email:r.email},this.mergeHeaders());return n.ok?g(void 0):a(n.error)}async verifyEmailCode(r,t){return this.post("/v1/fallback/email/verify",{userId:r,code:t},Q)}async startOnboarding(r){return this.post("/onboarding/start",r,ee)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,re)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,te)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,ne)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,se)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},L)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},L)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,ie)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,oe)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?g(void 0):a(n.error)}async verifyCrossDeviceRegistration(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify-registration`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?g(void 0):a(n.error)}};var je=3e4;function Ve(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();throw new Error("Web Crypto API is required but not available.")}function Re(e,r){let t=r*Math.pow(2,e);return Math.min(t,je)}function Be(e,r){return e!=="GET"?false:r>=500||r===429}var q=class{constructor(r,t=0,n=1e3,s){this.timeoutMs=r;this.maxRetries=t;this.retryDelayMs=n;this.logger=s;}async get(r,t){return this.request(r,{method:"GET",headers:t})}async post(r,t,n){return this.request(r,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n}})}async request(r,t){let n=(t.method??"GET").toUpperCase(),s=Ve(),o=new Headers(t.headers);o.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let u;for(let m=0;m<=this.maxRetries;m++)try{let d=new AbortController,h=setTimeout(()=>d.abort(),this.timeoutMs);try{let c=await fetch(r,{...t,headers:o,signal:d.signal});if(!c.ok){let O;try{O=await c.json();}catch{}let H=O,A=H?.message??c.statusText,ge=H?.error,me=R(ge==="challenge_mismatch"?"CHALLENGE_MISMATCH":ge??"NETWORK_FAILURE",A,{requestId:s,status:c.status,statusText:c.statusText,data:O});if(Be(n,c.status)&&m<this.maxRetries){u=me,await new Promise(ke=>setTimeout(ke,Re(m,this.retryDelayMs)));continue}return a(me)}if(c.status===204)return g(void 0);if(c.headers.get("content-length")==="0")return g(void 0);let M=await c.json();return g(M)}finally{clearTimeout(h);}}catch(d){if(u=d,n==="GET"&&m<this.maxRetries)await new Promise(c=>setTimeout(c,Re(m,this.retryDelayMs)));else break}return u instanceof Error&&u.name==="AbortError"?a(R("TIMEOUT","Request timed out",{requestId:s})):a(R("NETWORK_FAILURE",u instanceof Error?u.message:"Request failed",{requestId:s,cause:u}))}};function S(){try{return !(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return false}}async function We(){try{return !S()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?false:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return false}}async function fe(){let e=S(),r=await We();return {isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function E(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw $("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function He(e){if(typeof globalThis.atob>"u")throw $("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,o=>o.charCodeAt(0))}function x(e){let r=He(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function T(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw ye(r)}function he(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function k(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!he(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw R("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:r});let t=r.clientDataJSON,n=r.attestationObject;return {id:e.id,rawId:E(e.rawId),response:{clientDataJSON:E(t),attestationObject:E(n)},type:"public-key"}}function j(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!he(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw R("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:r});let t=r.clientDataJSON,n=r.authenticatorData,s=r.signature,o=r.userHandle;return {id:e.id,rawId:E(e.rawId),response:{authenticatorData:E(n),clientDataJSON:E(t),signature:E(s),...o&&{userHandle:E(o)}},type:"public-key"}}function D(e,r){try{U(e.challenge,"challenge"),U(e.user.id,"user.id");let t=x(e.challenge),n=x(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let o={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(u=>({id:x(u.id),type:u.type,...u.transports&&{transports:u.transports}}))}};return g({publicKey:o})}catch(t){return a(f(t))}}function ae(e,r){try{U(e.challenge,"challenge");let t=x(e.challenge);return g({publicKey:{challenge:t,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:x(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return a(f(t))}}async function be(e,r,t){try{if(t.emit("start",{type:"start",operation:"register"}),!S()){let c=N();return t.emit("error",{type:"error",error:c}),a(c)}let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let c=b("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:c}),a(c)}let s=await r.startRegister({external_user_id:n});if(!s.ok)return t.emit("error",{type:"error",error:s.error}),a(s.error);let o=D(s.value.challenge,e.authenticatorType);if(!o.ok)return t.emit("error",{type:"error",error:o.error}),a(o.error);let u={...o.value,...e.signal&&{signal:e.signal}},m=await navigator.credentials.create(u);if(!m){let c=b("credential","creation failed");return t.emit("error",{type:"error",error:c}),a(c)}try{T(m);}catch(c){let v=f(c);return t.emit("error",{type:"error",error:v}),a(v)}let d=await r.finishRegister({session_id:s.value.session_id,credential:k(m)});if(!d.ok)return t.emit("error",{type:"error",error:d.error}),a(d.error);let h={success:true,credentialId:d.value.credential_id,credential_id:d.value.credential_id,status:d.value.status,sessionToken:d.value.session_token,user:{userId:d.value.user.user_id,externalUserId:d.value.user.external_user_id,email:d.value.user.email,metadata:d.value.user.metadata}};return t.emit("success",{type:"success",operation:"register"}),g(h)}catch(n){let s=f(n);return t.emit("error",{type:"error",error:s}),a(s)}}async function ve(e,r,t){try{if(t.emit("start",{type:"start",operation:"authenticate"}),!S()){let c=N();return t.emit("error",{type:"error",error:c}),a(c)}let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let c=b("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:c}),a(c)}let s=await r.startAuth({external_user_id:n});if(!s.ok)return t.emit("error",{type:"error",error:s.error}),a(s.error);let o=ae(s.value.challenge,e.mediation);if(!o.ok)return t.emit("error",{type:"error",error:o.error}),a(o.error);let u={...o.value,...e.signal&&{signal:e.signal}},m=await navigator.credentials.get(u);if(!m){let c=b("credential","retrieval failed");return t.emit("error",{type:"error",error:c}),a(c)}try{T(m);}catch(c){let v=f(c);return t.emit("error",{type:"error",error:v}),a(v)}let d=await r.finishAuthentication({session_id:s.value.session_id,credential:j(m)});if(!d.ok)return t.emit("error",{type:"error",error:d.error}),a(d.error);let h={authenticated:d.value.authenticated,sessionToken:d.value.session_token,user:{userId:d.value.user.user_id,externalUserId:d.value.user.external_user_id,email:d.value.user.email,metadata:d.value.user.metadata},signals:d.value.signals};return t.emit("success",{type:"success",operation:"authenticate"}),g(h)}catch(n){let s=f(n);return t.emit("error",{type:"error",error:s}),a(s)}}var $e=2e3,Xe=60,V=class{constructor(r){this.apiClient=r;}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return a(t.error);let{session_id:n}=t.value;for(let s=0;s<Xe;s++){await new Promise(d=>setTimeout(d,$e));let o=await this.apiClient.getOnboardingStatus(n);if(!o.ok)return a(o.error);let u=o.value.status,m=o.value.onboarding_url;if(u==="pending_passkey"){let d=await this.apiClient.getOnboardingRegister(n);if(!d.ok)return a(d.error);let h=d.value;if(!h.challenge)return a(R("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:m}));let c=D(h.challenge);if(!c.ok)return a(c.error);let v;try{v=await navigator.credentials.create(c.value);}catch(A){return a(f(A))}try{T(v,"create");}catch(A){return a(f(A))}let M;try{M=k(v);}catch(A){return a(f(A))}let O=await this.apiClient.registerOnboardingPasskey(n,{credential:M,challenge:h.challenge.challenge});return O.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):a(O.error)}if(u==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return a(R("TIMEOUT","Onboarding timed out"))}};var Ye=2e3,Ge=60,B=class{constructor(r){this.apiClient=r;}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t){for(let n=0;n<Ge;n++){if(t?.aborted)return a(R("ABORT_ERROR","Operation aborted by user or timeout"));let s=await this.apiClient.getCrossDeviceStatus(r);if(!s.ok)return a(s.error);if(s.value.status==="completed")return !s.value.session_token||!s.value.user_id?a(R("UNKNOWN_ERROR","Missing data in completed session")):g({session_token:s.value.session_token,user_id:s.value.user_id});if(t?.aborted)return a(R("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(o=>{let u=setTimeout(()=>{o(null),t?.removeEventListener("abort",m);},Ye),m=()=>{clearTimeout(u),o(null);};t?.addEventListener("abort",m);}),t?.aborted)return a(R("ABORT_ERROR","Operation aborted by user or timeout"))}return a(R("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return a(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=D(t.options);if(!n.ok)return a(n.error);let s;try{s=await navigator.credentials.create(n.value);}catch(u){return a(f(u))}try{T(s,"create");}catch(u){return a(f(u))}let o;try{o=k(s);}catch(u){return a(f(u))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:o})}async executeAuthApproval(r,t){let n=ae(t.options);if(!n.ok)return a(n.error);let s;try{s=await navigator.credentials.get(n.value);}catch(u){return a(f(u))}try{T(s,"get");}catch(u){return a(f(u))}let o;try{o=j(s);}catch(u){return a(f(u))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:o})}};var W=class{handlers;constructor(){this.handlers=new Map;}on(r,t){let n=this.handlers.get(r);return n||(n=new Set,this.handlers.set(r,n)),n.add(t),()=>{this.off(r,t);}}off(r,t){let n=this.handlers.get(r);n&&(n.delete(t),n.size===0&&this.handlers.delete(r));}emit(r,t){let n=this.handlers.get(r);n&&n.forEach(s=>{try{s(t);}catch{}});}removeAllListeners(){this.handlers.clear();}};var le="https://api.trymellonauth.com",Ee="https://api.trymellonauth.com/v1/telemetry";var ue="trymellon_sandbox_session_token_v1";function _e(e){return {async send(r){let t=JSON.stringify(r);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,t);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"},keepalive:true});}}}function pe(e,r){return {event:e,latencyMs:r,ok:true}}var de=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;onboarding;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return a(b("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return a(b("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??le;X(s,"apiBaseUrl");let o=r.timeoutMs??3e4;return I(o,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&I(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&I(r.retryDelayMs,"retryDelayMs",100,1e4),g(new e(r))}catch(t){return w(t)?a(t):a(b("config",t.message))}}constructor(r){this.sandbox=r.sandbox===true,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:ue;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw b("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw b("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??le;X(s,"apiBaseUrl");let o=r.timeoutMs??3e4;I(o,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&I(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&I(r.retryDelayMs,"retryDelayMs",100,1e4);let u=r.maxRetries??3,m=r.retryDelayMs??1e3,d=new q(o,u,m,r.logger),h=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),c={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...h&&{Origin:h}};this.apiClient=new K(d,s,c),this.onboarding=new V(this.apiClient),this.crossDeviceManager=new B(this.apiClient),this.eventEmitter=new W,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??_e(r.telemetryEndpoint??Ee));}static isSupported(){return S()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(g({success:true,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await be(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(pe("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(g({authenticated:true,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await ve(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(pe("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(g({valid:true,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return fe()}on(r,t){return this.eventEmitter.on(r,t)}version(){return "1.4.9"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>this.apiClient.verifyEmailCode(r.userId,r.code)}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t)=>this.crossDeviceManager.waitForSession(r,t),approve:r=>this.crossDeviceManager.approve(r)}}};var ce=class{debug(r,t){t&&Object.keys(t).length>0?console.debug(`[TryMellon] ${r}`,t):console.debug(`[TryMellon] ${r}`);}info(r,t){t&&Object.keys(t).length>0?console.info(`[TryMellon] ${r}`,t):console.info(`[TryMellon] ${r}`);}warn(r,t){t&&Object.keys(t).length>0?console.warn(`[TryMellon] ${r}`,t):console.warn(`[TryMellon] ${r}`);}error(r,t){t&&Object.keys(t).length>0?console.error(`[TryMellon] ${r}`,t):console.error(`[TryMellon] ${r}`);}};
|
|
2
|
-
exports.ConsoleLogger=
|
|
1
|
+
var TryMellon=(function(exports){'use strict';var g=e=>({ok:true,value:e}),a=e=>({ok:false,error:e});var w=class e extends Error{code;details;isTryMellonError=true;constructor(r,t,n){super(t),this.name="TryMellonError",this.code=r,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,e);}},we={NOT_SUPPORTED:"WebAuthn is not supported in this environment",USER_CANCELLED:"User cancelled the operation",PASSKEY_NOT_FOUND:"Passkey not found",SESSION_EXPIRED:"Session has expired",NETWORK_FAILURE:"Network request failed",INVALID_ARGUMENT:"Invalid argument provided",TIMEOUT:"Operation timed out",ABORTED:"Operation was aborted",ABORT_ERROR:"Operation aborted by user or timeout",CHALLENGE_MISMATCH:"This link was already used or expired. Please try again from your computer.",UNKNOWN_ERROR:"An unknown error occurred"};function R(e,r,t){return new w(e,r??we[e],t)}function N(e){return e instanceof w||typeof e=="object"&&e!==null&&"isTryMellonError"in e&&e.isTryMellonError===true}function P(){return R("NOT_SUPPORTED")}function Ne(){return R("USER_CANCELLED")}function Ue(e){return R("NETWORK_FAILURE",void 0,{cause:e?.message,originalError:e})}function Fe(){return R("TIMEOUT")}function v(e,r){return R("INVALID_ARGUMENT",`Invalid argument: ${e} - ${r}`,{field:e,reason:r})}function fe(e){return R("UNKNOWN_ERROR",`Failed to ${e} credential`,{operation:e})}function $(e){return R("NOT_SUPPORTED",`No base64 ${e==="encode"?"encoding":"decoding"} available`,{type:e})}function X(e,r){try{let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw v(r,"must use http or https protocol")}catch(t){throw N(t)?t:v(r,"must be a valid URL")}}function S(e,r,t,n){if(!Number.isFinite(e))throw v(r,"must be a finite number");if(e<t||e>n)throw v(r,`must be between ${t} and ${n}`)}function U(e,r){if(typeof e!="string"||e.length===0)throw v(r,"must be a non-empty string");if(!/^[A-Za-z0-9_-]+$/.test(e))throw v(r,"must be a valid base64url string")}var Le={NotAllowedError:"USER_CANCELLED",AbortError:"ABORTED",NotSupportedError:"NOT_SUPPORTED",SecurityError:"NOT_SUPPORTED",InvalidStateError:"UNKNOWN_ERROR",UnknownError:"UNKNOWN_ERROR"};function h(e){if(e instanceof DOMException){let r=e.name,t=e.message||"WebAuthn operation failed",n=Le[r]??"UNKNOWN_ERROR";return R(n,t,{originalError:e})}return e instanceof Error?R("UNKNOWN_ERROR",e.message,{originalError:e}):R("UNKNOWN_ERROR","An unknown error occurred",{originalError:e})}function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e){return typeof e=="string"}function A(e){return typeof e=="number"&&Number.isFinite(e)}function F(e){return typeof e=="boolean"}function D(e){return Array.isArray(e)}function i(e,r){return a(R("UNKNOWN_ERROR",e,{...r,originalData:r?.originalData}))}function c(e,r){return e[r]}function Y(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id");if(!u(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=c(e,"challenge");if(!m(t))return i("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=c(t,"rp");if(!m(n)||!u(n.name)||!u(n.id))return i("Invalid API response: challenge.rp must have name and id strings",{originalData:e});let s=c(t,"user");if(!m(s)||!u(s.id)||!u(s.name)||!u(s.displayName))return i("Invalid API response: challenge.user must have id, name, displayName strings",{originalData:e});let o=c(t,"challenge");if(!u(o))return i("Invalid API response: challenge.challenge must be string",{originalData:e});let l=c(t,"pubKeyCredParams");if(!D(l))return i("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let d of l)if(!m(d)||d.type!=="public-key"||!A(d.alg))return i("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});let y=t.timeout;if(y!==void 0&&!A(y))return i("Invalid API response: challenge.timeout must be number",{originalData:e});let p=t.excludeCredentials;if(p!==void 0){if(!D(p))return i("Invalid API response: excludeCredentials must be array",{originalData:e});for(let d of p)if(!m(d)||d.type!=="public-key"||!u(d.id))return i("Invalid API response: excludeCredentials items must have id and type",{originalData:e})}let f=t.authenticatorSelection;return f!==void 0&&!m(f)?i("Invalid API response: authenticatorSelection must be object",{originalData:e}):g({session_id:r,challenge:{rp:n,user:s,challenge:o,pubKeyCredParams:l,...y!==void 0&&{timeout:y},...p!==void 0&&{excludeCredentials:p},...f!==void 0&&{authenticatorSelection:f}}})}function z(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id");if(!u(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});let t=c(e,"challenge");if(!m(t))return i("Invalid API response: challenge must be object",{field:"challenge",originalData:e});let n=c(t,"challenge"),s=c(t,"rpId"),o=t.allowCredentials;if(!u(n))return i("Invalid API response: challenge.challenge must be string",{originalData:e});if(!u(s))return i("Invalid API response: challenge.rpId must be string",{originalData:e});if(o!==void 0&&!D(o))return i("Invalid API response: allowCredentials must be array",{originalData:e});if(o){for(let p of o)if(!m(p)||p.type!=="public-key"||!u(p.id))return i("Invalid API response: allowCredentials items must have id and type",{originalData:e})}let l=t.timeout;if(l!==void 0&&!A(l))return i("Invalid API response: challenge.timeout must be number",{originalData:e});let y=t.userVerification;return y!==void 0&&!["required","preferred","discouraged"].includes(String(y))?i("Invalid API response: userVerification must be required|preferred|discouraged",{originalData:e}):g({session_id:r,challenge:{challenge:n,rpId:s,allowCredentials:o??[],...l!==void 0&&{timeout:l},...y!==void 0&&{userVerification:y}}})}function G(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"credential_id"),t=c(e,"status"),n=c(e,"session_token"),s=c(e,"user");if(!u(r))return i("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!u(t))return i("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(n))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!m(s))return i("Invalid API response: user must be object",{field:"user",originalData:e});let o=c(s,"user_id"),l=c(s,"external_user_id");if(!u(o)||!u(l))return i("Invalid API response: user must have user_id and external_user_id strings",{originalData:e});let y=s.email,p=s.metadata;return y!==void 0&&!u(y)?i("Invalid API response: user.email must be string",{originalData:e}):p!==void 0&&(typeof p!="object"||p===null)?i("Invalid API response: user.metadata must be object",{originalData:e}):g({credential_id:r,status:t,session_token:n,user:{user_id:o,external_user_id:l,...y!==void 0&&{email:y},...p!==void 0&&{metadata:p}}})}function J(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"authenticated"),t=c(e,"session_token"),n=c(e,"user"),s=c(e,"signals");if(!F(r))return i("Invalid API response: authenticated must be boolean",{field:"authenticated",originalData:e});if(!u(t))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!m(n))return i("Invalid API response: user must be object",{field:"user",originalData:e});let o=c(n,"user_id"),l=c(n,"external_user_id");return !u(o)||!u(l)?i("Invalid API response: user must have user_id and external_user_id strings",{originalData:e}):s!==void 0&&!m(s)?i("Invalid API response: signals must be object",{originalData:e}):g({authenticated:r,session_token:t,user:{user_id:o,external_user_id:l,...n.email!==void 0&&{email:n.email},...n.metadata!==void 0&&{metadata:n.metadata}},signals:s})}function Z(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"valid"),t=c(e,"user_id"),n=c(e,"external_user_id"),s=c(e,"tenant_id"),o=c(e,"app_id");return F(r)?u(t)?u(n)?u(s)?u(o)?g({valid:r,user_id:t,external_user_id:n,tenant_id:s,app_id:o}):i("Invalid API response: app_id must be string",{field:"app_id",originalData:e}):i("Invalid API response: tenant_id must be string",{field:"tenant_id",originalData:e}):i("Invalid API response: external_user_id must be string",{field:"external_user_id",originalData:e}):i("Invalid API response: user_id must be string",{field:"user_id",originalData:e}):i("Invalid API response: valid must be boolean",{field:"valid",originalData:e})}function Q(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"sessionToken");return u(r)?g({sessionToken:r}):i("Invalid API response: sessionToken must be string",{field:"sessionToken",originalData:e})}var Ke=["pending_passkey","pending_data","completed"],je=["pending_data","completed"];function ee(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"onboarding_url"),n=c(e,"expires_in");return u(r)?u(t)?A(n)?g({session_id:r,onboarding_url:t,expires_in:n}):i("Invalid API response: expires_in must be number",{field:"expires_in",originalData:e}):i("Invalid API response: onboarding_url must be string",{field:"onboarding_url",originalData:e}):i("Invalid API response: session_id must be string",{field:"session_id",originalData:e})}function re(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"status"),t=c(e,"onboarding_url"),n=c(e,"expires_in");return !u(r)||!Ke.includes(r)?i("Invalid API response: status must be pending_passkey|pending_data|completed",{field:"status",originalData:e}):u(t)?A(n)?g({status:r,onboarding_url:t,expires_in:n}):i("Invalid API response: expires_in must be number",{originalData:e}):i("Invalid API response: onboarding_url must be string",{originalData:e})}function te(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"onboarding_url");if(!u(r))return i("Invalid API response: session_id must be string",{field:"session_id",originalData:e});if(t!=="pending_passkey")return i("Invalid API response: status must be pending_passkey",{field:"status",originalData:e});if(!u(n))return i("Invalid API response: onboarding_url must be string",{originalData:e});let s=e.challenge,o;if(s!==void 0){let l=qe(s);if(!l.ok)return l;o=l.value;}return g({session_id:r,status:"pending_passkey",onboarding_url:n,...o!==void 0&&{challenge:o}})}function qe(e){if(!m(e))return i("Invalid API response: challenge must be object",{originalData:e});let r=c(e,"rp"),t=c(e,"user"),n=c(e,"challenge"),s=c(e,"pubKeyCredParams");if(!m(r)||!u(r.name)||!u(r.id))return i("Invalid API response: challenge.rp must have name and id",{originalData:e});if(!m(t)||!u(t.id)||!u(t.name)||!u(t.displayName))return i("Invalid API response: challenge.user must have id, name, displayName",{originalData:e});if(!u(n))return i("Invalid API response: challenge.challenge must be string",{originalData:e});if(!D(s))return i("Invalid API response: challenge.pubKeyCredParams must be array",{originalData:e});for(let o of s)if(!m(o)||o.type!=="public-key"||!A(o.alg))return i("Invalid API response: pubKeyCredParams items must have type and alg",{originalData:e});return g({rp:r,user:t,challenge:n,pubKeyCredParams:s})}function ne(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"user_id"),s=c(e,"tenant_id");return u(r)?!u(t)||!je.includes(t)?i("Invalid API response: status must be pending_data|completed",{originalData:e}):u(n)?u(s)?g({session_id:r,status:t,user_id:n,tenant_id:s}):i("Invalid API response: tenant_id must be string",{originalData:e}):i("Invalid API response: user_id must be string",{originalData:e}):i("Invalid API response: session_id must be string",{originalData:e})}function se(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"session_id"),t=c(e,"status"),n=c(e,"user_id"),s=c(e,"tenant_id"),o=c(e,"session_token");return u(r)?t!=="completed"?i("Invalid API response: status must be completed",{originalData:e}):!u(n)||!u(s)||!u(o)?i("Invalid API response: user_id, tenant_id, session_token must be strings",{originalData:e}):g({session_id:r,status:"completed",user_id:n,tenant_id:s,session_token:o}):i("Invalid API response: session_id must be string",{originalData:e})}function Ve(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&r.rp!=null&&typeof r.rp=="object"&&r.user!=null&&typeof r.user=="object"&&Array.isArray(r.pubKeyCredParams)}function We(e){if(!e||typeof e!="object")return false;let r=e;return typeof r.challenge=="string"&&typeof r.rpId=="string"}function L(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=e.session_id,t=e.qr_url,n=e.expires_at;return !u(r)||!u(t)||!u(n)?i("Invalid API response: missing required fields",{originalData:e}):g({session_id:r,qr_url:t,expires_at:n})}function ie(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=e.status;return !u(r)||!["pending","authenticated","completed"].includes(r)?i("Invalid API response: invalid status",{originalData:e}):g({status:r,user_id:e.user_id,session_token:e.session_token})}function oe(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=e.type,t=r==="registration"?"registration":"auth",n=e.options;return m(n)?t==="registration"?Ve(n)?g({type:"registration",options:n}):i("Invalid API response: registration options must have challenge, rp, user, pubKeyCredParams",{originalData:e}):We(n)?g({type:"auth",options:n}):i("Invalid API response: auth options must have challenge and rpId",{originalData:e}):i("Invalid API response: options are required",{originalData:e})}function ae(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"challenge"),t=c(e,"recovery_session_id");return m(r)?u(t)?g({challenge:r,recovery_session_id:t}):i("Invalid API response: recovery_session_id must be string",{field:"recovery_session_id",originalData:e}):i("Invalid API response: challenge must be object",{field:"challenge",originalData:e})}function le(e){if(!m(e))return i("Invalid API response: expected object",{originalData:e});let r=c(e,"status"),t=c(e,"session_token"),n=c(e,"user"),s=c(e,"credential_id");if(!u(r))return i("Invalid API response: status must be string",{field:"status",originalData:e});if(!u(t))return i("Invalid API response: session_token must be string",{field:"session_token",originalData:e});if(!u(s))return i("Invalid API response: credential_id must be string",{field:"credential_id",originalData:e});if(!m(n))return i("Invalid API response: user must be object",{field:"user",originalData:e});let o=c(n,"user_id");if(!u(o))return i("Invalid API response: user.user_id must be string",{field:"user.user_id",originalData:e});let l=n;return g({status:r,session_token:t,credential_id:s,user:{user_id:o,external_user_id:u(l.external_user_id)?l.external_user_id:void 0,email:u(l.email)?l.email:void 0,metadata:m(l.metadata)?l.metadata:void 0}})}var K=class{constructor(r,t,n={}){this.httpClient=r;this.baseUrl=t;this.defaultHeaders=n;}mergeHeaders(r){return {...this.defaultHeaders,...r}}async post(r,t,n){let s=`${this.baseUrl}${r}`,o=await this.httpClient.post(s,t,this.mergeHeaders());return o.ok?n(o.value):a(o.error)}async get(r,t,n){let s=`${this.baseUrl}${r}`,o=await this.httpClient.get(s,this.mergeHeaders(n));return o.ok?t(o.value):a(o.error)}async startRegister(r){return this.post("/v1/passkeys/register/start",r,Y)}async startAuth(r){return this.post("/v1/passkeys/auth/start",r,z)}async finishRegister(r){return this.post("/v1/passkeys/register/finish",r,G)}async finishAuthentication(r){return this.post("/v1/passkeys/auth/finish",r,J)}async validateSession(r){return this.get("/v1/sessions/validate",Z,{Authorization:`Bearer ${r}`})}async startEmailFallback(r){let t=`${this.baseUrl}/v1/fallback/email/start`,n=await this.httpClient.post(t,{userId:r.userId,email:r.email},this.mergeHeaders());return n.ok?g(void 0):a(n.error)}async verifyEmailCode(r,t){return this.post("/v1/fallback/email/verify",{userId:r,code:t},Q)}async startOnboarding(r){return this.post("/onboarding/start",r,ee)}async getOnboardingStatus(r){return this.get(`/onboarding/${r}/status`,re)}async getOnboardingRegister(r){return this.get(`/onboarding/${r}/register`,te)}async registerOnboardingPasskey(r,t){return this.post(`/onboarding/${r}/register-passkey`,t,ne)}async completeOnboarding(r,t){return this.post(`/onboarding/${r}/complete`,t,se)}async initCrossDeviceAuth(){return this.post("/v1/auth/cross-device/init",{},L)}async initCrossDeviceRegistration(r){return this.post("/v1/auth/cross-device/init-registration",{external_user_id:r.externalUserId},L)}async getCrossDeviceStatus(r){return this.get(`/v1/auth/cross-device/status/${r}`,ie)}async getCrossDeviceContext(r){return this.get(`/v1/auth/cross-device/context/${r}`,oe)}async verifyCrossDeviceAuth(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?g(void 0):a(n.error)}async verifyCrossDeviceRegistration(r){let t=`${this.baseUrl}/v1/auth/cross-device/verify-registration`,n=await this.httpClient.post(t,r,this.mergeHeaders());return n.ok?g(void 0):a(n.error)}async verifyAccountRecoveryOtp(r,t){return this.post("/v1/users/recovery/verify",{external_id:r,otp:t},ae)}async completeAccountRecovery(r,t){return this.post("/v1/users/recovery/complete",{recovery_session_id:r,credential:t},le)}};var Be=3e4;function He(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();throw new Error("Web Crypto API is required but not available.")}function he(e,r){let t=r*Math.pow(2,e);return Math.min(t,Be)}function $e(e,r){return e!=="GET"?false:r>=500||r===429}var j=class{constructor(r,t=0,n=1e3,s){this.timeoutMs=r;this.maxRetries=t;this.retryDelayMs=n;this.logger=s;}async get(r,t){return this.request(r,{method:"GET",headers:t})}async post(r,t,n){return this.request(r,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",...n}})}async request(r,t){let n=(t.method??"GET").toUpperCase(),s=He(),o=new Headers(t.headers);o.set("X-Request-Id",s),this.logger&&this.logger.debug("request",{requestId:s,url:r,method:n});let l;for(let y=0;y<=this.maxRetries;y++)try{let p=new AbortController,f=setTimeout(()=>p.abort(),this.timeoutMs);try{let d=await fetch(r,{...t,headers:o,signal:p.signal});if(!d.ok){let k;try{k=await d.json();}catch{}let H=k,C=H?.message??d.statusText,ye=H?.error,Re=R(ye==="challenge_mismatch"?"CHALLENGE_MISMATCH":ye??"NETWORK_FAILURE",C,{requestId:s,status:d.status,statusText:d.statusText,data:k});if($e(n,d.status)&&y<this.maxRetries){l=Re,await new Promise(Me=>setTimeout(Me,he(y,this.retryDelayMs)));continue}return a(Re)}if(d.status===204)return g(void 0);if(d.headers.get("content-length")==="0")return g(void 0);let O=await d.json();return g(O)}finally{clearTimeout(f);}}catch(p){if(l=p,n==="GET"&&y<this.maxRetries)await new Promise(d=>setTimeout(d,he(y,this.retryDelayMs)));else break}return l instanceof Error&&l.name==="AbortError"?a(R("TIMEOUT","Request timed out",{requestId:s})):a(R("NETWORK_FAILURE",l instanceof Error?l.message:"Request failed",{requestId:s,cause:l}))}};function _(){try{return !(typeof navigator>"u"||!navigator.credentials||typeof PublicKeyCredential>"u")}catch{return false}}async function Xe(){try{return !_()||typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable!="function"?false:await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return false}}async function ve(){let e=_(),r=await Xe();return {isPasskeySupported:e,platformAuthenticatorAvailable:r,recommendedFlow:e?"passkey":"fallback"}}function T(e){let r=new Uint8Array(e),t=Array.from(r,s=>String.fromCharCode(s)).join("");if(typeof globalThis.btoa>"u")throw $("encode");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ye(e){if(typeof globalThis.atob>"u")throw $("decode");let r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r.length%4,n=t===0?r:r+"=".repeat(4-t),s=globalThis.atob(n);return Uint8Array.from(s,o=>o.charCodeAt(0))}function M(e){let r=Ye(e),t=new ArrayBuffer(r.length);return new Uint8Array(t).set(r),t}function E(e,r="create"){if(!e||typeof e!="object"||!("id"in e)||!("rawId"in e)||!("response"in e))throw fe(r)}function be(e){return e!==null&&typeof e=="object"&&"clientDataJSON"in e&&e.clientDataJSON instanceof ArrayBuffer}function I(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!be(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("attestationObject"in r))throw R("UNKNOWN_ERROR","Invalid credential response structure for register: attestationObject is missing",{response:r});let t=r.clientDataJSON,n=r.attestationObject;return {id:e.id,rawId:T(e.rawId),response:{clientDataJSON:T(t),attestationObject:T(n)},type:"public-key"}}function q(e){if(!e.response)throw R("UNKNOWN_ERROR","Credential response is missing",{credential:e});let r=e.response;if(!be(r))throw R("UNKNOWN_ERROR","Invalid credential response structure",{response:r});if(!("authenticatorData"in r)||!("signature"in r))throw R("UNKNOWN_ERROR","Invalid credential response structure for auth: authenticatorData or signature is missing",{response:r});let t=r.clientDataJSON,n=r.authenticatorData,s=r.signature,o=r.userHandle;return {id:e.id,rawId:T(e.rawId),response:{authenticatorData:T(n),clientDataJSON:T(t),signature:T(s),...o&&{userHandle:T(o)}},type:"public-key"}}function x(e,r){try{U(e.challenge,"challenge"),U(e.user.id,"user.id");let t=M(e.challenge),n=M(e.user.id),s={userVerification:"preferred"};e.authenticatorSelection&&(s={...e.authenticatorSelection}),r&&(s={...s,authenticatorAttachment:r});let o={rp:{id:e.rp.id,name:e.rp.name},user:{id:n,name:e.user.name,displayName:e.user.displayName},challenge:t,pubKeyCredParams:e.pubKeyCredParams,...e.timeout!==void 0&&{timeout:e.timeout},attestation:"none",authenticatorSelection:s,...e.excludeCredentials&&{excludeCredentials:e.excludeCredentials.map(l=>({id:M(l.id),type:l.type,...l.transports&&{transports:l.transports}}))}};return g({publicKey:o})}catch(t){return a(h(t))}}function ue(e,r){try{U(e.challenge,"challenge");let t=M(e.challenge);return g({publicKey:{challenge:t,rpId:e.rpId,...e.timeout!==void 0&&{timeout:e.timeout},userVerification:e.userVerification??"preferred",...e.allowCredentials&&{allowCredentials:e.allowCredentials.map(n=>({id:M(n.id),type:n.type,...n.transports&&{transports:n.transports}}))}},...r!==void 0&&{mediation:r}})}catch(t){return a(h(t))}}async function Ee(e,r,t){try{if(t.emit("start",{type:"start",operation:"register"}),!_()){let d=P();return t.emit("error",{type:"error",error:d}),a(d)}let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let d=v("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:d}),a(d)}let s=await r.startRegister({external_user_id:n});if(!s.ok)return t.emit("error",{type:"error",error:s.error}),a(s.error);let o=x(s.value.challenge,e.authenticatorType);if(!o.ok)return t.emit("error",{type:"error",error:o.error}),a(o.error);let l={...o.value,...e.signal&&{signal:e.signal}},y=await navigator.credentials.create(l);if(!y){let d=v("credential","creation failed");return t.emit("error",{type:"error",error:d}),a(d)}try{E(y);}catch(d){let b=h(d);return t.emit("error",{type:"error",error:b}),a(b)}let p=await r.finishRegister({session_id:s.value.session_id,credential:I(y)});if(!p.ok)return t.emit("error",{type:"error",error:p.error}),a(p.error);let f={success:true,credentialId:p.value.credential_id,credential_id:p.value.credential_id,status:p.value.status,sessionToken:p.value.session_token,user:{userId:p.value.user.user_id,externalUserId:p.value.user.external_user_id,email:p.value.user.email,metadata:p.value.user.metadata}};return t.emit("success",{type:"success",operation:"register"}),g(f)}catch(n){let s=h(n);return t.emit("error",{type:"error",error:s}),a(s)}}async function _e(e,r,t){try{if(t.emit("start",{type:"start",operation:"authenticate"}),!_()){let b=P();return t.emit("error",{type:"error",error:b}),a(b)}let n=e.externalUserId??e.external_user_id,s=n!==void 0&&typeof n=="string"&&n.trim()!=="",o=await r.startAuth(s?{external_user_id:n.trim()}:{});if(!o.ok)return t.emit("error",{type:"error",error:o.error}),a(o.error);let l=ue(o.value.challenge,e.mediation);if(!l.ok)return t.emit("error",{type:"error",error:l.error}),a(l.error);let y={...l.value,...e.signal&&{signal:e.signal}},p=await navigator.credentials.get(y);if(!p){let b=v("credential","retrieval failed");return t.emit("error",{type:"error",error:b}),a(b)}try{E(p);}catch(b){let O=h(b);return t.emit("error",{type:"error",error:O}),a(O)}let f=await r.finishAuthentication({session_id:o.value.session_id,credential:q(p)});if(!f.ok)return t.emit("error",{type:"error",error:f.error}),a(f.error);let d={authenticated:f.value.authenticated,sessionToken:f.value.session_token,user:{userId:f.value.user.user_id,externalUserId:f.value.user.external_user_id,email:f.value.user.email,metadata:f.value.user.metadata},signals:f.value.signals};return t.emit("success",{type:"success",operation:"authenticate"}),g(d)}catch(n){let s=h(n);return t.emit("error",{type:"error",error:s}),a(s)}}var ze=2e3,Ge=60,V=class{constructor(r){this.apiClient=r;}async startFlow(r){let t=await this.apiClient.startOnboarding({user_role:r.user_role});if(!t.ok)return a(t.error);let{session_id:n}=t.value;for(let s=0;s<Ge;s++){await new Promise(p=>setTimeout(p,ze));let o=await this.apiClient.getOnboardingStatus(n);if(!o.ok)return a(o.error);let l=o.value.status,y=o.value.onboarding_url;if(l==="pending_passkey"){let p=await this.apiClient.getOnboardingRegister(n);if(!p.ok)return a(p.error);let f=p.value;if(!f.challenge)return a(R("NOT_SUPPORTED","Onboarding requires user action - complete passkey registration at the provided onboarding_url",{onboarding_url:y}));let d=x(f.challenge);if(!d.ok)return a(d.error);let b;try{b=await navigator.credentials.create(d.value);}catch(C){return a(h(C))}try{E(b,"create");}catch(C){return a(h(C))}let O;try{O=I(b);}catch(C){return a(h(C))}let k=await this.apiClient.registerOnboardingPasskey(n,{credential:O,challenge:f.challenge.challenge});return k.ok?await this.apiClient.completeOnboarding(n,{company_name:r.company_name}):a(k.error)}if(l==="completed")return await this.apiClient.completeOnboarding(n,{company_name:r.company_name})}return a(R("TIMEOUT","Onboarding timed out"))}};var Je=2e3,Ze=60,W=class{constructor(r){this.apiClient=r;}async init(){return this.apiClient.initCrossDeviceAuth()}async initRegistration(r){return this.apiClient.initCrossDeviceRegistration(r)}async waitForSession(r,t){for(let n=0;n<Ze;n++){if(t?.aborted)return a(R("ABORT_ERROR","Operation aborted by user or timeout"));let s=await this.apiClient.getCrossDeviceStatus(r);if(!s.ok)return a(s.error);if(s.value.status==="completed")return !s.value.session_token||!s.value.user_id?a(R("UNKNOWN_ERROR","Missing data in completed session")):g({session_token:s.value.session_token,user_id:s.value.user_id});if(t?.aborted)return a(R("ABORT_ERROR","Operation aborted by user or timeout"));if(await new Promise(o=>{let l=setTimeout(()=>{o(null),t?.removeEventListener("abort",y);},Je),y=()=>{clearTimeout(l),o(null);};t?.addEventListener("abort",y);}),t?.aborted)return a(R("ABORT_ERROR","Operation aborted by user or timeout"))}return a(R("TIMEOUT","Cross-device authentication timed out"))}async approve(r){let t=await this.apiClient.getCrossDeviceContext(r);if(!t.ok)return a(t.error);let n=t.value;return n.type==="registration"?this.executeRegistrationApproval(r,n):this.executeAuthApproval(r,n)}async executeRegistrationApproval(r,t){let n=x(t.options);if(!n.ok)return a(n.error);let s;try{s=await navigator.credentials.create(n.value);}catch(l){return a(h(l))}try{E(s,"create");}catch(l){return a(h(l))}let o;try{o=I(s);}catch(l){return a(h(l))}return this.apiClient.verifyCrossDeviceRegistration({session_id:r,credential:o})}async executeAuthApproval(r,t){let n=ue(t.options);if(!n.ok)return a(n.error);let s;try{s=await navigator.credentials.get(n.value);}catch(l){return a(h(l))}try{E(s,"get");}catch(l){return a(h(l))}let o;try{o=q(s);}catch(l){return a(h(l))}return this.apiClient.verifyCrossDeviceAuth({session_id:r,credential:o})}};var B=class{handlers;constructor(){this.handlers=new Map;}on(r,t){let n=this.handlers.get(r);return n||(n=new Set,this.handlers.set(r,n)),n.add(t),()=>{this.off(r,t);}}off(r,t){let n=this.handlers.get(r);n&&(n.delete(t),n.size===0&&this.handlers.delete(r));}emit(r,t){let n=this.handlers.get(r);n&&n.forEach(s=>{try{s(t);}catch{}});}removeAllListeners(){this.handlers.clear();}};async function Te(e,r,t){try{if(t.emit("start",{type:"start",operation:"register"}),!_()){let d=P();return t.emit("error",{type:"error",error:d}),a(d)}let n=e.externalUserId??e.external_user_id;if(!n||typeof n!="string"||n.trim()===""){let d=v("externalUserId","must be a non-empty string");return t.emit("error",{type:"error",error:d}),a(d)}if(!e.otp||typeof e.otp!="string"||e.otp.trim().length!==6){let d=v("otp","must be a 6-digit string");return t.emit("error",{type:"error",error:d}),a(d)}let s=await r.verifyAccountRecoveryOtp(n,e.otp);if(!s.ok)return t.emit("error",{type:"error",error:s.error}),a(s.error);let o=x(s.value.challenge);if(!o.ok)return t.emit("error",{type:"error",error:o.error}),a(o.error);let l={...o.value},y=await navigator.credentials.create(l);if(!y){let d=v("credential","creation failed");return t.emit("error",{type:"error",error:d}),a(d)}try{E(y);}catch(d){let b=h(d);return t.emit("error",{type:"error",error:b}),a(b)}let p=await r.completeAccountRecovery(s.value.recovery_session_id,I(y));if(!p.ok)return t.emit("error",{type:"error",error:p.error}),a(p.error);let f={success:true,credentialId:p.value.credential_id,status:p.value.status,sessionToken:p.value.session_token,user:{userId:p.value.user.user_id,externalUserId:p.value.user.external_user_id,email:p.value.user.email,metadata:p.value.user.metadata}};return t.emit("success",{type:"success",operation:"register"}),g(f)}catch(n){let s=h(n);return t.emit("error",{type:"error",error:s}),a(s)}}var ce="https://api.trymellonauth.com",Ae="https://api.trymellonauth.com/v1/telemetry";var pe="trymellon_sandbox_session_token_v1";function Ie(e){return {async send(r){let t=JSON.stringify(r);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function"){navigator.sendBeacon(e,t);return}typeof fetch<"u"&&await fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"},keepalive:true});}}}function de(e,r){return {event:e,latencyMs:r,ok:true}}var ge=class e{sandbox;sandboxToken;apiClient;eventEmitter;telemetrySender;crossDeviceManager;onboarding;static create(r){try{let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")return a(v("appId","must be a non-empty string"));if(!n||typeof n!="string"||n.trim()==="")return a(v("publishableKey","must be a non-empty string"));let s=r.apiBaseUrl??ce;X(s,"apiBaseUrl");let o=r.timeoutMs??3e4;return S(o,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&S(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&S(r.retryDelayMs,"retryDelayMs",100,1e4),g(new e(r))}catch(t){return N(t)?a(t):a(v("config",t.message))}}constructor(r){this.sandbox=r.sandbox===true,this.sandboxToken=this.sandbox&&r.sandboxToken!=null&&r.sandboxToken!==""?r.sandboxToken:pe;let t=r.appId,n=r.publishableKey;if(!t||typeof t!="string"||t.trim()==="")throw v("appId","must be a non-empty string");if(!n||typeof n!="string"||n.trim()==="")throw v("publishableKey","must be a non-empty string");let s=r.apiBaseUrl??ce;X(s,"apiBaseUrl");let o=r.timeoutMs??3e4;S(o,"timeoutMs",1e3,3e5),r.maxRetries!==void 0&&S(r.maxRetries,"maxRetries",0,10),r.retryDelayMs!==void 0&&S(r.retryDelayMs,"retryDelayMs",100,1e4);let l=r.maxRetries??3,y=r.retryDelayMs??1e3,p=new j(o,l,y,r.logger),f=r.origin??(typeof window<"u"&&window?.location?.origin?window.location.origin:void 0),d={"X-App-Id":t.trim(),Authorization:`Bearer ${n.trim()}`,...f&&{Origin:f}};this.apiClient=new K(p,s,d),this.onboarding=new V(this.apiClient),this.crossDeviceManager=new W(this.apiClient),this.eventEmitter=new B,r.enableTelemetry&&(this.telemetrySender=r.telemetrySender??Ie(r.telemetryEndpoint??Ae));}static isSupported(){return _()}async register(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(g({success:true,credentialId:"",status:"sandbox",sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await Ee(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(de("register",Date.now()-t)).catch(()=>{}),n}async authenticate(r){if(this.sandbox){let s=r.externalUserId??r.external_user_id??"sandbox";return Promise.resolve(g({authenticated:true,sessionToken:this.sandboxToken,user:{userId:"sandbox-user",externalUserId:typeof s=="string"?s:"sandbox"}}))}let t=Date.now(),n=await _e(r,this.apiClient,this.eventEmitter);return n.ok&&this.telemetrySender&&this.telemetrySender.send(de("authenticate",Date.now()-t)).catch(()=>{}),n}async validateSession(r){return this.sandbox&&r===this.sandboxToken?Promise.resolve(g({valid:true,user_id:"sandbox-user",external_user_id:"sandbox",tenant_id:"sandbox-tenant",app_id:"sandbox-app"})):this.apiClient.validateSession(r)}async getStatus(){return ve()}on(r,t){return this.eventEmitter.on(r,t)}version(){return "1.5.0"}fallback={email:{start:async r=>this.apiClient.startEmailFallback(r),verify:async r=>this.apiClient.verifyEmailCode(r.userId,r.code)}};auth={crossDevice:{init:()=>this.crossDeviceManager.init(),initRegistration:r=>this.crossDeviceManager.initRegistration(r),waitForSession:(r,t)=>this.crossDeviceManager.waitForSession(r,t),approve:r=>this.crossDeviceManager.approve(r)},recoverAccount:async r=>Te(r,this.apiClient,this.eventEmitter)}};var me=class{debug(r,t){t&&Object.keys(t).length>0?console.debug(`[TryMellon] ${r}`,t):console.debug(`[TryMellon] ${r}`);}info(r,t){t&&Object.keys(t).length>0?console.info(`[TryMellon] ${r}`,t):console.info(`[TryMellon] ${r}`);}warn(r,t){t&&Object.keys(t).length>0?console.warn(`[TryMellon] ${r}`,t):console.warn(`[TryMellon] ${r}`);}error(r,t){t&&Object.keys(t).length>0?console.error(`[TryMellon] ${r}`,t):console.error(`[TryMellon] ${r}`);}};
|
|
2
|
+
exports.ConsoleLogger=me;exports.SANDBOX_SESSION_TOKEN=pe;exports.TryMellon=ge;exports.TryMellonError=w;exports.createError=R;exports.createInvalidArgumentError=v;exports.createNetworkError=Ue;exports.createNotSupportedError=P;exports.createTimeoutError=Fe;exports.createUserCancelledError=Ne;exports.err=a;exports.isTryMellonError=N;exports.mapWebAuthnError=h;exports.ok=g;return exports;})({});//# sourceMappingURL=index.global.js.map
|
|
3
3
|
//# sourceMappingURL=index.global.js.map
|