Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Moneyzent API

Moneyzent is a private personal-finance REST API built with NestJS. It provides Firebase-authenticated CRUD endpoints for financial accounts, payees, categories, and transactions, with PostgreSQL persistence and Zod-validated request and response DTOs.

Recurring transaction groups let users save transaction templates and manually create the whole group on one selected date. They have no schedule or interval. See the data model and endpoint contracts.

Stack

  • NestJS 12 and TypeScript 6
  • PostgreSQL and TypeORM
  • Firebase Authentication
  • Zod through NestJS Standard Schema validation and serialization
  • Terminus database readiness checks
  • Helmet security headers and request rate limiting
  • Jest, Supertest, Oxlint, and Prettier
  • Bruno request collections for local API workflows

Prerequisites

  • Node.js 24 and npm
  • PostgreSQL
  • curl or Bruno for exercising the API

Firebase CLI is installed as a development dependency; local development does not require a Firebase account or service-account key.

Local setup

  1. Install the locked dependencies:

    npm ci
  2. Copy the example environment file:

    cp .env.example .env

    On PowerShell, use Copy-Item .env.example .env.

  3. Start PostgreSQL, create the database named in DATABASE_URL, and apply the migrations:

    npm run migration:run
  4. Start the Firebase Auth emulator and seed the local test users (the API test user and the frontend e2e user):

    npm run firebase:emulators
  5. In another terminal, start the API in watch mode:

    npm run start:dev
  6. Confirm the API is running:

    curl http://127.0.0.1:3000/health

The API defaults to http://127.0.0.1:3000. The Firebase Auth emulator listens on 127.0.0.1:9099, and the Emulator UI is available at http://127.0.0.1:4000.

Stop the emulator with Ctrl+C in its terminal, or from anywhere with:

npm run firebase:emulators:stop

The Firebase CLI has no stop command and its hub exposes no shutdown route, so the script terminates whatever is listening on FIREBASE_AUTH_EMULATOR_HOST along with the emulator hub recorded in the hub locator file, then removes that file. Use it when an emulator survives a closed terminal and the next start fails with "Port 9099 is not open". It refuses to run unless FIREBASE_PROJECT_ID starts with demo-, and it never touches the Emulator UI port, which is a common port for unrelated development servers.

Configuration

Configuration is loaded from .env and validated with Zod during startup. Invalid or missing required values stop the application before it begins listening.

Variable Required Default / purpose
APP_ENV No development; one of development, staging, prod, or test
PORT No Railway-provided listen port; takes precedence over APP_PORT
APP_PORT No 3000; local fallback when PORT is absent
APP_TRUST_PROXY_HOPS No 0; trusted reverse-proxy hops used to resolve the client IP
CORS_ALLOWED_ORIGINS No Comma-separated browser origins; cross-origin access is disabled when empty
LOG_LEVEL No info, or silent in test; one of pino's levels
DATABASE_URL Yes PostgreSQL connection URL
DATABASE_POOL_SIZE No 10
RATE_LIMIT_MAX_REQUESTS No 100; requests allowed per client IP in one window
RATE_LIMIT_TTL_MS No 60000; rate-limit window in milliseconds
FIREBASE_PROJECT_ID No Firebase project; local default is demo-moneyzent
FIREBASE_AUTH_EMULATOR_HOST No Emulator hostname:port; allowed only in development or test
FIREBASE_SERVICE_ACCOUNT_BASE64 No* Base64-encoded Firebase service-account JSON for deployed environments
FIREBASE_USE_APPLICATION_DEFAULT_CREDENTIALS No false; opts a deployed environment out of requiring a service account

For staging and production, remove FIREBASE_AUTH_EMULATOR_HOST and use either Application Default Credentials or FIREBASE_SERVICE_ACCOUNT_BASE64. Never commit .env or service-account credentials.

* When APP_ENV is staging or prod, startup fails unless FIREBASE_SERVICE_ACCOUNT_BASE64 is set or FIREBASE_USE_APPLICATION_DEFAULT_CREDENTIALS=true declares that the platform supplies Application Default Credentials. This turns a missing credential into a startup failure rather than an API that boots and rejects every authenticated request. Railway provides no Application Default Credentials, so set the service account there.

Set APP_TRUST_PROXY_HOPS=1 when the API runs behind Railway's edge proxy so rate limiting uses the originating client IP. Configure CORS_ALLOWED_ORIGINS with exact origins such as https://app.moneyzent.example; wildcard origins and origins containing paths are rejected during startup. The API enables CORS only when the allowlist is non-empty.

Railway deployment settings

Configure each Railway service with these commands:

Railway setting Value
Build command npm run build
Pre-deploy command npm run migration:run:prod
Start command npm start
Healthcheck path /health

