Setup initial project

This commit is contained in:
Aerilyn Weber 2026-03-27 14:50:34 +09:00
commit db79af06f7
119 changed files with 20761 additions and 0 deletions

View file

@ -0,0 +1,40 @@
import tseslint from 'typescript-eslint';
import prettierRecommended from 'eslint-plugin-prettier/recommended';
export default tseslint.config(
{ ignores: ['dist/**', 'coverage/**', 'eslint.config.js'] },
...tseslint.configs.recommended,
{
languageOptions: {
parserOptions: {
tsconfigRootDir: import.meta.dirname, // points to packages/api
project: ['./tsconfig.json', './tsconfig.test.json'],
},
},
rules: {
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-member-accessibility': ['error', { accessibility: 'explicit' }],
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
'@typescript-eslint/consistent-type-imports': [
'error',
{ prefer: 'type-imports', fixStyle: 'inline-type-imports' },
],
},
},
{
// Relax some rules in test files
files: ['**/*.test.ts'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-member-accessibility': 'off',
},
},
prettierRecommended,
);

47
packages/api/package.json Normal file
View file

@ -0,0 +1,47 @@
{
"name": "@meshitrack/api",
"version": "0.0.1",
"private": true,
"type": "module",
"scripts": {
"build": "tsc",
"dev": "tsx watch src/main.ts",
"start": "node dist/main.js",
"lint": "eslint src",
"lint-fix": "eslint src --fix",
"test": "vitest run",
"test:watch": "vitest",
"test:cov": "vitest run --coverage",
"typecheck": "tsc --noEmit",
"clean": "rimraf dist tsconfig.tsbuildinfo",
"seed": "tsx --env-file ../../.env src/scripts/seed.ts"
},
"dependencies": {
"@fastify/awilix": "^8.2.0",
"@fastify/compress": "^8.3.1",
"@fastify/cookie": "^11.0.2",
"@fastify/cors": "^11.2.0",
"@fastify/helmet": "^13.0.2",
"@fastify/rate-limit": "^10.3.0",
"@fastify/swagger": "^9.7.0",
"@fastify/swagger-ui": "^5.2.5",
"@meshitrack/shared": "*",
"awilix": "^13.0.3",
"fastify": "^5.8.4",
"fastify-plugin": "^5.1.0",
"fastify-type-provider-zod": "^6.1.0",
"jose": "^6.2.2",
"mongoose": "^9.3.3",
"uuid": "^13.0.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/node": "^25.5.0",
"@vitest/coverage-v8": "^4.1.1",
"pino-pretty": "^13.1.3",
"rimraf": "^6.1.3",
"tsx": "^4.21.0",
"typescript": "^6.0.2",
"vitest": "^4.1.1"
}
}

View file

@ -0,0 +1,85 @@
import { describe, it, expect } from 'vitest';
import {
AppError,
NotFoundError,
UnauthorizedError,
ForbiddenError,
ConflictError,
BadRequestError,
} from './errors.js';
describe(AppError.name, () => {
it('sets statusCode, error, message, and details', () => {
const details = { field: ['required'] };
const err = new AppError(422, 'Unprocessable', 'Bad input', details);
expect(err).toBeInstanceOf(Error);
expect(err).toBeInstanceOf(AppError);
expect(err.statusCode).toBe(422);
expect(err.error).toBe('Unprocessable');
expect(err.message).toBe('Bad input');
expect(err.details).toEqual(details);
});
it('works without details', () => {
const err = new AppError(500, 'Internal', 'Oops');
expect(err.details).toBeUndefined();
});
});
describe(NotFoundError.name, () => {
it('defaults to 404 with standard message', () => {
const err = new NotFoundError();
expect(err.statusCode).toBe(404);
expect(err.error).toBe('Not Found');
expect(err.message).toBe('Resource not found');
});
it('accepts custom message', () => {
const err = new NotFoundError('User not found');
expect(err.message).toBe('User not found');
});
});
describe(UnauthorizedError.name, () => {
it('defaults to 401', () => {
const err = new UnauthorizedError();
expect(err.statusCode).toBe(401);
expect(err.error).toBe('Unauthorized');
expect(err.message).toBe('Unauthorized');
});
});
describe(ForbiddenError.name, () => {
it('defaults to 403', () => {
const err = new ForbiddenError();
expect(err.statusCode).toBe(403);
expect(err.error).toBe('Forbidden');
expect(err.message).toBe('Forbidden');
});
});
describe(ConflictError.name, () => {
it('defaults to 409', () => {
const err = new ConflictError();
expect(err.statusCode).toBe(409);
expect(err.error).toBe('Conflict');
expect(err.message).toBe('Conflict');
});
});
describe(BadRequestError.name, () => {
it('defaults to 400', () => {
const err = new BadRequestError();
expect(err.statusCode).toBe(400);
expect(err.error).toBe('Bad Request');
expect(err.message).toBe('Bad Request');
});
it('accepts message and details', () => {
const details = { name: ['too short'] };
const err = new BadRequestError('Invalid input', details);
expect(err.message).toBe('Invalid input');
expect(err.details).toEqual(details);
});
});

View file

@ -0,0 +1,49 @@
export class AppError extends Error {
public readonly statusCode: number;
public readonly error: string;
public readonly details?: Record<string, string[]>;
public constructor(
statusCode: number,
error: string,
message: string,
details?: Record<string, string[]>,
) {
super(message);
this.statusCode = statusCode;
this.error = error;
this.details = details;
Object.setPrototypeOf(this, new.target.prototype);
this.name = new.target.name;
}
}
export class NotFoundError extends AppError {
public constructor(message = 'Resource not found') {
super(404, 'Not Found', message);
}
}
export class UnauthorizedError extends AppError {
public constructor(message = 'Unauthorized') {
super(401, 'Unauthorized', message);
}
}
export class ForbiddenError extends AppError {
public constructor(message = 'Forbidden') {
super(403, 'Forbidden', message);
}
}
export class ConflictError extends AppError {
public constructor(message = 'Conflict') {
super(409, 'Conflict', message);
}
}
export class BadRequestError extends AppError {
public constructor(message = 'Bad Request', details?: Record<string, string[]>) {
super(400, 'Bad Request', message, details);
}
}

View file

