tempest-express-sdk 0.9.0 → 0.11.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/README.md +1 -1
- package/dist/chunk-IHO6X75J.js +6 -0
- package/dist/{chunk-4QZZGHGV.js.map → chunk-IHO6X75J.js.map} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.cjs +185 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +255 -81
- package/dist/index.d.ts +255 -81
- package/dist/index.js +182 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4QZZGHGV.js +0 -6
package/dist/index.d.ts
CHANGED
|
@@ -2641,6 +2641,132 @@ interface TwilioWebhookOptions {
|
|
|
2641
2641
|
*/
|
|
2642
2642
|
declare function makeTwilioWebhookRouter(options: TwilioWebhookOptions): Router;
|
|
2643
2643
|
|
|
2644
|
+
/**
|
|
2645
|
+
* Email channel — a {@link MessagingProvider} over {@link EmailUtils}.
|
|
2646
|
+
*
|
|
2647
|
+
* Lets transactional email participate in the same swappable messaging contract
|
|
2648
|
+
* as WhatsApp/Telegram/SMS: `sendText` sends a plain email, `sendMedia` sends
|
|
2649
|
+
* the media as a link in the body. Inbound (`onMessage`) is absent — email
|
|
2650
|
+
* ingestion is out of scope. Requires the optional `nodemailer` peer via
|
|
2651
|
+
* {@link EmailUtils}.
|
|
2652
|
+
*/
|
|
2653
|
+
|
|
2654
|
+
/** Options for {@link EmailProvider}. */
|
|
2655
|
+
interface EmailProviderOptions {
|
|
2656
|
+
/** The configured SMTP sender. */
|
|
2657
|
+
email: EmailUtils;
|
|
2658
|
+
/** Default subject line for `sendText`/`sendMedia`. Default `"Notification"`. */
|
|
2659
|
+
subject?: string;
|
|
2660
|
+
}
|
|
2661
|
+
/** An email-backed {@link MessagingProvider}. */
|
|
2662
|
+
declare class EmailProvider implements MessagingProvider {
|
|
2663
|
+
private readonly email;
|
|
2664
|
+
private readonly subject;
|
|
2665
|
+
/**
|
|
2666
|
+
* @param options - The email sender and default subject.
|
|
2667
|
+
*/
|
|
2668
|
+
constructor(options: EmailProviderOptions);
|
|
2669
|
+
/**
|
|
2670
|
+
* Send a plain-text email.
|
|
2671
|
+
*
|
|
2672
|
+
* @param to - Recipient address.
|
|
2673
|
+
* @param text - Body text (also used as HTML).
|
|
2674
|
+
* @returns A sent result.
|
|
2675
|
+
*/
|
|
2676
|
+
sendText(to: string, text: string): Promise<OutboundResult>;
|
|
2677
|
+
/**
|
|
2678
|
+
* Send an email linking to the media (caption becomes the lead text).
|
|
2679
|
+
*
|
|
2680
|
+
* @param to - Recipient address.
|
|
2681
|
+
* @param media - The media reference (URL) + optional caption.
|
|
2682
|
+
* @returns A sent result.
|
|
2683
|
+
*/
|
|
2684
|
+
sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
|
|
2685
|
+
/** Always `"connected"` — SMTP reachability is verified on first send. */
|
|
2686
|
+
status(): Promise<string>;
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
/**
|
|
2690
|
+
* Broadcast + multi-channel helpers over {@link MessagingProvider}.
|
|
2691
|
+
*
|
|
2692
|
+
* {@link broadcastText} fans one message out to many recipients through a single
|
|
2693
|
+
* provider, with bounded concurrency and a per-recipient result (one failure
|
|
2694
|
+
* never aborts the rest). {@link MessagingHub} keeps named providers so app code
|
|
2695
|
+
* sends by channel name and can broadcast across all of them.
|
|
2696
|
+
*/
|
|
2697
|
+
|
|
2698
|
+
/** The outcome of a single recipient's send within a broadcast. */
|
|
2699
|
+
interface BroadcastResult {
|
|
2700
|
+
/** The recipient address/handle. */
|
|
2701
|
+
to: string;
|
|
2702
|
+
/** Whether the send succeeded. */
|
|
2703
|
+
ok: boolean;
|
|
2704
|
+
/** The provider result, when successful. */
|
|
2705
|
+
result?: OutboundResult;
|
|
2706
|
+
/** The error message, when failed. */
|
|
2707
|
+
error?: string;
|
|
2708
|
+
}
|
|
2709
|
+
/** Options for {@link broadcastText}. */
|
|
2710
|
+
interface BroadcastOptions extends SendOptions {
|
|
2711
|
+
/** Maximum concurrent sends. Default 10. */
|
|
2712
|
+
concurrency?: number;
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* Send `text` to every recipient through `provider`, bounded by concurrency.
|
|
2716
|
+
*
|
|
2717
|
+
* A failed recipient is captured in its {@link BroadcastResult} (`ok: false`)
|
|
2718
|
+
* rather than aborting the batch.
|
|
2719
|
+
*
|
|
2720
|
+
* @param provider - The channel to send through.
|
|
2721
|
+
* @param recipients - Recipient addresses/handles.
|
|
2722
|
+
* @param text - The message body.
|
|
2723
|
+
* @param options - Concurrency + send options.
|
|
2724
|
+
* @returns One result per recipient, in input order.
|
|
2725
|
+
*/
|
|
2726
|
+
declare function broadcastText(provider: MessagingProvider, recipients: string[], text: string, options?: BroadcastOptions): Promise<BroadcastResult[]>;
|
|
2727
|
+
/** A registry of named messaging channels. */
|
|
2728
|
+
declare class MessagingHub {
|
|
2729
|
+
private readonly channels;
|
|
2730
|
+
/**
|
|
2731
|
+
* Register a provider under a channel name.
|
|
2732
|
+
*
|
|
2733
|
+
* @param name - The channel name (e.g. `"whatsapp"`, `"sms"`).
|
|
2734
|
+
* @param provider - The provider implementation.
|
|
2735
|
+
* @returns The hub (chainable).
|
|
2736
|
+
*/
|
|
2737
|
+
register(name: string, provider: MessagingProvider): this;
|
|
2738
|
+
/**
|
|
2739
|
+
* Get a registered provider, throwing when the channel is unknown.
|
|
2740
|
+
*
|
|
2741
|
+
* @param name - The channel name.
|
|
2742
|
+
* @returns The provider.
|
|
2743
|
+
* @throws {Error} When no provider is registered under `name`.
|
|
2744
|
+
*/
|
|
2745
|
+
get(name: string): MessagingProvider;
|
|
2746
|
+
/** The registered channel names. */
|
|
2747
|
+
channelNames(): string[];
|
|
2748
|
+
/**
|
|
2749
|
+
* Send text through a named channel.
|
|
2750
|
+
*
|
|
2751
|
+
* @param channel - The channel name.
|
|
2752
|
+
* @param to - The recipient.
|
|
2753
|
+
* @param text - The message body.
|
|
2754
|
+
* @param options - Send options.
|
|
2755
|
+
* @returns The provider result.
|
|
2756
|
+
*/
|
|
2757
|
+
send(channel: string, to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
|
|
2758
|
+
/**
|
|
2759
|
+
* Broadcast text to many recipients on a named channel.
|
|
2760
|
+
*
|
|
2761
|
+
* @param channel - The channel name.
|
|
2762
|
+
* @param recipients - Recipient addresses/handles.
|
|
2763
|
+
* @param text - The message body.
|
|
2764
|
+
* @param options - Broadcast + send options.
|
|
2765
|
+
* @returns One result per recipient.
|
|
2766
|
+
*/
|
|
2767
|
+
broadcast(channel: string, recipients: string[], text: string, options?: BroadcastOptions): Promise<BroadcastResult[]>;
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2644
2770
|
/**
|
|
2645
2771
|
* Admin site + resource registry, mirroring `admin.site` / `admin.config`.
|
|
2646
2772
|
*
|
|
@@ -2919,6 +3045,17 @@ declare const mfaCodeSchema: z.ZodObject<{
|
|
|
2919
3045
|
}, {
|
|
2920
3046
|
code: string;
|
|
2921
3047
|
}>;
|
|
3048
|
+
/** MFA login-challenge body (`POST /auth/mfa/challenge`). */
|
|
3049
|
+
declare const mfaChallengeSchema: z.ZodObject<{
|
|
3050
|
+
mfaToken: z.ZodString;
|
|
3051
|
+
code: z.ZodString;
|
|
3052
|
+
}, "strip", z.ZodTypeAny, {
|
|
3053
|
+
code: string;
|
|
3054
|
+
mfaToken: string;
|
|
3055
|
+
}, {
|
|
3056
|
+
code: string;
|
|
3057
|
+
mfaToken: string;
|
|
3058
|
+
}>;
|
|
2922
3059
|
/** Activation body (`POST /auth/activate`). */
|
|
2923
3060
|
declare const activationSchema: z.ZodObject<{
|
|
2924
3061
|
token: z.ZodString;
|
|
@@ -2953,17 +3090,100 @@ type TokenPair = z.infer<typeof tokenPairSchema>;
|
|
|
2953
3090
|
type UserPublic = z.infer<typeof userPublicSchema>;
|
|
2954
3091
|
type AuthResponse = z.infer<typeof authResponseSchema>;
|
|
2955
3092
|
type MfaCodeInput = z.infer<typeof mfaCodeSchema>;
|
|
3093
|
+
type MfaChallengeInput = z.infer<typeof mfaChallengeSchema>;
|
|
2956
3094
|
type ActivationInput = z.infer<typeof activationSchema>;
|
|
2957
3095
|
type PasswordResetRequestInput = z.infer<typeof passwordResetRequestSchema>;
|
|
2958
3096
|
type PasswordResetConfirmInput = z.infer<typeof passwordResetConfirmSchema>;
|
|
2959
3097
|
|
|
3098
|
+
/**
|
|
3099
|
+
* TOTP MFA enrollment/verification, mirroring the FastAPI SDK MFA flow.
|
|
3100
|
+
*
|
|
3101
|
+
* Orchestrates {@link TOTPHelper} over a pluggable {@link MfaStore}: enroll
|
|
3102
|
+
* (generate + persist a secret, return the provisioning URI), confirm (verify a
|
|
3103
|
+
* code and flip MFA on), verify (login step) and disable.
|
|
3104
|
+
*/
|
|
3105
|
+
|
|
3106
|
+
/** Persistence port for MFA secrets/state. */
|
|
3107
|
+
interface MfaStore {
|
|
3108
|
+
/** Persist a user's TOTP secret (pending until confirmed). */
|
|
3109
|
+
setSecret(userId: string, secret: string): Promise<void>;
|
|
3110
|
+
/** Read a user's TOTP secret, or `null`. */
|
|
3111
|
+
getSecret(userId: string): Promise<string | null>;
|
|
3112
|
+
/** Flip the MFA-enabled flag. */
|
|
3113
|
+
setEnabled(userId: string, enabled: boolean): Promise<void>;
|
|
3114
|
+
/** Whether MFA is enabled for the user. */
|
|
3115
|
+
isEnabled(userId: string): Promise<boolean>;
|
|
3116
|
+
}
|
|
3117
|
+
/** The result of starting enrollment. */
|
|
3118
|
+
interface MfaEnrollment {
|
|
3119
|
+
/** The base32 secret (persist server-side; also shown once for manual entry). */
|
|
3120
|
+
secret: string;
|
|
3121
|
+
/** The `otpauth://` URI to render as a QR code. */
|
|
3122
|
+
otpauthUri: string;
|
|
3123
|
+
}
|
|
3124
|
+
/** Options for {@link MfaService}. */
|
|
3125
|
+
interface MfaServiceOptions {
|
|
3126
|
+
/** The MFA persistence port. */
|
|
3127
|
+
store: MfaStore;
|
|
3128
|
+
/** The TOTP helper (issuer preconfigured). */
|
|
3129
|
+
totp: TOTPHelper;
|
|
3130
|
+
}
|
|
3131
|
+
declare class MfaService {
|
|
3132
|
+
private readonly store;
|
|
3133
|
+
private readonly totp;
|
|
3134
|
+
/**
|
|
3135
|
+
* @param options - Store and TOTP helper.
|
|
3136
|
+
*/
|
|
3137
|
+
constructor(options: MfaServiceOptions);
|
|
3138
|
+
/**
|
|
3139
|
+
* Begin enrollment: generate and persist a secret, return the QR URI.
|
|
3140
|
+
*
|
|
3141
|
+
* @param userId - The enrolling user.
|
|
3142
|
+
* @param accountName - Label shown in the authenticator (usually the email).
|
|
3143
|
+
* @returns The secret and provisioning URI.
|
|
3144
|
+
*/
|
|
3145
|
+
enroll(userId: string, accountName: string): Promise<MfaEnrollment>;
|
|
3146
|
+
/**
|
|
3147
|
+
* Confirm enrollment by verifying a code, enabling MFA on success.
|
|
3148
|
+
*
|
|
3149
|
+
* @param userId - The user.
|
|
3150
|
+
* @param code - The 6-digit code from the authenticator.
|
|
3151
|
+
* @throws {ValidationException} When no secret is pending or the code is wrong.
|
|
3152
|
+
*/
|
|
3153
|
+
confirm(userId: string, code: string): Promise<void>;
|
|
3154
|
+
/**
|
|
3155
|
+
* Verify a code (login step). Returns `false` without throwing.
|
|
3156
|
+
*
|
|
3157
|
+
* @param userId - The user.
|
|
3158
|
+
* @param code - The submitted code.
|
|
3159
|
+
* @returns `true` when the code is valid.
|
|
3160
|
+
*/
|
|
3161
|
+
verify(userId: string, code: string): Promise<boolean>;
|
|
3162
|
+
/**
|
|
3163
|
+
* Whether MFA is enabled for a user (used to gate the login challenge).
|
|
3164
|
+
*
|
|
3165
|
+
* @param userId - The user.
|
|
3166
|
+
* @returns `true` when MFA is enabled.
|
|
3167
|
+
*/
|
|
3168
|
+
isEnabled(userId: string): Promise<boolean>;
|
|
3169
|
+
/**
|
|
3170
|
+
* Disable MFA after verifying a code.
|
|
3171
|
+
*
|
|
3172
|
+
* @param userId - The user.
|
|
3173
|
+
* @param code - The submitted code.
|
|
3174
|
+
* @throws {ValidationException} When the code is invalid.
|
|
3175
|
+
*/
|
|
3176
|
+
disable(userId: string, code: string): Promise<void>;
|
|
3177
|
+
}
|
|
3178
|
+
|
|
2960
3179
|
/**
|
|
2961
3180
|
* User authentication service, mirroring `auth.service.UserAuthService`.
|
|
2962
3181
|
*
|
|
2963
3182
|
* Orchestrates signup / login / refresh over a pluggable {@link UserStore},
|
|
2964
3183
|
* {@link PasswordUtils} and {@link JWTUtils}. It is ORM-agnostic — back the
|
|
2965
|
-
* store with a `tempest-db-js` repository (or anything else).
|
|
2966
|
-
*
|
|
3184
|
+
* store with a `tempest-db-js` repository (or anything else). With an
|
|
3185
|
+
* {@link MfaService} wired in, `login` returns an MFA challenge for enrolled
|
|
3186
|
+
* users (complete it via {@link UserAuthService.verifyMfaChallenge}).
|
|
2967
3187
|
*/
|
|
2968
3188
|
|
|
2969
3189
|
/** A persisted user as the auth layer needs to see it. */
|
|
@@ -3008,7 +3228,23 @@ interface UserAuthServiceOptions {
|
|
|
3008
3228
|
accessTtlSeconds?: number;
|
|
3009
3229
|
/** Refresh-token lifetime in seconds. Default 1209600 (14 days). */
|
|
3010
3230
|
refreshTtlSeconds?: number;
|
|
3011
|
-
|
|
3231
|
+
/**
|
|
3232
|
+
* When provided, `login` returns an MFA challenge instead of tokens for users
|
|
3233
|
+
* with MFA enabled; complete it with {@link UserAuthService.verifyMfaChallenge}.
|
|
3234
|
+
*/
|
|
3235
|
+
mfa?: MfaService;
|
|
3236
|
+
/** MFA challenge-token lifetime in seconds. Default 300 (5 min). */
|
|
3237
|
+
mfaChallengeTtlSeconds?: number;
|
|
3238
|
+
}
|
|
3239
|
+
/** Returned by `login` when the user must complete an MFA challenge. */
|
|
3240
|
+
interface MfaChallenge {
|
|
3241
|
+
/** Discriminator: an MFA step is required before tokens are issued. */
|
|
3242
|
+
mfaRequired: true;
|
|
3243
|
+
/** Short-lived token to submit alongside the code to `verifyMfaChallenge`. */
|
|
3244
|
+
mfaToken: string;
|
|
3245
|
+
}
|
|
3246
|
+
/** `login` result: either full auth, or an MFA challenge to complete. */
|
|
3247
|
+
type LoginResult = AuthResponse | MfaChallenge;
|
|
3012
3248
|
declare class UserAuthService {
|
|
3013
3249
|
private readonly store;
|
|
3014
3250
|
private readonly password;
|
|
@@ -3016,6 +3252,8 @@ declare class UserAuthService {
|
|
|
3016
3252
|
private readonly passwordMinLength;
|
|
3017
3253
|
private readonly accessTtlSeconds;
|
|
3018
3254
|
private readonly refreshTtlSeconds;
|
|
3255
|
+
private readonly mfa;
|
|
3256
|
+
private readonly mfaChallengeTtlSeconds;
|
|
3019
3257
|
/**
|
|
3020
3258
|
* @param options - Store, password/JWT helpers and token policy.
|
|
3021
3259
|
*/
|
|
@@ -3035,10 +3273,20 @@ declare class UserAuthService {
|
|
|
3035
3273
|
* Authenticate a user by email + password.
|
|
3036
3274
|
*
|
|
3037
3275
|
* @param data - Validated login payload.
|
|
3038
|
-
* @returns
|
|
3276
|
+
* @returns Full auth, or an {@link MfaChallenge} when MFA is enabled.
|
|
3039
3277
|
* @throws {UnauthorizedException} On bad credentials or inactive account.
|
|
3040
3278
|
*/
|
|
3041
|
-
login(data: LoginInput): Promise<
|
|
3279
|
+
login(data: LoginInput): Promise<LoginResult>;
|
|
3280
|
+
/**
|
|
3281
|
+
* Complete an MFA login challenge: verify the code and issue tokens.
|
|
3282
|
+
*
|
|
3283
|
+
* @param mfaToken - The challenge token from {@link login}.
|
|
3284
|
+
* @param code - The authenticator code.
|
|
3285
|
+
* @returns The public user and a fresh token pair.
|
|
3286
|
+
* @throws {UnauthorizedException} When the challenge/code is invalid, MFA is
|
|
3287
|
+
* not configured, or the account no longer exists / is inactive.
|
|
3288
|
+
*/
|
|
3289
|
+
verifyMfaChallenge(mfaToken: string, code: string): Promise<AuthResponse>;
|
|
3042
3290
|
/**
|
|
3043
3291
|
* Exchange a valid refresh token for a new token pair.
|
|
3044
3292
|
*
|
|
@@ -3050,80 +3298,6 @@ declare class UserAuthService {
|
|
|
3050
3298
|
refresh(refreshToken: string): Promise<AuthResponse>;
|
|
3051
3299
|
}
|
|
3052
3300
|
|
|
3053
|
-
/**
|
|
3054
|
-
* TOTP MFA enrollment/verification, mirroring the FastAPI SDK MFA flow.
|
|
3055
|
-
*
|
|
3056
|
-
* Orchestrates {@link TOTPHelper} over a pluggable {@link MfaStore}: enroll
|
|
3057
|
-
* (generate + persist a secret, return the provisioning URI), confirm (verify a
|
|
3058
|
-
* code and flip MFA on), verify (login step) and disable.
|
|
3059
|
-
*/
|
|
3060
|
-
|
|
3061
|
-
/** Persistence port for MFA secrets/state. */
|
|
3062
|
-
interface MfaStore {
|
|
3063
|
-
/** Persist a user's TOTP secret (pending until confirmed). */
|
|
3064
|
-
setSecret(userId: string, secret: string): Promise<void>;
|
|
3065
|
-
/** Read a user's TOTP secret, or `null`. */
|
|
3066
|
-
getSecret(userId: string): Promise<string | null>;
|
|
3067
|
-
/** Flip the MFA-enabled flag. */
|
|
3068
|
-
setEnabled(userId: string, enabled: boolean): Promise<void>;
|
|
3069
|
-
/** Whether MFA is enabled for the user. */
|
|
3070
|
-
isEnabled(userId: string): Promise<boolean>;
|
|
3071
|
-
}
|
|
3072
|
-
/** The result of starting enrollment. */
|
|
3073
|
-
interface MfaEnrollment {
|
|
3074
|
-
/** The base32 secret (persist server-side; also shown once for manual entry). */
|
|
3075
|
-
secret: string;
|
|
3076
|
-
/** The `otpauth://` URI to render as a QR code. */
|
|
3077
|
-
otpauthUri: string;
|
|
3078
|
-
}
|
|
3079
|
-
/** Options for {@link MfaService}. */
|
|
3080
|
-
interface MfaServiceOptions {
|
|
3081
|
-
/** The MFA persistence port. */
|
|
3082
|
-
store: MfaStore;
|
|
3083
|
-
/** The TOTP helper (issuer preconfigured). */
|
|
3084
|
-
totp: TOTPHelper;
|
|
3085
|
-
}
|
|
3086
|
-
declare class MfaService {
|
|
3087
|
-
private readonly store;
|
|
3088
|
-
private readonly totp;
|
|
3089
|
-
/**
|
|
3090
|
-
* @param options - Store and TOTP helper.
|
|
3091
|
-
*/
|
|
3092
|
-
constructor(options: MfaServiceOptions);
|
|
3093
|
-
/**
|
|
3094
|
-
* Begin enrollment: generate and persist a secret, return the QR URI.
|
|
3095
|
-
*
|
|
3096
|
-
* @param userId - The enrolling user.
|
|
3097
|
-
* @param accountName - Label shown in the authenticator (usually the email).
|
|
3098
|
-
* @returns The secret and provisioning URI.
|
|
3099
|
-
*/
|
|
3100
|
-
enroll(userId: string, accountName: string): Promise<MfaEnrollment>;
|
|
3101
|
-
/**
|
|
3102
|
-
* Confirm enrollment by verifying a code, enabling MFA on success.
|
|
3103
|
-
*
|
|
3104
|
-
* @param userId - The user.
|
|
3105
|
-
* @param code - The 6-digit code from the authenticator.
|
|
3106
|
-
* @throws {ValidationException} When no secret is pending or the code is wrong.
|
|
3107
|
-
*/
|
|
3108
|
-
confirm(userId: string, code: string): Promise<void>;
|
|
3109
|
-
/**
|
|
3110
|
-
* Verify a code (login step). Returns `false` without throwing.
|
|
3111
|
-
*
|
|
3112
|
-
* @param userId - The user.
|
|
3113
|
-
* @param code - The submitted code.
|
|
3114
|
-
* @returns `true` when the code is valid.
|
|
3115
|
-
*/
|
|
3116
|
-
verify(userId: string, code: string): Promise<boolean>;
|
|
3117
|
-
/**
|
|
3118
|
-
* Disable MFA after verifying a code.
|
|
3119
|
-
*
|
|
3120
|
-
* @param userId - The user.
|
|
3121
|
-
* @param code - The submitted code.
|
|
3122
|
-
* @throws {ValidationException} When the code is invalid.
|
|
3123
|
-
*/
|
|
3124
|
-
disable(userId: string, code: string): Promise<void>;
|
|
3125
|
-
}
|
|
3126
|
-
|
|
3127
3301
|
/**
|
|
3128
3302
|
* Email-activation flow, mirroring the FastAPI SDK activation flow.
|
|
3129
3303
|
*
|
|
@@ -3623,6 +3797,6 @@ interface RunServerOptions {
|
|
|
3623
3797
|
declare function runServer(app: Express, options?: RunServerOptions): Promise<Server>;
|
|
3624
3798
|
|
|
3625
3799
|
/** The installed SDK version. Single source of truth for the barrel + CLI. */
|
|
3626
|
-
declare const VERSION = "0.
|
|
3800
|
+
declare const VERSION = "0.11.0";
|
|
3627
3801
|
|
|
3628
|
-
export { type ActivationInput, ActivationService, type ActivationServiceOptions, type ActivationStore, type AdminField, type AdminListQuery, type AdminListResult, type AdminResource, type AdminRouterOptions, AdminSite, AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GPUMetrics, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, type MessagingProvider, type MetricsRouterOptions, MetricsUtils, type MfaCodeInput, type MfaEnrollment, MfaService, type MfaServiceOptions, type MfaStore, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, type PasswordResetConfirmInput, type PasswordResetRequestInput, PasswordResetService, type PasswordResetServiceOptions, type PasswordResetStore, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedisPublisherLike, RedisSSEBroker, type RedisSSEBrokerOptions, RedisSessionStore, type RedisSubscriberLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, type SessionRedisLike, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, TelegramProvider, type TelegramProviderOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, TwilioSmsProvider, type TwilioSmsProviderOptions, type TwilioWebhookOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, activationSchema, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeMetricsRouter, makeSessionMiddleware, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, mfaCodeSchema, mfaEnrollResponseSchema, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, passwordResetConfirmSchema, passwordResetRequestSchema, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
|
|
3802
|
+
export { type ActivationInput, ActivationService, type ActivationServiceOptions, type ActivationStore, type AdminField, type AdminListQuery, type AdminListResult, type AdminResource, type AdminRouterOptions, AdminSite, AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BroadcastOptions, type BroadcastResult, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailProvider, type EmailProviderOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GPUMetrics, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type LoginResult, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, MessagingHub, type MessagingProvider, type MetricsRouterOptions, MetricsUtils, type MfaChallenge, type MfaChallengeInput, type MfaCodeInput, type MfaEnrollment, MfaService, type MfaServiceOptions, type MfaStore, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, type PasswordResetConfirmInput, type PasswordResetRequestInput, PasswordResetService, type PasswordResetServiceOptions, type PasswordResetStore, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedisPublisherLike, RedisSSEBroker, type RedisSSEBrokerOptions, RedisSessionStore, type RedisSubscriberLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, type SessionRedisLike, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, TelegramProvider, type TelegramProviderOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, TwilioSmsProvider, type TwilioSmsProviderOptions, type TwilioWebhookOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, activationSchema, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, broadcastText, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeMetricsRouter, makeSessionMiddleware, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, mfaChallengeSchema, mfaCodeSchema, mfaEnrollResponseSchema, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, passwordResetConfirmSchema, passwordResetRequestSchema, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { VERSION } from './chunk-
|
|
1
|
+
export { VERSION } from './chunk-IHO6X75J.js';
|
|
2
2
|
import { AsyncLocalStorage } from 'async_hooks';
|
|
3
3
|
import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV31, OpenApiGeneratorV3 } from '@asteasolutions/zod-to-openapi';
|
|
4
4
|
export { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
|
|
@@ -8581,6 +8581,133 @@ function makeTwilioWebhookRouter(options) {
|
|
|
8581
8581
|
return router;
|
|
8582
8582
|
}
|
|
8583
8583
|
|
|
8584
|
+
// src/integrations/email.ts
|
|
8585
|
+
var EmailProvider = class {
|
|
8586
|
+
email;
|
|
8587
|
+
subject;
|
|
8588
|
+
/**
|
|
8589
|
+
* @param options - The email sender and default subject.
|
|
8590
|
+
*/
|
|
8591
|
+
constructor(options) {
|
|
8592
|
+
this.email = options.email;
|
|
8593
|
+
this.subject = options.subject ?? "Notification";
|
|
8594
|
+
}
|
|
8595
|
+
/**
|
|
8596
|
+
* Send a plain-text email.
|
|
8597
|
+
*
|
|
8598
|
+
* @param to - Recipient address.
|
|
8599
|
+
* @param text - Body text (also used as HTML).
|
|
8600
|
+
* @returns A sent result.
|
|
8601
|
+
*/
|
|
8602
|
+
async sendText(to, text) {
|
|
8603
|
+
await this.email.send({ to, subject: this.subject, text });
|
|
8604
|
+
return { status: "sent" };
|
|
8605
|
+
}
|
|
8606
|
+
/**
|
|
8607
|
+
* Send an email linking to the media (caption becomes the lead text).
|
|
8608
|
+
*
|
|
8609
|
+
* @param to - Recipient address.
|
|
8610
|
+
* @param media - The media reference (URL) + optional caption.
|
|
8611
|
+
* @returns A sent result.
|
|
8612
|
+
*/
|
|
8613
|
+
async sendMedia(to, media) {
|
|
8614
|
+
const caption = media.caption ?? "";
|
|
8615
|
+
await this.email.send({
|
|
8616
|
+
to,
|
|
8617
|
+
subject: this.subject,
|
|
8618
|
+
html: `${caption ? `<p>${caption}</p>` : ""}<p><a href="${media.media}">${media.media}</a></p>`
|
|
8619
|
+
});
|
|
8620
|
+
return { status: "sent" };
|
|
8621
|
+
}
|
|
8622
|
+
/** Always `"connected"` — SMTP reachability is verified on first send. */
|
|
8623
|
+
async status() {
|
|
8624
|
+
return "connected";
|
|
8625
|
+
}
|
|
8626
|
+
};
|
|
8627
|
+
|
|
8628
|
+
// src/integrations/broadcast.ts
|
|
8629
|
+
async function pool(items, limit, worker) {
|
|
8630
|
+
const results = new Array(items.length);
|
|
8631
|
+
let cursor = 0;
|
|
8632
|
+
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
8633
|
+
while (cursor < items.length) {
|
|
8634
|
+
const index = cursor++;
|
|
8635
|
+
results[index] = await worker(items[index], index);
|
|
8636
|
+
}
|
|
8637
|
+
});
|
|
8638
|
+
await Promise.all(runners);
|
|
8639
|
+
return results;
|
|
8640
|
+
}
|
|
8641
|
+
function broadcastText(provider, recipients, text, options = {}) {
|
|
8642
|
+
const { concurrency = 10, ...sendOptions } = options;
|
|
8643
|
+
return pool(recipients, concurrency, async (to) => {
|
|
8644
|
+
try {
|
|
8645
|
+
const result = await provider.sendText(to, text, sendOptions);
|
|
8646
|
+
return { to, ok: true, result };
|
|
8647
|
+
} catch (error) {
|
|
8648
|
+
return {
|
|
8649
|
+
to,
|
|
8650
|
+
ok: false,
|
|
8651
|
+
error: error instanceof Error ? error.message : String(error)
|
|
8652
|
+
};
|
|
8653
|
+
}
|
|
8654
|
+
});
|
|
8655
|
+
}
|
|
8656
|
+
var MessagingHub = class {
|
|
8657
|
+
channels = /* @__PURE__ */ new Map();
|
|
8658
|
+
/**
|
|
8659
|
+
* Register a provider under a channel name.
|
|
8660
|
+
*
|
|
8661
|
+
* @param name - The channel name (e.g. `"whatsapp"`, `"sms"`).
|
|
8662
|
+
* @param provider - The provider implementation.
|
|
8663
|
+
* @returns The hub (chainable).
|
|
8664
|
+
*/
|
|
8665
|
+
register(name, provider) {
|
|
8666
|
+
this.channels.set(name, provider);
|
|
8667
|
+
return this;
|
|
8668
|
+
}
|
|
8669
|
+
/**
|
|
8670
|
+
* Get a registered provider, throwing when the channel is unknown.
|
|
8671
|
+
*
|
|
8672
|
+
* @param name - The channel name.
|
|
8673
|
+
* @returns The provider.
|
|
8674
|
+
* @throws {Error} When no provider is registered under `name`.
|
|
8675
|
+
*/
|
|
8676
|
+
get(name) {
|
|
8677
|
+
const provider = this.channels.get(name);
|
|
8678
|
+
if (!provider) throw new Error(`Unknown messaging channel: ${name}`);
|
|
8679
|
+
return provider;
|
|
8680
|
+
}
|
|
8681
|
+
/** The registered channel names. */
|
|
8682
|
+
channelNames() {
|
|
8683
|
+
return [...this.channels.keys()];
|
|
8684
|
+
}
|
|
8685
|
+
/**
|
|
8686
|
+
* Send text through a named channel.
|
|
8687
|
+
*
|
|
8688
|
+
* @param channel - The channel name.
|
|
8689
|
+
* @param to - The recipient.
|
|
8690
|
+
* @param text - The message body.
|
|
8691
|
+
* @param options - Send options.
|
|
8692
|
+
* @returns The provider result.
|
|
8693
|
+
*/
|
|
8694
|
+
send(channel, to, text, options) {
|
|
8695
|
+
return this.get(channel).sendText(to, text, options);
|
|
8696
|
+
}
|
|
8697
|
+
/**
|
|
8698
|
+
* Broadcast text to many recipients on a named channel.
|
|
8699
|
+
*
|
|
8700
|
+
* @param channel - The channel name.
|
|
8701
|
+
* @param recipients - Recipient addresses/handles.
|
|
8702
|
+
* @param text - The message body.
|
|
8703
|
+
* @param options - Broadcast + send options.
|
|
8704
|
+
* @returns One result per recipient.
|
|
8705
|
+
*/
|
|
8706
|
+
broadcast(channel, recipients, text, options) {
|
|
8707
|
+
return broadcastText(this.get(channel), recipients, text, options);
|
|
8708
|
+
}
|
|
8709
|
+
};
|
|
8710
|
+
|
|
8584
8711
|
// src/admin/site.ts
|
|
8585
8712
|
var AdminSite = class {
|
|
8586
8713
|
/**
|
|
@@ -8720,6 +8847,10 @@ var mfaEnrollResponseSchema = z.object({
|
|
|
8720
8847
|
otpauthUri: z.string().openapi({ description: "otpauth:// URI to render as QR." })
|
|
8721
8848
|
}).openapi("MfaEnrollResponse");
|
|
8722
8849
|
var mfaCodeSchema = z.object({ code: z.string().min(1).openapi({ description: "Authenticator code." }) }).openapi("MfaCode");
|
|
8850
|
+
var mfaChallengeSchema = z.object({
|
|
8851
|
+
mfaToken: z.string().min(1).openapi({ description: "Challenge token from login." }),
|
|
8852
|
+
code: z.string().min(1).openapi({ description: "Authenticator code." })
|
|
8853
|
+
}).openapi("MfaChallenge");
|
|
8723
8854
|
var activationSchema = z.object({ token: z.string().min(1).openapi({ description: "Activation token." }) }).openapi("Activation");
|
|
8724
8855
|
var passwordResetRequestSchema = z.object({ email: z.string().email().openapi({ description: "Account email." }) }).openapi("PasswordResetRequest");
|
|
8725
8856
|
var passwordResetConfirmSchema = z.object({
|
|
@@ -8744,6 +8875,8 @@ var UserAuthService = class {
|
|
|
8744
8875
|
passwordMinLength;
|
|
8745
8876
|
accessTtlSeconds;
|
|
8746
8877
|
refreshTtlSeconds;
|
|
8878
|
+
mfa;
|
|
8879
|
+
mfaChallengeTtlSeconds;
|
|
8747
8880
|
/**
|
|
8748
8881
|
* @param options - Store, password/JWT helpers and token policy.
|
|
8749
8882
|
*/
|
|
@@ -8754,6 +8887,8 @@ var UserAuthService = class {
|
|
|
8754
8887
|
this.passwordMinLength = options.passwordMinLength ?? 12;
|
|
8755
8888
|
this.accessTtlSeconds = options.accessTtlSeconds ?? 3600;
|
|
8756
8889
|
this.refreshTtlSeconds = options.refreshTtlSeconds ?? 60 * 60 * 24 * 14;
|
|
8890
|
+
this.mfa = options.mfa;
|
|
8891
|
+
this.mfaChallengeTtlSeconds = options.mfaChallengeTtlSeconds ?? 300;
|
|
8757
8892
|
}
|
|
8758
8893
|
/** Mint a signed access + refresh token pair for `user`. */
|
|
8759
8894
|
async issueTokens(user) {
|
|
@@ -8803,7 +8938,7 @@ var UserAuthService = class {
|
|
|
8803
8938
|
* Authenticate a user by email + password.
|
|
8804
8939
|
*
|
|
8805
8940
|
* @param data - Validated login payload.
|
|
8806
|
-
* @returns
|
|
8941
|
+
* @returns Full auth, or an {@link MfaChallenge} when MFA is enabled.
|
|
8807
8942
|
* @throws {UnauthorizedException} On bad credentials or inactive account.
|
|
8808
8943
|
*/
|
|
8809
8944
|
async login(data) {
|
|
@@ -8815,6 +8950,37 @@ var UserAuthService = class {
|
|
|
8815
8950
|
if (!user.isActive) {
|
|
8816
8951
|
throw new UnauthorizedException({ message: "Account is inactive" });
|
|
8817
8952
|
}
|
|
8953
|
+
if (this.mfa && await this.mfa.isEnabled(user.id)) {
|
|
8954
|
+
const mfaToken = await this.jwt.encode(
|
|
8955
|
+
{ sub: user.id, type: "mfa" },
|
|
8956
|
+
{ ttlSeconds: this.mfaChallengeTtlSeconds }
|
|
8957
|
+
);
|
|
8958
|
+
return { mfaRequired: true, mfaToken };
|
|
8959
|
+
}
|
|
8960
|
+
return { user: toPublic(user), tokens: await this.issueTokens(user) };
|
|
8961
|
+
}
|
|
8962
|
+
/**
|
|
8963
|
+
* Complete an MFA login challenge: verify the code and issue tokens.
|
|
8964
|
+
*
|
|
8965
|
+
* @param mfaToken - The challenge token from {@link login}.
|
|
8966
|
+
* @param code - The authenticator code.
|
|
8967
|
+
* @returns The public user and a fresh token pair.
|
|
8968
|
+
* @throws {UnauthorizedException} When the challenge/code is invalid, MFA is
|
|
8969
|
+
* not configured, or the account no longer exists / is inactive.
|
|
8970
|
+
*/
|
|
8971
|
+
async verifyMfaChallenge(mfaToken, code) {
|
|
8972
|
+
if (!this.mfa) throw new UnauthorizedException({ message: "MFA not configured" });
|
|
8973
|
+
const claims = await this.jwt.decodeOrNull(mfaToken);
|
|
8974
|
+
if (!claims || claims.type !== "mfa" || typeof claims.sub !== "string") {
|
|
8975
|
+
throw new UnauthorizedException({ message: "Invalid MFA challenge" });
|
|
8976
|
+
}
|
|
8977
|
+
if (!await this.mfa.verify(claims.sub, code)) {
|
|
8978
|
+
throw new UnauthorizedException({ message: "Invalid MFA code" });
|
|
8979
|
+
}
|
|
8980
|
+
const user = await this.store.findById(claims.sub);
|
|
8981
|
+
if (!user || !user.isActive) {
|
|
8982
|
+
throw new UnauthorizedException({ message: "Account is inactive" });
|
|
8983
|
+
}
|
|
8818
8984
|
return { user: toPublic(user), tokens: await this.issueTokens(user) };
|
|
8819
8985
|
}
|
|
8820
8986
|
/**
|
|
@@ -8888,6 +9054,15 @@ var MfaService = class {
|
|
|
8888
9054
|
const secret = await this.store.getSecret(userId);
|
|
8889
9055
|
return secret ? this.totp.verify(secret, code) : false;
|
|
8890
9056
|
}
|
|
9057
|
+
/**
|
|
9058
|
+
* Whether MFA is enabled for a user (used to gate the login challenge).
|
|
9059
|
+
*
|
|
9060
|
+
* @param userId - The user.
|
|
9061
|
+
* @returns `true` when MFA is enabled.
|
|
9062
|
+
*/
|
|
9063
|
+
async isEnabled(userId) {
|
|
9064
|
+
return this.store.isEnabled(userId);
|
|
9065
|
+
}
|
|
8891
9066
|
/**
|
|
8892
9067
|
* Disable MFA after verifying a code.
|
|
8893
9068
|
*
|
|
@@ -9135,6 +9310,10 @@ function makeAuthRouter(options) {
|
|
|
9135
9310
|
}
|
|
9136
9311
|
if (options.mfa) {
|
|
9137
9312
|
const mfa = options.mfa;
|
|
9313
|
+
router.post(`${prefix}/mfa/challenge`, async (req, res) => {
|
|
9314
|
+
const { mfaToken, code } = mfaChallengeSchema.parse(req.body);
|
|
9315
|
+
res.json(await service.verifyMfaChallenge(mfaToken, code));
|
|
9316
|
+
});
|
|
9138
9317
|
const requireUser = (req) => {
|
|
9139
9318
|
const claims = getAuth(req);
|
|
9140
9319
|
if (!claims || typeof claims.sub !== "string") {
|
|
@@ -9436,6 +9615,6 @@ function runServer(app, options = {}) {
|
|
|
9436
9615
|
});
|
|
9437
9616
|
}
|
|
9438
9617
|
|
|
9439
|
-
export { ActivationService, AdminSite, AppException, AttemptThrottle, BaseController, BaseModel, BaseService, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, CircuitOpenError, CompositeFeatureFlagBackend, ConflictException, DEFAULT_LOCALE, EmailUtils, EnvFeatureFlagBackend, EventStream, ExpiredTokenException, FeatureFlags, ForbiddenException, HTTPClient, HTTP_500_MARKER, InvalidTokenException, JSONLogger, JWTUtils, LocalUploadStorage, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, MetricsUtils, MfaService, NotFoundException, PHONE_BR_PATTERN, PasswordResetService, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, RedisCacheManager, RedisSSEBroker, RedisSessionStore, Region, RetryPolicy, SSEBroker, ServerSentEvent, SessionService, TOTPHelper, TaskManager, TelegramProvider, TooManyRequestsException, TwilioSmsProvider, UF, UnauthorizedException, UserAuthService, ValidationException, WebPushDispatcher, WebPushError, WebPushGoneError, WebSocketHub, WhatsAppProvider, activationSchema, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached3 as cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeMetricsRouter, makeSessionMiddleware, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, mfaCodeSchema, mfaEnrollResponseSchema, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, passwordResetConfirmSchema, passwordResetRequestSchema, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
|
|
9618
|
+
export { ActivationService, AdminSite, AppException, AttemptThrottle, BaseController, BaseModel, BaseService, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, CircuitOpenError, CompositeFeatureFlagBackend, ConflictException, DEFAULT_LOCALE, EmailProvider, EmailUtils, EnvFeatureFlagBackend, EventStream, ExpiredTokenException, FeatureFlags, ForbiddenException, HTTPClient, HTTP_500_MARKER, InvalidTokenException, JSONLogger, JWTUtils, LocalUploadStorage, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, MessagingHub, MetricsUtils, MfaService, NotFoundException, PHONE_BR_PATTERN, PasswordResetService, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, RedisCacheManager, RedisSSEBroker, RedisSessionStore, Region, RetryPolicy, SSEBroker, ServerSentEvent, SessionService, TOTPHelper, TaskManager, TelegramProvider, TooManyRequestsException, TwilioSmsProvider, UF, UnauthorizedException, UserAuthService, ValidationException, WebPushDispatcher, WebPushError, WebPushGoneError, WebSocketHub, WhatsAppProvider, activationSchema, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, broadcastText, buildContentDisposition, cached3 as cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeMetricsRouter, makeSessionMiddleware, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, mfaChallengeSchema, mfaCodeSchema, mfaEnrollResponseSchema, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, passwordResetConfirmSchema, passwordResetRequestSchema, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
|
|
9440
9619
|
//# sourceMappingURL=index.js.map
|
|
9441
9620
|
//# sourceMappingURL=index.js.map
|