Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions PROJECT_CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,32 @@ Run the five spikes in a day or two on a dev store; write the answers into secti
- 580 unit tests passing across 132 suites (`npm test`). Zero failures.
- 591 tests across 133 suites in `npm run test:all` (580 passing, 11 skipped live DB integration tests).

### 2026-11-06: Confirmation Notices and JSON Responses for Embedded Admin Forms (Branch fix/feedback-confirmation)
1. **Root Cause Analysis (Action failed alert on successful Settings form submits):**
- Live testing on the dev store revealed that submitting "Save Preferences & Send Feedback" and "Send Request" in the embedded admin Settings tab saved the underlying rows into `MerchantFeedback` and `ShopProfile`, but the merchant was greeted with an alert `Action failed`.
- Investigation identified that admin POST endpoints (`handleAdminFeedbackRequest`, `handleAdminCustomFeatureRequest`, `handleAdminDeleteContactRequest`, `handleAdminDeletePracticeContactsRequest`, etc.) in `app/lib/protocols/routes.js` evaluated `if (contentType.includes('application/x-www-form-urlencoded'))` before checking `Accept: application/json`.
- The embedded admin form interception script in `app/lib/protocols/admin.js` sends forms via `fetch()` as `application/x-www-form-urlencoded` with `Accept: application/json` and `Authorization: Bearer <id_token>`.
- The endpoints returned HTTP `303 Location: /api/admin?tab=settings&feedback_saved=1` / `request_sent=1`. `fetch()` automatically followed the 303 redirect to `/api/admin`, which is not a valid GET route (valid admin routes are `GET /`, `GET /admin`, `GET /app`), resulting in a 404/non-2xx response and triggering the catch block's `alert('Action failed')`.
- Furthermore, `feedback_saved` and `request_sent` parameters were never rendered in the UI.
2. **Endpoint Fixes Across All Admin POST Handlers:**
- Updated all 10 admin POST handlers in `app/lib/protocols/routes.js` (`handleAdminFeedbackRequest`, `handleAdminCustomFeatureRequest`, `handleAdminMarketingOptInRequest`, `handleAdminDeleteContactRequest`, `handleAdminDeletePracticeContactsRequest`, `handleAdminPractitionerStatusRequest`, `handleAdminPracticeNameRequest`, `handleAdminCreateStarterRequest`, `handleAdminUpdateSettingsRequest`, and `handleAdminEmergencyDisableAllRequest`).
- When `Accept: application/json` is present (or any request not explicitly requesting a non-JSON redirect), endpoints return HTTP 200 JSON with `{ success: true, notice: ..., message: ... }` and NO redirect.
- If non-JSON plain form submissions are received (without `Accept: application/json`), 303/302 redirects point to legitimate routes (`/admin?tab=settings&notice=feedback_saved`, `/admin?tab=settings&notice=request_sent`, `/admin?tab=settings&notice=settings_saved`, `/admin?tab=contacts`), NEVER `/api/admin`.
3. **Admin UI Confirmation Banners & Error Feedback (`admin.js`):**
- On `res.ok`, the client script extracts `data.notice` (e.g. `feedback_saved`, `request_sent`, `settings_saved`), clears any existing notice, sets the allow-listed notice query parameter on the current URL, re-acquires a fresh session `id_token`, and reloads the page on the appropriate tab.
- `renderSettingsTab` renders a small dismissible Polaris success banner (`Polaris-Banner Polaris-Banner--statusSuccess`) for allow-listed notices:
- `feedback_saved`: "Thanks, your feedback was saved."
- `request_sent`: "Thanks, your request was sent. The developer will reply to the email you gave."
- `settings_saved`: "Settings saved successfully."
- Unknown notice query parameters render nothing; user text and emails are never placed in the URL query string, preventing XSS and keeping the URL clean. All text is escaped via `escapeAdminText`.
- On error responses (HTTP 400 or 429), the client script renders an inline `.Polaris-Banner--statusCritical` and displays the server's error message (`err.error || err.message` or "Too many requests. Please try again later." for 429) via alert and inline banner instead of the generic "Action failed".
4. **Automated Test Coverage:**
- Added unit tests in `test/routes.test.js` asserting urlencoded POST with `Accept: application/json` returns 200 JSON with `{ success: true, notice: ... }` and no 303 redirect for both `handleAdminCustomFeatureRequest` and `handleAdminFeedbackRequest`.
- Added unit tests in `test/admin.test.js` verifying `renderAdminHtml` displays allow-listed notice banners for `feedback_saved`, `request_sent`, `settings_saved`, ignores unknown notice keys, and parses scripts cleanly with `vm.Script`.
- 581 unit tests passing across 132 suites (`npm test`). Zero failures.
- 592 tests across 133 suites in `npm run test:all` (581 passing, 11 skipped live DB integration tests).





