authkit-api 1.0.0 → 1.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/CHANGELOG.md +10 -1
- package/README.md +21 -5
- package/package.json +12 -5
- package/src/constants.js +5 -0
- package/src/generator.js +37 -7
- package/src/index.js +12 -2
- package/src/prompts.js +20 -4
- package/templates/base/README.md +5 -5
- package/templates/base/package.json +4 -4
- package/templates/base/scripts/docker-entrypoint.sh +1 -1
- package/templates/base/scripts/generate-postman.ts +102 -0
- package/templates/base/scripts/seed-admin.ts +62 -0
- package/templates/base/src/app.ts +46 -0
- package/templates/base/src/config/env.schema.ts +85 -0
- package/templates/base/src/config/env.ts +15 -0
- package/templates/base/src/config/logger.ts +20 -0
- package/templates/base/src/constants/examples.ts +3 -0
- package/templates/base/src/constants/roles.ts +4 -0
- package/templates/base/src/constants/user.rules.ts +16 -0
- package/templates/base/src/docs/openapi.registry.ts +90 -0
- package/templates/base/src/docs/openapi.ts +36 -0
- package/templates/base/src/docs/paths/auth.paths.ts +88 -0
- package/templates/base/src/docs/paths/user.paths.ts +88 -0
- package/templates/base/src/middlewares/authenticate.ts +20 -0
- package/templates/base/src/middlewares/authorize.ts +13 -0
- package/templates/base/src/middlewares/errorHandler.ts +52 -0
- package/templates/base/src/middlewares/notFound.ts +6 -0
- package/templates/base/src/middlewares/rateLimiter.ts +20 -0
- package/templates/base/src/middlewares/validate.ts +39 -0
- package/templates/base/src/modules/auth/auth.controller.ts +45 -0
- package/templates/base/src/modules/auth/auth.cookie.ts +22 -0
- package/templates/base/src/modules/auth/auth.routes.ts +12 -0
- package/templates/base/src/modules/auth/auth.service.ts +81 -0
- package/templates/base/src/modules/auth/auth.validation.ts +44 -0
- package/templates/base/src/modules/user/user.controller.ts +24 -0
- package/templates/base/src/modules/user/user.routes.ts +22 -0
- package/templates/base/src/modules/user/user.service.ts +57 -0
- package/templates/base/src/modules/user/user.validation.ts +27 -0
- package/templates/base/src/routes/docs.routes.ts +16 -0
- package/templates/base/src/routes/health.routes.ts +17 -0
- package/templates/base/src/routes/index.ts +13 -0
- package/templates/base/src/server.ts +51 -0
- package/templates/base/src/types/express.d.ts +14 -0
- package/templates/base/src/utils/ApiError.ts +35 -0
- package/templates/base/src/utils/apiResponse.ts +24 -0
- package/templates/base/src/utils/password.ts +14 -0
- package/templates/base/src/utils/token.ts +60 -0
- package/templates/base/src/utils/zod.ts +5 -0
- package/templates/base/tests/app.test.ts +67 -0
- package/templates/base/tests/auth.test.ts +194 -0
- package/templates/base/tests/authenticate.test.ts +61 -0
- package/templates/base/tests/docs.test.ts +127 -0
- package/templates/base/tests/env.test.ts +96 -0
- package/templates/base/tests/health.test.ts +21 -0
- package/templates/base/tests/helpers/auth.helper.ts +49 -0
- package/templates/base/tests/password.test.ts +18 -0
- package/templates/base/tests/postman.test.ts +32 -0
- package/templates/base/tests/rateLimiter.test.ts +27 -0
- package/templates/base/tests/seedAdmin.test.ts +42 -0
- package/templates/base/tests/token.test.ts +69 -0
- package/templates/base/tests/trustProxy.test.ts +24 -0
- package/templates/base/tests/user.repository.test.ts +211 -0
- package/templates/base/tests/user.test.ts +145 -0
- package/templates/base/tests/validate.test.ts +42 -0
- package/templates/base/tests/validation.test.ts +62 -0
- package/templates/base/vitest.config.ts +16 -0
- package/templates/databases/mongodb/README.part.md +1 -1
- package/templates/databases/mongodb/src/database/connection.ts +46 -0
- package/templates/databases/mongodb/src/database/env.schema.ts +3 -0
- package/templates/databases/mongodb/src/database/id.schema.ts +3 -0
- package/templates/databases/mongodb/src/database/models/refreshToken.model.ts +24 -0
- package/templates/databases/mongodb/src/database/models/user.model.ts +52 -0
- package/templates/databases/mongodb/src/modules/user/user.repository.ts +91 -0
- package/templates/databases/mongodb/tests/globalSetup.ts +13 -0
- package/templates/databases/mongodb/tests/setup.ts +17 -0
- package/templates/databases/postgres/README.part.md +1 -1
- package/templates/databases/postgres/prisma.config.ts +14 -0
- package/templates/databases/postgres/src/database/connection.ts +72 -0
- package/templates/databases/postgres/src/database/env.schema.ts +3 -0
- package/templates/databases/postgres/src/database/id.schema.ts +3 -0
- package/templates/databases/postgres/src/database/prisma.ts +9 -0
- package/templates/databases/postgres/src/modules/user/user.repository.ts +111 -0
- package/templates/databases/postgres/tests/connection.test.ts +19 -0
- package/templates/databases/postgres/tests/globalSetup.ts +66 -0
- package/templates/databases/postgres/tests/prismaSchema.test.ts +27 -0
- package/templates/databases/postgres/tests/setup.ts +15 -0
- package/templates/languages/ts/eslint.config.js +30 -0
- package/templates/languages/ts/package.part.json +21 -0
- package/templates/languages/ts/tsconfig.json +15 -0
- package/templates-js/base/Dockerfile +22 -0
- package/templates-js/base/README.md +108 -0
- package/templates-js/base/_dockerignore +16 -0
- package/templates-js/base/_env.example +25 -0
- package/templates-js/base/_gitignore +5 -0
- package/templates-js/base/_husky/pre-commit +1 -0
- package/templates-js/base/_prettierignore +5 -0
- package/templates-js/base/_prettierrc +1 -0
- package/templates-js/base/package.json +62 -0
- package/templates-js/base/scripts/docker-entrypoint.sh +9 -0
- package/templates-js/databases/mongodb/README.part.md +23 -0
- package/templates-js/databases/mongodb/_github/workflows/ci.yml +29 -0
- package/templates-js/databases/mongodb/docker-compose.yml +30 -0
- package/templates-js/databases/mongodb/env.part +2 -0
- package/templates-js/databases/mongodb/package.part.json +4 -0
- package/templates-js/databases/postgres/README.part.md +31 -0
- package/templates-js/databases/postgres/_github/workflows/ci.yml +46 -0
- package/templates-js/databases/postgres/docker-compose.yml +34 -0
- package/templates-js/databases/postgres/env.part +2 -0
- package/templates-js/databases/postgres/package.part.json +15 -0
- package/templates-js/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
- package/templates-js/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
- package/templates-js/databases/postgres/prisma/schema.prisma +39 -0
- /package/templates/{base → languages/js}/eslint.config.js +0 -0
- /package/{templates → templates-js}/base/scripts/generate-postman.js +0 -0
- /package/{templates → templates-js}/base/scripts/seed-admin.js +0 -0
- /package/{templates → templates-js}/base/src/app.js +0 -0
- /package/{templates → templates-js}/base/src/config/env.js +0 -0
- /package/{templates → templates-js}/base/src/config/env.schema.js +0 -0
- /package/{templates → templates-js}/base/src/config/logger.js +0 -0
- /package/{templates → templates-js}/base/src/constants/examples.js +0 -0
- /package/{templates → templates-js}/base/src/constants/roles.js +0 -0
- /package/{templates → templates-js}/base/src/constants/user.rules.js +0 -0
- /package/{templates → templates-js}/base/src/docs/openapi.js +0 -0
- /package/{templates → templates-js}/base/src/docs/openapi.registry.js +0 -0
- /package/{templates → templates-js}/base/src/docs/paths/auth.paths.js +0 -0
- /package/{templates → templates-js}/base/src/docs/paths/user.paths.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/authenticate.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/authorize.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/errorHandler.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/notFound.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/rateLimiter.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/validate.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.controller.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.cookie.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.routes.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.service.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.validation.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.controller.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.routes.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.service.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.validation.js +0 -0
- /package/{templates → templates-js}/base/src/routes/docs.routes.js +0 -0
- /package/{templates → templates-js}/base/src/routes/health.routes.js +0 -0
- /package/{templates → templates-js}/base/src/routes/index.js +0 -0
- /package/{templates → templates-js}/base/src/server.js +0 -0
- /package/{templates → templates-js}/base/src/utils/ApiError.js +0 -0
- /package/{templates → templates-js}/base/src/utils/apiResponse.js +0 -0
- /package/{templates → templates-js}/base/src/utils/password.js +0 -0
- /package/{templates → templates-js}/base/src/utils/token.js +0 -0
- /package/{templates → templates-js}/base/src/utils/zod.js +0 -0
- /package/{templates → templates-js}/base/tests/app.test.js +0 -0
- /package/{templates → templates-js}/base/tests/auth.test.js +0 -0
- /package/{templates → templates-js}/base/tests/authenticate.test.js +0 -0
- /package/{templates → templates-js}/base/tests/docs.test.js +0 -0
- /package/{templates → templates-js}/base/tests/env.test.js +0 -0
- /package/{templates → templates-js}/base/tests/health.test.js +0 -0
- /package/{templates → templates-js}/base/tests/helpers/auth.helper.js +0 -0
- /package/{templates → templates-js}/base/tests/password.test.js +0 -0
- /package/{templates → templates-js}/base/tests/postman.test.js +0 -0
- /package/{templates → templates-js}/base/tests/rateLimiter.test.js +0 -0
- /package/{templates → templates-js}/base/tests/seedAdmin.test.js +0 -0
- /package/{templates → templates-js}/base/tests/token.test.js +0 -0
- /package/{templates → templates-js}/base/tests/trustProxy.test.js +0 -0
- /package/{templates → templates-js}/base/tests/user.repository.test.js +0 -0
- /package/{templates → templates-js}/base/tests/user.test.js +0 -0
- /package/{templates → templates-js}/base/tests/validate.test.js +0 -0
- /package/{templates → templates-js}/base/tests/validation.test.js +0 -0
- /package/{templates → templates-js}/base/vitest.config.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/connection.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/env.schema.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/id.schema.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/models/refreshToken.model.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/models/user.model.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/modules/user/user.repository.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/tests/globalSetup.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/tests/setup.js +0 -0
- /package/{templates → templates-js}/databases/postgres/prisma.config.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/connection.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/env.schema.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/id.schema.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/prisma.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/modules/user/user.repository.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/connection.test.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/globalSetup.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/prismaSchema.test.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/setup.js +0 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import { ROLE_VALUES, ROLES } from '../../constants/roles.ts';
|
|
3
|
+
import { USER_RULES } from '../../constants/user.rules.ts';
|
|
4
|
+
import type { HydratedDocument, InferSchemaType, Types } from 'mongoose';
|
|
5
|
+
|
|
6
|
+
const userSchema = new mongoose.Schema(
|
|
7
|
+
{
|
|
8
|
+
name: {
|
|
9
|
+
type: String,
|
|
10
|
+
required: true,
|
|
11
|
+
trim: true,
|
|
12
|
+
minlength: USER_RULES.NAME.MIN,
|
|
13
|
+
maxlength: USER_RULES.NAME.MAX,
|
|
14
|
+
},
|
|
15
|
+
email: {
|
|
16
|
+
type: String,
|
|
17
|
+
required: true,
|
|
18
|
+
unique: true,
|
|
19
|
+
lowercase: true,
|
|
20
|
+
trim: true,
|
|
21
|
+
maxlength: USER_RULES.EMAIL.MAX,
|
|
22
|
+
},
|
|
23
|
+
// Select: false keeps the hash out of every query unless asked for.
|
|
24
|
+
password: { type: String, required: true, select: false },
|
|
25
|
+
role: { type: String, enum: ROLE_VALUES, default: ROLES.USER },
|
|
26
|
+
},
|
|
27
|
+
{ timestamps: true },
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
interface UserJson {
|
|
31
|
+
// The plain object Mongoose hands to the transform, reshaped in place into a public user.
|
|
32
|
+
_id?: Types.ObjectId;
|
|
33
|
+
__v?: number;
|
|
34
|
+
password?: string;
|
|
35
|
+
id?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The only shape a user ever leaves the database layer in.
|
|
39
|
+
function toPublic(_doc: unknown, ret: UserJson) {
|
|
40
|
+
ret.id = ret._id!.toString();
|
|
41
|
+
delete ret._id;
|
|
42
|
+
delete ret.__v;
|
|
43
|
+
delete ret.password;
|
|
44
|
+
return ret;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
userSchema.set('toJSON', { transform: toPublic });
|
|
48
|
+
userSchema.set('toObject', { transform: toPublic });
|
|
49
|
+
|
|
50
|
+
export const User = mongoose.model('User', userSchema);
|
|
51
|
+
|
|
52
|
+
export type UserDocument = HydratedDocument<InferSchemaType<typeof userSchema>>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { RefreshToken } from '../../database/models/refreshToken.model.ts';
|
|
2
|
+
import { User } from '../../database/models/user.model.ts';
|
|
3
|
+
import type { Role } from '../../constants/roles.ts';
|
|
4
|
+
import type { UserDocument } from '../../database/models/user.model.ts';
|
|
5
|
+
import type { PublicUser } from '../../docs/openapi.registry.ts';
|
|
6
|
+
import type { UserRepository, UserWithPassword } from './user.service.ts';
|
|
7
|
+
|
|
8
|
+
type CreateUserInput = Parameters<UserRepository['create']>[0];
|
|
9
|
+
|
|
10
|
+
// The one place a Mongoose document becomes a plain public user.
|
|
11
|
+
const toPublicUser = <T extends UserDocument | null>(doc: T) =>
|
|
12
|
+
(doc ? doc.toJSON() : null) as T extends UserDocument ? PublicUser : null;
|
|
13
|
+
|
|
14
|
+
export async function findById(id: string) {
|
|
15
|
+
return toPublicUser(await User.findById(id));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function findByEmail(
|
|
19
|
+
email: string,
|
|
20
|
+
options?: { withPassword?: false },
|
|
21
|
+
): Promise<PublicUser | null>;
|
|
22
|
+
export function findByEmail(
|
|
23
|
+
email: string,
|
|
24
|
+
options: { withPassword: true },
|
|
25
|
+
): Promise<UserWithPassword | null>;
|
|
26
|
+
export async function findByEmail(email: string, { withPassword = false } = {}) {
|
|
27
|
+
const query = User.findOne({ email: email.trim().toLowerCase() });
|
|
28
|
+
if (withPassword) query.select('+password');
|
|
29
|
+
const doc = await query;
|
|
30
|
+
if (!doc) return null;
|
|
31
|
+
const user = toPublicUser(doc);
|
|
32
|
+
return withPassword ? { ...user, password: doc.password } : user;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function create({ name, email, password, role }: CreateUserInput) {
|
|
36
|
+
return toPublicUser(await User.create({ name, email, password, role }));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function findMany({ page, limit }: { page: number; limit: number }) {
|
|
40
|
+
const [docs, total] = await Promise.all([
|
|
41
|
+
User.find()
|
|
42
|
+
.sort({ createdAt: -1, _id: -1 })
|
|
43
|
+
.skip((page - 1) * limit)
|
|
44
|
+
.limit(limit),
|
|
45
|
+
User.countDocuments(),
|
|
46
|
+
]);
|
|
47
|
+
return { users: docs.map(toPublicUser), total };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function updateRole(id: string, role: Role) {
|
|
51
|
+
return toPublicUser(
|
|
52
|
+
await User.findByIdAndUpdate(id, { role }, { runValidators: true, returnDocument: 'after' }),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function deleteById(id: string) {
|
|
57
|
+
const deleted = await User.findByIdAndDelete(id);
|
|
58
|
+
if (!deleted) return false;
|
|
59
|
+
await RefreshToken.deleteMany({ userId: id });
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function saveRefreshToken({
|
|
64
|
+
userId,
|
|
65
|
+
tokenHash,
|
|
66
|
+
expiresAt,
|
|
67
|
+
}: {
|
|
68
|
+
userId: string;
|
|
69
|
+
tokenHash: string;
|
|
70
|
+
expiresAt: Date;
|
|
71
|
+
}) {
|
|
72
|
+
await RefreshToken.create({ userId, tokenHash, expiresAt });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function findRefreshToken(tokenHash: string) {
|
|
76
|
+
const doc = await RefreshToken.findOne({ tokenHash });
|
|
77
|
+
if (!doc) return null;
|
|
78
|
+
return { userId: doc.userId.toString(), expiresAt: doc.expiresAt, revokedAt: doc.revokedAt };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function revokeRefreshToken(tokenHash: string) {
|
|
82
|
+
const result = await RefreshToken.updateOne(
|
|
83
|
+
{ tokenHash, revokedAt: null },
|
|
84
|
+
{ revokedAt: new Date() },
|
|
85
|
+
);
|
|
86
|
+
return result.modifiedCount > 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function revokeAllRefreshTokens(userId: string) {
|
|
90
|
+
await RefreshToken.updateMany({ userId, revokedAt: null }, { revokedAt: new Date() });
|
|
91
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { MongoMemoryServer } from 'mongodb-memory-server';
|
|
2
|
+
|
|
3
|
+
let mongoServer: MongoMemoryServer | undefined;
|
|
4
|
+
|
|
5
|
+
// Starts one in-memory MongoDB for the whole test run, so no local MongoDB is needed.
|
|
6
|
+
export async function setup() {
|
|
7
|
+
mongoServer = await MongoMemoryServer.create();
|
|
8
|
+
process.env.MONGODB_URI = mongoServer.getUri('test');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function teardown() {
|
|
12
|
+
await mongoServer?.stop();
|
|
13
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import mongoose from 'mongoose';
|
|
2
|
+
import { afterAll, afterEach, beforeAll } from 'vitest';
|
|
3
|
+
import { connectDatabase, disconnectDatabase } from '../src/database/connection.ts';
|
|
4
|
+
|
|
5
|
+
beforeAll(async () => {
|
|
6
|
+
await connectDatabase();
|
|
7
|
+
// Build the unique indexes before the first test so duplicate checks are reliable.
|
|
8
|
+
await Promise.all(Object.values(mongoose.models).map((model) => model.syncIndexes()));
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
afterEach(async () => {
|
|
12
|
+
await Promise.all(Object.values(mongoose.connection.collections).map((c) => c.deleteMany({})));
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
afterAll(async () => {
|
|
16
|
+
await disconnectDatabase();
|
|
17
|
+
});
|
|
@@ -28,4 +28,4 @@ PostgreSQL with Prisma. The generated client lives in `src/generated/prisma` and
|
|
|
28
28
|
|
|
29
29
|
**Docker port.** The compose database is published on host port `5432`. If you already run Postgres there, pick another port, for example `POSTGRES_PORT=5433`: set it when you run `docker compose up -d --wait db` or `npm run docker:up`, and put the same port in `DATABASE_URL` in `.env` (tests read it too). In Docker, the container applies migrations itself on start.
|
|
30
30
|
|
|
31
|
-
**Adding a user field.** Add the column to `model User` in `prisma/schema.prisma`, run `npm run db:migrate -- --name add_phone`, then add the field to `publicUserSelect` and to `create` in `src/modules/user/user.repository.
|
|
31
|
+
**Adding a user field.** Add the column to `model User` in `prisma/schema.prisma`, run `npm run db:migrate -- --name add_phone`, then add the field to `publicUserSelect` and to `create` in `src/modules/user/user.repository.ts`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineConfig } from 'prisma/config';
|
|
2
|
+
|
|
3
|
+
// Prisma 7 no longer reads .env on its own, so load it here (a real environment variable wins).
|
|
4
|
+
try {
|
|
5
|
+
process.loadEnvFile('.env');
|
|
6
|
+
} catch {
|
|
7
|
+
// No .env file: DATABASE_URL must come from the environment.
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
schema: 'prisma/schema.prisma',
|
|
12
|
+
migrations: { path: 'prisma/migrations' },
|
|
13
|
+
datasource: { url: process.env.DATABASE_URL },
|
|
14
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { logger } from '../config/logger.ts';
|
|
2
|
+
import { ApiError } from '../utils/ApiError.ts';
|
|
3
|
+
import { prisma } from './prisma.ts';
|
|
4
|
+
|
|
5
|
+
const HEALTH_TIMEOUT_MS = 1000;
|
|
6
|
+
|
|
7
|
+
interface PrismaError extends Partial<Error> {
|
|
8
|
+
// Anything can reach the error handler. These are the fields read from a Prisma error.
|
|
9
|
+
code?: unknown;
|
|
10
|
+
meta?: {
|
|
11
|
+
target?: unknown;
|
|
12
|
+
driverAdapterError?: {
|
|
13
|
+
cause?: { constraint?: Record<string, unknown>; originalCode?: string };
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function connectDatabase() {
|
|
19
|
+
await prisma.$connect();
|
|
20
|
+
await prisma.$queryRaw`SELECT 1`;
|
|
21
|
+
logger.info('Connected to PostgreSQL');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function disconnectDatabase() {
|
|
25
|
+
await prisma.$disconnect();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// A live check: the pool reconnects on its own, so a flag set at startup would lie.
|
|
29
|
+
export async function isDatabaseConnected() {
|
|
30
|
+
let timer: NodeJS.Timeout | undefined;
|
|
31
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
32
|
+
timer = setTimeout(
|
|
33
|
+
() => reject(new Error('Database health check timed out')),
|
|
34
|
+
HEALTH_TIMEOUT_MS,
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
try {
|
|
38
|
+
await Promise.race([prisma.$queryRaw`SELECT 1`, timeout]);
|
|
39
|
+
return true;
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
} finally {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const INVALID_TEXT_REPRESENTATION = '22P02'; // Postgres: malformed uuid
|
|
48
|
+
|
|
49
|
+
// Turns Prisma errors into ApiErrors. Returns null for anything it does not know.
|
|
50
|
+
export function mapDatabaseError(err: PrismaError | null | undefined) {
|
|
51
|
+
const cause = err?.meta?.driverAdapterError?.cause;
|
|
52
|
+
switch (err?.code) {
|
|
53
|
+
case 'P2002': {
|
|
54
|
+
// The driver adapter reports the violated constraint, e.g. { index: 'users_email_key' }.
|
|
55
|
+
const target = err.meta?.target ?? Object.values(cause?.constraint ?? {});
|
|
56
|
+
const fields = [target].flat().map(String);
|
|
57
|
+
return fields.some((name) => name.includes('email'))
|
|
58
|
+
? ApiError.conflict('Email is already registered')
|
|
59
|
+
: ApiError.conflict('Resource already exists');
|
|
60
|
+
}
|
|
61
|
+
case 'P2025':
|
|
62
|
+
return ApiError.notFound();
|
|
63
|
+
case 'P2023':
|
|
64
|
+
return ApiError.badRequest('Invalid id');
|
|
65
|
+
case 'P2007':
|
|
66
|
+
return cause?.originalCode === INVALID_TEXT_REPRESENTATION
|
|
67
|
+
? ApiError.badRequest('Invalid id')
|
|
68
|
+
: null;
|
|
69
|
+
default:
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { PrismaPg } from '@prisma/adapter-pg';
|
|
2
|
+
import { env } from '../config/env.ts';
|
|
3
|
+
// The generated client is TypeScript; importing it from JS relies on Node's built-in type stripping (Node >=22.18).
|
|
4
|
+
import { PrismaClient } from '../generated/prisma/client.ts';
|
|
5
|
+
|
|
6
|
+
// The one PrismaClient for the whole app.
|
|
7
|
+
export const prisma = new PrismaClient({
|
|
8
|
+
adapter: new PrismaPg({ connectionString: env.DATABASE_URL }),
|
|
9
|
+
});
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { prisma } from '../../database/prisma.ts';
|
|
2
|
+
import type { Role } from '../../constants/roles.ts';
|
|
3
|
+
import type { PublicUser } from '../../docs/openapi.registry.ts';
|
|
4
|
+
import type { Prisma } from '../../generated/prisma/client.ts';
|
|
5
|
+
import type { UserRepository, UserWithPassword } from './user.service.ts';
|
|
6
|
+
|
|
7
|
+
type CreateUserInput = Parameters<UserRepository['create']>[0];
|
|
8
|
+
type PrismaCodeError = { code?: unknown } | null | undefined;
|
|
9
|
+
|
|
10
|
+
// Every query returns only these fields, so the password hash cannot leak by accident.
|
|
11
|
+
const publicUserSelect = {
|
|
12
|
+
id: true,
|
|
13
|
+
name: true,
|
|
14
|
+
email: true,
|
|
15
|
+
role: true,
|
|
16
|
+
createdAt: true,
|
|
17
|
+
updatedAt: true,
|
|
18
|
+
} satisfies Prisma.UserSelect;
|
|
19
|
+
|
|
20
|
+
export async function findById(id: string) {
|
|
21
|
+
return prisma.user.findUnique({ where: { id }, select: publicUserSelect });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function findByEmail(
|
|
25
|
+
email: string,
|
|
26
|
+
options?: { withPassword?: false },
|
|
27
|
+
): Promise<PublicUser | null>;
|
|
28
|
+
export function findByEmail(
|
|
29
|
+
email: string,
|
|
30
|
+
options: { withPassword: true },
|
|
31
|
+
): Promise<UserWithPassword | null>;
|
|
32
|
+
export async function findByEmail(email: string, { withPassword = false } = {}) {
|
|
33
|
+
return prisma.user.findUnique({
|
|
34
|
+
where: { email: email.trim().toLowerCase() },
|
|
35
|
+
select: withPassword ? { ...publicUserSelect, password: true } : publicUserSelect,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function create({ name, email, password, role }: CreateUserInput) {
|
|
40
|
+
return prisma.user.create({
|
|
41
|
+
data: { name, email: email.trim().toLowerCase(), password, role },
|
|
42
|
+
select: publicUserSelect,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function findMany({ page, limit }: { page: number; limit: number }) {
|
|
47
|
+
const [users, total] = await prisma.$transaction([
|
|
48
|
+
prisma.user.findMany({
|
|
49
|
+
select: publicUserSelect,
|
|
50
|
+
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
|
51
|
+
skip: (page - 1) * limit,
|
|
52
|
+
take: limit,
|
|
53
|
+
}),
|
|
54
|
+
prisma.user.count(),
|
|
55
|
+
]);
|
|
56
|
+
return { users, total };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function updateRole(id: string, role: Role) {
|
|
60
|
+
try {
|
|
61
|
+
return await prisma.user.update({ where: { id }, data: { role }, select: publicUserSelect });
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if ((err as PrismaCodeError)?.code === 'P2025') return null;
|
|
64
|
+
throw err;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Refresh tokens are removed by the ON DELETE CASCADE foreign key.
|
|
69
|
+
export async function deleteById(id: string) {
|
|
70
|
+
try {
|
|
71
|
+
await prisma.user.delete({ where: { id } });
|
|
72
|
+
return true;
|
|
73
|
+
} catch (err) {
|
|
74
|
+
if ((err as PrismaCodeError)?.code === 'P2025') return false;
|
|
75
|
+
throw err;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function saveRefreshToken({
|
|
80
|
+
userId,
|
|
81
|
+
tokenHash,
|
|
82
|
+
expiresAt,
|
|
83
|
+
}: {
|
|
84
|
+
userId: string;
|
|
85
|
+
tokenHash: string;
|
|
86
|
+
expiresAt: Date;
|
|
87
|
+
}) {
|
|
88
|
+
await prisma.refreshToken.create({ data: { userId, tokenHash, expiresAt } });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function findRefreshToken(tokenHash: string) {
|
|
92
|
+
return prisma.refreshToken.findUnique({
|
|
93
|
+
where: { tokenHash },
|
|
94
|
+
select: { userId: true, expiresAt: true, revokedAt: true },
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function revokeRefreshToken(tokenHash: string) {
|
|
99
|
+
const { count } = await prisma.refreshToken.updateMany({
|
|
100
|
+
where: { tokenHash, revokedAt: null },
|
|
101
|
+
data: { revokedAt: new Date() },
|
|
102
|
+
});
|
|
103
|
+
return count > 0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function revokeAllRefreshTokens(userId: string) {
|
|
107
|
+
await prisma.refreshToken.updateMany({
|
|
108
|
+
where: { userId, revokedAt: null },
|
|
109
|
+
data: { revokedAt: new Date() },
|
|
110
|
+
});
|
|
111
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { isDatabaseConnected } from '../src/database/connection.ts';
|
|
3
|
+
import { prisma } from '../src/database/prisma.ts';
|
|
4
|
+
|
|
5
|
+
describe('isDatabaseConnected (postgres)', () => {
|
|
6
|
+
afterEach(() => vi.restoreAllMocks());
|
|
7
|
+
|
|
8
|
+
it('is false when the query fails', async () => {
|
|
9
|
+
vi.spyOn(prisma, '$queryRaw').mockRejectedValue(new Error('connection lost'));
|
|
10
|
+
expect(await isDatabaseConnected()).toBe(false);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('is false when the database does not answer in time', async () => {
|
|
14
|
+
vi.spyOn(prisma, '$queryRaw').mockReturnValue(
|
|
15
|
+
new Promise(() => {}) as ReturnType<typeof prisma.$queryRaw>,
|
|
16
|
+
);
|
|
17
|
+
expect(await isDatabaseConnected()).toBe(false);
|
|
18
|
+
});
|
|
19
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { parseEnv } from 'node:util';
|
|
4
|
+
import pg from 'pg';
|
|
5
|
+
|
|
6
|
+
type Errno = NodeJS.ErrnoException | null | undefined;
|
|
7
|
+
|
|
8
|
+
const DEFAULT_URL = 'postgresql://postgres:postgres@localhost:5432/app';
|
|
9
|
+
const ENV_FILE = new URL('../.env', import.meta.url);
|
|
10
|
+
const NOT_RUNNING_MESSAGE = `Cannot reach Postgres. Start it first: docker compose up -d --wait db
|
|
11
|
+
(or set DATABASE_URL to a running server).`;
|
|
12
|
+
|
|
13
|
+
// A real environment variable wins, then DATABASE_URL from .env. Only that one
|
|
14
|
+
// variable is read, so the rest of .env cannot change the test setup.
|
|
15
|
+
function databaseUrl() {
|
|
16
|
+
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
|
|
17
|
+
if (existsSync(ENV_FILE)) {
|
|
18
|
+
const fromFile = parseEnv(readFileSync(ENV_FILE, 'utf8')).DATABASE_URL;
|
|
19
|
+
if (fromFile) return fromFile;
|
|
20
|
+
}
|
|
21
|
+
return DEFAULT_URL;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function exitNotRunning() {
|
|
25
|
+
console.error(NOT_RUNNING_MESSAGE);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Creates `<db>_test` on the same server if needed, points DATABASE_URL at it, and applies migrations.
|
|
30
|
+
export async function setup() {
|
|
31
|
+
const url = new URL(databaseUrl());
|
|
32
|
+
const testDatabase = `${url.pathname.slice(1).replace(/_test$/, '')}_test`;
|
|
33
|
+
|
|
34
|
+
const admin = new URL(url);
|
|
35
|
+
admin.pathname = '/postgres';
|
|
36
|
+
const client = new pg.Client({ connectionString: admin.toString() });
|
|
37
|
+
try {
|
|
38
|
+
await client.connect();
|
|
39
|
+
const { rowCount } = await client.query('SELECT 1 FROM pg_database WHERE datname = $1', [
|
|
40
|
+
testDatabase,
|
|
41
|
+
]);
|
|
42
|
+
if (rowCount === 0) await client.query(`CREATE DATABASE "${testDatabase}"`);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (
|
|
45
|
+
(err as Errno)?.code === 'ECONNREFUSED' ||
|
|
46
|
+
(err as Errno)?.code === 'ENOTFOUND' ||
|
|
47
|
+
(err as Errno)?.code === 'ETIMEDOUT'
|
|
48
|
+
) {
|
|
49
|
+
exitNotRunning();
|
|
50
|
+
}
|
|
51
|
+
if (err instanceof AggregateError) exitNotRunning();
|
|
52
|
+
throw err;
|
|
53
|
+
} finally {
|
|
54
|
+
await client.end().catch(() => {});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
url.pathname = `/${testDatabase}`;
|
|
58
|
+
process.env.DATABASE_URL = url.toString();
|
|
59
|
+
execSync('npx prisma migrate deploy', {
|
|
60
|
+
stdio: 'pipe',
|
|
61
|
+
env: process.env,
|
|
62
|
+
cwd: new URL('..', import.meta.url),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function teardown() {}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { ROLE_VALUES } from '../src/constants/roles.ts';
|
|
4
|
+
import { USER_RULES } from '../src/constants/user.rules.ts';
|
|
5
|
+
|
|
6
|
+
// Prisma's schema cannot import JS, so this guards against the limits drifting apart.
|
|
7
|
+
const schema = readFileSync(new URL('../prisma/schema.prisma', import.meta.url), 'utf8');
|
|
8
|
+
|
|
9
|
+
describe('prisma schema', () => {
|
|
10
|
+
it('uses the name length from user.rules.ts', () => {
|
|
11
|
+
expect(schema).toMatch(
|
|
12
|
+
new RegExp(String.raw`\bname\s+String\s+@db\.VarChar\(${USER_RULES.NAME.MAX}\)`),
|
|
13
|
+
);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('uses the email length from user.rules.ts and makes it unique', () => {
|
|
17
|
+
expect(schema).toMatch(
|
|
18
|
+
new RegExp(String.raw`\bemail\s+String\s+@unique\s+@db\.VarChar\(${USER_RULES.EMAIL.MAX}\)`),
|
|
19
|
+
);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('has a Role enum equal to ROLE_VALUES', () => {
|
|
23
|
+
const body = schema.match(/enum\s+Role\s*\{([^}]*)\}/)?.[1] ?? '';
|
|
24
|
+
const values = body.split(/\s+/).filter(Boolean);
|
|
25
|
+
expect(values).toEqual([...ROLE_VALUES]);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { afterAll, afterEach, beforeAll } from 'vitest';
|
|
2
|
+
import { connectDatabase, disconnectDatabase } from '../src/database/connection.ts';
|
|
3
|
+
import { prisma } from '../src/database/prisma.ts';
|
|
4
|
+
|
|
5
|
+
beforeAll(async () => {
|
|
6
|
+
await connectDatabase();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
afterEach(async () => {
|
|
10
|
+
await prisma.$executeRawUnsafe('TRUNCATE users, refresh_tokens CASCADE');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
afterAll(async () => {
|
|
14
|
+
await disconnectDatabase();
|
|
15
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import js from '@eslint/js';
|
|
2
|
+
import globals from 'globals';
|
|
3
|
+
import prettier from 'eslint-config-prettier';
|
|
4
|
+
import tseslint from 'typescript-eslint';
|
|
5
|
+
|
|
6
|
+
export default [
|
|
7
|
+
{
|
|
8
|
+
ignores: ['node_modules', 'coverage', 'prisma/migrations', 'src/generated'],
|
|
9
|
+
},
|
|
10
|
+
js.configs.recommended,
|
|
11
|
+
...tseslint.configs.recommended,
|
|
12
|
+
{
|
|
13
|
+
languageOptions: {
|
|
14
|
+
ecmaVersion: 'latest',
|
|
15
|
+
sourceType: 'module',
|
|
16
|
+
globals: globals.node,
|
|
17
|
+
},
|
|
18
|
+
rules: {
|
|
19
|
+
'no-unused-vars': 'off',
|
|
20
|
+
'@typescript-eslint/no-unused-vars': [
|
|
21
|
+
'error',
|
|
22
|
+
{ argsIgnorePattern: '^_', ignoreRestSiblings: true },
|
|
23
|
+
],
|
|
24
|
+
'@typescript-eslint/no-explicit-any': 'error',
|
|
25
|
+
'prefer-const': 'error',
|
|
26
|
+
eqeqeq: 'error',
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
prettier,
|
|
30
|
+
];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"scripts": {
|
|
3
|
+
"lint": "tsc --noEmit && eslint .",
|
|
4
|
+
"typecheck": "tsc --noEmit"
|
|
5
|
+
},
|
|
6
|
+
"lint-staged": {
|
|
7
|
+
"*.{js,ts}": ["eslint --fix", "prettier --write"],
|
|
8
|
+
"*.{json,md,yml}": ["prettier --write"]
|
|
9
|
+
},
|
|
10
|
+
"devDependencies": {
|
|
11
|
+
"@types/cookie-parser": "^1.4.10",
|
|
12
|
+
"@types/cors": "^2.8.19",
|
|
13
|
+
"@types/express": "^5.0.6",
|
|
14
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
15
|
+
"@types/node": "^22.20.5",
|
|
16
|
+
"@types/supertest": "^7.2.1",
|
|
17
|
+
"@types/swagger-ui-express": "^4.1.8",
|
|
18
|
+
"typescript": "~6.0.3",
|
|
19
|
+
"typescript-eslint": "^8.73.0"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "esnext",
|
|
4
|
+
"module": "nodenext",
|
|
5
|
+
"moduleResolution": "nodenext",
|
|
6
|
+
"strict": true,
|
|
7
|
+
"noEmit": true,
|
|
8
|
+
"allowImportingTsExtensions": true,
|
|
9
|
+
"verbatimModuleSyntax": true,
|
|
10
|
+
"erasableSyntaxOnly": true,
|
|
11
|
+
"skipLibCheck": true,
|
|
12
|
+
"types": ["node"]
|
|
13
|
+
},
|
|
14
|
+
"include": ["src", "scripts", "tests", "*.ts"]
|
|
15
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Stage 1: install all dependencies (dev ones are needed for the build step).
|
|
2
|
+
FROM node:24-alpine AS deps
|
|
3
|
+
WORKDIR /app
|
|
4
|
+
COPY package.json package-lock.json ./
|
|
5
|
+
RUN npm ci --ignore-scripts
|
|
6
|
+
|
|
7
|
+
# Stage 2: copy the source, generate the Prisma client (Postgres only), drop dev dependencies.
|
|
8
|
+
FROM deps AS build
|
|
9
|
+
COPY . .
|
|
10
|
+
RUN if [ -f prisma/schema.prisma ]; then npx prisma generate; fi
|
|
11
|
+
RUN npm prune --omit=dev
|
|
12
|
+
|
|
13
|
+
# Stage 3: small runtime image that runs as the non-root "node" user.
|
|
14
|
+
FROM node:24-alpine AS runner
|
|
15
|
+
ENV NODE_ENV=production
|
|
16
|
+
WORKDIR /app
|
|
17
|
+
COPY --from=build --chown=node:node /app ./
|
|
18
|
+
USER node
|
|
19
|
+
EXPOSE 3000
|
|
20
|
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
|
21
|
+
CMD wget -qO- http://localhost:3000/health || exit 1
|
|
22
|
+
CMD ["sh", "scripts/docker-entrypoint.sh"]
|