@ -0,0 +1,24 @@
import type mongoose from 'mongoose';
export interface AuthUser {
keycloakId: string;
email: string;
displayName: string;
roles: string[];
householdIds: string[];
}
declare module 'fastify' {
interface FastifyRequest {
user: AuthUser;
householdId: string;
}
}
declare module '@fastify/awilix' {
interface Cradle {
mongoose: typeof mongoose;
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface RequestCradle {}
}

View file

@ -0,0 +1,14 @@
import { describe, it, expect } from 'vitest';
import config from './configuration.js';
describe('configuration', () => {
it('exports default config values', () => {
expect(config.port).toBe(3001);
expect(config.mongodb.uri).toContain('mongodb://');
expect(config.keycloak.url).toBe('http://localhost:8080');
expect(config.keycloak.issuerUrl).toBe('http://localhost:8080');
expect(config.keycloak.realm).toBe('meshitrack');
expect(config.keycloak.clientId).toBe('meshitrack-api');
expect(config.cors.origin).toBe('http://localhost:3000');
});
});

View file

@ -0,0 +1,21 @@
const config = {
port: parseInt(process.env['PORT'] || '3001', 10),
mongodb: {
uri:
process.env['MONGODB_URI'] ||
'mongodb://meshitrack:devpassword@localhost:27017/meshitrack?authSource=admin&replicaSet=rs0',
},
keycloak: {
url: process.env['KEYCLOAK_URL'] || 'http://localhost:8080',
issuerUrl:
process.env['KEYCLOAK_ISSUER_URL'] || process.env['KEYCLOAK_URL'] || 'http://localhost:8080',
realm: process.env['KEYCLOAK_REALM'] || 'meshitrack',
clientId: process.env['KEYCLOAK_CLIENT_ID'] || 'meshitrack-api',
},
cors: {
origin: process.env['CORS_ORIGIN'] || 'http://localhost:3000',
},
} as const;
export type Config = typeof config;
export default config;

View file

@ -0,0 +1,188 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock mongoose to prevent real DB connections; provide class-based models
vi.mock('mongoose', () => {
class FakeSchema {
paths: Record<string, unknown> = {};
constructor(def: Record<string, unknown>, _opts?: unknown) {
for (const key of Object.keys(def)) {
this.paths[key] = { path: key };
}
this.paths['createdAt'] = { path: 'createdAt' };
this.paths['updatedAt'] = { path: 'updatedAt' };
}
}
const models: Record<string, unknown> = {};
function createFakeModel(name: string) {
const mockExec = vi.fn().mockResolvedValue(null);
const mockLean = vi.fn(() => ({ exec: mockExec }));
class Model {
_data: Record<string, unknown>;
constructor(data: Record<string, unknown>) {
this._data = data;
Object.assign(this, data);
}
save() {
return Promise.resolve(this);
}
toObject() {
return { _id: `${name}-id`, ...this._data };
}
static modelName = name;
static schema = new FakeSchema({});
static findOne = vi.fn(() => ({ lean: mockLean }));
static findById = vi.fn(() => ({ lean: mockLean }));
static findOneAndUpdate = vi.fn(() => ({ exec: mockExec }));
static findByIdAndUpdate = vi.fn(() => ({ exec: mockExec }));
}
return Model;
}
return {
default: {
Schema: FakeSchema,
model: vi.fn((name: string, _schema?: unknown) => {
if (!models[name]) models[name] = createFakeModel(name);
return models[name];
}),
connect: vi.fn().mockResolvedValue(undefined),
disconnect: vi.fn().mockResolvedValue(undefined),
},
};
});
vi.mock('jose', () => ({
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
jwtVerify: vi.fn(),
}));
import { buildApp } from './main.js';
import * as jose from 'jose';
import { NotFoundError } from './common/errors.js';
describe('buildApp', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('creates a Fastify app that is ready', async () => {
const app = await buildApp({ logger: false });
await app.ready();
expect(app).toBeDefined();
await app.close();
});
it('has the health route available', async () => {
const app = await buildApp({ logger: false });
await app.ready();
const res = await app.inject({ method: 'GET', url: '/api/v1/health' });
expect(res.statusCode).toBe(200);
expect(res.json().status).toBe('ok');
await app.close();
});
});
describe('error handler', () => {
async function getApp() {
// Set up a valid JWT mock for authenticated routes
vi.mocked(jose.jwtVerify).mockResolvedValue({
payload: {
sub: 'kc-1',
email: 'test@example.com',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: { alg: 'RS256' },
key: {} as never,
} as never);
const app = await buildApp({ logger: false });
// Register test routes that throw various errors
app.get('/test/app-error', { config: { public: true } as never }, async () => {
throw new NotFoundError('Test not found');
});
app.get('/test/generic-error', { config: { public: true } as never }, async () => {
const err = new Error('Something broke');
(err as unknown as Record<string, unknown>).statusCode = 422;
throw err;
});
app.get('/test/unknown-error', { config: { public: true } as never }, async () => {
throw new Error('Unexpected');
});
await app.ready();
return app;
}
beforeEach(() => {
vi.clearAllMocks();
});
it('handles AppError with correct status and body', async () => {
const app = await getApp();
const res = await app.inject({ method: 'GET', url: '/test/app-error' });
expect(res.statusCode).toBe(404);
const body = res.json();
expect(body.error).toBe('Not Found');
expect(body.message).toBe('Test not found');
expect(body.timestamp).toBeDefined();
expect(body.path).toBe('/test/app-error');
await app.close();
});
it('handles generic errors with statusCode', async () => {
const app = await getApp();
const res = await app.inject({ method: 'GET', url: '/test/generic-error' });
expect(res.statusCode).toBe(422);
const body = res.json();
expect(body.error).toBe('Error');
expect(body.message).toBe('Something broke');
await app.close();
});
it('handles unknown 500 errors without leaking messages', async () => {
const app = await getApp();
const res = await app.inject({ method: 'GET', url: '/test/unknown-error' });
expect(res.statusCode).toBe(500);
const body = res.json();
expect(body.error).toBe('Internal Server Error');
expect(body.message).toBe('An unexpected error occurred');
await app.close();
});
it('returns 404 for unknown routes', async () => {
const app = await getApp();
const res = await app.inject({
method: 'GET',
url: '/nonexistent',
headers: {
authorization: 'Bearer test-token',
'x-household-id': 'hh1',
},
});
expect(res.statusCode).toBe(404);
await app.close();
});
});

186
packages/api/src/main.ts Normal file
View file

@ -0,0 +1,186 @@
import Fastify from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import compress from '@fastify/compress';
import swagger from '@fastify/swagger';
import swaggerUi from '@fastify/swagger-ui';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import {
serializerCompiler,
validatorCompiler,
jsonSchemaTransform,
hasZodFastifySchemaValidationErrors,
isResponseSerializationError,
} from 'fastify-type-provider-zod';
import type { ApiError } from '@meshitrack/shared';
import config from './config/configuration.js';
import { AppError } from './common/errors.js';
// Import types to enable declaration merging
import './common/types.js';
// Import plugins
import mongoosePlugin from './plugins/mongoose.plugin.js';
import authPlugin from './plugins/auth.plugin.js';
import householdPlugin from './plugins/household.plugin.js';
// Import route modules
import healthRoutes from './modules/health/health.routes.js';
import usersRoutes from './modules/users/users.routes.js';
import householdsRoutes from './modules/households/households.routes.js';
export async function buildApp(opts: { logger?: boolean | object } = {}) {
const app = Fastify({
logger: opts.logger ?? {
level: 'info',
...(process.env['NODE_ENV'] !== 'production' ? { transport: { target: 'pino-pretty' } } : {}),
},
});
// Zod type provider
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);
// Security & compression
await app.register(helmet);
await app.register(cors, { origin: config.cors.origin, credentials: true });
await app.register(compress);
// Swagger / OpenAPI
await app.register(swagger, {
openapi: {
info: {
title: 'MeshiTrack API',
description: 'Nutrition & Pantry Management Platform',
version: '0.0.1',
},
servers: [{ url: `http://localhost:${config.port}` }],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
},
},
security: [{ bearerAuth: [] }],
},
transform: jsonSchemaTransform,
});
await app.register(swaggerUi, { routePrefix: '/api/docs' });
// DI container (Awilix)
await app.register(fastifyAwilixPlugin, {
disposeOnClose: true,
disposeOnResponse: true,
strictBooleanEnforced: true,
});
// Database
await app.register(mongoosePlugin);
// Auth & household guards
await app.register(authPlugin);
await app.register(householdPlugin);
// Route modules
await app.register(healthRoutes);
await app.register(usersRoutes);
await app.register(householdsRoutes);
// Global error handler
app.setErrorHandler((error, request, reply) => {
/* v8 ignore start -- Zod validation errors (tested via integration/E2E) */
if (hasZodFastifySchemaValidationErrors(error)) {
const body: ApiError = {
statusCode: 400,
error: 'Validation Error',
message: 'Request validation failed',
details: formatZodIssues(error.validation),
timestamp: new Date().toISOString(),
path: request.url,
};
return reply.status(400).send(body);
}
/* v8 ignore stop */
/* v8 ignore start -- Response serialization errors (tested via integration/E2E) */
if (isResponseSerializationError(error)) {
request.log.error(error, 'Response serialization error');
const body: ApiError = {
statusCode: 500,
error: 'Internal Server Error',
message: 'Response validation failed',
timestamp: new Date().toISOString(),
path: request.url,
};
return reply.status(500).send(body);
}
/* v8 ignore stop */
// Application errors (our custom error classes)
if (error instanceof AppError) {
const body: ApiError = {
statusCode: error.statusCode,
error: error.error,
message: error.message,
details: error.details,
timestamp: new Date().toISOString(),
path: request.url,
};
return reply.status(error.statusCode).send(body);
}
// Fastify-level errors (e.g., 404 from routing)
const fastifyError = error as { statusCode?: number; name?: string; message?: string };
const statusCode = fastifyError.statusCode ?? 500;
if (statusCode >= 500) {
request.log.error(error, 'Unhandled error');
}
const body: ApiError = {
statusCode,
error: statusCode >= 500 ? 'Internal Server Error' : (fastifyError.name ?? 'Error'),
message:
statusCode >= 500
? 'An unexpected error occurred'
: (fastifyError.message ?? 'Unknown error'),
timestamp: new Date().toISOString(),
path: request.url,
};
return reply.status(statusCode).send(body);
});
return app;
}
/* v8 ignore start -- called only from Zod validation handler above */
function formatZodIssues(issues: unknown[]): Record<string, string[]> {
const result: Record<string, string[]> = {};
for (const issue of issues) {
const zodIssue = issue as {
params?: { issue?: { path?: (string | number)[]; message?: string } };
};
const path = zodIssue.params?.issue?.path?.join('.') || '_root';
const message = zodIssue.params?.issue?.message || 'Validation failed';
if (!result[path]) result[path] = [];
result[path].push(message);
}
return result;
}
/* v8 ignore stop */
/* v8 ignore start -- entry-point bootstrap, tested via integration/E2E */
const isMain = process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/'));
if (isMain || process.argv[1]?.endsWith('main.js') || process.argv[1]?.endsWith('main.ts')) {
const app = await buildApp();
try {
await app.listen({ port: config.port, host: '0.0.0.0' });
} catch (err) {
app.log.fatal(err);
process.exit(1);
}
}
/* v8 ignore stop */

View file

@ -0,0 +1,40 @@
import { describe, it, expect } from 'vitest';
import Fastify from 'fastify';
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
import healthRoutes from './health.routes.js';
describe('Health Routes', () => {
async function buildTestApp() {
const app = Fastify({ logger: false });
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);
await app.register(healthRoutes);
return app;
}
it('GET /api/v1/health returns 200 with status ok', async () => {
const app = await buildTestApp();
const response = await app.inject({
method: 'GET',
url: '/api/v1/health',
});
expect(response.statusCode).toBe(200);
const body = response.json();
expect(body).toMatchObject({
status: 'ok',
version: expect.any(String),
uptime: expect.any(Number),
});
});
it('GET /api/v1/health returns increasing uptime', async () => {
const app = await buildTestApp();
const first = await app.inject({ method: 'GET', url: '/api/v1/health' });
const second = await app.inject({ method: 'GET', url: '/api/v1/health' });
expect(second.json().uptime).toBeGreaterThanOrEqual(first.json().uptime);
});
});

