@guren/server 1.0.0-rc.24 → 1.0.0-rc.26

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.
@@ -0,0 +1,327 @@
1
+ import { A as Authenticatable, U as UserProvider } from './api-token-BSSCLlFW.js';
2
+
3
+ /**
4
+ * Hash a token using SHA-256 or SHA-512.
5
+ */
6
+ declare function hashToken(token: string, algorithm?: 'sha256' | 'sha512'): string;
7
+ /**
8
+ * Generate a secure random token.
9
+ */
10
+ declare function generateToken(length?: number): string;
11
+ /**
12
+ * Generate a random ID (16 bytes = 32 hex chars).
13
+ */
14
+ declare function generateId(): string;
15
+ /**
16
+ * Securely compare two hex strings using timing-safe comparison.
17
+ */
18
+ declare function secureCompare(a: string, b: string): boolean;
19
+ /**
20
+ * Securely compare two arbitrary strings using timing-safe comparison.
21
+ * Unlike secureCompare, this works with any string encoding (UUIDs, tokens, etc.).
22
+ */
23
+ declare function secureStringCompare(a: string, b: string): boolean;
24
+ /**
25
+ * Build a URL with token and optional email parameters.
26
+ */
27
+ declare function buildTokenUrl(baseUrl: string, token: string, email?: string): string;
28
+ /**
29
+ * Parse a URL to extract token and email parameters.
30
+ */
31
+ declare function parseTokenUrl(url: string): {
32
+ token: string | null;
33
+ email: string | null;
34
+ };
35
+
36
+ /**
37
+ * Configuration for password reset tokens.
38
+ */
39
+ interface PasswordResetConfig {
40
+ /** Token expiration time in milliseconds (default: 1 hour) */
41
+ expiresIn?: number;
42
+ /** Token byte length before encoding (default: 32) */
43
+ tokenLength?: number;
44
+ }
45
+ /**
46
+ * Storage interface for password reset tokens.
47
+ */
48
+ interface PasswordResetTokenStore {
49
+ /** Store a token ID with associated email and expiration */
50
+ store(tokenId: string, email: string, expiresAt: Date): Promise<void>;
51
+ /** Find email by token ID, returns null if not found or expired */
52
+ find(tokenId: string): Promise<{
53
+ email: string;
54
+ expiresAt: Date;
55
+ } | null>;
56
+ /** Delete a token ID from storage */
57
+ delete(tokenId: string): Promise<void>;
58
+ /** Delete all tokens for an email */
59
+ deleteForEmail(email: string): Promise<void>;
60
+ }
61
+ /**
62
+ * In-memory token store for testing and development.
63
+ */
64
+ declare class MemoryPasswordResetStore implements PasswordResetTokenStore {
65
+ private tokens;
66
+ store(tokenId: string, email: string, expiresAt: Date): Promise<void>;
67
+ find(tokenId: string): Promise<{
68
+ email: string;
69
+ expiresAt: Date;
70
+ } | null>;
71
+ delete(tokenId: string): Promise<void>;
72
+ deleteForEmail(email: string): Promise<void>;
73
+ /** Clear all tokens (useful for testing) */
74
+ clear(): void;
75
+ }
76
+ /**
77
+ * Result of creating a password reset token.
78
+ */
79
+ interface PasswordResetTokenResult {
80
+ /** The plain-text token to send to the user (via email) */
81
+ token: string;
82
+ /** The token ID stored in the backing store */
83
+ tokenId: string;
84
+ /** When the token expires */
85
+ expiresAt: Date;
86
+ }
87
+ /**
88
+ * Create a password reset token for a user.
89
+ *
90
+ * @param email - The user's email address
91
+ * @param store - The token storage implementation
92
+ * @param config - Optional configuration
93
+ * @returns The token result containing plain token and hash
94
+ */
95
+ declare function createPasswordResetToken(email: string, store: PasswordResetTokenStore, config?: PasswordResetConfig): Promise<PasswordResetTokenResult>;
96
+ /**
97
+ * Verify a password reset token.
98
+ *
99
+ * @param token - The plain-text token from the reset URL
100
+ * @param store - The token storage implementation
101
+ * @param config - Optional configuration (must match createPasswordResetToken config)
102
+ * @returns The email if token is valid, null otherwise
103
+ */
104
+ declare function verifyPasswordResetToken(token: string, store: PasswordResetTokenStore, _config?: PasswordResetConfig): Promise<string | null>;
105
+ /**
106
+ * Complete a password reset by updating the user's password and invalidating the token.
107
+ *
108
+ * @param token - The plain-text token from the reset URL
109
+ * @param newPassword - The new password (should be validated by caller)
110
+ * @param store - The token storage implementation
111
+ * @param provider - The user provider to look up and update the user
112
+ * @param updatePassword - Function to update the user's password
113
+ * @param config - Optional configuration
114
+ * @returns The user if reset was successful, null if token is invalid
115
+ */
116
+ declare function completePasswordReset<T extends Authenticatable>(token: string, newPassword: string, store: PasswordResetTokenStore, provider: UserProvider<T>, updatePassword: (user: T, password: string) => Promise<void>, _config?: PasswordResetConfig): Promise<T | null>;
117
+ /**
118
+ * Build a password reset URL from a base URL and token.
119
+ */
120
+ declare const buildPasswordResetUrl: typeof buildTokenUrl;
121
+ /**
122
+ * Parse a password reset URL to extract the token and optional email.
123
+ */
124
+ declare const parsePasswordResetUrl: typeof parseTokenUrl;
125
+
126
+ /**
127
+ * Email verification token data stored in the backing store.
128
+ * Only the hashed token is stored for security.
129
+ */
130
+ interface EmailVerificationToken {
131
+ email: string;
132
+ tokenId: string;
133
+ expiresAt: Date;
134
+ createdAt: Date;
135
+ }
136
+ /**
137
+ * Store interface for email verification tokens.
138
+ * Implement this to use database-backed storage.
139
+ */
140
+ interface EmailVerificationTokenStore {
141
+ /**
142
+ * Store a new verification token.
143
+ */
144
+ store(token: EmailVerificationToken): Promise<void>;
145
+ /**
146
+ * Find a token by its opaque token ID.
147
+ */
148
+ findByTokenId(tokenId: string): Promise<EmailVerificationToken | null>;
149
+ /**
150
+ * Delete a token by its opaque token ID.
151
+ */
152
+ delete(tokenId: string): Promise<void>;
153
+ /**
154
+ * Delete all tokens for a given email.
155
+ */
156
+ deleteForEmail(email: string): Promise<void>;
157
+ }
158
+ /**
159
+ * In-memory store for testing purposes.
160
+ * Do NOT use in production - tokens will be lost on restart.
161
+ */
162
+ declare class MemoryEmailVerificationStore implements EmailVerificationTokenStore {
163
+ private tokens;
164
+ store(token: EmailVerificationToken): Promise<void>;
165
+ findByTokenId(tokenId: string): Promise<EmailVerificationToken | null>;
166
+ delete(tokenId: string): Promise<void>;
167
+ deleteForEmail(email: string): Promise<void>;
168
+ /**
169
+ * Clear all tokens (useful for testing).
170
+ */
171
+ clear(): void;
172
+ /**
173
+ * Get the count of stored tokens (useful for testing).
174
+ */
175
+ get size(): number;
176
+ }
177
+ /**
178
+ * Configuration options for email verification.
179
+ */
180
+ interface EmailVerificationConfig {
181
+ /**
182
+ * Token expiration time in milliseconds.
183
+ * @default 86400000 (24 hours)
184
+ */
185
+ expiresIn?: number;
186
+ /**
187
+ * Token byte length (before hex encoding).
188
+ * @default 32
189
+ */
190
+ tokenLength?: number;
191
+ }
192
+ /**
193
+ * Result of creating an email verification token.
194
+ */
195
+ interface EmailVerificationTokenResult {
196
+ /**
197
+ * The raw token to send to the user via email.
198
+ * This is NOT stored - only the hash is stored.
199
+ */
200
+ token: string;
201
+ /**
202
+ * When the token expires.
203
+ */
204
+ expiresAt: Date;
205
+ }
206
+ /**
207
+ * Create a new email verification token.
208
+ *
209
+ * @param email - The email address to verify
210
+ * @param store - Token store implementation
211
+ * @param config - Optional configuration
212
+ * @returns The raw token to send via email
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * const { token, expiresAt } = await createEmailVerificationToken(
217
+ * user.email,
218
+ * verificationStore
219
+ * )
220
+ *
221
+ * // Send email with verification link
222
+ * await sendEmail({
223
+ * to: user.email,
224
+ * subject: 'Verify your email',
225
+ * html: `<a href="${buildVerificationUrl(baseUrl, token)}">Verify Email</a>`,
226
+ * })
227
+ * ```
228
+ */
229
+ declare function createEmailVerificationToken(email: string, store: EmailVerificationTokenStore, config?: EmailVerificationConfig): Promise<EmailVerificationTokenResult>;
230
+ /**
231
+ * Verify an email verification token.
232
+ *
233
+ * @param token - The raw token from the verification link
234
+ * @param store - Token store implementation
235
+ * @param config - Optional configuration (not currently used, reserved for future)
236
+ * @returns The email address if valid, null if invalid or expired
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * const email = await verifyEmailToken(token, verificationStore)
241
+ *
242
+ * if (!email) {
243
+ * return ctx.json({ error: 'Invalid or expired token' }, 400)
244
+ * }
245
+ *
246
+ * // Mark user as verified
247
+ * await User.update({ email }, { emailVerifiedAt: new Date() })
248
+ * ```
249
+ */
250
+ declare function verifyEmailToken(token: string, store: EmailVerificationTokenStore, _config?: EmailVerificationConfig): Promise<string | null>;
251
+ /**
252
+ * Complete email verification by consuming the token.
253
+ *
254
+ * @param token - The raw token from the verification link
255
+ * @param store - Token store implementation
256
+ * @param markVerified - Function to mark the user as verified
257
+ * @returns The result of markVerified if successful, null if token invalid
258
+ *
259
+ * @example
260
+ * ```ts
261
+ * const result = await completeEmailVerification(
262
+ * token,
263
+ * verificationStore,
264
+ * async (email) => {
265
+ * await User.update({ email }, { emailVerifiedAt: new Date() })
266
+ * return User.findByEmail(email)
267
+ * }
268
+ * )
269
+ *
270
+ * if (!result) {
271
+ * return ctx.json({ error: 'Invalid or expired token' }, 400)
272
+ * }
273
+ *
274
+ * return ctx.redirect('/dashboard')
275
+ * ```
276
+ */
277
+ declare function completeEmailVerification<T>(token: string, store: EmailVerificationTokenStore, markVerified: (email: string) => Promise<T>): Promise<T | null>;
278
+ /**
279
+ * Build a verification URL.
280
+ */
281
+ declare const buildVerificationUrl: typeof buildTokenUrl;
282
+ /**
283
+ * Parse a verification URL to extract token and email.
284
+ */
285
+ declare const parseVerificationUrl: typeof parseTokenUrl;
286
+ /**
287
+ * Check if a user's email is verified.
288
+ * Helper function for use with User models.
289
+ *
290
+ * @param user - User object with emailVerifiedAt field
291
+ * @returns true if verified, false otherwise
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * if (!isEmailVerified(user)) {
296
+ * return ctx.redirect('/verify-email')
297
+ * }
298
+ * ```
299
+ */
300
+ declare function isEmailVerified(user: {
301
+ emailVerifiedAt?: Date | null;
302
+ } | null): boolean;
303
+ /**
304
+ * Middleware factory to require verified email.
305
+ *
306
+ * @param options - Configuration options
307
+ * @returns Middleware function
308
+ *
309
+ * @example
310
+ * ```ts
311
+ * router.get('/dashboard', [DashboardController, 'index'],
312
+ * requireAuthenticated(),
313
+ * requireVerifiedEmail({ redirectTo: '/verify-email' })
314
+ * )
315
+ * ```
316
+ */
317
+ declare function requireVerifiedEmail(options?: {
318
+ redirectTo?: string;
319
+ getUser?: (ctx: unknown) => Promise<{
320
+ emailVerifiedAt?: Date | null;
321
+ } | null>;
322
+ }): (ctx: {
323
+ get: (key: string) => unknown;
324
+ redirect: (url: string) => Response;
325
+ }, next: () => Promise<void>) => Promise<Response | undefined>;
326
+
327
+ export { type EmailVerificationTokenStore as E, MemoryEmailVerificationStore as M, type PasswordResetTokenStore as P, type EmailVerificationToken as a, type EmailVerificationConfig as b, type EmailVerificationTokenResult as c, MemoryPasswordResetStore as d, type PasswordResetConfig as e, type PasswordResetTokenResult as f, buildPasswordResetUrl as g, buildVerificationUrl as h, completeEmailVerification as i, completePasswordReset as j, createEmailVerificationToken as k, createPasswordResetToken as l, isEmailVerified as m, parseVerificationUrl as n, verifyPasswordResetToken as o, parsePasswordResetUrl as p, buildTokenUrl as q, requireVerifiedEmail as r, generateId as s, generateToken as t, hashToken as u, verifyEmailToken as v, parseTokenUrl as w, secureCompare as x, secureStringCompare as y };
package/dist/index.d.ts CHANGED
@@ -1,16 +1,19 @@
1
- import { E as ErrorResponse, S as ServiceProvider, C as Container, c as ServiceBindings, Q as QueueManager, N as NotificationManager } from './Application-D4_90raL.js';
2
- export { A as Application, d as ApplicationListenOptions, e as AuthPayload, f as CSRF_FORM_FIELD, g as CSRF_HEADER_NAME, h as CSRF_TOKEN_KEY, P as ContainerProvider, i as ContextualBinding, j as ContextualBindingBuilder, k as ContextualNeedsBuilder, m as Controller, n as ControllerInertiaProps, o as CsrfOptions, p as DatabaseChannelOptions, q as DatabaseNotification, r as ExceptionClass, t as ExceptionHandler, u as ExceptionHandlerOptions, v as ExceptionRenderer, w as ExceptionReporter, F as FailedJob, H as HostAuthorizationOptions, x as HstsOptions, I as InertiaOptions, y as InertiaPagePayload, z as InertiaResponse, B as InertiaSharedProps, J as InertiaSsrContext, K as InertiaSsrOptions, L as InertiaSsrRenderer, M as InertiaSsrResult, O as InferInertiaProps, R as Job, T as JobClass, U as JobFailureHandler, V as JobHandler, W as JobOptions, X as Notifiable, Y as Notification, Z as NotificationAttachment, _ as NotificationChannel, $ as NotificationChannelFactory, a0 as NotificationClass, a1 as NotificationMailMessage, a2 as NotificationManagerOptions, a3 as ProviderManager, a4 as QueueConfig, a5 as QueueDriver, a6 as QueueDriverFactory, a7 as QueuedJob, a8 as RendererRegistration, a9 as ResolvedSharedInertiaProps, aa as ResourceRouteOptions, ab as RouteBuilder, ac as RouteContractOptions, ad as RouteDefinition, ae as RouteOpenApiMetadata, af as RouteResourceAction, ag as Router, ah as SecurityHeadersOptions, ai as SentNotification, aj as ServiceBinding, ak as ServiceClass, al as ServiceFactory, am as ServiceProviderClass, an as ServiceProviderConstructor, ao as ServiceProviderOptions, ap as SharedInertiaPropsResolver, aq as SlackAttachment, ar as SlackBlock, as as SlackMessage, at as VALIDATED_DATA_KEY, au as ValidateRequestOptions, av as ValidationSchema, aw as WorkerOptions, ax as abort, ay as abortIf, az as abortUnless, aA as clearJobRegistry, aB as createApp, aC as createContainer, aD as createCsrfMiddleware, aE as createExceptionHandler, aF as createHostAuthorizationMiddleware, aG as createNotificationManager, aH as createQueueManager, aI as createSecurityHeaders, aJ as csrfField, aK as formatValidationErrors, aL as getContainer, aM as getCsrfToken, aN as getExceptionHandler, aO as getInertiaSharedPropsResolver, aP as getJob, aQ as getNotificationManager, aR as getQueueDriver, aS as getRegisteredJobs, aT as getValidatedData, aU as inertia, aV as parseRequestPayload, aW as registerJob, aX as resolve, aY as setContainer, aZ as setExceptionHandler, a_ as setInertiaSharedProps, a$ as setNotificationManager, b0 as setQueueDriver, b1 as shareInertiaProps, b2 as validate, b3 as validateRequest, b4 as validateRequestWith, b5 as validateSafe, b6 as verifyCsrfToken } from './Application-D4_90raL.js';
1
+ import { E as ErrorResponse, S as ServiceProvider, C as Container, c as ServiceBindings, Q as QueueManager, N as NotificationManager } from './Application-BnsyCKXY.js';
2
+ export { A as Application, d as ApplicationListenOptions, e as ApplicationOptions, f as AuthPayload, g as AuthPluginOptions, h as CSRF_FORM_FIELD, i as CSRF_HEADER_NAME, j as CSRF_TOKEN_KEY, P as ContainerProvider, k as ContextualBinding, m as ContextualBindingBuilder, n as ContextualNeedsBuilder, o as Controller, p as ControllerInertiaProps, q as CsrfOptions, r as DatabaseChannelOptions, t as DatabaseNotification, u as ExceptionClass, v as ExceptionHandler, w as ExceptionHandlerOptions, x as ExceptionRenderer, y as ExceptionReporter, F as FailedJob, H as HostAuthorizationOptions, z as HstsOptions, I as InertiaOptions, B as InertiaPagePayload, J as InertiaResponse, K as InertiaSharedProps, L as InertiaSsrContext, M as InertiaSsrOptions, O as InertiaSsrRenderer, R as InertiaSsrResult, T as InferInertiaProps, U as Job, V as JobClass, W as JobFailureHandler, X as JobHandler, Y as JobOptions, Z as Notifiable, _ as Notification, $ as NotificationAttachment, a0 as NotificationChannel, a1 as NotificationChannelFactory, a2 as NotificationClass, a3 as NotificationMailMessage, a4 as NotificationManagerOptions, a5 as ProviderManager, a6 as QueueConfig, a7 as QueueDriver, a8 as QueueDriverFactory, a9 as QueuedJob, aa as RendererRegistration, ab as ResolvedSharedInertiaProps, ac as ResourceRouteOptions, ad as RouteBuilder, ae as RouteContractOptions, af as RouteDefinition, ag as RouteOpenApiMetadata, ah as RouteResourceAction, ai as Router, aj as SecurityHeadersOptions, ak as SentNotification, al as ServiceBinding, am as ServiceClass, an as ServiceFactory, ao as ServiceProviderClass, ap as ServiceProviderConstructor, aq as ServiceProviderOptions, ar as SharedInertiaPropsResolver, as as SlackAttachment, at as SlackBlock, au as SlackMessage, av as VALIDATED_DATA_KEY, aw as ValidateRequestOptions, ax as ValidationSchema, ay as WorkerOptions, az as abort, aA as abortIf, aB as abortUnless, aC as clearJobRegistry, aD as createApp, aE as createContainer, aF as createCsrfMiddleware, aG as createExceptionHandler, aH as createHostAuthorizationMiddleware, aI as createNotificationManager, aJ as createQueueManager, aK as createSecurityHeaders, aL as csrfField, aM as formatValidationErrors, aN as getContainer, aO as getCsrfToken, aP as getExceptionHandler, aQ as getInertiaSharedPropsResolver, aR as getJob, aS as getNotificationManager, aT as getQueueDriver, aU as getRegisteredJobs, aV as getValidatedData, aW as inertia, aX as parseRequestPayload, aY as registerJob, aZ as resolve, a_ as setContainer, a$ as setExceptionHandler, b0 as setInertiaSharedProps, b1 as setNotificationManager, b2 as setQueueDriver, b3 as shareInertiaProps, b4 as validate, b5 as validateRequest, b6 as validateRequestWith, b7 as validateSafe, b8 as verifyCsrfToken } from './Application-BnsyCKXY.js';
3
3
  import * as hono from 'hono';
