@guren/server 1.0.0-rc.25 → 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,14 @@
1
+ // src/redis/client.ts
2
+ import Redis from "ioredis";
3
+ function createRedisClient(options = {}) {
4
+ const { url, ...redisOptions } = options;
5
+ if (url) {
6
+ return new Redis(url, redisOptions);
7
+ }
8
+ return new Redis(redisOptions);
9
+ }
10
+
11
+ export {
12
+ Redis,
13
+ createRedisClient
14
+ };
@@ -0,0 +1,232 @@
1
+ import { Context, MiddlewareHandler } from 'hono';
2
+ import Redis, { RedisOptions } from 'ioredis';
3
+
4
+ /**
5
+ * Rate limit entry stored in the backing store.
6
+ */
7
+ interface RateLimitEntry {
8
+ count: number;
9
+ resetAt: number;
10
+ }
11
+ /**
12
+ * Store interface for rate limit data.
13
+ * Implement this for Redis or database-backed storage.
14
+ */
15
+ interface RateLimitStore {
16
+ /**
17
+ * Get the current rate limit entry for a key.
18
+ */
19
+ get(key: string): Promise<RateLimitEntry | null>;
20
+ /**
21
+ * Increment the count for a key and return the new entry.
22
+ * If the key doesn't exist, create it with count=1.
23
+ */
24
+ increment(key: string, windowMs: number): Promise<RateLimitEntry>;
25
+ /**
26
+ * Reset the count for a key.
27
+ */
28
+ reset(key: string): Promise<void>;
29
+ }
30
+ /**
31
+ * Base class for in-memory rate limit stores with automatic cleanup.
32
+ */
33
+ declare abstract class BaseMemoryStore implements RateLimitStore {
34
+ protected cleanupInterval?: ReturnType<typeof setInterval>;
35
+ constructor(cleanupIntervalMs?: number);
36
+ abstract get(key: string): Promise<RateLimitEntry | null>;
37
+ abstract increment(key: string, windowMs: number): Promise<RateLimitEntry>;
38
+ abstract reset(key: string): Promise<void>;
39
+ abstract cleanup(): void;
40
+ abstract clear(): void;
41
+ abstract get size(): number;
42
+ destroy(): void;
43
+ }
44
+ /**
45
+ * In-memory rate limit store.
46
+ * Suitable for single-process development, not for production clusters.
47
+ */
48
+ declare class MemoryRateLimitStore extends BaseMemoryStore {
49
+ private entries;
50
+ get(key: string): Promise<RateLimitEntry | null>;
51
+ increment(key: string, windowMs: number): Promise<RateLimitEntry>;
52
+ reset(key: string): Promise<void>;
53
+ cleanup(): void;
54
+ clear(): void;
55
+ get size(): number;
56
+ }
57
+ /**
58
+ * Configuration options for rate limiting.
59
+ */
60
+ interface RateLimitOptions {
61
+ /**
62
+ * Maximum number of requests allowed in the time window.
63
+ * @default 100
64
+ */
65
+ limit?: number;
66
+ /**
67
+ * Time window in milliseconds.
68
+ * @default 60000 (1 minute)
69
+ */
70
+ windowMs?: number;
71
+ /**
72
+ * Function to extract the rate limit key from the request.
73
+ * Defaults to using the client IP address.
74
+ */
75
+ keyGenerator?: (ctx: Context) => string | Promise<string>;
76
+ /**
77
+ * Rate limit store implementation.
78
+ * Defaults to in-memory store.
79
+ */
80
+ store?: RateLimitStore;
81
+ /**
82
+ * Whether to skip rate limiting for certain requests.
83
+ */
84
+ skip?: (ctx: Context) => boolean | Promise<boolean>;
85
+ /**
86
+ * Custom handler when rate limit is exceeded.
87
+ */
88
+ onRateLimited?: (ctx: Context, retryAfter: number) => Response | Promise<Response>;
89
+ /**
90
+ * Whether to add rate limit headers to all responses.
91
+ * @default true
92
+ */
93
+ headers?: boolean;
94
+ /**
95
+ * Custom message when rate limit is exceeded.
96
+ * @default 'Too many requests, please try again later.'
97
+ */
98
+ message?: string;
99
+ /**
100
+ * HTTP status code when rate limit is exceeded.
101
+ * @default 429
102
+ */
103
+ statusCode?: number;
104
+ /**
105
+ * Prefix for rate limit keys.
106
+ * @default 'rl:'
107
+ */
108
+ keyPrefix?: string;
109
+ /**
110
+ * Trust reverse-proxy headers for client IP resolution, checked in order:
111
+ * `CF-Connecting-IP`, `True-Client-IP`, `X-Real-IP`, then the first entry
112
+ * of `X-Forwarded-For`. Falls back to `server.requestIP()` when none are set.
113
+ *
114
+ * Enable ONLY when every request passes through a proxy that sets or strips
115
+ * these headers — on direct deployments clients can spoof them to bypass
116
+ * per-client limits. Ignored when a custom `keyGenerator` is supplied.
117
+ * @default false
118
+ */
119
+ trustProxy?: boolean;
120
+ }
121
+ /**
122
+ * Create a rate limiting middleware.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * // Basic usage - 100 requests per minute per IP
127
+ * app.use('*', createRateLimitMiddleware())
128
+ *
129
+ * // Stricter limit for login endpoint
130
+ * router.post('/login', [AuthController, 'login'],
131
+ * createRateLimitMiddleware({
132
+ * limit: 5,
133
+ * windowMs: 15 * 60 * 1000, // 15 minutes
134
+ * })
135
+ * )
136
+ *
137
+ * // Custom key based on authenticated user
138
+ * app.use('/api/*', createRateLimitMiddleware({
139
+ * limit: 1000,
140
+ * windowMs: 60 * 60 * 1000, // 1 hour
141
+ * keyGenerator: async (ctx) => {
142
+ * const user = await ctx.get('user')
143
+ * return user?.id?.toString() ?? defaultKeyGenerator(ctx)
144
+ * },
145
+ * }))
146
+ * ```
147
+ */
148
+ declare function createRateLimitMiddleware(options?: RateLimitOptions): MiddlewareHandler;
149
+ /**
150
+ * Rate limit result information.
151
+ */
152
+ interface RateLimitInfo {
153
+ limit: number;
154
+ remaining: number;
155
+ resetAt: Date;
156
+ isLimited: boolean;
157
+ }
158
+ /**
159
+ * Get rate limit information for a key without incrementing.
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * const info = await getRateLimitInfo('user:123', store, { limit: 100 })
164
+ * console.log(`${info.remaining} requests remaining`)
165
+ * ```
166
+ */
167
+ declare function getRateLimitInfo(key: string, store: RateLimitStore, options?: {
168
+ limit: number;
169
+ keyPrefix?: string;
170
+ }): Promise<RateLimitInfo>;
171
+ /**
172
+ * Reset rate limit for a specific key.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * // Reset rate limit after successful captcha
177
+ * await resetRateLimit(clientIp, store)
178
+ * ```
179
+ */
180
+ declare function resetRateLimit(key: string, store: RateLimitStore, options?: {
181
+ keyPrefix?: string;
182
+ }): Promise<void>;
183
+ /**
184
+ * Sliding window rate limit store.
185
+ * More accurate than fixed window but uses more memory.
186
+ */
187
+ declare class SlidingWindowRateLimitStore extends BaseMemoryStore {
188
+ private requests;
189
+ get(key: string): Promise<RateLimitEntry | null>;
190
+ increment(key: string, windowMs: number): Promise<RateLimitEntry>;
191
+ reset(key: string): Promise<void>;
192
+ cleanup(): void;
193
+ clear(): void;
194
+ get size(): number;
195
+ }
196
+
197
+ /**
198
+ * Options for creating a Redis client.
199
+ */
200
+ interface RedisClientOptions extends RedisOptions {
201
+ /**
202
+ * Redis connection URL (e.g., 'redis://localhost:6379').
203
+ * If provided, overrides host/port/password.
204
+ */
205
+ url?: string;
206
+ /**
207
+ * Key prefix for all operations.
208
+ * @default ''
209
+ */
210
+ keyPrefix?: string;
211
+ }
212
+ /**
213
+ * Create a Redis client with the given options.
214
+ *
215
+ * @example
216
+ * ```ts
217
+ * // Using URL
218
+ * const redis = createRedisClient({ url: 'redis://localhost:6379' })
219
+ *
220
+ * // Using host/port
221
+ * const redis = createRedisClient({ host: 'localhost', port: 6379 })
222
+ *
223
+ * // With key prefix
224
+ * const redis = createRedisClient({
225
+ * url: process.env.REDIS_URL,
226
+ * keyPrefix: 'myapp:',
227
+ * })
228
+ * ```
229
+ */
230
+ declare function createRedisClient(options?: RedisClientOptions): Redis;
231
+
232
+ export { MemoryRateLimitStore as M, type RateLimitStore as R, SlidingWindowRateLimitStore as S, type RateLimitEntry as a, type RedisClientOptions as b, createRedisClient as c, type RateLimitInfo as d, type RateLimitOptions as e, createRateLimitMiddleware as f, getRateLimitInfo as g, resetRateLimit as r };
@@ -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 };