View file

@ -0,0 +1,34 @@
import fp from 'fastify-plugin';
import { z } from 'zod/v4';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
const packageVersion = '0.0.1';
export default fp(
async (fastify) => {
const app = fastify.withTypeProvider<ZodTypeProvider>();
app.route({
method: 'GET',
url: '/api/v1/health',
config: { public: true },
schema: {
response: {
200: z.object({
status: z.literal('ok'),
version: z.string(),
uptime: z.number(),
}),
},
},
handler: async (_request, reply) => {
return reply.send({
status: 'ok' as const,
version: packageVersion,
uptime: process.uptime(),
});
},
});
},
{ name: 'health-routes' },
);

View file

@ -0,0 +1,134 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HouseholdRole } from '@meshitrack/shared';
const { _mockLean, mockExec, mockFindById, mockFindOne, mockFindByIdAndUpdate, mockSave } =
vi.hoisted(() => {
const mockExec = vi.fn();
const mockLean = vi.fn(() => ({ exec: mockExec }));
return {
mockExec,
mockLean,
mockFindById: vi.fn(() => ({ lean: mockLean })),
mockFindOne: vi.fn(() => ({ lean: mockLean })),
mockFindByIdAndUpdate: vi.fn(() => ({ exec: mockExec })),
mockSave: vi.fn(),
};
});
vi.mock('../../schemas/household.schema.js', () => {
class MockHouseholdModel {
_data: Record<string, unknown>;
constructor(data: Record<string, unknown>) {
this._data = data;
Object.assign(this, data);
}
save() {
mockSave();
return Promise.resolve(this);
}
toObject() {
return { _id: 'hh-new', ...this._data };
}
static findById = mockFindById;
static findOne = mockFindOne;
static findByIdAndUpdate = mockFindByIdAndUpdate;
}
return { HouseholdModel: MockHouseholdModel };
});
import { HouseholdsRepository } from './households.repository.js';
describe('HouseholdsRepository', () => {
let repo: HouseholdsRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new HouseholdsRepository();
});
describe('findById', () => {
it('calls findById with lean', async () => {
const household = { _id: 'hh1', name: 'Test' };
mockExec.mockResolvedValue(household);
const result = await repo.findById('hh1');
expect(mockFindById).toHaveBeenCalledWith('hh1');
expect(result).toEqual(household);
});
});
describe('findByInviteCode', () => {
it('calls findOne with inviteCode', async () => {
const household = { _id: 'hh1', inviteCode: 'ABCD' };
mockExec.mockResolvedValue(household);
const result = await repo.findByInviteCode('ABCD');
expect(mockFindOne).toHaveBeenCalledWith({ inviteCode: 'ABCD' });
expect(result).toEqual(household);
});
});
describe('create', () => {
it('creates a household with owner as first member', async () => {
mockSave.mockResolvedValue({});
const result = await repo.create({ name: 'Test' }, 'owner-1', 'INVITE1');
expect(mockSave).toHaveBeenCalled();
expect(result).toMatchObject({ name: 'Test', ownerUserId: 'owner-1', inviteCode: 'INVITE1' });
});
});
describe('update', () => {
it('calls findByIdAndUpdate with $set', async () => {
mockExec.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
const result = await repo.update('hh1', { name: 'Updated' });
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
'hh1',
{ $set: { name: 'Updated' } },
{ new: true, lean: true },
);
expect(result).toEqual({ _id: 'hh1', name: 'Updated' });
});
});
describe('addMember', () => {
it('pushes a new member to the array', async () => {
mockExec.mockResolvedValue({ _id: 'hh1', members: [] });
await repo.addMember('hh1', 'user-2', HouseholdRole.MEMBER);
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
'hh1',
{
$push: {
members: expect.objectContaining({
userId: 'user-2',
role: HouseholdRole.MEMBER,
}),
},
},
{ new: true, lean: true },
);
});
});
describe('updateInviteCode', () => {
it('sets the new invite code', async () => {
mockExec.mockResolvedValue({ _id: 'hh1', inviteCode: 'NEWCODE' });
const result = await repo.updateInviteCode('hh1', 'NEWCODE');
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
'hh1',
{ $set: { inviteCode: 'NEWCODE' } },
{ new: true, lean: true },
);
expect(result).toEqual({ _id: 'hh1', inviteCode: 'NEWCODE' });
});
});
});

View file

@ -0,0 +1,55 @@
import type mongoose from 'mongoose';
import { HouseholdModel } from '../../schemas/household.schema.js';
import type { CreateHouseholdInput, UpdateHouseholdInput } from '@meshitrack/shared';
import { HouseholdRole } from '@meshitrack/shared';
export class HouseholdsRepository {
public async findById(id: string) {
return HouseholdModel.findById(id).lean().exec();
}
public async findByInviteCode(inviteCode: string) {
return HouseholdModel.findOne({ inviteCode }).lean().exec();
}
public async create(
data: CreateHouseholdInput,
ownerUserId: string,
inviteCode: string,
session?: mongoose.ClientSession,
) {
const household = new HouseholdModel({
...data,
ownerUserId,
inviteCode,
members: [{ userId: ownerUserId, role: HouseholdRole.OWNER, joinedAt: new Date() }],
});
const saved = await household.save({ session });
return saved.toObject();
}
public async update(id: string, data: UpdateHouseholdInput) {
return HouseholdModel.findByIdAndUpdate(id, { $set: data }, { new: true, lean: true }).exec();
}
public async addMember(
id: string,
userId: string,
role: HouseholdRole,
session?: mongoose.ClientSession,
) {
return HouseholdModel.findByIdAndUpdate(
id,
{ $push: { members: { userId, role, joinedAt: new Date() } } },
{ new: true, lean: true, session },
).exec();
}
public async updateInviteCode(id: string, inviteCode: string) {
return HouseholdModel.findByIdAndUpdate(
id,
{ $set: { inviteCode } },
{ new: true, lean: true },
).exec();
}
}

View file

@ -0,0 +1,225 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Fastify from 'fastify';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
import { HouseholdRole } from '@meshitrack/shared';
// Mock jose for auth plugin
vi.mock('jose', () => ({
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
jwtVerify: vi.fn().mockResolvedValue({
payload: {
sub: 'kc-1',
email: 'test@example.com',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: { alg: 'RS256' },
key: {},
}),
}));
// Hoist mock fns
const {
mockCreate,
mockFindById,
mockUpdate,
mockUpdateInviteCode,
mockFindByInviteCode,
mockAddMember,
mockFindByKeycloakId,
mockUserUpdate,
} = vi.hoisted(() => ({
mockCreate: vi.fn(),
mockFindById: vi.fn(),
mockUpdate: vi.fn(),
mockUpdateInviteCode: vi.fn(),
mockFindByInviteCode: vi.fn(),
mockAddMember: vi.fn(),
mockFindByKeycloakId: vi.fn(),
mockUserUpdate: vi.fn(),
}));
vi.mock('./households.repository.js', () => ({
HouseholdsRepository: class {
create = mockCreate;
findById = mockFindById;
update = mockUpdate;
updateInviteCode = mockUpdateInviteCode;
findByInviteCode = mockFindByInviteCode;
addMember = mockAddMember;
},
}));
vi.mock('../users/users.repository.js', () => ({
UsersRepository: class {
findByKeycloakId = mockFindByKeycloakId;
update = mockUserUpdate;
},
}));
vi.mock('uuid', () => ({
v4: vi.fn(() => '12345678-1234-1234-1234-123456789abc'),
}));
vi.mock('mongoose', () => ({
default: {
startSession: vi.fn().mockResolvedValue({
startTransaction: vi.fn(),
commitTransaction: vi.fn().mockResolvedValue(undefined),
abortTransaction: vi.fn().mockResolvedValue(undefined),
endSession: vi.fn(),
}),
},
}));
import authPlugin from '../../plugins/auth.plugin.js';
import householdPlugin from '../../plugins/household.plugin.js';
import usersRoutes from '../users/users.routes.js';
import householdsRoutes from './households.routes.js';
function makeFakeHousehold(overrides = {}) {
return {
_id: 'hh1',
name: 'Test Household',
ownerUserId: 'kc-1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER, joinedAt: new Date().toISOString() }],
inviteCode: '12345678',
settings: { timezone: 'UTC', currency: 'USD', language: 'en' },
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
};
}
describe('households.routes', () => {
let app: Awaited<ReturnType<typeof buildTestApp>>;
async function buildTestApp() {
const instance = Fastify({ logger: false });
instance.setValidatorCompiler(validatorCompiler);
instance.setSerializerCompiler(serializerCompiler);
await instance.register(fastifyAwilixPlugin, {
disposeOnClose: true,
disposeOnResponse: true,
strictBooleanEnforced: true,
});
await instance.register(authPlugin);
await instance.register(householdPlugin);
await instance.register(usersRoutes);
await instance.register(householdsRoutes);
await instance.ready();
return instance;
}
const authHeaders = { authorization: 'Bearer valid-token' };
beforeEach(async () => {
vi.clearAllMocks();
app = await buildTestApp();
});
afterEach(async () => {
if (app) await app.close();
});
describe('POST /api/v1/households', () => {
it('creates a household', async () => {
const household = makeFakeHousehold();
mockCreate.mockResolvedValue(household);
mockFindByKeycloakId.mockResolvedValue({ householdIds: [], defaultHouseholdId: null });
mockUserUpdate.mockResolvedValue({});
const res = await app.inject({
method: 'POST',
url: '/api/v1/households',
headers: authHeaders,
payload: { name: 'Test Household' },
});
expect(res.statusCode).toBe(201);
expect(res.json().name).toBe('Test Household');
});
});
describe('GET /api/v1/households/:id', () => {
it('returns a household', async () => {
const household = makeFakeHousehold();
mockFindById.mockResolvedValue(household);
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().name).toBe('Test Household');
});
});
describe('PATCH /api/v1/households/:id', () => {
it('updates a household', async () => {
const household = makeFakeHousehold();
mockFindById.mockResolvedValue(household);
mockUpdate.mockResolvedValue({ ...household, name: 'Updated' });
const res = await app.inject({
method: 'PATCH',
url: '/api/v1/households/hh1',
headers: authHeaders,
payload: { name: 'Updated' },
});
expect(res.statusCode).toBe(200);
expect(res.json().name).toBe('Updated');
});
});
describe('POST /api/v1/households/:id/invite', () => {
it('generates a new invite code', async () => {
const household = makeFakeHousehold();
mockFindById.mockResolvedValue(household);
mockUpdateInviteCode.mockResolvedValue({ ...household, inviteCode: '12345678' });
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/invite',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().inviteCode).toBeDefined();
});
});
describe('POST /api/v1/households/join', () => {
it('joins a household via invite code', async () => {
const household = makeFakeHousehold({
members: [
{ userId: 'kc-other', role: HouseholdRole.OWNER, joinedAt: new Date().toISOString() },
],
});
mockFindByInviteCode.mockResolvedValue(household);
mockAddMember.mockResolvedValue({
...household,
members: [
...household.members,
{ userId: 'kc-1', role: HouseholdRole.MEMBER, joinedAt: new Date().toISOString() },
],
});
mockFindByKeycloakId.mockResolvedValue({ householdIds: [], defaultHouseholdId: null });
mockUserUpdate.mockResolvedValue({});
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/join',
headers: authHeaders,
payload: { inviteCode: '12345678' },
});
expect(res.statusCode).toBe(200);
});
});
});