4
4
  import { Context, MiddlewareHandler } from 'hono';
5
5
  export { Context } from 'hono';
6
- import { a as AuthContext } from './api-token-BGOsfuI9.js';
7
- export { c as API_TOKEN_KEY, b as ApiToken, d as ApiTokenStore, e as AuthCredentials, A as AuthManager, f as AuthManagerOptions, g as Authenticatable, B as BaseUserProvider, h as BearerTokenMiddlewareOptions, i as CreateApiTokenOptions, j as CreateApiTokenResult, G as Guard, k as GuardContext, l as GuardFactory, M as MemoryApiTokenStore, m as MemoryOAuthStateStore, n as MemorySessionStore, o as ModelUserProvider, p as OAuthAuthorizeOptions, q as OAuthCallbackPayload, O as OAuthManager, r as OAuthManagerOptions, s as OAuthProviderConfig, t as OAuthProviderFactoryInput, u as OAuthStateConfig, v as OAuthStatePayload, w as OAuthStateStore, x as OAuthTokenResult, y as OAuthUserProfile, P as ProviderFactory, S as Session, z as SessionData, D as SessionStore, U as UserProvider, E as buildOAuthAuthorizeUrl, F as buildOAuthRedirectUrl, H as createApiToken, I as createBearerTokenMiddleware, J as createDiscordOAuthProviderConfig, K as createGitHubOAuthProviderConfig, L as createGoogleOAuthProviderConfig, N as createOAuthManager, Q as createOAuthState, R as createSessionMiddleware, T as exchangeOAuthCode, V as fetchOAuthUserProfile, W as getApiToken, X as getApiTokenOrFail, Y as getSessionFromContext, Z as getUserApiTokens, _ as parseApiToken, $ as parseOAuthRedirectUrl, a0 as revokeAllApiTokens, a1 as revokeApiToken, a2 as tokenCan, a3 as tokenCanAll, a4 as tokenCanAny, a5 as verifyApiToken, a6 as verifyOAuthState } from './api-token-BGOsfuI9.js';
8
- export { AuthenticatableModel, EmailVerificationConfig, EmailVerificationToken, EmailVerificationTokenResult, EmailVerificationTokenStore, ScryptHasher as Hash, MemoryEmailVerificationStore, MemoryPasswordResetStore, NodeHasher, PasswordResetConfig, PasswordResetTokenResult, PasswordResetTokenStore, ScryptHasher, SessionGuard, buildPasswordResetUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createEmailVerificationToken, createPasswordResetToken, isEmailVerified, parsePasswordResetUrl, parseVerificationUrl, requireVerifiedEmail, verifyEmailToken, verifyPasswordResetToken } from './auth/index.js';
6
+ import { P as PasswordHasher } from './AuthManager-SfhCNkAU.js';
7
+ export { A as AuthManager, B as BaseUserProvider, M as ModelUserProvider } from './AuthManager-SfhCNkAU.js';
8
+ export { AuthenticatableModel, NodeHasher, ScryptHasher, SessionGuard } from './auth/index.js';
9
+ export { b as EmailVerificationConfig, a as EmailVerificationToken, c as EmailVerificationTokenResult, E as EmailVerificationTokenStore, M as MemoryEmailVerificationStore, d as MemoryPasswordResetStore, e as PasswordResetConfig, f as PasswordResetTokenResult, P as PasswordResetTokenStore, g as buildPasswordResetUrl, h as buildVerificationUrl, i as completeEmailVerification, j as completePasswordReset, k as createEmailVerificationToken, l as createPasswordResetToken, m as isEmailVerified, p as parsePasswordResetUrl, n as parseVerificationUrl, r as requireVerifiedEmail, v as verifyEmailToken, o as verifyPasswordResetToken } from './email-verification-CAeArjui.js';
10
+ import { g as AuthContext } from './api-token-BSSCLlFW.js';
11
+ export { m as API_TOKEN_KEY, j as ApiToken, i as ApiTokenStore, a as AuthCredentials, c as AuthManagerOptions, A as Authenticatable, B as BearerTokenMiddlewareOptions, n as CreateApiTokenOptions, o as CreateApiTokenResult, e as Guard, d as GuardContext, G as GuardFactory, M as MemoryApiTokenStore, p as MemoryOAuthStateStore, q as MemorySessionStore, r as OAuthAuthorizeOptions, s as OAuthCallbackPayload, l as OAuthManager, t as OAuthManagerOptions, u as OAuthProviderConfig, v as OAuthProviderFactoryInput, w as OAuthStateConfig, k as OAuthStatePayload, O as OAuthStateStore, x as OAuthTokenResult, y as OAuthUserProfile, P as ProviderFactory, z as Session, h as SessionData, S as SessionStore, U as UserProvider, D as buildOAuthAuthorizeUrl, E as buildOAuthRedirectUrl, F as createApiToken, H as createBearerTokenMiddleware, I as createDiscordOAuthProviderConfig, J as createGitHubOAuthProviderConfig, K as createGoogleOAuthProviderConfig, L as createOAuthManager, N as createOAuthState, Q as createSessionMiddleware, R as exchangeOAuthCode, T as fetchOAuthUserProfile, V as getApiToken, W as getApiTokenOrFail, X as getSessionFromContext, Y as getUserApiTokens, Z as parseApiToken, _ as parseOAuthRedirectUrl, $ as revokeAllApiTokens, a0 as revokeApiToken, a1 as tokenCan, a2 as tokenCanAll, a3 as tokenCanAny, a4 as verifyApiToken, a5 as verifyOAuthState } from './api-token-BSSCLlFW.js';
9
12
  export { M as Middleware, d as defineMiddleware, j as jsonResponse } from './index-9_Jzj5jo.js';
