@mountsqli/auth 0.1.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +550 -0
  2. package/dist/index.js +1247 -0
  3. package/package.json +42 -0
@@ -0,0 +1,550 @@
1
+ import * as _mountsqli_pg from '@mountsqli/pg';
2
+
3
+ /**
4
+ * Auth type definitions.
5
+ */
6
+ interface AuthConfig {
7
+ /** Database instance (MountSQLi Database) */
8
+ db: any;
9
+ /** Secret key for JWT signing */
10
+ secret: string;
11
+ /** Auth providers */
12
+ providers: AuthProvider[];
13
+ /** Session configuration */
14
+ session?: SessionConfig;
15
+ /** Custom pages */
16
+ pages?: PagesConfig;
17
+ /** Lifecycle callbacks */
18
+ callbacks?: CallbacksConfig;
19
+ }
20
+ interface SessionConfig {
21
+ strategy: 'jwt' | 'database';
22
+ maxAge: number;
23
+ }
24
+ interface PagesConfig {
25
+ signIn?: string;
26
+ signUp?: string;
27
+ error?: string;
28
+ verifyRequest?: string;
29
+ }
30
+ interface CallbacksConfig {
31
+ onRegister?: (user: User) => Promise<void> | void;
32
+ onLogin?: (user: User) => Promise<void> | void;
33
+ onLogout?: (session: SessionData) => Promise<void> | void;
34
+ onSession?: (session: SessionData) => Promise<SessionData | null> | SessionData | null;
35
+ }
36
+ interface User {
37
+ id: string;
38
+ email: string;
39
+ emailVerified: Date | null;
40
+ name: string | null;
41
+ image: string | null;
42
+ twoFactorEnabled: boolean;
43
+ createdAt: Date;
44
+ updatedAt: Date;
45
+ }
46
+ interface CreateUserInput {
47
+ email: string;
48
+ password?: string;
49
+ name?: string;
50
+ image?: string;
51
+ emailVerified?: Date;
52
+ }
53
+ interface Session {
54
+ id: string;
55
+ userId: string;
56
+ token: string;
57
+ expiresAt: Date;
58
+ ipAddress?: string;
59
+ userAgent?: string;
60
+ }
61
+ interface SessionData {
62
+ user: User;
63
+ expiresAt: Date;
64
+ }
65
+ interface AuthResult {
66
+ user: User;
67
+ session: SessionData;
68
+ token: string;
69
+ }
70
+ interface AuthProvider {
71
+ id: string;
72
+ name: string;
73
+ type: 'credentials' | 'oauth' | 'email';
74
+ }
75
+ interface CredentialsProvider extends AuthProvider {
76
+ type: 'credentials';
77
+ authorize: (credentials: Record<string, string>, req?: any) => Promise<User | null>;
78
+ }
79
+ interface OAuthProvider extends AuthProvider {
80
+ type: 'oauth';
81
+ clientId: string;
82
+ clientSecret: string;
83
+ scope?: string[];
84
+ authorizationUrl?: string;
85
+ tokenUrl?: string;
86
+ userInfoUrl?: string;
87
+ }
88
+ interface EmailProvider extends AuthProvider {
89
+ type: 'email';
90
+ sendVerificationEmail?: (email: string, token: string) => Promise<void>;
91
+ }
92
+ interface Role {
93
+ id: string;
94
+ name: string;
95
+ permissions: string[];
96
+ createdAt: Date;
97
+ }
98
+ interface UserRole {
99
+ userId: string;
100
+ roleId: string;
101
+ }
102
+ interface MiddlewareOptions {
103
+ required?: boolean;
104
+ requiredRole?: string;
105
+ requiredPermission?: string;
106
+ }
107
+ interface AuthMiddlewareResult {
108
+ user: User | null;
109
+ session: SessionData | null;
110
+ }
111
+ interface JWTPayload {
112
+ sub: string;
113
+ email: string;
114
+ name?: string;
115
+ image?: string;
116
+ iat: number;
117
+ exp: number;
118
+ }
119
+ interface OAuthCallbackParams {
120
+ code?: string;
121
+ state?: string;
122
+ error?: string;
123
+ error_description?: string;
124
+ }
125
+ interface OAuthTokenResponse {
126
+ access_token: string;
127
+ token_type: string;
128
+ expires_in?: number;
129
+ refresh_token?: string;
130
+ scope?: string;
131
+ }
132
+ interface OAuthUserInfo {
133
+ id: string;
134
+ email: string;
135
+ name?: string;
136
+ image?: string;
137
+ emailVerified?: boolean;
138
+ }
139
+
140
+ /**
141
+ * Main Auth class — orchestrates all auth functionality.
142
+ */
143
+
144
+ declare class Auth {
145
+ private config;
146
+ private db;
147
+ private secret;
148
+ private sessionConfig;
149
+ private emailAdapter;
150
+ private rateLimiter;
151
+ private usersTable;
152
+ private sessionsTable;
153
+ private accountsTable;
154
+ private verificationTable;
155
+ private rolesTable;
156
+ private userRolesTable;
157
+ constructor(config: AuthConfig);
158
+ register(data: {
159
+ email: string;
160
+ password: string;
161
+ name?: string;
162
+ }): Promise<AuthResult>;
163
+ login(providerId: string, credentials: Record<string, string>): Promise<AuthResult>;
164
+ private loginWithCredentials;
165
+ signIn(providerId: string): Promise<string>;
166
+ handleCallback(providerId: string, params: {
167
+ code?: string;
168
+ state?: string;
169
+ error?: string;
170
+ }): Promise<AuthResult>;
171
+ getSession(request: {
172
+ headers?: Record<string, string | undefined>;
173
+ }): Promise<SessionData | null>;
174
+ logout(token: string): Promise<void>;
175
+ twoFactor: {
176
+ generate: (userId: string) => Promise<{
177
+ secret: string;
178
+ otpauthUrl: string;
179
+ }>;
180
+ enable: (userId: string, code: string) => Promise<void>;
181
+ disable: (userId: string) => Promise<void>;
182
+ verify: (secret: string, code: string) => boolean;
183
+ };
184
+ passwordReset: {
185
+ create: (email: string) => Promise<string>;
186
+ verify: (token: string, newPassword: string) => Promise<void>;
187
+ };
188
+ emailVerification: {
189
+ create: (userId: string) => Promise<string>;
190
+ verify: (token: string) => Promise<void>;
191
+ };
192
+ rbac: {
193
+ createRole: (data: {
194
+ name: string;
195
+ permissions: string[];
196
+ }) => Promise<Role>;
197
+ deleteRole: (roleId: string) => Promise<void>;
198
+ assignRole: (userId: string, roleName: string) => Promise<void>;
199
+ removeRole: (userId: string, roleName: string) => Promise<void>;
200
+ getUserRoles: (userId: string) => Promise<Role[]>;
201
+ hasRole: (userId: string, roleName: string) => Promise<boolean>;
202
+ authorize: (userId: string, permission: string) => Promise<boolean>;
203
+ };
204
+ private isValidEmail;
205
+ private isValidPassword;
206
+ /** Generate a CSRF token for a session */
207
+ generateCsrfToken(sessionToken: string): string;
208
+ /** Validate a CSRF token */
209
+ validateCsrfToken(sessionToken: string, csrfToken: string): boolean;
210
+ private extractToken;
211
+ private sanitizeUser;
212
+ }
213
+
214
+ /**
215
+ * Pre-built users table for auth.
216
+ */
217
+ declare const authUsers: _mountsqli_pg.PgTable & {
218
+ columns: {
219
+ id: any;
220
+ email: any;
221
+ emailVerified: any;
222
+ password: any;
223
+ name: any;
224
+ image: any;
225
+ twoFactorEnabled: any;
226
+ twoFactorSecret: any;
227
+ createdAt: any;
228
+ updatedAt: any;
229
+ };
230
+ };
231
+
232
+ /**
233
+ * Pre-built sessions table for auth.
234
+ */
235
+ declare const authSessions: _mountsqli_pg.PgTable & {
236
+ columns: {
237
+ id: any;
238
+ userId: any;
239
+ token: any;
240
+ expiresAt: any;
241
+ ipAddress: any;
242
+ userAgent: any;
243
+ };
244
+ };
245
+
246
+ /**
247
+ * Pre-built OAuth accounts table for auth.
248
+ */
249
+ declare const authAccounts: _mountsqli_pg.PgTable & {
250
+ columns: {
251
+ id: any;
252
+ userId: any;
253
+ provider: any;
254
+ providerAccountId: any;
255
+ accessToken: any;
256
+ refreshToken: any;
257
+ expiresAt: any;
258
+ createdAt: any;
259
+ };
260
+ };
261
+
262
+ /**
263
+ * Pre-built verification tokens table for email verification and password reset.
264
+ */
265
+ declare const authVerificationTokens: _mountsqli_pg.PgTable & {
266
+ columns: {
267
+ id: any;
268
+ identifier: any;
269
+ token: any;
270
+ expiresAt: any;
271
+ };
272
+ };
273
+
274
+ /**
275
+ * Pre-built roles table for RBAC.
276
+ */
277
+ declare const authRoles: _mountsqli_pg.PgTable & {
278
+ columns: {
279
+ id: any;
280
+ name: any;
281
+ permissions: any;
282
+ createdAt: any;
283
+ };
284
+ };
285
+
286
+ /**
287
+ * Pre-built user_roles junction table for RBAC.
288
+ */
289
+ declare const authUserRoles: _mountsqli_pg.PgTable & {
290
+ columns: {
291
+ userId: any;
292
+ roleId: any;
293
+ };
294
+ };
295
+
296
+ /**
297
+ * Credentials (email/password) provider.
298
+ */
299
+
300
+ interface CredentialsProviderConfig {
301
+ /** Custom authorization function */
302
+ authorize?: (credentials: Record<string, string>) => Promise<any | null>;
303
+ }
304
+ declare function credentials(config?: CredentialsProviderConfig): CredentialsProvider;
305
+
306
+ /**
307
+ * Google OAuth provider.
308
+ */
309
+
310
+ interface GoogleProviderConfig {
311
+ clientId: string;
312
+ clientSecret: string;
313
+ scope?: string[];
314
+ }
315
+ declare function google(config: GoogleProviderConfig): OAuthProvider;
316
+
317
+ /**
318
+ * GitHub OAuth provider.
319
+ */
320
+
321
+ interface GitHubProviderConfig {
322
+ clientId: string;
323
+ clientSecret: string;
324
+ scope?: string[];
325
+ }
326
+ declare function github(config: GitHubProviderConfig): OAuthProvider;
327
+
328
+ /**
329
+ * Framework-agnostic auth middleware helper.
330
+ */
331
+
332
+ /**
333
+ * Resolve auth session from a request-like object.
334
+ */
335
+ declare function resolveAuth(auth: Auth, request: {
336
+ headers?: Record<string, string | undefined>;
337
+ }, options?: MiddlewareOptions): Promise<AuthMiddlewareResult>;
338
+
339
+ /**
340
+ * Express middleware adapter.
341
+ */
342
+
343
+ interface ExpressAuthMiddlewareOptions extends MiddlewareOptions {
344
+ /** Custom error handler */
345
+ onError?: (err: Error, req: any, res: any, next: any) => void;
346
+ }
347
+ /**
348
+ * Create Express middleware.
349
+ */
350
+ declare function expressMiddleware(auth: Auth, options?: ExpressAuthMiddlewareOptions): (req: any, res: any, next: any) => Promise<void>;
351
+ /**
352
+ * Create Express route protector.
353
+ */
354
+ declare function requireAuth(auth: Auth, options?: ExpressAuthMiddlewareOptions): (req: any, res: any, next: any) => Promise<void>;
355
+
356
+ interface NextAuthMiddlewareOptions extends MiddlewareOptions {
357
+ /** Pages to redirect to */
358
+ pages?: {
359
+ signIn?: string;
360
+ signUp?: string;
361
+ };
362
+ /** Authorized callbacks */
363
+ authorized?: (auth: {
364
+ user: any;
365
+ } | null, request: any) => boolean | Promise<boolean>;
366
+ }
367
+ /**
368
+ * Create Next.js middleware.
369
+ * Returns a redirect object or null (continue to next middleware).
370
+ */
371
+ declare function nextjsMiddleware(auth: Auth, options?: NextAuthMiddlewareOptions): (request: any) => Promise<{
372
+ redirect: string;
373
+ } | null>;
374
+ /**
375
+ * Create Next.js API route helper.
376
+ */
377
+ declare function nextjsApiAuth(auth: Auth): (request: any) => Promise<AuthMiddlewareResult>;
378
+
379
+ /**
380
+ * Fastify middleware adapter.
381
+ */
382
+
383
+ interface FastifyAuthMiddlewareOptions extends MiddlewareOptions {
384
+ onError?: (err: Error, request: any, reply: any) => void;
385
+ }
386
+ /**
387
+ * Create Fastify plugin.
388
+ */
389
+ declare function fastifyPlugin(auth: Auth, options?: FastifyAuthMiddlewareOptions): (fastify: any) => Promise<void>;
390
+ /**
391
+ * Create Fastify route protector.
392
+ */
393
+ declare function requireAuthFastify(auth: Auth, options?: FastifyAuthMiddlewareOptions): (request: any, reply: any) => Promise<void>;
394
+
395
+ /**
396
+ * Hono middleware adapter.
397
+ */
398
+
399
+ interface HonoAuthMiddlewareOptions extends MiddlewareOptions {
400
+ onError?: (err: Error, c: any) => Response | Promise<Response>;
401
+ }
402
+ /**
403
+ * Create Hono middleware.
404
+ */
405
+ declare function honoMiddleware(auth: Auth, options?: HonoAuthMiddlewareOptions): (c: any, next: () => Promise<void>) => Promise<any>;
406
+ /**
407
+ * Create Hono route protector.
408
+ */
409
+ declare function requireAuthHono(auth: Auth, options?: HonoAuthMiddlewareOptions): (c: any, next: () => Promise<void>) => Promise<any>;
410
+
411
+ /**
412
+ * Password hashing using Node.js scrypt (built-in, no native deps).
413
+ */
414
+ /**
415
+ * Hash a password using scrypt.
416
+ */
417
+ declare function hashPassword(password: string): Promise<string>;
418
+ /**
419
+ * Verify a password against a hash.
420
+ */
421
+ declare function verifyPassword(password: string, hash: string): Promise<boolean>;
422
+
423
+ /**
424
+ * JWT creation and verification using jose.
425
+ */
426
+
427
+ /**
428
+ * Create a JWT token.
429
+ */
430
+ declare function createToken(payload: Omit<JWTPayload, 'iat' | 'exp'>, secret: string, options?: {
431
+ maxAge?: number;
432
+ }): Promise<string>;
433
+ /**
434
+ * Verify and decode a JWT token.
435
+ */
436
+ declare function verifyToken(token: string, secret: string): Promise<JWTPayload | null>;
437
+ /**
438
+ * Decode a JWT without verification (for debugging).
439
+ */
440
+ declare function decodeToken(token: string): JWTPayload | null;
441
+
442
+ /**
443
+ * TOTP (Time-based One-Time Password) 2FA implementation.
444
+ * Uses HMAC-SHA1 based TOTP as per RFC 6238.
445
+ */
446
+ interface TOTPConfig {
447
+ /** Number of digits in the code (default: 6) */
448
+ digits?: number;
449
+ /** Time step in seconds (default: 30) */
450
+ period?: number;
451
+ /** Algorithm (default: 'sha1') */
452
+ algorithm?: 'sha1' | 'sha256' | 'sha512';
453
+ }
454
+ /**
455
+ * Generate a random TOTP secret.
456
+ */
457
+ declare function generateSecret(length?: number): string;
458
+ /**
459
+ * Generate a TOTP code for a given secret and timestamp.
460
+ */
461
+ declare function generateCode(secret: string, timestamp?: number, config?: TOTPConfig): string;
462
+ /**
463
+ * Verify a TOTP code against a secret.
464
+ * Allows for ±1 time step drift.
465
+ * Uses timing-safe comparison to prevent timing attacks.
466
+ */
467
+ declare function verifyCode(secret: string, code: string, config?: TOTPConfig): boolean;
468
+ /**
469
+ * Generate a TOTP URI for QR code generation.
470
+ */
471
+ declare function generateURI(secret: string, email: string, issuer?: string, config?: TOTPConfig): string;
472
+
473
+ /**
474
+ * Email sending interface and built-in adapters.
475
+ */
476
+ interface EmailAdapter {
477
+ send(params: {
478
+ to: string;
479
+ subject: string;
480
+ text?: string;
481
+ html?: string;
482
+ }): Promise<void>;
483
+ }
484
+ /**
485
+ * Console email adapter (logs to console — for development).
486
+ */
487
+ declare class ConsoleEmailAdapter implements EmailAdapter {
488
+ send(params: {
489
+ to: string;
490
+ subject: string;
491
+ text?: string;
492
+ html?: string;
493
+ }): Promise<void>;
494
+ }
495
+ /**
496
+ * Send a verification email.
497
+ */
498
+ declare function sendVerificationEmail(adapter: EmailAdapter, email: string, token: string, baseUrl?: string): Promise<void>;
499
+ /**
500
+ * Send a password reset email.
501
+ */
502
+ declare function sendPasswordResetEmail(adapter: EmailAdapter, email: string, token: string, baseUrl?: string): Promise<void>;
503
+
504
+ /**
505
+ * Auth-specific error classes.
506
+ */
507
+ declare class AuthError extends Error {
508
+ constructor(message: string);
509
+ }
510
+ declare class UnauthorizedError extends AuthError {
511
+ constructor(message?: string);
512
+ }
513
+ declare class ForbiddenError extends AuthError {
514
+ constructor(message?: string);
515
+ }
516
+ declare class InvalidCredentialsError extends AuthError {
517
+ constructor(message?: string);
518
+ }
519
+ declare class UserNotFoundError extends AuthError {
520
+ constructor(message?: string);
521
+ }
522
+ declare class EmailAlreadyExistsError extends AuthError {
523
+ constructor(message?: string);
524
+ }
525
+ declare class InvalidTokenError extends AuthError {
526
+ constructor(message?: string);
527
+ }
528
+ declare class TwoFactorRequiredError extends AuthError {
529
+ constructor(message?: string);
530
+ }
531
+ declare class TwoFactorInvalidError extends AuthError {
532
+ constructor(message?: string);
533
+ }
534
+ declare class SessionExpiredError extends AuthError {
535
+ constructor(message?: string);
536
+ }
537
+ declare class ProviderError extends AuthError {
538
+ constructor(message?: string);
539
+ }
540
+
541
+ /**
542
+ * @mountsqli/auth — Pre-built authentication system for MountSQLi.
543
+ */
544
+
545
+ /**
546
+ * Create an Auth instance.
547
+ */
548
+ declare function createAuth(config: AuthConfig): Auth;
549
+
550
+ export { Auth, type AuthConfig, AuthError, type AuthMiddlewareResult, type AuthProvider, type AuthResult, type CallbacksConfig, ConsoleEmailAdapter, type CreateUserInput, type CredentialsProvider, type CredentialsProviderConfig, type EmailAdapter, EmailAlreadyExistsError, type EmailProvider, type ExpressAuthMiddlewareOptions, type FastifyAuthMiddlewareOptions, ForbiddenError, type GitHubProviderConfig, type GoogleProviderConfig, type HonoAuthMiddlewareOptions, InvalidCredentialsError, InvalidTokenError, type JWTPayload, type MiddlewareOptions, type NextAuthMiddlewareOptions, type OAuthCallbackParams, type OAuthProvider, type OAuthTokenResponse, type OAuthUserInfo, type PagesConfig, ProviderError, type Role, type Session, type SessionConfig, type SessionData, SessionExpiredError, TwoFactorInvalidError, TwoFactorRequiredError, UnauthorizedError, type User, UserNotFoundError, type UserRole, authAccounts, authRoles, authSessions, authUserRoles, authUsers, authVerificationTokens, createAuth, createToken, credentials, decodeToken, expressMiddleware, fastifyPlugin, generateCode, generateSecret, generateURI, github, google, hashPassword, honoMiddleware, nextjsApiAuth, nextjsMiddleware, requireAuth, requireAuthFastify, requireAuthHono, resolveAuth, sendPasswordResetEmail, sendVerificationEmail, verifyCode, verifyPassword, verifyToken };