View file

@ -0,0 +1,166 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
CreateHouseholdSchema,
UpdateHouseholdSchema,
JoinHouseholdSchema,
HouseholdResponseSchema,
} from '@meshitrack/shared';
type AnyHouseholdDoc = {
_id: string | { toString: () => string };
name: string;
ownerUserId: string;
members: ReadonlyArray<{
userId: string;
role: string;
joinedAt: string | { toISOString: () => string };
}>;
inviteCode: string;
settings?: { timezone?: string; currency?: string; language?: string } | null;
createdAt: string | { toISOString: () => string };
updatedAt: string | { toISOString: () => string };
};
function toStr(v: string | { toString: () => string }): string {
return typeof v === 'string' ? v : v.toString();
}
function toIso(v: string | { toISOString: () => string }): string {
return typeof v === 'string' ? v : v.toISOString();
}
function toHouseholdResponse(doc: AnyHouseholdDoc): z.infer<typeof HouseholdResponseSchema> {
return {
_id: toStr(doc._id),
name: doc.name,
ownerUserId: doc.ownerUserId,
members: doc.members.map((m) => ({
userId: m.userId,
role: m.role,
joinedAt: toIso(m.joinedAt),
})),
inviteCode: doc.inviteCode,
settings: {
timezone: doc.settings?.timezone ?? 'UTC',
currency: doc.settings?.currency ?? 'USD',
language: doc.settings?.language ?? 'en',
},
createdAt: toIso(doc.createdAt),
updatedAt: toIso(doc.updatedAt),
};
}
import { HouseholdsRepository } from './households.repository.js';
import { HouseholdsService } from './households.service.js';
declare module '@fastify/awilix' {
interface Cradle {
householdsRepository: HouseholdsRepository;
householdsService: HouseholdsService;
}
}
export default fp(
async (fastify) => {
// Register DI
fastify.diContainer.register({
householdsRepository: asClass(HouseholdsRepository, { lifetime: Lifetime.SINGLETON }),
householdsService: asClass(HouseholdsService, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
// POST /api/v1/households — create a new household
app.route({
method: 'POST',
url: '/api/v1/households',
config: { skipHousehold: true },
schema: {
body: CreateHouseholdSchema,
response: { 201: HouseholdResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('householdsService');
const household = await service.create(request.body, request.user.keycloakId);
return reply.status(201).send(toHouseholdResponse(household));
},
});
// GET /api/v1/households/:householdId — get household by id (members only)
app.route({
method: 'GET',
url: '/api/v1/households/:householdId',
schema: {
params: z.object({ householdId: z.string() }),
response: { 200: HouseholdResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('householdsService');
const household = await service.getById(request.params.householdId);
return reply.send(toHouseholdResponse(household));
},
});
// PATCH /api/v1/households/:householdId — update household settings
app.route({
method: 'PATCH',
url: '/api/v1/households/:householdId',
schema: {
params: z.object({ householdId: z.string() }),
body: UpdateHouseholdSchema,
response: { 200: HouseholdResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('householdsService');
const household = await service.update(
request.params.householdId,
request.body,
request.user.keycloakId,
);
return reply.send(toHouseholdResponse(household));
},
});
// POST /api/v1/households/:householdId/invite — generate new invite code
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/invite',
schema: {
params: z.object({ householdId: z.string() }),
response: { 200: HouseholdResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('householdsService');
const household = await service.generateInviteCode(
request.params.householdId,
request.user.keycloakId,
);
return reply.send(toHouseholdResponse(household));
},
});
// POST /api/v1/households/join — join via invite code
app.route({
method: 'POST',
url: '/api/v1/households/join',
config: { skipHousehold: true },
schema: {
body: JoinHouseholdSchema,
response: { 200: HouseholdResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('householdsService');
const household = await service.join(request.body.inviteCode, request.user.keycloakId);
return reply.send(toHouseholdResponse(household));
},
});
},
{
name: 'households-routes',
// users-routes must load first: it registers UsersRepository into the DI container,
// which HouseholdsService depends on.
dependencies: ['auth-plugin', 'users-routes'],
},
);

View file

@ -0,0 +1,253 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HouseholdsService } from './households.service.js';
import { NotFoundError, ForbiddenError, ConflictError } from '../../common/errors.js';
import { HouseholdRole } from '@meshitrack/shared';
// Mock uuid to return deterministic values
vi.mock('uuid', () => ({
v4: vi.fn(() => '12345678-1234-1234-1234-123456789abc'),
}));
const { mockSession } = vi.hoisted(() => ({
mockSession: {
startTransaction: vi.fn(),
commitTransaction: vi.fn().mockResolvedValue(undefined),
abortTransaction: vi.fn().mockResolvedValue(undefined),
endSession: vi.fn(),
},
}));
vi.mock('mongoose', () => ({
default: { startSession: vi.fn().mockResolvedValue(mockSession) },
}));
describe('HouseholdsService', () => {
const mockHouseholdsRepo = {
findById: vi.fn(),
findByInviteCode: vi.fn(),
create: vi.fn(),
update: vi.fn(),
addMember: vi.fn(),
updateInviteCode: vi.fn(),
};
const mockUsersRepo = {
findByKeycloakId: vi.fn(),
findById: vi.fn(),
create: vi.fn(),
update: vi.fn(),
upsertFromToken: vi.fn(),
};
let service: HouseholdsService;
beforeEach(() => {
vi.clearAllMocks();
service = new HouseholdsService({
householdsRepository: mockHouseholdsRepo as never,
usersRepository: mockUsersRepo as never,
});
});
describe('create', () => {
it('creates a household and updates owner user', async () => {
const household = { _id: 'hh1', name: 'Test', ownerUserId: 'kc-1', inviteCode: '12345678' };
mockHouseholdsRepo.create.mockResolvedValue(household);
mockUsersRepo.findByKeycloakId.mockResolvedValue({
householdIds: [],
defaultHouseholdId: null,
});
mockUsersRepo.update.mockResolvedValue({});
const result = await service.create({ name: 'Test' }, 'kc-1');
expect(result).toEqual(household);
expect(mockHouseholdsRepo.create).toHaveBeenCalledWith(
{ name: 'Test' },
'kc-1',
'12345678',
mockSession,
);
expect(mockUsersRepo.update).toHaveBeenCalledWith(
'kc-1',
{ householdIds: ['hh1'], defaultHouseholdId: 'hh1' },
mockSession,
);
});
it('preserves existing defaultHouseholdId when user already has one', async () => {
const household = { _id: 'hh2', name: 'Second', ownerUserId: 'kc-1' };
mockHouseholdsRepo.create.mockResolvedValue(household);
mockUsersRepo.findByKeycloakId.mockResolvedValue({
householdIds: ['hh1'],
defaultHouseholdId: 'hh1',
});
mockUsersRepo.update.mockResolvedValue({});
await service.create({ name: 'Second' }, 'kc-1');
expect(mockUsersRepo.update).toHaveBeenCalledWith(
'kc-1',
{ householdIds: ['hh1', 'hh2'], defaultHouseholdId: 'hh1' },
mockSession,
);
});
it('handles case when owner user not found in db', async () => {
const household = { _id: 'hh1', name: 'Test', ownerUserId: 'kc-1' };
mockHouseholdsRepo.create.mockResolvedValue(household);
mockUsersRepo.findByKeycloakId.mockResolvedValue(null);
const result = await service.create({ name: 'Test' }, 'kc-1');
expect(result).toEqual(household);
expect(mockUsersRepo.update).not.toHaveBeenCalled();
});
});
describe('getById', () => {
it('returns household when found', async () => {
const household = { _id: 'hh1', name: 'Test' };
mockHouseholdsRepo.findById.mockResolvedValue(household);
const result = await service.getById('hh1');
expect(result).toEqual(household);
});
it('throws NotFoundError when not found', async () => {
mockHouseholdsRepo.findById.mockResolvedValue(null);
await expect(service.getById('missing')).rejects.toThrow(NotFoundError);
});
});
describe('update', () => {
it('allows owner to update', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
});
mockHouseholdsRepo.update.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
const result = await service.update('hh1', { name: 'Updated' }, 'kc-1');
expect(result).toEqual({ _id: 'hh1', name: 'Updated' });
});
it('allows admin to update', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-2', role: HouseholdRole.ADMIN }],
});
mockHouseholdsRepo.update.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
await service.update('hh1', { name: 'Updated' }, 'kc-2');
expect(mockHouseholdsRepo.update).toHaveBeenCalled();
});
it('throws ForbiddenError for regular member', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-3', role: HouseholdRole.MEMBER }],
});
await expect(service.update('hh1', { name: 'X' }, 'kc-3')).rejects.toThrow(ForbiddenError);
});
it('throws ForbiddenError for non-member', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
});
await expect(service.update('hh1', { name: 'X' }, 'kc-other')).rejects.toThrow(
ForbiddenError,
);
});
});
describe('generateInviteCode', () => {
it('generates new invite code for owner', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
});
mockHouseholdsRepo.updateInviteCode.mockResolvedValue({ inviteCode: '12345678' });
const result = await service.generateInviteCode('hh1', 'kc-1');
expect(mockHouseholdsRepo.updateInviteCode).toHaveBeenCalledWith('hh1', '12345678');
expect(result).toEqual({ inviteCode: '12345678' });
});
it('throws ForbiddenError for regular member', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-3', role: HouseholdRole.MEMBER }],
});
await expect(service.generateInviteCode('hh1', 'kc-3')).rejects.toThrow(ForbiddenError);
});
});
describe('join', () => {
it('joins a household via invite code', async () => {
const household = {
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
};
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
mockHouseholdsRepo.addMember.mockResolvedValue({
...household,
members: [...household.members, { userId: 'kc-2' }],
});
mockUsersRepo.findByKeycloakId.mockResolvedValue({
householdIds: [],
defaultHouseholdId: null,
});
mockUsersRepo.update.mockResolvedValue({});
const result = await service.join('ABCD1234', 'kc-2');
expect(mockHouseholdsRepo.addMember).toHaveBeenCalledWith(
'hh1',
'kc-2',
HouseholdRole.MEMBER,
mockSession,
);
expect(mockUsersRepo.update).toHaveBeenCalledWith(
'kc-2',
{ householdIds: ['hh1'], defaultHouseholdId: 'hh1' },
mockSession,
);
expect(result).toBeDefined();
});
it('throws NotFoundError for invalid invite code', async () => {
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(null);
await expect(service.join('INVALID', 'kc-2')).rejects.toThrow(NotFoundError);
});
it('throws ConflictError when already a member', async () => {
mockHouseholdsRepo.findByInviteCode.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
});
await expect(service.join('CODE', 'kc-1')).rejects.toThrow(ConflictError);
});
it('handles case when joining user not found in db', async () => {
const household = {
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
};
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
mockHouseholdsRepo.addMember.mockResolvedValue({});
mockUsersRepo.findByKeycloakId.mockResolvedValue(null);
await service.join('CODE', 'kc-new');
expect(mockUsersRepo.update).not.toHaveBeenCalled();
});
});
});

