Nano Store - Ecommerce Docs
Developer ResourcesCatalog Integrity and Client IP

Catalog Integrity and Client IP Backend Architecture

Lock protocol, delete guards, constraint-error mapping and the client-IP resolution chain across the API and the admin BFF.

Module Scope

This change spans three places and adds no module and no table.

  • Catalog admin (apps/api/src/modules/catalog/admin/) owns the delete guards, the parent and brand checks on restore, and the lock timeout.
  • Products (apps/api/src/modules/products/) owns the product side of the lock protocol and the constraint-error mapping.
  • Client IP is resolved by apps/api/src/common/interceptors/trusted-client-ip.interceptor.ts and read through apps/api/src/modules/activity/activity-context.util.ts. The admin panel (Happy-shop-admin) is the sender.

It does not own:

  • The activity log write path (apps/api/src/modules/activity/activity-record.service.ts), which only stores the address it is given.
  • Rate limit tiers and limits. IpThrottlerGuard and the login limiter read the forwarded address through resolveTrustedClientIpHeader, which accepts it only with a matching INTERNAL_CLIENT_IP_TOKEN; without a valid token the guard keeps req.ip. See Login Brute-Force Throttling.
  • Repair of legacy rows. No migration ships.

Composition

ElementFileRole
CatalogCategoryWriteService.delete, .restoreapps/api/src/modules/catalog/admin/category/catalog-category-write.service.tsSingle category delete (children then products) and restore (live parent)
CatalogCategoryBulkService.bulkDelete, .bulkRestoreapps/api/src/modules/catalog/admin/category/catalog-category-bulk.service.tsBulk equivalents with per-id failures
CatalogBrandAdminService.deleteapps/api/src/modules/catalog/admin/brand/catalog-brand-admin.service.tsSingle brand delete
CatalogBrandBulkService.bulkDeleteapps/api/src/modules/catalog/admin/brand/catalog-brand-bulk.service.tsBulk brand delete
CatalogBrandSeriesAdminServiceapps/api/src/modules/catalog/admin/brand-series/catalog-brand-series-admin.service.tsSeries delete; lockLiveBrand used by create, update and restore
CatalogBrandSeriesBulkServiceapps/api/src/modules/catalog/admin/brand-series/catalog-brand-series-bulk.service.tsBulk series delete and restore (brands locked up front)
catalog-lock-timeout.tsapps/api/src/modules/catalog/shared/catalog-lock-timeout.tssetCatalogLockTimeout, isLockNotAvailable, catalogResourceBusy
ProductWriteSupportServiceapps/api/src/modules/products/shared/product-write-support.service.tsReferent lookups with FOR KEY SHARE, allowUnchangedDeleted, runWithConstraintMapping
product-restore-guard.tsapps/api/src/modules/products/admin/product/product-restore-guard.tsLocked referent reads for product restore
ProductImportServiceapps/api/src/modules/products/import-export/product-import.service.tsTakes referent locks on the write-pass transaction
TrustedClientIpInterceptorapps/api/src/common/interceptors/trusted-client-ip.interceptor.tsValidates the token and sets request.trustedClientIp; registered as APP_INTERCEPTOR in app.module.ts
resolveRequestClientIpapps/api/src/modules/activity/activity-context.util.tsSingle resolver for the activity log and the auth session
AuthService.getRequestContextapps/api/src/modules/auth/auth.service.tsBuilds the auth RequestContext through the resolver
Admin helperslib/auth/client-ip.ts, lib/auth/client-ip-forward-allowlist.ts, lib/auth/auth-upstream-fetch.ts, lib/mobile-api/http.ts in Happy-shop-adminCompute and attach the two headers

Data Model

No schema change and no migration. The rules read these existing columns.

TableColumns used
productcategory_id, brand_id, brand_series_id, deleted_at
categoryid, parent_id, deleted_at
brandid, deleted_at
brand_seriesid, brand_id, deleted_at
admin_sessionsip_address (text), written on login by AuthSessionService (apps/api/src/modules/auth/services/auth-session.service.ts)

The activity log is stored in MongoDB. request.ip holds the address and the activity API returns it as ipAddress.

Write behavior. Deletes and restores are single transactions. Nothing here writes a new row.

Runtime Rules and Domain Invariants

No live product under a deleted category, brand or series

