@tylix/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.
- package/package.json +14 -0
- package/src/cookies/authCookies.js +58 -0
- package/src/generators/AuthGenerator.js +100 -0
- package/src/generators/AuthGenerator.test.js +33 -0
- package/src/generators/templates/auth-controller.tyx +224 -0
- package/src/generators/templates/auth-validator.tyx +48 -0
- package/src/generators/templates/mailer.tyx +23 -0
- package/src/generators/templates/password-reset-migration.tyx +24 -0
- package/src/generators/templates/password-reset-model.tyx +54 -0
- package/src/generators/templates/refresh-token-migration.tyx +24 -0
- package/src/generators/templates/refresh-token-model.tyx +64 -0
- package/src/generators/templates/user-migration.tyx +24 -0
- package/src/generators/templates/user-model.tyx +50 -0
- package/src/index.js +5 -0
- package/src/password/hashPassword.js +19 -0
- package/src/password/hashPassword.test.js +32 -0
- package/src/rateLimiter/loginRateLimiter.js +62 -0
- package/src/token/signToken.js +49 -0
- package/src/token/signToken.test.js +49 -0
package/package.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tylix/auth",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./src/index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "node --test src/**/*.test.js"
|
|
8
|
+
},
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"@tylix/generator": "^0.1.0",
|
|
11
|
+
"@tylix/orm": "^0.1.0",
|
|
12
|
+
"@tylix/shared": "^0.1.0"
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* httpOnly cookie helpers for access/refresh tokens.
|
|
3
|
+
*
|
|
4
|
+
* ASSUMPTION: your Express app has `cookie-parser` (or equivalent)
|
|
5
|
+
* registered so `req.cookies` is populated, e.g.:
|
|
6
|
+
*
|
|
7
|
+
* import cookieParser from "cookie-parser";
|
|
8
|
+
* app.use(cookieParser());
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const ACCESS_TOKEN_COOKIE = 'tylix_access_token'
|
|
12
|
+
const REFRESH_TOKEN_COOKIE = 'tylix_refresh_token'
|
|
13
|
+
|
|
14
|
+
const baseCookieOptions = {
|
|
15
|
+
httpOnly: true,
|
|
16
|
+
sameSite: 'lax',
|
|
17
|
+
secure: process.env.NODE_ENV === 'production',
|
|
18
|
+
path: '/',
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function setAuthCookies(
|
|
22
|
+
res,
|
|
23
|
+
{ accessToken, refreshToken, accessTtlSeconds, refreshTtlSeconds } = {},
|
|
24
|
+
) {
|
|
25
|
+
if (accessToken) {
|
|
26
|
+
res.cookie(ACCESS_TOKEN_COOKIE, accessToken, {
|
|
27
|
+
...baseCookieOptions,
|
|
28
|
+
maxAge: accessTtlSeconds * 1000,
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (refreshToken) {
|
|
33
|
+
res.cookie(REFRESH_TOKEN_COOKIE, refreshToken, {
|
|
34
|
+
...baseCookieOptions,
|
|
35
|
+
maxAge: refreshTtlSeconds * 1000,
|
|
36
|
+
// Scoped so the browser only sends it to the refresh endpoint.
|
|
37
|
+
path: '/api/auth/refresh',
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function clearAuthCookies(res) {
|
|
43
|
+
res.clearCookie(ACCESS_TOKEN_COOKIE, { ...baseCookieOptions })
|
|
44
|
+
res.clearCookie(REFRESH_TOKEN_COOKIE, {
|
|
45
|
+
...baseCookieOptions,
|
|
46
|
+
path: '/api/auth/refresh',
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function readAccessToken(req) {
|
|
51
|
+
return req.cookies?.[ACCESS_TOKEN_COOKIE] ?? null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function readRefreshToken(req) {
|
|
55
|
+
return req.cookies?.[REFRESH_TOKEN_COOKIE] ?? null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export { ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE }
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import fs from 'node:fs/promises'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import { writeFile } from '@tylix/shared'
|
|
5
|
+
|
|
6
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
7
|
+
const TEMPLATES_DIR = path.join(__dirname, 'templates')
|
|
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
|
+
function timestampSuffix(offsetMs = 0) {
|
|
13
|
+
return new Date(Date.now() + offsetMs)
|
|
14
|
+
.toISOString()
|
|
15
|
+
.replace(/[-:.TZ]/g, '')
|
|
16
|
+
.slice(0, 14)
|
|
17
|
+
}
|
|
18
|
+
|
|
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
|
+
export class AuthGenerator {
|
|
25
|
+
async generate(baseDir) {
|
|
26
|
+
const results = {}
|
|
27
|
+
const read = (name) => fs.readFile(path.join(TEMPLATES_DIR, name), 'utf-8')
|
|
28
|
+
|
|
29
|
+
results.userModel = await writeFile(
|
|
30
|
+
path.join(baseDir, 'app', 'models', 'User.js'),
|
|
31
|
+
await read('user-model.tyx'),
|
|
32
|
+
{ overwrite: true },
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
results.refreshTokenModel = await writeFile(
|
|
36
|
+
path.join(baseDir, 'app', 'models', 'RefreshToken.js'),
|
|
37
|
+
await read('refresh-token-model.tyx'),
|
|
38
|
+
{ overwrite: true },
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
results.passwordResetModel = await writeFile(
|
|
42
|
+
path.join(baseDir, 'app', 'models', 'PasswordReset.js'),
|
|
43
|
+
await read('password-reset-model.tyx'),
|
|
44
|
+
{ overwrite: true },
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
results.validator = await writeFile(
|
|
48
|
+
path.join(baseDir, 'app', 'validators', 'AuthValidator.js'),
|
|
49
|
+
await read('auth-validator.tyx'),
|
|
50
|
+
{ overwrite: true },
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
results.controller = await writeFile(
|
|
54
|
+
path.join(baseDir, 'app', 'controllers', 'AuthController.js'),
|
|
55
|
+
await read('auth-controller.tyx'),
|
|
56
|
+
{ overwrite: true },
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
results.mailer = await writeFile(
|
|
60
|
+
path.join(baseDir, 'app', 'mail', 'mailer.js'),
|
|
61
|
+
await read('mailer.tyx'),
|
|
62
|
+
{ overwrite: true },
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
results.userMigration = await writeFile(
|
|
66
|
+
path.join(
|
|
67
|
+
baseDir,
|
|
68
|
+
'database',
|
|
69
|
+
'migrations',
|
|
70
|
+
`${timestampSuffix(0)}_create_users_table.js`,
|
|
71
|
+
),
|
|
72
|
+
await read('user-migration.tyx'),
|
|
73
|
+
{ overwrite: true },
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
results.refreshTokenMigration = await writeFile(
|
|
77
|
+
path.join(
|
|
78
|
+
baseDir,
|
|
79
|
+
'database',
|
|
80
|
+
'migrations',
|
|
81
|
+
`${timestampSuffix(1000)}_create_refresh_tokens_table.js`,
|
|
82
|
+
),
|
|
83
|
+
await read('refresh-token-migration.tyx'),
|
|
84
|
+
{ overwrite: true },
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
results.passwordResetMigration = await writeFile(
|
|
88
|
+
path.join(
|
|
89
|
+
baseDir,
|
|
90
|
+
'database',
|
|
91
|
+
'migrations',
|
|
92
|
+
`${timestampSuffix(2000)}_create_password_resets_table.js`,
|
|
93
|
+
),
|
|
94
|
+
await read('password-reset-migration.tyx'),
|
|
95
|
+
{ overwrite: true },
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
return results
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { AuthGenerator } from "./AuthGenerator.js";
|
|
7
|
+
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
test("generates User model, validator, controller, and migration", async () => {
|
|
11
|
+
const outputDir = path.join(__dirname, ".tmp-test-output");
|
|
12
|
+
await fs.mkdir(outputDir, { recursive: true });
|
|
13
|
+
|
|
14
|
+
const generator = new AuthGenerator();
|
|
15
|
+
const results = await generator.generate(outputDir);
|
|
16
|
+
|
|
17
|
+
const modelContent = await fs.readFile(results.model, "utf-8");
|
|
18
|
+
const validatorContent = await fs.readFile(results.validator, "utf-8");
|
|
19
|
+
const controllerContent = await fs.readFile(results.controller, "utf-8");
|
|
20
|
+
const migrationContent = await fs.readFile(results.migration, "utf-8");
|
|
21
|
+
|
|
22
|
+
assert.match(modelContent, /export class User extends Model/);
|
|
23
|
+
assert.match(modelContent, /static async create\(data\)/);
|
|
24
|
+
assert.match(validatorContent, /export function validateRegister/);
|
|
25
|
+
assert.match(validatorContent, /export function validateLogin/);
|
|
26
|
+
assert.match(controllerContent, /export class AuthController/);
|
|
27
|
+
assert.match(controllerContent, /async register\(req, res\)/);
|
|
28
|
+
assert.match(controllerContent, /async login\(req, res\)/);
|
|
29
|
+
assert.match(controllerContent, /async me\(req, res\)/);
|
|
30
|
+
assert.match(migrationContent, /createTable\("users"/);
|
|
31
|
+
|
|
32
|
+
await fs.rm(outputDir, { recursive: true, force: true });
|
|
33
|
+
});
|
|
@@ -0,0 +1,224 @@
|
|
|
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 { User } from "../models/User.js";
|
|
12
|
+
import { RefreshToken } from "../models/RefreshToken.js";
|
|
13
|
+
import { PasswordReset } from "../models/PasswordReset.js";
|
|
14
|
+
import {
|
|
15
|
+
verifyPassword,
|
|
16
|
+
signToken,
|
|
17
|
+
verifyToken,
|
|
18
|
+
setAuthCookies,
|
|
19
|
+
clearAuthCookies,
|
|
20
|
+
readRefreshToken,
|
|
21
|
+
checkLoginAllowed,
|
|
22
|
+
recordFailedLogin,
|
|
23
|
+
clearLoginAttempts,
|
|
24
|
+
} from "@tylix/auth";
|
|
25
|
+
import { sendVerificationEmail, sendPasswordResetEmail } from "../mail/mailer.js";
|
|
26
|
+
import {
|
|
27
|
+
validateRegister,
|
|
28
|
+
validateLogin,
|
|
29
|
+
validateForgotPassword,
|
|
30
|
+
validateResetPassword,
|
|
31
|
+
} from "../validators/AuthValidator.js";
|
|
32
|
+
|
|
33
|
+
const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 15 * 60; // 15 minutes, used if config doesn't specify one
|
|
34
|
+
|
|
35
|
+
export class AuthController {
|
|
36
|
+
constructor({ secret, tokenExpiresInSeconds } = {}) {
|
|
37
|
+
this.secret = secret;
|
|
38
|
+
this.accessTokenTtlSeconds = tokenExpiresInSeconds ?? DEFAULT_ACCESS_TOKEN_TTL_SECONDS;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async register(req, res) {
|
|
42
|
+
const result = validateRegister(req.body);
|
|
43
|
+
if (!result.valid) {
|
|
44
|
+
return res.status(422).json({ errors: result.errors });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const existing = await User.all();
|
|
48
|
+
if (existing.some((u) => u.email === req.body.email)) {
|
|
49
|
+
return res.status(422).json({ errors: { email: ["This email is already registered."] } });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const user = await User.create(req.body);
|
|
53
|
+
|
|
54
|
+
const verificationToken = signToken(
|
|
55
|
+
{ userId: user.id, purpose: "email-verify" },
|
|
56
|
+
this.secret,
|
|
57
|
+
{ expiresInSeconds: 60 * 60 * 24 },
|
|
58
|
+
);
|
|
59
|
+
await sendVerificationEmail(user, verificationToken);
|
|
60
|
+
|
|
61
|
+
return res.status(201).json({
|
|
62
|
+
user: User.toSafeObject(user),
|
|
63
|
+
message: "Registration successful. Check your email to verify your account before logging in.",
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async login(req, res) {
|
|
68
|
+
const result = validateLogin(req.body);
|
|
69
|
+
if (!result.valid) {
|
|
70
|
+
return res.status(422).json({ errors: result.errors });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const rateLimitKey = req.body.email;
|
|
74
|
+
const { allowed, retryAfterSeconds } = checkLoginAllowed(rateLimitKey);
|
|
75
|
+
if (!allowed) {
|
|
76
|
+
return res.status(429).json({
|
|
77
|
+
error: `Too many failed attempts. Try again in ${retryAfterSeconds} seconds.`,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const users = await User.all();
|
|
82
|
+
const user = users.find((u) => u.email === req.body.email);
|
|
83
|
+
|
|
84
|
+
if (!user) {
|
|
85
|
+
recordFailedLogin(rateLimitKey);
|
|
86
|
+
return res.status(401).json({ error: "Invalid email or password." });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const passwordMatches = await verifyPassword(req.body.password, user.password);
|
|
90
|
+
if (!passwordMatches) {
|
|
91
|
+
recordFailedLogin(rateLimitKey);
|
|
92
|
+
return res.status(401).json({ error: "Invalid email or password." });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (!User.isEmailVerified(user)) {
|
|
96
|
+
return res.status(403).json({
|
|
97
|
+
error: "Please verify your email before logging in.",
|
|
98
|
+
code: "EMAIL_NOT_VERIFIED",
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
clearLoginAttempts(rateLimitKey);
|
|
103
|
+
|
|
104
|
+
const accessToken = signToken({ userId: user.id }, this.secret, {
|
|
105
|
+
expiresInSeconds: this.accessTokenTtlSeconds,
|
|
106
|
+
});
|
|
107
|
+
const { rawToken: refreshToken, ttlSeconds: refreshTtlSeconds } = await RefreshToken.issue(user.id);
|
|
108
|
+
|
|
109
|
+
setAuthCookies(res, {
|
|
110
|
+
accessToken,
|
|
111
|
+
refreshToken,
|
|
112
|
+
accessTtlSeconds: this.accessTokenTtlSeconds,
|
|
113
|
+
refreshTtlSeconds,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
return res.json({ user: User.toSafeObject(user) });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async refresh(req, res) {
|
|
120
|
+
const rawToken = readRefreshToken(req);
|
|
121
|
+
if (!rawToken) {
|
|
122
|
+
return res.status(401).json({ error: "No refresh token provided." });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const record = await RefreshToken.findValid(rawToken);
|
|
126
|
+
if (!record) {
|
|
127
|
+
clearAuthCookies(res);
|
|
128
|
+
return res.status(401).json({ error: "Refresh token invalid or expired." });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const accessToken = signToken({ userId: record.user_id }, this.secret, {
|
|
132
|
+
expiresInSeconds: this.accessTokenTtlSeconds,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
setAuthCookies(res, { accessToken, accessTtlSeconds: this.accessTokenTtlSeconds });
|
|
136
|
+
|
|
137
|
+
return res.json({ ok: true });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async logout(req, res) {
|
|
141
|
+
const rawToken = readRefreshToken(req);
|
|
142
|
+
if (rawToken) {
|
|
143
|
+
await RefreshToken.revoke(rawToken);
|
|
144
|
+
}
|
|
145
|
+
clearAuthCookies(res);
|
|
146
|
+
return res.status(204).send();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async me(req, res) {
|
|
150
|
+
const user = await User.find(req.user.userId);
|
|
151
|
+
if (!user) {
|
|
152
|
+
return res.status(404).json({ error: "User not found." });
|
|
153
|
+
}
|
|
154
|
+
return res.json(User.toSafeObject(user));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async verifyEmail(req, res) {
|
|
158
|
+
const token = req.query.token;
|
|
159
|
+
if (!token) {
|
|
160
|
+
return res.status(400).json({ error: "Missing verification token." });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const { valid, payload } = verifyToken(token, this.secret);
|
|
164
|
+
if (!valid || payload.purpose !== "email-verify") {
|
|
165
|
+
return res.status(400).json({ error: "Invalid or expired verification link." });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const user = await User.find(payload.userId);
|
|
169
|
+
if (!user) {
|
|
170
|
+
return res.status(404).json({ error: "User not found." });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
await User.markEmailVerified(user.id);
|
|
174
|
+
return res.json({ ok: true, message: "Email verified. You can now log in." });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async forgotPassword(req, res) {
|
|
178
|
+
const result = validateForgotPassword(req.body);
|
|
179
|
+
if (!result.valid) {
|
|
180
|
+
return res.status(422).json({ errors: result.errors });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const users = await User.all();
|
|
184
|
+
const user = users.find((u) => u.email === req.body.email);
|
|
185
|
+
|
|
186
|
+
// Always respond the same way whether or not the email exists,
|
|
187
|
+
// so this endpoint can't be used to enumerate registered users.
|
|
188
|
+
if (user) {
|
|
189
|
+
const { rawToken } = await PasswordReset.issue(user.email);
|
|
190
|
+
await sendPasswordResetEmail(user, rawToken);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return res.json({
|
|
194
|
+
ok: true,
|
|
195
|
+
message: "If that email is registered, a reset link has been sent.",
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async resetPassword(req, res) {
|
|
200
|
+
const result = validateResetPassword(req.body);
|
|
201
|
+
if (!result.valid) {
|
|
202
|
+
return res.status(422).json({ errors: result.errors });
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const record = await PasswordReset.findValid(req.body.token, req.body.email);
|
|
206
|
+
if (!record) {
|
|
207
|
+
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const users = await User.all();
|
|
211
|
+
const user = users.find((u) => u.email === req.body.email);
|
|
212
|
+
if (!user) {
|
|
213
|
+
return res.status(404).json({ error: "User not found." });
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
await User.updatePassword(user.id, req.body.password);
|
|
217
|
+
await PasswordReset.markUsed(record.id);
|
|
218
|
+
// Resetting the password kills every existing session, in case the
|
|
219
|
+
// reset was triggered because the account was compromised.
|
|
220
|
+
await RefreshToken.revokeAllForUser(user.id);
|
|
221
|
+
|
|
222
|
+
return res.json({ ok: true, message: "Password updated. Please log in again." });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -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) {
|
|
35
|
+
return validate(data, registerSchema);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function validateLogin(data) {
|
|
39
|
+
return validate(data, loginSchema);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function validateForgotPassword(data) {
|
|
43
|
+
return validate(data, forgotPasswordSchema);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function validateResetPassword(data) {
|
|
47
|
+
return validate(data, resetPasswordSchema);
|
|
48
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
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
|
+
export async function sendVerificationEmail(user, token) {
|
|
16
|
+
const verifyUrl = `${APP_URL}/api/auth/verify-email?token=${token}`;
|
|
17
|
+
console.log(`[mailer] Verification email for ${user.email}: ${verifyUrl}`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function sendPasswordResetEmail(user, token) {
|
|
21
|
+
const resetUrl = `${APP_URL}/reset-password?token=${token}&email=${encodeURIComponent(user.email)}`;
|
|
22
|
+
console.log(`[mailer] Password reset email for ${user.email}: ${resetUrl}`);
|
|
23
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
export const up = async (schema) => {
|
|
12
|
+
await schema.createTable("password_resets", (table) => {
|
|
13
|
+
table.increments("id");
|
|
14
|
+
table.string("email");
|
|
15
|
+
table.string("token_hash").unique();
|
|
16
|
+
table.datetime("expires_at");
|
|
17
|
+
table.datetime("used_at");
|
|
18
|
+
table.timestamps();
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const down = async (schema) => {
|
|
23
|
+
await schema.dropTable("password_resets");
|
|
24
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
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 { Model } from "@tylix/orm";
|
|
12
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
13
|
+
|
|
14
|
+
const RESET_TOKEN_TTL_SECONDS = 60 * 60; // 1 hour
|
|
15
|
+
|
|
16
|
+
export class PasswordReset extends Model {
|
|
17
|
+
static table = "password_resets";
|
|
18
|
+
|
|
19
|
+
static fillable = ["email", "token_hash", "expires_at", "used_at"];
|
|
20
|
+
|
|
21
|
+
static hash(rawToken) {
|
|
22
|
+
return createHash("sha256").update(rawToken).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static async issue(email) {
|
|
26
|
+
const rawToken = randomBytes(32).toString("hex");
|
|
27
|
+
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_SECONDS * 1000);
|
|
28
|
+
|
|
29
|
+
await this.create({
|
|
30
|
+
email,
|
|
31
|
+
token_hash: this.hash(rawToken),
|
|
32
|
+
expires_at: expiresAt.toISOString(),
|
|
33
|
+
used_at: null,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
return { rawToken, expiresAt };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
static async findValid(rawToken, email) {
|
|
40
|
+
const tokenHash = this.hash(rawToken);
|
|
41
|
+
const all = await this.all();
|
|
42
|
+
const record = all.find((r) => r.token_hash === tokenHash && r.email === email);
|
|
43
|
+
|
|
44
|
+
if (!record) return null;
|
|
45
|
+
if (record.used_at) return null;
|
|
46
|
+
if (new Date(record.expires_at).getTime() < Date.now()) return null;
|
|
47
|
+
|
|
48
|
+
return record;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
static async markUsed(id) {
|
|
52
|
+
return this.update(id, { used_at: new Date().toISOString() });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
export const up = async (schema) => {
|
|
12
|
+
await schema.createTable("refresh_tokens", (table) => {
|
|
13
|
+
table.increments("id");
|
|
14
|
+
table.integer("user_id");
|
|
15
|
+
table.string("token_hash").unique();
|
|
16
|
+
table.datetime("expires_at");
|
|
17
|
+
table.datetime("revoked_at");
|
|
18
|
+
table.timestamps();
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const down = async (schema) => {
|
|
23
|
+
await schema.dropTable("refresh_tokens");
|
|
24
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
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 { Model } from "@tylix/orm";
|
|
12
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
13
|
+
|
|
14
|
+
const REFRESH_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 30; // 30 days
|
|
15
|
+
|
|
16
|
+
export class RefreshToken extends Model {
|
|
17
|
+
static table = "refresh_tokens";
|
|
18
|
+
|
|
19
|
+
static fillable = ["user_id", "token_hash", "expires_at", "revoked_at"];
|
|
20
|
+
|
|
21
|
+
// We never store the raw refresh token, only a hash of it — same idea
|
|
22
|
+
// as password hashing, so a DB leak doesn't hand out live sessions.
|
|
23
|
+
static hash(rawToken) {
|
|
24
|
+
return createHash("sha256").update(rawToken).digest("hex");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
static async issue(userId) {
|
|
28
|
+
const rawToken = randomBytes(48).toString("hex");
|
|
29
|
+
const expiresAt = new Date(Date.now() + REFRESH_TOKEN_TTL_SECONDS * 1000);
|
|
30
|
+
|
|
31
|
+
await this.create({
|
|
32
|
+
user_id: userId,
|
|
33
|
+
token_hash: this.hash(rawToken),
|
|
34
|
+
expires_at: expiresAt.toISOString(),
|
|
35
|
+
revoked_at: null,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
return { rawToken, expiresAt, ttlSeconds: REFRESH_TOKEN_TTL_SECONDS };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
static async findValid(rawToken) {
|
|
42
|
+
const tokenHash = this.hash(rawToken);
|
|
43
|
+
const all = await this.all();
|
|
44
|
+
const record = all.find((t) => t.token_hash === tokenHash);
|
|
45
|
+
|
|
46
|
+
if (!record) return null;
|
|
47
|
+
if (record.revoked_at) return null;
|
|
48
|
+
if (new Date(record.expires_at).getTime() < Date.now()) return null;
|
|
49
|
+
|
|
50
|
+
return record;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
static async revoke(rawToken) {
|
|
54
|
+
const record = await this.findValid(rawToken);
|
|
55
|
+
if (!record) return;
|
|
56
|
+
await this.update(record.id, { revoked_at: new Date().toISOString() });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
static async revokeAllForUser(userId) {
|
|
60
|
+
const all = await this.all();
|
|
61
|
+
const active = all.filter((t) => t.user_id === userId && !t.revoked_at);
|
|
62
|
+
await Promise.all(active.map((t) => this.update(t.id, { revoked_at: new Date().toISOString() })));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
export const up = async (schema) => {
|
|
12
|
+
await schema.createTable("users", (table) => {
|
|
13
|
+
table.increments("id");
|
|
14
|
+
table.string("name");
|
|
15
|
+
table.string("email").unique();
|
|
16
|
+
table.string("password");
|
|
17
|
+
table.datetime("email_verified_at");
|
|
18
|
+
table.timestamps();
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const down = async (schema) => {
|
|
23
|
+
await schema.dropTable("users");
|
|
24
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
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 class User extends Model {
|
|
15
|
+
static table = "users";
|
|
16
|
+
|
|
17
|
+
static fillable = [
|
|
18
|
+
"name",
|
|
19
|
+
"email",
|
|
20
|
+
"password",
|
|
21
|
+
"email_verified_at",
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
static async create(data) {
|
|
25
|
+
const hashed = await hashPassword(data.password);
|
|
26
|
+
return super.create({ ...data, password: hashed });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ASSUMPTION: Model exposes a generic `update(id, data)` — mirrors the
|
|
30
|
+
// pattern already used by `create`/`find` on this class. Adjust if your
|
|
31
|
+
// ORM's update method has a different signature.
|
|
32
|
+
static async updatePassword(id, plainPassword) {
|
|
33
|
+
const hashed = await hashPassword(plainPassword);
|
|
34
|
+
return this.update(id, { password: hashed });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
static async markEmailVerified(id) {
|
|
38
|
+
return this.update(id, { email_verified_at: new Date().toISOString() });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
static isEmailVerified(user) {
|
|
42
|
+
return Boolean(user?.email_verified_at);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
static toSafeObject(user) {
|
|
46
|
+
if (!user) return null;
|
|
47
|
+
const { password, ...safe } = user;
|
|
48
|
+
return safe;
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { randomBytes, scrypt as scryptCallback } from "node:crypto";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
|
|
4
|
+
const scrypt = promisify(scryptCallback);
|
|
5
|
+
const KEY_LENGTH = 64;
|
|
6
|
+
|
|
7
|
+
export async function hashPassword(plainPassword) {
|
|
8
|
+
const salt = randomBytes(16).toString("hex");
|
|
9
|
+
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH);
|
|
10
|
+
return `${salt}:${derivedKey.toString("hex")}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function verifyPassword(plainPassword, storedHash) {
|
|
14
|
+
const [salt, key] = storedHash.split(":");
|
|
15
|
+
if (!salt || !key) return false;
|
|
16
|
+
|
|
17
|
+
const derivedKey = await scrypt(plainPassword, salt, KEY_LENGTH);
|
|
18
|
+
return derivedKey.toString("hex") === key;
|
|
19
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { hashPassword, verifyPassword } from "./hashPassword.js";
|
|
4
|
+
|
|
5
|
+
test("hashPassword produces a salt:hash string different from the plain password", async () => {
|
|
6
|
+
const hash = await hashPassword("correct-horse-battery-staple");
|
|
7
|
+
assert.notEqual(hash, "correct-horse-battery-staple");
|
|
8
|
+
assert.match(hash, /^[0-9a-f]+:[0-9a-f]+$/);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test("verifyPassword returns true for the correct password", async () => {
|
|
12
|
+
const hash = await hashPassword("my-secret-password");
|
|
13
|
+
const result = await verifyPassword("my-secret-password", hash);
|
|
14
|
+
assert.equal(result, true);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("verifyPassword returns false for an incorrect password", async () => {
|
|
18
|
+
const hash = await hashPassword("my-secret-password");
|
|
19
|
+
const result = await verifyPassword("wrong-password", hash);
|
|
20
|
+
assert.equal(result, false);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("two hashes of the same password are different (unique salts)", async () => {
|
|
24
|
+
const hash1 = await hashPassword("same-password");
|
|
25
|
+
const hash2 = await hashPassword("same-password");
|
|
26
|
+
assert.notEqual(hash1, hash2);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("verifyPassword returns false for a malformed stored hash", async () => {
|
|
30
|
+
const result = await verifyPassword("anything", "not-a-valid-hash");
|
|
31
|
+
assert.equal(result, false);
|
|
32
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory login attempt limiter, keyed by email.
|
|
3
|
+
*
|
|
4
|
+
* NOTE: this state lives in process memory. That's fine for a single
|
|
5
|
+
* instance / dev, but it resets on restart and doesn't share state
|
|
6
|
+
* across multiple server processes. If you deploy more than one
|
|
7
|
+
* instance behind a load balancer, swap the Map below for Redis
|
|
8
|
+
* (INCR + EXPIRE) using the same function signatures.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const attempts = new Map()
|
|
12
|
+
|
|
13
|
+
const MAX_ATTEMPTS = 5
|
|
14
|
+
const WINDOW_MS = 15 * 60 * 1000 // 15 minutes
|
|
15
|
+
const LOCKOUT_MS = 15 * 60 * 1000 // 15 minutes
|
|
16
|
+
|
|
17
|
+
function keyFor(identifier) {
|
|
18
|
+
return String(identifier ?? '').toLowerCase()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function checkLoginAllowed(identifier) {
|
|
22
|
+
const record = attempts.get(keyFor(identifier))
|
|
23
|
+
if (!record) return { allowed: true }
|
|
24
|
+
|
|
25
|
+
if (record.lockedUntil && record.lockedUntil > Date.now()) {
|
|
26
|
+
return {
|
|
27
|
+
allowed: false,
|
|
28
|
+
retryAfterSeconds: Math.ceil((record.lockedUntil - Date.now()) / 1000),
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return { allowed: true }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function recordFailedLogin(identifier) {
|
|
36
|
+
const key = keyFor(identifier)
|
|
37
|
+
const now = Date.now()
|
|
38
|
+
const record = attempts.get(key) ?? {
|
|
39
|
+
count: 0,
|
|
40
|
+
firstAttemptAt: now,
|
|
41
|
+
lockedUntil: null,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (now - record.firstAttemptAt > WINDOW_MS) {
|
|
45
|
+
record.count = 0
|
|
46
|
+
record.firstAttemptAt = now
|
|
47
|
+
record.lockedUntil = null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
record.count += 1
|
|
51
|
+
|
|
52
|
+
if (record.count >= MAX_ATTEMPTS) {
|
|
53
|
+
record.lockedUntil = now + LOCKOUT_MS
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
attempts.set(key, record)
|
|
57
|
+
return record
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function clearLoginAttempts(identifier) {
|
|
61
|
+
attempts.delete(keyFor(identifier))
|
|
62
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
function base64url(input) {
|
|
4
|
+
return Buffer.from(input).toString("base64url");
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function sign(payloadB64, secret) {
|
|
8
|
+
return createHmac("sha256", secret).update(payloadB64).digest("base64url");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function signToken(payload, secret, { expiresInSeconds } = {}) {
|
|
12
|
+
const body = { ...payload };
|
|
13
|
+
if (expiresInSeconds) {
|
|
14
|
+
body.exp = Math.floor(Date.now() / 1000) + expiresInSeconds;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const payloadB64 = base64url(JSON.stringify(body));
|
|
18
|
+
const signature = sign(payloadB64, secret);
|
|
19
|
+
return `${payloadB64}.${signature}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function verifyToken(token, secret) {
|
|
23
|
+
if (typeof token !== "string" || !token.includes(".")) {
|
|
24
|
+
return { valid: false, payload: null, error: "Malformed token" };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const [payloadB64, signature] = token.split(".");
|
|
28
|
+
const expectedSignature = sign(payloadB64, secret);
|
|
29
|
+
|
|
30
|
+
const sigBuffer = Buffer.from(signature ?? "", "base64url");
|
|
31
|
+
const expectedBuffer = Buffer.from(expectedSignature, "base64url");
|
|
32
|
+
|
|
33
|
+
if (sigBuffer.length !== expectedBuffer.length || !timingSafeEqual(sigBuffer, expectedBuffer)) {
|
|
34
|
+
return { valid: false, payload: null, error: "Invalid signature" };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
let payload;
|
|
38
|
+
try {
|
|
39
|
+
payload = JSON.parse(Buffer.from(payloadB64, "base64url").toString("utf-8"));
|
|
40
|
+
} catch {
|
|
41
|
+
return { valid: false, payload: null, error: "Invalid payload" };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (payload.exp && Math.floor(Date.now() / 1000) > payload.exp) {
|
|
45
|
+
return { valid: false, payload: null, error: "Token expired" };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return { valid: true, payload, error: null };
|
|
49
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { signToken, verifyToken } from "./signToken.js";
|
|
4
|
+
|
|
5
|
+
test("signToken produces a two-part dot-separated string", () => {
|
|
6
|
+
const token = signToken({ userId: 1 }, "test-secret");
|
|
7
|
+
assert.equal(token.split(".").length, 2);
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test("verifyToken accepts a validly signed token and returns the payload", () => {
|
|
11
|
+
const token = signToken({ userId: 42 }, "test-secret");
|
|
12
|
+
const result = verifyToken(token, "test-secret");
|
|
13
|
+
assert.equal(result.valid, true);
|
|
14
|
+
assert.equal(result.payload.userId, 42);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("verifyToken rejects a token signed with a different secret", () => {
|
|
18
|
+
const token = signToken({ userId: 1 }, "secret-a");
|
|
19
|
+
const result = verifyToken(token, "secret-b");
|
|
20
|
+
assert.equal(result.valid, false);
|
|
21
|
+
assert.equal(result.error, "Invalid signature");
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("verifyToken rejects a tampered payload", () => {
|
|
25
|
+
const token = signToken({ userId: 1 }, "test-secret");
|
|
26
|
+
const [, signature] = token.split(".");
|
|
27
|
+
const tampered = `${Buffer.from(JSON.stringify({ userId: 999 })).toString("base64url")}.${signature}`;
|
|
28
|
+
const result = verifyToken(tampered, "test-secret");
|
|
29
|
+
assert.equal(result.valid, false);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("verifyToken rejects an expired token", () => {
|
|
33
|
+
const token = signToken({ userId: 1 }, "test-secret", { expiresInSeconds: -10 });
|
|
34
|
+
const result = verifyToken(token, "test-secret");
|
|
35
|
+
assert.equal(result.valid, false);
|
|
36
|
+
assert.equal(result.error, "Token expired");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("verifyToken accepts a token that has not yet expired", () => {
|
|
40
|
+
const token = signToken({ userId: 1 }, "test-secret", { expiresInSeconds: 3600 });
|
|
41
|
+
const result = verifyToken(token, "test-secret");
|
|
42
|
+
assert.equal(result.valid, true);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("verifyToken rejects a malformed token string", () => {
|
|
46
|
+
const result = verifyToken("not-a-real-token", "test-secret");
|
|
47
|
+
assert.equal(result.valid, false);
|
|
48
|
+
assert.equal(result.error, "Malformed token");
|
|
49
|
+
});
|