Skip to content

About

Backend for LineGuard MES, a manufacturing execution system. ASP.NET Core 8 API with SignalR for live machine data, batch weighing, downtime tracking, QC with e-signatures, OEE, shift reports, and a hash-chained audit log.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

LineGuard MES — Backend (C# / .NET 8)

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.

Solution layout (Clean Architecture)

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).

Quick start (portable SQLite demo)

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 /swagger

Demo 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.

Production (PostgreSQL 16)

  1. Create roles and database: deploy/postgres/least-privilege.sql (first half), run as superuser.
  2. 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
  3. Run the second half of the script to grant runtime privileges to lineguard_app (SELECT/INSERT/UPDATE on operational tables, SELECT/INSERT only on AuditLogs, no DELETE).
  4. 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.

Local demo on Windows (no database server)

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.

Hosting online (free tiers, for testing)

Recommended combination: Neon for PostgreSQL + Render for the API container.

  1. 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.
  2. In Render choose New → Blueprint, select this repository (it reads render.yaml), then fill in ConnectionStrings__LineGuard and Seed__DemoPassword. Jwt__SigningKey is generated by Render.
  3. 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 allows https://zee7x.github.io for the web build.
  4. Optional CD: add the Render deploy hook URL as repository secret RENDER_DEPLOY_HOOK_URL; every push to main then builds ghcr.io/zee7x/lineguard-api and 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.

CI/CD

  • backend-ci (PRs): build, tests, pending-migration check.
  • backend-cd (push to main / tags v*): tests → container image to GHCR (+ Render hook) and the Windows self-contained demo package; on a v* tag the package is attached to a GitHub Release.

Security controls (PRD §3)

  • 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-signature returns 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 their employeeId.
  • Audit trail: EF Core interceptor appends AuditLogs rows in the same transaction as each change, with RowHash = SHA256(PreviousHash + payload + timestamp). GET /api/v1/audit-logs/verify recomputes 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).

Real-time contract (/hubs/plant)

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.

Demo script

  1. Supervisor creates an order: POST /api/v1/batches.
  2. Operator places material: POST /api/v1/simulator/scale/place-load (batchId → target ± random, or explicit weightKg).
  3. After the scale reports IsStable, POST /api/v1/batches/{id}/capture-weight. Out-of-tolerance returns 422 OUT_OF_TOLERANCE until a supervisor signs WEIGHT_OVERRIDE.
  4. Inject PRESSURE_SPIKE or EMERGENCY_STOP (POST /api/v1/simulator/inject-anomaly): the machine latches FAULT/STOPPED, a downtime ticket opens, alerts fire. Resolve with a root cause to return to RUNNING.
  5. QC inspector signs QC_DECISION and posts /api/v1/qc/{batchId}/inspect.
  6. Export GET /api/v1/reports/shift/export?format=pdf|csv.

Tests

dotnet test

Covers 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).

About

Backend for LineGuard MES, a manufacturing execution system. ASP.NET Core 8 API with SignalR for live machine data, batch weighing, downtime tracking, QC with e-signatures, OEE, shift reports, and a hash-chained audit log.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages