Vector
Serialized hardware inventory for engineering fleets. Track every part from receiving → bin → host → repair → destruction, with a complete per-part audit trail, field-maintenance ticketing, per-technician custody, and manufacturer EOL visibility.
Vector is a pnpm + Turborepo monorepo written in strict TypeScript end to end: an Express/Prisma API, a React/Vite web client, shared zod contracts, and a shadcn/ui design system.
What it does
Inventory
- Serialized
Parts live underSite → Room → Binlocations or on aHost. - Every state change writes a
PartEventin the same transaction — nothing mutates silently. PartModels are grouped byManufacturerandCategory, with optional EOL dates that feed dashboard risk widgets.Tags andSavedViews for cross-cutting organization and reusable filters.
Field workflow
FMtickets track active issues per host, with attached repairs and close times.Repairlogs pair a broken serial with its replacement and auto-ingest parts from a tech's input when the broken serial isn't yet in Vector.- Per-technician custody tracks parts held for repair, pending drop-off, or pending destruction — so broken or pre-staged parts never go missing between events.
Operations dashboard
- Universal KPIs: total parts, total spent, deployed value, open FMs, past-EOL deployments, upcoming-EOL deployments (≤180 d).
- Admin-only: 7/30-day repair tempo, FMs opened, average FM close time, repairs trend chart, open-FMs-by-host, and a custody backlog by user.
Integrations
- Outbound webhooks signed with
HMAC-SHA256(timestamp + "." + body), headersx-vector-signature,x-vector-timestamp,x-vector-event, plus ax-vector-webhook: v1recursion guard. - Streaming CSV export of the audit log for admins.
Architecture
vector/
├── apps/
│ ├── api/ Express 5 + Prisma + zod. controllers → services → tx.
│ ├── web/ React 19 + Vite + TanStack Query/Table + shadcn/ui.
│ └── e2e/ Playwright smoke tests (login, parts, repairs, admin).
├── packages/
│ ├── db/ Prisma schema, migrations, seed, singleton client.
│ ├── shared/ zod schemas + DTOs — the source of truth for the API.
│ ├── ui/ shadcn primitives + Vector design tokens.
│ └── config/ Shared tsconfig + Tailwind tokens.
├── .gitea/workflows/build.yml tests on every PR; images for every merge to main.
├── .gitea/workflows/release.yml a vX.Y.Z tag publishes main's images as vX.Y.Z.
├── docker-compose.yml db (PostgreSQL) + api + web, for a single host.
└── turbo.json dev · build · test · typecheck · lint.
The API is strict about its boundaries. Every service takes (tx, input, actor)
so controllers can compose multiple services inside a single
prisma.$transaction — part mutations and their audit rows are always atomic
or not at all. Controllers do no validation and no business logic; they parse
through a zod schema and dispatch.
Tech stack
| Layer | Choice |
|---|---|
| Language | TypeScript strict mode across every workspace |
| API | Express 5, Prisma 5, zod, JWT + refresh-token rotation, CSRF, helmet |
| Web | React 19, Vite, TanStack Query, TanStack Table, react-hook-form, nuqs |
| UI | shadcn/ui on Radix primitives, Tailwind v4, Sonner toasts, Recharts |
| Database | PostgreSQL 16 (CloudNativePG in TWS's cluster) |
| Observability | pino (JSON in prod, pretty in dev) with per-request requestId; Prometheus metrics |
| Testing | Vitest (unit, and API tests on a real PostgreSQL), Playwright (E2E) |
| Monorepo | pnpm workspaces + Turborepo |
| CI / deps | Gitea Actions + self-hosted Renovate |
Writes that read a part, check it and change it (repairs, custody moves, part
updates) lock the part's row (SELECT … FOR UPDATE, services/locks.ts), so
two concurrent requests can't both take the same spare.
Quick start
Prerequisites: Node 20+, pnpm 10+ (corepack enable), and PostgreSQL 16
(Docker is the easy way):
docker run -d --name vector-pg -p 5432:5432 \
-e POSTGRES_USER=vector -e POSTGRES_PASSWORD=vector -e POSTGRES_DB=vector \
postgres:16-alpine
pnpm install
cp apps/api/.env.example apps/api/.env # DATABASE_URL already points at the container above
node -e "console.log(require('crypto').randomBytes(48).toString('hex'))" # paste as JWT_SECRET
export DATABASE_URL=postgresql://vector:vector@localhost:5432/vector
pnpm -C packages/db exec prisma migrate dev
pnpm -C packages/db run db:seed # development data: admin/admin and part categories
pnpm dev
- API: http://localhost:3001
- Web: http://localhost:5173 (proxies
/api→ API) - Development credentials:
admin/admin(fromdb:seed, which refuses to run withNODE_ENV=production).
In development the workspace packages (@vector/shared, @vector/db) are used from
source through the development export condition (Vite and Vitest set it; pnpm dev
runs the API with tsx --conditions=development). Plain Node, as in the images, uses
their compiled dist/.
Deployment
TWS runs Vector on Kubernetes (see How changes reach production).
To run a build anywhere else, docker-compose.yml starts PostgreSQL, the API and the
web app from the published images:
# 1. authenticate to the registry
docker login gitea.thewrightserver.net
# 2. create a .env next to docker-compose.yml with at minimum:
# TAG=v1.0.0 # a release; there is no "latest"
# POSTGRES_PASSWORD=<random>
# JWT_SECRET=<64-char hex>
# SEED_ADMIN_PASSWORD=<12+ chars> # the first admin on an empty database
# CLIENT_ORIGIN=https://vector.example.com
# WEB_PORT=8080
# COOKIE_SECURE=true # required once you're behind TLS
docker compose pull && docker compose up -d
Images
| Image | Listens on | Runs as | Notes |
|---|---|---|---|
gitea.thewrightserver.net/josh/vector-api |
3001 (API); 9464 (/metrics, with METRICS_PORT=9464) |
node (uid 1000) |
start.sh: prisma migrate deploy, the optional first-admin seed, then exec node (PID 1) |
gitea.thewrightserver.net/josh/vector-web |
8080 | nginx (uid 101) |
the static app; proxies /api/, /healthz and /readyz to API_UPSTREAM (default http://api:3001) |
API configuration
| Variable | Required | Meaning |
|---|---|---|
DATABASE_URL |
yes | postgresql://… |
JWT_SECRET |
yes | at least 32 random characters, one per environment; placeholders and non-random values are refused at start |
NODE_ENV |
production in the image |
|
PORT |
default 3001 | |
CLIENT_ORIGIN |
the web app's origin (CORS), default http://localhost:5173 |
|
COOKIE_SECURE |
true behind TLS, false over plain HTTP (browsers drop Secure cookies there); default true in production |
|
TRUST_PROXY |
proxies in front of the API to trust for the client address and protocol; default 1 (the web container) | |
METRICS_PORT |
serve Prometheus /metrics on this port; off when unset |
|
SHUTDOWN_DELAY_MS |
after SIGTERM, how long /readyz answers 503 before the server stops accepting; default 0 |
|
APP_VERSION |
the deployed image tag, reported by /api/version (Kargo sets it per stage) |
|
BUILD_COMMIT |
baked into the image by CI | |
SEED_ADMIN |
false: never seed an admin (accounts come from the bootstrap script) |
|
SEED_ADMIN_USERNAME, SEED_ADMIN_EMAIL, SEED_ADMIN_PASSWORD |
the first admin on an empty database; in production the password is required (no default) | |
TICKETING_URL |
TicketingSystem's origin (a URL). A repair's ticket reference (V + nine digits) links to ${TICKETING_URL}/<ref>, served to the web app by GET /api/config; without it the reference is plain text |
|
LOG_LEVEL |
pino level; default info in production |
Health, version and metrics
GET /healthz: liveness,{"status":"ok"}while the process answers (no database check).GET /readyz: readiness, 200 when the database answers; 503 when it doesn't or the process is shutting down.GET /api/config:{"ticketingUrl": TICKETING_URL or null}, without signing in. The web app reads it once per page load.GET /api/version:{"version": APP_VERSION, "commit": BUILD_COMMIT}(unknownwhen unset), without signing in. The web app shows it as the last line of the user menu.GET /metricsonMETRICS_PORT:vector_build_info{version,commit} 1,vector_http_requests_total{method,route,status},vector_http_request_duration_seconds{method,route}(buckets 0.01–5 s) and the default process metrics, all prefixedvector_.
On SIGTERM the API marks itself not ready, waits SHUTDOWN_DELAY_MS, stops accepting
connections, finishes in-flight requests, disconnects from the database and exits 0.
Accounts (bootstrap script)
dist/scripts/bootstrap.js in the API image creates or updates one account. The password
comes from a file or standard input (its first line, at least 12 characters), never from
the command line:
kubectl -n vector-dev exec -i deploy/api -- \
node dist/scripts/bootstrap.js --username goddard --role ADMIN --password-stdin < goddard.password
# or --password-file <path inside the container>; optional --email goddard@example.com
It is idempotent: a missing account is created; an existing one gets the given role, email
and password, and nothing is written when they already match. A changed password revokes
the account's refresh tokens. The last line on stdout is
BOOTSTRAP {"username":"goddard","role":"ADMIN","status":"created|updated|unchanged","changed":[…]};
an error exits 1 with the reason on stderr. The password is never printed.
API keys (automation)
Automation (n8n, scripts) authenticates with an API key instead of a password: no cookie, no
CSRF token, no refresh token. Send it in the X-Api-Key header:
curl -H "X-Api-Key: $VECTOR_API_KEY" "$base/api/parts?pageSize=1"
- Creating one: My API keys in the web app (
/account/api-keys: any account, for itself), or Admin › API keys (/admin/api-keys: an admin, for any account). The API isPOST /api/api-keyswith{"name","scope"}, orPOST /api/admin/api-keyswith{"name","scope","userId"}, from a signed-in session (a key can't create, list or revoke keys). The response carries the key, once; it is never shown again. - What it can do: it acts as its owner, and the owner's current role is the ceiling (read
from the database on every request, so a demoted owner's key loses admin rights at once). The
scope narrows it further:
READallowsGETandHEADonly (anything else answers 403);WRITEallows whatever the owner's role allows. Changes made with a key are recorded as the owner's. - Refused with 401: a malformed or unknown key, a revoked key, a key whose owner was deleted. A request with an invalid key is refused even if it also carries a valid session cookie.
- Cookie and key together: the key decides (identity, role, scope) and CSRF isn't required, as for any key request; the cookie is ignored. A browser never sends this header by itself, so there is nothing for another site to forge. Cookie sessions always need the CSRF token.
- Storage: a key is
vk_plus 32 random bytes in hex. Only its SHA-256 hash and a display prefix (vk_plus 8 characters) are stored; lists show the prefix, never the key or the hash. The key is redacted from the request logs.lastUsedAtis written at most once a minute per key. - Revoking:
DELETE /api/api-keys/<id>(your own) orDELETE /api/admin/api-keys/<id>(admin); the next request with the key answers 401. Revoked keys are kept for the record.
Smoke test
An automated check signs in as a service account (cookie + CSRF), works on rows with a fixed
identity and cleans up, so repeated runs leave nothing behind. With $base the web service
(through nginx, like a browser) and $stage dev or staging:
GET $base/readyzuntil it answers 200.- Sign in:
POST $base/api/auth/loginwith the JSON body{"username":"…","password":"…"}. Keep the cookies (curl -c jar, then-b jar -c jar); the CSRF token is the value of thecsrfcookie. Every laterPOST,PATCHorDELETEsends the cookies and the headerX-CSRF-Token: <csrf>. - Remove a leftover from a run that stopped half-way:
GET $base/api/parts?serialNumber=SMOKE-KARGO-$stage&pageSize=1; if the body starts with{"data":[{"id":"<id>",DELETE $base/api/parts/<id>(204). - The manufacturer, created once and reused:
GET $base/api/manufacturers?name=Kargo%20smoke(an exact match); ifdatais empty,POST $base/api/manufacturerswith{"name":"Kargo smoke"}(201, body starts with{"id":"<id>"). - Create the part:
POST $base/api/partswith{"serialNumber":"SMOKE-KARGO-<stage>","manufacturerId":"<id>","mpn":"KARGO-SMOKE","notes":"Kargo smoke test"}(201; the part modelKARGO-SMOKEis created on first use; the body starts with{"id":"<part id>"). - Read it back:
GET $base/api/parts/<part id>contains"serialNumber":"SMOKE-KARGO-<stage>". - A custody move:
POST $base/api/custody/<part id>/take-for-repairanswers with"state":"PENDING_REPAIR", andGET $base/api/parts/<part id>/eventscontains"type":"STATE_CHANGED". - Clean up:
DELETE $base/api/parts/<part id>(204; its events go with it), thenGET $base/api/parts/<part id>answers 404. Sign out:POST $base/api/auth/logout.
What stays between runs: one manufacturer and one part model (fixed names) and one revoked
refresh-token row per sign-in. The account needs the ADMIN role (creating manufacturers and
parts and deleting parts are admin-only). apps/api/src/test/api.db.test.ts runs this
sequence twice, and after a half-finished run.
Read-only variant (prod): sign in as above, then GET $base/api/auth/me (the account's
username), GET $base/api/parts?pageSize=1 (200, body starts with {"data":[; an empty page
is fine), GET $base/api/analytics/dashboard (200), the same parts request without cookies
(401), and POST $base/api/auth/logout. It writes no inventory data (signing in records a
refresh token).
Development commands
All commands run at the workspace root; Turbo fans them out with caching.
| Command | Does |
|---|---|
pnpm dev |
API + web concurrently |
pnpm build |
Build every package and app |
pnpm typecheck |
tsc --noEmit across the graph |
pnpm lint |
ESLint across the graph |
pnpm test |
Vitest across packages that define it |
pnpm -C apps/api test:coverage |
Services/lib coverage report (no threshold gate yet) |
pnpm -C apps/e2e test |
Playwright, against a live stack (see below) |
pnpm -C packages/db run db:studio |
Prisma Studio |
pnpm -C packages/db run db:reset |
Drop schema, migrate, seed |
Testing
Unit tests live next to the code they cover (*.test.ts). The API covers
services, lib/ helpers, and the analytics aggregator (tested with an
in-memory Tx double). Shared covers every zod contract.
Database tests (apps/api/src/**/*.db.test.ts) run against a real PostgreSQL:
the HTTP layer with sign-in and CSRF, API keys (scopes, roles, revocation, logs), the smoke
sequence, the account scripts, and concurrent repairs and custody moves (exactly one of two conflicting requests wins).
test:db resets the database first, so never point it at real data:
DATABASE_URL=postgresql://vector:vector@localhost:5432/vector_test pnpm -C apps/api test:db
End-to-end tests in apps/e2e/ run Playwright against a live stack and
skip themselves unless TEST_USERNAME and TEST_PASSWORD are set:
pnpm dev # terminal 1
TEST_USERNAME=admin TEST_PASSWORD=admin \
pnpm -C apps/e2e exec playwright install --with-deps chromium
TEST_USERNAME=admin TEST_PASSWORD=admin \
pnpm -C apps/e2e test
Reports land in apps/e2e/playwright-report/.
Continuous integration
.gitea/workflows/build.yml runs on every pull request and every push to main
(docs-only pushes excepted), in plain node:22-bookworm containers:
- Lint: ESLint for the API and the web app.
- Test (typecheck, unit, build):
pnpm typecheck, the shared and API unit tests,pnpm build. - Test (API, PostgreSQL): against a
postgres:16service, checks that the migrations produce exactlyschema.prisma(prisma migrate diff --exit-code), then runstest:db. - Dependency audit, report only.
On main only, once those pass, it builds and pushes vector-api and vector-web tagged
main-<commit time UTC>-<short commit> and the full commit. release.yml publishes a
vX.Y.Z tag. The registry comes from the repository variable REGISTRY and the secret
REGISTRY_TOKEN. The Playwright suite is not in CI yet (#20).
Dependency updates come from self-hosted Renovate — grouped minor/patch PRs
weekly, auto-merge for dev-dep patches, prisma + @prisma/client grouped
together, Radix/shadcn held for manual review.
How changes reach production
TWS runs Vector on its Kubernetes cluster, deployed by Argo CD from josh/tws-k8s and moved between stages by Kargo. An image is built once, in CI, and the same image moves from stage to stage.
| Stage | Runs | How an image gets there |
|---|---|---|
dev |
the newest main |
automatically, minutes after a merge (Kargo Warehouse vector-dev) |
staging |
the newest release, vX.Y.Z |
automatically when a release tag is pushed (Warehouse vector-release) |
prod |
a release that passed staging | a deploy ticket, approved by josh, then a manual promotion in Kargo |
- Merging: squash merges only (one PR = one commit = one image), branches deleted after merge,
mainprotected by the test jobs. CI (.gitea/workflows/build.yml) runs the tests on every PR and buildsmain-<commit time>-<commit>plus the full commit for every merge tomain; docs-only changes build nothing. There is nolatest. - Releasing: when what's in
devis ready, create a release in Gitea (Releases → New release) with a tagvX.Y.Zon thatmaincommit..gitea/workflows/release.ymladdsvX.Y.Zto the imagesdevalready ran (same digests; it only builds if that commit has none), and Kargo takes it tostaging. Only strictvX.Y.Ztags count: no pre-releases. The first release isv1.0.0. - Verification after each promotion is Kargo's, in the stage itself: the API answers
/healthzand/readyz,/api/versionreports the promoted tag on every replica, the web app loads, and indevandstagingthe smoke test signs in, creates, reads back and deletes a part.prodruns the read-only variant and accepts only a releasestagingverified. - Rollback: promote the previous release to the stage in Kargo. Hotfix: a normal PR, then a patch release (
vX.Y.Z+1). - Migrations must work with the previous release still running. A deploy rolls the API replicas one at a time and each runs
prisma migrate deployat start (under PostgreSQL's advisory lock, so replicas starting together are safe), so the old replica keeps serving against the new schema for a while, and a rollback runs the old image against it. Add first, remove later: never drop or rename a column or table in the same release that stops using it; make new columns nullable or give them a default. Destructive changes ship in a later release, once nothing that still uses the old shape can be rolled back to.
Conventions
- API shape — errors are
{ code, message, requestId, details? }; paginated lists are{ data, page, pageSize, total }. - Validation — every request body and query is parsed through a zod schema
from
@vector/sharedbefore reaching a controller. No ad-hoc validation inside route handlers. - Query keys — hierarchical factory at
apps/web/src/lib/queryKeys.ts. Invalidate by domain (queryKeys.parts.all) or by filter set (queryKeys.parts.list(filters)). - Commits — Conventional Commits. Renovate already expects them.