npm start runs node dist/main.js directly. The application prefers Railway's injected PORT, falls back to APP_PORT for local use, listens on 0.0.0.0, and enables Nest shutdown hooks so SIGTERM closes application resources cleanly. The pre-deploy migration command runs compiled migrations before a new deployment starts and aborts the deployment when a migration fails.

Set APP_ENV=staging or APP_ENV=prod as appropriate. Runtime TypeORM schema synchronization is disabled in every environment; migrations are the only way the schema changes. Do not set the Firebase emulator variable in either deployed environment.

HTTP security and readiness

Helmet applies security-related response headers to every route. A global, in-memory rate limiter allows RATE_LIMIT_MAX_REQUESTS requests per resolved client IP during each RATE_LIMIT_TTL_MS window. The health endpoint is exempt from rate limiting so infrastructure checks cannot be blocked.

GET /health is a readiness check backed by Terminus and TypeORM. It executes SELECT 1 through the application's database connection and returns 200 only while PostgreSQL is reachable; an unhealthy check returns 503. The endpoint remains anonymous for Railway and external monitors. Terminus 12 includes the database check's responseTime in milliseconds under both info.database and details.database.

Logging

Logging goes through Pino, wired up by src/modules/logging/. Deployed environments write one JSON object per line to stdout, which is what Railway's log explorer parses; development pretty-prints instead. Levels are written as labels (info, warn, error) and timestamps as ISO strings so both are filterable without a custom parser.

Every completed request produces one line carrying the method, URL, status code, and duration:

{
  "level": "warn",
  "time": "2026-08-29T19:54:27.226Z",
  "req": { "id": "bfbf4321-...", "method": "GET", "url": "/missing" },
  "res": { "statusCode": 404 },
  "responseTime": 1,
  "msg": "request completed"
}

Severity follows the response: 2xx is info, 4xx is warn, and 5xx or a thrown error is error. GET /health is never logged, because Railway polls it continuously and those lines would bury real traffic.

Each request carries a correlation id. The x-request-id header is reused when the proxy supplies a well-formed one and generated otherwise, then echoed back on the response. Injecting Logger from nestjs-pino into a service attaches that id to everything the service logs, so a stack trace can be tied to the request that caused it.

Request headers are never logged. The serializers emit only the fields above, which keeps bearer tokens and cookies out of the logs regardless of what a caller sends; REDACTED_LOG_PATHS is a second line of defence if those serializers are ever changed.

Set LOG_LEVEL to override the default. LOG_LEVEL=debug turns a deployed instance up without a code change, and LOG_LEVEL=warn logs only failed requests when request volume makes per-request logging too costly. The application is silent in test so the end-to-end suite's own [e2e] lines stay readable.

Authentication

All endpoints are protected by the global Firebase guard unless their handler is explicitly decorated with @AllowAnonymous(). Send a Firebase ID token in the standard bearer header:

Authorization: Bearer <firebase-id-token>

The local emulator script creates this development-only user:

Email: test@moneyzent.local
Password: TestPassword123!

To obtain an ID token without Bruno:

curl -s -X POST \
  "http://127.0.0.1:9099/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=demo-key" \
  -H "Content-Type: application/json" \
  -d '{"email":"test@moneyzent.local","password":"TestPassword123!","returnSecureToken":true}'

Use the returned idToken to call a protected route:

curl http://127.0.0.1:3000/user \
  -H "Authorization: Bearer <idToken>"

Endpoints

Method Route Authentication Purpose
GET / Public Basic service response
GET /health Public PostgreSQL-backed readiness check
GET /user Firebase token Return the authenticated Firebase user
GET /accounts Firebase token List the user's financial accounts
POST /accounts Firebase token Create an account (USD, CAD, or INR)
GET /accounts/:id Firebase token Get one account
PATCH /accounts/:id Firebase token Rename one account
DELETE /accounts/:id Firebase token Soft-delete one account
GET /payees Firebase token List the user's payees
POST /payees Firebase token Create a payee
GET /payees/:id Firebase token Get one payee
GET /payees/:id/last-used-category Firebase token Category id of the payee's latest transaction
PATCH /payees/:id Firebase token Update one payee
DELETE /payees/:id Firebase token Soft-delete one payee
GET /categories Firebase token List the user's category tree
POST /categories Firebase token Create a category
GET /categories/:id Firebase token Get one category
PATCH /categories/:id Firebase token Update one category
DELETE /categories/:id Firebase token Soft-delete one category
GET /transactions/filter Firebase token Filter the user's transactions
POST /transactions/bulk Firebase token Create multiple transactions atomically
POST /transactions Firebase token Create a transaction
GET /transactions/:id Firebase token Get one transaction
PATCH /transactions/:id Firebase token Update one transaction
DELETE /transactions/:id Firebase token Soft-delete one transaction
GET /recurring-transaction-groups Firebase token List recurring groups and their items
POST /recurring-transaction-groups Firebase token Create a recurring group
GET /recurring-transaction-groups/:id Firebase token Get a recurring group
PATCH /recurring-transaction-groups/:id Firebase token Update a group and/or replace its items
DELETE /recurring-transaction-groups/:id Firebase token Soft-delete a group and its items

