goddard 92cfc19c08
Build & Push / Lint (push) Successful in 34s
Build & Push / Test (typecheck, unit, build) (push) Successful in 59s
Build & Push / Dependency audit (report only) (push) Successful in 6s
Build & Push / Test (API, PostgreSQL) (push) Successful in 44s
Build & Push / Build and push images (push) Successful in 1m13s
Release / Publish release images (push) Successful in 9s
API keys for service accounts (X-Api-Key) (#36)
2026-11-23 09:54:22 -05:00
2026-04-16 20:52:32 -04:00
2026-04-16 20:52:32 -04:00

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 under Site → Room → Bin locations or on a Host.
  • Every state change writes a PartEvent in the same transaction — nothing mutates silently.
  • PartModels are grouped by Manufacturer and Category, with optional EOL dates that feed dashboard risk widgets.
  • Tags and SavedViews for cross-cutting organization and reusable filters.

Field workflow

  • FM tickets track active issues per host, with attached repairs and close times.
  • Repair logs 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), headers x-vector-signature, x-vector-timestamp, x-vector-event, plus a x-vector-webhook: v1 recursion 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

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} (unknown when unset), without signing in. The web app shows it as the last line of the user menu.
  • GET /metrics on METRICS_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 prefixed vector_.

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 is POST /api/api-keys with {"name","scope"}, or POST /api/admin/api-keys with {"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: READ allows GET and HEAD only (anything else answers 403); WRITE allows 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. lastUsedAt is written at most once a minute per key.
  • Revoking: DELETE /api/api-keys/<id> (your own) or DELETE /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:

  1. GET $base/readyz until it answers 200.
  2. Sign in: POST $base/api/auth/login with the JSON body {"username":"…","password":"…"}. Keep the cookies (curl -c jar, then -b jar -c jar); the CSRF token is the value of the csrf cookie. Every later POST, PATCH or DELETE sends the cookies and the header X-CSRF-Token: <csrf>.
  3. 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).
  4. The manufacturer, created once and reused: GET $base/api/manufacturers?name=Kargo%20smoke (an exact match); if data is empty, POST $base/api/manufacturers with {"name":"Kargo smoke"} (201, body starts with {"id":"<id>").
  5. Create the part: POST $base/api/parts with {"serialNumber":"SMOKE-KARGO-<stage>","manufacturerId":"<id>","mpn":"KARGO-SMOKE","notes":"Kargo smoke test"} (201; the part model KARGO-SMOKE is created on first use; the body starts with {"id":"<part id>").
  6. Read it back: GET $base/api/parts/<part id> contains "serialNumber":"SMOKE-KARGO-<stage>".
  7. A custody move: POST $base/api/custody/<part id>/take-for-repair answers with "state":"PENDING_REPAIR", and GET $base/api/parts/<part id>/events contains "type":"STATE_CHANGED".
  8. Clean up: DELETE $base/api/parts/<part id> (204; its events go with it), then GET $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:

  1. Lint: ESLint for the API and the web app.
  2. Test (typecheck, unit, build): pnpm typecheck, the shared and API unit tests, pnpm build.
  3. Test (API, PostgreSQL): against a postgres:16 service, checks that the migrations produce exactly schema.prisma (prisma migrate diff --exit-code), then runs test:db.
  4. 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, main protected by the test jobs. CI (.gitea/workflows/build.yml) runs the tests on every PR and builds main-<commit time>-<commit> plus the full commit for every merge to main; docs-only changes build nothing. There is no latest.
  • Releasing: when what's in dev is ready, create a release in Gitea (Releases → New release) with a tag vX.Y.Z on that main commit. .gitea/workflows/release.yml adds vX.Y.Z to the images dev already ran (same digests; it only builds if that commit has none), and Kargo takes it to staging. Only strict vX.Y.Z tags count: no pre-releases. The first release is v1.0.0.
  • Verification after each promotion is Kargo's, in the stage itself: the API answers /healthz and /readyz, /api/version reports the promoted tag on every replica, the web app loads, and in dev and staging the smoke test signs in, creates, reads back and deletes a part. prod runs the read-only variant and accepts only a release staging verified.
  • 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 deploy at 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/shared before 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.
S
Description
Serialized hardware inventory for engineering fleets
Readme
836 KiB
0 Stars 1 Watchers 0 Forks
v1.1.0
Latest
2026-11-23 10:18:44 -05:00
Languages
TypeScript 98.7%
Dockerfile 0.5%
CSS 0.5%
JavaScript 0.2%