10
13
  import { E as EventManager } from './EventManager-CmIoLt7r.js';
11
14
  export { a as Event, b as EventClass, c as EventListener, d as EventSubscription, L as ListenerOptions, R as RegisteredListener, e as createEventManager } from './EventManager-CmIoLt7r.js';
12
15
  export { ApplicationShutdown, ApplicationStarted, JobFailed, JobProcessed, Listener, ListenerClass, RequestFinished, RequestReceived, UserAuthenticated, UserLoggedOut } from './events/index.js';
13
- export { FailedJobHandler, FailedJobInfo, FailedJobReporter, MemoryDriver, RedisDriver, RedisDriverOptions, SqsDriver, SyncDriver, Worker, WorkerEvents, createSqsAdapter, processJob } from './queue/index.js';
16
+ export { FailedJobHandler, FailedJobInfo, FailedJobReporter, MemoryDriver, MemoryDriver as MemoryQueueDriver, RedisDriver, RedisDriverOptions, RedisDriver as RedisQueueDriver, SqsDriver, SyncDriver, SyncDriver as SyncQueueDriver, Worker, WorkerEvents, createSqsAdapter, processJob } from './queue/index.js';
14
17
  import { M as MailManager } from './MailManager-DpMvYiP9.js';
15
18
  export { a as MailAddress, b as MailAttachment, c as MailConfig, d as MailMessage, e as MailTransport, f as MailTransportConfig, g as MailTransportFactory, h as MemoryTransportOptions, R as ResendTransportOptions, S as SendResult, i as SmtpTransportOptions, j as createMailManager } from './MailManager-DpMvYiP9.js';