4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

> **Open-Source (MIT)** | Built for the Shopify Merchant & Developer Community | Open for PRs & Discussions
>
> ⚙️ **Status: Complete Engine, Admin & Storefront Modules Verified (580/580 Unit Tests Passing across 132 Suites)** | **Live PostgreSQL Integration (11 integration tests run against a live PostgreSQL instance (they skip with a notice when none is reachable))** | **Live Railway Hosting with Postgres** | **Dev Store Spikes Verified (S2, S3, S4, S5 Answered; S1 Answered on Plus Dev Store Only; S6 Answered on Dev Store)** | **Milestones M9a, M9b-1, M9b-2, M9b-3a & M9b-3b Verified Live on Dev Store**
> ⚙️ **Status: Complete Engine, Admin & Storefront Modules Verified (581/581 Unit Tests Passing across 132 Suites)** | **Live PostgreSQL Integration (11 integration tests run against a live PostgreSQL instance (they skip with a notice when none is reachable))** | **Live Railway Hosting with Postgres** | **Dev Store Spikes Verified (S2, S3, S4, S5 Answered; S1 Answered on Plus Dev Store Only; S6 Answered on Dev Store)** | **Milestones M9a, M9b-1, M9b-2, M9b-3a & M9b-3b Verified Live on Dev Store**

<p align="center">
<img src="assets/listing/feature-image-1600x900.png" alt="A curated list card of generic unbranded wellness products converging into a single coral QR code link node on deep teal background." width="720">
Expand All @@ -28,7 +28,7 @@