View file

@ -0,0 +1,135 @@
import mongoose from 'mongoose';
import { v4 as uuidv4 } from 'uuid';
import type { HouseholdsRepository } from './households.repository.js';
import type { UsersRepository } from '../users/users.repository.js';
import type { CreateHouseholdInput, UpdateHouseholdInput } from '@meshitrack/shared';
import { HouseholdRole } from '@meshitrack/shared';
import { NotFoundError, ForbiddenError, ConflictError } from '../../common/errors.js';
interface Deps {
householdsRepository: HouseholdsRepository;
usersRepository: UsersRepository;
}
export class HouseholdsService {
private readonly householdsRepository: HouseholdsRepository;
private readonly usersRepository: UsersRepository;
public constructor({ householdsRepository, usersRepository }: Deps) {
this.householdsRepository = householdsRepository;
this.usersRepository = usersRepository;
}
public async create(data: CreateHouseholdInput, ownerKeycloakId: string) {
const inviteCode = uuidv4().slice(0, 8).toUpperCase();
const session = await mongoose.startSession();
try {
session.startTransaction();
const household = await this.householdsRepository.create(
data,
ownerKeycloakId,
inviteCode,
session,
);
const user = await this.usersRepository.findByKeycloakId(ownerKeycloakId, session);
if (user) {
const householdId = household._id.toString();
await this.usersRepository.update(
ownerKeycloakId,
{
householdIds: [...user.householdIds, householdId],
defaultHouseholdId: user.defaultHouseholdId ?? householdId,
},
session,
);
}
await session.commitTransaction();
return household;
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
session.endSession();
}
}
public async getById(id: string) {
const household = await this.householdsRepository.findById(id);
if (!household) {
throw new NotFoundError('Household not found');
}
return household;
}
public async update(id: string, data: UpdateHouseholdInput, requestingUserId: string) {
const household = await this.getById(id);
const member = household.members.find((m) => m.userId === requestingUserId);
if (!member || (member.role !== HouseholdRole.OWNER && member.role !== HouseholdRole.ADMIN)) {
throw new ForbiddenError('Only owners and admins can update household settings');
}
const updated = await this.householdsRepository.update(id, data);
if (!updated) throw new NotFoundError('Household not found');
return updated;
}
public async generateInviteCode(id: string, requestingUserId: string) {
const household = await this.getById(id);
const member = household.members.find((m) => m.userId === requestingUserId);
if (!member || (member.role !== HouseholdRole.OWNER && member.role !== HouseholdRole.ADMIN)) {
throw new ForbiddenError('Only owners and admins can generate invite codes');
}
const newCode = uuidv4().slice(0, 8).toUpperCase();
const updated = await this.householdsRepository.updateInviteCode(id, newCode);
if (!updated) throw new NotFoundError('Household not found');
return updated;
}
public async join(inviteCode: string, userId: string) {
const household = await this.householdsRepository.findByInviteCode(inviteCode);
if (!household) {
throw new NotFoundError('Invalid invite code');
}
const alreadyMember = household.members.some((m) => m.userId === userId);
if (alreadyMember) {
throw new ConflictError('Already a member of this household');
}
const session = await mongoose.startSession();
try {
session.startTransaction();
const updated = await this.householdsRepository.addMember(
household._id.toString(),
userId,
HouseholdRole.MEMBER,
session,
);
if (!updated) throw new NotFoundError('Household not found');
const user = await this.usersRepository.findByKeycloakId(userId, session);
if (user) {
const householdId = household._id.toString();
await this.usersRepository.update(
userId,
{
householdIds: [...user.householdIds, householdId],
defaultHouseholdId: user.defaultHouseholdId ?? householdId,
},
session,
);
}
await session.commitTransaction();
return updated;
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
session.endSession();
}
}
}

View file