16
19
  export { LogTransport, Mail, MemoryTransport, ResendTransport, SmtpTransport, getMailManager, mail, setMailManager } from './mail/index.js';
@@ -35,16 +38,17 @@ export { DatabaseChannel, MailChannel, MailChannelOptions, MemoryChannel, SlackC
35
38
  import { B as BroadcastManager } from './BroadcastManager-CGWl9rUO.js';
36
39
  export { A as AuthMiddlewareOptions, a as BroadcastDriver, b as BroadcastDriverFactory, c as BroadcastEvent, d as BroadcastManagerOptions, e as BroadcastableEvent, C as Channel, f as ChannelAuthorizer, g as ChannelRegistration, P as PresenceBroadcastDriver, h as PresenceChannel, i as PresenceChannelAuthorizer, j as PresenceMember, k as PrivateChannel, S as SSEClient, l as SSEMiddlewareOptions, W as WebSocketClient, m as createBroadcastManager, n as getBroadcastManager, s as setBroadcastManager } from './BroadcastManager-CGWl9rUO.js';
37
40
  export { RedisClient as BroadcastRedisClient, RedisDriverOptions as BroadcastRedisDriverOptions, MemoryDriver as MemoryBroadcastDriver, RedisDriver as RedisBroadcastDriver, createTypedBroadcaster } from './broadcasting/index.js';
38
- import { I as InputInterface, P as ParsedSignature, O as OptionDefinition, a as CommandInstance, b as OutputInterface } from './ConsoleKernel-BPYcP-2f.js';
39
- export { A as ArgumentDefinition, c as CommandClass, C as ConsoleKernel, d as ConsoleKernelOptions, e as ProgressInterface, f as PromptInterface, S as ScheduledCommand, g as createConsoleKernel } from './ConsoleKernel-BPYcP-2f.js';
41
+ import { I as InputInterface, P as ParsedSignature, O as OptionDefinition, a as CommandInstance, b as OutputInterface } from './ConsoleKernel-BDtBETjm.js';
42
+ export { A as ArgumentDefinition, c as CommandClass, C as ConsoleKernel, d as ConsoleKernelOptions, e as ProgressInterface, f as PromptInterface, S as ScheduledCommand, g as createConsoleKernel } from './ConsoleKernel-BDtBETjm.js';
40
43
  import * as readline from 'readline';
41
44
  export { R as AuthResponse, A as AuthUser, a as AuthorizationResponse, b as AuthorizeOptions, G as Gate, c as GateCallback, d as GateDefinition, e as GateOptions, P as PolicyClass, f as PolicyInterface, g as PolicyMethod, h as PolicyRegistration, i as ResourceAction, j as ResponseBuilder, k as authorizeAbility, l as can, m as cannot, n as createGate, o as defineGate, p as getGate, s as setGate } from './Gate-CynjZCtS.js';
42
45
  export { AuthorizedContext, Policy, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, definePolicy, withAuthorization } from './authorization/index.js';
43
46
  export { A as AppKeyring, D as DecryptOptions, a as EncryptOptions, b as EncryptedPayload, E as Encrypter, c as EncrypterConfig, H as HashAlgorithm, d as HmacOptions, P as PasswordHashOptions, R as RandomStringOptions, e as createEncrypter, f as decrypt, g as deriveAppKey, h as deriveAppKeyring, i as encrypt, j as generateAppKey, k as generateKey, l as getAppKeyringFromEnv, m as getEncrypter, n as normalizeAppKey, p as parseAppKey, o as parsePreviousAppKeys, s as setEncrypter } from './app-key-CsBfRC_Q.js';
44
47
  export { MessageSigner, SignMessageOptions, SignedMessageClaims, SignedUrlOptions, VerifySignedMessageOptions, VerifySignedUrlOptions, check as checkHash, generateOtp, generatePassword, generateSlug, hash, hashPassword, hmac, md5, needsRehash, pick, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, sample, secureCompare, sha256, sha512, shuffle, signUrl, urlSafeToken, uuid, verifyHmac, verifyPassword, verifySignedUrl } from './encryption/index.js';
45
- import Redis, { RedisOptions } from 'ioredis';
48
+ export { M as MemoryRateLimitStore, a as RateLimitEntry, d as RateLimitInfo, e as RateLimitOptions, R as RateLimitStore, S as SlidingWindowRateLimitStore, f as createRateLimitMiddleware, c as createRedisClient, g as getRateLimitInfo, r as resetRateLimit } from './client-CKXJLsTe.js';
46
49
  import 'vite';
47
50
  import '@guren/orm';
51
+ import 'ioredis';
48
52
 
49
53
  interface RequireAuthOptions {
50
54
  redirectTo?: string;
@@ -56,199 +60,6 @@ declare function attachAuthContext(contextFactory: (ctx: Context) => AuthContext
56
60
  declare function requireAuthenticated(options?: RequireAuthOptions): MiddlewareHandler;
57
61
  declare function requireGuest(options?: RequireAuthOptions): MiddlewareHandler;
58
62
 
59
- /**
60
- * Rate limit entry stored in the backing store.
61
- */
62
- interface RateLimitEntry {
63
- count: number;
64
- resetAt: number;
65
- }
66
- /**
67
- * Store interface for rate limit data.
68
- * Implement this for Redis or database-backed storage.
69
- */
70
- interface RateLimitStore {
71
- /**
72
- * Get the current rate limit entry for a key.
73
- */
74
- get(key: string): Promise<RateLimitEntry | null>;
75
- /**
76
- * Increment the count for a key and return the new entry.
77
- * If the key doesn't exist, create it with count=1.
78
- */
79
- increment(key: string, windowMs: number): Promise<RateLimitEntry>;
80
- /**
81
- * Reset the count for a key.
82
- */
83
- reset(key: string): Promise<void>;
84
- }
85
- /**
86
- * Base class for in-memory rate limit stores with automatic cleanup.
87
- */
88
- declare abstract class BaseMemoryStore implements RateLimitStore {
89
- protected cleanupInterval?: ReturnType<typeof setInterval>;
90
- constructor(cleanupIntervalMs?: number);
91
- abstract get(key: string): Promise<RateLimitEntry | null>;
92
- abstract increment(key: string, windowMs: number): Promise<RateLimitEntry>;
93
- abstract reset(key: string): Promise<void>;
94
- abstract cleanup(): void;
95
- abstract clear(): void;
96
- abstract get size(): number;
97
- destroy(): void;
98
- }
99
- /**
100
- * In-memory rate limit store.
101
- * Suitable for single-process development, not for production clusters.
102
- */
103
- declare class MemoryRateLimitStore extends BaseMemoryStore {
104
- private entries;
105
- get(key: string): Promise<RateLimitEntry | null>;
106
- increment(key: string, windowMs: number): Promise<RateLimitEntry>;
107
- reset(key: string): Promise<void>;
108
- cleanup(): void;
109
- clear(): void;
110
- get size(): number;
111
- }
112
- /**
113
- * Configuration options for rate limiting.
114
- */
115
- interface RateLimitOptions {
116
- /**
117
- * Maximum number of requests allowed in the time window.
118
- * @default 100
119
- */
120
- limit?: number;
121
- /**
122
- * Time window in milliseconds.
123
- * @default 60000 (1 minute)
124
- */
125
- windowMs?: number;
126
- /**
127
- * Function to extract the rate limit key from the request.
128
- * Defaults to using the client IP address.
129
- */
130
- keyGenerator?: (ctx: Context) => string | Promise<string>;
131
- /**
132
- * Rate limit store implementation.
133
- * Defaults to in-memory store.
134
- */
135
- store?: RateLimitStore;
136
- /**
137
- * Whether to skip rate limiting for certain requests.
138
- */
139
- skip?: (ctx: Context) => boolean | Promise<boolean>;
140
- /**
141
- * Custom handler when rate limit is exceeded.
142
- */
143
- onRateLimited?: (ctx: Context, retryAfter: number) => Response | Promise<Response>;
144
- /**
145
- * Whether to add rate limit headers to all responses.
146
- * @default true
147
- */
148
- headers?: boolean;
149
- /**
150
- * Custom message when rate limit is exceeded.
151
- * @default 'Too many requests, please try again later.'
152
- */
153
- message?: string;
154
- /**
155
- * HTTP status code when rate limit is exceeded.
156
- * @default 429
157
- */
158
- statusCode?: number;
159
- /**
160
- * Prefix for rate limit keys.
161
- * @default 'rl:'
162
- */
163
- keyPrefix?: string;
164
- /**
165
- * Trust reverse-proxy headers for client IP resolution, checked in order:
166
- * `CF-Connecting-IP`, `True-Client-IP`, `X-Real-IP`, then the first entry
167
- * of `X-Forwarded-For`. Falls back to `server.requestIP()` when none are set.
168
- *
169
- * Enable ONLY when every request passes through a proxy that sets or strips
170
- * these headers — on direct deployments clients can spoof them to bypass
171
- * per-client limits. Ignored when a custom `keyGenerator` is supplied.
172
- * @default false
173
- */
174
- trustProxy?: boolean;
175
- }
176
- /**
177
- * Create a rate limiting middleware.
178
- *
179
- * @example
180
- * ```ts
181
- * // Basic usage - 100 requests per minute per IP
182
- * app.use('*', createRateLimitMiddleware())
183
- *
184
- * // Stricter limit for login endpoint
185
- * router.post('/login', [AuthController, 'login'],
186
- * createRateLimitMiddleware({
187
- * limit: 5,
188
- * windowMs: 15 * 60 * 1000, // 15 minutes
189
- * })
190
- * )
191
- *
192
- * // Custom key based on authenticated user
193
- * app.use('/api/*', createRateLimitMiddleware({
194
- * limit: 1000,
195
- * windowMs: 60 * 60 * 1000, // 1 hour
196
- * keyGenerator: async (ctx) => {
197
- * const user = await ctx.get('user')
198
- * return user?.id?.toString() ?? defaultKeyGenerator(ctx)
199
- * },
200
- * }))
201
- * ```
202
- */
203
- declare function createRateLimitMiddleware(options?: RateLimitOptions): MiddlewareHandler;
204
- /**
205
- * Rate limit result information.
206
- */
207
- interface RateLimitInfo {
208
- limit: number;
209
- remaining: number;
210
- resetAt: Date;
211
- isLimited: boolean;
212
- }
213
- /**
214
- * Get rate limit information for a key without incrementing.
215
- *
216
- * @example
217
- * ```ts
218
- * const info = await getRateLimitInfo('user:123', store, { limit: 100 })
219
- * console.log(`${info.remaining} requests remaining`)
220
- * ```
221
- */
222
- declare function getRateLimitInfo(key: string, store: RateLimitStore, options?: {
223
- limit: number;
224
- keyPrefix?: string;
225
- }): Promise<RateLimitInfo>;
226
- /**
227
- * Reset rate limit for a specific key.
228
- *
229
- * @example
230
- * ```ts
231
- * // Reset rate limit after successful captcha
232
- * await resetRateLimit(clientIp, store)
233
- * ```
234
- */
235
- declare function resetRateLimit(key: string, store: RateLimitStore, options?: {
236
- keyPrefix?: string;
237
- }): Promise<void>;
238
- /**
239
- * Sliding window rate limit store.
240
- * More accurate than fixed window but uses more memory.
241
- */
242
- declare class SlidingWindowRateLimitStore extends BaseMemoryStore {
243
- private requests;
244
- get(key: string): Promise<RateLimitEntry | null>;
245
- increment(key: string, windowMs: number): Promise<RateLimitEntry>;
246
- reset(key: string): Promise<void>;
247
- cleanup(): void;
248
- clear(): void;
249
- get size(): number;
250
- }
251
-
252
63
  interface CspDirectives {
253
64
  defaultSrc?: string[];
254
65
  scriptSrc?: string[];
@@ -1023,6 +834,10 @@ interface FileLike {
1023
834
  * // data is typed as StorePostData
1024
835
  * ```
1025
836
  */
837
+ /**
838
+ * @deprecated Legacy compatibility layer — prefer schema-first validation
839
+ * via `this.validateBody()` / `validateQuery()` / `validateParams()`.
840
+ */
1026
841
  declare abstract class FormRequest<T = Record<string, unknown>> {
1027
842
  protected ctx: Context;
1028
843
  /**
@@ -2302,10 +2117,6 @@ declare abstract class Command implements CommandInstance {
2302
2117
  * Call another command.
2303
2118
  */
2304
2119
  call(command: string, args?: string[]): Promise<number>;
2305
- /**
2306
- * Call another command silently.
2307
- */
2308
- callSilent(command: string, args?: string[]): Promise<number>;
2309
2120
  /**
2310
2121
  * Resolve a service from the container.
2311
2122
  */
@@ -2651,38 +2462,16 @@ declare function renderDebugPage(error: Error, request?: Request): string;
2651
2462
  declare function debugErrorMiddleware(): MiddlewareHandler;
2652
2463
 
2653
2464
  /**
2654
- * Options for creating a Redis client.
2465
+ * Runtime-detecting password hasher: uses Bun's native scrypt implementation
2466
+ * when running on Bun, and the Node.js crypto implementation otherwise
2467
+ * (e.g. AWS Lambda on the Node runtime). This is the hasher behind the
2468
+ * `Hash` export, so code written against `Hash` runs on both runtimes.
2655
2469
  */
2656
- interface RedisClientOptions extends RedisOptions {
2657
- /**
2658
- * Redis connection URL (e.g., 'redis://localhost:6379').
2659
- * If provided, overrides host/port/password.
2660
- */
2661
- url?: string;
2662
- /**
2663
- * Key prefix for all operations.
2664
- * @default ''
2665
- */
2666
- keyPrefix?: string;
2470
+ declare class DefaultHasher implements PasswordHasher {
2471
+ private readonly delegate;
2472
+ constructor();
2473
+ hash(plain: string): Promise<string>;
2474
+ verify(hashed: string, plain: string): Promise<boolean>;
2667
2475
  }
2668
- /**
2669
- * Create a Redis client with the given options.
2670
- *
2671
- * @example
2672
- * ```ts
2673
- * // Using URL
2674
- * const redis = createRedisClient({ url: 'redis://localhost:6379' })
2675
- *
2676
- * // Using host/port
2677
- * const redis = createRedisClient({ host: 'localhost', port: 6379 })
2678
- *
2679
- * // With key prefix
2680
- * const redis = createRedisClient({
2681
- * url: process.env.REDIS_URL,
2682
- * keyPrefix: 'myapp:',
2683
- * })
2684
- * ```
2685
- */
2686
- declare function createRedisClient(options?: RedisClientOptions): Redis;
2687
2476
 
2688
- export { AUTH_CONTEXT_KEY, AuthContext, AuthContext as AuthRuntimeContext, AuthServiceProvider, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, type BaseResource, BaseSeeder, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CacheManager, CacheServiceProvider, Command, CommandInstance, Container, type CorsOptions, type CspDirectives, type CspOptions, type CursorPaginatedResponse, type CursorPaginationMeta, CursorPaginator, type CursorPaginatorOptions, type DiscoveryOptions, type DiscoveryResult, EncryptionServiceProvider, ErrorResponse, ErrorServiceProvider, EventManager, EventServiceProvider, BaseFactory as Factory, type FactoryClass, type Factory as FactoryInterface, FieldValidator, type FileLike, type FileValidationOptions, type ForceHttpsOptions, FormRequest, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, type ImageValidationOptions, InertiaServiceProvider, type InferResourceData, Input, InputInterface, JsonResource, LogManager, LogServiceProvider, MailManager, MailServiceProvider, MemoryRateLimitStore, MethodNotAllowedException, NotFoundHttpException, NotificationManager, NotificationServiceProvider, OAuthServiceProvider, OptionDefinition, Output, OutputInterface, type PaginatedPageProps, type PaginatedResponse, type PaginatedResultLike, type PaginationLinks, type PaginationMeta, type PaginationPageLink, Paginator, type PaginatorOptions, ParsedSignature, QueueManager, QueueServiceProvider, type RateLimitEntry, type RateLimitInfo, type RateLimitOptions, type RateLimitStore, type RedirectSafetyOptions, type RequireAuthOptions, Resource, type ResourceClass, ResourceCollection, type ResourceData, type RuleDefinition, Scheduler, SchedulingServiceProvider, BaseSeeder as Seeder, type SeederClass, type Seeder as SeederInterface, SeederRunner, type SeederRunnerOptions, ServiceBindings, ServiceProvider, SlidingWindowRateLimitStore, StorageManager, StorageServiceProvider, type ValidationErrors, ValidationException, type ValidationResult, type ValidationRule, Validator, type ValidatorOptions, ViewEngine, after, afterOrEqual, alpha, alphaDash, alphaNum, array as arrayRule, attachAuthContext, before, beforeOrEqual, between, boolean as booleanRule, collect, confirmed, createCorsMiddleware, createCspMiddleware, createFacade, createFacades, createForceHttpsMiddleware, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createSeederRunner, createValidator, cursorPaginate, custom, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, defineFactory, different, email as emailRule, encodeCursor, endsWith, exists, file as fileRule, getCspNonce, getRateLimitInfo, image as imageRule, inValues, integer, ip, ipv4, ipv6, isSafeRedirectUrl, json as jsonRule, max, maxFileSize, mimes, min, minFileSize, notIn, nullable, numeric, object as objectRule, paginate, parseSignature, quickValidate, quickValidateOrThrow, regex, renderDebugPage, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, same, size, startsWith, string as stringRule, unique, url as urlRule, uuid as uuidRule };
2477
+ export { AUTH_CONTEXT_KEY, AuthContext, AuthContext as AuthRuntimeContext, AuthServiceProvider, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, type BaseResource, BaseSeeder, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CacheManager, CacheServiceProvider, Command, CommandInstance, Container, type CorsOptions, type CspDirectives, type CspOptions, type CursorPaginatedResponse, type CursorPaginationMeta, CursorPaginator, type CursorPaginatorOptions, DefaultHasher, type DiscoveryOptions, type DiscoveryResult, EncryptionServiceProvider, ErrorResponse, ErrorServiceProvider, EventManager, EventServiceProvider, BaseFactory as Factory, type FactoryClass, type Factory as FactoryInterface, FieldValidator, type FileLike, type FileValidationOptions, type ForceHttpsOptions, FormRequest, DefaultHasher as Hash, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, type ImageValidationOptions, InertiaServiceProvider, type InferResourceData, Input, InputInterface, JsonResource, LogManager, LogServiceProvider, MailManager, MailServiceProvider, MethodNotAllowedException, NotFoundHttpException, NotificationManager, NotificationServiceProvider, OAuthServiceProvider, OptionDefinition, Output, OutputInterface, type PaginatedPageProps, type PaginatedResponse, type PaginatedResultLike, type PaginationLinks, type PaginationMeta, type PaginationPageLink, Paginator, type PaginatorOptions, ParsedSignature, QueueManager, QueueServiceProvider, type RedirectSafetyOptions, type RequireAuthOptions, Resource, type ResourceClass, ResourceCollection, type ResourceData, type RuleDefinition, Scheduler, SchedulingServiceProvider, BaseSeeder as Seeder, type SeederClass, type Seeder as SeederInterface, SeederRunner, type SeederRunnerOptions, ServiceBindings, ServiceProvider, StorageManager, StorageServiceProvider, type ValidationErrors, ValidationException, type ValidationResult, type ValidationRule, Validator, type ValidatorOptions, ViewEngine, after, afterOrEqual, alpha, alphaDash, alphaNum, array as arrayRule, attachAuthContext, before, beforeOrEqual, between, boolean as booleanRule, collect, confirmed, createCorsMiddleware, createCspMiddleware, createFacade, createFacades, createForceHttpsMiddleware, createRedirectSafetyMiddleware, createSeederRunner, createValidator, cursorPaginate, custom, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, defineFactory, different, email as emailRule, encodeCursor, endsWith, exists, file as fileRule, getCspNonce, image as imageRule, inValues, integer, ip, ipv4, ipv6, isSafeRedirectUrl, json as jsonRule, max, maxFileSize, mimes, min, minFileSize, notIn, nullable, numeric, object as objectRule, paginate, parseSignature, quickValidate, quickValidateOrThrow, regex, renderDebugPage, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, same, size, startsWith, string as stringRule, unique, url as urlRule, uuid as uuidRule };