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.tsand read throughapps/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.
IpThrottlerGuardand the login limiter read the forwarded address throughresolveTrustedClientIpHeader, which accepts it only with a matchingINTERNAL_CLIENT_IP_TOKEN; without a valid token the guard keepsreq.ip. See Login Brute-Force Throttling. - Repair of legacy rows. No migration ships.
Composition
| Element | File | Role |
|---|---|---|
CatalogCategoryWriteService.delete, .restore | apps/api/src/modules/catalog/admin/category/catalog-category-write.service.ts | Single category delete (children then products) and restore (live parent) |
CatalogCategoryBulkService.bulkDelete, .bulkRestore | apps/api/src/modules/catalog/admin/category/catalog-category-bulk.service.ts | Bulk equivalents with per-id failures |
CatalogBrandAdminService.delete | apps/api/src/modules/catalog/admin/brand/catalog-brand-admin.service.ts | Single brand delete |
CatalogBrandBulkService.bulkDelete | apps/api/src/modules/catalog/admin/brand/catalog-brand-bulk.service.ts | Bulk brand delete |
CatalogBrandSeriesAdminService | apps/api/src/modules/catalog/admin/brand-series/catalog-brand-series-admin.service.ts | Series delete; lockLiveBrand used by create, update and restore |
CatalogBrandSeriesBulkService | apps/api/src/modules/catalog/admin/brand-series/catalog-brand-series-bulk.service.ts | Bulk series delete and restore (brands locked up front) |
catalog-lock-timeout.ts | apps/api/src/modules/catalog/shared/catalog-lock-timeout.ts | setCatalogLockTimeout, isLockNotAvailable, catalogResourceBusy |
ProductWriteSupportService | apps/api/src/modules/products/shared/product-write-support.service.ts | Referent lookups with FOR KEY SHARE, allowUnchangedDeleted, runWithConstraintMapping |
product-restore-guard.ts | apps/api/src/modules/products/admin/product/product-restore-guard.ts | Locked referent reads for product restore |
ProductImportService | apps/api/src/modules/products/import-export/product-import.service.ts | Takes referent locks on the write-pass transaction |
TrustedClientIpInterceptor | apps/api/src/common/interceptors/trusted-client-ip.interceptor.ts | Validates the token and sets request.trustedClientIp; registered as APP_INTERCEPTOR in app.module.ts |
resolveRequestClientIp | apps/api/src/modules/activity/activity-context.util.ts | Single resolver for the activity log and the auth session |
AuthService.getRequestContext | apps/api/src/modules/auth/auth.service.ts | Builds the auth RequestContext through the resolver |
| Admin helpers | lib/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-admin | Compute and attach the two headers |
Data Model
No schema change and no migration. The rules read these existing columns.
| Table | Columns used |
|---|---|
product | category_id, brand_id, brand_series_id, deleted_at |
category | id, parent_id, deleted_at |
brand | id, deleted_at |
brand_series | id, brand_id, deleted_at |
admin_sessions | ip_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:
| SQLSTATE | Constraint | Result |
|---|---|---|
23503 | fk_product_brand_series | 409 PRODUCT_SERIES_BRAND_MISMATCH |
23505 | uq_product_sku_live | 409 PRODUCT_SKU_ALREADY_EXISTS |
23514 | chk_product_live_requires_thumbnail | 409 PRODUCT_THUMBNAIL_REQUIRED_TO_PUBLISH |
23514 | chk_product_selling_price_not_above_mrp | 409 PRODUCT_SELLING_PRICE_ABOVE_MRP |
23514 | chk_product_thumbnail_alt_requires_key | 400 VALIDATION_FAILED |
The tag service reads uq_tag_slug_live the same way (isUniqueSlugViolation).
Client IP resolution
- Admin.
trustedClientIpHeadersreturns nothing unlessINTERNAL_CLIENT_IP_TOKENis set, andresolveClientIpreturns nothing whenTRUSTED_PROXY_HOPSis below 1. Both default to "send nothing".lib/mobile-api/http.tsattaches the pair to everyadminApi*andmobileApi*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:
POSTonauth/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 answers400before any backend call. Upstream fetches useredirect: "manual", and any upstream 3xx becomes a fixed502with noLocation. - Interceptor. It trusts the address only when the token header matches
INTERNAL_CLIENT_IP_TOKEN(timingSafeEqualover 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.
resolveRequestClientIpreturnsnormalizeIp(req.trustedClientIp) ?? normalizeIp(req.ip). Both branches are validated, so a junkreq.ipis never written to the log. It must be called from handlers and services. Guards run before the interceptor, sotrustedClientIpis unset there. - Auth.
AuthService.getRequestContextreturns{ ip: resolveRequestClientIp(req), userAgent }. It no longer readsreq.ips[0]orx-forwarded-for. - Bind address.
main.tslistens onAPI_BIND_HOST(default0.0.0.0). Withtrust proxyset to 1 and the API reachable directly on its port, a caller can forgereq.ip, so the operator closes the port before enabling hop counting. In production the key is required and must be loopback or private.
Configuration
| Key | Required | Default | Purpose |
|---|---|---|---|
CATALOG_DELETE_LOCK_TIMEOUT_MS | no | 5000 | Positive integer, milliseconds. Lock wait for catalog deletes before CATALOG_RESOURCE_BUSY |
API_BIND_HOST | in production (boot fails without it); otherwise no | 0.0.0.0 | IP 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_SECONDS | no | 900 | Window for the known-IP login counter (was 300). See Login Brute-Force Throttling |
AUTH_LIMITER_REDIS_CONNECT_TIMEOUT_MS | no | 2000 | Integer 100 to 10000, milliseconds. Connect timeout for the limiter Redis client |
INTERNAL_CLIENT_IP_TOKEN | in production (boot fails without it); otherwise no | unset | At 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) | no | 0 | Number 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_WRITEthroughIpThrottlerGuard. - Secrets.
INTERNAL_CLIENT_IP_TOKENis 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 ENABLEDor... is disabled (INTERNAL_CLIENT_IP_TOKEN unset). A token mismatch has no log line; checkadmin_sessions.ip_address. - Deploy. Order and verification are in
docs/vps-deployment-runbook.md, section 13.4.
Error Contract
errorCode | HTTP | Raised when |
|---|---|---|
CATEGORY_HAS_ACTIVE_PRODUCTS | 409 | A live product references the category |
BRAND_HAS_ACTIVE_PRODUCTS | 409 | A live product references the brand |
BRAND_SERIES_HAS_ACTIVE_PRODUCTS | 409 | A live product references the series |
CATALOG_RESOURCE_BUSY | 409 | A catalog delete could not take its locks within the timeout |
CATEGORY_PARENT_DELETED | 409 | Category restore, create or move under a deleted or missing parent |
BRAND_SERIES_BRAND_DELETED | 409 | Series create, restore or re-parent under a deleted brand |
PRODUCT_CATEGORY_DELETED, PRODUCT_BRAND_DELETED, PRODUCT_SERIES_DELETED | 409 | Product 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_MRP | 409 | The database constraint above fired |
VALIDATION_FAILED | 400 | thumbnailAlt 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.tsSee Also
Catalog Integrity and Client IP Feature Guide
Delete protection for categories, brands and series, safe restore rules, constraint errors that no longer surface as 500, and the real client IP in audit and session records.
Catalog Integrity and Client IP API Reference
Changed behavior, new 409 codes and bulk failure shapes for the catalog delete and restore endpoints, plus the internal client-IP headers.