@ -0,0 +1,128 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Use vi.hoisted so mocks are available in vi.mock factory (which is hoisted)
const { mockLean, mockExec, mockFindOne, mockFindById, mockFindOneAndUpdate, mockSave } =
vi.hoisted(() => {
const mockExec = vi.fn();
const mockLean = vi.fn(() => ({ exec: mockExec }));
return {
mockExec,
mockLean,
mockFindOne: vi.fn(() => ({ lean: mockLean })),
mockFindById: vi.fn(() => ({ lean: mockLean })),
mockFindOneAndUpdate: vi.fn(() => ({ exec: mockExec })),
mockSave: vi.fn(),
};
});
vi.mock('../../schemas/user.schema.js', () => {
class MockUserModel {
_data: Record<string, unknown>;
constructor(data: Record<string, unknown>) {
this._data = data;
Object.assign(this, data);
}
save() {
mockSave();
return Promise.resolve(this);
}
toObject() {
return { _id: 'new-id', ...this._data };
}
static findOne = mockFindOne;
static findById = mockFindById;
static findOneAndUpdate = mockFindOneAndUpdate;
}
return { UserModel: MockUserModel };
});
import { UsersRepository } from './users.repository.js';
describe('UsersRepository', () => {
let repo: UsersRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new UsersRepository();
});
describe('findByKeycloakId', () => {
it('calls findOne with keycloakId and returns lean result', async () => {
const user = { _id: 'u1', keycloakId: 'kc-1' };
mockExec.mockResolvedValue(user);
const result = await repo.findByKeycloakId('kc-1');
expect(mockFindOne).toHaveBeenCalledWith({ keycloakId: 'kc-1' }, null, {
session: undefined,
});
expect(mockLean).toHaveBeenCalled();
expect(mockExec).toHaveBeenCalled();
expect(result).toEqual(user);
});
});
describe('findById', () => {
it('calls findById and returns lean result', async () => {
const user = { _id: 'u1' };
mockExec.mockResolvedValue(user);
const result = await repo.findById('u1');
expect(mockFindById).toHaveBeenCalledWith('u1');
expect(result).toEqual(user);
});
});
describe('create', () => {
it('creates a new user and returns plain object', async () => {
mockSave.mockResolvedValue({});
const data = {
keycloakId: 'kc-1',
email: 'test@example.com',
displayName: 'Test',
householdIds: [],
};
const result = await repo.create(data as never);
expect(mockSave).toHaveBeenCalled();
expect(result).toMatchObject({ keycloakId: 'kc-1' });
});
});
describe('update', () => {
it('calls findOneAndUpdate with $set', async () => {
const updated = { _id: 'u1', displayName: 'Updated' };
mockExec.mockResolvedValue(updated);
const result = await repo.update('kc-1', { displayName: 'Updated' } as never);
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ keycloakId: 'kc-1' },
{ $set: { displayName: 'Updated' } },
{ new: true, lean: true, session: undefined },
);
expect(result).toEqual(updated);
});
});
describe('upsertFromToken', () => {
it('upserts user with $set and $setOnInsert', async () => {
const upserted = { _id: 'u1', keycloakId: 'kc-1' };
mockExec.mockResolvedValue(upserted);
const result = await repo.upsertFromToken('kc-1', 'a@b.com', 'Name');
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ keycloakId: 'kc-1' },
{
$set: { email: 'a@b.com', displayName: 'Name' },
$setOnInsert: { keycloakId: 'kc-1', householdIds: [], defaultHouseholdId: null },
},
{ upsert: true, new: true, lean: true },
);
expect(result).toEqual(upserted);
});
});
});

View file

@ -0,0 +1,38 @@
import type mongoose from 'mongoose';
import { UserModel } from '../../schemas/user.schema.js';
import type { CreateUserInput, UpdateUserInput } from '@meshitrack/shared';
export class UsersRepository {
public async findByKeycloakId(keycloakId: string, session?: mongoose.ClientSession) {
return UserModel.findOne({ keycloakId }, null, { session }).lean().exec();
}
public async findById(id: string) {
return UserModel.findById(id).lean().exec();
}
public async create(data: CreateUserInput) {
const user = new UserModel(data);
const saved = await user.save();
return saved.toObject();
}
public async update(keycloakId: string, data: UpdateUserInput, session?: mongoose.ClientSession) {
return UserModel.findOneAndUpdate(
{ keycloakId },
{ $set: data },
{ new: true, lean: true, session },
).exec();
}
public async upsertFromToken(keycloakId: string, email: string, displayName: string) {
return UserModel.findOneAndUpdate(
{ keycloakId },
{
$set: { email, displayName },
$setOnInsert: { keycloakId, householdIds: [], defaultHouseholdId: null },
},
{ upsert: true, new: true, lean: true },
).exec();
}
}

View file

@ -0,0 +1,82 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify from 'fastify';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
// Mock jose for auth plugin
vi.mock('jose', () => ({
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
jwtVerify: vi.fn().mockResolvedValue({
payload: {
sub: 'kc-1',
email: 'test@example.com',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: { alg: 'RS256' },
key: {},
}),
}));
// Mock the users repository module with a real class
const mockUpsertFromToken = vi.hoisted(() => vi.fn());
vi.mock('./users.repository.js', () => ({
UsersRepository: class MockUsersRepository {
upsertFromToken = mockUpsertFromToken;
},
}));
import authPlugin from '../../plugins/auth.plugin.js';
import usersRoutes from './users.routes.js';
describe('users.routes', () => {
async function buildTestApp() {
const app = Fastify({ logger: false });
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);
await app.register(fastifyAwilixPlugin, {
disposeOnClose: true,
disposeOnResponse: true,
strictBooleanEnforced: true,
});
await app.register(authPlugin);
await app.register(usersRoutes);
return app;
}
beforeEach(() => {
vi.clearAllMocks();
});
it('GET /api/v1/users/me syncs user from token and returns profile', async () => {
const mockUser = {
_id: 'u1',
keycloakId: 'kc-1',
displayName: 'testuser',
email: 'test@example.com',
householdIds: ['hh1'],
defaultHouseholdId: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
mockUpsertFromToken.mockResolvedValue(mockUser);
const app = await buildTestApp();
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/api/v1/users/me',
headers: { authorization: 'Bearer valid-token' },
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.keycloakId).toBe('kc-1');
expect(body.email).toBe('test@example.com');
expect(mockUpsertFromToken).toHaveBeenCalledWith('kc-1', 'test@example.com', 'testuser');
await app.close();
});
});

View file

