@omni2fa/core 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { IOmni2FaClient } from '../client/Interfaces/IOmni2FaClient';
2
2
  import { ChallengeActor } from '../machines/challenge/challengeMachine';
3
3
  import { EmailEnrollmentActor } from '../machines/emailEnrollment/emailEnrollmentMachine';
4
4
  import { MethodsActor } from '../machines/methods/methodsMachine';
5
+ import { StepUpActor } from '../machines/stepup/stepUpMachine';
5
6
  import { TotpEnrollmentActor } from '../machines/totpEnrollment/totpEnrollmentMachine';
6
7
  import { WebAuthnEnrollmentActor } from '../machines/webauthnEnrollment/webauthnEnrollmentMachine';
7
8
  /** Assembled Omni2FA core — client plus running xstate actors and a teardown hook. */
@@ -11,6 +12,8 @@ export interface IOmni2Fa {
11
12
  emailEnrollment: EmailEnrollmentActor;
12
13
  webauthnEnrollment: WebAuthnEnrollmentActor;
13
14
  challenge: ChallengeActor;
15
+ /** Drives action-confirmation (step-up) ceremonies. The React `useStepUp` hook wraps this to confirm 2FA and yield a single-use token. */
16
+ stepUp: StepUpActor;
14
17
  methods: MethodsActor;
15
18
  /** Stops all internal actors. Call on app teardown or when switching users. */
16
19
  dispose(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"IOmni2Fa.d.ts","sourceRoot":"","sources":["../../src/Interfaces/IOmni2Fa.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oDAAoD,CAAC;AAC/F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AAExG,sFAAsF;AACtF,MAAM,WAAW,QAAQ;IACrB,MAAM,EAAE,cAAc,CAAC;IACvB,cAAc,EAAE,mBAAmB,CAAC;IACpC,eAAe,EAAE,oBAAoB,CAAC;IACtC,kBAAkB,EAAE,uBAAuB,CAAC;IAC5C,SAAS,EAAE,cAAc,CAAC;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,+EAA+E;IAC/E,OAAO,IAAI,IAAI,CAAC;CACnB"}
1
+ {"version":3,"file":"IOmni2Fa.d.ts","sourceRoot":"","sources":["../../src/Interfaces/IOmni2Fa.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oDAAoD,CAAC;AAC/F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AACpE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AAExG,sFAAsF;AACtF,MAAM,WAAW,QAAQ;IACrB,MAAM,EAAE,cAAc,CAAC;IACvB,cAAc,EAAE,mBAAmB,CAAC;IACpC,eAAe,EAAE,oBAAoB,CAAC;IACtC,kBAAkB,EAAE,uBAAuB,CAAC;IAC5C,SAAS,EAAE,cAAc,CAAC;IAC1B,0IAA0I;IAC1I,MAAM,EAAE,WAAW,CAAC;IACpB,OAAO,EAAE,YAAY,CAAC;IACtB,+EAA+E;IAC/E,OAAO,IAAI,IAAI,CAAC;CACnB"}
@@ -1,5 +1,7 @@
1
- import { ChallengeResendRequest, ChallengeStartRequest, ChallengeStartResponse, ChallengeVerifyRequest, EmailEnrollConfirmRequest, EmailEnrollResendRequest, EmailEnrollStartRequest, EmailEnrollStartResponse, MethodCreatedResponse, RecoveryCodesResponse, RecoveryCodeVerifyRequest, TotpEnrollConfirmRequest, TotpEnrollStartResponse, TwoFactorMethodDto, VerifySuccessResponse, WebAuthnEnrollConfirmRequest, WebAuthnEnrollStartResponse } from '../../types/dtos';
1
+ import { ChallengeResendRequest, ChallengeStartRequest, ChallengeStartResponse, ChallengeVerifyRequest, EmailEnrollConfirmRequest, EmailEnrollResendRequest, EmailEnrollStartRequest, EmailEnrollStartResponse, MethodCreatedResponse, RecoveryCodesResponse, RecoveryCodeVerifyRequest, StepUpVerifyResponse, TotpEnrollConfirmRequest, TotpEnrollStartResponse, TwoFactorMethodDto, VerifySuccessResponse, WebAuthnEnrollConfirmRequest, WebAuthnEnrollStartResponse } from '../../types/dtos';
2
2
  import { ClientCall } from './ClientCall';
3
+ /** Confirms 2FA and resolves a single-use step-up token, or null if the user cancels. Registered via {@link IOmni2FaClient.setStepUpHandler}. */
4
+ export type StepUpHandler = (methods: TwoFactorMethodDto[]) => Promise<string | null>;
3
5
  /** Typed wrapper over the Omni2FA HTTP contract. Adapters consume this — they never call <c>fetch</c> directly. */
4
6
  export interface IOmni2FaClient {
5
7
  listMethods(): Promise<ClientCall<TwoFactorMethodDto[]>>;
@@ -15,6 +17,10 @@ export interface IOmni2FaClient {
15
17
  resendChallenge(request: ChallengeResendRequest): Promise<ClientCall<ChallengeStartResponse>>;
16
18
  verifyChallenge(request: ChallengeVerifyRequest): Promise<ClientCall<VerifySuccessResponse>>;
17
19
  verifyRecoveryCode(request: RecoveryCodeVerifyRequest): Promise<ClientCall<VerifySuccessResponse>>;
20
+ /** Step-up (action confirmation) for an authenticated user. Mirror the challenge flow; verify yields a single-use step-up token. */
21
+ startStepUp(request: ChallengeStartRequest): Promise<ClientCall<ChallengeStartResponse>>;
22
+ resendStepUp(request: ChallengeResendRequest): Promise<ClientCall<ChallengeStartResponse>>;
23
+ verifyStepUp(request: ChallengeVerifyRequest): Promise<ClientCall<StepUpVerifyResponse>>;
18
24
  regenerateRecoveryCodes(): Promise<ClientCall<RecoveryCodesResponse>>;
19
25
  /** Pre-auth token — sent on <c>/challenge/*</c> during the 2FA ceremony. */
20
26
  setPreAuthToken(token: string | null): void;
@@ -22,5 +28,12 @@ export interface IOmni2FaClient {
22
28
  /** Host session token — sent on host-session endpoints (<c>/methods</c>, <c>/enroll/*</c>, <c>/recovery-codes/*</c>). */
23
29
  setSessionToken(token: string | null): void;
24
30
  getSessionToken(): string | null;
31
+ /**
32
+ * Register a handler that confirms 2FA when one of the library's own sensitive calls (remove method,
33
+ * regenerate recovery codes, enroll start) returns <c>403 STEP_UP_REQUIRED</c> — only when the host
34
+ * enabled the matching server flag. The client invokes it, then retries the call with the step-up
35
+ * header. Pass the React <c>useStepUp().confirmTwoFactor</c> here, or null to clear.
36
+ */
37
+ setStepUpHandler(handler: StepUpHandler | null): void;
25
38
  }
26
39
  //# sourceMappingURL=IOmni2FaClient.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"IOmni2FaClient.d.ts","sourceRoot":"","sources":["../../../src/client/Interfaces/IOmni2FaClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,EACrB,qBAAqB,EACrB,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,EACvB,kBAAkB,EAClB,qBAAqB,EACrB,4BAA4B,EAC5B,2BAA2B,EAC9B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,mHAAmH;AACnH,MAAM,WAAW,cAAc;IAC3B,WAAW,IAAI,OAAO,CAAC,UAAU,CAAC,kBAAkB,EAAE,CAAC,CAAC,CAAC;IACzD,YAAY,CAAC,QAAQ,EAAE,MAAM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AAM,GAAG,IAAI,CAAC;IAEjC,yHAAyH;IACzH,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAC;IAC5C,eAAe,IAAI,MAAM,GAAG,IAAI,CAAC;IAEjC;;;;;OAKG;IACH,gBAAgB,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI,GAAG,IAAI,CAAC;CACzD"}
@@ -1,6 +1,6 @@
1
- import { ChallengeResendRequest, ChallengeStartRequest, ChallengeStartResponse, ChallengeVerifyRequest, EmailEnrollConfirmRequest, EmailEnrollResendRequest, EmailEnrollStartRequest, EmailEnrollStartResponse, MethodCreatedResponse, RecoveryCodesResponse, RecoveryCodeVerifyRequest, TotpEnrollConfirmRequest, TotpEnrollStartResponse, TwoFactorMethodDto, VerifySuccessResponse, WebAuthnEnrollConfirmRequest, WebAuthnEnrollStartResponse } from '../types/dtos';
1
+ import { ChallengeResendRequest, ChallengeStartRequest, ChallengeStartResponse, ChallengeVerifyRequest, EmailEnrollConfirmRequest, EmailEnrollResendRequest, EmailEnrollStartRequest, EmailEnrollStartResponse, MethodCreatedResponse, RecoveryCodesResponse, RecoveryCodeVerifyRequest, StepUpVerifyResponse, TotpEnrollConfirmRequest, TotpEnrollStartResponse, TwoFactorMethodDto, VerifySuccessResponse, WebAuthnEnrollConfirmRequest, WebAuthnEnrollStartResponse } from '../types/dtos';
2
2
  import { ClientCall } from './Interfaces/ClientCall';
3
- import { IOmni2FaClient } from './Interfaces/IOmni2FaClient';
3
+ import { IOmni2FaClient, StepUpHandler } from './Interfaces/IOmni2FaClient';
4
4
  import { Omni2FaClientConfig } from './Omni2FaClientConfig';
5
5
  export declare class Omni2FaClient implements IOmni2FaClient {
6
6
  private readonly storage;
@@ -8,6 +8,7 @@ export declare class Omni2FaClient implements IOmni2FaClient {
8
8
  private readonly sessionKey;
9
9
  private readonly basePath;
10
10
  private readonly inner;
11
+ private stepUpHandler;
11
12
  constructor(config: Omni2FaClientConfig);
12
13
  /** Pre-auth endpoints are exactly the ones mounted under <c>{basePath}/challenge/</c>. */
13
14
  private isPreAuthEndpoint;
@@ -15,6 +16,13 @@ export declare class Omni2FaClient implements IOmni2FaClient {
15
16
  getPreAuthToken(): string | null;
16
17
  setSessionToken(token: string | null): void;
17
18
  getSessionToken(): string | null;
19
+ setStepUpHandler(handler: StepUpHandler | null): void;
20
+ /**
21
+ * Run a request and, if it comes back 403 STEP_UP_REQUIRED with a handler registered, confirm 2FA
22
+ * and retry once with the step-up header. Used by the library's own sensitive endpoints; other calls
23
+ * invoke openapi-fetch directly.
24
+ */
25
+ private sendWithStepUp;
18
26
  private setToken;
19
27
  listMethods(): Promise<ClientCall<TwoFactorMethodDto[]>>;
20
28
  removeMethod(methodId: string): Promise<ClientCall<void>>;
@@ -29,6 +37,9 @@ export declare class Omni2FaClient implements IOmni2FaClient {
29
37
  resendChallenge(request: ChallengeResendRequest): Promise<ClientCall<ChallengeStartResponse>>;
30
38
  verifyChallenge(request: ChallengeVerifyRequest): Promise<ClientCall<VerifySuccessResponse>>;
31
39
  verifyRecoveryCode(request: RecoveryCodeVerifyRequest): Promise<ClientCall<VerifySuccessResponse>>;
40
+ startStepUp(request: ChallengeStartRequest): Promise<ClientCall<ChallengeStartResponse>>;
41
+ resendStepUp(request: ChallengeResendRequest): Promise<ClientCall<ChallengeStartResponse>>;
42
+ verifyStepUp(request: ChallengeVerifyRequest): Promise<ClientCall<StepUpVerifyResponse>>;
32
43
  regenerateRecoveryCodes(): Promise<ClientCall<RecoveryCodesResponse>>;
33
44
  private toCall;
34
45
  private errorCall;
@@ -1 +1 @@
1
- {"version":3,"file":"Omni2FaClient.d.ts","sourceRoot":"","sources":["../../src/client/Omni2FaClient.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACR,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EAExB,qBAAqB,EACrB,qBAAqB,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appings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAOtD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,QAAQ,CA8BnE"}
1
+ {"version":3,"file":"createOmni2Fa.d.ts","sourceRoot":"","sources":["../src/createOmni2Fa.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAQtD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,QAAQ,CAkCnE"}
@@ -13,6 +13,7 @@ export declare const Omni2FaErrorCodes: {
13
13
  readonly RecoveryCodeUsed: "RECOVERY_CODE_USED";
14
14
  readonly WebAuthnVerificationFailed: "WEBAUTHN_VERIFICATION_FAILED";
15
15
  readonly ValidationFailed: "VALIDATION_FAILED";
16
+ readonly StepUpRequired: "STEP_UP_REQUIRED";
16
17
  readonly NetworkError: "NETWORK_ERROR";
17
18
  readonly Unknown: "UNKNOWN";
18
19
  };
@@ -1 +1 @@
1
- {"version":3,"file":"codes.d.ts","sourceRoot":"","sources":["../../src/errors/codes.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;CAiBpB,CAAC;AAEX,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,OAAO,iBAAiB,CAAC,CAAC"}
1
+ {"version":3,"file":"codes.d.ts","sourceRoot":"","sources":["../../src/errors/codes.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;CAkBpB,CAAC;AAEX,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,OAAO,iBAAiB,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/errors/messages.ts"],"names":[],"mappings":"AAqBA,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD"}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/errors/messages.ts"],"names":[],"mappings":"AAsBA,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("openapi-fetch"),s=require("xstate");class M{map=new Map;get(e){return this.map.get(e)??null}set(e,r){this.map.set(e,r)}remove(e){this.map.delete(e)}}const a={InvalidCode:"INVALID_CODE",PreAuthExpired:"PREAUTH_EXPIRED",PreAuthInvalid:"PREAUTH_INVALID",ChallengeNotFound:"CHALLENGE_NOT_FOUND",ChallengeConsumed:"CHALLENGE_CONSUMED",TooManyAttempts:"TOO_MANY_ATTEMPTS",MethodNotFound:"METHOD_NOT_FOUND",TypeAlreadyEnrolled:"TYPE_ALREADY_ENROLLED",MaxMethodsReached:"MAX_METHODS_REACHED",LastMethodProtected:"LAST_METHOD_PROTECTED",RecoveryCodeInvalid:"RECOVERY_CODE_INVALID",RecoveryCodeUsed:"RECOVERY_CODE_USED",WebAuthnVerificationFailed:"WEBAUTHN_VERIFICATION_FAILED",ValidationFailed:"VALIDATION_FAILED",NetworkError:"NETWORK_ERROR",Unknown:"UNKNOWN"},C={[a.InvalidCode]:"The code you entered is invalid.",[a.PreAuthExpired]:"Your session has expired. Please sign in again.",[a.PreAuthInvalid]:"Your session is invalid. Please sign in again.",[a.ChallengeNotFound]:"No active verification step. Please restart.",[a.ChallengeConsumed]:"This verification step was already used. Please sign in again.",[a.TooManyAttempts]:"Too many attempts. Please wait before trying again.",[a.MethodNotFound]:"The selected 2FA method was not found.",[a.TypeAlreadyEnrolled]:"You already have this type of 2FA enabled.",[a.MaxMethodsReached]:"You have reached the maximum number of 2FA methods.",[a.LastMethodProtected]:"You cannot remove your last 2FA method.",[a.RecoveryCodeInvalid]:"The recovery code is invalid.",[a.RecoveryCodeUsed]:"This recovery code has already been used.",[a.WebAuthnVerificationFailed]:"Security key verification failed.",[a.ValidationFailed]:"The request was malformed.",[a.NetworkError]:"Network error. Please check your connection.",[a.Unknown]:"An unexpected error occurred."};function E(t){return C[t]??C[a.Unknown]}const J="omni2fa:preauth",L="omni2fa:session",v="http://omni2fa.local";class S{storage;preAuthKey;sessionKey;basePath;inner;constructor(e){this.storage=e.storage??new M,this.preAuthKey=e.preAuthStorageKey??J,this.sessionKey=e.sessionStorageKey??L,this.basePath=new URL(e.baseUrl,v).pathname.replace(/\/$/,""),this.inner=F({baseUrl:e.baseUrl,fetch:e.fetch??globalThis.fetch.bind(globalThis),...e.credentials?{credentials:e.credentials}:{}}),this.inner.use({onRequest:({request:r})=>{if(r.headers.has("Authorization"))return r;const n=this.isPreAuthEndpoint(r.url)?this.getPreAuthToken():this.getSessionToken();return n&&r.headers.set("Authorization",`Bearer ${n}`),r}})}isPreAuthEndpoint(e){const r=new URL(e,v).pathname;return(r.startsWith(this.basePath)?r.slice(this.basePath.length):r).startsWith("/challenge/")}setPreAuthToken(e){this.setToken(this.preAuthKey,e)}getPreAuthToken(){return this.storage.get(this.preAuthKey)}setSessionToken(e){this.setToken(this.sessionKey,e)}getSessionToken(){return this.storage.get(this.sessionKey)}setToken(e,r){r===null||r.length===0?this.storage.remove(e):this.storage.set(e,r)}async listMethods(){const{data:e,error:r,response:n}=await this.inner.GET("/methods");return this.toCall(e,r,n)}async removeMethod(e){const{error:r,response:n}=await this.inner.DELETE("/methods/{methodId}",{params:{path:{methodId:e}}});return r?this.errorCall(r,n):{ok:!0,value:void 0}}async startTotpEnrollment(){const{data:e,error:r,response:n}=await this.inner.POST("/enroll/totp/start");return this.toCall(e,r,n)}async confirmTotpEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/totp/confirm",{body:e});return this.toCall(r,n,o)}async startEmailEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/email/start",{body:e});return this.toCall(r,n,o)}async confirmEmailEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/email/confirm",{body:e});return this.toCall(r,n,o)}async resendEmailEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/email/resend",{body:e});return this.toCall(r,n,o)}async startWebAuthnEnrollment(){const{data:e,error:r,response:n}=await this.inner.POST("/enroll/webauthn/start");return this.toCall(e,r,n)}async confirmWebAuthnEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/webauthn/confirm",{body:e});return this.toCall(r,n,o)}async startChallenge(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/start",{body:e});return this.toCall(r,n,o)}async resendChallenge(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/resend",{body:e});return this.toCall(r,n,o)}async verifyChallenge(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/verify",{body:e});return this.toCall(r,n,o)}async verifyRecoveryCode(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/recovery-code",{body:e});return this.toCall(r,n,o)}async regenerateRecoveryCodes(){const{data:e,error:r,response:n}=await this.inner.POST("/recovery-codes/regenerate");return this.toCall(e,r,n)}toCall(e,r,n){return r!==void 0?this.errorCall(r,n):e===void 0?{ok:!1,code:a.NetworkError,message:E(a.NetworkError),httpStatus:n.status}:{ok:!0,value:e}}errorCall(e,r){const n=e.code||a.Unknown;return{ok:!1,code:n,message:e.message||E(n),httpStatus:r.status,details:e.details??null}}}class K{get(e){return globalThis.sessionStorage?.getItem(e)??null}set(e,r){globalThis.sessionStorage?.setItem(e,r)}remove(e){globalThis.sessionStorage?.removeItem(e)}}class W{get(e){return globalThis.localStorage?.getItem(e)??null}set(e,r){globalThis.localStorage?.setItem(e,r)}remove(e){globalThis.localStorage?.removeItem(e)}}class l extends Error{code;httpStatus;details;constructor(e,r,n,o=null){super(r),this.name="Omni2FaApiError",this.code=e,this.httpStatus=n,this.details=o}}const $={enrollmentId:null,otpAuthUri:null,secret:null,methodId:null,recoveryCodes:null,errorCode:null,errorMessage:null};function O(t){return s.setup({types:{context:{},events:{}},actors:{startEnrollment:s.fromPromise(async()=>{const e=await t.startTotpEnrollment();if(!e.ok)throw new l(e.code,e.message,e.httpStatus,e.details??null);return e.value}),confirmEnrollment:s.fromPromise(async({input:e})=>{const r=await t.confirmTotpEnrollment({enrollmentId:e.enrollmentId,code:e.code,name:e.name});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value})}}).createMachine({id:"totpEnrollment",initial:"idle",context:$,states:{idle:{on:{start:{target:"starting"}}},starting:{invoke:{src:"startEnrollment",onDone:{target:"awaitingCode",actions:({context:e,event:r})=>{e.enrollmentId=r.output.enrollmentId,e.otpAuthUri=r.output.otpAuthUri,e.secret=r.output.secret,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>w(e,r.error)}}},awaitingCode:{on:{submit:{target:"confirming"},reset:{target:"idle",actions:h}}},confirming:{invoke:{src:"confirmEnrollment",input:({context:e,event:r})=>{if(r.type!=="submit")throw new Error("confirming requires submit event");if(!e.enrollmentId)throw new Error("no enrollmentId");return{enrollmentId:e.enrollmentId,code:r.code,name:r.name??null}},onDone:{target:"enrolled",actions:({context:e,event:r})=>{e.methodId=r.output.methodId,e.recoveryCodes=r.output.recoveryCodes??null,e.errorCode=null,e.errorMessage=null}},onError:{target:"awaitingCode",actions:({context:e,event:r})=>w(e,r.error)}}},enrolled:{on:{reset:{target:"idle",actions:h}}},failed:{on:{start:{target:"starting"},reset:{target:"idle",actions:h}}}}})}function h({context:t}){t.enrollmentId=null,t.otpAuthUri=null,t.secret=null,t.methodId=null,t.recoveryCodes=null,t.errorCode=null,t.errorMessage=null}function w(t,e){e instanceof l?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}const H={enrollmentId:null,email:null,expiresAt:null,resendAvailableAt:null,methodId:null,recoveryCodes:null,errorCode:null,errorMessage:null};function k(t){return s.setup({types:{context:{},events:{}},actors:{startEnrollment:s.fromPromise(async({input:e})=>{const r=await t.startEmailEnrollment(e.email!==void 0?{email:e.email}:{});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value}),resendEnrollment:s.fromPromise(async({input:e})=>{const r=await t.resendEmailEnrollment({enrollmentId:e.enrollmentId});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value}),confirmEnrollment:s.fromPromise(async({input:e})=>{const r=await t.confirmEmailEnrollment({enrollmentId:e.enrollmentId,code:e.code,name:e.name});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value})}}).createMachine({id:"emailEnrollment",initial:"idle",context:H,states:{idle:{on:{start:{target:"starting"}}},starting:{entry:({context:e,event:r})=>{r.type==="start"&&(e.email=r.email??null)},invoke:{src:"startEnrollment",input:({context:e})=>({email:e.email??void 0}),onDone:{target:"awaitingCode",actions:({context:e,event:r})=>I(e,r.output)},onError:{target:"failed",actions:({context:e,event:r})=>p(e,r.error)}}},awaitingCode:{on:{submit:{target:"confirming"},resend:{target:"resending"},reset:{target:"idle",actions:g}}},resending:{invoke:{src:"resendEnrollment",input:({context:e})=>{if(!e.enrollmentId)throw new Error("no enrollmentId");return{enrollmentId:e.enrollmentId}},onDone:{target:"awaitingCode",actions:({context:e,event:r})=>I(e,r.output)},onError:{target:"awaitingCode",actions:({context:e,event:r})=>p(e,r.error)}}},confirming:{invoke:{src:"confirmEnrollment",input:({context:e,event:r})=>{if(r.type!=="submit")throw new Error("confirming requires submit event");if(!e.enrollmentId)throw new Error("no enrollmentId");return{enrollmentId:e.enrollmentId,code:r.code,name:r.name??null}},onDone:{target:"enrolled",actions:({context:e,event:r})=>{e.methodId=r.output.methodId,e.recoveryCodes=r.output.recoveryCodes??null,e.errorCode=null,e.errorMessage=null}},onError:{target:"awaitingCode",actions:({context:e,event:r})=>p(e,r.error)}}},enrolled:{on:{reset:{target:"idle",actions:g}}},failed:{on:{start:{target:"starting"},reset:{target:"idle",actions:g}}}}})}function I(t,e){t.enrollmentId=e.enrollmentId,t.expiresAt=e.expiresAt,t.resendAvailableAt=e.resendAvailableAt,t.errorCode=null,t.errorMessage=null}function g({context:t}){t.enrollmentId=null,t.email=null,t.expiresAt=null,t.resendAvailableAt=null,t.methodId=null,t.recoveryCodes=null,t.errorCode=null,t.errorMessage=null}function p(t,e){e instanceof l?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}function c(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=atob(r),o=new Uint8Array(n.length);for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);return o.buffer}function d(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function P(t){return(t??[]).map(e=>({...e,id:c(e.id)}))}async function N(t){const e=JSON.parse(t),r={...e,challenge:c(e.challenge),user:{...e.user,id:c(e.user.id)},excludeCredentials:P(e.excludeCredentials)},n=await navigator.credentials.create({publicKey:r});if(n===null)throw new Error("WebAuthn registration produced no credential.");const o=n.response;return JSON.stringify({id:n.id,rawId:d(n.rawId),type:n.type,extensions:n.getClientExtensionResults(),response:{attestationObject:d(o.attestationObject),clientDataJSON:d(o.clientDataJSON)}})}async function R(t){const e=JSON.parse(t),r={...e,challenge:c(e.challenge),allowCredentials:P(e.allowCredentials)},n=await navigator.credentials.get({publicKey:r});if(n===null)throw new Error("WebAuthn authentication produced no credential.");const o=n.response;return JSON.stringify({id:n.id,rawId:d(n.rawId),type:n.type,extensions:n.getClientExtensionResults(),response:{authenticatorData:d(o.authenticatorData),clientDataJSON:d(o.clientDataJSON),signature:d(o.signature),userHandle:o.userHandle?d(o.userHandle):null}})}const Y={enrollmentId:null,optionsJson:null,name:null,methodId:null,recoveryCodes:null,errorCode:null,errorMessage:null};function D(t){return s.setup({types:{context:{},events:{}},actors:{startEnrollment:s.fromPromise(async()=>{const e=await t.startWebAuthnEnrollment();if(!e.ok)throw new l(e.code,e.message,e.httpStatus,e.details??null);return e.value}),registerAndConfirm:s.fromPromise(async({input:e})=>{const r=await N(e.optionsJson),n=await t.confirmWebAuthnEnrollment({enrollmentId:e.enrollmentId,attestationResponseJson:r,name:e.name});if(!n.ok)throw new l(n.code,n.message,n.httpStatus,n.details??null);return n.value})}}).createMachine({id:"webauthnEnrollment",initial:"idle",context:Y,states:{idle:{on:{start:{target:"starting"}}},starting:{entry:({context:e,event:r})=>{r.type==="start"&&(e.name=r.name??null)},invoke:{src:"startEnrollment",onDone:{target:"registering",actions:({context:e,event:r})=>{e.enrollmentId=r.output.enrollmentId,e.optionsJson=r.output.optionsJson,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>T(e,r.error)}}},registering:{invoke:{src:"registerAndConfirm",input:({context:e})=>{if(!e.enrollmentId||!e.optionsJson)throw new Error("no pending enrollment");return{enrollmentId:e.enrollmentId,optionsJson:e.optionsJson,name:e.name}},onDone:{target:"enrolled",actions:({context:e,event:r})=>{e.methodId=r.output.methodId,e.recoveryCodes=r.output.recoveryCodes??null,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>T(e,r.error)}}},enrolled:{on:{reset:{target:"idle",actions:A}}},failed:{on:{retry:{target:"starting"},reset:{target:"idle",actions:A}}}}})}function A({context:t}){t.enrollmentId=null,t.optionsJson=null,t.name=null,t.methodId=null,t.recoveryCodes=null,t.errorCode=null,t.errorMessage=null}function T(t,e){e instanceof l?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}const V={methodId:null,methodType:null,userId:null,verifiedToken:null,expiresAt:null,resendAvailableAt:null,optionsJson:null,errorCode:null,errorMessage:null};function U(t){return s.setup({types:{context:{},events:{}},actors:{startChallenge:s.fromPromise(async({input:e})=>{const r=await t.startChallenge({methodId:e.methodId});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value}),resendChallenge:s.fromPromise(async({input:e})=>{const r=await t.resendChallenge({methodId:e.methodId});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value}),verifyChallenge:s.fromPromise(async({input:e})=>{const r=await t.verifyChallenge({methodId:e.methodId,code:e.code});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value}),assertChallenge:s.fromPromise(async({input:e})=>{const r=await R(e.optionsJson),n=await t.verifyChallenge({methodId:e.methodId,assertionResponseJson:r});if(!n.ok)throw new l(n.code,n.message,n.httpStatus,n.details??null);return n.value}),verifyRecoveryCode:s.fromPromise(async({input:e})=>{const r=await t.verifyRecoveryCode({recoveryCode:e.code});if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return r.value})}}).createMachine({id:"challenge",initial:"idle",context:V,states:{idle:{on:{pick:{target:"starting"},useRecoveryCode:{target:"verifyingRecovery"}}},starting:{entry:({context:e,event:r})=>{r.type==="pick"&&(e.methodId=r.methodId)},invoke:{src:"startChallenge",input:({context:e})=>{if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId}},onDone:[{guard:({event:e})=>e.output.type==="WebAuthn",target:"asserting",actions:({context:e,event:r})=>f(e,r.output)},{target:"awaitingCode",actions:({context:e,event:r})=>f(e,r.output)}],onError:{target:"failed",actions:({context:e,event:r})=>u(e,r.error)}}},asserting:{invoke:{src:"assertChallenge",input:({context:e})=>{if(!e.methodId||!e.optionsJson)throw new Error("no assertion options");return{methodId:e.methodId,optionsJson:e.optionsJson}},onDone:{target:"verified",actions:({context:e,event:r})=>{e.userId=r.output.userId,e.verifiedToken=r.output.verifiedToken,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>u(e,r.error)}}},awaitingCode:{on:{submit:{target:"verifying"},resend:{target:"resending"},useRecoveryCode:{target:"verifyingRecovery"},reset:{target:"idle",actions:y}}},verifyingRecovery:{invoke:{src:"verifyRecoveryCode",input:({event:e})=>{if(e.type!=="useRecoveryCode")throw new Error("verifyingRecovery requires useRecoveryCode event");return{code:e.code}},onDone:{target:"verified",actions:({context:e,event:r})=>{e.userId=r.output.userId,e.verifiedToken=r.output.verifiedToken,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>u(e,r.error)}}},resending:{invoke:{src:"resendChallenge",input:({context:e})=>{if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId}},onDone:{target:"awaitingCode",actions:({context:e,event:r})=>f(e,r.output)},onError:{target:"awaitingCode",actions:({context:e,event:r})=>u(e,r.error)}}},verifying:{invoke:{src:"verifyChallenge",input:({context:e,event:r})=>{if(r.type!=="submit")throw new Error("verifying requires submit event");if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId,code:r.code}},onDone:{target:"verified",actions:({context:e,event:r})=>{e.userId=r.output.userId,e.verifiedToken=r.output.verifiedToken,e.errorCode=null,e.errorMessage=null}},onError:{target:"awaitingCode",actions:({context:e,event:r})=>u(e,r.error)}}},verified:{on:{reset:{target:"idle",actions:y}}},failed:{on:{pick:{target:"starting"},useRecoveryCode:{target:"verifyingRecovery"},reset:{target:"idle",actions:y}}}}})}function f(t,e){t.methodType=e.type,t.expiresAt=e.expiresAt??null,t.resendAvailableAt=e.resendAvailableAt??null,t.optionsJson=e.optionsJson??null,t.errorCode=null,t.errorMessage=null}function y({context:t}){t.methodId=null,t.methodType=null,t.userId=null,t.verifiedToken=null,t.expiresAt=null,t.resendAvailableAt=null,t.optionsJson=null,t.errorCode=null,t.errorMessage=null}function u(t,e){e instanceof l?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}const q={items:[],errorCode:null,errorMessage:null};function _(t){return s.setup({types:{context:{},events:{}},actors:{load:s.fromPromise(async()=>{const e=await t.listMethods();if(!e.ok)throw new l(e.code,e.message,e.httpStatus,e.details??null);return e.value}),remove:s.fromPromise(async({input:e})=>{const r=await t.removeMethod(e.methodId);if(!r.ok)throw new l(r.code,r.message,r.httpStatus,r.details??null);return e.methodId})}}).createMachine({id:"methods",initial:"idle",context:q,states:{idle:{on:{load:{target:"loading"}}},loading:{invoke:{src:"load",onDone:{target:"ready",actions:({context:e,event:r})=>{e.items=r.output,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>b(e,r.error)}}},ready:{on:{load:{target:"loading"},remove:{target:"removing"}}},removing:{invoke:{src:"remove",input:({event:e})=>{if(e.type!=="remove")throw new Error("removing requires remove event");return{methodId:e.methodId}},onDone:{target:"ready",actions:({context:e,event:r})=>{const n=r.output;e.items=e.items.filter(o=>o.id!==n),e.errorCode=null,e.errorMessage=null}},onError:{target:"ready",actions:({context:e,event:r})=>b(e,r.error)}}},failed:{on:{load:{target:"loading"},reset:{target:"idle",actions:B}}}}})}function B({context:t}){t.items=[],t.errorCode=null,t.errorMessage=null}function b(t,e){e instanceof l?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}function G(t){const e=new S(t),r=s.createActor(O(e)),n=s.createActor(k(e)),o=s.createActor(D(e)),i=s.createActor(U(e)),m=s.createActor(_(e));return r.start(),n.start(),o.start(),i.start(),m.start(),{client:e,totpEnrollment:r,emailEnrollment:n,webauthnEnrollment:o,challenge:i,methods:m,dispose(){r.stop(),n.stop(),o.stop(),i.stop(),m.stop()}}}exports.LocalStorageStorage=W;exports.MemoryStorage=M;exports.Omni2FaApiError=l;exports.Omni2FaClient=S;exports.Omni2FaErrorCodes=a;exports.SessionStorageStorage=K;exports.createChallengeMachine=U;exports.createEmailEnrollmentMachine=k;exports.createMethodsMachine=_;exports.createOmni2Fa=G;exports.createTotpEnrollmentMachine=O;exports.createWebAuthnEnrollmentMachine=D;exports.getDefaultMessage=E;exports.startAuthentication=R;exports.startRegistration=N;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("openapi-fetch"),s=require("xstate");class N{map=new Map;get(e){return this.map.get(e)??null}set(e,r){this.map.set(e,r)}remove(e){this.map.delete(e)}}const i={InvalidCode:"INVALID_CODE",PreAuthExpired:"PREAUTH_EXPIRED",PreAuthInvalid:"PREAUTH_INVALID",ChallengeNotFound:"CHALLENGE_NOT_FOUND",ChallengeConsumed:"CHALLENGE_CONSUMED",TooManyAttempts:"TOO_MANY_ATTEMPTS",MethodNotFound:"METHOD_NOT_FOUND",TypeAlreadyEnrolled:"TYPE_ALREADY_ENROLLED",MaxMethodsReached:"MAX_METHODS_REACHED",LastMethodProtected:"LAST_METHOD_PROTECTED",RecoveryCodeInvalid:"RECOVERY_CODE_INVALID",RecoveryCodeUsed:"RECOVERY_CODE_USED",WebAuthnVerificationFailed:"WEBAUTHN_VERIFICATION_FAILED",ValidationFailed:"VALIDATION_FAILED",StepUpRequired:"STEP_UP_REQUIRED",NetworkError:"NETWORK_ERROR",Unknown:"UNKNOWN"},S={[i.InvalidCode]:"The code you entered is invalid.",[i.PreAuthExpired]:"Your session has expired. Please sign in again.",[i.PreAuthInvalid]:"Your session is invalid. Please sign in again.",[i.ChallengeNotFound]:"No active verification step. Please restart.",[i.ChallengeConsumed]:"This verification step was already used. Please sign in again.",[i.TooManyAttempts]:"Too many attempts. Please wait before trying again.",[i.MethodNotFound]:"The selected 2FA method was not found.",[i.TypeAlreadyEnrolled]:"You already have this type of 2FA enabled.",[i.MaxMethodsReached]:"You have reached the maximum number of 2FA methods.",[i.LastMethodProtected]:"You cannot remove your last 2FA method.",[i.RecoveryCodeInvalid]:"The recovery code is invalid.",[i.RecoveryCodeUsed]:"This recovery code has already been used.",[i.WebAuthnVerificationFailed]:"Security key verification failed.",[i.ValidationFailed]:"The request was malformed.",[i.StepUpRequired]:"Please confirm two-factor authentication to continue.",[i.NetworkError]:"Network error. Please check your connection.",[i.Unknown]:"An unexpected error occurred."};function I(t){return S[t]??S[i.Unknown]}const R="X-Omni2FA-StepUp",Y="omni2fa:preauth",q="omni2fa:session",T="http://omni2fa.local";class D{storage;preAuthKey;sessionKey;basePath;inner;stepUpHandler=null;constructor(e){this.storage=e.storage??new N,this.preAuthKey=e.preAuthStorageKey??Y,this.sessionKey=e.sessionStorageKey??q,this.basePath=new URL(e.baseUrl,T).pathname.replace(/\/$/,""),this.inner=V({baseUrl:e.baseUrl,fetch:e.fetch??globalThis.fetch.bind(globalThis),...e.credentials?{credentials:e.credentials}:{}}),this.inner.use({onRequest:({request:r})=>{if(r.headers.has("Authorization"))return r;const n=this.isPreAuthEndpoint(r.url)?this.getPreAuthToken():this.getSessionToken();return n&&r.headers.set("Authorization",`Bearer ${n}`),r}})}isPreAuthEndpoint(e){const r=new URL(e,T).pathname;return(r.startsWith(this.basePath)?r.slice(this.basePath.length):r).startsWith("/challenge/")}setPreAuthToken(e){this.setToken(this.preAuthKey,e)}getPreAuthToken(){return this.storage.get(this.preAuthKey)}setSessionToken(e){this.setToken(this.sessionKey,e)}getSessionToken(){return this.storage.get(this.sessionKey)}setStepUpHandler(e){this.stepUpHandler=e}async sendWithStepUp(e){const r=await e({});if(r.error!==void 0&&r.response.status===403&&r.error.code===i.StepUpRequired&&this.stepUpHandler!==null){const n=r.error.details?.availableMethods??[],o=await this.stepUpHandler(n);if(o)return e({[R]:o})}return r}setToken(e,r){r===null||r.length===0?this.storage.remove(e):this.storage.set(e,r)}async listMethods(){const{data:e,error:r,response:n}=await this.inner.GET("/methods");return this.toCall(e,r,n)}async removeMethod(e){const{error:r,response:n}=await this.sendWithStepUp(o=>this.inner.DELETE("/methods/{methodId}",{params:{path:{methodId:e}},headers:o}));return r?this.errorCall(r,n):{ok:!0,value:void 0}}async startTotpEnrollment(){const{data:e,error:r,response:n}=await this.sendWithStepUp(o=>this.inner.POST("/enroll/totp/start",{headers:o}));return this.toCall(e,r,n)}async confirmTotpEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/totp/confirm",{body:e});return this.toCall(r,n,o)}async startEmailEnrollment(e){const{data:r,error:n,response:o}=await this.sendWithStepUp(l=>this.inner.POST("/enroll/email/start",{body:e,headers:l}));return this.toCall(r,n,o)}async confirmEmailEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/email/confirm",{body:e});return this.toCall(r,n,o)}async resendEmailEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/email/resend",{body:e});return this.toCall(r,n,o)}async startWebAuthnEnrollment(){const{data:e,error:r,response:n}=await this.sendWithStepUp(o=>this.inner.POST("/enroll/webauthn/start",{headers:o}));return this.toCall(e,r,n)}async confirmWebAuthnEnrollment(e){const{data:r,error:n,response:o}=await this.inner.POST("/enroll/webauthn/confirm",{body:e});return this.toCall(r,n,o)}async startChallenge(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/start",{body:e});return this.toCall(r,n,o)}async resendChallenge(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/resend",{body:e});return this.toCall(r,n,o)}async verifyChallenge(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/verify",{body:e});return this.toCall(r,n,o)}async verifyRecoveryCode(e){const{data:r,error:n,response:o}=await this.inner.POST("/challenge/recovery-code",{body:e});return this.toCall(r,n,o)}async startStepUp(e){const{data:r,error:n,response:o}=await this.inner.POST("/stepup/start",{body:e});return this.toCall(r,n,o)}async resendStepUp(e){const{data:r,error:n,response:o}=await this.inner.POST("/stepup/resend",{body:e});return this.toCall(r,n,o)}async verifyStepUp(e){const{data:r,error:n,response:o}=await this.inner.POST("/stepup/verify",{body:e});return this.toCall(r,n,o)}async regenerateRecoveryCodes(){const{data:e,error:r,response:n}=await this.sendWithStepUp(o=>this.inner.POST("/recovery-codes/regenerate",{headers:o}));return this.toCall(e,r,n)}toCall(e,r,n){return r!==void 0?this.errorCall(r,n):e===void 0?{ok:!1,code:i.NetworkError,message:I(i.NetworkError),httpStatus:n.status}:{ok:!0,value:e}}errorCall(e,r){const n=e.code||i.Unknown;return{ok:!1,code:n,message:e.message||I(n),httpStatus:r.status,details:e.details??null}}}class B{get(e){return globalThis.sessionStorage?.getItem(e)??null}set(e,r){globalThis.sessionStorage?.setItem(e,r)}remove(e){globalThis.sessionStorage?.removeItem(e)}}class G{get(e){return globalThis.localStorage?.getItem(e)??null}set(e,r){globalThis.localStorage?.setItem(e,r)}remove(e){globalThis.localStorage?.removeItem(e)}}class a extends Error{code;httpStatus;details;constructor(e,r,n,o=null){super(r),this.name="Omni2FaApiError",this.code=e,this.httpStatus=n,this.details=o}}const j={enrollmentId:null,otpAuthUri:null,secret:null,methodId:null,recoveryCodes:null,errorCode:null,errorMessage:null};function _(t){return s.setup({types:{context:{},events:{}},actors:{startEnrollment:s.fromPromise(async()=>{const e=await t.startTotpEnrollment();if(!e.ok)throw new a(e.code,e.message,e.httpStatus,e.details??null);return e.value}),confirmEnrollment:s.fromPromise(async({input:e})=>{const r=await t.confirmTotpEnrollment({enrollmentId:e.enrollmentId,code:e.code,name:e.name});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value})}}).createMachine({id:"totpEnrollment",initial:"idle",context:j,states:{idle:{on:{start:{target:"starting"}}},starting:{invoke:{src:"startEnrollment",onDone:{target:"awaitingCode",actions:({context:e,event:r})=>{e.enrollmentId=r.output.enrollmentId,e.otpAuthUri=r.output.otpAuthUri,e.secret=r.output.secret,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>b(e,r.error)}}},awaitingCode:{on:{submit:{target:"confirming"},reset:{target:"idle",actions:p}}},confirming:{invoke:{src:"confirmEnrollment",input:({context:e,event:r})=>{if(r.type!=="submit")throw new Error("confirming requires submit event");if(!e.enrollmentId)throw new Error("no enrollmentId");return{enrollmentId:e.enrollmentId,code:r.code,name:r.name??null}},onDone:{target:"enrolled",actions:({context:e,event:r})=>{e.methodId=r.output.methodId,e.recoveryCodes=r.output.recoveryCodes??null,e.errorCode=null,e.errorMessage=null}},onError:{target:"awaitingCode",actions:({context:e,event:r})=>b(e,r.error)}}},enrolled:{on:{reset:{target:"idle",actions:p}}},failed:{on:{start:{target:"starting"},reset:{target:"idle",actions:p}}}}})}function p({context:t}){t.enrollmentId=null,t.otpAuthUri=null,t.secret=null,t.methodId=null,t.recoveryCodes=null,t.errorCode=null,t.errorMessage=null}function b(t,e){e instanceof a?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}const X={enrollmentId:null,email:null,expiresAt:null,resendAvailableAt:null,methodId:null,recoveryCodes:null,errorCode:null,errorMessage:null};function J(t){return s.setup({types:{context:{},events:{}},actors:{startEnrollment:s.fromPromise(async({input:e})=>{const r=await t.startEmailEnrollment(e.email!==void 0?{email:e.email}:{});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),resendEnrollment:s.fromPromise(async({input:e})=>{const r=await t.resendEmailEnrollment({enrollmentId:e.enrollmentId});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),confirmEnrollment:s.fromPromise(async({input:e})=>{const r=await t.confirmEmailEnrollment({enrollmentId:e.enrollmentId,code:e.code,name:e.name});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value})}}).createMachine({id:"emailEnrollment",initial:"idle",context:X,states:{idle:{on:{start:{target:"starting"}}},starting:{entry:({context:e,event:r})=>{r.type==="start"&&(e.email=r.email??null)},invoke:{src:"startEnrollment",input:({context:e})=>({email:e.email??void 0}),onDone:{target:"awaitingCode",actions:({context:e,event:r})=>M(e,r.output)},onError:{target:"failed",actions:({context:e,event:r})=>y(e,r.error)}}},awaitingCode:{on:{submit:{target:"confirming"},resend:{target:"resending"},reset:{target:"idle",actions:f}}},resending:{invoke:{src:"resendEnrollment",input:({context:e})=>{if(!e.enrollmentId)throw new Error("no enrollmentId");return{enrollmentId:e.enrollmentId}},onDone:{target:"awaitingCode",actions:({context:e,event:r})=>M(e,r.output)},onError:{target:"awaitingCode",actions:({context:e,event:r})=>y(e,r.error)}}},confirming:{invoke:{src:"confirmEnrollment",input:({context:e,event:r})=>{if(r.type!=="submit")throw new Error("confirming requires submit event");if(!e.enrollmentId)throw new Error("no enrollmentId");return{enrollmentId:e.enrollmentId,code:r.code,name:r.name??null}},onDone:{target:"enrolled",actions:({context:e,event:r})=>{e.methodId=r.output.methodId,e.recoveryCodes=r.output.recoveryCodes??null,e.errorCode=null,e.errorMessage=null}},onError:{target:"awaitingCode",actions:({context:e,event:r})=>y(e,r.error)}}},enrolled:{on:{reset:{target:"idle",actions:f}}},failed:{on:{start:{target:"starting"},reset:{target:"idle",actions:f}}}}})}function M(t,e){t.enrollmentId=e.enrollmentId,t.expiresAt=e.expiresAt,t.resendAvailableAt=e.resendAvailableAt,t.errorCode=null,t.errorMessage=null}function f({context:t}){t.enrollmentId=null,t.email=null,t.expiresAt=null,t.resendAvailableAt=null,t.methodId=null,t.recoveryCodes=null,t.errorCode=null,t.errorMessage=null}function y(t,e){e instanceof a?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}function c(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=atob(r),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);return o.buffer}function d(t){const e=new Uint8Array(t);let r="";for(const n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function F(t){return(t??[]).map(e=>({...e,id:c(e.id)}))}async function W(t){const e=JSON.parse(t),r={...e,challenge:c(e.challenge),user:{...e.user,id:c(e.user.id)},excludeCredentials:F(e.excludeCredentials)},n=await navigator.credentials.create({publicKey:r});if(n===null)throw new Error("WebAuthn registration produced no credential.");const o=n.response;return JSON.stringify({id:n.id,rawId:d(n.rawId),type:n.type,extensions:n.getClientExtensionResults(),response:{attestationObject:d(o.attestationObject),clientDataJSON:d(o.clientDataJSON)}})}async function A(t){const e=JSON.parse(t),r={...e,challenge:c(e.challenge),allowCredentials:F(e.allowCredentials)},n=await navigator.credentials.get({publicKey:r});if(n===null)throw new Error("WebAuthn authentication produced no credential.");const o=n.response;return JSON.stringify({id:n.id,rawId:d(n.rawId),type:n.type,extensions:n.getClientExtensionResults(),response:{authenticatorData:d(o.authenticatorData),clientDataJSON:d(o.clientDataJSON),signature:d(o.signature),userHandle:o.userHandle?d(o.userHandle):null}})}const z={enrollmentId:null,optionsJson:null,name:null,methodId:null,recoveryCodes:null,errorCode:null,errorMessage:null};function L(t){return s.setup({types:{context:{},events:{}},actors:{startEnrollment:s.fromPromise(async()=>{const e=await t.startWebAuthnEnrollment();if(!e.ok)throw new a(e.code,e.message,e.httpStatus,e.details??null);return e.value}),registerAndConfirm:s.fromPromise(async({input:e})=>{const r=await W(e.optionsJson),n=await t.confirmWebAuthnEnrollment({enrollmentId:e.enrollmentId,attestationResponseJson:r,name:e.name});if(!n.ok)throw new a(n.code,n.message,n.httpStatus,n.details??null);return n.value})}}).createMachine({id:"webauthnEnrollment",initial:"idle",context:z,states:{idle:{on:{start:{target:"starting"}}},starting:{entry:({context:e,event:r})=>{r.type==="start"&&(e.name=r.name??null)},invoke:{src:"startEnrollment",onDone:{target:"registering",actions:({context:e,event:r})=>{e.enrollmentId=r.output.enrollmentId,e.optionsJson=r.output.optionsJson,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>U(e,r.error)}}},registering:{invoke:{src:"registerAndConfirm",input:({context:e})=>{if(!e.enrollmentId||!e.optionsJson)throw new Error("no pending enrollment");return{enrollmentId:e.enrollmentId,optionsJson:e.optionsJson,name:e.name}},onDone:{target:"enrolled",actions:({context:e,event:r})=>{e.methodId=r.output.methodId,e.recoveryCodes=r.output.recoveryCodes??null,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>U(e,r.error)}}},enrolled:{on:{reset:{target:"idle",actions:k}}},failed:{on:{retry:{target:"starting"},reset:{target:"idle",actions:k}}}}})}function k({context:t}){t.enrollmentId=null,t.optionsJson=null,t.name=null,t.methodId=null,t.recoveryCodes=null,t.errorCode=null,t.errorMessage=null}function U(t,e){e instanceof a?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}const Q={methodId:null,methodType:null,userId:null,verifiedToken:null,expiresAt:null,resendAvailableAt:null,optionsJson:null,errorCode:null,errorMessage:null};function K(t){return s.setup({types:{context:{},events:{}},actors:{startChallenge:s.fromPromise(async({input:e})=>{const r=await t.startChallenge({methodId:e.methodId});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),resendChallenge:s.fromPromise(async({input:e})=>{const r=await t.resendChallenge({methodId:e.methodId});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),verifyChallenge:s.fromPromise(async({input:e})=>{const r=await t.verifyChallenge({methodId:e.methodId,code:e.code});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),assertChallenge:s.fromPromise(async({input:e})=>{const r=await A(e.optionsJson),n=await t.verifyChallenge({methodId:e.methodId,assertionResponseJson:r});if(!n.ok)throw new a(n.code,n.message,n.httpStatus,n.details??null);return n.value}),verifyRecoveryCode:s.fromPromise(async({input:e})=>{const r=await t.verifyRecoveryCode({recoveryCode:e.code});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value})}}).createMachine({id:"challenge",initial:"idle",context:Q,states:{idle:{on:{pick:{target:"starting"},useRecoveryCode:{target:"verifyingRecovery"}}},starting:{entry:({context:e,event:r})=>{r.type==="pick"&&(e.methodId=r.methodId)},invoke:{src:"startChallenge",input:({context:e})=>{if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId}},onDone:[{guard:({event:e})=>e.output.type==="WebAuthn",target:"asserting",actions:({context:e,event:r})=>E(e,r.output)},{target:"awaitingCode",actions:({context:e,event:r})=>E(e,r.output)}],onError:{target:"failed",actions:({context:e,event:r})=>u(e,r.error)}}},asserting:{invoke:{src:"assertChallenge",input:({context:e})=>{if(!e.methodId||!e.optionsJson)throw new Error("no assertion options");return{methodId:e.methodId,optionsJson:e.optionsJson}},onDone:{target:"verified",actions:({context:e,event:r})=>{e.userId=r.output.userId,e.verifiedToken=r.output.verifiedToken,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>u(e,r.error)}}},awaitingCode:{on:{submit:{target:"verifying"},resend:{target:"resending"},useRecoveryCode:{target:"verifyingRecovery"},reset:{target:"idle",actions:w}}},verifyingRecovery:{invoke:{src:"verifyRecoveryCode",input:({event:e})=>{if(e.type!=="useRecoveryCode")throw new Error("verifyingRecovery requires useRecoveryCode event");return{code:e.code}},onDone:{target:"verified",actions:({context:e,event:r})=>{e.userId=r.output.userId,e.verifiedToken=r.output.verifiedToken,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>u(e,r.error)}}},resending:{invoke:{src:"resendChallenge",input:({context:e})=>{if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId}},onDone:{target:"awaitingCode",actions:({context:e,event:r})=>E(e,r.output)},onError:{target:"awaitingCode",actions:({context:e,event:r})=>u(e,r.error)}}},verifying:{invoke:{src:"verifyChallenge",input:({context:e,event:r})=>{if(r.type!=="submit")throw new Error("verifying requires submit event");if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId,code:r.code}},onDone:{target:"verified",actions:({context:e,event:r})=>{e.userId=r.output.userId,e.verifiedToken=r.output.verifiedToken,e.errorCode=null,e.errorMessage=null}},onError:{target:"awaitingCode",actions:({context:e,event:r})=>u(e,r.error)}}},verified:{on:{reset:{target:"idle",actions:w}}},failed:{on:{pick:{target:"starting"},useRecoveryCode:{target:"verifyingRecovery"},reset:{target:"idle",actions:w}}}}})}function E(t,e){t.methodType=e.type,t.expiresAt=e.expiresAt??null,t.resendAvailableAt=e.resendAvailableAt??null,t.optionsJson=e.optionsJson??null,t.errorCode=null,t.errorMessage=null}function w({context:t}){t.methodId=null,t.methodType=null,t.userId=null,t.verifiedToken=null,t.expiresAt=null,t.resendAvailableAt=null,t.optionsJson=null,t.errorCode=null,t.errorMessage=null}function u(t,e){e instanceof a?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}const Z={items:[],errorCode:null,errorMessage:null};function H(t){return s.setup({types:{context:{},events:{}},actors:{load:s.fromPromise(async()=>{const e=await t.listMethods();if(!e.ok)throw new a(e.code,e.message,e.httpStatus,e.details??null);return e.value}),remove:s.fromPromise(async({input:e})=>{const r=await t.removeMethod(e.methodId);if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return e.methodId})}}).createMachine({id:"methods",initial:"idle",context:Z,states:{idle:{on:{load:{target:"loading"}}},loading:{invoke:{src:"load",onDone:{target:"ready",actions:({context:e,event:r})=>{e.items=r.output,e.errorCode=null,e.errorMessage=null}},onError:{target:"failed",actions:({context:e,event:r})=>O(e,r.error)}}},ready:{on:{load:{target:"loading"},remove:{target:"removing"}}},removing:{invoke:{src:"remove",input:({event:e})=>{if(e.type!=="remove")throw new Error("removing requires remove event");return{methodId:e.methodId}},onDone:{target:"ready",actions:({context:e,event:r})=>{const n=r.output;e.items=e.items.filter(o=>o.id!==n),e.errorCode=null,e.errorMessage=null}},onError:{target:"ready",actions:({context:e,event:r})=>O(e,r.error)}}},failed:{on:{load:{target:"loading"},reset:{target:"idle",actions:x}}}}})}function x({context:t}){t.items=[],t.errorCode=null,t.errorMessage=null}function O(t,e){e instanceof a?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}const ee={methodId:null,methodType:null,stepUpToken:null,expiresAt:null,resendAvailableAt:null,optionsJson:null,errorCode:null,errorMessage:null};function $(t){return s.setup({types:{context:{},events:{}},actors:{startStepUp:s.fromPromise(async({input:e})=>{const r=await t.startStepUp({methodId:e.methodId});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),resendStepUp:s.fromPromise(async({input:e})=>{const r=await t.resendStepUp({methodId:e.methodId});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),verifyStepUp:s.fromPromise(async({input:e})=>{const r=await t.verifyStepUp({methodId:e.methodId,code:e.code});if(!r.ok)throw new a(r.code,r.message,r.httpStatus,r.details??null);return r.value}),assertStepUp:s.fromPromise(async({input:e})=>{const r=await A(e.optionsJson),n=await t.verifyStepUp({methodId:e.methodId,assertionResponseJson:r});if(!n.ok)throw new a(n.code,n.message,n.httpStatus,n.details??null);return n.value})}}).createMachine({id:"stepup",initial:"idle",context:ee,states:{idle:{on:{pick:{target:"starting"}}},starting:{entry:({context:e,event:r})=>{r.type==="pick"&&(e.methodId=r.methodId)},invoke:{src:"startStepUp",input:({context:e})=>{if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId}},onDone:[{guard:({event:e})=>e.output.type==="WebAuthn",target:"asserting",actions:({context:e,event:r})=>v(e,r.output)},{target:"awaitingCode",actions:({context:e,event:r})=>v(e,r.output)}],onError:{target:"failed",actions:({context:e,event:r})=>h(e,r.error)}}},asserting:{invoke:{src:"assertStepUp",input:({context:e})=>{if(!e.methodId||!e.optionsJson)throw new Error("no assertion options");return{methodId:e.methodId,optionsJson:e.optionsJson}},onDone:{target:"verified",actions:({context:e,event:r})=>P(e,r.output.stepUpToken)},onError:{target:"failed",actions:({context:e,event:r})=>h(e,r.error)}}},awaitingCode:{on:{submit:{target:"verifying"},resend:{target:"resending"},reset:{target:"idle",actions:C}}},resending:{invoke:{src:"resendStepUp",input:({context:e})=>{if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId}},onDone:{target:"awaitingCode",actions:({context:e,event:r})=>v(e,r.output)},onError:{target:"awaitingCode",actions:({context:e,event:r})=>h(e,r.error)}}},verifying:{invoke:{src:"verifyStepUp",input:({context:e,event:r})=>{if(r.type!=="submit")throw new Error("verifying requires submit event");if(!e.methodId)throw new Error("no methodId");return{methodId:e.methodId,code:r.code}},onDone:{target:"verified",actions:({context:e,event:r})=>P(e,r.output.stepUpToken)},onError:{target:"awaitingCode",actions:({context:e,event:r})=>h(e,r.error)}}},verified:{on:{reset:{target:"idle",actions:C}}},failed:{on:{pick:{target:"starting"},reset:{target:"idle",actions:C}}}}})}function v(t,e){t.methodType=e.type,t.expiresAt=e.expiresAt??null,t.resendAvailableAt=e.resendAvailableAt??null,t.optionsJson=e.optionsJson??null,t.errorCode=null,t.errorMessage=null}function P(t,e){t.stepUpToken=e,t.errorCode=null,t.errorMessage=null}function C({context:t}){t.methodId=null,t.methodType=null,t.stepUpToken=null,t.expiresAt=null,t.resendAvailableAt=null,t.optionsJson=null,t.errorCode=null,t.errorMessage=null}function h(t,e){e instanceof a?(t.errorCode=e.code,t.errorMessage=e.message):(t.errorCode="UNKNOWN",t.errorMessage=e instanceof Error?e.message:null)}function re(t){const e=new D(t),r=s.createActor(_(e)),n=s.createActor(J(e)),o=s.createActor(L(e)),l=s.createActor(K(e)),m=s.createActor($(e)),g=s.createActor(H(e));return r.start(),n.start(),o.start(),l.start(),m.start(),g.start(),{client:e,totpEnrollment:r,emailEnrollment:n,webauthnEnrollment:o,challenge:l,stepUp:m,methods:g,dispose(){r.stop(),n.stop(),o.stop(),l.stop(),m.stop(),g.stop()}}}exports.LocalStorageStorage=G;exports.MemoryStorage=N;exports.Omni2FaApiError=a;exports.Omni2FaClient=D;exports.Omni2FaErrorCodes=i;exports.STEP_UP_HEADER=R;exports.SessionStorageStorage=B;exports.createChallengeMachine=K;exports.createEmailEnrollmentMachine=J;exports.createMethodsMachine=H;exports.createOmni2Fa=re;exports.createStepUpMachine=$;exports.createTotpEnrollmentMachine=_;exports.createWebAuthnEnrollmentMachine=L;exports.getDefaultMessage=I;exports.startAuthentication=A;exports.startRegistration=W;
2
2
  //# sourceMappingURL=index.cjs.map