# Known bugs — apps/backend Found while writing the API integration suites under `tests/api/`. Each entry gives the source location, the actual behaviour, the expected behaviour and the test that pins it. Severity is my judgement of impact. --- ## High — security / data integrity ### 1. A user token can perform admin writes (missing staff guard) `src/trpc/trpc-index.ts` — `protectedProcedure` only requires *some* identity (`ctx.user` OR `ctx.staffUser`). Many `admin.*` procedures never re-check `ctx.staffUser`, so a plain user token can call them. Confirmed reachable with a user token: - `admin.order.cancelOrder` — cancel any order - `admin.user.updateUserSuspension` — suspend any user - `admin.user.sendNotification` — broadcast notifications - `admin.product.toggleOutOfStock` (and the other `admin.product.*` writes) - `admin.staffUser.createStaffUser` — **create a usable staff account (privilege escalation)**; the new account can log in Procedures that *do* guard correctly: `admin.slots.*`, `admin.coupon.create`, `admin.coupon.createReservedCoupon` (they check `ctx.staffUser?.id`). **Fix:** add a `staffProcedure` (or a `ctx.staffUser` check) to every `admin.*` write. **Pinned by:** `tests/api/authorization-matrix.test.ts`. > **Partially fixed (FC-01/SEC-01):** `admin.const.*` is no longer reachable with > a user token. The router now uses `staffProcedure`; `updateConstants` also > rejects global-scope keys (globals are superadmin-only), and the redundant > `getGlobalConstants`/`updateGlobalConstants`/`getLegacyConstants`/ > `updateLegacyConstants` procedures were removed (they had no production UI > caller — the admin apps use `admin.region.*`, the superadmin UI uses > `superadmin.const.*`). The remaining entries above are still open. ### 2. Public `admin.vendorSnippets` endpoints `src/trpc/apis/admin-apis/apis/vendor-snippets.ts` - `getUpcomingSlots:176? / 259` — `publicProcedure` - `getOrdersBySnippet:176` — `publicProcedure`, returns order/customer data for a snippet code - `getOrdersBySnippetAndSlot:275` — `publicProcedure` - `updateOrderItemPackaging:362` — `publicProcedure` with the staff check **commented out** (lines 355-360), so anyone can flip packaging state **Fix:** require staff on all four. **Pinned by:** `tests/api/authorization-matrix.test.ts`. ### 3. `user.auth.updateProfile` always throws `src/trpc/apis/user-apis/apis/auth.ts:342` ```ts const authHeader = ctx.req.header('authorization'); ``` `ctx.req` is a fetch `Request` (see `src/app.ts` context: `{ req, c, ... }`), which has `.headers.get(...)`, not `.header(...)`. The call throws `TypeError: ctx.req.header is not a function`. Worse, the profile update (`updateUserProfileInDb`) and the profile image URL resolving both run *before* line 342, so the write is committed and the client still receives an error — a silent partial success. **Fix:** `ctx.req.headers.get('authorization')` (or use `ctx.c`). **Pinned by:** `tests/api/misc-procedures.test.ts` — "pins: updateProfile crashes after writing the change". > **Fixed (FC-15/AU-07):** `Context.req` is now typed as the fetch `Request` the > adapter actually passes, and `updateProfile` reads > `ctx.req.headers.get('authorization')`. The optional email was also relaxed: > an empty email means "no change" (the client only requires it when registering). ### 4. `user.auth.updatePassword` silently does nothing `packages/db_helper_sqlite/src/user-apis/auth.ts:177` (`upsertUserPassword`) ```ts try { await db.insert(userCreds).values({ userId, userPassword: hashedPassword }) return } catch (error) { if (error.code === '23505') { /* postgres unique violation -> UPDATE */ } throw error } ``` `user_creds` has **no UNIQUE constraint on `user_id`** (schema: `id, user_id, user_password, created_at`), and `23505` is the *Postgres* unique-violation code — on D1 the insert simply succeeds. Result: a second credentials row is created, `getUserAuthCreds` keeps returning the original row, and the account's password never changes. Verified: after "updating" the password, the **old password still logs in** and the new one is rejected; the user now has duplicate rows in `user_creds`. **Fix:** add a UNIQUE index on `user_creds.user_id` and handle the SQLite constraint code, or do an explicit select-then-insert/update. **Pinned by:** `tests/api/misc-procedures.test.ts` — "pins: updatePassword reports success but the old password still works". > **Fixed (FC-16/AU-08):** `upsertUserPassword` now does an explicit > select-then-update-or-insert (updating every row for the user, which also > repairs existing duplicates), and a `uniqueIndex` on `user_creds.user_id` was > added to the schema. Existing duplicate rows must be deduped before the index > migration can be applied (the local DB has duplicates for users 379, 908, 1311). --- ## High — money ### 5. A ≥100% coupon produces a negative order total `packages/db_helper_sqlite/src/user-apis/order.ts` (`applyDiscountToOrder`) The percentage branch caps the discount at `maxValue * proportion` or `Infinity` and **never at `orderTotal`** (the flat branch does cap at the order total). A coupon with `discountPercent >= 100` and no `maxValue` therefore drives `orders.totalAmount` to zero or negative. `admin.coupon.create` accepts any `discountPercent` (no upper bound). **Pinned by:** `tests/api/coupon-math.test.ts` — "pins: a 150% coupon produces a negative total". ### 6. The discount is applied to the delivery-inclusive base `src/trpc/apis/user-apis/apis/order.ts:156` ```ts const orderTotalAmount = isFirstOrder ? subOrderTotalWithDelivery : subOrderTotal; ``` `isFirstOrder` is true for the **first sub-order of every placeOrder call**, so that sub-order's discount is computed on `goods + deliveryCharge`. A percentage coupon therefore discounts the delivery fee as well. **Pinned by:** `tests/api/coupon-math.test.ts` — "pins: a percentage coupon discounts the delivery fee too". > **Fixed (FC-08):** `placeOrderUtil` now computes the coupon discount on the > whole cart **subtotal** and decides delivery on the **post-discount** total > (`finalTotal < freeDeliveryThreshold`), mirroring the customer app. A > percentage coupon no longer touches the delivery fee. (FC-07 is fixed too: the > threshold key is now `freeDeliveryThreshold`, not `minRegularOrderValue`.) ### 7. Money is never rounded Nothing rounds `totalAmount`; it is written with `.toString()` on a raw float, so percentage discounts leave float noise (e.g. `999 - 15%`). **Pinned by:** `tests/api/coupon-math.test.ts` — "pins: amounts are stored unrounded". --- ## Medium — coupon rules ### 8. Coupon scoping is not enforced at placeOrder `validateAndGetCoupon` checks invalidated / expiry / per-user limit / minOrder / first-order-only, but **not** `isUserBased`, `applicableUsers`, `skuIds` or `exclusiveApply`. Only the display endpoints (`getEligible` / `getMyCoupons`) filter by applicability, so user B can spend a coupon issued to user A by passing its id to `placeOrder`. **Pinned by:** `tests/api/coupon-ux.test.ts` — "rejects user B applying a coupon issued to user A". > **Partially fixed (FC-04/SEC-06):** `validateAndGetCoupon` now loads > `applicableUsers` and rejects a user-based coupon for anyone not listed (unless > `isApplyForAll`). `skuIds` and region are **deliberately not enforced**: no > SKU-specific or region-scoped coupons are created today (FC-09/FC-10 are false > flags for now). `exclusiveApply` remains unenforced. ### 9. Cancelling an order does not release its coupon usage `recordUserCouponUsage` runs at placement; `cancelOrderTransaction` never touches `coupon_usage`. A cancelled order permanently consumes a `maxLimitForUser` slot. **Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: cancelling an order does not release its coupon usage". ### 10. A cancelled first order poisons an `isFirstOrderOnly` coupon `getOrderCount` counts every order including cancelled ones, and `isUserBased`/first-order checks run off it — so placing and cancelling a first order permanently blocks a first-order-only coupon for that user. **Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: a cancelled first order poisons an isFirstOrderOnly coupon". ### 11. Reserved-coupon expiry is not checked at redemption `redeemReservedCoupon` checks "already redeemed" and first-order-only, but not `validTill`. An expired reserved code still redeems (it only fails later at `placeOrder`). **Pinned by:** `tests/api/coupon-ux.test.ts` — "pins: an expired reserved code still redeems". ### 12. `exclusiveApply` is stored but never enforced Coupons carry `exclusiveApply`, and `placeOrder` accepts a single `couponId`, so the flag has no effect anywhere. (Observation from reading the code; no runtime test.) --- ## Medium — placeOrder guards ### 13. Out-of-stock products are still orderable `placeOrderUtil` checks `isFlashAvailable` for flash orders but never `isOutOfStock`. **Pinned by:** `tests/api/place-order-edge-cases.test.ts`. > **Fixed (FC-03/SEC-05):** `placeOrderUtil` now rejects a product that is > `isDeleted`, `isOutOfStock` or `isSuspended` (400 "… is unavailable"). The > cross-region-SKU case (FC-02/SEC-04) is rejected too: the SKU's product > `regionId` must equal the order region (409). ### 14. An empty `selectedItems` list fails with a raw DB error There is no `.min(1)` on `selectedItems`, so an empty list reaches Drizzle, which throws `values() must be called with at least one value` instead of returning a 400. **Pinned by:** `tests/api/place-order-edge-cases.test.ts`. ### 15. No quantity cap `quantity` is `z.number().int().positive()` with no upper bound; `1_000_000` units are accepted. **Pinned by:** `tests/api/place-order-edge-cases.test.ts`. ### 16. No slot validity checks `placeOrder` only checks slot *capacity*. An inactive slot, a slot whose delivery time has already passed, and a slot that does not carry the ordered SKU are all accepted. **Pinned by:** `tests/api/place-order-edge-cases.test.ts`. > **Fixed (FC-03/SEC-05, FC-13/SL-04):** `placeOrderUtil` now requires a > non-null `slotId` for scheduled orders and validates the slot: it must exist, > belong to the order region (409), be `isActive`, have `freezeTime > now` and > `deliveryTime > now`, and carry every ordered `skuId` in `slot.skuIds` (400 > otherwise). ### 17. No idempotency Two identical `placeOrder` calls create two orders (`orderGroupId` is `Date.now()-userId`, with no uniqueness check). **Pinned by:** `tests/api/place-order-edge-cases.test.ts`. > **Mitigated client-side (FC-17/OR-12):** the Place Order button is disabled while a > submit is in flight and `handlePlaceOrder` early-returns via a synchronous `useRef` > guard, so an accidental double-tap cannot submit twice. **Server-side idempotency is > still absent** — a direct API replay or network retry can create duplicates. A > client-generated idempotency key remains the proper fix if/when wanted. --- ## Low — error handling / lifecycle ### 18. `cancelOrder` swallows every error into one generic message `src/trpc/apis/user-apis/apis/order.ts:554-599` wraps the whole handler in a `try/catch` that rethrows `new ApiError("failed to cancel order")`, discarding the specific 404/400 messages it constructs ("Order not found", "Order is already cancelled", "Cannot cancel delivered order"). `updateUserNotes`, by contrast, has no catch and propagates its real messages. **Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` and `tests/api/authorization-matrix.test.ts`. ### 19. No order status transition guards `admin.order.updateDelivered` / `updatePackaged` accept any state: a cancelled order can be marked delivered, and delivered is reversible. **Pinned by:** `tests/api/order-lifecycle-gaps.test.ts`. ### 20. `getUserDetails` breaks past ~110 orders `admin.user.getUserDetails` builds an unchunked `IN (...)` over the user's order ids and fails once the history is large. Documented in `tests/api/admin-users.test.ts` (that suite uses a throwaway user to avoid it). --- ## Out of scope (per request) Online payments (`user.payment.*`, `admin.payments.initiateRefund`), OTP (`sendOtp`/`verifyOtp`) and `deleteAccount` are deliberately untested and not listed here.