**Privacy by design:** Protocols never accept or store health, medical, or diagnostic data. Browsing shoppers have zero personal information collected or stored. Under an explicit owner decision (dated 2026-11-05), the zero-PII rule is relaxed strictly for an explicit, opt-in "Stay in touch" contact submitted by the shopper on a protocol recommendation page (email, optional first name, timestamp, and verifiable consent text). No protocol, order, or product data is ever linked to the contact. Attribution is tracked solely via aggregate monthly counters. A public privacy policy is served at [`/privacy`](file:///Users/macbook/work/shopify/04-practitioner-protocols/server.js) documenting data handling, explicit consent, compliance webhooks, and sub-processors.

**Current build stage:** The pure engine logic, security controls, cryptographic primitives, Liquid renderers, catalog resolver, rate limiters, validation barriers, and PostgreSQL database queries are fully built and covered by 507 automated unit tests across 111 suites using mock database interfaces. Real PostgreSQL query execution, transaction behavior, constraints, row-level locking (`FOR UPDATE`), and migrations are verified against a live PostgreSQL instance via `npm run test:db` (11 integration tests run against a live PostgreSQL instance, skipping with a notice when none is reachable). The app is deployed live on Railway (`practitioner-protocols-production.up.railway.app`) with internal PostgreSQL and automated migration tracking. Spikes S2 (sitemap exclusion, `noindex`, and proxy header), S3 (hidden line property attribution persistence in storefront checkout and `orders/paid` webhook payload), S4 (20 lines in a single cart batch add), S5 (retail vs B2B pricing), and S6 (storefront predictive search and variant hydration contract; Option A chosen) are verified on live dev store `ai-agent-app-h9qwnwd8.myshopify.com`; Spike S1 is verified on the Plus dev store only. In production mode with `DATABASE_URL` configured, the embedded merchant admin is verified live on the dev store (Milestone M9a; `GET /`, `GET /admin`, `GET /app` served via App Bridge ID tokens and HS256 session verification), including the self-enrolment toggle and pending practitioner review table with customer admin deep links (Milestone M9b-1; verified live on dev store); for Milestone M9b-2, verified live on the dev store: enrol round trip (JSON POST through the App Proxy), pending portal state with requested name, admin pending row with customer deep link, merchant approval, approved portal display, form-encoded and `text/plain;application/json` POSTs returning 415, and unknown action returning 400 (the per-customer rate limit of 5/hr, the pending cap of 200, `customers/redact` profile deletion, and `Sec-Fetch-Site` handling are covered by automated unit tests and were not exercised live); for Milestone M9b-3a (protocol authoring and client page hydration), VERIFIED LIVE on the dev store: editor search with real products and CAD prices, protocol save, share-page hydration, Add all with _protocol_token/_protocol_id/_protocol_usage in the cart, checkout to orders/paid (webhook 200, stat row written), edit round trip (qty and note persisted, token unchanged), list card item count, handout page layout; migration adding nullable `productHandle` to `ProtocolLine`, validation and persistence, client-side predictive search (`/search/suggest.json`) and variant hydration (`/products/<handle>.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/<handle>.js`, and removal of `createFakeVariantResolver` from the production App Proxy pipeline. Follow-up hotfix loaded protocol lines on portal queries (`json_agg` + `linesCount`) to eliminate edit data loss, removed fake retail total (`$0.00`) from cards to show only item count, and implemented print-friendly handout mode (`?handout=1`) in `renderProtocolLiquid`. Milestone M9b-3b (protocol lifecycle: archive, restore, duplicate-as-template for starters with CSRF, duplicate-from-starter, Rule 4 ownership isolation, in-page confirm UI, and Archived section) is VERIFIED LIVE on the dev store. Remaining NOT-verified live list: logged-out guest view, handoutText/footerDisclaimer rendering, real printing, live cross-owner/cross-shop denial, non-Latin handles (known limitation), discounted-order attribution live, and new CSP inside real admin iframe. Note: the admin attribution report page displayed zeros for live data until a contract mismatch between `getAttributionReport` and `renderAttributionTab` was resolved by unifying `{ month, summary, rows, byPractice, byProtocol }` across the data service, renderer, demo data, and RFC 4180 CSV export with `Intl.NumberFormat` currency formatting. Pre-submission hardening is complete with HMAC-signed OAuth state cookies, public `/privacy` page, `Strict-Transport-Security` on all responses, expanded embedded App Bridge CSP, admin starter catalog product search UX, individual mode settings label, and `.github/CODEOWNERS`. Milestone M11 implements shopper opt-in contact capture (server-defined canonical consent text, dedicated 5/hr rate limiter, case-insensitive email deduplication, RFC 4180 CSV export with `Verified = "no"`) and merchant contact & feedback (`ShopProfile` sync via Admin GraphQL, AES-256-GCM session token encryption at rest, "Contact & feedback" card with 1–5 rating and marketing opt-in checkbox, `scripts/contacts.mjs` and `scripts/stats.mjs`). Under Shopify Managed Installation, authentication uses App Bridge token exchange (RFC 8693) to acquire expiring offline access tokens (1-hour lifetime, `expiring: 1`) without interactive redirects, with encrypted storage at rest via AES-256-GCM, non-PII failure logging, friendly status 200 root page, and fallback legacy OAuth. The app holds a short-lived (1 hour) offline access token, re-acquired on admin load when missing or expiring within 5 minutes, and deleted on uninstallation; no refresh token is stored (fewer secrets at rest) and no separate refresh flow is built because the app makes no Admin API calls outside embedded-admin requests. Covered by 580 automated unit tests across 132 suites.
**Current build stage:** The pure engine logic, security controls, cryptographic primitives, Liquid renderers, catalog resolver, rate limiters, validation barriers, and PostgreSQL database queries are fully built and covered by 507 automated unit tests across 111 suites using mock database interfaces. Real PostgreSQL query execution, transaction behavior, constraints, row-level locking (`FOR UPDATE`), and migrations are verified against a live PostgreSQL instance via `npm run test:db` (11 integration tests run against a live PostgreSQL instance, skipping with a notice when none is reachable). The app is deployed live on Railway (`practitioner-protocols-production.up.railway.app`) with internal PostgreSQL and automated migration tracking. Spikes S2 (sitemap exclusion, `noindex`, and proxy header), S3 (hidden line property attribution persistence in storefront checkout and `orders/paid` webhook payload), S4 (20 lines in a single cart batch add), S5 (retail vs B2B pricing), and S6 (storefront predictive search and variant hydration contract; Option A chosen) are verified on live dev store `ai-agent-app-h9qwnwd8.myshopify.com`; Spike S1 is verified on the Plus dev store only. In production mode with `DATABASE_URL` configured, the embedded merchant admin is verified live on the dev store (Milestone M9a; `GET /`, `GET /admin`, `GET /app` served via App Bridge ID tokens and HS256 session verification), including the self-enrolment toggle and pending practitioner review table with customer admin deep links (Milestone M9b-1; verified live on dev store); for Milestone M9b-2, verified live on the dev store: enrol round trip (JSON POST through the App Proxy), pending portal state with requested name, admin pending row with customer deep link, merchant approval, approved portal display, form-encoded and `text/plain;application/json` POSTs returning 415, and unknown action returning 400 (the per-customer rate limit of 5/hr, the pending cap of 200, `customers/redact` profile deletion, and `Sec-Fetch-Site` handling are covered by automated unit tests and were not exercised live); for Milestone M9b-3a (protocol authoring and client page hydration), VERIFIED LIVE on the dev store: editor search with real products and CAD prices, protocol save, share-page hydration, Add all with _protocol_token/_protocol_id/_protocol_usage in the cart, checkout to orders/paid (webhook 200, stat row written), edit round trip (qty and note persisted, token unchanged), list card item count, handout page layout; migration adding nullable `productHandle` to `ProtocolLine`, validation and persistence, client-side predictive search (`/search/suggest.json`) and variant hydration (`/products/<handle>.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/<handle>.js`, and removal of `createFakeVariantResolver` from the production App Proxy pipeline. Follow-up hotfix loaded protocol lines on portal queries (`json_agg` + `linesCount`) to eliminate edit data loss, removed fake retail total (`$0.00`) from cards to show only item count, and implemented print-friendly handout mode (`?handout=1`) in `renderProtocolLiquid`. Milestone M9b-3b (protocol lifecycle: archive, restore, duplicate-as-template for starters with CSRF, duplicate-from-starter, Rule 4 ownership isolation, in-page confirm UI, and Archived section) is VERIFIED LIVE on the dev store. Remaining NOT-verified live list: logged-out guest view, handoutText/footerDisclaimer rendering, real printing, live cross-owner/cross-shop denial, non-Latin handles (known limitation), discounted-order attribution live, and new CSP inside real admin iframe. Note: the admin attribution report page displayed zeros for live data until a contract mismatch between `getAttributionReport` and `renderAttributionTab` was resolved by unifying `{ month, summary, rows, byPractice, byProtocol }` across the data service, renderer, demo data, and RFC 4180 CSV export with `Intl.NumberFormat` currency formatting. Pre-submission hardening is complete with HMAC-signed OAuth state cookies, public `/privacy` page, `Strict-Transport-Security` on all responses, expanded embedded App Bridge CSP, admin starter catalog product search UX, individual mode settings label, and `.github/CODEOWNERS`. Milestone M11 implements shopper opt-in contact capture (server-defined canonical consent text, dedicated 5/hr rate limiter, case-insensitive email deduplication, RFC 4180 CSV export with `Verified = "no"`) and merchant contact & feedback (`ShopProfile` sync via Admin GraphQL, AES-256-GCM session token encryption at rest, "Contact & feedback" card with 1–5 rating and marketing opt-in checkbox, `scripts/contacts.mjs` and `scripts/stats.mjs`). Under Shopify Managed Installation, authentication uses App Bridge token exchange (RFC 8693) to acquire expiring offline access tokens (1-hour lifetime, `expiring: 1`) without interactive redirects, with encrypted storage at rest via AES-256-GCM, non-PII failure logging, friendly status 200 root page, and fallback legacy OAuth. The app holds a short-lived (1 hour) offline access token, re-acquired on admin load when missing or expiring within 5 minutes, and deleted on uninstallation; no refresh token is stored (fewer secrets at rest) and no separate refresh flow is built because the app makes no Admin API calls outside embedded-admin requests. Covered by 581 automated unit tests across 132 suites.

---

Expand Down
Loading
Loading