Backend for LineGuard MES: REST API + SignalR hub, telemetry/scale simulator, batch weighing, downtime, QC with electronic signatures, OEE, shift reports and a tamper-evident audit trail. The Flutter client lives in Zee7X/LineGuard-MES.
| Project | Responsibility |
|---|---|
LineGuard.Domain |
Entities, enums, shift calendar. No dependencies. |
LineGuard.Application |
Use-case services, DTOs, FluentValidation validators, abstractions (IMachineSensorProvider, IWeighingScaleProvider, IRealtimeNotifier, …). |
LineGuard.Infrastructure |
EF Core (PostgreSQL / SQLite), audit interceptor, Argon2id, JWT, Data Protection, simulator + background workers, QuestPDF/CSV exporters. |
LineGuard.Api |
Controllers, SignalR hub /hubs/plant, auth/RBAC, rate limiting, ProblemDetails, security headers, Serilog. |
tests/LineGuard.Tests |
Integration tests (WebApplicationFactory + SQLite). |
cd src/LineGuard.Api
dotnet user-secrets set "Jwt:SigningKey" "<random string, at least 32 characters>"
dotnet user-secrets set "Seed:DemoPassword" "<demo password, at least 10 characters>"
dotnet run --launch-profile http # http://0.0.0.0:5080, Swagger at /swaggerDemo users created on first start (all with Seed:DemoPassword): ADM001 (Admin), PM001 (Plant Manager),
SPV001 (Supervisor), OPR001 / OPR002 (Operator), QC001 (QC Inspector). Operators and supervisors must send a
shift (Shift1|Shift2|Shift3) at login.
- Create roles and database:
deploy/postgres/least-privilege.sql(first half), run as superuser. - Apply migrations as the owner role:
LINEGUARD_MIGRATIONS_CONNECTION="Host=…;Database=lineguard;Username=lineguard_owner;Password=…" dotnet ef database update -p src/LineGuard.Infrastructure -s src/LineGuard.Infrastructure - Run the second half of the script to grant runtime privileges to
lineguard_app(SELECT/INSERT/UPDATE on operational tables, SELECT/INSERT only onAuditLogs, no DELETE). - Configure the API with environment variables (never commit secrets):
| Variable | Purpose |
|---|---|
ConnectionStrings__LineGuard |
Connection string for lineguard_app (use SSL Mode=VerifyFull). |
Database__Provider |
PostgreSQL (default) or Sqlite. |
Jwt__SigningKey |
HS256 key, ≥ 256 bits. Startup fails if missing or short. |
DataProtection__KeysPath |
Persistent key ring directory (protect it with OS ACLs / a KMS). |
Kestrel__Endpoints__Https__Url, Kestrel__Endpoints__Https__Certificate__Path/Password |
HTTPS endpoint. Kestrel is pinned to TLS 1.3. |
Plant__TimeZoneId |
Shift and Lot-ID time zone (default Asia/Jakarta). |
Serilog__WriteTo__2__Name=Seq, Serilog__WriteTo__2__Args__serverUrl |
Optional Seq sink. |
Download lineguard-api-windows-demo.zip from the latest GitHub Release (or the backend-cd workflow artifacts),
extract it and run run-demo.cmd. It starts the API on http://localhost:5080 with a SQLite file
(lineguard-demo.db next to the script), generates a local JWT key and asks once for the demo users' password.
Then start the Flutter local demo build (lineguard-mes-windows-localdemo.zip from the frontend release).
Delete lineguard-demo.db to reset all data.
Recommended combination: Neon for PostgreSQL + Render for the API container.
- Create a Neon project and database
lineguard; copy the connection details into an Npgsql connection string:Host=<ep-xxx>.neon.tech;Database=lineguard;Username=<user>;Password=<password>;SSL Mode=Require. - In Render choose New → Blueprint, select this repository (it reads
render.yaml), then fill inConnectionStrings__LineGuardandSeed__DemoPassword.Jwt__SigningKeyis generated by Render. - The container applies migrations on startup, stores the Data Protection key ring in the database
(
DataProtection__PersistToDatabase=true, free instances have no persistent disk) and trusts the platform proxy for HTTPS and client IPs (ForwardedHeaders__Enabled=true). CORS allowshttps://zee7x.github.iofor the web build. - Optional CD: add the Render deploy hook URL as repository secret
RENDER_DEPLOY_HOOK_URL; every push tomainthen buildsghcr.io/zee7x/lineguard-apiand triggers a deploy.
Keep-alive: ping GET /alive (no database access) every 10 minutes, e.g. with cron-job.org, so the Render
instance does not spin down. With Simulator__IdleAfterMinutes=10 the simulator, and therefore all database traffic,
pauses when no signed-in user or live connection is active, so Neon can still scale to zero. Render gives 750 free
instance hours per workspace per month; one always-on service uses about 730.
Free-tier caveats: the Render free instance sleeps when idle (first request after a pause is slow, the simulator pauses while asleep) and Neon scales compute to zero. For a real plant run the API on-premises with PostgreSQL and the least-privilege roles described above, instead of migrating with the app role.
backend-ci(PRs): build, tests, pending-migration check.backend-cd(push tomain/ tagsv*): tests → container image to GHCR (+ Render hook) and the Windows self-contained demo package; on av*tag the package is attached to a GitHub Release.
- Passwords: Argon2id (19 MiB, t=2, p=1). Unknown users cost the same time as wrong passwords.
- Tokens: 15-minute JWT (HS256) + 8-hour rotating refresh token stored as SHA-256. Re-using a rotated token revokes the whole session family; logout, deactivation and role changes revoke access tokens immediately.
- Lockout: 5 failed attempts → 15-minute lock (also counts failed e-signatures).
- RBAC: policy per endpoint (
Api/Security/Policies.cs), deny-by-default fallback, hub requires a token. Segregation of duties: whoever created, weighed or overrode a batch cannot release its QC. - Electronic signatures:
POST /api/v1/auth/verify-signaturereturns a single-use, 2-minute token bound to one purpose (WEIGHT_OVERRIDE,QC_DECISION,MASTER_DATA_CHANGE,SESSION_UNLOCK). Supervisors can co-sign at an operator station by passing theiremployeeId. - Audit trail: EF Core interceptor appends
AuditLogsrows in the same transaction as each change, withRowHash = SHA256(PreviousHash + payload + timestamp).GET /api/v1/audit-logs/verifyrecomputes the chain. Updates/deletes of audit rows are blocked in the app, by DB grants and by a PostgreSQL trigger. - No hard deletes, optimistic concurrency tokens, atomic weighing transaction (weight + Lot ID + WIP deduction + QC ticket).
- API hardening: DTOs + FluentValidation only, rate limits (login 5/min/IP, API 120/min/user), RFC 7807 errors with correlation id and no internals, security headers, strict CORS, HSTS in production.
- Data at rest: product formulation notes encrypted with Data Protection (AES-256-GCM).
Known limitation: the audit-chain lock, signature tokens and session revocation list are in-process, so run a single API instance (or move them to PostgreSQL advisory locks / Redis before scaling out).
Connect with accessTokenFactory (token goes in the access_token query string only for the WebSocket handshake;
it is never logged). Call SubscribeLineGroup("ALL") for the overview or SubscribeLineGroup("L01") for one line.
Server events: ReceiveTelemetry, ReceiveScaleReading, ReceiveAlert, BatchStatusUpdated,
MachineStatusChanged, DowntimeUpdated. Enums are serialized as strings.
- Supervisor creates an order:
POST /api/v1/batches. - Operator places material:
POST /api/v1/simulator/scale/place-load(batchId→ target ± random, or explicitweightKg). - After the scale reports
IsStable,POST /api/v1/batches/{id}/capture-weight. Out-of-tolerance returns422 OUT_OF_TOLERANCEuntil a supervisor signsWEIGHT_OVERRIDE. - Inject
PRESSURE_SPIKEorEMERGENCY_STOP(POST /api/v1/simulator/inject-anomaly): the machine latchesFAULT/STOPPED, a downtime ticket opens, alerts fire. Resolve with a root cause to return toRUNNING. - QC inspector signs
QC_DECISIONand posts/api/v1/qc/{batchId}/inspect. - Export
GET /api/v1/reports/shift/export?format=pdf|csv.
dotnet testCovers login/lockout, RBAC matrix, token rotation and reuse detection, logout revocation, weighing + tolerance override, single-use signatures, QC lock and segregation of duties, downtime/alerts, report export, audit hash-chain tamper detection, hard-delete guard and encryption at rest.
QuestPDF is used under its Community license (free below USD 1M annual revenue).