Skip to content

Commit 83255c3

Browse files
committed
plan
1 parent bcd25e9 commit 83255c3

1 file changed

Lines changed: 193 additions & 0 deletions

File tree

  • specs/002-harden-checkout-tenancy

specs/002-harden-checkout-tenancy/plan.md

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,196 @@ tests/
9393
|-----------|------------|-------------------------------------|
9494
||||
9595

96+
## Phase Structure Overview
97+
98+
This project is broken into clearly scoped phases to reduce risk and provide verifiable exit criteria at each stage:
99+
100+
- P0 — Verification Baseline
101+
- P1 — Security & Isolation Core (Checkout + Storefront Tenancy)
102+
- P2 — Transaction & Data Integrity Expansion
103+
- P3 — Error Handling & Response Standardization
104+
- P4 — Schema & Migration Alignment
105+
- P5 — Caching & Performance Foundations
106+
- P6 — Newsletter Engagement Feature Delivery
107+
- P7 — Testing Coverage Uplift & Tooling
108+
- P8 — Documentation, Observability & Final Audit
109+
110+
Each phase has explicit actions, tests, exit criteria and a short risk/mitigation summary. Work should proceed sequentially unless a parallel low‑risk task is approved (e.g., docs updates or isolated unit tests).
111+
112+
---
113+
114+
## Phase Details
115+
116+
### Phase 0: Verification Baseline
117+
Deliverables:
118+
- Current metrics snapshot (coverage, Lighthouse, Axe)
119+
- Inventory of hardcoded `storeId` usages (grep + review)
120+
- Pricing tamper test script (automated E2E that attempts price override)
121+
122+
Risks:
123+
- Hidden edge cases where `storeId` is injected at runtime. Mitigation: static grep + runtime assertion tests.
124+
125+
Exit Criteria:
126+
- Inventory complete and checked into `specs/002-harden-checkout-tenancy/artifacts/`
127+
- Baseline reports stored (coverage HTML, Lighthouse report, axe results)
128+
129+
### Phase 1: Security & Isolation Core
130+
Actions:
131+
- Implement server-side price recalculation service (e.g., `src/services/pricing-service.ts`)
132+
- Enforce auth in checkout route/server action; require session with `storeId`
133+
- Implement domain-based store resolver at `src/lib/store/resolve-store.ts`
134+
- Remove all hardcoded `DEFAULT_STORE_ID` fallbacks and sanitize code paths
135+
- Adjust `proxy.ts` to enforce tenancy rules for storefront paths and canonical redirect from subdomain → custom domain
136+
- Add Suspense + skeleton components for dashboard lists and ensure unauthenticated redirects
137+
138+
Testing:
139+
- E2E checkout tamper test (price override should be corrected)
140+
- Unit tests for store resolver (domain->storeId mapping)
141+
- Integration test for unauthorized checkout attempts
142+
143+
Exit:
144+
- Tamper attempt corrected server-side
145+
- Unauthorized checkout blocked
146+
- No hardcoded `storeId` occurrences remain (verify via grep)
147+
148+
### Phase 2: Transaction & Data Integrity
149+
Actions:
150+
- Introduce transaction wrapper `src/services/transaction.ts` to centralize `prisma.$transaction` usage
151+
- Refactor checkout flow to use a single transaction that includes order, items, inventory adjustments, discount consumption, and payment record
152+
- Add payment validation adapter `src/services/payments/intent-validator.ts` to pre-validate payment intents before commit
153+
154+
Testing:
155+
- Integration rollback tests that force failure at payment validation to assert no partial writes
156+
- Inventory consistency assertions after simulated concurrent purchases
157+
158+
Exit:
159+
- All writes for checkout are atomic and rollback on failure
160+
- Rollback behavior validated by tests
161+
162+
### Phase 3: Error Handling & Response Standardization
163+
Actions:
164+
- Create `src/lib/errors.ts` with `BaseError` subclasses: `ValidationError`, `AuthError`, `NotFoundError`, `ConflictError`, `RateLimitError`, `InternalError`
165+
- Refactor API route handlers and services to throw typed errors instead of returning strings
166+
- Implement error mapper `src/lib/error-response.ts` to convert errors to uniform response shapes and HTTP codes
167+
- Introduce API middleware pipeline (auth, rate limit, validation, logging, requestId header) and migrate routes to use it
168+
169+
Testing:
170+
- Unit tests for error mapping
171+
- Integration tests to assert API error shape and HTTP status codes
172+
173+
Exit:
174+
- 100% of modified endpoints conform to new error shape
175+
- Legacy string-matching error paths removed
176+
177+
### Phase 4: Schema & Migration Alignment
178+
Actions:
179+
- Identify inconsistent column types (e.g., images CSV vs string[]), missing `deletedAt` fields, and JSON column candidates
180+
- Create migration plan and backlog for PostgreSQL-only JSON migrations where necessary
181+
- Run `prisma migrate dev --name <descriptive>` for each change and update validation schemas (Zod)
182+
183+
Testing:
184+
- Migration test script: seed pre-migration DB, run migrations, verify shape and data integrity
185+
- Unit validators updated and tested
186+
187+
Exit:
188+
- Schema consistent across environments; migrations applied; `npm run type-check` and tests green
189+
190+
### Phase 5: Caching & Performance Foundations
191+
Actions:
192+
- Define cache tag registry `src/lib/cache/tags.ts` and document tag naming conventions
193+
- Implement tag usage in product/category/page fetch services and call `revalidateTag(tag, 'max')` on mutations
194+
- Add minimal metrics logging around transaction boundaries
195+
- Add Cache Components wrappers/un-stable cache usage for featured products and category tree with tag-based invalidation
196+
197+
Testing:
198+
- Integration test: mutation triggers tag invalidation and revalidation request
199+
- Manual Lighthouse check to ensure no regression
200+
201+
Exit:
202+
- Cache tags operational and logged; documentation updated
203+
204+
### Phase 6: Newsletter Engagement Feature Delivery
205+
Actions:
206+
- Implement Server Action at `app/(storefront)/newsletter/actions.ts` with Zod validation, rate limiting, optimistic UI, and consent recording
207+
- Create `ConsentRecord` entries; write audit logs; respect DNT and cookie consent banner
208+
- Ensure deduplication by `(storeId,email)` and single opt-in flow; send CSV export link via email + in-app notification when admin requests subscriber export
209+
210+
Testing:
211+
- Unit validation tests for Zod schema
212+
- Integration tests preventing duplicate subscriptions
213+
- E2E subscription path including consent banner and in-app notification
214+
215+
Exit:
216+
- Newsletter signup functional; consent & audit rows created; E2E passes
217+
218+
### Phase 7: Testing Coverage Uplift & Tooling
219+
Actions:
220+
- Add missing unit tests (transaction wrapper, payment validator, error mapper, cache tags)
221+
- Add E2E isolation attempts that simulate tampering and concurrency
222+
- Integrate coverage thresholds into CI and enforce gates
223+
224+
Testing:
225+
- Automated Vitest + Playwright runs with coverage reporting
226+
227+
Exit:
228+
- Coverage thresholds met and CI gating green
229+
230+
### Phase 8: Documentation, Observability & Final Audit
231+
Actions:
232+
- Update `docs/design-system.md` with error classes and cache tag conventions
233+
- Update `docs/testing-strategy.md` and `CHANGELOG.md` entries
234+
- Produce final audit report and update risk register
235+
- Run full accessibility scan and store artifacts
236+
237+
Testing:
238+
- Review checklists; grep verification of no hardcoded `storeId`; accessibility scans (axe)
239+
240+
Exit:
241+
- Final audit report stored and all acceptance criteria satisfied
242+
243+
---
244+
245+
## Architectural Decisions
246+
- Use Server Actions where form-based flows are appropriate (newsletter, optional checkout Server Action) while ensuring auth and price recalculation happen on the server boundary.
247+
- Keep a clear services layer for pure business logic; transaction wrapper isolated at `src/services/transaction.ts`.
248+
- Centralize error classes and codes in `src/lib/errors.ts`; export enumerated error codes for clients and logs.
249+
- Keep cache tags minimal in the first iteration to avoid complexity; expand based on metrics.
250+
- Centralize API middleware for auth, rate limiting, validation, logging and requestId propagation to improve consistency and observability.
251+
252+
## Testing Strategy (Detailed)
253+
- Use deterministic fixtures under `tests/fixtures` for product/discount/inventory states.
254+
- Payment validator to support stubbed scenarios (valid, invalid, expired, network-failure).
255+
- Include timeout & rate limit tests using synthetic rapid calls.
256+
- Integrate accessibility checks (axe) into E2E for checkout and newsletter forms.
257+
258+
## Performance Strategy
259+
- Instrument query timing around new transaction boundaries and log slow queries for review.
260+
- Ensure product fetch `select` lists minimal fields required for UI.
261+
- Limit client component usage; newsletter form should be a minimal client component with optimistic UI and server actions.
262+
- Use dynamic import + Suspense for heavy analytics components; prefer server-side aggregation + cache tags.
263+
264+
## Risk Matrix (Expanded)
265+
| Risk | Phase | Impact | Likelihood | Mitigation |
266+
|------|-------|--------|------------|------------|
267+
| Deadlocks | P2 | High | Low | Short-living transactions, index usage review |
268+
| Migration Data Loss | P4 | High | Medium | Backup + dry-run + verification script |
269+
| Cache Incorrectness | P5 | Medium | Medium | Observability logging, staged rollout |
270+
| Test Flakiness | P7 | Medium | Medium | Deterministic fixtures, retry budget |
271+
| Performance Regress | Any | High | Medium | Lighthouse & k6 gate before merge |
272+
273+
## Phase Dependencies
274+
- P2 depends on secure base from P1
275+
- P3 waits for transaction shapes from P2
276+
- P4 is safer post-P2 but can be prepared earlier
277+
- P5 builds on stable product/category services
278+
- P6 requires tenancy resolved in P1
279+
280+
## Exit Review Checklist (Global)
281+
- All acceptance criteria mapped to test IDs in `specs/002-harden-checkout-tenancy/tasks.md`
282+
- Coverage thresholds enforced in CI
283+
- No hardcoded `storeId` occurrences
284+
- Error codes documented in `src/lib/errors.ts`
285+
- Cache tags enumerated and documented
286+
- Migration plan created and backups confirmed
287+
288+

0 commit comments

Comments
 (0)