Enforced by lock order, not by a constraint. A product writer (create, update, import write pass, single and bulk restore) reads each referent FOR KEY SHARE. A delete reads the row FOR UPDATE, which conflicts, then counts live products. Whichever transaction goes second sees the other's result:

  • The writer first: the delete waits, then its count includes the new product and it answers *_HAS_ACTIVE_PRODUCTS.
  • The delete first: the writer waits, then reads a deleted referent and answers PRODUCT_*_DELETED.

Without the row lock the soft-delete UPDATE alone would not conflict with a KEY SHARE.

No live series under a deleted brand

Series create, update (when a brand is supplied) and restore read the brand with FOR KEY SHARE and no deleted filter (lockLiveBrand). Brand delete holds FOR UPDATE. Series bulk restore locks every owning brand of the batch in one statement ordered by id.

Lock ordering prevents deadlock

Bulk deletes lock all requested rows in one statement, ORDER BY id. Product-side warm loaders also order by id and run sequentially when locking. Category deletes take the tree-wide advisory lock first (acquireLock) and the category row second.

Every wait is bounded

setCatalogLockTimeout is the first statement of every catalog delete transaction, before the advisory lock, because that wait honours lock_timeout too. It runs SELECT set_config('lock_timeout', $1, true) with a bound parameter, so the setting is local to the transaction. When Postgres raises 55P03, isLockNotAvailable matches it and the service throws CATALOG_RESOURCE_BUSY. The code is read from err.code ?? err.cause?.code, because Drizzle wraps driver errors in DrizzleQueryError and puts the SQLSTATE on .cause.

Unchanged classification is allowed on update

resolveClassification takes allowUnchangedDeleted. Only ProductWriteService.update passes it. For a field whose looked-up id equals the id already stored on the product, the deleted-referent refusal is skipped. The row is still read and locked. Create, import and restore never set it.

Constraint errors map from the cause

runWithConstraintMapping reads code and constraint from the error or from error.cause. Mapped constraints:

SQLSTATEConstraintResult
23503fk_product_brand_series409 PRODUCT_SERIES_BRAND_MISMATCH
23505uq_product_sku_live409 PRODUCT_SKU_ALREADY_EXISTS
23514chk_product_live_requires_thumbnail409 PRODUCT_THUMBNAIL_REQUIRED_TO_PUBLISH
23514chk_product_selling_price_not_above_mrp409 PRODUCT_SELLING_PRICE_ABOVE_MRP
23514chk_product_thumbnail_alt_requires_key400 VALIDATION_FAILED

The tag service reads uq_tag_slug_live the same way (isUniqueSlugViolation).

Client IP resolution

  • Admin. trustedClientIpHeaders returns nothing unless INTERNAL_CLIENT_IP_TOKEN is set, and resolveClientIp returns nothing when TRUSTED_PROXY_HOPS is below 1. Both default to "send nothing". lib/mobile-api/http.ts attaches the pair to every adminApi* and mobileApi* call.
  • Admin auth proxies. The two catch-all auth routes attach the pair only when the HTTP method and the upstream path equal an entry of a six-entry allowlist: POST on auth/login/email, auth/refresh, auth/password/forgot, auth/account-deletion/recover, auth/phone/verify/request, auth/email/verify/resend. Each path segment must match ^[a-z0-9-]+$ or the route answers 400 before any backend call. Upstream fetches use redirect: "manual", and any upstream 3xx becomes a fixed 502 with no Location.
  • Interceptor. It trusts the address only when the token header matches INTERNAL_CLIENT_IP_TOKEN (timingSafeEqual over SHA-256 digests of both values, no length branch), the header appears once, and the value is a single IP literal without a zone id. A repeated header or a comma list is refused.
  • Resolver. resolveRequestClientIp returns normalizeIp(req.trustedClientIp) ?? normalizeIp(req.ip). Both branches are validated, so a junk req.ip is never written to the log. It must be called from handlers and services. Guards run before the interceptor, so trustedClientIp is unset there.
  • Auth. AuthService.getRequestContext returns { ip: resolveRequestClientIp(req), userAgent }. It no longer reads req.ips[0] or x-forwarded-for.
  • Bind address. main.ts listens on API_BIND_HOST (default 0.0.0.0). With trust proxy set to 1 and the API reachable directly on its port, a caller can forge req.ip, so the operator closes the port before enabling hop counting. In production the key is required and must be loopback or private.

Configuration