@ -0,0 +1,81 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import { UsersRepository } from './users.repository.js';
import { UsersService } from './users.service.js';
import { NotFoundError } from '../../common/errors.js';
type AnyUserDoc = {
_id: string | { toString: () => string };
keycloakId: string;
displayName: string;
email: string;
householdIds: string[];
defaultHouseholdId?: string | null;
createdAt: string | { toISOString: () => string };
updatedAt: string | { toISOString: () => string };
};
function toUserResponse(doc: AnyUserDoc) {
const id = typeof doc._id === 'string' ? doc._id : doc._id.toString();
const createdAt = typeof doc.createdAt === 'string' ? doc.createdAt : doc.createdAt.toISOString();
const updatedAt = typeof doc.updatedAt === 'string' ? doc.updatedAt : doc.updatedAt.toISOString();
return {
_id: id,
keycloakId: doc.keycloakId,
displayName: doc.displayName,
email: doc.email,
householdIds: doc.householdIds,
defaultHouseholdId: doc.defaultHouseholdId ?? null,
createdAt,
updatedAt,
};
}
declare module '@fastify/awilix' {
interface Cradle {
usersRepository: UsersRepository;
usersService: UsersService;
}
}
export default fp(
async (fastify) => {
// Register DI
fastify.diContainer.register({
usersRepository: asClass(UsersRepository, { lifetime: Lifetime.SINGLETON }),
usersService: asClass(UsersService, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
// GET /api/v1/users/me — get current user profile (syncs from token on first call)
app.route({
method: 'GET',
url: '/api/v1/users/me',
config: { skipHousehold: true },
schema: {
response: {
200: z.object({
_id: z.string(),
keycloakId: z.string(),
displayName: z.string(),
email: z.string(),
householdIds: z.array(z.string()),
defaultHouseholdId: z.string().nullable(),
createdAt: z.string(),
updatedAt: z.string(),
}),
},
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('usersService');
const user = await service.syncFromToken(request.user);
if (!user) throw new NotFoundError('User sync failed');
return reply.send(toUserResponse(user));
},
});
},
{ name: 'users-routes', dependencies: ['auth-plugin'] },
);

View file

@ -0,0 +1,61 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { UsersService } from './users.service.js';
import { NotFoundError } from '../../common/errors.js';
describe('UsersService', () => {
const mockRepo = {
findByKeycloakId: vi.fn(),
findById: vi.fn(),
create: vi.fn(),
update: vi.fn(),
upsertFromToken: vi.fn(),
};
let service: UsersService;
beforeEach(() => {
vi.clearAllMocks();
service = new UsersService({ usersRepository: mockRepo as never });
});
describe('syncFromToken', () => {
it('upserts user from auth token data', async () => {
const authUser = {
keycloakId: 'kc-1',
email: 'test@example.com',
displayName: 'Test User',
roles: ['member'],
householdIds: [],
};
const upserted = { _id: 'u1', ...authUser };
mockRepo.upsertFromToken.mockResolvedValue(upserted);
const result = await service.syncFromToken(authUser);
expect(mockRepo.upsertFromToken).toHaveBeenCalledWith(
'kc-1',
'test@example.com',
'Test User',
);
expect(result).toEqual(upserted);
});
});
describe('getProfile', () => {
it('returns user when found', async () => {
const user = { _id: 'u1', keycloakId: 'kc-1', displayName: 'Test' };
mockRepo.findByKeycloakId.mockResolvedValue(user);
const result = await service.getProfile('kc-1');
expect(result).toEqual(user);
expect(mockRepo.findByKeycloakId).toHaveBeenCalledWith('kc-1');
});
it('throws NotFoundError when user not found', async () => {
mockRepo.findByKeycloakId.mockResolvedValue(null);
await expect(service.getProfile('kc-missing')).rejects.toThrow(NotFoundError);
});
});
});

View file

@ -0,0 +1,27 @@
import type { UsersRepository } from './users.repository.js';
import type { AuthUser } from '../../common/types.js';
import { NotFoundError } from '../../common/errors.js';
interface Deps {
usersRepository: UsersRepository;
}
export class UsersService {
private readonly usersRepository: UsersRepository;
public constructor({ usersRepository }: Deps) {
this.usersRepository = usersRepository;
}
public async syncFromToken(user: AuthUser) {
return this.usersRepository.upsertFromToken(user.keycloakId, user.email, user.displayName);
}
public async getProfile(keycloakId: string) {
const user = await this.usersRepository.findByKeycloakId(keycloakId);
if (!user) {
throw new NotFoundError('User not found');
}
return user;
}
}

View file

@ -0,0 +1,161 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify from 'fastify';
const { MockJOSEError } = vi.hoisted(() => ({
MockJOSEError: class JOSEError extends Error {},
}));
// Mock jose before importing the plugin
vi.mock('jose', () => ({
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
jwtVerify: vi.fn(),
errors: { JOSEError: MockJOSEError },
}));
import authPlugin from './auth.plugin.js';
import * as jose from 'jose';
describe('auth.plugin', () => {
function buildApp() {
const app = Fastify({ logger: false });
return app;
}
beforeEach(() => {
vi.clearAllMocks();
});
it('skips auth for routes marked as public', async () => {
const app = buildApp();
await app.register(authPlugin);
app.get('/public', { config: { public: true } as never }, async () => ({ ok: true }));
await app.ready();
const res = await app.inject({ method: 'GET', url: '/public' });
expect(res.statusCode).toBe(200);
});
it('throws 401 when no Authorization header', async () => {
const app = buildApp();
await app.register(authPlugin);
app.get('/protected', async () => ({ ok: true }));
await app.ready();
const res = await app.inject({ method: 'GET', url: '/protected' });
expect(res.statusCode).toBe(401);
expect(res.json().message).toContain('Missing or invalid Authorization');
});
it('throws 401 when Authorization header is not Bearer', async () => {
const app = buildApp();
await app.register(authPlugin);
app.get('/protected', async () => ({ ok: true }));
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/protected',
headers: { authorization: 'Basic abc123' },
});
expect(res.statusCode).toBe(401);
});
it('throws 401 when token is invalid', async () => {
vi.mocked(jose.jwtVerify).mockRejectedValue(new MockJOSEError('Invalid token'));
const app = buildApp();
await app.register(authPlugin);
app.get('/protected', async () => ({ ok: true }));
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/protected',
headers: { authorization: 'Bearer invalid-token' },
});
expect(res.statusCode).toBe(401);
expect(res.json().message).toContain('Invalid or expired token');
});
it('sets request.user from valid JWT payload', async () => {
vi.mocked(jose.jwtVerify).mockResolvedValue({
payload: {
sub: 'kc-1',
email: 'test@example.com',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
iss: 'http://localhost:8080/realms/meshitrack',
aud: 'meshitrack-api',
},
protectedHeader: { alg: 'RS256' },
key: {} as never,
} as never);
const app = buildApp();
await app.register(authPlugin);
let capturedUser: unknown;
app.get('/protected', async (request) => {
capturedUser = request.user;
return { ok: true };
});
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/protected',
headers: { authorization: 'Bearer valid-token' },
});
expect(res.statusCode).toBe(200);
expect(capturedUser).toEqual({
keycloakId: 'kc-1',
email: 'test@example.com',
displayName: 'testuser',
roles: ['member'],
householdIds: ['hh1'],
});
});
it('handles missing optional fields in JWT payload', async () => {
vi.mocked(jose.jwtVerify).mockResolvedValue({
payload: {
// sub, email, preferred_username, realm_access, householdIds all missing
iss: 'http://localhost:8080/realms/meshitrack',
aud: 'meshitrack-api',
},
protectedHeader: { alg: 'RS256' },
key: {} as never,
} as never);
const app = buildApp();
await app.register(authPlugin);
let capturedUser: unknown;
app.get('/protected', async (request) => {
capturedUser = request.user;
return { ok: true };
});
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/protected',
headers: { authorization: 'Bearer token' },
});
expect(res.statusCode).toBe(200);
expect(capturedUser).toEqual({
keycloakId: '',
email: '',
displayName: '',
roles: [],
householdIds: [],
});
});
});

View file

@ -0,0 +1,72 @@
import fp from 'fastify-plugin';
import * as jose from 'jose';
import config from '../config/configuration.js';
import type { AuthUser } from '../common/types.js';
import { UnauthorizedError } from '../common/errors.js';
let jwks: jose.JWTVerifyGetKey | undefined;
function getJwks(): jose.JWTVerifyGetKey {
if (!jwks) {
// Use internal URL (config.keycloak.url) to reach JWKS endpoint within Docker network
jwks = jose.createRemoteJWKSet(
new URL(
`${config.keycloak.url}/realms/${config.keycloak.realm}/protocol/openid-connect/certs`,
),
);
}
return jwks;
}
export default fp(
async (fastify) => {
// Decorate request with user and householdId (null defaults)
fastify.decorateRequest('user', null as unknown as AuthUser);
fastify.decorateRequest('householdId', '');
fastify.addHook('onRequest', async (request, _reply) => {
// Skip auth for routes marked as public via route config
const routeConfig = request.routeOptions.config as unknown as
| Record<string, unknown>
| undefined;
if (routeConfig?.['public'] === true) {
return;
}
const authHeader = request.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
throw new UnauthorizedError('Missing or invalid Authorization header');
}
const token = authHeader.slice(7);
// Use public issuer URL (config.keycloak.issuerUrl) to validate the iss claim in the token.
// Tokens have iss set to the public URL (KC_HOSTNAME_URL), not the internal Docker hostname.
const expectedIssuer = `${config.keycloak.issuerUrl}/realms/${config.keycloak.realm}`;
try {
const { payload } = await jose.jwtVerify(token, getJwks(), {
issuer: expectedIssuer,
audience: config.keycloak.clientId,
});
const user: AuthUser = {
keycloakId: payload.sub ?? '',
email: (payload['email'] as string) ?? '',
displayName: (payload['preferred_username'] as string) ?? '',
roles: (payload['realm_access'] as Record<string, string[]>)?.['roles'] ?? [],
householdIds: (payload['householdIds'] as string[]) ?? [],
};
request.user = user;
} catch (err) {
// Only map jose-specific errors (bad signature, expired, wrong issuer, etc.) to 401.
// Other errors (e.g. JWKS network failure) propagate as 500 so callers aren't misled.
if (err instanceof jose.errors.JOSEError) {
throw new UnauthorizedError('Invalid or expired token');
}
throw err;
}
});
},
{ name: 'auth-plugin' },
);

View file

@ -0,0 +1,101 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify from 'fastify';
// Mock jose for the auth plugin dependency
vi.mock('jose', () => ({
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
jwtVerify: vi.fn().mockResolvedValue({
payload: {
sub: 'kc-1',
email: 'test@example.com',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: { alg: 'RS256' },
key: {},
}),
}));
import authPlugin from './auth.plugin.js';
import householdPlugin from './household.plugin.js';
describe('household.plugin', () => {
async function buildApp() {
const app = Fastify({ logger: false });
await app.register(authPlugin);
await app.register(householdPlugin);
return app;
}
beforeEach(() => {
vi.clearAllMocks();
});
it('skips household check for public routes', async () => {
const app = await buildApp();
app.get('/public', { config: { public: true } as never }, async () => ({ ok: true }));
await app.ready();
const res = await app.inject({ method: 'GET', url: '/public' });
expect(res.statusCode).toBe(200);
});
it('skips household check for routes with skipHousehold', async () => {
const app = await buildApp();
app.get('/skip', { config: { skipHousehold: true } as never }, async () => ({ ok: true }));
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/skip',
headers: { authorization: 'Bearer valid' },
});
expect(res.statusCode).toBe(200);
});
it('throws 403 when user does not belong to household', async () => {
const app = await buildApp();
app.get('/households/:householdId/data', async () => ({ ok: true }));
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/households/hh-unknown/data',
headers: { authorization: 'Bearer valid' },
});
expect(res.statusCode).toBe(403);
expect(res.json().message).toContain('do not belong');
});
it('sets request.householdId when user belongs to household', async () => {
const app = await buildApp();
let capturedId: string | undefined;
app.get('/households/:householdId/data', async (request) => {
capturedId = request.householdId;
return { ok: true };
});
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/households/hh1/data',
headers: { authorization: 'Bearer valid' },
});
expect(res.statusCode).toBe(200);
expect(capturedId).toBe('hh1');
});
it('skips household check when route has no householdId param', async () => {
const app = await buildApp();
app.get('/no-household', async () => ({ ok: true }));
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/no-household',
headers: { authorization: 'Bearer valid' },
});
expect(res.statusCode).toBe(200);
});
});

View file