Account, payee, category, and transaction operations are always scoped to the authenticated Firebase user ID. A transaction date uses YYYY-MM-DD; its type is income or expense; and amountMinor is a positive integer string in the account currency's minor units. A transaction references an account, payee, and category by their accountUuid, payeeUuid, and categoryUuid values. An account's currency is fixed when the account is created and cannot be updated. The financial_account.currency_type column stores any ISO 4217 alphabetic code, while the API currently accepts only USD, CAD, and INR; widening that list is an application change and needs no migration. Filtering transactions requires the accountId, type, startDate, and endDate query parameters. Type is income or expense; dates use YYYY-MM-DD, and both boundaries are inclusive.

Filter results are a display shape rather than the stored shape. Each result carries nested account, payee, and category objects instead of the accountUuid, payeeUuid, and categoryUuid values, and authenticated user data is omitted. Its date is formatted for display (Aug 15, 2026), and amountMinor is replaced by displayAmount, the amount rendered in the account's currency with whole amounts shown without decimals ($125, $125.50, ₹125). The nested category adds displayCategory, which is Parent:Child for a child category and the plain name for a root category, and a parent object that is null for a root category. The other transaction endpoints continue to return the stored shape with date, amountMinor, and the *Uuid values.

GET /payees/:id/last-used-category returns { "categoryId" }, the category of the payee's most recent transaction, ordered by transaction date and then creation time. categoryId is null when the payee has no transaction yet, so a client can prefill the category for a known payee and fall back to a manual choice otherwise. An unknown payee or one owned by another user answers 404.

Bruno workflows

The collection in bruno/ signs in through the local Firebase emulator and stores the returned token as {{idToken}}. Start PostgreSQL, the emulator, and the API before running these commands:

npm run bruno:auth
npm run bruno:accounts
npm run bruno:payees
npm run bruno:categories
npm run bruno:transactions

The account, payee, and category workflows authenticate, then create, list, get, update, and delete one resource. The category list request also checks the tree response shape, and the payee workflow checks that the freshly created payee has no last used category yet. The transaction workflow exercises only transaction create, filter, get, update, and delete. Before running it, set transactionAccountId, transactionPayeeId, and transactionCategoryId in the Bruno local environment to existing resources owned by the authenticated user. The workflow leaves those related resources unchanged. The Bruno CLI must be available as bru to run these scripts; alternatively, open bruno/ in the Bruno desktop app and select the local environment.

Database and migrations

Entities live with their feature modules, while TypeORM migrations live in src/migrations/.

# Generate a migration after changing an entity
npm run migration:generate -- src/migrations/DescribeChange

# Create an empty migration
npm run migration:create -- src/migrations/DescribeChange

# Inspect, apply, or revert migrations
npm run migration:show
npm run migration:run
npm run migration:revert

# Apply compiled migrations after npm run build
npm run migration:run:prod

The TypeORM CLI data source and Nest runtime always use synchronize: false and never run migrations automatically. Migrations are the only schema source of truth in every environment—review every generated up and down method before applying it.

Mock database

moneyzent-mock is a throwaway PostgreSQL database that is created from scratch, filled with fixtures for two Firebase users, and dropped again. The end-to-end suite prepares its own database, moneyzent-mock-e2e, with the same logic and the same fixtures, so the two never interfere.

# Seed: create the database, apply migrations, and fill every entity
npm run db:mock:seed

# Teardown: drop the database
npm run db:mock:teardown

Seeding requires a running Firebase Auth emulator (npm run firebase:emulators) and a reachable PostgreSQL server. It runs in this order:

  1. mock.one@moneyzent.local and mock.two@moneyzent.local are created in the Firebase Auth emulator, which supplies the userId every row is scoped to.
  2. moneyzent-mock is created on the server named in DATABASE_URL. Seeding fails if the database already exists; run the teardown first.
  3. The migrations in src/migrations/ are applied.
  4. Each user receives its own payees, financial accounts, a two-level category tree, and transactions, inside a single database transaction.

Both users receive identical fixture names so tests can assert user scoping on data that differs only by userId. If the seed fails after the database is created, it is dropped again so the next run starts clean.

Teardown drops the database only. The emulator users are left in place and are signed into and reused on the next seed, so their uids stay stable across seed and teardown cycles.

Guardrails: seeding and teardown refuse to run unless APP_ENV is development or test, FIREBASE_PROJECT_ID starts with demo-, and DATABASE_URL points at a database other than moneyzent-mock and moneyzent-mock-e2e.

