Skip to content

Commit 330d6c2

Browse files
committed
up
1 parent 5e73cc5 commit 330d6c2

4 files changed

Lines changed: 366 additions & 132 deletions

File tree

docs/specify.md

Lines changed: 99 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -1,132 +1,99 @@
1-
## /speckit.specify
2-
3-
StormCom has three critical issues: (1) insecure checkout flow (no auth enforcement, trusts client-submitted prices, incomplete transactional boundaries, missing payment verification), (2) storefront multi-tenancy bypass (hardcoded storeId, inconsistent domain-based store resolution propagation), and (3) a non-functional newsletter signup path. Additional high/medium issues include inconsistent schema arrays vs strings, ad hoc error handling via string matching, absence of a formal caching/tag invalidation strategy, incomplete Prisma multi-tenant middleware enforcement, and partial transaction scope in certain service flows.
4-
5-
This specification defines the objectives, constraints, acceptance criteria, and success measures for remediating these issues while aligning with Next.js 16 (App Router + proxy), React 19 Server Components-first design, strict TypeScript, Prisma tenant isolation, WCAG 2.1 AA accessibility, and performance budgets.
6-
7-
Goals & Objectives:
8-
1. Secure checkout: Enforce authentication, re-verify prices server-side, validate payment intents, wrap all write operations in atomic transactions.
9-
2. Enforce multi-tenancy storefront: Implement canonical store resolution (domain/subdomain -> storeId) and eliminate all hardcoded identifiers.
10-
3. Implement functional newsletter signup (Server Action + validation + rate limit + audit logging + consent record creation).
11-
4. Standardize error handling (Error class hierarchy, typed error codes, unified API response pattern).
12-
5. Align data schema (migrate inconsistent string[]/string fields, add missing deletedAt where necessary, consider JSON column migrations for PostgreSQL).
13-
6. Strengthen Prisma middleware (guaranteed storeId injection for all tenant-scoped models; audit missing models).
14-
7. Expand transactional integrity (checkout, inventory adjustments, discount application, payment capture/refund flows).
15-
8. Introduce caching strategy (cache tags + revalidateTag w/ second arg + optional Cache Components adoption plan, selective stable fetch caching with "use cache").
16-
9. Performance & accessibility validation (maintain budgets: LCP<2.5s mobile, CLS<0.1, JS bundle<200KB gzipped; Axe core zero blocking violations; multi-tenant queries optimized).
17-
10. Comprehensive test coverage uplift (≥80% services, 100% utilities; E2E coverage for checkout, tenancy resolution, newsletter; error handling cases; migration tests).
18-
11. Establish API middleware pipeline (auth, rate limit, request validation, structured logging with requestId header) eliminating string-based error matching.
19-
12. Correct REST semantics & response consistency (PUT requires full resource; PATCH partial; remove inconsistent `success` flags; uniform error payloads).
20-
13. Implement streaming CSV export with size limits & background job fallback for large order datasets.
21-
14. Elevate storefront SEO & accessibility (dynamic per-store metadata, Open Graph/Twitter, optional JSON-LD, figure/figcaption for charts, skip links, aria-live status components).
22-
15. Harden dashboard access (remove DEFAULT_STORE_ID fallback, enforce redirect for unauthenticated, introduce Suspense + skeleton patterns).
23-
16. Integrate GDPR cookie consent banner (ConsentRecord persistence, respect DNT) and align newsletter & tracking behavior.
24-
17. Improve analytics & chart accessibility (textual summaries, data transformation utilities, cache tags for expensive aggregations).
25-
26-
Scope:
27-
IN-SCOPE:
28-
- Checkout route handlers/service logic (pricing, payment, inventory, discount, order creation).
29-
- Storefront domain resolution utility (server-only) + layout propagation.
30-
- Newsletter subscription pipeline (Server Action, GDPR consent, duplicate prevention, audit logging).
31-
- Error handling module refactor (new errors in src/lib/errors.ts + mapping layer).
32-
- Prisma middleware enhancements (src/lib/prisma-middleware.ts or integrated into db.ts).
33-
- Schema migration(s) (prisma/schema.prisma + migration generation) for arrays vs strings and deletedAt additions.
34-
- Caching strategy primitives (tag registry, usage docs, integration into product, category, page fetchers).
35-
- Test suites (unit, integration, E2E) additions & updates.
36-
- Documentation updates (design-system.md, testing-strategy.md, database/schema-guide.md, CHANGELOG.md).
37-
38-
OUT-OF-SCOPE (Future or Separate Initiatives):
39-
- Payment provider abstraction overhaul beyond verification (e.g., multi-gateway expansion).
40-
- Full analytics subsystem redesign.
41-
- Search indexing engine (Elasticsearch/OpenSearch) adoption.
42-
- Full CDN edge caching strategy (beyond Next.js standard).
43-
44-
Non-Functional Requirements (NFR):
45-
Performance: p95 API <500ms (checkout <650ms including payment), DB p95 queries <100ms.
46-
Reliability: All critical flows wrapped in transactions with rollback semantics.
47-
Security: Auth required for checkout; price calculated server-side; payment intent validated; rate limiting (100 req/min) for newsletter + checkout.
48-
Compliance: GDPR consent recorded; audit log entries for subscription and order creation; PCI boundaries respected (no raw card storage).
49-
Accessibility: Newsletter form & checkout maintain WCAG 2.1 AA; keyboard navigation, ARIA labels, focus ring consistency.
50-
Observability: Structured logs (level, module, correlationId) + error codes surfaced consistently.
51-
Maintainability: Files <300 lines, functions <50 lines, error class hierarchy documented; minimal client-side state.
52-
Testability: Deterministic test data fixtures; coverage thresholds enforced; E2E critical path stable across browsers.
53-
54-
Functional Requirements (FR):
55-
FR-001: Secure checkout must reject unauthenticated requests.
56-
FR-002: Checkout recalculates line item totals and discounts server-side ignoring client-submitted prices.
57-
FR-003: Payment intent or token is validated before order creation; failed validation aborts transaction.
58-
FR-004: Order creation, inventory decrement, discount usage mark, and payment record are a single atomic transaction.
59-
FR-005: Storefront requests derive storeId from domain/subdomain mapping; fallback to 404 if unresolvable.
60-
FR-006: No hardcoded storeId remains in storefront components or services.
61-
FR-007: Newsletter subscription uses Server Action with Zod validation, deduplication (email+storeId), GDPR consent creation, optional double opt-in placeholder.
62-
FR-008: Error handling returns consistent shape `{ error: { code, message, details? } }` and success returns `{ data, meta?, message? }`.
63-
FR-009: All tenant-scoped Prisma queries enforce storeId filter either via middleware or explicit where clause.
64-
FR-010: Data schema consistency: targeted fields migrated to correct types (string[] vs CSV string) with backfill and forward validation.
65-
FR-011: Caching: Tag definitions for products, categories, pages; invalidation on create/update/delete (revalidateTag(tag,"max")).
66-
FR-012: Introduce Cache Components plan (flag disabled initially; documented enabling steps).
67-
FR-013: Test coverage thresholds enforced by CI; new tests for checkout fraud scenarios, multi-tenant isolation breach attempts, newsletter flows, error mapping.
68-
FR-014: API middleware pipeline enforces auth, rate limits (100 req/min IP baseline; stricter for login), request validation (Zod), structured logging with requestId.
69-
FR-015: Products endpoints: PUT requires full schema; PATCH allows partial; error payload uniform (no `success` field); uses error classes.
70-
FR-016: Orders CSV export streams response for <=10k rows; >10k triggers background job & downloadable link notification.
71-
FR-017: Dashboard pages redirect unauthenticated users; no DEFAULT_STORE_ID fallback present; list pages use Suspense + skeleton components.
72-
FR-018: Analytics & chart components include `<figure>` + `<figcaption>` or textual summary; axe accessibility audit passes with zero violations.
73-
FR-019: GDPR cookie consent banner writes ConsentRecord per store and honors DNT (no tracking or analytics beyond essential).
74-
FR-020: Storefront dynamic metadata (title, description, Open Graph, Twitter card) per store; optional JSON-LD for product & shop pages.
75-
FR-021: Request/response include `X-Request-Id` header on all API responses produced by middleware.
76-
77-
Acceptance Criteria:
78-
AC-001: All critical issues resolved; manual penetration test reports 0 high severity findings.
79-
AC-002: Hardcoded storeId search yields zero results outside controlled fixtures/tests.
80-
AC-003: Checkout E2E test passes across Chromium/Firefox/WebKit and validates server-side price mismatch correction.
81-
AC-004: Newsletter E2E test shows successful subscription, audit log entry, consent record.
82-
AC-005: Prisma middleware logs storeId injection for all tenant models (verified via instrumentation test).
83-
AC-006: Migration(s) applied cleanly; no orphaned data; dev & prod schema parity.
84-
AC-007: Error responses standardized (sample audit shows 100% conformity for modified endpoints).
85-
AC-008: Cache tag invalidation observed (revalidateTag invoked with second argument) after product update test.
86-
AC-009: Coverage reports meet thresholds (≥80% services, 100% utilities).
87-
AC-010: Lighthouse CI and Axe tests pass budgets and accessibility checks.
88-
AC-011: Streaming CSV export integration test completes under memory threshold; large export job path validated.
89-
AC-012: All API responses include `X-Request-Id`; logs correlate (sampled verification with grep).
90-
AC-013: PUT/PATCH semantics verified by integration tests (PUT fails on partial; PATCH succeeds on partial) & consistent error payloads (no stray `success` flag).
91-
AC-014: Dashboard unauthenticated access redirects to /login; grep confirms absence of DEFAULT_STORE_ID fallback.
92-
AC-015: Storefront metadata dynamic per store; Open Graph tags present; optional JSON-LD validated in test snapshot.
93-
AC-016: Charts audited: each has `<figure>` & `<figcaption>`; accessibility scan shows zero violations in analytics page.
94-
AC-017: GDPR consent persisted; DNT requests bypass non-essential tracking (log sample demonstrates skip).
95-
96-
Constraints:
97-
- Next.js 16 App Router only; async params/searchParams; proxy.ts for auth/rate limiting.
98-
- React 19 Server Components default; minimal Client Components.
99-
- TypeScript strict; no any.
100-
- Prisma only; no raw SQL; multi-tenant enforced.
101-
- Tailwind exclusively; no CSS-in-JS.
102-
- File/function line limits.
103-
- Implementation must not regress performance budgets.
104-
105-
Risks & Mitigations:
106-
R1: Transaction complexity increases risk of deadlocks -> Use minimal locking scope; avoid unnecessary read-after-write inside same transaction.
107-
R2: Schema migrations could impact existing data -> Dry-run & backup; write idempotent migration scripts; add verification tests.
108-
R3: Payment intent validation integration complexity -> Start with stub/adapter; progressive hardening.
109-
R4: Caching misconfiguration -> Start with conservative tags; add observability counters; rollback plan (feature flag).
110-
R5: Error hierarchy adoption regressions -> Provide adapter shim mapping legacy strings to new error codes during transition.
111-
112-
Glossary (Selected):
113-
StoreId: Tenant discriminator for all multi-tenant data.
114-
Cache Tag: Semantic identifier (e.g., product:<id>, products:list:store:<storeId>) used with revalidateTag.
115-
Server Action: `'use server'` function for form mutation or secure writes.
116-
Atomic Transaction: All-or-nothing database operation group.
117-
Consent Record: GDPR artifact tracking user consent.
118-
119-
Out of Scope Clarifications:
120-
- Real-time inventory sync with external marketplaces.
121-
- Full theme versioning system (documented as future improvement).
122-
- Refund partial ledger (placeholder suggestion only).
123-
124-
High-Level Data Flow (Checkout):
125-
Client Cart -> Server (Checkout Action/API) -> Re-fetch products & discounts -> Validate payment intent -> Begin Transaction -> Create Order -> Create OrderItems -> Adjust Inventory -> Record Payment -> Commit -> Emit Audit Log -> Return response.
126-
127-
Initial Test Strategy Summary:
128-
- Unit: Price recalculation, payment validation stub, error mapping, store resolution.
129-
- Integration: Transaction success/rollback scenarios, middleware enforcement.
130-
- E2E: Checkout (price tampering attempt), Newsletter subscription, Multi-tenant isolation (cross-store data access attempt blocked).
131-
- Accessibility: Focus traversal on forms, labels, color contrast.
132-
- Performance: k6 smoke (light) & Lighthouse CI gating.
1+
### Phase Structure Overview
2+
P0 Verification Baseline
3+
P1 Security & Isolation Core (Checkout + Storefront Tenancy)
4+
P2 Transaction & Data Integrity Expansion
5+
P3 Error Handling & Response Standardization
6+
P4 Schema & Migration Alignment
7+
P5 Caching & Performance Foundations
8+
P6 Newsletter Engagement Feature Delivery
9+
P7 Testing Coverage Uplift & Tooling
10+
P8 Documentation, Observability & Final Audit
11+
12+
### Phase Details
13+
14+
Phase 0: Verification Baseline
15+
Deliverables: Current metrics snapshot (coverage, Lighthouse, Axe), inventory of hardcoded storeIds, pricing tamper test script.
16+
Risks: Hidden edge cases. Mitigation: grep + dynamic runtime assertion tests.
17+
Exit Criteria: Inventory complete; baseline reports stored.
18+
19+
Phase 1: Security & Isolation Core
20+
Actions: Implement server-side price recalculation service, auth enforcement in checkout route/server action, domain-based store resolver (lib/store/resolve-store.ts), remove hardcoded storeIds, adjust proxy.ts to enforce tenancy for storefront paths. Remove DEFAULT_STORE_ID fallback; introduce Suspense + skeleton components for dashboard lists; ensure unauthenticated redirect.
21+
Testing: E2E checkout tamper test; unit tests store resolver; integration test unauthorized checkout.
22+
Exit: Tamper attempt corrected; unauthorized blocked; no hardcoded storeIds left.
23+
24+
Phase 2: Transaction & Data Integrity
25+
Actions: Introduce transaction wrapper (services/transaction.ts), refactor checkout to single transaction, include inventory adjustments & discount usage. Add payment validation adapter (services/payments/intent-validator.ts).
26+
Testing: Integration rollback tests (forced failure at payment validation), inventory consistency assertions.
27+
Exit: All writes atomic; rollback verified.
28+
29+
Phase 3: Error Handling Standardization
30+
Actions: Create src/lib/errors.ts (BaseError subclasses: ValidationError, AuthError, NotFoundError, ConflictError, RateLimitError, InternalError); refactor API route handlers & services to throw typed errors; implement mapper (lib/error-response.ts). Introduce API middleware (auth, rate limit, validation, logging, requestId header) and migrate routes away from string matching.
31+
Testing: Unit map tests, integration endpoint error shape tests.
32+
Exit: 100% of modified endpoints conform; legacy string matching removed.
33+
34+
Phase 4: Schema & Migration Alignment
35+
Actions: Identify inconsistent fields (e.g., images stored as CSV vs string[]), add missing deletedAt, plan JSON column migrations (PostgreSQL only) backlog entry, run `prisma migrate dev` with descriptive names, update validation schemas.
36+
Testing: Migration test script (seed pre-migration, run, verify shape), unit validators.
37+
Exit: Schema consistent; migrations applied; green type-check.
38+
39+
Phase 5: Caching & Performance Foundations
40+
Actions: Define cache tag registry (lib/cache/tags.ts), implement tag usage in product/category/page fetch services, call revalidateTag(tag,"max") on mutations, document enabling Cache Components; add minimal metrics logging. Add storefront unstable_cache wrappers for featured products & category tree with tag-based revalidation; instrument analytics data aggregation caching.
41+
Testing: Integration mutation triggers tag invalidation; manual build check; Lighthouse unaffected.
42+
Exit: Tags operational; invalidations logged; docs updated.
43+
44+
Phase 6: Newsletter Engagement
45+
Actions: Implement Server Action (app/(storefront)/newsletter/actions.ts) with Zod schema, consent record creation, audit log entry, rate limiting integration, optimistic UI state. Implement GDPR cookie consent banner linked to ConsentRecord model & DNT respect.
46+
Testing: Unit validation tests, integration duplication prevention, E2E subscription path.
47+
Exit: Newsletter functional; consent & audit rows created; E2E passes.
48+
49+
Phase 7: Testing Coverage Uplift & Tooling
50+
Actions: Add missing unit tests (transactions, payment validator, error mapper, cache tags), add E2E isolation attempts, ensure coverage >= targets, integrate coverage threshold gating in CI.
51+
Testing: Automated via Vitest + Playwright; coverage report.
52+
Exit: Coverage thresholds met; CI gating green.
53+
54+
Phase 8: Documentation & Final Audit
55+
Actions: Update design-system.md (error classes, cache tags), testing-strategy.md (new suites), CHANGELOG.md entries, generate final audit report, risk register updates.
56+
Testing: Review checklists; grep verification; accessibility scan.
57+
Exit: Final report stored; all acceptance criteria satisfied.
58+
59+
### Architectural Decisions
60+
- Use Server Actions where form-based (checkout optional; ensure auth & price recalculation in server boundary).
61+
- Maintain services layer segregation (pure business logic). Keep transaction wrapper isolated.
62+
- Error classes centralize codes; enumerated codes exported.
63+
- Cache tags minimal first iteration; avoid premature complexity.
64+
- API middleware centralizes cross-cutting concerns (auth, rate limiting, validation, logging, requestId) for consistency and observability.
65+
66+
### Testing Strategy (Detailed)
67+
- Use fixtures under tests/fixtures for deterministic product/discount/inventory states.
68+
- Payment validator stub with scenario variants (valid/invalid/expired).
69+
- Timeout & rate limit tests using synthetic fast repeated calls.
70+
- Accessibility check integrated into E2E for checkout & newsletter forms.
71+
72+
### Performance Strategy
73+
- Monitor query times via instrumentation logs (only around new transaction boundary).
74+
- Ensure product fetch selects minimal fields.
75+
- Avoid client component sprawl; keep newsletter form minimal client footprint.
76+
- Use dynamic import + Suspense for heavy analytics chart components; server-side aggregation with lean datasets and cache tags to reduce recalculation.
77+
78+
### Risk Matrix (Expanded)
79+
| Risk | Phase | Impact | Likelihood | Mitigation |
80+
|------|-------|--------|------------|------------|
81+
| Deadlocks | P2 | High | Low | Short-living transactions, index usage review |
82+
| Migration Data Loss | P4 | High | Medium | Backup + dry-run + verification script |
83+
| Cache Incorrectness | P5 | Medium | Medium | Observability logging, staged rollout |
84+
| Test Flakiness | P7 | Medium | Medium | Deterministic fixtures, retry budget |
85+
| Performance Regress | Any | High | Medium | Lighthouse & k6 gate before merge |
86+
87+
### Phase Dependencies
88+
- P2 depends on secure base from P1.
89+
- P3 waits for transaction shapes from P2.
90+
- P4 independent but safer post-P2.
91+
- P5 builds on product/category service stability from earlier phases.
92+
- P6 newsletter can start after tenancy (P1) to ensure correct storeId.
93+
94+
### Exit Review Checklist (Global)
95+
- All acceptance criteria mapped to test IDs.
96+
- Coverage thresholds enforced.
97+
- No hardcoded storeId.
98+
- Error codes documented.
99+
- Cache tags listed & referenced.

0 commit comments

Comments
 (0)