A TypeScript commerce backend for customers, products, inventory, orders, and staff accounts. Built with NestJS, TypeORM, and PostgreSQL, it combines transactional shop operations with JWT access tokens, database-backed sessions, rotating refresh tokens, and role-based access.
This is the p6_1a implementation in the existing p6_1 repository: stackwander/backend_nest_p6_secure. It uses the improved p6 shop implementation as its base and completes and hardens the user/token features introduced in p6_1, retaining the repository's Git history.
Originally part of the Stevaso Tech TypeScript End-to-End series, Parts 6 and 6.1.
Architecture & Development: Burhan Saadi
Application boundary: this is a staff/back-office API. Authorized staff share shop records. A staff account is not automatically the owner of a customer or order. Customer-facing login, record ownership, and tenant isolation require an additional authorization model.
- Architecture & Flow
- Key Features
- Repository Structure
- Architecture Concepts
- Getting Started
- Docker Deployment
- Configuration
- Authentication & Permissions
- API Reference & Examples
- Testing & Verification
- Migrations & Existing Databases
- Production Notes
- HTTP Errors & Troubleshooting
- Author & Project Background
- License
The application is a modular monolith: one deployable Node.js application with feature modules for customers, products, orders, users, and authentication, sharing a PostgreSQL database. Grouping related controllers, services, DTOs, and entities by feature provides elements of Vertical Slice Architecture, while each feature retains its controller/service/persistence layers. Shared database and HTTP infrastructure support those features.
The diagrams below are pre-rendered SVG images, so they load without the GitHub Mermaid renderer. Editable sources and regeneration instructions are in docs/diagrams.
JWT protection is global. Health, login, and refresh routes explicitly permit requests without an access JWT; login still validates credentials and refresh still validates its opaque token. CORS middleware handles configured browser preflights before route authorization.
| Layer | Responsibility | Where to look |
|---|---|---|
| Bootstrap | Start the app, configure HTTP, listen, and enable shutdown hooks | main.ts, setup.ts |
| Composition | Wire modules, database, rate limiting, logging, and filters | app.module.ts |
| Controllers | Define routes, accept validated input, delegate work | src/*/*.controller.ts |
| DTOs | Allowlisted fields, types, lengths, nested data, and UUID validation | src/*/dto/ |
| Feature services | Business rules and transactional persistence | orders.service.ts |
| Authentication | Login, token rotation, session revocation, password changes | auth.service.ts |
| Authorization | JWT verification, active-session checks, and role enforcement | jwt-auth.guard.ts |
| Entities | Records, relationships, timestamps, and serialization exclusions | src/*/entities/ |
| Database operations | Connection settings, explicit migrations, admin bootstrap, cleanup | database/ |
| Shared infrastructure | Pagination, completion logs, safe database errors | common/ |
Each order contains 1–100 distinct products. Items snapshot the product name and selling price; later catalog edits do not rewrite existing item prices. Foreign keys protect customer and product records referenced by retained order history.
Consumed refresh hashes are retained until session expiry to detect reuse. A separate
auth_login_attempt table stores atomic account-attempt counters keyed by a hash of the normalized
username. Auth tables do not establish ownership of shop customers or orders.
- Feature modules — Customers, products, orders, users, and authentication with explicit NestJS dependencies.
- Individual staff access — Reader, writer, and admin permissions; protected routes require a Bearer token.
- Strict JWT validation — External signing secret, pinned HS256, issuer/audience/purpose checks, and validated identifiers and lifetime.
- Complete session lifecycle — Five-minute access tokens, seven-day absolute sessions, refresh rotation, replay detection, and current/all-device logout.
- Safe account management — Admin-only user management, normalized unique email usernames, safe own-profile route, password hashing, and session revocation after security changes.
- Brute-force controls — Route/IP throttling and persistent account-attempt limits.
- Runtime validation — Unknown-field rejection, nested DTO checks, UUID validation, and bounded pagination.
- Retry-safe orders — Idempotency keys prevent duplicate reservations; transaction locks protect inventory.
- Consistent order history — Integer money, server-calculated totals, price snapshots, payment rules, cancellation, and soft deletion.
- Container deployment — Database health checks, migration job, non-root runtime, and optional k6 load profile.
- Automated verification — Unit and PostgreSQL integration tests, production-image smoke checks, and CI.
backend_nest_p6_secure/ # Existing repository; local folder may be backend_nest_p6_1
├── src/
│ ├── main.ts # Application entry point
│ ├── setup.ts # HTTP headers, CORS, body limit, validation, serialization
│ ├── app.module.ts # Feature and infrastructure composition
│ ├── config.ts # Local .env loading and configuration checks
│ ├── health.controller.ts # Public liveness and database readiness
│ ├── auth/
│ │ ├── auth.controller.ts # Login, refresh, logout, password and counts routes
│ │ ├── auth.service.ts # Tokens, transactions and revocation
│ │ ├── jwt-auth.guard.ts # Global JWT/session and role enforcement
│ │ ├── auth.types.ts # Public/role metadata, principal and token lifetimes
│ │ ├── password.ts # bcrypt hashing and UTF-8 byte-length checks
│ │ ├── dto/ # Login, refresh and password input contracts
│ │ └── entities/ # Session and refresh-token hash records
│ ├── users/ # Admin user management and own-profile access
│ ├── customers/ # Customer records
│ ├── products/ # Catalog, prices and available stock
│ ├── orders/ # Transactional orders and item snapshots
│ ├── common/ # Pagination, database filter and HTTP logging
│ └── database/
│ ├── data-source.ts # Shared connection, entities and migration list
│ ├── cli.ts # TypeORM migration entry point
│ ├── bootstrap-admin.ts # Explicit first-admin setup
│ ├── cleanup-auth.ts # Expired sessions and stale attempt counters
│ └── migrations/ # Initial shop schema and additive auth schema
├── test/
│ ├── app.e2e-spec.ts # PostgreSQL shop regression tests
│ ├── auth.e2e-spec.ts # JWT, roles, passwords and session security tests
│ ├── runtime-smoke.cjs # Compiled-container workflow assertions
│ ├── verify-runtime.ps1 # Disposable production-image verification
│ └── k6scripts/test.js # Optional authenticated load smoke test
├── docs/
│ ├── SECURITY.md # Security design and operating requirements
│ ├── CHANGES.md # p6_1a changes and client/data compatibility
│ ├── VERIFICATION.md # Dated checks and known audit findings
│ └── diagrams/ # Pre-rendered SVGs, editable Mermaid and regeneration
├── .github/workflows/ci.yml # CI with isolated PostgreSQL
├── .env.example # Configuration template, no working credentials
├── Dockerfile # Build and non-root production stages
├── docker-compose.yml # PostgreSQL, migrations, API and optional k6
├── rest-client.http # Editable authenticated request examples
├── test-data.txt # Current example request bodies
└── package.json # Locked toolchain and npm commands
Unit tests live beside their source as *.spec.ts. Compiled output and installed dependencies
are generated locally and excluded from Git.
Order creation writes the order, reserves stock, creates item snapshots, and calculates the total
in one transaction. Any failure rolls back the entire operation. Related writes use the
transaction's EntityManager. Order updates and cancellation also run transactionally.
POST /orders requires an Idempotency-Key containing 8–128 ASCII letters, digits, underscores,
or hyphens. A transaction-scoped advisory lock serializes the same key, and a normalized request
hash distinguishes retries from conflicting reuse.
Item ordering is normalized; comments and shipping date contribute to the fingerprint. Retry keys survive soft deletion. A retry returns the stored order's current state, rather than a cached original response. Internal keys and hashes are excluded from API responses. Keys are unique across the shared shop database, so clients should generate a fresh unique key for each new order.
Product rows are locked with pessimistic_write in sorted ID order before stock changes. Concurrent
orders for the last unit must take turns; a request with insufficient remaining stock receives 409.
Updates lock the order before changing its contents.
Prices use integer minor units in one application currency: 150 means 1.50 for a currency
with two decimal places. Product msrp becomes an item's initial unitPrice:
order.total = sum(item.unitPrice × item.quantity)
Prices and stock inputs range from 0 to 100,000,000. Item quantities range from 1 to 100,000, and order totals must fit a signed PostgreSQL integer. Existing products in a replacement item list retain their price snapshots. Taxes, discounts, shipping charges, and currency conversion are outside the calculation. DTOs allow product IDs and quantities; the server chooses item IDs, price/name snapshots, initial status/payment state, and totals.
Only pending orders can change. Editing paid items requires clearing payment confirmation,
beforehand or in the same patch. Shipping requires confirmed payment and supplies a shipping date
if absent. Cancellation requires payment to be cleared and releases stock once. Shipped and
cancelled orders cannot reopen. Deletion requires cancellation and sets deletedAt; deleted
is not another status value. Payment/refund flags record staff confirmation of external activity;
this backend does not process payments or refunds.
A JWT carries the user, session and token identifiers plus token purpose, issuer, audience and time claims. Every protected request verifies the JWT, then checks the session and current active user in PostgreSQL. Permissions come from the database. This allows revocation of still-unexpired access tokens on subsequent requests; an already-authorized request may finish.
Serialize refresh calls, including across tabs if a session is shared. Replace both returned tokens together. Replaying a consumed token, concurrent refreshes, or retrying after losing a successful refresh response revokes that session; there is no replay grace period. Refreshing never extends the session's absolute seven-day expiry.
- Docker with Compose for the bundled Linux-container stack.
- Node.js 24 or 26 and npm for host development; the Docker image and CI use Node 24.
- PostgreSQL 17 reachable from the host for a native development run.
- Your own database password, randomly generated signing secret, and first-admin credentials.
Work from the repository directory containing package.json and docker-compose.yml. For a
fresh checkout:
git clone https://github.com/stackwander/backend_nest_p6_secure.git
cd backend_nest_p6_secureCopy the template in PowerShell:
Copy-Item .env.example .envOn Linux/macOS use cp .env.example .env. Set DB_PASSWORD to a unique password. Generate a
signing secret and paste the output into JWT_SECRET in .env:
node -e "console.log(require('crypto').randomBytes(48).toString('base64url'))"Keep .env private. The app and database CLI commands automatically load .env from the current
working directory, through config.ts; existing process variables take precedence.
The example placeholders are not usable deployment credentials.
Point DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, and DB_NAME at an empty application database
on a reachable PostgreSQL instance, then run:
npm ci
npm run migration:runCreate the first administrator using the host instructions below, then start watch mode:
npm run start:devFor a compiled host run use npm run build followed by npm run start:prod. The default API URL
is http://localhost:3000/v1/api. The Compose database is private to its container network;
host development needs a separate database or an explicitly published development port.
In PowerShell 7.1+, read a password without putting it in command history:
$env:BOOTSTRAP_USERNAME = 'admin@example.com'
$env:BOOTSTRAP_FULLNAME = 'Shop Administrator'
$env:BOOTSTRAP_PASSWORD = Read-Host 'New admin password (12+ characters)' -MaskInput
try {
npm run admin:bootstrap
} finally {
Remove-Item Env:BOOTSTRAP_USERNAME, Env:BOOTSTRAP_FULLNAME, Env:BOOTSTRAP_PASSWORD
}In Bash:
export BOOTSTRAP_USERNAME='admin@example.com'
export BOOTSTRAP_FULLNAME='Shop Administrator'
read -r -s -p 'New admin password (12+ characters): ' BOOTSTRAP_PASSWORD; echo
export BOOTSTRAP_PASSWORD
npm run admin:bootstrap
unset BOOTSTRAP_USERNAME BOOTSTRAP_FULLNAME BOOTSTRAP_PASSWORDPasswords require at least 12 characters, at most 72 UTF-8 bytes, and no NUL character. There is no public signup or default account. Bootstrap refuses to run once an active admin exists and does not reset an existing account. Create subsequent users through the authenticated admin API.
With .env configured:
docker compose up --build -dThe startup sequence is:
PostgreSQL healthy → both schema migrations applied → backend API starts
| Service | Purpose |
|---|---|
postgres |
PostgreSQL 17; persistent postgres_data volume; no published host database port |
migrate |
One-shot execution of compiled migrations |
backendapi |
API published at 127.0.0.1:3000 on the host |
k6 |
Optional authenticated load runner under the load profile |
Compose overrides database host/port to postgres:5432 and sets the API container's PORT=3000
to match its published port and readiness probe. The multi-stage Docker image installs the
lockfile, compiles TypeScript, removes development dependencies, and runs as the non-root node user.
After the stack starts, open a disposable shell using the API service's configuration:
docker compose run --rm -it backendapi shRun inside that shell:
export BOOTSTRAP_USERNAME=admin@example.com
export BOOTSTRAP_FULLNAME='Shop Administrator'
read -s -p 'New admin password (12+ characters): ' BOOTSTRAP_PASSWORD; echo
export BOOTSTRAP_PASSWORD
node dist/database/bootstrap-admin.js
unset BOOTSTRAP_PASSWORD BOOTSTRAP_USERNAME BOOTSTRAP_FULLNAME
exitLog in with that account to create staff users and shop records. No customer or catalog seed data is loaded automatically. Useful stack commands:
docker compose ps
docker compose logs --tail=100 backendapi migrate
docker compose downdown stops the stack while retaining its named database volume.
| Variable | Required? | Default / example | Purpose |
|---|---|---|---|
DB_HOST |
Yes | None | PostgreSQL host; Compose uses postgres |
DB_PORT |
No | 5432 |
PostgreSQL port |
DB_USER |
Yes | None | Database username |
DB_PASSWORD |
Yes | None | Database password |
DB_NAME |
Yes | None | Application database |
DB_SSL |
No | Disabled | Set exactly true for certificate-verified database TLS |
PORT |
No | 3000 |
Host HTTP port; Compose forces the container port to 3000 |
JWT_SECRET |
Yes for API | Generated base64url value | Canonical encoding of at least 32 random bytes; never a human-chosen password |
JWT_ISSUER |
Yes for API | backend-nest-p6-1a in template |
Exact issuer used when signing and verifying |
JWT_AUDIENCE |
Yes for API | shop-api in template |
Exact intended API audience |
CORS_ORIGINS |
No | http://localhost:5173 in template |
Comma-separated exact HTTP(S) browser origins; omit for no cross-origin access |
BOOTSTRAP_USERNAME |
Bootstrap only | Your admin email | Normalized first-admin username |
BOOTSTRAP_FULLNAME |
Bootstrap only | Your admin name | First-admin display name |
BOOTSTRAP_PASSWORD |
Bootstrap only | Hidden prompt / secret manager | First-admin password; remove after setup |
ACCESS_TOKEN |
k6 only | Fresh reader access token | Authorization for optional load smoke test |
Required values and valid ports are checked during initialization. Signing secrets must be canonical unpadded base64url; generate them with the command above. JWT issuer, audience, and secret must agree across replicas. Database migration/cleanup/bootstrap CLIs need the database settings; they do not issue or verify JWTs.
CORS origins must omit paths, trailing slashes, credentials, and wildcards. Allowed request
headers include Authorization, Content-Type, and Idempotency-Key. Authentication uses Bearer
headers and refresh request bodies, with no authentication cookies. CORS does not grant API access.
| Identity | Allowed operations |
|---|---|
| Anonymous | Health checks; attempt login or refresh with the required credentials |
| Reader | Read shop records; own profile; own password change and logout operations |
| Writer | Reader capabilities plus create, update and delete shop records |
| Admin | Writer capabilities plus user management and counts |
New users default to reader. User-management routes and counts are admin-only. GET /users/me
is available to every authenticated role. A transaction protects the last active admin from
deactivation or demotion. User deletion is not exposed; use active: false to disable an account.
- Access JWTs expire after 300 seconds; sessions expire seven days after login, regardless of refresh activity.
- JWT verification pins HS256, validates issuer/audience/purpose and UUID identifiers, and requires valid issuance/expiry claims with no lifetime above five minutes.
- Refresh tokens contain 48 random bytes; only SHA-256 hashes are stored. They are single-use and rotate atomically.
- Logout revokes the current session; logout-all revokes every session for the caller. Both invalidate corresponding access and refresh tokens on subsequent requests.
- Password, username, role, or active-status changes through the admin API revoke all affected sessions in the same transaction. Self-service password change requires the current password and also revokes all devices.
- Passwords are hashed with bcrypt cost 12 on creation and update. They are excluded from normal selects, serialization, and token/profile responses. Usernames are trimmed and lowercased before validation and uniqueness checks.
- Generic credential failures and a dummy hash comparison for unknown users reduce username-disclosure signals. Login attempts are still rate limited.
The default source-IP limiter is 120 requests/minute per route per process. Login allows 10/minute, refresh 30/minute, and self-service password changes 5/minute. PostgreSQL separately limits a normalized account to ten login attempts within a 15-minute window; a successful login clears that account's counter. After the limit, wait for the remaining cooldown. These limits do not replace a shared ingress limiter when running multiple instances.
See SECURITY.md for browser storage, key rotation, proxy boundaries, and operational requirements.
All routes below are relative to /v1/api. Protected calls send
Authorization: Bearer ACCESS_TOKEN. The old p6 x-api-key mechanism is no longer accepted.
| Method | Route | Permission and result |
|---|---|---|
GET |
/health/live, /health/ready |
Public process/database checks |
POST |
/auth/login |
Username/password; 200 with tokens and public profile |
POST |
/auth/refresh |
Opaque refresh token; 200 with replacement token pair |
POST |
/auth/logout |
Any authenticated role; current session revoked; 204 |
POST |
/auth/logout-all |
Any authenticated role; all own sessions revoked; 204 |
POST |
/auth/password |
Any role, current/new password; all own sessions revoked; 204 |
GET |
/users/me |
Any role; own public profile |
POST |
/users |
Admin; create staff user; 201 |
GET |
/users, /users/:id |
Admin; bounded list or public user profile |
PATCH |
/users/:id |
Admin; update profile/password/role/activation |
GET |
/auth/counts |
Admin; numeric usercount, productcount, customercount, ordercount |
POST http://localhost:3000/v1/api/auth/login
Content-Type: application/json
{ "username": "admin@example.com", "password": "YOUR_ADMIN_PASSWORD" }The response includes access_token, refresh_token, token_type: "Bearer", expires_in: 300,
refresh_expires_at, fullname, and a safe user object. Store tokens according to your client's
security model and replace both after refresh:
POST http://localhost:3000/v1/api/auth/refresh
Content-Type: application/json
{ "refresh_token": "CURRENT_REFRESH_TOKEN" }Use /auth/logout with the current access token to end this session. After access-token expiry,
use a still-valid refresh token to obtain a current access token before calling protected routes.
POST http://localhost:3000/v1/api/users
Authorization: Bearer ADMIN_ACCESS_TOKEN
Content-Type: application/json
{
"fullname": "Catalog Staff",
"username": "writer@example.com",
"password": "REPLACE_WITH_A_UNIQUE_PASSWORD",
"role": "writer",
"updateinmail": false
}Create requires fullname, email username, and password. Optional role is reader, writer,
or admin; updateinmail is a stored preference, not an implemented email-subscription service.
Admin PATCH accepts these fields plus boolean active; empty updates and explicit nulls are rejected.
For self-service password change:
POST http://localhost:3000/v1/api/auth/password
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
{ "currentPassword": "CURRENT_PASSWORD", "newPassword": "NEW_UNIQUE_PASSWORD" }After its 204 response, log in again on every device.
| Method | Route | Purpose / permission |
|---|---|---|
GET |
/customers, /products, /orders |
Paginated reads; reader/writer/admin |
GET |
/customers/:id, /products/:id, /orders/:id |
Individual reads; reader/writer/admin |
POST |
/customers, /products, /orders |
Create; writer/admin |
PATCH |
/customers/:id, /products/:id, /orders/:id |
Update; writer/admin |
DELETE |
/customers/:id, /products/:id, /orders/:id |
Delete or eligible order soft deletion; writer/admin |
Use a writer or admin access token:
POST http://localhost:3000/v1/api/customers
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
{
"customerName": "Example Customer",
"cemail": "customer@example.com",
"phone": "+923001234567",
"address": "1 Example Street",
"city": "Karachi",
"postalCode": "74000",
"country": "PK"
}POST http://localhost:3000/v1/api/products
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
{
"productName": "Wireless Headphones",
"productvendor": "Example Vendor",
"productDescription": "Example catalog item",
"quantityInStock": 10,
"buyPrice": 10000,
"msrp": 15000
}Keep the generated customerId and productId. Field names such as cemail and productvendor
match the current DTOs. Sending fractional prices, unknown fields, or invalid identifiers is rejected.
POST http://localhost:3000/v1/api/orders
Authorization: Bearer ACCESS_TOKEN
Idempotency-Key: example-order-001
Content-Type: application/json
{
"customerId": "CUSTOMER_UUID",
"comments": "Example order",
"orderItems": [{ "productId": "PRODUCT_UUID", "quantity": 2 }]
}Replace ID placeholders with real UUID v4 values. With the example product, the server calculates
total: 30000 and reserves two units. An identical retry with the same key returns that order
without reserving stock again. Use a new key for a new order. An optional shippingDate is allowed.
PATCH http://localhost:3000/v1/api/orders/ORDER_UUID
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
{ "comments": "Updated delivery instructions" }Omitting orderItems leaves items unchanged; supplying it replaces the complete list of 1–100
distinct products using product IDs and quantities. Item IDs, client prices, and client totals are
rejected. After external payment confirmation a writer/admin can submit
{"paid": true, "status": "shipped"}. After any required external refund, cancel with
{"paid": false, "status": "cancelled"}. Do not replace items in the same cancellation patch.
GET http://localhost:3000/v1/api/products?offset=0&limit=20
Authorization: Bearer ACCESS_TOKENCustomer/product/order lists return { "items": [...], "total": 42, "offset": 0, "limit": 20 }
in a stable order. Limit is 1–100 (default 20); offset is 0–100,000. Order lists omit items;
individual order reads include them. The admin /users list uses the same pagination bounds but
returns a plain array of safe profiles. Counts return a JSON object with numbers, not a
JSON-encoded string. Clients must not apply an extra JSON.parse to counts.
See rest-client.http and test-data.txt for editable examples.
npm run lint
npm run typecheck
npm run build
npm test -- --runInBand
npm audit --omit=dev| Command | Purpose |
|---|---|
npm run start:dev |
Watch-mode development |
npm run build / npm run start:prod |
Compile / run compiled API |
npm run format / npm run lint:fix |
Apply source formatting / lint fixes |
npm run test:watch / npm run test:cov |
Unit watch mode / coverage |
npm run test:e2e |
Serial PostgreSQL integration suites |
npm run check |
Lint, types, build, units, then database integration |
npm run migration:run |
Apply registered migrations |
npm run admin:bootstrap |
Create the first administrator |
npm run auth:cleanup |
Remove absolutely expired sessions and stale login counters |
Use a disposable database whose name ends in _test. Suites run migrations and truncate
shop and auth tables. Never point them at application data. One local option is:
docker run --rm --name p6-1a-tests -d -e POSTGRES_USER=app -e POSTGRES_PASSWORD=integration-only -e POSTGRES_DB=shop_p6_1a_test -p 127.0.0.1:55461:5432 postgres:17-alpineWait for docker exec p6-1a-tests pg_isready -U app -d shop_p6_1a_test to succeed. Then set host
connection variables in PowerShell:
$env:DB_HOST = '127.0.0.1'
$env:DB_PORT = '55461'
$env:DB_USER = 'app'
$env:DB_PASSWORD = 'integration-only'
$env:DB_NAME = 'shop_p6_1a_test'
npm run test:e2eUse a dedicated terminal for these overrides, or clear them before running the application again.
An alternative is an ignored .env.test.local containing those connection settings:
node --env-file=.env.test.local ./node_modules/jest/bin/jest.js --config ./test/jest-e2e.json --runInBandSuites generate their own JWT secrets and test users. They run serially because they share and
reset the database. docker stop p6-1a-tests stops the temporary --rm container. Its anonymous
database storage is disposable; do not reuse it for application data.
PowerShell 7 can verify the complete production image in isolated temporary containers:
pwsh -File test/verify-runtime.ps1The script builds the image, applies migrations, creates the first admin, confirms bootstrap rerun
refusal, checks roles and a customer/product/order/token workflow, verifies stock and revocation,
confirms non-root execution and absence of Nest CLI, and runs auth cleanup. It generates credentials
in memory, publishes no ports, and stops its containers. Use -SkipBuild only for an image that
already contains the current source.
For a running Compose stack, put a fresh reader access token in the terminal's ACCESS_TOKEN
environment variable, then run:
docker compose --profile load run --rm k6The script uses one virtual user for three minutes against the customer list. Its thresholds are
less than 1% HTTP failures, p95 duration below 200 ms, and more than 99% passing checks. These are
test thresholds, not a service-level guarantee. Start immediately after login so the five-minute
JWT remains valid throughout the run, then clear ACCESS_TOKEN from the environment.
On 7 November 2026, verification recorded 29 passing unit tests and 41 passing PostgreSQL integration tests: 33 auth/security cases plus eight shop regression cases. Lint, strict types, build, Compose validation, and the production Docker workflow passed. After relocation into this repository, source equality and a fresh install, lint, types, build and all 29 units were checked again.
Auth cases include malformed/tampered/expired JWTs, claim types and binding, permissions, password exclusion and changes, rotation/replay/concurrent refresh, absolute expiry, logout, deactivation, last-admin protection, cooldown, IP throttling and CORS. Shop cases cover idempotent retries, rollback, partial updates, cancellation, history, payment restrictions and overselling prevention.
The CI workflow provisions PostgreSQL and runs the production audit, lint, types, build, units and integration tests. See the dated verification record for the evidence and audit limits; these results do not claim a new audit on every README update.
TypeORM synchronize and automatic application-start migrations are disabled. Registered migrations
are InitialSchema for shop tables and
Authentication for users, sessions,
refresh hashes and attempt counters. Compose runs them before starting the API.
- Fresh database: apply both migrations, then bootstrap an admin.
- Already migrated improved-p6 database: apply the additive auth migration through the existing migration ledger.
- Legacy p6/p6_1 synchronized database: plan a reviewed migration into a new database; the current migrations do not automatically import or baseline old tables.
For legacy data, verify a restorable backup, reconcile floating-point prices into integer minor units, agree timestamp assumptions, reconstruct historical prices only from reliable records, reconcile payment/stock balances, and assign unique retry keys. Normalize/deduplicate usernames, inspect password hashes and explicitly assign staff roles. Validate totals, references and inventory before cutover. Old JWTs do not belong to the new session model and require login again.
For new changes, write and review a migration, register it in
databaseOptions().migrations, and apply it once before deploying
replicas. Destructive rollback is deliberately disabled; migration:revert will refuse it. Use a
reviewed forward migration or a verified backup restore. Do not delete old volumes or enable
synchronization to bypass schema conflicts.
See CHANGES.md for client and data compatibility differences.
- Transport and secrets — Use HTTPS at ingress, verified TLS for remote PostgreSQL, least-privilege database access, and deployment-managed secrets. Keep issuer/audience/key configuration consistent across instances.
- Browser clients — Tokens are returned in JSON; no persistent browser-cookie flow is implemented. For persistent browser login, use a backend-for-frontend with Secure/HttpOnly/SameSite cookies and appropriate CSRF controls. Do not store credentials/tokens in URLs or browser localStorage/sessionStorage. In-memory tokens end with page reload.
- Rate limits and proxies — Per-IP counters are process-local; enforce shared ingress limits when scaling. Account counters and session revocation already use PostgreSQL. Proxy trust is disabled; configure it only for known proxy boundaries. Account cooldown can temporarily deny login to a targeted user.
- Input protection — Helmet headers, a 128 KiB uncompressed JSON limit, runtime validation, unknown-field rejection, and UUID route validation are enabled.
- Observability — Completion logs include generated request ID, method, path, status and duration; bodies, credentials and query strings are omitted. Export stdout and alert on repeated failures, latency and readiness problems. Full actor-level audit trails are not implemented.
- Database capacity — Each pool has at most 10 connections, a 5-second connection timeout, 10-second lock timeout and 15-second statement timeout. Size connection totals across replicas and exercise backup restoration.
- Health and shutdown —
/v1/api/health/livechecks liveness;/v1/api/health/readychecks database connectivity. Shutdown hooks are enabled. Readiness is not a schema-drift check. Database outages do not allow offline JWT bypass. - Session cleanup — Schedule
npm run auth:cleanupdaily on a configured host, ordocker compose run --rm backendapi node dist/database/cleanup-auth.js. No scheduler is installed automatically. Consumed refresh hashes must remain until absolute session expiry for replay detection. - Key rotation — A new signing key rejects old access JWTs. Existing valid opaque refresh sessions can obtain access JWTs signed with the new key. If invalidating all logins is required, revoke all sessions as well; automated multi-key rollover is not implemented.
- Current scope — One application currency and manually confirmed payments. MFA, email verification/reset, external identity providers, customer ownership, tenant isolation, payment settlement/refunds, taxes, discounts and automated marketing email need additional implementation.
At the 7 November 2026 verification, npm audit --omit=dev reported zero known production
vulnerabilities. The full audit reported nine low-severity development-tool findings through
deepmerge in Jest/Nest CLI tooling. Development tools are excluded from the runtime image.
Recheck the audit when updating or deploying; the recorded result is not an ongoing security guarantee.
Further design details are in SECURITY.md.
| Status / symptom | Meaning | What to check |
|---|---|---|
400 Bad Request |
Invalid DTO, UUID, pagination, idempotency key, or token-body format | Field names/types, unknown fields, nulls, byte limits and required headers |
401 Unauthorized |
Invalid credentials, JWT, refresh token, user or session | Bearer header, issuer/audience/key, expiry, active user, and whether the session was revoked |
403 Forbidden |
Authenticated role lacks permission | Reader versus writer access; admin required for users/counts |
404 Not Found |
Missing resource or soft-deleted order | Correct UUID and lifecycle |
409 Conflict |
Stock, state, retry-key, uniqueness, reference, concurrency, or last-admin conflict | Resolve the specific business conflict before retrying |
413 Payload Too Large |
JSON exceeds the limit | Keep the uncompressed body below 128 KiB |
415 Unsupported Media Type |
Compressed JSON rejected | Send uncompressed JSON |
429 Too Many Requests |
Source-IP/route limit or account cooldown | Reduce requests; wait for the account window when login is blocked |
500 Internal Server Error |
Unexpected application/database failure | Server logs and database availability |
503 on readiness |
Database connectivity failed | Host, port, credentials, database health and network |
| Startup configuration error | Missing variable, invalid port/key/origin | Run in the repository directory; check .env, process overrides, generated base64url key and exact origins |
| Browser CORS failure | Origin/header not allowed | Exact scheme/host/port in CORS_ORIGINS; omit trailing slash and restart after config changes |
| Refresh succeeds once, then all tokens fail | Old refresh token replay revoked its family | Serialize refreshes, atomically replace both tokens, then log in again |
| Bootstrap exits with failure | Config/validation/schema issue or an active admin already exists | Run migrations, meet password rules, or use an existing admin to manage users |
| Migration reports existing tables | Legacy schema was not migrated/baselined | Follow a reviewed data-upgrade plan |
| Host cannot reach Compose PostgreSQL | No database host port is published | Use a separate host-development database or deliberate development-only port mapping |
Database exceptions return safe messages rather than raw SQL or driver details. Validation, HTTP and database errors can have different response shapes; there is no universal error-code envelope.
Burhan Saadi — Architecture & Development
Created for the Stevaso Tech TypeScript End-to-End series, Parts 6 and 6.1, covering REST APIs, NestJS modules, TypeORM, PostgreSQL, staff accounts and JWT access. The current p6_1a implementation builds on improved p6 transactions, validation, concurrency, money and order lifecycle behavior, then completes authentication, refresh, revocation and account authorization in this same repository.
Existing clients must adopt the current contracts: individual Bearer credentials, admin-managed accounts, paginated shop lists, UUIDs, integer money, server-owned order fields, idempotency headers, controlled state transitions, refresh rotation and numeric JSON counts. See CHANGES.md for the compatibility guide.
Copyright (c) 2024 Burhan Saadi. Licensed under the MIT License.
You may use, modify, distribute, sublicense, and sell copies provided the copyright and permission notices are included. The software is provided "as is", without warranty. Dependency licenses remain their respective authors' terms.