@tylix/auth 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/package.json +8 -6
- package/src/cookies/authCookies.d.ts +16 -0
- package/src/generators/AuthGenerator.d.ts +15 -0
- package/src/generators/AuthGenerator.js +25 -28
- package/src/generators/templates/auth-controller-ts.tyx +232 -0
- package/src/generators/templates/auth-validator-ts.tyx +48 -0
- package/src/generators/templates/mailer-ts.tyx +28 -0
- package/src/generators/templates/password-reset-migration-ts.tyx +26 -0
- package/src/generators/templates/password-reset-model-ts.tyx +55 -0
- package/src/generators/templates/refresh-token-migration-ts.tyx +26 -0
- package/src/generators/templates/refresh-token-model-ts.tyx +65 -0
- package/src/generators/templates/user-migration-ts.tyx +26 -0
- package/src/generators/templates/user-model-ts.tyx +75 -0
- package/src/index.d.ts +5 -0
- package/src/password/hashPassword.d.ts +2 -0
- package/src/password/hashPassword.js +22 -11
- package/src/rateLimiter/loginRateLimiter.d.ts +8 -0
- package/src/token/signToken.d.ts +22 -0
package/README.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# @tylix/auth
|
|
2
|
+
|
|
3
|
+
Authentication primitives for Tylix applications — password hashing,
|
|
4
|
+
tokens, cookies, and rate limiting.
|
|
5
|
+
|
|
6
|
+
## What's included
|
|
7
|
+
|
|
8
|
+
- `hashPassword` — password hashing
|
|
9
|
+
- `signToken` — auth token signing
|
|
10
|
+
- `authCookies` — cookie helpers for session/auth state
|
|
11
|
+
- `loginRateLimiter` — rate limiting for login attempts
|
|
12
|
+
- `AuthGenerator` — scaffolds auth routes/controllers/views via
|
|
13
|
+
`tylix make:auth`
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import { hashPassword, signToken } from '@tylix/auth'
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or scaffold auth into a project:
|
package/package.json
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./src/index.js",
|
|
6
|
+
"types": "./src/index.d.ts",
|
|
6
7
|
"scripts": {
|
|
7
8
|
"test": "node --test src/**/*.test.js"
|
|
8
9
|
},
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@tylix/core": "^0.1.0",
|
|
12
|
+
"@tylix/generator": "^0.1.0",
|
|
13
|
+
"@tylix/orm": "^0.1.0",
|
|
14
|
+
"@tylix/shared": "^0.1.0"
|
|
15
|
+
}
|
|
14
16
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { TylixRequest, TylixResponse } from '@tylix/core'
|
|
2
|
+
|
|
3
|
+
export declare const ACCESS_TOKEN_COOKIE: string
|
|
4
|
+
export declare const REFRESH_TOKEN_COOKIE: string
|
|
5
|
+
|
|
6
|
+
export interface SetAuthCookiesOptions {
|
|
7
|
+
accessToken?: string
|
|
8
|
+
refreshToken?: string
|
|
9
|
+
accessTtlSeconds?: number
|
|
10
|
+
refreshTtlSeconds?: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export declare function setAuthCookies(res: TylixResponse, options?: SetAuthCookiesOptions): void
|
|
14
|
+
export declare function clearAuthCookies(res: TylixResponse): void
|
|
15
|
+
export declare function readAccessToken(req: TylixRequest): string | null
|
|
16
|
+
export declare function readRefreshToken(req: TylixRequest): string | null
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface AuthGeneratorResults {
|
|
2
|
+
userModel: string
|
|
3
|
+
refreshTokenModel: string
|
|
4
|
+
passwordResetModel: string
|
|
5
|
+
validator: string
|
|
6
|
+
controller: string
|
|
7
|
+
mailer: string
|
|
8
|
+
userMigration: string
|
|
9
|
+
refreshTokenMigration: string
|
|
10
|
+
passwordResetMigration: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export declare class AuthGenerator {
|
|
14
|
+
generate(baseDir: string): Promise<AuthGeneratorResults>
|
|
15
|
+
}
|
|
@@ -1,14 +1,11 @@
|
|
|
1
1
|
import fs from 'node:fs/promises'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import { fileURLToPath } from 'node:url'
|
|
4
|
-
import { writeFile } from '@tylix/shared'
|
|
4
|
+
import { writeFile, detectLanguage } from '@tylix/shared'
|
|
5
5
|
|
|
6
6
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
7
7
|
const TEMPLATES_DIR = path.join(__dirname, 'templates')
|
|
8
8
|
|
|
9
|
-
// Small offsets so migration filenames sort in dependency-safe order
|
|
10
|
-
// (users -> refresh_tokens -> password_resets) even when generated
|
|
11
|
-
// within the same millisecond.
|
|
12
9
|
function timestampSuffix(offsetMs = 0) {
|
|
13
10
|
return new Date(Date.now() + offsetMs)
|
|
14
11
|
.toISOString()
|
|
@@ -16,49 +13,49 @@ function timestampSuffix(offsetMs = 0) {
|
|
|
16
13
|
.slice(0, 14)
|
|
17
14
|
}
|
|
18
15
|
|
|
19
|
-
// NOTE: this no longer writes a per-project requireAuth middleware file.
|
|
20
|
-
// requireAuth already exists in the http runtime package
|
|
21
|
-
// (app/../http/requireAuth.js equivalent) and was updated to also accept
|
|
22
|
-
// the access-token cookie, so there's nothing feature-specific to
|
|
23
|
-
// generate here anymore -- see ROUTES_TO_WIRE_IN.md.
|
|
24
16
|
export class AuthGenerator {
|
|
25
17
|
async generate(baseDir) {
|
|
26
18
|
const results = {}
|
|
27
|
-
const
|
|
19
|
+
const language = await detectLanguage(baseDir)
|
|
20
|
+
const ext = language === 'typescript' ? 'ts' : 'js'
|
|
21
|
+
const suffix = language === 'typescript' ? '-ts' : ''
|
|
22
|
+
|
|
23
|
+
const read = (name) =>
|
|
24
|
+
fs.readFile(path.join(TEMPLATES_DIR, `${name}${suffix}.tyx`), 'utf-8')
|
|
28
25
|
|
|
29
26
|
results.userModel = await writeFile(
|
|
30
|
-
path.join(baseDir, 'app', 'models',
|
|
31
|
-
await read('user-model
|
|
27
|
+
path.join(baseDir, 'app', 'models', `User.${ext}`),
|
|
28
|
+
await read('user-model'),
|
|
32
29
|
{ overwrite: true },
|
|
33
30
|
)
|
|
34
31
|
|
|
35
32
|
results.refreshTokenModel = await writeFile(
|
|
36
|
-
path.join(baseDir, 'app', 'models',
|
|
37
|
-
await read('refresh-token-model
|
|
33
|
+
path.join(baseDir, 'app', 'models', `RefreshToken.${ext}`),
|
|
34
|
+
await read('refresh-token-model'),
|
|
38
35
|
{ overwrite: true },
|
|
39
36
|
)
|
|
40
37
|
|
|
41
38
|
results.passwordResetModel = await writeFile(
|
|
42
|
-
path.join(baseDir, 'app', 'models',
|
|
43
|
-
await read('password-reset-model
|
|
39
|
+
path.join(baseDir, 'app', 'models', `PasswordReset.${ext}`),
|
|
40
|
+
await read('password-reset-model'),
|
|
44
41
|
{ overwrite: true },
|
|
45
42
|
)
|
|
46
43
|
|
|
47
44
|
results.validator = await writeFile(
|
|
48
|
-
path.join(baseDir, 'app', 'validators',
|
|
49
|
-
await read('auth-validator
|
|
45
|
+
path.join(baseDir, 'app', 'validators', `AuthValidator.${ext}`),
|
|
46
|
+
await read('auth-validator'),
|
|
50
47
|
{ overwrite: true },
|
|
51
48
|
)
|
|
52
49
|
|
|
53
50
|
results.controller = await writeFile(
|
|
54
|
-
path.join(baseDir, 'app', 'controllers',
|
|
55
|
-
await read('auth-controller
|
|
51
|
+
path.join(baseDir, 'app', 'controllers', `AuthController.${ext}`),
|
|
52
|
+
await read('auth-controller'),
|
|
56
53
|
{ overwrite: true },
|
|
57
54
|
)
|
|
58
55
|
|
|
59
56
|
results.mailer = await writeFile(
|
|
60
|
-
path.join(baseDir, 'app', 'mail',
|
|
61
|
-
await read('mailer
|
|
57
|
+
path.join(baseDir, 'app', 'mail', `mailer.${ext}`),
|
|
58
|
+
await read('mailer'),
|
|
62
59
|
{ overwrite: true },
|
|
63
60
|
)
|
|
64
61
|
|
|
@@ -67,9 +64,9 @@ export class AuthGenerator {
|
|
|
67
64
|
baseDir,
|
|
68
65
|
'database',
|
|
69
66
|
'migrations',
|
|
70
|
-
`${timestampSuffix(0)}_create_users_table
|
|
67
|
+
`${timestampSuffix(0)}_create_users_table.${ext}`,
|
|
71
68
|
),
|
|
72
|
-
await read('user-migration
|
|
69
|
+
await read('user-migration'),
|
|
73
70
|
{ overwrite: true },
|
|
74
71
|
)
|
|
75
72
|
|
|
@@ -78,9 +75,9 @@ export class AuthGenerator {
|
|
|
78
75
|
baseDir,
|
|
79
76
|
'database',
|
|
80
77
|
'migrations',
|
|
81
|
-
`${timestampSuffix(1000)}_create_refresh_tokens_table
|
|
78
|
+
`${timestampSuffix(1000)}_create_refresh_tokens_table.${ext}`,
|
|
82
79
|
),
|
|
83
|
-
await read('refresh-token-migration
|
|
80
|
+
await read('refresh-token-migration'),
|
|
84
81
|
{ overwrite: true },
|
|
85
82
|
)
|
|
86
83
|
|
|
@@ -89,9 +86,9 @@ export class AuthGenerator {
|
|
|
89
86
|
baseDir,
|
|
90
87
|
'database',
|
|
91
88
|
'migrations',
|
|
92
|
-
`${timestampSuffix(2000)}_create_password_resets_table
|
|
89
|
+
`${timestampSuffix(2000)}_create_password_resets_table.${ext}`,
|
|
93
90
|
),
|
|
94
|
-
await read('password-reset-migration
|
|
91
|
+
await read('password-reset-migration'),
|
|
95
92
|
{ overwrite: true },
|
|
96
93
|
)
|
|
97
94
|
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.1.0
|
|
6
|
+
* Feature: Auth
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { TylixRequest, TylixResponse } from "@tylix/core";
|
|
12
|
+
import { User } from "../models/User.js";
|
|
13
|
+
import { RefreshToken } from "../models/RefreshToken.js";
|
|
14
|
+
import { PasswordReset } from "../models/PasswordReset.js";
|
|
15
|
+
import {
|
|
16
|
+
verifyPassword,
|
|
17
|
+
signToken,
|
|
18
|
+
verifyToken,
|
|
19
|
+
setAuthCookies,
|
|
20
|
+
clearAuthCookies,
|
|
21
|
+
readRefreshToken,
|
|
22
|
+
checkLoginAllowed,
|
|
23
|
+
recordFailedLogin,
|
|
24
|
+
clearLoginAttempts,
|
|
25
|
+
} from "@tylix/auth";
|
|
26
|
+
import { sendVerificationEmail, sendPasswordResetEmail } from "../mail/mailer.js";
|
|
27
|
+
import {
|
|
28
|
+
validateRegister,
|
|
29
|
+
validateLogin,
|
|
30
|
+
validateForgotPassword,
|
|
31
|
+
validateResetPassword,
|
|
32
|
+
} from "../validators/AuthValidator.js";
|
|
33
|
+
|
|
34
|
+
const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 15 * 60;
|
|
35
|
+
|
|
36
|
+
interface AuthControllerOptions {
|
|
37
|
+
secret: string;
|
|
38
|
+
tokenExpiresInSeconds?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class AuthController {
|
|
42
|
+
secret: string;
|
|
43
|
+
accessTokenTtlSeconds: number;
|
|
44
|
+
|
|
45
|
+
constructor({ secret, tokenExpiresInSeconds }: AuthControllerOptions) {
|
|
46
|
+
this.secret = secret;
|
|
47
|
+
this.accessTokenTtlSeconds = tokenExpiresInSeconds ?? DEFAULT_ACCESS_TOKEN_TTL_SECONDS;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async register(req: TylixRequest, res: TylixResponse) {
|
|
51
|
+
const result = validateRegister(req.body);
|
|
52
|
+
if (!result.valid) {
|
|
53
|
+
return res.status(422).json({ errors: result.errors });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const existing = await User.all();
|
|
57
|
+
if (existing.some((u) => u.email === req.body.email)) {
|
|
58
|
+
return res.status(422).json({ errors: { email: ["This email is already registered."] } });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const user = await User.create(req.body);
|
|
62
|
+
if (!user) {
|
|
63
|
+
return res.status(500).json({ error: "Failed to create user." });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const verificationToken = signToken(
|
|
67
|
+
{ userId: user.id, purpose: "email-verify" },
|
|
68
|
+
this.secret,
|
|
69
|
+
{ expiresInSeconds: 60 * 60 * 24 },
|
|
70
|
+
);
|
|
71
|
+
await sendVerificationEmail(user, verificationToken);
|
|
72
|
+
|
|
73
|
+
return res.status(201).json({
|
|
74
|
+
user: User.toSafeObject(user),
|
|
75
|
+
message: "Registration successful. Check your email to verify your account before logging in.",
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async login(req: TylixRequest, res: TylixResponse) {
|
|
80
|
+
const result = validateLogin(req.body);
|
|
81
|
+
if (!result.valid) {
|
|
82
|
+
return res.status(422).json({ errors: result.errors });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const rateLimitKey = req.body.email as string;
|
|
86
|
+
const { allowed, retryAfterSeconds } = checkLoginAllowed(rateLimitKey);
|
|
87
|
+
if (!allowed) {
|
|
88
|
+
return res.status(429).json({
|
|
89
|
+
error: `Too many failed attempts. Try again in ${retryAfterSeconds} seconds.`,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const users = await User.all();
|
|
94
|
+
const user = users.find((u) => u.email === req.body.email);
|
|
95
|
+
|
|
96
|
+
if (!user) {
|
|
97
|
+
recordFailedLogin(rateLimitKey);
|
|
98
|
+
return res.status(401).json({ error: "Invalid email or password." });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const passwordMatches = await verifyPassword(req.body.password as string, user.password);
|
|
102
|
+
if (!passwordMatches) {
|
|
103
|
+
recordFailedLogin(rateLimitKey);
|
|
104
|
+
return res.status(401).json({ error: "Invalid email or password." });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (!User.isEmailVerified(user)) {
|
|
108
|
+
return res.status(403).json({
|
|
109
|
+
error: "Please verify your email before logging in.",
|
|
110
|
+
code: "EMAIL_NOT_VERIFIED",
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
clearLoginAttempts(rateLimitKey);
|
|
115
|
+
|
|
116
|
+
const accessToken = signToken({ userId: user.id }, this.secret, {
|
|
117
|
+
expiresInSeconds: this.accessTokenTtlSeconds,
|
|
118
|
+
});
|
|
119
|
+
const { rawToken: refreshToken, ttlSeconds: refreshTtlSeconds } = await RefreshToken.issue(user.id);
|
|
120
|
+
|
|
121
|
+
setAuthCookies(res, {
|
|
122
|
+
accessToken,
|
|
123
|
+
refreshToken,
|
|
124
|
+
accessTtlSeconds: this.accessTokenTtlSeconds,
|
|
125
|
+
refreshTtlSeconds,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
return res.json({ user: User.toSafeObject(user) });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async refresh(req: TylixRequest, res: TylixResponse) {
|
|
132
|
+
const rawToken = readRefreshToken(req);
|
|
133
|
+
if (!rawToken) {
|
|
134
|
+
return res.status(401).json({ error: "No refresh token provided." });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const record = await RefreshToken.findValid(rawToken);
|
|
138
|
+
if (!record) {
|
|
139
|
+
clearAuthCookies(res);
|
|
140
|
+
return res.status(401).json({ error: "Refresh token invalid or expired." });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const accessToken = signToken({ userId: record.user_id }, this.secret, {
|
|
144
|
+
expiresInSeconds: this.accessTokenTtlSeconds,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
setAuthCookies(res, { accessToken, accessTtlSeconds: this.accessTokenTtlSeconds });
|
|
148
|
+
|
|
149
|
+
return res.json({ ok: true });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async logout(req: TylixRequest, res: TylixResponse) {
|
|
153
|
+
const rawToken = readRefreshToken(req);
|
|
154
|
+
if (rawToken) {
|
|
155
|
+
await RefreshToken.revoke(rawToken);
|
|
156
|
+
}
|
|
157
|
+
clearAuthCookies(res);
|
|
158
|
+
return res.status(204).send();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async me(req: TylixRequest, res: TylixResponse) {
|
|
162
|
+
const user = await User.find(req.user!.userId as number);
|
|
163
|
+
if (!user) {
|
|
164
|
+
return res.status(404).json({ error: "User not found." });
|
|
165
|
+
}
|
|
166
|
+
return res.json(User.toSafeObject(user));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async verifyEmail(req: TylixRequest, res: TylixResponse) {
|
|
170
|
+
const token = req.query.token as string;
|
|
171
|
+
if (!token) {
|
|
172
|
+
return res.status(400).json({ error: "Missing verification token." });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const { valid, payload } = verifyToken(token, this.secret);
|
|
176
|
+
if (!valid || !payload || payload.purpose !== "email-verify") {
|
|
177
|
+
return res.status(400).json({ error: "Invalid or expired verification link." });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const user = await User.find(payload.userId as number);
|
|
181
|
+
if (!user) {
|
|
182
|
+
return res.status(404).json({ error: "User not found." });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
await User.markEmailVerified(user.id);
|
|
186
|
+
return res.json({ ok: true, message: "Email verified. You can now log in." });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async forgotPassword(req: TylixRequest, res: TylixResponse) {
|
|
190
|
+
const result = validateForgotPassword(req.body);
|
|
191
|
+
if (!result.valid) {
|
|
192
|
+
return res.status(422).json({ errors: result.errors });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const users = await User.all();
|
|
196
|
+
const user = users.find((u) => u.email === req.body.email);
|
|
197
|
+
|
|
198
|
+
if (user) {
|
|
199
|
+
const { rawToken } = await PasswordReset.issue(user.email);
|
|
200
|
+
await sendPasswordResetEmail(user, rawToken);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return res.json({
|
|
204
|
+
ok: true,
|
|
205
|
+
message: "If that email is registered, a reset link has been sent.",
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async resetPassword(req: TylixRequest, res: TylixResponse) {
|
|
210
|
+
const result = validateResetPassword(req.body);
|
|
211
|
+
if (!result.valid) {
|
|
212
|
+
return res.status(422).json({ errors: result.errors });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const record = await PasswordReset.findValid(req.body.token as string, req.body.email as string);
|
|
216
|
+
if (!record) {
|
|
217
|
+
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const users = await User.all();
|
|
221
|
+
const user = users.find((u) => u.email === req.body.email);
|
|
222
|
+
if (!user) {
|
|
223
|
+
return res.status(404).json({ error: "User not found." });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
await User.updatePassword(user.id, req.body.password as string);
|
|
227
|
+
await PasswordReset.markUsed(record.id);
|
|
228
|
+
await RefreshToken.revokeAllForUser(user.id);
|
|
229
|
+
|
|
230
|
+
return res.json({ ok: true, message: "Password updated. Please log in again." });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.1.0
|
|
6
|
+
* Feature: Auth
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { validate, required, isString, isEmail } from "@tylix/shared";
|
|
12
|
+
|
|
13
|
+
const registerSchema = {
|
|
14
|
+
name: [required, isString],
|
|
15
|
+
email: [required, isString, isEmail],
|
|
16
|
+
password: [required, isString],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const loginSchema = {
|
|
20
|
+
email: [required, isString, isEmail],
|
|
21
|
+
password: [required, isString],
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const forgotPasswordSchema = {
|
|
25
|
+
email: [required, isString, isEmail],
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const resetPasswordSchema = {
|
|
29
|
+
email: [required, isString, isEmail],
|
|
30
|
+
token: [required, isString],
|
|
31
|
+
password: [required, isString],
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function validateRegister(data: Record<string, unknown>) {
|
|
35
|
+
return validate(data, registerSchema);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function validateLogin(data: Record<string, unknown>) {
|
|
39
|
+
return validate(data, loginSchema);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function validateForgotPassword(data: Record<string, unknown>) {
|
|
43
|
+
return validate(data, forgotPasswordSchema);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function validateResetPassword(data: Record<string, unknown>) {
|
|
47
|
+
return validate(data, resetPasswordSchema);
|
|
48
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.1.0
|
|
6
|
+
* Feature: Auth
|
|
7
|
+
*
|
|
8
|
+
* This file is meant to be edited — wire up a real email provider
|
|
9
|
+
* (Resend, Postmark, SES, etc.) using environment variables. Until then
|
|
10
|
+
* this just logs the links so you can click them during development.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const APP_URL = process.env.APP_URL ?? "http://localhost:3000";
|
|
14
|
+
|
|
15
|
+
interface MailableUser {
|
|
16
|
+
email: string;
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function sendVerificationEmail(user: MailableUser, token: string) {
|
|
21
|
+
const verifyUrl = `${APP_URL}/api/auth/verify-email?token=${token}`;
|
|
22
|
+
console.log(`[mailer] Verification email for ${user.email}: ${verifyUrl}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function sendPasswordResetEmail(user: MailableUser, token: string) {
|
|
26
|
+
const resetUrl = `${APP_URL}/reset-password?token=${token}&email=${encodeURIComponent(user.email)}`;
|
|
27
|
+
console.log(`[mailer] Password reset email for ${user.email}: ${resetUrl}`);
|
|
28
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.1.0
|
|
6
|
+
* Feature: PasswordReset
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Schema, CreateTableBuilder } from "@tylix/shared";
|
|
12
|
+
|
|
13
|
+
export const up = async (schema: Schema) => {
|
|
14
|
+
await schema.createTable("password_resets", (table: CreateTableBuilder) => {
|
|
15
|
+
table.increments("id");
|
|
16
|
+
table.string("email");
|
|
17
|
+
table.string("token_hash").unique();
|
|
18
|
+
table.datetime("expires_at");
|
|
19
|
+
table.datetime("used_at");
|
|
20
|
+
table.timestamps();
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const down = async (schema: Schema) => {
|
|
25
|
+
await schema.dropTable("password_resets");
|
|
26
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { Model } from "@tylix/orm";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
const RESET_TOKEN_TTL_SECONDS = 60 * 60;
|
|
5
|
+
|
|
6
|
+
export interface PasswordResetAttributes {
|
|
7
|
+
id: number;
|
|
8
|
+
email: string;
|
|
9
|
+
token_hash: string;
|
|
10
|
+
expires_at: string;
|
|
11
|
+
used_at: string | null;
|
|
12
|
+
created_at: string;
|
|
13
|
+
updated_at: string;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class PasswordReset extends Model {
|
|
18
|
+
static table = "password_resets";
|
|
19
|
+
|
|
20
|
+
static fillable: string[] = ["email", "token_hash", "expires_at", "used_at"];
|
|
21
|
+
|
|
22
|
+
static hash(rawToken: string): string {
|
|
23
|
+
return createHash("sha256").update(rawToken).digest("hex");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
static async issue(email: string) {
|
|
27
|
+
const rawToken = randomBytes(32).toString("hex");
|
|
28
|
+
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_SECONDS * 1000);
|
|
29
|
+
|
|
30
|
+
await this.create({
|
|
31
|
+
email,
|
|
32
|
+
token_hash: this.hash(rawToken),
|
|
33
|
+
expires_at: expiresAt.toISOString(),
|
|
34
|
+
used_at: null,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return { rawToken, expiresAt };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static async findValid(rawToken: string, email: string): Promise<PasswordResetAttributes | null> {
|
|
41
|
+
const tokenHash = this.hash(rawToken);
|
|
42
|
+
const all = (await this.all()) as PasswordResetAttributes[];
|
|
43
|
+
const record = all.find((r) => r.token_hash === tokenHash && r.email === email);
|
|
44
|
+
|
|
45
|
+
if (!record) return null;
|
|
46
|
+
if (record.used_at) return null;
|
|
47
|
+
if (new Date(record.expires_at).getTime() < Date.now()) return null;
|
|
48
|
+
|
|
49
|
+
return record;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
static async markUsed(id: number) {
|
|
53
|
+
return this.update(id, { used_at: new Date().toISOString() });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.1.0
|
|
6
|
+
* Feature: RefreshToken
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Schema, CreateTableBuilder } from "@tylix/shared";
|
|
12
|
+
|
|
13
|
+
export const up = async (schema: Schema) => {
|
|
14
|
+
await schema.createTable("refresh_tokens", (table: CreateTableBuilder) => {
|
|
15
|
+
table.increments("id");
|
|
16
|
+
table.integer("user_id");
|
|
17
|
+
table.string("token_hash").unique();
|
|
18
|
+
table.datetime("expires_at");
|
|
19
|
+
table.datetime("revoked_at");
|
|
20
|
+
table.timestamps();
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const down = async (schema: Schema) => {
|
|
25
|
+
await schema.dropTable("refresh_tokens");
|
|
26
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Model } from "@tylix/orm";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
const REFRESH_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 30;
|
|
5
|
+
|
|
6
|
+
export interface RefreshTokenAttributes {
|
|
7
|
+
id: number;
|
|
8
|
+
user_id: number;
|
|
9
|
+
token_hash: string;
|
|
10
|
+
expires_at: string;
|
|
11
|
+
revoked_at: string | null;
|
|
12
|
+
created_at: string;
|
|
13
|
+
updated_at: string;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class RefreshToken extends Model {
|
|
18
|
+
static table = "refresh_tokens";
|
|
19
|
+
|
|
20
|
+
static fillable: string[] = ["user_id", "token_hash", "expires_at", "revoked_at"];
|
|
21
|
+
|
|
22
|
+
static hash(rawToken: string): string {
|
|
23
|
+
return createHash("sha256").update(rawToken).digest("hex");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
static async issue(userId: number) {
|
|
27
|
+
const rawToken = randomBytes(48).toString("hex");
|
|
28
|
+
const expiresAt = new Date(Date.now() + REFRESH_TOKEN_TTL_SECONDS * 1000);
|
|
29
|
+
|
|
30
|
+
await this.create({
|
|
31
|
+
user_id: userId,
|
|
32
|
+
token_hash: this.hash(rawToken),
|
|
33
|
+
expires_at: expiresAt.toISOString(),
|
|
34
|
+
revoked_at: null,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return { rawToken, expiresAt, ttlSeconds: REFRESH_TOKEN_TTL_SECONDS };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static async findValid(rawToken: string): Promise<RefreshTokenAttributes | null> {
|
|
41
|
+
const tokenHash = this.hash(rawToken);
|
|
42
|
+
const all = (await this.all()) as RefreshTokenAttributes[];
|
|
43
|
+
const record = all.find((t) => t.token_hash === tokenHash);
|
|
44
|
+
|
|
45
|
+
if (!record) return null;
|
|
46
|
+
if (record.revoked_at) return null;
|
|
47
|
+
if (new Date(record.expires_at).getTime() < Date.now()) return null;
|
|
48
|
+
|
|
49
|
+
return record;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
static async revoke(rawToken: string) {
|
|
53
|
+
const record = await this.findValid(rawToken);
|
|
54
|
+
if (!record) return;
|
|
55
|
+
await this.update(record.id, { revoked_at: new Date().toISOString() });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
static async revokeAllForUser(userId: number) {
|
|
59
|
+
const all = (await this.all()) as RefreshTokenAttributes[];
|
|
60
|
+
const active = all.filter((t) => t.user_id === userId && !t.revoked_at);
|
|
61
|
+
await Promise.all(
|
|
62
|
+
active.map((t) => this.update(t.id, { revoked_at: new Date().toISOString() })),
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.1.0
|
|
6
|
+
* Feature: User
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Schema, CreateTableBuilder } from "@tylix/shared";
|
|
12
|
+
|
|
13
|
+
export const up = async (schema: Schema) => {
|
|
14
|
+
await schema.createTable("users", (table: CreateTableBuilder) => {
|
|
15
|
+
table.increments("id");
|
|
16
|
+
table.string("name");
|
|
17
|
+
table.string("email").unique();
|
|
18
|
+
table.string("password");
|
|
19
|
+
table.datetime("email_verified_at");
|
|
20
|
+
table.timestamps();
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const down = async (schema: Schema) => {
|
|
25
|
+
await schema.dropTable("users");
|
|
26
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.1.0
|
|
6
|
+
* Feature: User
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Model } from "@tylix/orm";
|
|
12
|
+
import { hashPassword } from "@tylix/auth";
|
|
13
|
+
|
|
14
|
+
export interface UserAttributes {
|
|
15
|
+
id: number;
|
|
16
|
+
name: string;
|
|
17
|
+
email: string;
|
|
18
|
+
password: string;
|
|
19
|
+
email_verified_at: string | null;
|
|
20
|
+
created_at: string;
|
|
21
|
+
updated_at: string;
|
|
22
|
+
[key: string]: unknown;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type SafeUser = Omit<UserAttributes, "password">;
|
|
26
|
+
|
|
27
|
+
interface UserCreateInput {
|
|
28
|
+
name: string;
|
|
29
|
+
email: string;
|
|
30
|
+
password: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class User extends Model {
|
|
34
|
+
static table = "users";
|
|
35
|
+
|
|
36
|
+
static fillable: string[] = [
|
|
37
|
+
"name",
|
|
38
|
+
"email",
|
|
39
|
+
"password",
|
|
40
|
+
"email_verified_at",
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
static async all(): Promise<UserAttributes[]> {
|
|
44
|
+
return (await super.all()) as UserAttributes[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
static async find(id: number | string): Promise<UserAttributes | null> {
|
|
48
|
+
return (await super.find(id)) as UserAttributes | null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
static async create(data: Record<string, unknown>): Promise<UserAttributes | null> {
|
|
52
|
+
const hashed = await hashPassword(data.password as string);
|
|
53
|
+
return (await super.create({ ...data, password: hashed })) as UserAttributes | null;
|
|
54
|
+
}
|
|
55
|
+
static async updatePassword(id: number, plainPassword: string) {
|
|
56
|
+
const hashed = await hashPassword(plainPassword);
|
|
57
|
+
return this.update(id, { password: hashed });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
static async markEmailVerified(id: number) {
|
|
61
|
+
return this.update(id, { email_verified_at: new Date().toISOString() });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static isEmailVerified(user: UserAttributes | null | undefined): boolean {
|
|
65
|
+
return Boolean(user?.email_verified_at);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
static toSafeObject(user: UserAttributes | null): SafeUser | null {
|
|
69
|
+
if (!user) return null;
|
|
70
|
+
const { password, ...safe } = user;
|
|
71
|
+
return safe;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -1,19 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
randomBytes,
|
|
3
|
+
scrypt as scryptCallback,
|
|
4
|
+
timingSafeEqual,
|
|
5
|
+
} from 'node:crypto'
|
|
6
|
+
import { promisify } from 'node:util'
|
|
3
7
|
|
|
4
|
-
const scrypt = promisify(scryptCallback)
|
|
5
|
-
const KEY_LENGTH = 64
|
|
8
|
+
const scrypt = promisify(scryptCallback)
|
|
9
|
+
const KEY_LENGTH = 64
|
|
6
10
|
|
|
7
11
|
export async function hashPassword(plainPassword) {
|
|
8
|
-
const salt = randomBytes(16).toString(
|
|
9
|
-
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH)
|
|
10
|
-
return `${salt}:${derivedKey.toString(
|
|
12
|
+
const salt = randomBytes(16).toString('hex')
|
|
13
|
+
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH)
|
|
14
|
+
return `${salt}:${derivedKey.toString('hex')}`
|
|
11
15
|
}
|
|
12
16
|
|
|
13
17
|
export async function verifyPassword(plainPassword, storedHash) {
|
|
14
|
-
const [salt, key] = storedHash.split(
|
|
15
|
-
if (!salt || !key) return false
|
|
18
|
+
const [salt, key] = storedHash.split(':')
|
|
19
|
+
if (!salt || !key) return false
|
|
16
20
|
|
|
17
|
-
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH)
|
|
18
|
-
|
|
21
|
+
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH)
|
|
22
|
+
const keyBuffer = Buffer.from(key, 'hex')
|
|
23
|
+
|
|
24
|
+
// derivedKey and keyBuffer must be equal length for timingSafeEqual,
|
|
25
|
+
// or it throws -- guard against a corrupted/foreign-format stored
|
|
26
|
+
// hash rather than letting a length mismatch crash the login route.
|
|
27
|
+
if (derivedKey.length !== keyBuffer.length) return false
|
|
28
|
+
|
|
29
|
+
return timingSafeEqual(derivedKey, keyBuffer)
|
|
19
30
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface LoginAllowedResult {
|
|
2
|
+
allowed: boolean
|
|
3
|
+
retryAfterSeconds?: number
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export declare function checkLoginAllowed(identifier: string): LoginAllowedResult
|
|
7
|
+
export declare function recordFailedLogin(identifier: string): { count: number; firstAttemptAt: number; lockedUntil: number | null }
|
|
8
|
+
export declare function clearLoginAttempts(identifier: string): void
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface TokenPayload {
|
|
2
|
+
[key: string]: unknown
|
|
3
|
+
exp?: number
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface SignTokenOptions {
|
|
7
|
+
expiresInSeconds?: number
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface VerifyTokenResult {
|
|
11
|
+
valid: boolean
|
|
12
|
+
payload: TokenPayload | null
|
|
13
|
+
error: string | null
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export declare function signToken(
|
|
17
|
+
payload: Record<string, unknown>,
|
|
18
|
+
secret: string,
|
|
19
|
+
options?: SignTokenOptions,
|
|
20
|
+
): string
|
|
21
|
+
|
|
22
|
+
export declare function verifyToken(token: string, secret: string): VerifyTokenResult
|