KeyRequiredDefaultPurpose
CATALOG_DELETE_LOCK_TIMEOUT_MSno5000Positive integer, milliseconds. Lock wait for catalog deletes before CATALOG_RESOURCE_BUSY
API_BIND_HOSTin production (boot fails without it); otherwise no0.0.0.0IP literal the API listens on. A hostname fails boot validation. Blank counts as unset. In production it must be loopback or private (RFC 1918, ::1, fc00::/7) or the API refuses to boot
AUTH_LOGIN_KNOWN_IP_WINDOW_SECONDSno900Window for the known-IP login counter (was 300). See Login Brute-Force Throttling
AUTH_LIMITER_REDIS_CONNECT_TIMEOUT_MSno2000Integer 100 to 10000, milliseconds. Connect timeout for the limiter Redis client
INTERNAL_CLIENT_IP_TOKENin production (boot fails without it); otherwise nounsetAt least 16 characters. Must equal INTERNAL_CLIENT_IP_TOKEN in the admin deployment. Use hex: it travels in an HTTP header
TRUSTED_PROXY_HOPS (admin)no0Number of proxies in front of the admin. 1 behind Nginx. Admin-only

A token mismatch fails closed and silently: the API records the direct peer.

Security and Operational Controls

  • Authorization. Unchanged. Catalog deletes and restores keep Categories_DELETE / Categories_RESTORE, Brands_*, BrandSeries_*.
  • Rate limiting. The bulk routes keep RATE_LIMITS.ADMIN_BULK_WRITE through IpThrottlerGuard.
  • Secrets. INTERNAL_CLIENT_IP_TOKEN is compared in constant time. The admin sends it only on allowlisted auth targets and on server-side admin API calls, never from the browser.
  • Observability. At boot the API logs either Trusted client-IP forwarding is ENABLED or ... is disabled (INTERNAL_CLIENT_IP_TOKEN unset). A token mismatch has no log line; check admin_sessions.ip_address.
  • Deploy. Order and verification are in docs/vps-deployment-runbook.md, section 13.4.

Error Contract

errorCodeHTTPRaised when
CATEGORY_HAS_ACTIVE_PRODUCTS409A live product references the category
BRAND_HAS_ACTIVE_PRODUCTS409A live product references the brand
BRAND_SERIES_HAS_ACTIVE_PRODUCTS409A live product references the series
CATALOG_RESOURCE_BUSY409A catalog delete could not take its locks within the timeout
CATEGORY_PARENT_DELETED409Category restore, create or move under a deleted or missing parent
BRAND_SERIES_BRAND_DELETED409Series create, restore or re-parent under a deleted brand
PRODUCT_CATEGORY_DELETED, PRODUCT_BRAND_DELETED, PRODUCT_SERIES_DELETED409Product create, update (changed id) or restore against a deleted referent
PRODUCT_SKU_ALREADY_EXISTS, PRODUCT_SERIES_BRAND_MISMATCH, PRODUCT_THUMBNAIL_REQUIRED_TO_PUBLISH, PRODUCT_SELLING_PRICE_ABOVE_MRP409The database constraint above fired
VALIDATION_FAILED400thumbnailAlt without thumbnailKey fired its check constraint

Precedence on delete. Already deleted, then active children (category) or active series (brand), then active products. A lock timeout aborts the whole transaction first and wins over all of them.

File Map

apps/api/src/modules/catalog/
  shared/catalog-lock-timeout.ts
  admin/category/catalog-category-write.service.ts
  admin/category/catalog-category-bulk.service.ts
  admin/brand/catalog-brand-admin.service.ts
  admin/brand/catalog-brand-bulk.service.ts
  admin/brand-series/catalog-brand-series-admin.service.ts
  admin/brand-series/catalog-brand-series-bulk.service.ts
  admin/tag/catalog-tag-admin.service.ts
  admin/catalog-delete-guards.int.spec.ts
apps/api/src/modules/products/
  shared/product-write-support.service.ts
  admin/product/product-write.service.ts
  admin/product/product-bulk.service.ts
  admin/product/product-restore-guard.ts
  admin/product/product-write-facets.service.ts
  admin/product/product-referent-locks.int.spec.ts
  admin/product/product-constraint-mapping.int.spec.ts
  import-export/product-import.service.ts
apps/api/src/common/interceptors/trusted-client-ip.interceptor.ts
apps/api/src/modules/activity/activity-context.util.ts
apps/api/src/modules/auth/auth.service.ts
apps/api/src/config/env.validation.ts
apps/api/src/main.ts

See Also