@tylix/auth 0.5.2 → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mbiyrukzz
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.
package/README.md CHANGED
@@ -8,7 +8,9 @@ tokens, cookies, and rate limiting.
8
8
  - `hashPassword` — password hashing
9
9
  - `signToken` — auth token signing
10
10
  - `authCookies` — cookie helpers for session/auth state
11
- - `loginRateLimiter` — rate limiting for login attempts
11
+ - `loginRateLimiter` — rate limiting for login attempts (the generated
12
+ controller also uses the shared limiters from `@tylix/core`, so limits
13
+ hold across workers)
12
14
  - `AuthGenerator` — scaffolds auth routes/controllers/views via
13
15
  `tylix make:auth`
14
16
 
package/package.json CHANGED
@@ -1,20 +1,50 @@
1
1
  {
2
2
  "name": "@tylix/auth",
3
- "version": "0.5.2",
3
+ "version": "0.7.0",
4
+ "description": "Authentication for Tylix apps: password hashing, signed tokens, httpOnly cookie sessions with refresh, and the make:auth generator.",
5
+ "license": "MIT",
6
+ "author": "Mbiyrukzz",
4
7
  "type": "module",
5
8
  "keywords": [
6
9
  "tylix",
7
- "auth"
10
+ "auth",
11
+ "authentication",
12
+ "jwt",
13
+ "session"
8
14
  ],
15
+ "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/auth#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Mbiyrukzz/tylix.git",
19
+ "directory": "packages/auth"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/Mbiyrukzz/tylix/issues"
23
+ },
24
+ "engines": {
25
+ "node": ">=22.13"
26
+ },
9
27
  "main": "./src/index.js",
10
28
  "types": "./src/index.d.ts",
29
+ "files": [
30
+ "src",
31
+ "!**/*.test.js",
32
+ "!**/*.test.mjs",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
11
39
  "scripts": {
12
40
  "test": "node --test src/**/*.test.js"
13
41
  },
14
42
  "dependencies": {
15
- "@tylix/core": "^0.5.1",
16
- "@tylix/generator": "^0.5.1",
17
- "@tylix/orm": "^0.5.1",
18
- "@tylix/shared": "^0.5.1"
43
+ "@tylix/generator": "^0.7.0",
44
+ "@tylix/orm": "^0.7.0",
45
+ "@tylix/shared": "^0.7.0"
46
+ },
47
+ "peerDependencies": {
48
+ "@tylix/core": "^0.7.0"
19
49
  }
20
50
  }
@@ -13,6 +13,21 @@ function timestampSuffix(offsetMs = 0) {
13
13
  .slice(0, 14)
14
14
  }
15
15
 