The reusable pieces live in src/modules/database/seeding/. A test can call provisionMockDatabase(databaseName) and teardownMockDatabase(databaseName) directly—both default to moneyzent-mock—and the provision result returns each seeded user's uid and a Firebase idToken for authenticating requests.

Development commands

Command Purpose
npm run start:dev Start NestJS in watch mode
npm run build Compile the application to dist/
npm run start:prod Run the compiled application
npm run lint Check src/, test/, and scripts/ with Oxlint
npm run format Format TypeScript and emulator scripts with Prettier
npm test Run Jest tests
npm run test:watch Run Jest in watch mode
npm run test:cov Run tests with coverage
npm run test:e2e Run the Supertest end-to-end suite
npm run firebase:emulators Start the local Firebase Auth emulator
npm run firebase:emulators:stop Stop the local Firebase Auth emulator
npm run db:mock:seed Create and seed the moneyzent-mock database
npm run db:mock:teardown Drop the moneyzent-mock database

End-to-end tests

The suite in test/ drives the real application over HTTP against its own seeded database, moneyzent-mock-e2e. It is provisioned from the same fixtures as moneyzent-mock but kept separate, so a test run never disturbs the mock database you keep for manual work. Start the Firebase Auth emulator first, then run it:

npm run firebase:emulators   # in a separate terminal
npm run test:e2e

A run:

  1. drops and reprovisions moneyzent-mock-e2e (test/global-setup.ts), so every run starts from the same fixtures and an interrupted run leaves nothing behind;
  2. points DATABASE_URL at that database and forces APP_ENV=test before AppModule is imported (test/setup-environment.ts);
  3. signs both mock users into the emulator for their id tokens (test/utils/sign-in-mock-users.ts);
  4. drops the database again (test/global-teardown.ts).

Because the suite boots the whole application, it needs a valid .env, an accessible PostgreSQL server, and the emulator. Tests name every record they create with the E2E_NAME_PREFIX prefix and leave the seeded fixtures alone, so assertions on the fixtures hold no matter which tests ran before.

Every request a test makes is printed as it completes (test/utils/log-http-requests.ts):

[e2e] POST /payees 201 12ms
[e2e] GET /payees/8f0e… 404 4ms

Jest prints only the run summary by default; add --verbose --reporters=default to see suite and test names alongside those lines:

npm run test:e2e -- --verbose --reporters=default

All Jest scripts run under --experimental-vm-modules to load NestJS 12 and Firebase's ESM dependencies. Use the pinned Node.js 24.20.0 runtime; Jest's CommonJS-to-ESM support requires Node.js 24.9 or newer. Run a focused unit test with npm test -- src/modules/payee/tests/payee.service.spec.ts --runInBand.

The NestJS 12 upgrade retains CommonJS application output and Pino logging. Zod schemas are passed directly to Nest's StandardSchemaValidationPipe via @Body({ schema }) and @Query({ schema }). Response handlers use @SerializeOptions({ schema }) with StandardSchemaSerializerInterceptor; array responses use the item schema. DTO types are inferred from the schemas. Validation keeps the 400 response with message: "Validation failed" and an errors array. Invalid response objects return 500 without exposing their data. Environment configuration uses ConfigModule's Standard Schema validation. nestjs-zod and @nestjs/observe are not installed. Firebase authentication is implemented locally in src/modules/auth/ using firebase-admin. The service owns its Firebase app and deletes it on module shutdown. The global guard verifies ID tokens with revocation checks and the local @FirebaseUser() decorator reads the verified user from the request. Service-account credentials, Application Default Credentials, and the local Auth emulator use the existing environment configuration.

A package-specific npm override aligns @nestjs/throttler with the application's NestJS dependencies; its current release still declares NestJS 11 ranges. Revisit this override when the package publishes NestJS 12 support. Keep it scoped so a clean npm ci installs one shared NestJS runtime.

Project structure

src/
  modules/
    account/          # Financial-account controller, service, entity, DTOs, tests
    auth/             # Global Firebase guard and public-route decorator
    configuration/    # Environment schema and ConfigModule setup
    database/         # TypeORM runtime and CLI configuration, shared base entity
      seeding/        # Mock-database provisioning, entity seeders, and fixtures
    health/           # PostgreSQL-backed readiness endpoint
    payee/            # Payee controller, service, entity, DTOs, tests
  migrations/         # Versioned PostgreSQL schema changes
  app.module.ts       # Application composition and Standard Schema providers
bruno/                # Authenticated local API workflows
docs/                 # Code style and naming conventions
scripts/              # Firebase emulator start/stop and mock-database CLIs
test/                 # HTTP end-to-end tests and their setup

See AGENTS.md for contributor guardrails, docs/CODE_STYLE.md for implementation conventions, and docs/NAMING_CONVENTIONS.md for naming rules.

License

UNLICENSED — private repository.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages