Files
backend_fiesta/services/posService.go
Suriya 12165d5e58 Give the POS a real sign-in, and stop believing the store id on the wire
The POS surface was open. A till named its own outlet — `store_id` in a query
or in an ingest batch — and was believed, so one number changed in Settings
read another tenant's catalogue or posted bills into their books. There was no
middleware in the codebase at all, and the `JWT_SECRET_KEY` in the config was
read and never used.

Products were never mis-scoped: `resolvePosStore` already derived the tenant
from the location and the catalogue query already filtered on both. The tenant
was never taken from the wire. What was missing was any check that the caller
was entitled to the location they named.

So the outlet now comes *out* of a sign-in rather than going *in* from the
till. `POST /pos/login` authenticates against the same `app_users` rows the web
console uses — one account store, so deactivating a leaver closes both doors —
and answers with the outlets that account may reach, sealed in an HMAC-SHA256
token the terminal cannot edit.

Two checks then guard everything else, in order: the token verifies, and the
outlet named in the request belongs to the token's tenant. The second is the
one that matters — a valid token is a licence to name *your* outlets, not any.

Notes on the awkward parts:

- The guard reads the outlet from the body as well as the query. The two routes
  that write carry `store_id` in a JSON batch and never in the URL, so a
  query-only check would have left exactly the dangerous call unguarded.
- Three spellings of one thing survive — `store_id`, `locationid`,
  `location_id`. All three are read rather than normalised, because renaming
  them breaks terminals already in the field.
- `POS_AUTH_REQUIRED` defaults to false. Tills are billing real customers
  against the open endpoints right now and enforcing at deploy would stop every
  one mid-trade. A token is still verified when sent, and a wrong-tenant token
  still refused; the flag only governs requests carrying none.
- `POS_TOKEN_SECRET` has no baked-in fallback and fails loudly. A development
  secret in source is the same as no signature at all.
- `configid` is inferred when the till does not send it, because a person at a
  counter has no way to know theirs. `authname` is not unique in this schema —
  live data has one address twice under one configid — so an ambiguous match is
  refused rather than resolved by LIMIT 1, which could bill into the wrong
  tenant's books.

Verified against live data: 58 accounts across 34 tenants can open a till, an
account pinned to a location resolves to it alone, a tenant-level account gets
all six of its outlets, and a cross-tenant outlet request is refused.

Passwords are still plaintext platform-wide. Flagged at the comparison site;
fixing it is a migration touching every login path, not this endpoint.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 15:46:38 +05:30

114 lines
3.8 KiB
Go

package services
import (
"context"
"time"
"nearle/models"
"nearle/repositories"
"nearle/utils"
)
type PosService interface {
IngestOrders(batch models.PosOrderBatch) (*models.PosAck, error)
IngestCustomers(batch models.PosCustomerBatch) (*models.PosAck, error)
Catalogue(storeID, since string, page, pageSize int) (*models.PosCatalogueResponse, error)
// RecordHealth stores one heartbeat. Never acknowledged back to the till:
// presence is a fire-and-forget signal, and a terminal that stopped selling
// because its heartbeat failed would be a worse outcome than a blank board.
RecordHealth(ctx context.Context, health models.PosHealth) error
TerminalHealth(ctx context.Context, terminalID string) (map[string]string, error)
LocationHealth(ctx context.Context, locationID string) ([]map[string]string, error)
Sales(f models.PosSalesFilter) (*models.PosSalesPage, error)
SaleDetail(locationID int, reference string) (*models.PosOrders, error)
SalesSummary(f models.PosSalesFilter) (*models.PosSalesSummary, error)
// Login authenticates a person against the same account store the web
// console uses and mints the session a till carries for the trading day.
Login(req models.PosLoginRequest) (*models.PosSession, error)
// LocationAllowed is the authorisation check every other POS call rests on:
// does the tenant in the caller's token actually own this outlet.
LocationAllowed(tenantID, locationID int) (bool, error)
}
type posService struct {
repo repositories.PosRepository
presence repositories.PosPresenceRepository
}
func NewPosService(repo repositories.PosRepository, presence repositories.PosPresenceRepository) PosService {
return &posService{repo: repo, presence: presence}
}
func (s *posService) RecordHealth(ctx context.Context, health models.PosHealth) error {
return s.presence.Record(ctx, health)
}
func (s *posService) TerminalHealth(ctx context.Context, terminalID string) (map[string]string, error) {
return s.presence.Terminal(ctx, terminalID)
}
func (s *posService) LocationHealth(ctx context.Context, locationID string) ([]map[string]string, error) {
return s.presence.Location(ctx, locationID)
}
func (s *posService) IngestOrders(batch models.PosOrderBatch) (*models.PosAck, error) {
return s.repo.IngestOrders(batch)
}
func (s *posService) IngestCustomers(batch models.PosCustomerBatch) (*models.PosAck, error) {
return s.repo.IngestCustomers(batch)
}
func (s *posService) Catalogue(storeID, since string, page, pageSize int) (*models.PosCatalogueResponse, error) {
return s.repo.Catalogue(storeID, since, page, pageSize)
}
func (s *posService) Sales(f models.PosSalesFilter) (*models.PosSalesPage, error) {
return s.repo.Sales(f)
}
func (s *posService) SaleDetail(locationID int, reference string) (*models.PosOrders, error) {
return s.repo.SaleDetail(locationID, reference)
}
func (s *posService) SalesSummary(f models.PosSalesFilter) (*models.PosSalesSummary, error) {
return s.repo.SalesSummary(f)
}
// Login authenticates a terminal's operator and issues its session.
//
// The token is minted here rather than in the repository so that the signing
// key stays out of the layer that talks to the database, and so a future change
// of token format touches one function.
func (s *posService) Login(req models.PosLoginRequest) (*models.PosSession, error) {
session, err := s.repo.PosLogin(req)
if err != nil {
return nil, err
}
token, expires, err := utils.MintPosToken(utils.PosClaims{
Userid: session.Userid,
Tenantid: session.Tenantid,
Locationid: session.Locationid,
Roleid: session.Roleid,
Terminalid: req.Terminalid,
}, time.Now())
if err != nil {
return nil, err
}
session.Token = token
session.Expiresat = expires.UTC().Format(time.RFC3339)
return session, nil
}
func (s *posService) LocationAllowed(tenantID, locationID int) (bool, error) {
return s.repo.PosLocationAllowed(tenantID, locationID)
}