@ -0,0 +1,31 @@
import fp from 'fastify-plugin';
import { ForbiddenError } from '../common/errors.js';
export default fp(
async (fastify) => {
fastify.addHook('preHandler', async (request) => {
// Skip household check for public routes or routes that explicitly opt out
const routeConfig = request.routeOptions.config as unknown as
| Record<string, unknown>
| undefined;
if (routeConfig?.['public'] === true || routeConfig?.['skipHousehold'] === true) {
return;
}
// householdId must be present in the route URL params (e.g. /households/:householdId/...)
const params = request.params as Record<string, string> | undefined;
const householdId = params?.['householdId'];
if (!householdId) {
return; // route has no household context — no scoping needed
}
// Validate user belongs to this household
if (!request.user?.householdIds?.includes(householdId)) {
throw new ForbiddenError('You do not belong to this household');
}
request.householdId = householdId;
});
},
{ name: 'household-plugin', dependencies: ['auth-plugin'] },
);

View file

@ -0,0 +1,46 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify from 'fastify';
// Mock mongoose and awilix before importing the plugin
vi.mock('mongoose', () => ({
default: {
connect: vi.fn().mockResolvedValue(undefined),
disconnect: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock('@fastify/awilix', () => ({
diContainer: {
register: vi.fn(),
},
}));
import mongoosePlugin from './mongoose.plugin.js';
import mongoose from 'mongoose';
import { diContainer } from '@fastify/awilix';
describe('mongoose.plugin', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('connects to MongoDB on registration', async () => {
const app = Fastify({ logger: false });
await app.register(mongoosePlugin);
await app.ready();
expect(mongoose.connect).toHaveBeenCalled();
expect(diContainer.register).toHaveBeenCalled();
await app.close();
});
it('disconnects from MongoDB on close', async () => {
const app = Fastify({ logger: false });
await app.register(mongoosePlugin);
await app.ready();
await app.close();
expect(mongoose.disconnect).toHaveBeenCalled();
});
});

View file

@ -0,0 +1,22 @@
import fp from 'fastify-plugin';
import mongoose from 'mongoose';
import { diContainer } from '@fastify/awilix';
import { asValue } from 'awilix';
import config from '../config/configuration.js';
export default fp(
async (fastify) => {
fastify.log.info('Connecting to MongoDB...');
await mongoose.connect(config.mongodb.uri);
fastify.log.info('MongoDB connected');
// Register mongoose in DI container for other services to use
diContainer.register({ mongoose: asValue(mongoose) });
fastify.addHook('onClose', async () => {
fastify.log.info('Closing MongoDB connection...');
await mongoose.disconnect();
});
},
{ name: 'mongoose-plugin' },
);

View file

@ -0,0 +1,19 @@
import { describe, it, expect } from 'vitest';
import { HouseholdModel } from './household.schema.js';
describe('HouseholdModel', () => {
it('is a valid mongoose model', () => {
expect(HouseholdModel.modelName).toBe('Household');
});
it('has expected schema paths', () => {
const paths = Object.keys(HouseholdModel.schema.paths);
expect(paths).toContain('name');
expect(paths).toContain('ownerUserId');
expect(paths).toContain('members');
expect(paths).toContain('inviteCode');
expect(paths).toContain('settings');
expect(paths).toContain('createdAt');
expect(paths).toContain('updatedAt');
});
});

View file

@ -0,0 +1,45 @@
import mongoose from 'mongoose';
import { HouseholdRole } from '@meshitrack/shared';
const householdMemberSchema = new mongoose.Schema(
{
userId: { type: String, required: true },
role: { type: String, enum: Object.values(HouseholdRole), required: true },
joinedAt: { type: Date, default: Date.now },
},
{ _id: false },
);
const householdSettingsSchema = new mongoose.Schema(
{
timezone: { type: String, default: 'UTC' },
currency: { type: String, default: 'USD', maxlength: 3 },
language: { type: String, default: 'en', maxlength: 5 },
},
{ _id: false },
);
const householdSchema = new mongoose.Schema(
{
name: { type: String, required: true },
ownerUserId: { type: String, required: true, index: true },
members: { type: [householdMemberSchema], default: [] },
inviteCode: { type: String, required: true, index: true },
/* v8 ignore start -- Mongoose default factory, only invoked at document creation */
settings: {
type: householdSettingsSchema,
default: () => ({ timezone: 'UTC', currency: 'USD', language: 'en' }),
},
/* v8 ignore stop */
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
export const HouseholdModel = mongoose.model('Household', householdSchema);
export type HouseholdDocument = mongoose.InferSchemaType<typeof householdSchema> & {
_id: mongoose.Types.ObjectId;
};

View file

@ -0,0 +1,19 @@
import { describe, it, expect } from 'vitest';
import { UserModel } from './user.schema.js';
describe('UserModel', () => {
it('is a valid mongoose model', () => {
expect(UserModel.modelName).toBe('User');
});
it('has expected schema paths', () => {
const paths = Object.keys(UserModel.schema.paths);
expect(paths).toContain('keycloakId');
expect(paths).toContain('displayName');
expect(paths).toContain('email');
expect(paths).toContain('householdIds');
expect(paths).toContain('defaultHouseholdId');
expect(paths).toContain('createdAt');
expect(paths).toContain('updatedAt');
});
});

View file

@ -0,0 +1,21 @@
import mongoose from 'mongoose';
const userSchema = new mongoose.Schema(
{
keycloakId: { type: String, required: true, unique: true, index: true },
displayName: { type: String, required: true },
email: { type: String, required: true },
householdIds: { type: [String], default: [] },
defaultHouseholdId: { type: String, default: null },
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
export const UserModel = mongoose.model('User', userSchema);
export type UserDocument = mongoose.InferSchemaType<typeof userSchema> & {
_id: mongoose.Types.ObjectId;
};

View file

@ -0,0 +1,81 @@
import mongoose from 'mongoose';
// Fixed ID shared with the Keycloak test users' householdIds attribute.
// Both must be kept in sync with docker/keycloak/realm-export.json.
const TEST_HOUSEHOLD_ID = new mongoose.Types.ObjectId('000000000000000000000001');
// SEED_MONGODB_URI is preferred so host-machine seeding always uses localhost,
// even when MONGODB_URI is set to the Docker-internal hostname in the environment.
const MONGODB_URI =
process.env.SEED_MONGODB_URI ||
process.env.MONGODB_URI ||
'mongodb://meshitrack:devpassword@localhost:27017/meshitrack?authSource=admin&replicaSet=rs0';
async function seed() {
console.log('Starting seed...');
console.log(`Connecting to: ${MONGODB_URI.replace(/:[^:@]+@/, ':****@')}`);
const conn = await mongoose.connect(MONGODB_URI);
const db = conn.connection.db;
if (!db) {
throw new Error('Failed to get database reference');
}
// Clean existing dev data
const collections = await db.listCollections().toArray();
for (const col of collections) {
await db.dropCollection(col.name);
}
console.log('Cleared existing collections');
// Create household with the fixed ID that matches Keycloak user attributes.
// User documents are not seeded here — they are created automatically via
// upsertFromToken when each test user logs in for the first time.
const householdsCollection = db.collection('households');
await householdsCollection.insertOne({
_id: TEST_HOUSEHOLD_ID,
name: 'Test Household',
ownerUserId: 'testuser1-keycloak-id',
inviteCode: 'TESTCODE',
members: [
{
userId: 'testuser1-keycloak-id',
role: 'owner',
joinedAt: new Date(),
},
{
userId: 'testuser2-keycloak-id',
role: 'member',
joinedAt: new Date(),
},
],
settings: {
timezone: 'UTC',
currency: 'USD',
language: 'en',
},
createdAt: new Date(),
updatedAt: new Date(),
});
const householdId = TEST_HOUSEHOLD_ID.toString();
console.log('Created test household');
console.log('');
console.log('=== Seed Complete ===');
console.log('');
console.log('Test Users (log in via Keycloak to create user documents):');
console.log(' testuser1 / test1234 (owner, admin)');
console.log(' testuser2 / test1234 (member)');
console.log(` Household ID: ${householdId}`);
console.log(` Invite Code: TESTCODE`);
console.log('');
await conn.disconnect();
}
seed().catch((err) => {
console.error('Seed failed:', err);
process.exit(1);
});

View file

@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"declaration": false,
"declarationMap": false,
"sourceMap": true,
"incremental": true
},
"include": ["src/**/*"],
"exclude": ["src/**/*.test.ts"]
}

View file

@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": true
},
"include": ["src/**/*"],
"exclude": []
}

View file

@ -0,0 +1,29 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['src/**/*.test.ts'],
coverage: {
provider: 'v8',
enabled: false, // enable via --coverage flag or test:cov script
include: ['src/**/*.ts'],
exclude: [
'src/**/*.test.ts',
'src/scripts/**',
'src/common/types.ts', // declaration merging only — no runtime logic
],
reporter: ['text', 'lcov', 'json-summary', 'html'],
reportsDirectory: './coverage',
thresholds: {
lines: 100,
functions: 100,
branches: 90,
statements: 100,
},
},
testTimeout: 10_000,
hookTimeout: 30_000,
},
});