Setup initial project
This commit is contained in:
commit
db79af06f7
119 changed files with 20761 additions and 0 deletions
40
packages/api/eslint.config.js
Normal file
40
packages/api/eslint.config.js
Normal 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
47
packages/api/package.json
Normal 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"
|
||||
}
|
||||
}
|
||||
85
packages/api/src/common/errors.test.ts
Normal file
85
packages/api/src/common/errors.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
49
packages/api/src/common/errors.ts
Normal file
49
packages/api/src/common/errors.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
24
packages/api/src/common/types.ts
Normal file
24
packages/api/src/common/types.ts
Normal 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 {}
|
||||
}
|
||||
14
packages/api/src/config/configuration.test.ts
Normal file
14
packages/api/src/config/configuration.test.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
21
packages/api/src/config/configuration.ts
Normal file
21
packages/api/src/config/configuration.ts
Normal 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;
|
||||
188
packages/api/src/main.test.ts
Normal file
188
packages/api/src/main.test.ts
Normal 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
186
packages/api/src/main.ts
Normal 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 */
|
||||
40
packages/api/src/modules/health/health.routes.test.ts
Normal file
40
packages/api/src/modules/health/health.routes.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
34
packages/api/src/modules/health/health.routes.ts
Normal file
34
packages/api/src/modules/health/health.routes.ts
Normal 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' },
|
||||
);
|
||||
|
|
@ -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' });
|
||||
});
|
||||
});
|
||||
});
|
||||
55
packages/api/src/modules/households/households.repository.ts
Normal file
55
packages/api/src/modules/households/households.repository.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
225
packages/api/src/modules/households/households.routes.test.ts
Normal file
225
packages/api/src/modules/households/households.routes.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
166
packages/api/src/modules/households/households.routes.ts
Normal file
166
packages/api/src/modules/households/households.routes.ts
Normal 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'],
|
||||
},
|
||||
);
|
||||
253
packages/api/src/modules/households/households.service.test.ts
Normal file
253
packages/api/src/modules/households/households.service.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
});
|
||||
135
packages/api/src/modules/households/households.service.ts
Normal file
135
packages/api/src/modules/households/households.service.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
128
packages/api/src/modules/users/users.repository.test.ts
Normal file
128
packages/api/src/modules/users/users.repository.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
38
packages/api/src/modules/users/users.repository.ts
Normal file
38
packages/api/src/modules/users/users.repository.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
82
packages/api/src/modules/users/users.routes.test.ts
Normal file
82
packages/api/src/modules/users/users.routes.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
81
packages/api/src/modules/users/users.routes.ts
Normal file
81
packages/api/src/modules/users/users.routes.ts
Normal 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'] },
|
||||
);
|
||||
61
packages/api/src/modules/users/users.service.test.ts
Normal file
61
packages/api/src/modules/users/users.service.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
27
packages/api/src/modules/users/users.service.ts
Normal file
27
packages/api/src/modules/users/users.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
161
packages/api/src/plugins/auth.plugin.test.ts
Normal file
161
packages/api/src/plugins/auth.plugin.test.ts
Normal 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: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
72
packages/api/src/plugins/auth.plugin.ts
Normal file
72
packages/api/src/plugins/auth.plugin.ts
Normal 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' },
|
||||
);
|
||||
101
packages/api/src/plugins/household.plugin.test.ts
Normal file
101
packages/api/src/plugins/household.plugin.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
31
packages/api/src/plugins/household.plugin.ts
Normal file
31
packages/api/src/plugins/household.plugin.ts
Normal 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'] },
|
||||
);
|
||||
46
packages/api/src/plugins/mongoose.plugin.test.ts
Normal file
46
packages/api/src/plugins/mongoose.plugin.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
22
packages/api/src/plugins/mongoose.plugin.ts
Normal file
22
packages/api/src/plugins/mongoose.plugin.ts
Normal 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' },
|
||||
);
|
||||
19
packages/api/src/schemas/household.schema.test.ts
Normal file
19
packages/api/src/schemas/household.schema.test.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
45
packages/api/src/schemas/household.schema.ts
Normal file
45
packages/api/src/schemas/household.schema.ts
Normal 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;
|
||||
};
|
||||
19
packages/api/src/schemas/user.schema.test.ts
Normal file
19
packages/api/src/schemas/user.schema.test.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
21
packages/api/src/schemas/user.schema.ts
Normal file
21
packages/api/src/schemas/user.schema.ts
Normal 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;
|
||||
};
|
||||
81
packages/api/src/scripts/seed.ts
Normal file
81
packages/api/src/scripts/seed.ts
Normal 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);
|
||||
});
|
||||
13
packages/api/tsconfig.json
Normal file
13
packages/api/tsconfig.json
Normal 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"]
|
||||
}
|
||||
8
packages/api/tsconfig.test.json
Normal file
8
packages/api/tsconfig.test.json
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": []
|
||||
}
|
||||
29
packages/api/vitest.config.ts
Normal file
29
packages/api/vitest.config.ts
Normal 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,
|
||||
},
|
||||
});
|
||||
38
packages/shared/eslint.config.js
Normal file
38
packages/shared/eslint.config.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import tseslint from 'typescript-eslint';
|
||||
import prettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist/**', 'coverage/**'] },
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
tsconfigRootDir: import.meta.dirname, // points to packages/shared
|
||||
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' },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['**/*.test.ts'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
prettierRecommended,
|
||||
);
|
||||
37
packages/shared/package.json
Normal file
37
packages/shared/package.json
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
{
|
||||
"name": "@meshitrack/shared",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./validation": {
|
||||
"types": "./dist/validation/index.d.ts",
|
||||
"import": "./dist/validation/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"dev": "tsc --watch",
|
||||
"clean": "rimraf dist tsconfig.tsbuildinfo",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
"test": "vitest run",
|
||||
"test:cov": "vitest run --coverage"
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "^4.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitest/coverage-v8": "^4.1.1",
|
||||
"rimraf": "^6.0.0",
|
||||
"typescript": "^6.0.0",
|
||||
"vitest": "^4.1.1"
|
||||
}
|
||||
}
|
||||
1
packages/shared/src/enums/index.ts
Normal file
1
packages/shared/src/enums/index.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from './roles.enums.js';
|
||||
14
packages/shared/src/enums/roles.enums.test.ts
Normal file
14
packages/shared/src/enums/roles.enums.test.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import { HouseholdRole } from './roles.enums.js';
|
||||
|
||||
describe('HouseholdRole', () => {
|
||||
it('has OWNER, ADMIN, MEMBER values', () => {
|
||||
expect(HouseholdRole.OWNER).toBe('owner');
|
||||
expect(HouseholdRole.ADMIN).toBe('admin');
|
||||
expect(HouseholdRole.MEMBER).toBe('member');
|
||||
});
|
||||
|
||||
it('has exactly 3 roles', () => {
|
||||
expect(Object.values(HouseholdRole)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
5
packages/shared/src/enums/roles.enums.ts
Normal file
5
packages/shared/src/enums/roles.enums.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export enum HouseholdRole {
|
||||
OWNER = 'owner',
|
||||
ADMIN = 'admin',
|
||||
MEMBER = 'member',
|
||||
}
|
||||
8
packages/shared/src/index.ts
Normal file
8
packages/shared/src/index.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
// Types
|
||||
export * from './types/index.js';
|
||||
|
||||
// Enums
|
||||
export * from './enums/index.js';
|
||||
|
||||
// Validation schemas
|
||||
export * from './validation/index.js';
|
||||
28
packages/shared/src/types/common.ts
Normal file
28
packages/shared/src/types/common.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
export interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
pagination: {
|
||||
cursor: string | null;
|
||||
hasMore: boolean;
|
||||
total?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
statusCode: number;
|
||||
error: string;
|
||||
message: string;
|
||||
details?: Record<string, string[]>;
|
||||
timestamp: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface ApiSuccess<T> {
|
||||
data: T;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface HealthResponse {
|
||||
status: 'ok';
|
||||
version: string;
|
||||
uptime: number;
|
||||
}
|
||||
24
packages/shared/src/types/household.ts
Normal file
24
packages/shared/src/types/household.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import type { HouseholdRole } from '../enums/roles.enums.js';
|
||||
|
||||
export interface Household {
|
||||
id: string;
|
||||
name: string;
|
||||
ownerUserId: string;
|
||||
members: HouseholdMember[];
|
||||
inviteCode: string;
|
||||
settings: HouseholdSettings;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface HouseholdMember {
|
||||
userId: string;
|
||||
role: HouseholdRole;
|
||||
joinedAt: Date;
|
||||
}
|
||||
|
||||
export interface HouseholdSettings {
|
||||
timezone: string;
|
||||
currency: string;
|
||||
language: string;
|
||||
}
|
||||
3
packages/shared/src/types/index.ts
Normal file
3
packages/shared/src/types/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export * from './user.js';
|
||||
export * from './household.js';
|
||||
export * from './common.js';
|
||||
10
packages/shared/src/types/user.ts
Normal file
10
packages/shared/src/types/user.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
export interface User {
|
||||
id: string;
|
||||
keycloakId: string;
|
||||
displayName: string;
|
||||
email: string;
|
||||
householdIds: string[];
|
||||
defaultHouseholdId: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
136
packages/shared/src/validation/household.schemas.test.ts
Normal file
136
packages/shared/src/validation/household.schemas.test.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
HouseholdSettingsSchema,
|
||||
CreateHouseholdSchema,
|
||||
UpdateHouseholdSchema,
|
||||
JoinHouseholdSchema,
|
||||
HouseholdMemberSchema,
|
||||
} from './household.schemas.js';
|
||||
import { HouseholdRole } from '../enums/roles.enums.js';
|
||||
|
||||
describe('HouseholdSettingsSchema', () => {
|
||||
it('accepts empty object with defaults', () => {
|
||||
const result = HouseholdSettingsSchema.safeParse({});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.timezone).toBe('UTC');
|
||||
expect(result.data.currency).toBe('USD');
|
||||
expect(result.data.language).toBe('en');
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts custom settings', () => {
|
||||
const result = HouseholdSettingsSchema.safeParse({
|
||||
timezone: 'Asia/Tokyo',
|
||||
currency: 'JPY',
|
||||
language: 'ja',
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects currency exceeding 3 chars', () => {
|
||||
const result = HouseholdSettingsSchema.safeParse({ currency: 'LONG' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects language exceeding 5 chars', () => {
|
||||
const result = HouseholdSettingsSchema.safeParse({ language: 'toolong' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CreateHouseholdSchema', () => {
|
||||
it('accepts valid input', () => {
|
||||
const result = CreateHouseholdSchema.safeParse({ name: 'My Household' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects empty name', () => {
|
||||
const result = CreateHouseholdSchema.safeParse({ name: '' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects name exceeding 100 chars', () => {
|
||||
const result = CreateHouseholdSchema.safeParse({ name: 'x'.repeat(101) });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('trims name', () => {
|
||||
const result = CreateHouseholdSchema.safeParse({ name: ' Test ' });
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.name).toBe('Test');
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts optional settings', () => {
|
||||
const result = CreateHouseholdSchema.safeParse({
|
||||
name: 'Test',
|
||||
settings: { timezone: 'US/Eastern' },
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UpdateHouseholdSchema', () => {
|
||||
it('accepts partial updates', () => {
|
||||
const result = UpdateHouseholdSchema.safeParse({ name: 'Updated' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts empty object', () => {
|
||||
const result = UpdateHouseholdSchema.safeParse({});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts partial settings', () => {
|
||||
const result = UpdateHouseholdSchema.safeParse({ settings: { currency: 'EUR' } });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('JoinHouseholdSchema', () => {
|
||||
it('accepts valid invite code', () => {
|
||||
const result = JoinHouseholdSchema.safeParse({ inviteCode: 'ABC123' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects empty invite code', () => {
|
||||
const result = JoinHouseholdSchema.safeParse({ inviteCode: '' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects missing invite code', () => {
|
||||
const result = JoinHouseholdSchema.safeParse({});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HouseholdMemberSchema', () => {
|
||||
it('accepts valid member', () => {
|
||||
const result = HouseholdMemberSchema.safeParse({
|
||||
userId: 'user-1',
|
||||
role: HouseholdRole.OWNER,
|
||||
joinedAt: new Date(),
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects invalid role', () => {
|
||||
const result = HouseholdMemberSchema.safeParse({
|
||||
userId: 'user-1',
|
||||
role: 'superadmin',
|
||||
joinedAt: new Date(),
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects empty userId', () => {
|
||||
const result = HouseholdMemberSchema.safeParse({
|
||||
userId: '',
|
||||
role: HouseholdRole.MEMBER,
|
||||
joinedAt: new Date(),
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
54
packages/shared/src/validation/household.schemas.ts
Normal file
54
packages/shared/src/validation/household.schemas.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { z } from 'zod/v4';
|
||||
import { HouseholdRole } from '../enums/roles.enums.js';
|
||||
|
||||
export const HouseholdSettingsSchema = z.object({
|
||||
timezone: z.string().default('UTC'),
|
||||
currency: z.string().max(3).default('USD'),
|
||||
language: z.string().max(5).default('en'),
|
||||
});
|
||||
|
||||
export const CreateHouseholdSchema = z.object({
|
||||
name: z.string().min(1).max(100).trim(),
|
||||
settings: HouseholdSettingsSchema.optional(),
|
||||
});
|
||||
|
||||
export const UpdateHouseholdSchema = z.object({
|
||||
name: z.string().min(1).max(100).trim().optional(),
|
||||
settings: HouseholdSettingsSchema.partial().optional(),
|
||||
});
|
||||
|
||||
export const JoinHouseholdSchema = z.object({
|
||||
inviteCode: z.string().min(1),
|
||||
});
|
||||
|
||||
export const HouseholdMemberSchema = z.object({
|
||||
userId: z.string().min(1),
|
||||
role: z.nativeEnum(HouseholdRole),
|
||||
joinedAt: z.date(),
|
||||
});
|
||||
|
||||
// Response schema for API output — dates are ISO strings after JSON serialization.
|
||||
export const HouseholdResponseSchema = z.object({
|
||||
_id: z.string(),
|
||||
name: z.string(),
|
||||
ownerUserId: z.string(),
|
||||
members: z.array(
|
||||
z.object({
|
||||
userId: z.string(),
|
||||
role: z.string(),
|
||||
joinedAt: z.string(),
|
||||
}),
|
||||
),
|
||||
inviteCode: z.string(),
|
||||
settings: z.object({
|
||||
timezone: z.string(),
|
||||
currency: z.string(),
|
||||
language: z.string(),
|
||||
}),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
});
|
||||
|
||||
export type CreateHouseholdInput = z.infer<typeof CreateHouseholdSchema>;
|
||||
export type UpdateHouseholdInput = z.infer<typeof UpdateHouseholdSchema>;
|
||||
export type JoinHouseholdInput = z.infer<typeof JoinHouseholdSchema>;
|
||||
2
packages/shared/src/validation/index.ts
Normal file
2
packages/shared/src/validation/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './user.schemas.js';
|
||||
export * from './household.schemas.js';
|
||||
84
packages/shared/src/validation/user.schemas.test.ts
Normal file
84
packages/shared/src/validation/user.schemas.test.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import { CreateUserSchema, UpdateUserSchema } from './user.schemas.js';
|
||||
|
||||
describe('CreateUserSchema', () => {
|
||||
it('accepts valid input', () => {
|
||||
const result = CreateUserSchema.safeParse({
|
||||
keycloakId: 'kc-1',
|
||||
displayName: 'Test User',
|
||||
email: 'test@example.com',
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.householdIds).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects missing keycloakId', () => {
|
||||
const result = CreateUserSchema.safeParse({
|
||||
displayName: 'Test',
|
||||
email: 'test@example.com',
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects empty keycloakId', () => {
|
||||
const result = CreateUserSchema.safeParse({
|
||||
keycloakId: '',
|
||||
displayName: 'Test',
|
||||
email: 'test@example.com',
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects invalid email', () => {
|
||||
const result = CreateUserSchema.safeParse({
|
||||
keycloakId: 'kc-1',
|
||||
displayName: 'Test',
|
||||
email: 'not-email',
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('trims displayName', () => {
|
||||
const result = CreateUserSchema.safeParse({
|
||||
keycloakId: 'kc-1',
|
||||
displayName: ' Test ',
|
||||
email: 'test@example.com',
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.displayName).toBe('Test');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects displayName exceeding 100 chars', () => {
|
||||
const result = CreateUserSchema.safeParse({
|
||||
keycloakId: 'kc-1',
|
||||
displayName: 'x'.repeat(101),
|
||||
email: 'test@example.com',
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UpdateUserSchema', () => {
|
||||
it('accepts partial updates', () => {
|
||||
const result = UpdateUserSchema.safeParse({ displayName: 'New Name' });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts empty object (all fields optional)', () => {
|
||||
const result = UpdateUserSchema.safeParse({});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('does not allow keycloakId', () => {
|
||||
const result = UpdateUserSchema.safeParse({ keycloakId: 'kc-1' });
|
||||
// keycloakId is omitted, so it should be stripped or rejected
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect('keycloakId' in result.data).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
14
packages/shared/src/validation/user.schemas.ts
Normal file
14
packages/shared/src/validation/user.schemas.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { z } from 'zod/v4';
|
||||
|
||||
export const CreateUserSchema = z.object({
|
||||
keycloakId: z.string().min(1),
|
||||
displayName: z.string().min(1).max(100).trim(),
|
||||
email: z.email(),
|
||||
householdIds: z.array(z.string()).default([]),
|
||||
defaultHouseholdId: z.string().optional(),
|
||||
});
|
||||
|
||||
export const UpdateUserSchema = CreateUserSchema.partial().omit({ keycloakId: true });
|
||||
|
||||
export type CreateUserInput = z.infer<typeof CreateUserSchema>;
|
||||
export type UpdateUserInput = z.infer<typeof UpdateUserSchema>;
|
||||
12
packages/shared/tsconfig.json
Normal file
12
packages/shared/tsconfig.json
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
8
packages/shared/tsconfig.test.json
Normal file
8
packages/shared/tsconfig.test.json
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": []
|
||||
}
|
||||
30
packages/shared/vitest.config.ts
Normal file
30
packages/shared/vitest.config.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['src/**/*.test.ts'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
enabled: false,
|
||||
include: ['src/**/*.ts'],
|
||||
exclude: [
|
||||
'src/**/*.test.ts',
|
||||
'src/index.ts',
|
||||
'src/types/**', // pure type declarations
|
||||
'src/enums/index.ts',
|
||||
'src/validation/index.ts',
|
||||
],
|
||||
reporter: ['text', 'lcov', 'json-summary', 'html'],
|
||||
reportsDirectory: './coverage',
|
||||
thresholds: {
|
||||
lines: 100,
|
||||
functions: 100,
|
||||
branches: 90,
|
||||
statements: 100,
|
||||
},
|
||||
},
|
||||
testTimeout: 10_000,
|
||||
},
|
||||
});
|
||||
47
packages/web/eslint.config.js
Normal file
47
packages/web/eslint.config.js
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import tseslint from 'typescript-eslint';
|
||||
import reactPlugin from 'eslint-plugin-react';
|
||||
import reactHooksPlugin from 'eslint-plugin-react-hooks';
|
||||
import nextPlugin from '@next/eslint-plugin-next';
|
||||
import prettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['.next/**', 'coverage/**'] },
|
||||
...tseslint.configs.recommended,
|
||||
// React flat config — uses JSX runtime transform (no need to import React)
|
||||
reactPlugin.configs.flat['jsx-runtime'],
|
||||
// React Hooks
|
||||
{
|
||||
plugins: { 'react-hooks': reactHooksPlugin },
|
||||
rules: reactHooksPlugin.configs.recommended.rules,
|
||||
},
|
||||
// Next.js
|
||||
{
|
||||
plugins: { '@next/next': nextPlugin },
|
||||
rules: {
|
||||
...nextPlugin.configs.recommended.rules,
|
||||
...nextPlugin.configs['core-web-vitals'].rules,
|
||||
},
|
||||
},
|
||||
{
|
||||
settings: {
|
||||
react: { version: 'detect' },
|
||||
},
|
||||
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' },
|
||||
],
|
||||
},
|
||||
},
|
||||
prettierRecommended,
|
||||
);
|
||||
6
packages/web/next-env.d.ts
vendored
Normal file
6
packages/web/next-env.d.ts
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/types/routes.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
7
packages/web/next.config.ts
Normal file
7
packages/web/next.config.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import type { NextConfig } from 'next';
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
transpilePackages: ['@meshitrack/shared'],
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
34
packages/web/package.json
Normal file
34
packages/web/package.json
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
{
|
||||
"name": "@meshitrack/web",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "next dev --port 3000 --turbopack",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint src",
|
||||
"lint-fix": "eslint src --fix",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "echo 'no tests yet'"
|
||||
},
|
||||
"dependencies": {
|
||||
"@meshitrack/shared": "*",
|
||||
"next": "^16.2.0",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"swr": "^2.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@next/eslint-plugin-next": "^16.2.1",
|
||||
"@tailwindcss/postcss": "^4.2.0",
|
||||
"@types/node": "^25.0.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"tailwindcss": "^4.2.0",
|
||||
"typescript": "^6.0.0"
|
||||
}
|
||||
}
|
||||
5
packages/web/postcss.config.mjs
Normal file
5
packages/web/postcss.config.mjs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
};
|
||||
61
packages/web/src/app/(dashboard)/dashboard/page.tsx
Normal file
61
packages/web/src/app/(dashboard)/dashboard/page.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import Link from 'next/link';
|
||||
|
||||
export default function DashboardPage() {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold mb-4">Dashboard</h1>
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
<DashboardCard
|
||||
title="Product Library"
|
||||
description="Manage your food products and nutrition data"
|
||||
href="/products"
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Recipes"
|
||||
description="Create and manage recipes with auto-nutrition"
|
||||
href="/recipes"
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Pantry"
|
||||
description="Track what's in your fridge and pantry"
|
||||
href="/pantry"
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Meal Plans"
|
||||
description="Plan your weekly meals and hit nutrition targets"
|
||||
href="/meal-plans"
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Shopping Lists"
|
||||
description="Create shopping lists and track prices"
|
||||
href="/shopping"
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Settings"
|
||||
description="Manage household and account settings"
|
||||
href="/settings"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DashboardCard({
|
||||
title,
|
||||
description,
|
||||
href,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
href: string;
|
||||
}) {
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
className="rounded-xl border bg-white p-6 shadow-sm hover:shadow-md transition-shadow"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">{title}</h2>
|
||||
<p className="mt-1 text-sm text-gray-500">{description}</p>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
14
packages/web/src/app/(dashboard)/layout.tsx
Normal file
14
packages/web/src/app/(dashboard)/layout.tsx
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { Sidebar } from '@/components/layout/Sidebar';
|
||||
import { TopBar } from '@/components/layout/TopBar';
|
||||
|
||||
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex h-screen">
|
||||
<Sidebar />
|
||||
<div className="flex flex-1 flex-col">
|
||||
<TopBar />
|
||||
<main className="flex-1 overflow-auto p-6">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
7
packages/web/src/app/(dashboard)/loading.tsx
Normal file
7
packages/web/src/app/(dashboard)/loading.tsx
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
32
packages/web/src/app/(dashboard)/settings/page.tsx
Normal file
32
packages/web/src/app/(dashboard)/settings/page.tsx
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
export default function SettingsPage() {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold mb-4">Settings</h1>
|
||||
<div className="max-w-2xl space-y-6">
|
||||
<section className="rounded-xl border bg-white p-6 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-4">Household</h2>
|
||||
<p className="text-sm text-gray-500">
|
||||
Household management will be available here. Create a household, invite members, or
|
||||
switch between households.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border bg-white p-6 shadow-sm">
|
||||
<h2 className="text-lg font-semibold mb-4">Account</h2>
|
||||
<p className="text-sm text-gray-500">
|
||||
Account settings are managed through Keycloak. Click the button below to manage your
|
||||
profile.
|
||||
</p>
|
||||
<a
|
||||
href={`${process.env.NEXT_PUBLIC_KEYCLOAK_URL || 'http://localhost:8080'}/realms/${process.env.NEXT_PUBLIC_KEYCLOAK_REALM || 'meshitrack'}/account`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-4 inline-block rounded-lg border px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
Manage Keycloak Account →
|
||||
</a>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
3
packages/web/src/app/api/auth/[...nextauth]/route.ts
Normal file
3
packages/web/src/app/api/auth/[...nextauth]/route.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { handlers } from '@/lib/auth';
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
15
packages/web/src/app/layout.tsx
Normal file
15
packages/web/src/app/layout.tsx
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import type { Metadata } from 'next';
|
||||
import '@/styles/globals.css';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'MeshiTrack',
|
||||
description: 'Nutrition & Pantry Management Platform',
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className="min-h-screen bg-gray-50">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
20
packages/web/src/app/login/page.tsx
Normal file
20
packages/web/src/app/login/page.tsx
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use client';
|
||||
|
||||
import { signIn } from 'next-auth/react';
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="w-full max-w-sm rounded-xl border bg-white p-8 shadow-sm">
|
||||
<h1 className="text-2xl font-bold text-center mb-2">MeshiTrack</h1>
|
||||
<p className="text-gray-500 text-center text-sm mb-6">Sign in to manage your kitchen</p>
|
||||
<button
|
||||
onClick={() => signIn('keycloak', { callbackUrl: '/dashboard' })}
|
||||
className="block w-full rounded-lg bg-primary-600 py-3 text-center text-white font-medium hover:bg-primary-700 transition-colors"
|
||||
>
|
||||
Sign in with Keycloak
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
21
packages/web/src/app/page.tsx
Normal file
21
packages/web/src/app/page.tsx
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import Link from 'next/link';
|
||||
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h1 className="text-4xl font-bold text-primary-700 mb-4">MeshiTrack</h1>
|
||||
<p className="text-gray-600 mb-8 max-w-md">
|
||||
Your household nutrition & pantry management platform. Track food, plan meals, reduce
|
||||
waste, save money.
|
||||
</p>
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-block rounded-lg bg-primary-600 px-6 py-3 text-white font-medium hover:bg-primary-700 transition-colors"
|
||||
>
|
||||
Sign In
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
packages/web/src/components/layout/Sidebar.tsx
Normal file
37
packages/web/src/components/layout/Sidebar.tsx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import Link from 'next/link';
|
||||
|
||||
const navItems = [
|
||||
{ label: 'Dashboard', href: '/dashboard' },
|
||||
{ label: 'Products', href: '/products' },
|
||||
{ label: 'Recipes', href: '/recipes' },
|
||||
{ label: 'Pantry', href: '/pantry' },
|
||||
{ label: 'Meal Plans', href: '/meal-plans' },
|
||||
{ label: 'Shopping', href: '/shopping' },
|
||||
{ label: 'Settings', href: '/settings' },
|
||||
];
|
||||
|
||||
export function Sidebar() {
|
||||
return (
|
||||
<aside className="flex w-64 flex-col border-r bg-white">
|
||||
<div className="flex h-16 items-center border-b px-6">
|
||||
<Link href="/dashboard" className="text-xl font-bold text-primary-700">
|
||||
MeshiTrack
|
||||
</Link>
|
||||
</div>
|
||||
<nav className="flex-1 overflow-y-auto p-4">
|
||||
<ul className="space-y-1">
|
||||
{navItems.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link
|
||||
href={item.href}
|
||||
className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 transition-colors"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
28
packages/web/src/components/layout/TopBar.tsx
Normal file
28
packages/web/src/components/layout/TopBar.tsx
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { auth } from '@/lib/auth';
|
||||
|
||||
export async function TopBar() {
|
||||
const session = await auth();
|
||||
const name = session?.user?.name ?? 'Unknown';
|
||||
const initial = name.charAt(0).toUpperCase();
|
||||
const householdId = session?.householdIds?.[0] ?? null;
|
||||
|
||||
return (
|
||||
<header className="flex h-16 items-center justify-between border-b bg-white px-6">
|
||||
<div className="text-sm text-gray-500">
|
||||
{householdId ? (
|
||||
<span className="rounded-md border px-3 py-1 font-medium text-gray-700">
|
||||
{householdId}
|
||||
</span>
|
||||
) : (
|
||||
<span className="rounded-md border px-3 py-1 text-gray-400">No household</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-sm text-gray-600">{name}</span>
|
||||
<div className="h-8 w-8 rounded-full bg-primary-200 flex items-center justify-center text-sm font-medium text-primary-800">
|
||||
{initial}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
52
packages/web/src/lib/auth.ts
Normal file
52
packages/web/src/lib/auth.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import NextAuth from 'next-auth';
|
||||
import Keycloak from 'next-auth/providers/keycloak';
|
||||
|
||||
const keycloakInternalUrl = process.env.KEYCLOAK_URL!;
|
||||
const keycloakPublicUrl = process.env.NEXT_PUBLIC_KEYCLOAK_URL!;
|
||||
const realm = process.env.KEYCLOAK_REALM!;
|
||||
|
||||
const internalBase = `${keycloakInternalUrl}/realms/${realm}`;
|
||||
const publicBase = `${keycloakPublicUrl}/realms/${realm}`;
|
||||
|
||||
export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
providers: [
|
||||
Keycloak({
|
||||
clientId: process.env.KEYCLOAK_CLIENT_ID!,
|
||||
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
|
||||
// issuer must match KC_HOSTNAME_URL so iss claim validation passes
|
||||
issuer: publicBase,
|
||||
// auth.js calls oauth4webapi.discoveryRequest(issuer) which constructs the URL from
|
||||
// `issuer` directly — our `wellKnown` override is ignored in that code path.
|
||||
// Bypass discovery entirely by pre-supplying all endpoints:
|
||||
// - authorization uses the public URL (browser redirect)
|
||||
// - token/userinfo/jwks use the internal Docker hostname (server-side fetches)
|
||||
// These values match what KC_HOSTNAME_URL would return in the discovery document anyway.
|
||||
authorization: `${publicBase}/protocol/openid-connect/auth`,
|
||||
token: `${internalBase}/protocol/openid-connect/token`,
|
||||
userinfo: `${internalBase}/protocol/openid-connect/userinfo`,
|
||||
jwks_endpoint: `${internalBase}/protocol/openid-connect/certs`,
|
||||
}),
|
||||
],
|
||||
pages: {
|
||||
signIn: '/login',
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, account, profile }) {
|
||||
if (account) {
|
||||
token.accessToken = account.access_token;
|
||||
token.refreshToken = account.refresh_token;
|
||||
token.expiresAt = account.expires_at;
|
||||
// householdIds is injected into the ID token by the Keycloak protocol mapper
|
||||
token.householdIds = (profile as Record<string, unknown>)?.['householdIds'] as
|
||||
| string[]
|
||||
| undefined;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
session.accessToken = token.accessToken as string;
|
||||
session.householdIds = (token.householdIds as string[] | undefined) ?? [];
|
||||
return session;
|
||||
},
|
||||
},
|
||||
});
|
||||
6
packages/web/src/proxy.ts
Normal file
6
packages/web/src/proxy.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export { auth as proxy } from '@/lib/auth';
|
||||
|
||||
export const config = {
|
||||
// Protect all routes except auth callbacks, the login page, and Next.js internals.
|
||||
matcher: ['/((?!api/auth|login|_next/static|_next/image|favicon.ico).*)'],
|
||||
};
|
||||
73
packages/web/src/services/api-client.ts
Normal file
73
packages/web/src/services/api-client.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1';
|
||||
|
||||
class ApiClient {
|
||||
private _accessToken: string | null = null;
|
||||
|
||||
public set accessToken(token: string) {
|
||||
this._accessToken = token;
|
||||
}
|
||||
|
||||
private getHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
if (this._accessToken) {
|
||||
headers['Authorization'] = `Bearer ${this._accessToken}`;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
public async get<T>(url: string): Promise<T> {
|
||||
const res = await fetch(`${BASE_URL}${url}`, {
|
||||
headers: this.getHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ message: res.statusText }));
|
||||
throw new Error(error.message || `Request failed: ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
public async post<T>(url: string, body?: unknown): Promise<T> {
|
||||
const res = await fetch(`${BASE_URL}${url}`, {
|
||||
method: 'POST',
|
||||
headers: this.getHeaders(),
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ message: res.statusText }));
|
||||
throw new Error(error.message || `Request failed: ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
public async patch<T>(url: string, body: unknown): Promise<T> {
|
||||
const res = await fetch(`${BASE_URL}${url}`, {
|
||||
method: 'PATCH',
|
||||
headers: this.getHeaders(),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ message: res.statusText }));
|
||||
throw new Error(error.message || `Request failed: ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
public async delete<T = void>(url: string): Promise<T> {
|
||||
const res = await fetch(`${BASE_URL}${url}`, {
|
||||
method: 'DELETE',
|
||||
headers: this.getHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ message: res.statusText }));
|
||||
throw new Error(error.message || `Request failed: ${res.status}`);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json();
|
||||
}
|
||||
}
|
||||
|
||||
export const apiClient = new ApiClient();
|
||||
24
packages/web/src/styles/globals.css
Normal file
24
packages/web/src/styles/globals.css
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--color-primary-50: #f0fdf4;
|
||||
--color-primary-100: #dcfce7;
|
||||
--color-primary-200: #bbf7d0;
|
||||
--color-primary-300: #86efac;
|
||||
--color-primary-400: #4ade80;
|
||||
--color-primary-500: #22c55e;
|
||||
--color-primary-600: #16a34a;
|
||||
--color-primary-700: #15803d;
|
||||
--color-primary-800: #166534;
|
||||
--color-primary-900: #14532d;
|
||||
}
|
||||
|
||||
:root {
|
||||
--foreground-rgb: 0, 0, 0;
|
||||
--background-rgb: 255, 255, 255;
|
||||
}
|
||||
|
||||
body {
|
||||
color: rgb(var(--foreground-rgb));
|
||||
background: rgb(var(--background-rgb));
|
||||
}
|
||||
25
packages/web/tsconfig.json
Normal file
25
packages/web/tsconfig.json
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["dom", "dom.iterable", "ES2022"],
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"verbatimModuleSyntax": false,
|
||||
"jsx": "preserve",
|
||||
"noEmit": true,
|
||||
"incremental": true,
|
||||
"declaration": false,
|
||||
"declarationMap": false,
|
||||
"isolatedModules": true,
|
||||
"allowJs": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"],
|
||||
"@meshitrack/shared": ["../shared/src"],
|
||||
"@meshitrack/shared/*": ["../shared/src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue