freshyo/REPO-REVIEW-OPUS.md
2026-11-05 23:33:54 +05:30

312 lines
28 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Freshyo Monorepo — Full Code Review
- **Date:** 2026-11-02
- **Branch:** `main`, at commit `0ca0a95`
- **Method:** read-only review. No files under review were edited, and no tests or migrations were run.
- **Scope:** all apps and packages except `packages/db_helper_postgres`, which is abandoned.
- **Known issues:** anything already listed in `unfixed-issues-MULTI_REGION_I2.md` is left out.
- **Deployment model:** the git remote is private and self-hosted, so repository contents are not treated as an exposure vector. Findings that only matter if the repo leaks (committed credentials, database dumps, tracked `.env` files) are excluded.
Severity runs from Critical to High, Medium and Low. **✓** means the finding was checked directly in the source. Unmarked findings come from the area reviewers, with the confidence they reported.
---
## Round 1
### Critical
#### C1. The production superadmin is seeded with a test password and cannot be changed
- **Where:** `packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql:96-98` seeds the `superadmin` user with a fixed bcrypt hash that matches `TEST_SUPERADMIN_PASSWORD` in `apps/backend/tests/.env`. There is no endpoint for changing the superadmin password.
- **Why this still matters with a private repo:** the exposure is not "someone reads the repo". It is that the production credential is a *test* credential:
- anyone who has ever had a clone, a backup, a laptop, a CI log or a screenshare retains it;
- it cannot be rotated through the product, only by hand-editing the database;
- superadmin login (`superadmin-apis/apis/auth.ts:10`) has no throttling, so a weak or common test password is remotely brute-forceable.
- **Check:** confirm what the live production hash actually resolves to. If it is still the seeded value, log in and change it, or add a password-change endpoint.
#### C2. Admin endpoints can be called with a customer token ✓
- **Cause:** `adminRouter` (`admin-apis/apis/admin-trpc-index.ts`) has no staff-only gate, and `protectedProcedure` (`trpc-index.ts:121-128`) accepts customer tokens.
- **Confirmed reachable by a customer:**
- `admin.user.updateUserSuspension` (`admin-apis/apis/user.ts:143-157`) can suspend or unsuspend any user, with no region check either.
- `admin.user.sendNotification` (`user.ts:183-252`) sends any title, text and image to every device when `userIds: []`.
- `admin.staffUser.getStaff` and `getRoles` (`staff-user.ts:66,121`) list every staff member, role and permission.
- **Partly protected:** admin handlers that read `ctx.staffUser!.regionId` fail with a TypeError (a 500) when a customer calls them, so they are protected by accident.
- **Fix:** add a `staffProcedure` and use it for the whole admin router.
#### C3. The dev worker uses the production database ✓
- **Where:** `wrangler.dev.toml:14` and `wrangler.prod.toml:12` have the same D1 `database_id`, and the same JWT secret.
- **Impact:** a `deploy:dev` build reads and writes live orders, and a dev-issued token is accepted by production (it is the same signing key, so environment separation does not exist at the auth layer).
- **Also affected:** dev image uploads go to the `meatfarmer-dev` bucket while their database rows land in prod, so those images break in prod.
- **Related ✓:** `apps/backend/reset-remote-db.sh:24-25` runs `wrangler d1 delete` and then `create` on that database. Prod goes down, and the new database id no longer matches `wrangler.prod.toml`.
### High
#### H1. Database transactions do nothing ✓
- **Cause:** `packages/db_helper_sqlite/src/db/db_index.ts:29-33` replaces `transaction` with `handler(base)`, so the 36 call sites get no atomicity.
- **Order placement:** `placeOrderTransaction` (`user-apis/order.ts:339-368`) inserts the orders, then the items five at a time, then the statuses. Cart deletion and `recordUserCouponUsage` are separate writes.
- **Effect of a partial failure:** an order with no items or no `order_status` row. It can't be cancelled ("Order status not found"), or the discount is applied but the coupon usage is never recorded.
- **Other writers affected:** `createSlotWithRelations`, `rebalanceSlots`, product create/update, and user and admin cancel.
- **Fix:** use `db.batch`, as `redeemReservedCoupon` already does.
#### H2. Coupon limits can be beaten by placing two orders at once
- **Where:** `validateAndGetCoupons` (`user-apis/order.ts:150,168`) checks usage, and the usage row is only written after the orders are inserted.
- **Gap:** no unique constraint, conditional write or idempotency key prevents a second use.
- **Scenario:** two parallel `placeOrder` calls with a `maxLimitForUser=1` or first-order-only coupon both get the discount.
- **Related:** `orderGroupId = \`${Date.now()}-${userId}\`` (`order.ts:69`) can collide when one user sends two requests in the same millisecond.
#### H3. Suspended users keep full tRPC access ✓
- **Where:** `apps/backend/src/app.ts:80-94`.
- **Cause:** `user = decoded` is set before the suspension check, and the thrown `TRPCError` is swallowed by `catch {}`. Suspension is only enforced on the Hono `/api/v1` path.
#### H4. `vendorSnippets.updateOrderItemPackaging` needs no login ✓
- **Where:** `admin-apis/apis/vendor-snippets.ts:366-387`. It is a `publicProcedure`, and its auth check is commented out.
- **Impact:** anyone can flip `is_packaged` on any order item by trying sequential IDs.
- **Related:** `getOrdersBySnippetAndSlot` (`:278-298`) ignores snippet `validTill` and never checks that the slot belongs to the snippet or its region. One valid code returns another region's customer orders.
#### H5. An address outside every delivery area takes the region the client sends ✓
- **Where:** `user-apis/apis/order.ts:80-90`.
- **Cause:** when the address has coordinates but `resolveRegionAndBound` returns null, the `else if` skips `address.regionId`.
- **Impact:** the client's `regionId`/`boundId` then decides pricing, the delivery charge, the free-delivery threshold and whether flash is allowed.
#### H6. A customer can change their mobile number without OTP
- **Where:** `user-apis/apis/auth.ts:303-333`.
- **Scenario:** an attacker sets their account's mobile to a victim's unregistered number. When the victim later logs in by OTP, they land in the attacker's account.
#### H7. The profile image path can read other buckets
- **Where:** `user-apis/apis/auth.ts:129,173,180,282,335` → `s3-client.ts:160-179`.
- **Cause:** `profileImageUrl` accepts any string, and `new URL` collapses `../`. A value like `../meatfarmer-dev/<key>` returns a signed GET URL for another bucket's object.
- **Confidence:** medium. It depends on the R2 key having access to more than one bucket.
#### H8. The cart picks delivery slots that have already closed (user-ui and server) ✓
- **Where:** `apps/user-ui/components/cart-page.tsx:806-824` and `:450`, `hooks/useProductSlotIdentifier.ts:21-23`, `components/floating-cart-bar.tsx:144-152`, and the server's `getAllSlotsWithProductsForCache` (`packages/db_helper_sqlite/src/stores/store-helpers.ts:371-376`).
- **Cause:** all of these filter only `deliveryTime > now` and ignore `freezeTime`.
- **Scenario:** after a slot's freeze time, the cart still auto-selects it as the earliest slot, then shows "slot has closed" and blocks checkout.
#### H9. A slot picked in the user-ui cart reverts on any cart refetch
- **Where:** `cart-page.tsx:788-831`.
- **Cause:** the effect depends on `cartItems` and rewrites each slot from the saved `item.slotId`. The choices made in `setSelectedSlots` and "Deliver all at…" are never saved.
- **Scenario:** change a slot, then tap +/- or let the app regain focus. The slot jumps back.
#### H10. web-ui: lowering quantity to 0 never removes the item ✓
- **Where:** `apps/web-ui/src/components/ProductCard.tsx:68`, `routes/home.product.$id.tsx:77`, `routes/flash.tsx:433`.
- **Cause:** these pass the cart line's `id` (a `Date.now()` value), but `useRemoveFromCart` (`hooks/cart-query-hooks.ts:128-142`) filters by `skuId`.
#### H11. web-ui ignores the per-area "flash delivery enabled" setting
- **Where:** `apps/web-ui/src/components/AddToCartDialog.tsx:34` hardcodes `isFlashDeliveryEnabled = true`, and `/flash` has no gate. user-ui blocks the flash section in `flash-delivery/_layout.tsx:14`.
- **Impact:** production crons switch flash off every day, and web users can still check out. Their orders then fail with a 403.
#### H12. web-ui never repairs expired cart slots and can pick a past slot
- **Where:** `apps/web-ui/src/hooks/useProductSlotIdentifier.ts:16-21` returns `slots[0]` unsorted, with no time filter, and there is no `useReconcileCartSlots` equivalent. `PaymentAndOrderComponent.tsx:104` sends the stored `slotId` as is.
- **Impact:** checkout fails with "Selected delivery slot is closed for orders", and `/cart` gives no way to change the slot.
#### H13. web-ui checkout sends out-of-stock and non-flash items, so the whole order is rejected
- **Where:** `components/PaymentAndOrderComponent.tsx:101-111`, `routes/flash.checkout.tsx:93`, `routes/home.checkout.tsx:93`. user-ui filters these out (`PaymentAndOrderComponent.tsx:121-131`).
- **Impact:** one out-of-stock line blocks checkout on web, and `/cart` shows no out-of-stock indicator.
#### H14. Admin product edit puts every out-of-stock variant back in stock ✓
- **Where:** admin-ui `products/edit.tsx:163-183` and admin-web `dashboard.products.edit.tsx` leave `isOutOfStock` out of the variant payload.
- **Cause:** the server defaults the missing value to `false` (`admin-apis/apis/product.ts:62`) and writes it.
- **Scenario:** fix a typo in a product name, and every out-of-stock variant goes back on sale.
#### H15. Saving a product twice deletes all its images, from storage too
- **Where:** `products/edit.tsx:202` calls `clearImages()` after a successful save while the screen stays open. admin-web does the same (`dashboard.products.edit.tsx:195`).
- **Cause:** on the next save, `ProductForm.tsx:253-261` marks every existing key as deleted, and the server removes the R2 objects (`apis/product.ts:431-436`).
#### H16. Editing a slot that has vendor snippets fails or duplicates them
- **Where:** `SlotForm.tsx:65-70` reads `snippet.name`, but the server only returns `snippetCode` (`db_helper_sqlite/.../slots.ts:110-118`).
- **Effect:** the update fails validation. If the admin types a name, `updateSlotWithRelations` (`slots.ts:382-402`) creates a duplicate snippet with a new code.
#### H17. Admin delivery sequence saves the wrong driver's list
- **Where:** admin-ui `delivery-sequences/index.tsx:432-437, 485-491, 714`, admin-web `dashboard.orders.sequence.tsx:438-457`.
- **Cause:** the "unsaved changes" flag isn't reset when the selected driver changes.
- **Scenario A:** reorder driver A's list, switch to driver B, and save. B's unchanged list is saved, A's reorder is lost, and a success message is shown.
- **Scenario B:** saving while "All Users" (-2) is selected stores a corrupt `"-2"` key. After that, the Unassigned view is always empty and the assignment labels are wrong.
### Medium
#### Backend
- **Cancelled orders can be marked delivered.** `updateOrderDelivered` (`admin-apis/order.ts:134-155`) has no `isCancelled` check, and it sends a "delivered" notification. `updateOrderPackaged(false)` resets `isDelivered=false`, which reopens a delivered order. Neither path rejects archived orders.
- **Complaints can be filed against another user's order.** `user-apis/apis/complaint.ts:34-48` never checks `orderId` against the user.
- **Cache versions can collide.** `region-cache-versions.ts:40-60` reads the version and then writes +1. Concurrent slot, stock or price mutations can get the same version, and the client never refetches. Fix: `UPDATE … SET value = value + 1 RETURNING value`.
- **Fractional quantities can never be ordered.** `placeOrder` requires `quantity: z.number().int()` (`order.ts:375`), while `increment_step` is a `real` column.
- **Combo-only SKUs can be bought on their own.** `order.ts:164-171` doesn't check `isComboOnly`.
- **Staff roles are never enforced.** Any staff member, even a `marketer`, can call `createStaffUser` with a `super_admin` role.
- **OTP and login have no rate limits.** OTP inputs are also put into the provider URL without escaping (`otp-utils.ts:35,57`). User login and register also reveal whether an account exists.
- **Missing indexes.** The hot foreign keys have none: `orders.user_id`, `order_items.order_id`, `order_status.order_id`, `coupon_usage(user_id, coupon_id)`, `addresses.user_id`, `notifications.user_id`, `notif_creds.user_id`, `product_skus.product_id`. D1 bills per row read.
- **Schema and migration drift.** Snapshots stop at 0002 while the journal goes to 0006, so the next `drizzle-kit generate` will produce a wrong migration. `schema.ts` doesn't declare the `idx_*_region` indexes, so they would be dropped. Its `region_id` nullability also doesn't match the database, and `reserved_coupons.region_id` has no foreign key.
- **Migration 0006 reuses an old filename.** Databases that applied the old 0006–0009 files may never run the squashed content. Confidence: low–medium.
#### user-ui
- **Stale selected address.** `useAddressStore` isn't reset on logout (`AuthContext.tsx:50-64`) or on address delete. Checkout shows the default address but submits the stale id, and the order fails with "Invalid address".
- **The Add-to-Cart dialog allows quantity 0** (`AddToCartDialog.tsx:261-266`). The server then rejects the whole order.
- **The flash cart bill includes items that can't be delivered by flash** (`cart-page.tsx:357-373, 491-510`). The coupon and free-delivery thresholds pass in the cart but fail at checkout.
- **A successful order clears the whole local cart**, including items that weren't ordered (`PaymentAndOrderComponent.tsx:59-62,94`).
- **`useAuthenticatedRoute` can push the login screen several times** because its focus callback is an inline function (`hooks/useAuthenticatedRoute.ts:16`).
#### web-ui
- **Login shows no errors at all** (`routes/login.tsx`).
- **The address list doesn't refresh.** The invalidation calls use the wrong key format, `['user.address.getUserAddresses']`, so they do nothing (`CheckoutAddressSelector.tsx:35`, `checkout-hooks.ts:71`, `checkout.tsx:130`).
- **Flash cart, checkout and success screens show the wrong price.** They use `price` instead of `flashPrice`, and the flash delivery charge is left out.
- **Logout leaves the previous user's data.** It doesn't call `queryClient.clear()` (`lib/auth-context.tsx:101-112`). The next user sees the previous user's cached data, and `RegionGate` writes it into the new user's snapshot.
- **The success page shows a locally computed total** instead of the server's `totalAmount`.
#### admin-ui and admin-web
- **A price-dialog save with no real change fails the whole batch** ("No price fields to update"). It also drops an earlier Flash toggle.
- **Coupon edit can't switch discount type or clear optional fields**, because `undefined` means "keep the current value".
- **Every coupon edit cuts `validTill` down to midnight.**
- **Coupon edit doesn't load `exclusiveApply` or `applicableUsers`.** Picking users then replaces the existing list.
- **admin-web toggles stock for the whole product instead of per variant** (`dashboard.products.tsx:85-87`).
- **The admin-ui orders list may crash.** `orders/index.tsx:186` uses `{score && score > 0 && …}`, which renders a bare `0` outside `<Text>`. Not reproduced on a device.
- **Rebalance has no confirmation and no double-submit guard**, and it shows "Rebalance Complete" from `onSettled`, so it also appears on errors.
### Low
- **Unchecked env values.** `env-exporter.ts:104-106`: if `MIN_ORDER_VALUE` or `DELIVERY_CHARGE` is missing they become `NaN`, and the delivery charge is silently never applied.
- **Unused setting.** `minOrderAmountForCoupon` is editable but never enforced.
- **Blind SSRF.** Possible through `googleMapsUrl` (`license-util.ts:3`).
- **Loose upload URLs.** They don't sign Content-Type, customers can write to admin asset folders, and keys collide when several MIME types are requested at once.
- **Large build artifacts tracked.** `apps/admin-ui/mfa_20_mar_dev.apk` (92 MB), `apps/user-ui/user-ui-shafi-dev-arm.apk` (35 MB), a 17 MB binary in `.opencode/`, `.expo` caches and `web-ui/.output`. Not a secret risk, but every clone and CI checkout pays for it.
- **Stale Docker setup.** It targets the old Postgres/Node backend, so it no longer describes how the app actually runs.
- **ProductCard re-renders every 5 s.** user-ui `ProductCard.tsx:62-67` bumps an unused `updater` state.
- **Delivery notes carry over.** `useCheckoutStore.userNotes` survives a successful order and logout.
- **Malformed checkout links crash.** A `slots` deep link without `:` crashes the checkout screen (`checkout-page.tsx:83-90`).
- **Cancelling "Remove item" resets the displayed quantity to 1** instead of the stored quantity.
- **Cart writes have no locking.** Read-modify-write on AsyncStorage can lose updates.
- **web quantity buttons ignore min/max.** The web `Quantifier` doesn't enforce them for steps that don't divide evenly, and fractional steps build up float error.
- **superadmin-ui and fallback-ui don't check token expiry.** The superadmin profile is also not restored after a reload.
- **Suspending a user fails silently** in the admin UI.
- **Two admin delivery-sequence problems.** The order menu shows stale status after an update, and selected order ids carry over when switching slots.
- **Large reads.** Slot and cache reads load the whole `productSkus` table, and the `!item.isDeleted` filter is a no-op because the column isn't selected.
- **web flash memoisation doesn't hold.** web `flash.tsx`'s `handleAddToCart` depends on the `useMutation` result object, which is new on every render, so the memo is ineffective.
- **Home ordering goes stale.** user-ui `getQuickestSlot` is memoised but depends on time, so the home catalogue ordering goes stale as slots expire.
### Checked and fine
- Address queries filter by `userId`, so there is no address IDOR.
- `/api/test` routes are gated by `ENABLE_TEST_ROUTES`.
- JWTs use HS256 and carry an expiry.
- The raw `sql` usage that was checked is parameterised.
- Prices are computed on the server, and discounts are capped at the subtotal.
- Scheduled orders enforce freeze time on the server.
- Catalogue image cache-busting only touches public asset URLs.
- web-ui has no `dangerouslySetInnerHTML`.
---
## Round 2 — deeper review
Round 2 was done by reading the code directly, since the scheduled reviewers were unavailable. Items marked ✓ were read and confirmed in the source.
### High
#### R2-1. The test suite asserts the auth holes as "current" behaviour ✓
- **Where:** `apps/backend/tests/api/auth-matrix.test.ts`.
- **What it does:**
- `AUTH-03` asserts that a customer token succeeds on `admin.vendorSnippets.getAll` and `admin.staffUser.getStaff`, and gets 500s from the other admin reads.
- `AUTH-04` asserts that a customer token passes the admin write guard, then *actually suspends a throwaway user* with a customer token and asserts `isOk === true`.
- `HARNESS-13` and `AUTH-11` assert that a suspended user still passes tRPC.
- **Why it matters:** these tests pass today, so a green suite does not mean the authorization is correct. Fixing C2 and H3 requires rewriting these cases; until then the suite actively protects the vulnerability.
#### R2-2. `web-ui` and `admin-web` have no tests at all ✓
- **Counts:** user-ui 56 test files, admin-ui 65, backend 72, web-ui 0, admin-web 0.
- **Impact:** every web-only bug found in round 1 (cart removal, flash gate, address invalidation keys, logout cache, wrong flash prices) is uncovered. The project rule that admin-ui and user-ui changes must be mirrored on web makes this the highest-risk blind spot, because the web copies drift without any test to catch it.
### Medium
#### R2-3. Cancelling an order always returns a 500 with a generic message ✓
- **Where:** `apps/backend/src/trpc/apis/user-apis/apis/order.ts:633-690`.
- **Cause:** the handler `catch`es every error and rethrows `new ApiError("failed to cancel order")`. `ApiError` defaults to status 500.
- **Effect:** "Order not found" (404), "already cancelled" (400) and "Cannot cancel delivered order" (400) all reach the client as a 500 "failed to cancel order". The specific messages only reach the logs.
- **Second effect:** `publishCancellation` is awaited *after* the cancel transaction. If the queue publish fails, the user is told the cancellation failed even though it succeeded. Retrying then hits "already cancelled", which also surfaces as the same generic 500.
- **Fix:** rethrow `ApiError` unchanged, and only wrap unknown errors.
#### R2-4. A coupon can increase the amount the customer pays ✓
- **Where:** `packages/shared/cart-pricing.ts:493-494`.
- **Cause:** `finalTotal = goodsSubtotal - discountTotal`, then `deliveryTotal = finalTotal < threshold ? charge : 0`. The free-delivery threshold is tested **after** discounts.
- **Example:** goods ₹500, threshold ₹500, delivery charge ₹60, coupon ₹50. Without the coupon the total is ₹500 (free delivery). With it, ₹450 is below the threshold, so the total becomes ₹510. Applying the coupon costs ₹10 more.
- **Note:** the user-ui cart (`cart-page.tsx:620-638`) and the server agree, because both apply the same rule, so the bill is consistent but wrong from the customer's point of view.
- **Fix:** compare the threshold against the pre-discount goods subtotal, or never charge more than the no-coupon total.
#### R2-5. Queue consumers are not idempotent and have no per-message handling ✓
- **Where:** `apps/backend/src/lib/queue-consumer.ts`.
- **Cause:** `handleNotifQueue`, `handleOrderPlacedQueue` and `handleOrderCancelledQueue` loop over `batch.messages`, await each, and never call `ack()` or `retry()`.
- **Effect:** any throw inside the loop fails the whole batch, so Cloudflare retries all messages, including the ones already processed. That means duplicate pushes and repeated order-placed side effects. A single poison message retries the entire batch until the retry limit.
- **Fix:** catch per message, `message.ack()` on success and `message.retry()` on failure, or make the handlers idempotent (for example, keyed on order id).
#### R2-6. `runBatched` promises a rollback that cannot happen ✓
- **Where:** `packages/db_helper_sqlite/src/lib/run-batched.ts`.
- **Cause:** its doc comment says "All chunks commit together, or the whole thing rolls back", but it runs inside `db.transaction`, which is the no-op from H1.
- **Effect:** callers relying on the documented atomicity (archive and order-item chunking) get partial writes on failure.
#### R2-7. Checkout delivery notes leak between orders and between users ✓
- **Where:** `apps/user-ui/src/store/checkoutStore.ts`, used at `cart-page.tsx:287` and `PaymentAndOrderComponent.tsx:56`.
- **Cause:** `userNotes` is never reset after a successful order or on logout (`AuthContext.clearSession` clears the token and the query cache only).
- **Effect on a shared device:** the next user's first order is pre-filled with the previous user's delivery instructions, and is submitted with them unless the field is edited. On the same account, every order carries the previous order's note.
#### R2-8. Cart quantity 0 is displayed as the stored quantity ✓
- **Where:** `apps/user-ui/components/cart-page.tsx:488-499, 357-372`.
- **Cause:** `quantities[item.id] || item.quantity` treats a pending 0 as "not set".
- **Effect:** when a decrement to 0 is pending or was cancelled, the cart bill and coupon maths use the stored quantity while the row shows 0. This compounds the round-1 Low item "Cancelling 'Remove item' resets the displayed quantity to 1 instead of the stored quantity".
### Low
#### R2-9. Production CORS allows local and LAN origins with credentials ✓
- **Where:** `apps/backend/src/app.ts:17-22`.
- **What's allowed:** `http://localhost:5174/4174/4175/4176` and `http://192.168.100.126:4175`, with `credentials: true`, in the production worker.
- **Impact:** a process listening on the victim's machine at one of those ports can read authenticated cross-origin responses using the web session cookie. Unlikely, but it should be gated on `NODE_ENV`.
#### R2-10. `user.savePushToken` is a public procedure ✓
- **Where:** `apps/backend/src/trpc/apis/user-apis/apis/user.ts:73`.
- **Intent:** deliberately public so that signed-out devices can register a token, and the region comes from the address.
- **Risk:** an anonymous caller can register or reassign arbitrary Expo tokens and region ids. Worth rate-limiting, or requiring a signed-out device id.
#### R2-11. The flash cron comment is wrong (the logic is not) ✓
- **Where:** `apps/backend/src/lib/flash-delivery-cron.ts:8-9`.
- **Details:** `0 16 * * *` is 21:30 IST, which matches its "9:30 PM IST" comment. `0 1 * * *` is 06:30 IST, but the comment says "6:30 PM IST". That is a sign error in a comment only: flash turns on at 06:30 and off at 21:30.
- **Also:** the toggle calls `computeConstants()` and `refreshGenKv()`, so clients do receive the new bound setting.
#### R2-12. Customer-reachable admin reads confirmed ✓
- `admin.vendorSnippets.getAll` and `admin.staffUser.getStaff` fully succeed for a customer token, since they never touch `ctx.staffUser`. The other admin reads fail with a 500 (TypeError) rather than a 401, as documented in `AUTH-03`.
- **Fix:** route all of them through `staffProcedure`.
### Verified as correct (so these are not re-reported later)
- **Region scoping is sound.** A script check over every exported helper in `packages/db_helper_sqlite/src/{admin,user,superadmin}-apis`, `stores` and `lib` found that every function that accepts `regionId` uses it in its query.
- **User ownership is sound.** Every helper that accepts `userId` uses it. Address, order and complaint reads are properly scoped (the complaint *write* gap is listed separately).
- **Order money maths is server-authoritative.** Prices come from the database. The free-delivery threshold, coupon stacking, sub-order splitting and the single delivery charge on the primary sub-order all behave consistently, and the shared helper uses the same ordering on client and server.
- **Slot rules are enforced on the server.** Existence, region, active flag, freeze time, delivery time and SKU membership are all checked in `placeOrder` for scheduled orders. Flash is re-checked against the bound setting.
- **Cron wiring covers all three schedules.** Archive at `30 20`, flash off at `0 16`, flash on at `0 1`.
- **API tests target `localhost:8787` by default**, so they do not point at production.
---
## Suggested order of work
1. **Containment (do first, regardless of code fixes)**
- Verify and change the production superadmin password, and add a way to rotate it.
- Stop tracking the build artifacts (APKs, `.wrangler` state, `.expo`, `web-ui/.output`); they are repo bloat rather than a secret risk.
- Give dev its own D1 database, and fix or delete `reset-remote-db.sh`.
2. **Authorization**
- Add a `staffProcedure` gate to the whole admin router (C2).
- Fix the suspension check in `app.ts` (H3).
- Make `updateOrderItemPackaging` authenticated (H4).
- Then rewrite `AUTH-03/04`, `HARNESS-13` and `AUTH-11` so they assert the fixed behaviour (R2-1).
3. **Data integrity**
- Replace `db.transaction` with `db.batch` where atomicity is claimed (H1, R2-6).
- Add an atomic guard for coupon usage (H2).
4. **Slot correctness**
- Filter on `freezeTime` in the cart, `useProductSlotIdentifier`, `floating-cart-bar` and `getAllSlotsWithProductsForCache` (H8).
- Persist the user's slot choice in the cart (H9, H12).
5. **Admin data-loss bugs**
- Out-of-stock flags and images on product edit (H14, H15).
- Slot snippet editing (H16).
- Delivery sequence save-after-switch (H17).
6. **web-ui parity**
- Cart removal (H10).
- Flash gate (H11).
- Checkout filtering (H13).
- Logout cache and address invalidation.
- Add the missing web test coverage (R2-2).
## Coverage notes
- Every app and package was read in round 1: backend (auth, business logic, jobs), `user-ui`, `web-ui`, `admin-ui`, `admin-web`, `superadmin-ui`, `fallback-ui`, `shared`, `ui`, `web-components`, schema and migrations, and infra.
- Round 2 added a full authorization sweep, the order/coupon/slot code paths, jobs and queues, and the cart pricing helper.
- **Less deeply reviewed:** `superadmin-ui` beyond the auth-context issue, `fallback-ui`, `packages/migrator`, and the individual `packages/ui` components. These had a first-pass read only, so treat their sections as non-exhaustive.
- The abandoned `packages/db_helper_postgres` was excluded by project rule.