16
+ // The migration that already creates `table`, whatever its timestamp, so
17
+ // running make:auth again (for example to regenerate the controller) never
18
+ // adds a second "create users table" migration.
19
+ async function findExistingMigration(migrationsDir, name) {
20
+ let entries = []
21
+ try {
22
+ entries = await fs.readdir(migrationsDir)
23
+ } catch {
24
+ return null // no migrations folder yet
25
+ }
26
+ const pattern = new RegExp(`^\\d{14}_${name}\\.(js|ts)$`)
27
+ const match = entries.filter((entry) => pattern.test(entry)).sort()[0]
28
+ return match ? path.join(migrationsDir, match) : null
29
+ }
30
+
16
31
  export class AuthGenerator {
17
32
  async generate(baseDir) {
18
33
  const results = {}
@@ -29,6 +44,22 @@ export class AuthGenerator {
29
44
  { overwrite: true },
30
45
  )
31
46
 
47
+ // The user observer and the job it queues. Kept if they already exist
48
+ // (make:auth may run again in an app whose own versions they are).
49
+ const writeIfMissing = async (file, template) => {
50
+ const existing = await fs.access(file).then(() => true, () => false)
51
+ if (!existing) await writeFile(file, await read(template))
52
+ return file
53
+ }
54
+ results.userObserver = await writeIfMissing(
55
+ path.join(baseDir, 'app', 'observers', `UserObserver.${ext}`),
56
+ 'user-observer',
57
+ )
58
+ results.welcomeJob = await writeIfMissing(
59
+ path.join(baseDir, 'app', 'jobs', `SendWelcomeEmail.${ext}`),
60
+ 'welcome-job',
61
+ )
62
+
32
63
  results.refreshTokenModel = await writeFile(
33
64
  path.join(baseDir, 'app', 'models', `RefreshToken.${ext}`),
34
65
  await read('refresh-token-model'),
@@ -91,38 +122,24 @@ export class AuthGenerator {
91
122
  { overwrite: true },
92
123
  )
93
124
 
94
- results.userMigration = await writeFile(
95
- path.join(
96
- baseDir,
97
- 'database',
98
- 'migrations',
99
- `${timestampSuffix(0)}_create_users_table.${ext}`,
100
- ),
101
- await read('user-migration'),
102
- { overwrite: true },
103
- )
125
+ // An existing migration is kept as it is: it may already have run
126
+ // against a database, so rewriting it would be wrong too.
127
+ const migrationsDir = path.join(baseDir, 'database', 'migrations')
128
+ const writeMigration = async (name, offsetMs, template) => {
129
+ const existing = await findExistingMigration(migrationsDir, name)
130
+ if (existing) return existing
131
+ return writeFile(
132
+ path.join(migrationsDir, `${timestampSuffix(offsetMs)}_${name}.${ext}`),
133
+ await read(template),
134
+ { overwrite: true },
135
+ )
136
+ }
104
137
 
105
- results.refreshTokenMigration = await writeFile(
106
- path.join(
107
- baseDir,
108
- 'database',
109
- 'migrations',
110
- `${timestampSuffix(1000)}_create_refresh_tokens_table.${ext}`,
111
- ),
112
- await read('refresh-token-migration'),
113
- { overwrite: true },
114
- )
138
+ results.userMigration = await writeMigration('create_users_table', 0, 'user-migration')
115
139
 
116
- results.passwordResetMigration = await writeFile(
117
- path.join(
118
- baseDir,
119
- 'database',
120
- 'migrations',
121
- `${timestampSuffix(2000)}_create_password_resets_table.${ext}`,
122
- ),
123
- await read('password-reset-migration'),
124
- { overwrite: true },
125
- )
140
+ results.refreshTokenMigration = await writeMigration('create_refresh_tokens_table', 1000, 'refresh-token-migration')
141
+
142
+ results.passwordResetMigration = await writeMigration('create_password_resets_table', 2000, 'password-reset-migration')
126
143
 
127
144
  return results
128
145
  }
@@ -35,9 +35,11 @@ import {
35
35
  const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 15 * 60;
36
36
 
37
37
  // In-memory limits (per server process).
38
- const registerLimiter = createRateLimiter({ max: 20, windowMs: 60 * 60 * 1000 });
39
- const forgotIpLimiter = createRateLimiter({ max: 10, windowMs: 15 * 60 * 1000 });
40
- const forgotEmailLimiter = createRateLimiter({ max: 5, windowMs: 60 * 60 * 1000 });
38
+ // Counted in the app's store (STORE_DRIVER), so the limits hold across
39
+ // every worker and server, not per process.
40
+ const registerLimiter = createRateLimiter({ name: "register", max: 20, windowMs: 60 * 60 * 1000, store: "shared" });
41
+ const forgotIpLimiter = createRateLimiter({ name: "forgot-password-ip", max: 10, windowMs: 15 * 60 * 1000, store: "shared" });
42
+ const forgotEmailLimiter = createRateLimiter({ name: "forgot-password-email", max: 5, windowMs: 60 * 60 * 1000, store: "shared" });
41
43
 
42
44
  // Emails are case-insensitive: always compare and store them trimmed and lowercased.
43
45
  function normalizeEmail(value: unknown): string {
@@ -66,7 +68,7 @@ export class AuthController {
66
68
  }
67
69
 
68
70
  async register(req: TylixRequest, res: TylixResponse) {
69
- const limit = registerLimiter(clientIp(req));
71
+ const limit = await registerLimiter(clientIp(req));
70
72
  if (!limit.allowed) {
71
73
  return res.status(429).json({
72
74
  error: `Too many sign-ups from this address. Try again in ${limit.retryAfterSeconds} seconds.`,
@@ -217,7 +219,7 @@ export class AuthController {
217
219
  }
218
220
 
219
221
  async forgotPassword(req: TylixRequest, res: TylixResponse) {
220
- const ipLimit = forgotIpLimiter(clientIp(req));
222
+ const ipLimit = await forgotIpLimiter(clientIp(req));
221
223
  if (!ipLimit.allowed) {
222
224
  return res.status(429).json({
223
225
  error: `Too many requests. Try again in ${ipLimit.retryAfterSeconds} seconds.`,
@@ -233,7 +235,7 @@ export class AuthController {
233
235
 
234
236
  // Counted for every address, registered or not, so hitting this limit
235
237
  // reveals nothing. When it is hit we answer as normal but send nothing.
236
- const emailLimit = forgotEmailLimiter(email);
238
+ const emailLimit = await forgotEmailLimiter(email);
237
239
  const user = await User.findByEmail(email);
238
240
 
239
241
  if (user && emailLimit.allowed) {
@@ -34,9 +34,11 @@ import {
34
34
  const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 15 * 60; // 15 minutes, used if config doesn't specify one
35
35
 
36
36
  // In-memory limits (per server process).
37
- const registerLimiter = createRateLimiter({ max: 20, windowMs: 60 * 60 * 1000 });
38
- const forgotIpLimiter = createRateLimiter({ max: 10, windowMs: 15 * 60 * 1000 });
39
- const forgotEmailLimiter = createRateLimiter({ max: 5, windowMs: 60 * 60 * 1000 });
37
+ // Counted in the app's store (STORE_DRIVER), so the limits hold across
38
+ // every worker and server, not per process.
39
+ const registerLimiter = createRateLimiter({ name: "register", max: 20, windowMs: 60 * 60 * 1000, store: "shared" });
40
+ const forgotIpLimiter = createRateLimiter({ name: "forgot-password-ip", max: 10, windowMs: 15 * 60 * 1000, store: "shared" });
41
+ const forgotEmailLimiter = createRateLimiter({ name: "forgot-password-email", max: 5, windowMs: 60 * 60 * 1000, store: "shared" });
40
42
 
41
43
  // Emails are case-insensitive: always compare and store them trimmed and lowercased.
42
44
  function normalizeEmail(value) {
@@ -55,7 +57,7 @@ export class AuthController {
55
57
  }
56
58
 
57
59
  async register(req, res) {
58
- const limit = registerLimiter(clientIp(req));
60
+ const limit = await registerLimiter(clientIp(req));
59
61
  if (!limit.allowed) {
60
62
  return res.status(429).json({
61
63
  error: `Too many sign-ups from this address. Try again in ${limit.retryAfterSeconds} seconds.`,
@@ -203,7 +205,7 @@ export class AuthController {
203
205
  }
204
206
 
205
207
  async forgotPassword(req, res) {
206
- const ipLimit = forgotIpLimiter(clientIp(req));
208
+ const ipLimit = await forgotIpLimiter(clientIp(req));
207
209
  if (!ipLimit.allowed) {
208
210
  return res.status(429).json({
209
211
  error: `Too many requests. Try again in ${ipLimit.retryAfterSeconds} seconds.`,
@@ -219,7 +221,7 @@ export class AuthController {
219
221
 
220
222
  // Counted for every address, registered or not, so hitting this limit
221
223
  // reveals nothing. When it is hit we answer as normal but send nothing.
222
- const emailLimit = forgotEmailLimiter(email);
224
+ const emailLimit = await forgotEmailLimiter(email);
223
225
  const user = await User.findByEmail(email);
224
226
 
225
227
  if (user && emailLimit.allowed) {
@@ -8,74 +8,71 @@
8
8
  * Do not edit this section.
9
9
  */
10
10
 
11
- import { validate, required, isString, isEmail } from "@tylix/shared";
11
+ // The rules for the auth forms. The API checks requests with them, and the
12
+ // frontend's login and register pages import this same file to check the
13
+ // form before sending it, so both always agree. That is why it imports
14
+ // from "@tylix/shared/validation", which runs in the browser too.
15
+ import {
16
+ validate,
17
+ required,
18
+ isString,
19
+ isEmail,
20
+ minLength,
21
+ maxLength,
22
+ withMessage,
23
+ } from "@tylix/shared/validation";
12
24
 
13
- const MIN_PASSWORD_LENGTH = 8;
14
- const MAX_PASSWORD_LENGTH = 128;
25
+ export const MIN_PASSWORD_LENGTH = 8;
26
+ export const MAX_PASSWORD_LENGTH = 128;
15
27
 
16
- type ValidationResult = ReturnType<typeof validate>;
28
+ const email = [
29
+ withMessage(required, "Enter your email address."),
30
+ isString,
31
+ withMessage(isEmail, "Enter a valid email address."),
32
+ ];
17
33
 
18
- const registerSchema = {
19
- name: [required, isString],
20
- email: [required, isString, isEmail],
21
- password: [required, isString],
22
- };
34
+ // Only for passwords being set (register, reset). Login must not enforce
35
+ // the length, so people with older, shorter passwords can still sign in.
36
+ const newPassword = [
37
+ withMessage(required, "Choose a password."),
38
+ isString,
39
+ minLength(MIN_PASSWORD_LENGTH, `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`),
40
+ maxLength(MAX_PASSWORD_LENGTH, `Password must be at most ${MAX_PASSWORD_LENGTH} characters.`),
41
+ ];
23
42
 
24
- const loginSchema = {
25
- email: [required, isString, isEmail],
26
- password: [required, isString],
43
+ export const registerSchema = {
44
+ name: [withMessage(required, "Enter your name."), isString, maxLength(100)],
45
+ email,
46
+ password: newPassword,
27
47
  };
28
48
 
29
- const forgotPasswordSchema = {
30
- email: [required, isString, isEmail],
49
+ export const loginSchema = {
50
+ email,
51
+ password: [withMessage(required, "Enter your password."), isString],
31
52
  };
32
53
 
33
- const resetPasswordSchema = {
34
- email: [required, isString, isEmail],
35
- token: [required, isString],
36
- password: [required, isString],
54
+ export const forgotPasswordSchema = {
55
+ email,
37
56
  };
38
57
 
39
- // Only for passwords being set (register, reset). Login must not enforce
40
- // it, so people with older, shorter passwords can still sign in.
41
- function enforcePasswordLength(
42
- data: Record<string, unknown>,
43
- result: ValidationResult,
44
- ): ValidationResult {
45
- const password = data?.password;
46
- if (typeof password !== "string") return result;
47
-
48
- const existing =
49
- (result as unknown as { errors?: Record<string, string[]> }).errors ?? {};
50
- if (existing.password?.length) return result;
51
-
52
- let message: string | null = null;
53
- if (password.length < MIN_PASSWORD_LENGTH) {
54
- message = `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`;
55
- } else if (password.length > MAX_PASSWORD_LENGTH) {
56
- message = `Password must be at most ${MAX_PASSWORD_LENGTH} characters.`;
57
- }
58
- if (!message) return result;
59
-
60
- return {
61
- ...result,
62
- valid: false,
63
- errors: { ...existing, password: [message] },
64
- } as unknown as ValidationResult;
65
- }
58
+ export const resetPasswordSchema = {
59
+ email,
60
+ token: [withMessage(required, "This reset link is incomplete."), isString],
61
+ password: newPassword,
62
+ };
66
63
 
67
- export function validateRegister(data: Record<string, unknown>) {
68
- return enforcePasswordLength(data, validate(data, registerSchema));
64
+ export function validateRegister(data: unknown) {
65
+ return validate(data, registerSchema);
69
66
  }
70
67
 
71
- export function validateLogin(data: Record<string, unknown>) {
68
+ export function validateLogin(data: unknown) {
72
69
  return validate(data, loginSchema);
73
70
  }
74
71
 
75
- export function validateForgotPassword(data: Record<string, unknown>) {
72
+ export function validateForgotPassword(data: unknown) {
76
73
  return validate(data, forgotPasswordSchema);
77
74
  }
78
75
 
79
- export function validateResetPassword(data: Record<string, unknown>) {
80
- return enforcePasswordLength(data, validate(data, resetPasswordSchema));
81
- }
76
+ export function validateResetPassword(data: unknown) {
77
+ return validate(data, resetPasswordSchema);
78
+ }
@@ -8,56 +8,61 @@
8
8
  * Do not edit this section.
9
9
  */
10
10
 
11
- import { validate, required, isString, isEmail } from "@tylix/shared";
11
+ // The rules for the auth forms. The API checks requests with them, and the
12
+ // frontend's login and register pages import this same file to check the
13
+ // form before sending it, so both always agree. That is why it imports
14
+ // from "@tylix/shared/validation", which runs in the browser too.
15
+ import {
16
+ validate,
17
+ required,
18
+ isString,
19
+ isEmail,
20
+ minLength,
21
+ maxLength,
22
+ withMessage,
23
+ } from "@tylix/shared/validation";
12
24
 
13
- const MIN_PASSWORD_LENGTH = 8;
14
- const MAX_PASSWORD_LENGTH = 128;
25
+ export const MIN_PASSWORD_LENGTH = 8;
26
+ export const MAX_PASSWORD_LENGTH = 128;
15
27
 
16
- const registerSchema = {
17
- name: [required, isString],
18
- email: [required, isString, isEmail],
19
- password: [required, isString],
20
- };
28
+ const email = [
29
+ withMessage(required, "Enter your email address."),
30
+ isString,
31
+ withMessage(isEmail, "Enter a valid email address."),
32
+ ];
21
33
 
22
- const loginSchema = {
23
- email: [required, isString, isEmail],
24
- password: [required, isString],
25
- };
34
+ // Only for passwords being set (register, reset). Login must not enforce
35
+ // the length, so people with older, shorter passwords can still sign in.
36
+ const newPassword = [
37
+ withMessage(required, "Choose a password."),
38
+ isString,
39
+ minLength(MIN_PASSWORD_LENGTH, `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`),
40
+ maxLength(MAX_PASSWORD_LENGTH, `Password must be at most ${MAX_PASSWORD_LENGTH} characters.`),
41
+ ];
26
42
 
27
- const forgotPasswordSchema = {
28
- email: [required, isString, isEmail],
43
+ export const registerSchema = {
44
+ name: [withMessage(required, "Enter your name."), isString, maxLength(100)],
45
+ email,
46
+ password: newPassword,
29
47
  };
30
48
 
31
- const resetPasswordSchema = {
32
- email: [required, isString, isEmail],
33
- token: [required, isString],
34
- password: [required, isString],
49
+ export const loginSchema = {
50
+ email,
51
+ password: [withMessage(required, "Enter your password."), isString],
35
52
  };
36
53
 
37
- // Only for passwords being set (register, reset). Login must not enforce
38
- // it, so people with older, shorter passwords can still sign in.
39
- function enforcePasswordLength(data, result) {
40
- const password = data?.password;
41
- if (typeof password !== "string") return result;
42
- if (result.errors?.password?.length) return result;
43
-
44
- let message = null;
45
- if (password.length < MIN_PASSWORD_LENGTH) {
46
- message = `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`;
47
- } else if (password.length > MAX_PASSWORD_LENGTH) {
48
- message = `Password must be at most ${MAX_PASSWORD_LENGTH} characters.`;
49
- }
50
- if (!message) return result;
54
+ export const forgotPasswordSchema = {
55
+ email,
56
+ };
51
57
 
52
- return {
53
- ...result,
54
- valid: false,
55
- errors: { ...(result.errors ?? {}), password: [message] },
56
- };
57
- }
58
+ export const resetPasswordSchema = {
59
+ email,
60
+ token: [withMessage(required, "This reset link is incomplete."), isString],
61
+ password: newPassword,
62
+ };
58
63
 
59
64
  export function validateRegister(data) {
60
- return enforcePasswordLength(data, validate(data, registerSchema));
65
+ return validate(data, registerSchema);
61
66
  }
62
67
 
63
68
  export function validateLogin(data) {
@@ -69,5 +74,5 @@ export function validateForgotPassword(data) {
69
74
  }
70
75
 
71
76
  export function validateResetPassword(data) {
72
- return enforcePasswordLength(data, validate(data, resetPasswordSchema));
73
- }
77
+ return validate(data, resetPasswordSchema);
78
+ }
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { Model } from "@tylix/orm";
12
12
  import { hashPassword } from "@tylix/auth";
13
+ import { UserObserver } from "../observers/UserObserver.js";
13
14
 
14
15
  export interface UserAttributes {
15
16
  id: number;
@@ -27,6 +28,9 @@ export type SafeUser = Omit<UserAttributes, "password">;
27
28
  export class User extends Model {
28
29
  static table = "users";
29
30
 
31
+ // Hooks that run on create/update/delete: see app/observers/UserObserver.
32
+ static observers = [UserObserver];
33
+
30
34
  static fillable: string[] = [
31
35
  "name",
32
36
  "email",
@@ -10,10 +10,14 @@
10
10
 
11
11
  import { Model } from "@tylix/orm";
12
12
  import { hashPassword } from "@tylix/auth";
13
+ import { UserObserver } from "../observers/UserObserver.js";
13
14
 
14
15
  export class User extends Model {
15
16
  static table = "users";
16
17
 
18
+ // Hooks that run on create/update/delete: see app/observers/UserObserver.
19
+ static observers = [UserObserver];
20
+
17
21
  static fillable = [
18
22
  "name",
19
23
  "email",
@@ -0,0 +1,12 @@
1
+ import { dispatch } from "@tylix/core";
2
+
3
+ // Runs when users are created, updated or deleted. Enabled by
4
+ // `static observers = [UserObserver]` in app/models/User.
5
+ // See "tylix make:observer" for every hook an observer can define.
6
+ export class UserObserver {
7
+ // After a sign-up: queue the welcome email instead of sending it during
8
+ // the request. "tylix queue:work" runs it (app/jobs/SendWelcomeEmail).
9
+ async created(user: Record<string, unknown>) {
10
+ await dispatch("SendWelcomeEmail", { userId: user.id });
11
+ }
12
+ }
@@ -0,0 +1,12 @@
1
+ import { dispatch } from "@tylix/core";
2
+
3
+ // Runs when users are created, updated or deleted. Enabled by
4
+ // `static observers = [UserObserver]` in app/models/User.
5
+ // See "tylix make:observer" for every hook an observer can define.
6
+ export class UserObserver {
7
+ // After a sign-up: queue the welcome email instead of sending it during
8
+ // the request. "tylix queue:work" runs it (app/jobs/SendWelcomeEmail).
9
+ async created(user) {
10
+ await dispatch("SendWelcomeEmail", { userId: user.id });
11
+ }
12
+ }
@@ -0,0 +1,15 @@
1
+ import { User } from "../models/User.js";
2
+
3
+ // Queued by app/observers/UserObserver when someone signs up, and run by
4
+ // "tylix queue:work", outside the request. Throwing marks the job failed,
5
+ // with the error recorded on its row in the jobs table.
6
+ export const SendWelcomeEmail = {
7
+ async handle(payload: { userId: number | string }) {
8
+ const user = await User.find(payload.userId);
9
+ if (!user) return; // deleted since sign-up: nothing to send
10
+
11
+ // Send a real email with a mailable, as app/mail/mailer does for
12
+ // verification. Logged here so the job is visible in the worker.
13
+ console.log(`Welcome email for ${String(user.email)} (user ${String(user.id)})`);
14
+ },
15
+ };
@@ -0,0 +1,15 @@
1
+ import { User } from "../models/User.js";
2
+
3
+ // Queued by app/observers/UserObserver when someone signs up, and run by
4
+ // "tylix queue:work", outside the request. Throwing marks the job failed,
5
+ // with the error recorded on its row in the jobs table.
6
+ export const SendWelcomeEmail = {
7
+ async handle(payload) {
8
+ const user = await User.find(payload.userId);
9
+ if (!user) return; // deleted since sign-up: nothing to send
10
+
11
+ // Send a real email with a mailable, as app/mail/mailer does for
12
+ // verification. Logged here so the job is visible in the worker.
13
+ console.log(`Welcome email for ${user.email} (user ${user.id})`);
14
+ },
15
+ };
@@ -1,59 +0,0 @@
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 auth models, validator, controller, mail files and migrations', async () => {
11
- const outputDir = path.join(__dirname, '.tmp-test-output')
12
- await fs.rm(outputDir, { recursive: true, force: true })
13
- await fs.mkdir(outputDir, { recursive: true })
14
-
15
- try {
16
- const results = await new AuthGenerator().generate(outputDir)
17
-
18
- // Every key the generator reports must point at a real file.
19
- const expected = [
20
- 'userModel',
21
- 'refreshTokenModel',
22
- 'passwordResetModel',
23
- 'validator',
24
- 'controller',
25
- 'mailer',
26
- 'verifyEmailMail',
27
- 'resetPasswordMail',
28
- 'verifyEmailView',
29
- 'resetPasswordView',
30
- 'userMigration',
31
- 'refreshTokenMigration',
32
- 'passwordResetMigration',
33
- ]
34
- for (const key of expected) {
35
- assert.ok(results[key], `generate() returned no path for "${key}"`)
36
- await fs.access(results[key])
37
- }
38
-
39
- const read = (key) => fs.readFile(results[key], 'utf-8')
40
-
41
- assert.match(await read('userModel'), /export class User extends Model/)
42
- assert.match(await read('refreshTokenModel'), /export class RefreshToken/)
43
- assert.match(await read('passwordResetModel'), /export class PasswordReset/)
44
- assert.match(await read('validator'), /export function validateRegister/)
45
- assert.match(await read('validator'), /export function validateLogin/)
46
-
47
- const controller = await read('controller')
48
- assert.match(controller, /export class AuthController/)
49
- assert.match(controller, /async register\(req, res\)/)
50
- assert.match(controller, /async login\(req, res\)/)
51
- assert.match(controller, /async me\(req, res\)/)
52
-
53
- assert.match(await read('userMigration'), /createTable\("users"/)
54
- assert.match(await read('refreshTokenMigration'), /createTable\("refresh_tokens"/)
55
- assert.match(await read('passwordResetMigration'), /createTable\("password_resets"/)
56
- } finally {
57
- await fs.rm(outputDir, { recursive: true, force: true })
58
- }
59
- })
@@ -1,32 +0,0 @@
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
- });
@@ -1,49 +0,0 @@
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
- });