@authcore/core 0.5.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/database.interface.d.ts +42 -0
  3. package/dist/adapters/database.interface.d.ts.map +1 -0
  4. package/dist/adapters/database.interface.js +2 -0
  5. package/dist/adapters/database.interface.js.map +1 -0
  6. package/dist/adapters/email.interface.d.ts +31 -0
  7. package/dist/adapters/email.interface.d.ts.map +1 -0
  8. package/dist/adapters/email.interface.js +2 -0
  9. package/dist/adapters/email.interface.js.map +1 -0
  10. package/dist/auth.d.ts +73 -0
  11. package/dist/auth.d.ts.map +1 -0
  12. package/dist/auth.js +180 -0
  13. package/dist/auth.js.map +1 -0
  14. package/dist/features/emailVerification.d.ts +25 -0
  15. package/dist/features/emailVerification.d.ts.map +1 -0
  16. package/dist/features/emailVerification.js +52 -0
  17. package/dist/features/emailVerification.js.map +1 -0
  18. package/dist/features/passwordReset.d.ts +26 -0
  19. package/dist/features/passwordReset.d.ts.map +1 -0
  20. package/dist/features/passwordReset.js +57 -0
  21. package/dist/features/passwordReset.js.map +1 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +10 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/types.d.ts +71 -0
  27. package/dist/types.d.ts.map +1 -0
  28. package/dist/types.js +6 -0
  29. package/dist/types.js.map +1 -0
  30. package/dist/utils/password.d.ts +18 -0
  31. package/dist/utils/password.d.ts.map +1 -0
  32. package/dist/utils/password.js +25 -0
  33. package/dist/utils/password.js.map +1 -0
  34. package/dist/utils/token.d.ts +44 -0
  35. package/dist/utils/token.d.ts.map +1 -0
  36. package/dist/utils/token.js +64 -0
  37. package/dist/utils/token.js.map +1 -0
  38. package/dist/utils/validation.d.ts +56 -0
  39. package/dist/utils/validation.d.ts.map +1 -0
  40. package/dist/utils/validation.js +30 -0
  41. package/dist/utils/validation.js.map +1 -0
  42. package/package.json +52 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David Ouatedem
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,42 @@
1
+ import type { User, Token, TokenType, CreateUserInput, CreateTokenInput } from '../types.js';
2
+ /**
3
+ * DatabaseAdapter defines the contract that any database implementation must fulfill.
4
+ * Implement this interface to add support for a new database (Drizzle, Mongoose, etc.).
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import type { DatabaseAdapter } from '@authcore/core'
9
+ *
10
+ * export function myAdapter(client: MyClient): DatabaseAdapter {
11
+ * return {
12
+ * findUserByEmail: (email) => client.user.findUnique({ where: { email } }),
13
+ * // ...
14
+ * }
15
+ * }
16
+ * ```
17
+ */
18
+ export interface DatabaseAdapter {
19
+ /** Find a user by their email address. Returns null if not found. */
20
+ findUserByEmail(email: string): Promise<User | null>;
21
+ /** Find a user by their ID. Returns null if not found. */
22
+ findUserById(id: string): Promise<User | null>;
23
+ /** Create a new user record. */
24
+ createUser(data: CreateUserInput): Promise<User>;
25
+ /** Update fields on an existing user. */
26
+ updateUser(id: string, data: Partial<Omit<User, 'id' | 'createdAt'>>): Promise<User>;
27
+ /**
28
+ * Create a new token record.
29
+ * The `token` field in `data` must be the SHA-256 hash of the raw token.
30
+ */
31
+ createToken(data: CreateTokenInput): Promise<Token>;
32
+ /**
33
+ * Find a token record by the raw token value and type.
34
+ * Implementations MUST hash the raw token before querying.
35
+ */
36
+ findToken(rawToken: string, type: TokenType): Promise<Token | null>;
37
+ /** Delete a token by its ID. */
38
+ deleteToken(id: string): Promise<void>;
39
+ /** Delete all expired tokens. Call periodically for housekeeping. */
40
+ deleteExpiredTokens(): Promise<void>;
41
+ }
42
+ //# sourceMappingURL=database.interface.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.interface.d.ts","sourceRoot":"","sources":["../../src/adapters/database.interface.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAE5F;;;;;;;;;;;;;;;GAeG;AACH,MAAM,WAAW,eAAe;IAC9B,qEAAqE;IACrE,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAAA;IAEpD,0DAA0D;IAC1D,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAAA;IAE9C,gCAAgC;IAChC,UAAU,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAEhD,yCAAyC;IACzC,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,GAAG,WAAW,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAEpF;;;OAGG;IACH,WAAW,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;IAEnD;;;OAGG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,CAAA;IAEnE,gCAAgC;IAChC,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAEtC,qEAAqE;IACrE,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CACrC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=database.interface.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database.interface.js","sourceRoot":"","sources":["../../src/adapters/database.interface.ts"],"names":[],"mappings":""}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * EmailAdapter defines the contract for any email provider implementation.
3
+ * Implement this interface to add support for a new email provider (SendGrid, Mailgun, etc.).
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { EmailAdapter } from '@authcore/core'
8
+ *
9
+ * export function myEmailAdapter(apiKey: string): EmailAdapter {
10
+ * return {
11
+ * send: async ({ to, subject, html, text }) => {
12
+ * await myEmailClient.send({ apiKey, to, subject, html, text })
13
+ * }
14
+ * }
15
+ * }
16
+ * ```
17
+ */
18
+ export interface EmailAdapter {
19
+ /**
20
+ * Send an email.
21
+ * Must throw on failure — AuthCore will not retry automatically.
22
+ */
23
+ send(options: {
24
+ from: string;
25
+ to: string;
26
+ subject: string;
27
+ html: string;
28
+ text: string;
29
+ }): Promise<void>;
30
+ }
31
+ //# sourceMappingURL=email.interface.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"email.interface.d.ts","sourceRoot":"","sources":["../../src/adapters/email.interface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,IAAI,CAAC,OAAO,EAAE;QACZ,IAAI,EAAE,MAAM,CAAA;QACZ,EAAE,EAAE,MAAM,CAAA;QACV,OAAO,EAAE,MAAM,CAAA;QACf,IAAI,EAAE,MAAM,CAAA;QACZ,IAAI,EAAE,MAAM,CAAA;KACb,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAClB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=email.interface.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"email.interface.js","sourceRoot":"","sources":["../../src/adapters/email.interface.ts"],"names":[],"mappings":""}
package/dist/auth.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { AuthCoreConfig, PublicUser } from './types.js';
2
+ export declare class AuthError extends Error {
3
+ readonly code: string;
4
+ readonly statusCode: number;
5
+ constructor(message: string, code: string, statusCode: number);
6
+ }
7
+ /**
8
+ * The AuthCore instance returned by createAuth.
9
+ * Framework adapters (Express, Fastify) wrap this object.
10
+ */
11
+ export interface AuthCore {
12
+ /**
13
+ * Register a new user.
14
+ * @throws AuthError on validation failure (400) or duplicate email (409)
15
+ */
16
+ register(input: unknown): Promise<{
17
+ user: PublicUser;
18
+ token: string;
19
+ }>;
20
+ /**
21
+ * Authenticate a user with email/password.
22
+ * @throws AuthError on invalid credentials (401)
23
+ */
24
+ login(input: unknown): Promise<{
25
+ user: PublicUser;
26
+ token: string;
27
+ }>;
28
+ /**
29
+ * Verify a JWT and return the public user.
30
+ * Returns null if the token is invalid or expired.
31
+ */
32
+ verifyToken(token: string): Promise<PublicUser | null>;
33
+ /**
34
+ * Initiate email verification (requires emailVerification feature).
35
+ * Sends a verification email.
36
+ */
37
+ sendEmailVerification(params: {
38
+ userId: string;
39
+ email: string;
40
+ verificationUrl: string;
41
+ }): Promise<void>;
42
+ /**
43
+ * Complete email verification using the raw token.
44
+ * @throws AuthError if token is invalid or expired (400)
45
+ */
46
+ verifyEmail(input: unknown): Promise<void>;
47
+ /**
48
+ * Initiate password reset. Always returns successfully (prevents enumeration).
49
+ */
50
+ forgotPassword(input: unknown): Promise<void>;
51
+ /**
52
+ * Complete password reset using the raw token.
53
+ * @throws AuthError if token is invalid or expired (400)
54
+ */
55
+ resetPassword(input: unknown): Promise<void>;
56
+ }
57
+ /**
58
+ * Create an AuthCore instance from the provided configuration.
59
+ * This is the main entry point for the core package.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * import { createAuth } from '@authcore/core'
64
+ * import { prismaAdapter } from '@authcore/prisma-adapter'
65
+ *
66
+ * const auth = createAuth({
67
+ * db: prismaAdapter(prisma),
68
+ * session: { strategy: 'jwt', secret: process.env.AUTH_SECRET! },
69
+ * })
70
+ * ```
71
+ */
72
+ export declare function createAuth(config: AuthCoreConfig): AuthCore;
73
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAmB5D,qBAAa,SAAU,SAAQ,KAAK;aAGhB,IAAI,EAAE,MAAM;aACZ,UAAU,EAAE,MAAM;gBAFlC,OAAO,EAAE,MAAM,EACC,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM;CAKrC;AAED;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACvB;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAEtE;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAEnE;;;OAGG;IACH,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAA;IAEtD;;;OAGG;IACH,qBAAqB,CAAC,MAAM,EAAE;QAC5B,MAAM,EAAE,MAAM,CAAA;QACd,KAAK,EAAE,MAAM,CAAA;QACb,eAAe,EAAE,MAAM,CAAA;KACxB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAEjB;;;OAGG;IACH,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAE1C;;OAEG;IACH,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAE7C;;;OAGG;IACH,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC7C;AAmBD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,cAAc,GAAG,QAAQ,CAuL3D"}
package/dist/auth.js ADDED
@@ -0,0 +1,180 @@
1
+ import { hashPassword, verifyPassword } from './utils/password.js';
2
+ import { signJwt, verifyJwt } from './utils/token.js';
3
+ import { registerSchema, loginSchema, forgotPasswordSchema, resetPasswordSchema, verifyEmailSchema, } from './utils/validation.js';
4
+ import { createEmailVerification, verifyEmail as verifyEmailFeature, } from './features/emailVerification.js';
5
+ import { createPasswordReset, resetPassword as resetPasswordFeature, } from './features/passwordReset.js';
6
+ export class AuthError extends Error {
7
+ code;
8
+ statusCode;
9
+ constructor(message, code, statusCode) {
10
+ super(message);
11
+ this.code = code;
12
+ this.statusCode = statusCode;
13
+ this.name = 'AuthError';
14
+ }
15
+ }
16
+ function toPublicUser(user) {
17
+ return {
18
+ id: user.id,
19
+ email: user.email,
20
+ emailVerified: user.emailVerified,
21
+ createdAt: user.createdAt,
22
+ updatedAt: user.updatedAt,
23
+ };
24
+ }
25
+ /**
26
+ * Create an AuthCore instance from the provided configuration.
27
+ * This is the main entry point for the core package.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * import { createAuth } from '@authcore/core'
32
+ * import { prismaAdapter } from '@authcore/prisma-adapter'
33
+ *
34
+ * const auth = createAuth({
35
+ * db: prismaAdapter(prisma),
36
+ * session: { strategy: 'jwt', secret: process.env.AUTH_SECRET! },
37
+ * })
38
+ * ```
39
+ */
40
+ export function createAuth(config) {
41
+ const { db, session, email, features = [], password: pwConfig = {}, callbacks = {} } = config;
42
+ const saltRounds = pwConfig.saltRounds ?? 12;
43
+ const minPasswordLength = pwConfig.minLength ?? 8;
44
+ const expiresIn = session.expiresIn ?? '7d';
45
+ const hasEmailVerification = features.includes('emailVerification');
46
+ const hasPasswordReset = features.includes('passwordReset');
47
+ return {
48
+ async register(input) {
49
+ const schema = registerSchema(minPasswordLength);
50
+ const parsed = schema.safeParse(input);
51
+ if (!parsed.success) {
52
+ throw new AuthError(parsed.error.errors[0]?.message ?? 'Validation failed', 'VALIDATION_ERROR', 400);
53
+ }
54
+ const { email: userEmail, password } = parsed.data;
55
+ const existing = await db.findUserByEmail(userEmail);
56
+ if (existing) {
57
+ throw new AuthError('An account with this email already exists', 'EMAIL_EXISTS', 409);
58
+ }
59
+ const passwordHash = await hashPassword(password, saltRounds);
60
+ const user = await db.createUser({ email: userEmail, passwordHash });
61
+ const publicUser = toPublicUser(user);
62
+ const token = signJwt({ sub: user.id, email: user.email }, session.secret, expiresIn);
63
+ await callbacks.onSignUp?.(publicUser);
64
+ return { user: publicUser, token };
65
+ },
66
+ async login(input) {
67
+ const parsed = loginSchema.safeParse(input);
68
+ if (!parsed.success) {
69
+ throw new AuthError(parsed.error.errors[0]?.message ?? 'Validation failed', 'VALIDATION_ERROR', 400);
70
+ }
71
+ const { email: userEmail, password } = parsed.data;
72
+ const user = await db.findUserByEmail(userEmail);
73
+ if (!user) {
74
+ throw new AuthError('Invalid email or password', 'INVALID_CREDENTIALS', 401);
75
+ }
76
+ const valid = await verifyPassword(password, user.passwordHash);
77
+ if (!valid) {
78
+ throw new AuthError('Invalid email or password', 'INVALID_CREDENTIALS', 401);
79
+ }
80
+ if (hasEmailVerification && !user.emailVerified) {
81
+ throw new AuthError('Please verify your email address before signing in', 'EMAIL_NOT_VERIFIED', 403);
82
+ }
83
+ const publicUser = toPublicUser(user);
84
+ const token = signJwt({ sub: user.id, email: user.email }, session.secret, expiresIn);
85
+ await callbacks.onSignIn?.(publicUser);
86
+ return { user: publicUser, token };
87
+ },
88
+ async verifyToken(token) {
89
+ const payload = verifyJwt(token, session.secret);
90
+ if (!payload)
91
+ return null;
92
+ const user = await db.findUserById(payload.sub);
93
+ if (!user)
94
+ return null;
95
+ return toPublicUser(user);
96
+ },
97
+ async sendEmailVerification({ userId, email: userEmail, verificationUrl }) {
98
+ if (!hasEmailVerification) {
99
+ throw new AuthError('emailVerification feature is not enabled', 'FEATURE_DISABLED', 500);
100
+ }
101
+ if (!email) {
102
+ throw new AuthError('Email provider is not configured', 'EMAIL_NOT_CONFIGURED', 500);
103
+ }
104
+ await createEmailVerification({
105
+ userId,
106
+ email: userEmail,
107
+ db,
108
+ emailProvider: email.provider,
109
+ from: email.from,
110
+ verificationUrl,
111
+ });
112
+ },
113
+ async verifyEmail(input) {
114
+ const parsed = verifyEmailSchema.safeParse(input);
115
+ if (!parsed.success) {
116
+ throw new AuthError(parsed.error.errors[0]?.message ?? 'Validation failed', 'VALIDATION_ERROR', 400);
117
+ }
118
+ try {
119
+ await verifyEmailFeature({ rawToken: parsed.data.token, db });
120
+ }
121
+ catch (err) {
122
+ const message = err instanceof Error ? err.message : 'Invalid token';
123
+ throw new AuthError(message, 'INVALID_TOKEN', 400);
124
+ }
125
+ },
126
+ async forgotPassword(input) {
127
+ if (!hasPasswordReset) {
128
+ // Silently ignore — don't reveal feature status
129
+ return;
130
+ }
131
+ const parsed = forgotPasswordSchema.safeParse(input);
132
+ if (!parsed.success) {
133
+ // Still return successfully to prevent enumeration
134
+ return;
135
+ }
136
+ if (!email)
137
+ return;
138
+ // Intentionally swallow errors — always return 200
139
+ try {
140
+ await createPasswordReset({
141
+ email: parsed.data.email,
142
+ db,
143
+ emailProvider: email.provider,
144
+ from: email.from,
145
+ resetUrl: `${session.secret}/reset-password`, // overridden by framework adapter
146
+ });
147
+ }
148
+ catch {
149
+ // Swallow — no email enumeration
150
+ }
151
+ },
152
+ async resetPassword(input) {
153
+ const schema = resetPasswordSchema(minPasswordLength);
154
+ const parsed = schema.safeParse(input);
155
+ if (!parsed.success) {
156
+ throw new AuthError(parsed.error.errors[0]?.message ?? 'Validation failed', 'VALIDATION_ERROR', 400);
157
+ }
158
+ try {
159
+ await resetPasswordFeature({
160
+ rawToken: parsed.data.token,
161
+ newPassword: parsed.data.password,
162
+ db,
163
+ saltRounds,
164
+ });
165
+ const tokenRecord = await db.findToken(parsed.data.token, 'PASSWORD_RESET');
166
+ if (tokenRecord) {
167
+ const user = await db.findUserById(tokenRecord.userId);
168
+ if (user) {
169
+ await callbacks.onPasswordReset?.(toPublicUser(user));
170
+ }
171
+ }
172
+ }
173
+ catch (err) {
174
+ const message = err instanceof Error ? err.message : 'Invalid token';
175
+ throw new AuthError(message, 'INVALID_TOKEN', 400);
176
+ }
177
+ },
178
+ };
179
+ }
180
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAClE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAkC,MAAM,kBAAkB,CAAA;AACrF,OAAO,EACL,cAAc,EACd,WAAW,EACX,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EACL,uBAAuB,EACvB,WAAW,IAAI,kBAAkB,GAClC,MAAM,iCAAiC,CAAA;AACxC,OAAO,EACL,mBAAmB,EACnB,aAAa,IAAI,oBAAoB,GACtC,MAAM,6BAA6B,CAAA;AAEpC,MAAM,OAAO,SAAU,SAAQ,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M,CAAC,IAAI,CAAC,KAAK;oBAC3B,WAAW,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ;oBACjC,EAAE;oBACF,UAAU;iBACX,CAAC,CAAA;gBACF,MAAM,WAAW,GAAG,MAAM,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAA;gBAC3E,IAAI,WAAW,EAAE,CAAC;oBAChB,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,YAAY,CAAC,WAAW,CAAC,MAAM,CAAC,CAAA;oBACtD,IAAI,IAAI,EAAE,CAAC;wBACT,MAAM,SAAS,CAAC,eAAe,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAA;oBACvD,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,CAAA;gBACpE,MAAM,IAAI,SAAS,CAAC,OAAO,EAAE,eAAe,EAAE,GAAG,CAAC,CAAA;YACpD,CAAC;QACH,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { DatabaseAdapter } from '../adapters/database.interface.js';
2
+ import type { EmailAdapter } from '../adapters/email.interface.js';
3
+ /**
4
+ * Create an email verification token and send the verification email.
5
+ *
6
+ * @returns The raw token (not the hash). Store only the hash in DB.
7
+ */
8
+ export declare function createEmailVerification(params: {
9
+ userId: string;
10
+ email: string;
11
+ db: DatabaseAdapter;
12
+ emailProvider: EmailAdapter;
13
+ from: string;
14
+ verificationUrl: string;
15
+ }): Promise<string>;
16
+ /**
17
+ * Verify an email address using the raw token from the user's email link.
18
+ *
19
+ * @throws Error if the token is invalid or expired
20
+ */
21
+ export declare function verifyEmail(params: {
22
+ rawToken: string;
23
+ db: DatabaseAdapter;
24
+ }): Promise<void>;
25
+ //# sourceMappingURL=emailVerification.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emailVerification.d.ts","sourceRoot":"","sources":["../../src/features/emailVerification.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAA;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAA;AAMlE;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,MAAM,EAAE;IACpD,MAAM,EAAE,MAAM,CAAA;IACd,KAAK,EAAE,MAAM,CAAA;IACb,EAAE,EAAE,eAAe,CAAA;IACnB,aAAa,EAAE,YAAY,CAAA;IAC3B,IAAI,EAAE,MAAM,CAAA;IACZ,eAAe,EAAE,MAAM,CAAA;CACxB,GAAG,OAAO,CAAC,MAAM,CAAC,CA8BlB;AAED;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,MAAM,EAAE;IACxC,QAAQ,EAAE,MAAM,CAAA;IAChB,EAAE,EAAE,eAAe,CAAA;CACpB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBhB"}
@@ -0,0 +1,52 @@
1
+ import { generateOpaqueToken, hashToken } from '../utils/token.js';
2
+ const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
3
+ /**
4
+ * Create an email verification token and send the verification email.
5
+ *
6
+ * @returns The raw token (not the hash). Store only the hash in DB.
7
+ */
8
+ export async function createEmailVerification(params) {
9
+ const { userId, email, db, emailProvider, from, verificationUrl } = params;
10
+ const rawToken = generateOpaqueToken();
11
+ const hashedToken = hashToken(rawToken);
12
+ await db.createToken({
13
+ userId,
14
+ type: 'EMAIL_VERIFICATION',
15
+ token: hashedToken,
16
+ expiresAt: new Date(Date.now() + EMAIL_VERIFICATION_TTL_MS),
17
+ });
18
+ const link = `${verificationUrl}?token=${rawToken}`;
19
+ await emailProvider.send({
20
+ from,
21
+ to: email,
22
+ subject: 'Verify your email address',
23
+ html: `
24
+ <p>Hello,</p>
25
+ <p>Please verify your email address by clicking the link below:</p>
26
+ <p><a href="${link}">${link}</a></p>
27
+ <p>This link expires in 24 hours.</p>
28
+ <p>If you did not create an account, you can ignore this email.</p>
29
+ `,
30
+ text: `Please verify your email by visiting: ${link}\n\nThis link expires in 24 hours.`,
31
+ });
32
+ return rawToken;
33
+ }
34
+ /**
35
+ * Verify an email address using the raw token from the user's email link.
36
+ *
37
+ * @throws Error if the token is invalid or expired
38
+ */
39
+ export async function verifyEmail(params) {
40
+ const { rawToken, db } = params;
41
+ const tokenRecord = await db.findToken(rawToken, 'EMAIL_VERIFICATION');
42
+ if (!tokenRecord) {
43
+ throw new Error('Invalid or expired verification token');
44
+ }
45
+ if (tokenRecord.expiresAt < new Date()) {
46
+ await db.deleteToken(tokenRecord.id);
47
+ throw new Error('Invalid or expired verification token');
48
+ }
49
+ await db.updateUser(tokenRecord.userId, { emailVerified: true });
50
+ await db.deleteToken(tokenRecord.id);
51
+ }
52
+ //# sourceMappingURL=emailVerification.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emailVerification.js","sourceRoot":"","sources":["../../src/features/emailVerification.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AAElE,MAAM,yBAAyB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,WAAW;AAEjE;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,MAO7C;IACC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe,EAAE,GAAG,MAAM,CAAA;IAE1E,MAAM,QAAQ,GAAG,mBAAmB,EAAE,CAAA;IACtC,MAAM,WAAW,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;IAEvC,MAAM,EAAE,CAAC,WAAW,CAAC;QACnB,MAAM;QACN,IAAI,EAAE,oBAAoB;QAC1B,KAAK,EAAE,WAAW;QAClB,SAAS,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,yBAAyB,CAAC;KAC5D,CAAC,CAAA;IAEF,MAAM,IAAI,GAAG,GAAG,eAAe,UAAU,QAAQ,EAAE,CAAA;IAEnD,MAAM,aAAa,CAAC,IAAI,CAAC;QACvB,IAAI;QACJ,EAAE,EAAE,KAAK;QACT,OAAO,EAAE,2BAA2B;QACpC,IAAI,EAAE;;;oBAGU,IAAI,KAAK,IAAI;;;KAG5B;QACD,IAAI,EAAE,yCAAyC,IAAI,oCAAoC;KACxF,CAAC,CAAA;IAEF,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,MAGjC;IACC,MAAM,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,MAAM,CAAA;IAE/B,MAAM,WAAW,GAAiB,MAAM,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,oBAAoB,CAAC,CAAA;IAEpF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAA;IAC1D,CAAC;IAED,IAAI,WAAW,CAAC,SAAS,GAAG,IAAI,IAAI,EAAE,EAAE,CAAC;QACvC,MAAM,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;QACpC,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAA;IAC1D,CAAC;IAED,MAAM,EAAE,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAA;IAChE,MAAM,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;AACtC,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { DatabaseAdapter } from '../adapters/database.interface.js';
2
+ import type { EmailAdapter } from '../adapters/email.interface.js';
3
+ /**
4
+ * Initiate a password reset flow.
5
+ * Always returns successfully even if the email is not found — prevents email enumeration.
6
+ * Callers should catch and swallow errors from the email send step if needed.
7
+ */
8
+ export declare function createPasswordReset(params: {
9
+ email: string;
10
+ db: DatabaseAdapter;
11
+ emailProvider: EmailAdapter;
12
+ from: string;
13
+ resetUrl: string;
14
+ }): Promise<void>;
15
+ /**
16
+ * Complete a password reset using the raw token from the reset email.
17
+ *
18
+ * @throws Error if the token is invalid or expired
19
+ */
20
+ export declare function resetPassword(params: {
21
+ rawToken: string;
22
+ newPassword: string;
23
+ db: DatabaseAdapter;
24
+ saltRounds?: number;
25
+ }): Promise<void>;
26
+ //# sourceMappingURL=passwordReset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passwordReset.d.ts","sourceRoot":"","sources":["../../src/features/passwordReset.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAA;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAA;AAOlE;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAC,MAAM,EAAE;IAChD,KAAK,EAAE,MAAM,CAAA;IACb,EAAE,EAAE,eAAe,CAAA;IACnB,aAAa,EAAE,YAAY,CAAA;IAC3B,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,MAAM,CAAA;CACjB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgChB;AAED;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE;IAC1C,QAAQ,EAAE,MAAM,CAAA;IAChB,WAAW,EAAE,MAAM,CAAA;IACnB,EAAE,EAAE,eAAe,CAAA;IACnB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBhB"}
@@ -0,0 +1,57 @@
1
+ import { generateOpaqueToken, hashToken } from '../utils/token.js';
2
+ import { hashPassword } from '../utils/password.js';
3
+ const PASSWORD_RESET_TTL_MS = 60 * 60 * 1000; // 1 hour
4
+ /**
5
+ * Initiate a password reset flow.
6
+ * Always returns successfully even if the email is not found — prevents email enumeration.
7
+ * Callers should catch and swallow errors from the email send step if needed.
8
+ */
9
+ export async function createPasswordReset(params) {
10
+ const { email, db, emailProvider, from, resetUrl } = params;
11
+ // Always returns 200 — do not reveal whether the email exists
12
+ const user = await db.findUserByEmail(email);
13
+ if (!user)
14
+ return;
15
+ const rawToken = generateOpaqueToken();
16
+ const hashedToken = hashToken(rawToken);
17
+ await db.createToken({
18
+ userId: user.id,
19
+ type: 'PASSWORD_RESET',
20
+ token: hashedToken,
21
+ expiresAt: new Date(Date.now() + PASSWORD_RESET_TTL_MS),
22
+ });
23
+ const link = `${resetUrl}?token=${rawToken}`;
24
+ await emailProvider.send({
25
+ from,
26
+ to: email,
27
+ subject: 'Reset your password',
28
+ html: `
29
+ <p>Hello,</p>
30
+ <p>We received a request to reset your password. Click the link below to proceed:</p>
31
+ <p><a href="${link}">${link}</a></p>
32
+ <p>This link expires in 1 hour.</p>
33
+ <p>If you did not request a password reset, you can ignore this email.</p>
34
+ `,
35
+ text: `Reset your password by visiting: ${link}\n\nThis link expires in 1 hour.`,
36
+ });
37
+ }
38
+ /**
39
+ * Complete a password reset using the raw token from the reset email.
40
+ *
41
+ * @throws Error if the token is invalid or expired
42
+ */
43
+ export async function resetPassword(params) {
44
+ const { rawToken, newPassword, db, saltRounds } = params;
45
+ const tokenRecord = await db.findToken(rawToken, 'PASSWORD_RESET');
46
+ if (!tokenRecord) {
47
+ throw new Error('Invalid or expired reset token');
48
+ }
49
+ if (tokenRecord.expiresAt < new Date()) {
50
+ await db.deleteToken(tokenRecord.id);
51
+ throw new Error('Invalid or expired reset token');
52
+ }
53
+ const passwordHash = await hashPassword(newPassword, saltRounds);
54
+ await db.updateUser(tokenRecord.userId, { passwordHash });
55
+ await db.deleteToken(tokenRecord.id);
56
+ }
57
+ //# sourceMappingURL=passwordReset.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passwordReset.js","sourceRoot":"","s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,EAAE,EAAE,UAAU,EAAE,GAAG,MAAM,CAAA;IAExD,MAAM,WAAW,GAAiB,MAAM,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAA;IAEhF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;IACnD,CAAC;IAED,IAAI,WAAW,CAAC,SAAS,GAAG,IAAI,IAAI,EAAE,EAAE,CAAC;QACvC,MAAM,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;QACpC,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAA;IACnD,CAAC;IAED,MAAM,YAAY,GAAG,MAAM,YAAY,CAAC,WAAW,EAAE,UAAU,CAAC,CAAA;IAChE,MAAM,EAAE,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,YAAY,EAAE,CAAC,CAAA;IACzD,MAAM,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;AACtC,CAAC"}
@@ -0,0 +1,13 @@
1
+ export type { User, Token, TokenType, CreateUserInput, CreateTokenInput, PublicUser, SessionConfig, EmailConfig, AuthCallbacks, AuthCoreConfig, } from './types.js';
2
+ export type { DatabaseAdapter } from './adapters/database.interface.js';
3
+ export type { EmailAdapter } from './adapters/email.interface.js';
4
+ export { hashPassword, verifyPassword } from './utils/password.js';
5
+ export { generateOpaqueToken, hashToken, safeCompareTokens, signJwt, verifyJwt, } from './utils/token.js';
6
+ export type { JwtPayload } from './utils/token.js';
7
+ export { registerSchema, loginSchema, forgotPasswordSchema, resetPasswordSchema, verifyEmailSchema, } from './utils/validation.js';
8
+ export type { RegisterInput, LoginInput, ForgotPasswordInput, ResetPasswordInput, VerifyEmailInput, } from './utils/validation.js';
9
+ export { createEmailVerification, verifyEmail } from './features/emailVerification.js';
10
+ export { createPasswordReset, resetPassword } from './features/passwordReset.js';
11
+ export { createAuth, AuthError } from './auth.js';
12
+ export type { AuthCore } from './auth.js';
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,YAAY,EACV,IAAI,EACJ,KAAK,EACL,SAAS,EACT,eAAe,EACf,gBAAgB,EAChB,UAAU,EACV,aAAa,EACb,WAAW,EACX,aAAa,EACb,cAAc,GACf,MAAM,YAAY,CAAA;AAGnB,YAAY,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAA;AACvE,YAAY,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAGjE,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAClE,OAAO,EACL,mBAAmB,EACnB,SAAS,EACT,iBAAiB,EACjB,OAAO,EACP,SAAS,GACV,MAAM,kBAAkB,CAAA;AACzB,YAAY,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAClD,OAAO,EACL,cAAc,EACd,WAAW,EACX,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,uBAAuB,CAAA;AAC9B,YAAY,EACV,aAAa,EACb,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,uBAAuB,CAAA;AAG9B,OAAO,EAAE,uBAAuB,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAA;AACtF,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAGhF,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACjD,YAAY,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // Utilities
2
+ export { hashPassword, verifyPassword } from './utils/password.js';
3
+ export { generateOpaqueToken, hashToken, safeCompareTokens, signJwt, verifyJwt, } from './utils/token.js';
4
+ export { registerSchema, loginSchema, forgotPasswordSchema, resetPasswordSchema, verifyEmailSchema, } from './utils/validation.js';
5
+ // Features
6
+ export { createEmailVerification, verifyEmail } from './features/emailVerification.js';
7
+ export { createPasswordReset, resetPassword } from './features/passwordReset.js';
8
+ // Auth factory
9
+ export { createAuth, AuthError } from './auth.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAkBA,YAAY;AACZ,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAClE,OAAO,EACL,mBAAmB,EACnB,SAAS,EACT,iBAAiB,EACjB,OAAO,EACP,SAAS,GACV,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EACL,cAAc,EACd,WAAW,EACX,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,uBAAuB,CAAA;AAS9B,WAAW;AACX,OAAO,EAAE,uBAAuB,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAA;AACtF,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAEhF,eAAe;AACf,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Core domain types for AuthCore.
3
+ * These are the canonical shapes that adapters must produce/consume.
4
+ */
5
+ export type TokenType = 'EMAIL_VERIFICATION' | 'PASSWORD_RESET' | 'SESSION';
6
+ /** A user record as stored in the database. */
7
+ export interface User {
8
+ id: string;
9
+ email: string;
10
+ passwordHash: string;
11
+ emailVerified: boolean;
12
+ createdAt: Date;
13
+ updatedAt: Date;
14
+ }
15
+ /** A token record as stored in the database. The `token` field is the hashed value. */
16
+ export interface Token {
17
+ id: string;
18
+ userId: string;
19
+ type: TokenType;
20
+ /** SHA-256 hash of the raw token. Never the raw token itself. */
21
+ token: string;
22
+ expiresAt: Date;
23
+ createdAt: Date;
24
+ }
25
+ /** Input shape for creating a new user. */
26
+ export interface CreateUserInput {
27
+ email: string;
28
+ passwordHash: string;
29
+ }
30
+ /** Input shape for creating a new token. */
31
+ export interface CreateTokenInput {
32
+ userId: string;
33
+ type: TokenType;
34
+ /** SHA-256 hash of the raw token. */
35
+ token: string;
36
+ expiresAt: Date;
37
+ }
38
+ /** Safe user shape returned to callers (no passwordHash). */
39
+ export type PublicUser = Omit<User, 'passwordHash'>;
40
+ /** Configuration for the AuthCore session/JWT strategy. */
41
+ export interface SessionConfig {
42
+ strategy: 'jwt';
43
+ secret: string;
44
+ expiresIn?: string;
45
+ }
46
+ /** Configuration for email features. */
47
+ export interface EmailConfig {
48
+ provider: import('./adapters/email.interface.js').EmailAdapter;
49
+ from: string;
50
+ }
51
+ /** Optional lifecycle callbacks. */
52
+ export interface AuthCallbacks {
53
+ onSignUp?: (user: PublicUser) => void | Promise<void>;
54
+ onSignIn?: (user: PublicUser) => void | Promise<void>;
55
+ onSignOut?: (userId: string) => void | Promise<void>;
56
+ onPasswordReset?: (user: PublicUser) => void | Promise<void>;
57
+ }
58
+ /** Top-level AuthCore configuration object. */
59
+ export interface AuthCoreConfig {
60
+ db: import('./adapters/database.interface.js').DatabaseAdapter;
61
+ session: SessionConfig;
62
+ email?: EmailConfig;
63
+ features?: Array<'emailVerification' | 'passwordReset'>;
64
+ mode?: 'api' | 'monorepo' | 'auto';
65
+ password?: {
66
+ minLength?: number;
67
+ saltRounds?: number;
68
+ };
69
+ callbacks?: AuthCallbacks;
70
+ }
71
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,MAAM,SAAS,GAAG,oBAAoB,GAAG,gBAAgB,GAAG,SAAS,CAAA;AAE3E,+CAA+C;AAC/C,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;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rD,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACpD,eAAe,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC7D;AAED,+CAA+C;AAC/C,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,OAAO,kCAAkC,EAAE,eAAe,CAAA;IAC9D,OAAO,EAAE,aAAa,CAAA;IACtB,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB,QAAQ,CAAC,EAAE,KAAK,CAAC,mBAAmB,GAAG,eAAe,CAAC,CAAA;IACvD,IAAI,CAAC,EAAE,KAAK,GAAG,UAAU,GAAG,MAAM,CAAA;IAClC,QAAQ,CAAC,EAAE;QACT,SAAS,CAAC,EAAE,MAAM,CAAA;QAClB,UAAU,CAAC,EAAE,MAAM,CAAA;KACpB,CAAA;IACD,SAAS,CAAC,EAAE,aAAa,CAAA;CAC1B"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Core domain types for AuthCore.
3
+ * These are the canonical shapes that adapters must produce/consume.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Hash a plain-text password using bcrypt.
3
+ *
4
+ * @param password - Plain-text password. Never stored or logged.
5
+ * @param saltRounds - bcrypt cost factor (default: 12, minimum: 12)
6
+ * @returns bcrypt hash string
7
+ */
8
+ export declare function hashPassword(password: string, saltRounds?: number): Promise<string>;
9
+ /**
10
+ * Verify a plain-text password against a bcrypt hash.
11
+ * Uses bcrypt's internal timing-safe comparison.
12
+ *
13
+ * @param password - Plain-text candidate password
14
+ * @param hash - bcrypt hash from the database
15
+ * @returns true if the password matches the hash
16
+ */
17
+ export declare function verifyPassword(password: string, hash: string): Promise<boolean>;
18
+ //# sourceMappingURL=password.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"password.d.ts","sourceRoot":"","sources":["../../src/utils/password.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,MAAM,EAChB,UAAU,GAAE,MAA4B,GACvC,OAAO,CAAC,MAAM,CAAC,CAGjB;AAED;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAErF"}
@@ -0,0 +1,25 @@
1
+ import bcrypt from 'bcrypt';
2
+ const DEFAULT_SALT_ROUNDS = 12;
3
+ /**
4
+ * Hash a plain-text password using bcrypt.
5
+ *
6
+ * @param password - Plain-text password. Never stored or logged.
7
+ * @param saltRounds - bcrypt cost factor (default: 12, minimum: 12)
8
+ * @returns bcrypt hash string
9
+ */
10
+ export async function hashPassword(password, saltRounds = DEFAULT_SALT_ROUNDS) {
11
+ const rounds = Math.max(saltRounds, DEFAULT_SALT_ROUNDS);
12
+ return bcrypt.hash(password, rounds);
13
+ }
14
+ /**
15
+ * Verify a plain-text password against a bcrypt hash.
16
+ * Uses bcrypt's internal timing-safe comparison.
17
+ *
18
+ * @param password - Plain-text candidate password
19
+ * @param hash - bcrypt hash from the database
20
+ * @returns true if the password matches the hash
21
+ */
22
+ export async function verifyPassword(password, hash) {
23
+ return bcrypt.compare(password, hash);
24
+ }
25
+ //# sourceMappingURL=password.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"password.js","sourceRoot":"","sources":["../../src/utils/password.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAE3B,MAAM,mBAAmB,GAAG,EAAE,CAAA;AAE9B;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,QAAgB,EAChB,aAAqB,mBAAmB;IAExC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,mBAAmB,CAAC,CAAA;IACxD,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;AACtC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,QAAgB,EAAE,IAAY;IACjE,OAAO,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;AACvC,CAAC"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Generate a cryptographically random opaque token.
3
+ * Returns a 64-character hex string (256 bits of entropy).
4
+ */
5
+ export declare function generateOpaqueToken(): string;
6
+ /**
7
+ * Hash a raw token using SHA-256 for safe database storage.
8
+ * Store the hash; return the raw token to the user.
9
+ *
10
+ * @param rawToken - The raw token to hash
11
+ * @returns SHA-256 hex digest
12
+ */
13
+ export declare function hashToken(rawToken: string): string;
14
+ /**
15
+ * Timing-safe comparison of two token strings.
16
+ * Prevents timing attacks when comparing tokens.
17
+ *
18
+ * @returns true if the strings are equal
19
+ */
20
+ export declare function safeCompareTokens(a: string, b: string): boolean;
21
+ export interface JwtPayload {
22
+ sub: string;
23
+ email: string;
24
+ iat?: number;
25
+ exp?: number;
26
+ }
27
+ /**
28
+ * Sign a JWT access token.
29
+ *
30
+ * @param payload - Data to encode in the token
31
+ * @param secret - Signing secret
32
+ * @param expiresIn - Expiry duration (e.g. '7d', '1h')
33
+ * @returns Signed JWT string
34
+ */
35
+ export declare function signJwt(payload: Omit<JwtPayload, 'iat' | 'exp'>, secret: string, expiresIn?: string): string;
36
+ /**
37
+ * Verify and decode a JWT.
38
+ *
39
+ * @param token - JWT string to verify
40
+ * @param secret - Signing secret
41
+ * @returns Decoded payload, or null if invalid/expired
42
+ */
43
+ export declare function verifyJwt(token: string, secret: string): JwtPayload | null;
44
+ //# sourceMappingURL=token.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/utils/token.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAE5C;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAElD;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAK/D;AAED,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,MAAM,CAAA;IACb,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,GAAG,CAAC,EAAE,MAAM,CAAA;CACb;AAED;;;;;;;GAOG;AACH,wBAAgB,OAAO,CACrB,OAAO,EAAE,IAAI,CAAC,UAAU,EAAE,KAAK,GAAG,KAAK,CAAC,EACxC,MAAM,EAAE,MAAM,EACd,SAAS,SAAO,GACf,MAAM,CAIR;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAQ1E"}
@@ -0,0 +1,64 @@
1
+ import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
2
+ import jwt from 'jsonwebtoken';
3
+ /**
4
+ * Generate a cryptographically random opaque token.
5
+ * Returns a 64-character hex string (256 bits of entropy).
6
+ */
7
+ export function generateOpaqueToken() {
8
+ return randomBytes(32).toString('hex');
9
+ }
10
+ /**
11
+ * Hash a raw token using SHA-256 for safe database storage.
12
+ * Store the hash; return the raw token to the user.
13
+ *
14
+ * @param rawToken - The raw token to hash
15
+ * @returns SHA-256 hex digest
16
+ */
17
+ export function hashToken(rawToken) {
18
+ return createHash('sha256').update(rawToken).digest('hex');
19
+ }
20
+ /**
21
+ * Timing-safe comparison of two token strings.
22
+ * Prevents timing attacks when comparing tokens.
23
+ *
24
+ * @returns true if the strings are equal
25
+ */
26
+ export function safeCompareTokens(a, b) {
27
+ if (a.length !== b.length)
28
+ return false;
29
+ const bufA = Buffer.from(a, 'utf8');
30
+ const bufB = Buffer.from(b, 'utf8');
31
+ return timingSafeEqual(bufA, bufB);
32
+ }
33
+ /**
34
+ * Sign a JWT access token.
35
+ *
36
+ * @param payload - Data to encode in the token
37
+ * @param secret - Signing secret
38
+ * @param expiresIn - Expiry duration (e.g. '7d', '1h')
39
+ * @returns Signed JWT string
40
+ */
41
+ export function signJwt(payload, secret, expiresIn = '7d') {
42
+ // Cast options to avoid exactOptionalPropertyTypes conflict with the jwt overloads
43
+ const options = { algorithm: 'HS256', expiresIn };
44
+ return jwt.sign(payload, secret, options);
45
+ }
46
+ /**
47
+ * Verify and decode a JWT.
48
+ *
49
+ * @param token - JWT string to verify
50
+ * @param secret - Signing secret
51
+ * @returns Decoded payload, or null if invalid/expired
52
+ */
53
+ export function verifyJwt(token, secret) {
54
+ try {
55
+ const decoded = jwt.verify(token, secret, { algorithms: ['HS256'] });
56
+ if (typeof decoded === 'string')
57
+ return null;
58
+ return decoded;
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ //# sourceMappingURL=token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.js","sourceRoot":"","sources":["../../src/utils/token.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AACtE,OAAO,GAAG,MAAM,cAAc,CAAA;AAE9B;;;GAGG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;AACxC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,QAAgB;IACxC,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;AAC5D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,CAAS,EAAE,CAAS;IACpD,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAA;IACvC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;IACnC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;IACnC,OAAO,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;AACpC,CAAC;AASD;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CACrB,OAAwC,EACxC,MAAc,EACd,SAAS,GAAG,IAAI;IAEhB,mFAAmF;IACnF,MAAM,OAAO,GAAG,EAAE,SAAS,EAAE,OAAgB,EAAE,SAAS,EAAE,CAAA;IAC1D,OAAO,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAA0B,CAAC,CAAA;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,KAAa,EAAE,MAAc;IACrD,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,UAAU,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QACpE,IAAI,OAAO,OAAO,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAA;QAC5C,OAAO,OAAqB,CAAA;IAC9B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC"}
@@ -0,0 +1,56 @@
1
+ import { z } from 'zod';
2
+ /** Schema for POST /register */
3
+ export declare const registerSchema: (minPasswordLength?: number) => z.ZodObject<{
4
+ email: z.ZodString;
5
+ password: z.ZodString;
6
+ }, "strip", z.ZodTypeAny, {
7
+ email: string;
8
+ password: string;
9
+ }, {
10
+ email: string;
11
+ password: string;
12
+ }>;
13
+ /** Schema for POST /login */
14
+ export declare const loginSchema: z.ZodObject<{
15
+ email: z.ZodString;
16
+ password: z.ZodString;
17
+ }, "strip", z.ZodTypeAny, {
18
+ email: string;
19
+ password: string;
20
+ }, {
21
+ email: string;
22
+ password: string;
23
+ }>;
24
+ /** Schema for POST /forgot-password */
25
+ export declare const forgotPasswordSchema: z.ZodObject<{
26
+ email: z.ZodString;
27
+ }, "strip", z.ZodTypeAny, {
28
+ email: string;
29
+ }, {
30
+ email: string;
31
+ }>;
32
+ /** Schema for POST /reset-password */
33
+ export declare const resetPasswordSchema: (minPasswordLength?: number) => z.ZodObject<{
34
+ token: z.ZodString;
35
+ password: z.ZodString;
36
+ }, "strip", z.ZodTypeAny, {
37
+ password: string;
38
+ token: string;
39
+ }, {
40
+ password: string;
41
+ token: string;
42
+ }>;
43
+ /** Schema for POST /verify-email */
44
+ export declare const verifyEmailSchema: z.ZodObject<{
45
+ token: z.ZodString;
46
+ }, "strip", z.ZodTypeAny, {
47
+ token: string;
48
+ }, {
49
+ token: string;
50
+ }>;
51
+ export type RegisterInput = z.infer<ReturnType<typeof registerSchema>>;
52
+ export type LoginInput = z.infer<typeof loginSchema>;
53
+ export type ForgotPasswordInput = z.infer<typeof forgotPasswordSchema>;
54
+ export type ResetPasswordInput = z.infer<ReturnType<typeof resetPasswordSchema>>;
55
+ export type VerifyEmailInput = z.infer<typeof verifyEmailSchema>;
56
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAUvB,gCAAgC;AAChC,eAAO,MAAM,cAAc,GAAI,0BAAqB;;;;;;;;;EAIhD,CAAA;AAEJ,6BAA6B;AAC7B,eAAO,MAAM,WAAW;;;;;;;;;EAGtB,CAAA;AAEF,uCAAuC;AACvC,eAAO,MAAM,oBAAoB;;;;;;EAE/B,CAAA;AAEF,sCAAsC;AACtC,eAAO,MAAM,mBAAmB,GAAI,0BAAqB;;;;;;;;;EAIrD,CAAA;AAEJ,oCAAoC;AACpC,eAAO,MAAM,iBAAiB;;;;;;EAE5B,CAAA;AAEF,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC,CAAA;AACtE,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAA;AACpD,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAA;AACtE,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC,CAAA;AAChF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAA"}
@@ -0,0 +1,30 @@
1
+ import { z } from 'zod';
2
+ const emailSchema = z.string().email('Invalid email address');
3
+ const passwordSchema = (minLength) => z
4
+ .string()
5
+ .min(minLength, `Password must be at least ${minLength} characters`)
6
+ .max(72, 'Password must be at most 72 characters'); // bcrypt max
7
+ /** Schema for POST /register */
8
+ export const registerSchema = (minPasswordLength = 8) => z.object({
9
+ email: emailSchema,
10
+ password: passwordSchema(minPasswordLength),
11
+ });
12
+ /** Schema for POST /login */
13
+ export const loginSchema = z.object({
14
+ email: emailSchema,
15
+ password: z.string().min(1, 'Password is required'),
16
+ });
17
+ /** Schema for POST /forgot-password */
18
+ export const forgotPasswordSchema = z.object({
19
+ email: emailSchema,
20
+ });
21
+ /** Schema for POST /reset-password */
22
+ export const resetPasswordSchema = (minPasswordLength = 8) => z.object({
23
+ token: z.string().min(1, 'Token is required'),
24
+ password: passwordSchema(minPasswordLength),
25
+ });
26
+ /** Schema for POST /verify-email */
27
+ export const verifyEmailSchema = z.object({
28
+ token: z.string().min(1, 'Token is required'),
29
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iB,CAAC;CAC5C,CAAC,CAAA;AAEJ,oCAAoC;AACpC,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACxC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,mBAAmB,CAAC;CAC9C,CAAC,CAAA"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@authcore/core",
3
+ "version": "0.5.0",
4
+ "description": "Framework-agnostic authentication core for AuthCore",
5
+ "license": "MIT",
6
+ "author": "David Ouatedem",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/david-ouatedem/auth-core",
10
+ "directory": "packages/core"
11
+ },
12
+ "keywords": [
13
+ "auth",
14
+ "authentication",
15
+ "authcore",
16
+ "jwt",
17
+ "bcrypt"
18
+ ],
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "type": "module",
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "import": "./dist/index.js",
31
+ "types": "./dist/index.d.ts"
32
+ }
33
+ },
34
+ "dependencies": {
35
+ "bcrypt": "^5.1.1",
36
+ "jsonwebtoken": "^9.0.2",
37
+ "zod": "^3.23.0"
38
+ },
39
+ "devDependencies": {
40
+ "@types/bcrypt": "^5.0.2",
41
+ "@types/jsonwebtoken": "^9.0.6",
42
+ "@types/node": "^20.0.0",
43
+ "typescript": "^5.4.0",
44
+ "vitest": "^1.6.0"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc",
48
+ "dev": "tsc --watch",
49
+ "test": "vitest run",
50
+ "test:watch": "vitest"
51
+ }
52
+ }