diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index a791f08..e165fc5 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -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 `. + - 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¬ice=feedback_saved`, `/admin?tab=settings¬ice=request_sent`, `/admin?tab=settings¬ice=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). + + diff --git a/README.md b/README.md index 8aea48d..ca33823 100644 --- a/README.md +++ b/README.md @@ -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**

A curated list card of generic unbranded wellness products converging into a single coral QR code link node on deep teal background. @@ -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/.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/.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/.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/.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. --- diff --git a/app/lib/protocols/admin.js b/app/lib/protocols/admin.js index ce66b5c..5d5f6df 100644 --- a/app/lib/protocols/admin.js +++ b/app/lib/protocols/admin.js @@ -1400,7 +1400,8 @@ export function renderAdminHtml(options = {}) { contactsData = null, shopProfile = null, adminEmail = '', - activeTab = 'practitioners' + activeTab = 'practitioners', + notice = '' } = options; // Enforce zero PII barrier on all inputs @@ -1557,6 +1558,40 @@ export function renderAdminHtml(options = {}) { color: var(--p-color-text-subdued); margin-top: 0.25rem; } + .Polaris-Banner { + display: flex; + align-items: flex-start; + justify-content: space-between; + padding: 0.75rem 1rem; + border-radius: 8px; + margin-bottom: 1.5rem; + font-size: 0.875rem; + line-height: 1.4; + } + .Polaris-Banner--statusSuccess { + background: #f1f8f5; + border: 1px solid #95c9b4; + color: #0d593c; + } + .Polaris-Banner--statusCritical { + background: #fff4f4; + border: 1px solid #fec8c8; + color: #8c1b09; + } + .Polaris-Banner__Dismiss { + background: none; + border: none; + cursor: pointer; + font-size: 1.25rem; + line-height: 1; + color: inherit; + opacity: 0.7; + margin-left: 0.75rem; + padding: 0 0.25rem; + } + .Polaris-Banner__Dismiss:hover { + opacity: 1; + } `; // Tab 1: Practitioners List @@ -1856,7 +1891,20 @@ export function renderAdminHtml(options = {}) { const disclaimer = escapeAdminText(settings?.disclaimer || settings?.footerDisclaimer || ''); const handout = escapeAdminText(settings?.handoutText || ''); + const ALLOWED_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.' + }; + const noticeText = ALLOWED_NOTICES[notice] || ''; + const bannerHtml = noticeText ? ` +

+
${escapeAdminText(noticeText)}
+ +
` : ''; + return ` + ${bannerHtml}

App Settings

@@ -2191,15 +2239,44 @@ ${appBridgeHead} Practitioner Protocols — Admin }); if (res.ok) { + const data = await res.json().catch(function() { return {}; }); const freshToken = await getToken(); const nextUrl = new URL(window.location.href); if (freshToken) { nextUrl.searchParams.set('id_token', freshToken); } + if (action.includes('/settings') || action.includes('/feedback') || action.includes('/emergency/')) { + nextUrl.searchParams.set('tab', 'settings'); + } else if (action.includes('/contacts')) { + nextUrl.searchParams.set('tab', 'contacts'); + } else if (action.includes('/practitioners')) { + nextUrl.searchParams.set('tab', 'practitioners'); + } else if (action.includes('/starters')) { + nextUrl.searchParams.set('tab', 'starters'); + } + nextUrl.searchParams.delete('notice'); + var allowedNotices = ['feedback_saved', 'request_sent', 'settings_saved']; + if (data && data.notice && allowedNotices.indexOf(data.notice) !== -1) { + nextUrl.searchParams.set('notice', data.notice); + } window.location.href = nextUrl.toString(); } else { const err = await res.json().catch(function() { return {}; }); - alert(err.error || 'Action failed'); + var errorMsg = err.error || err.message; + if (res.status === 429) { + errorMsg = errorMsg || 'Too many requests. Please try again later.'; + } + if (!errorMsg) { + errorMsg = 'Action failed'; + } + var prevBanner = form.querySelector('.Polaris-Banner--statusCritical'); + if (prevBanner) prevBanner.remove(); + var banner = document.createElement('div'); + banner.className = 'Polaris-Banner Polaris-Banner--statusCritical'; + banner.setAttribute('role', 'alert'); + banner.textContent = errorMsg; + form.insertBefore(banner, form.firstChild); + alert(errorMsg); if (submitBtn) submitBtn.disabled = false; } } catch (err) { diff --git a/app/lib/protocols/routes.js b/app/lib/protocols/routes.js index 17b4cab..388b473 100644 --- a/app/lib/protocols/routes.js +++ b/app/lib/protocols/routes.js @@ -1732,6 +1732,7 @@ export async function handleAdminDashboardRequest(db, request, options = {}) { const activeTab = urlObj?.searchParams?.get('tab') || request?.query?.tab || 'practitioners'; const month = urlObj?.searchParams?.get('month') || request?.query?.month || new Date().toISOString().slice(0, 7); + const notice = urlObj?.searchParams?.get('notice') || request?.query?.notice || ''; let profiles = options.demoData?.profiles || []; let starters = options.demoData?.starters || []; @@ -1777,7 +1778,8 @@ export async function handleAdminDashboardRequest(db, request, options = {}) { contactsData, shopProfile, adminEmail: session.email || '', - activeTab + activeTab, + notice }); const frameAncestors = shop && SHOPIFY_DOMAIN_REGEX.test(shop) @@ -1855,7 +1857,7 @@ export async function handleAdminPractitionerStatusRequest(db, request, options // Handle form redirect vs JSON response const acceptHeader = getHeader(request, 'accept') || ''; const contentType = getHeader(request, 'content-type') || ''; - if (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html')) { + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 302, headers: { Location: '/admin?tab=practitioners' } @@ -1893,7 +1895,7 @@ export async function handleAdminPracticeNameRequest(db, request, options = {}) const acceptHeader = getHeader(request, 'accept') || ''; const contentType = getHeader(request, 'content-type') || ''; - if (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html')) { + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 302, headers: { Location: '/admin?tab=practitioners' } @@ -1949,7 +1951,7 @@ export async function handleAdminCreateStarterRequest(db, request, options = {}) const acceptHeader = getHeader(request, 'accept') || ''; const contentType = getHeader(request, 'content-type') || ''; - if (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html')) { + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 302, headers: { Location: '/admin?tab=starters' } @@ -1986,14 +1988,14 @@ export async function handleAdminUpdateSettingsRequest(db, request, options = {} const acceptHeader = getHeader(request, 'accept') || ''; const contentType = getHeader(request, 'content-type') || ''; - if (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html')) { + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 302, - headers: { Location: '/admin?tab=settings' } + headers: { Location: '/admin?tab=settings¬ice=settings_saved' } }); } - return Response.json({ ok: true, settings }, { status: 200 }); + return Response.json({ ok: true, notice: 'settings_saved', settings }, { status: 200 }); } catch (err) { return handleErrorResponse(err); } @@ -2019,7 +2021,7 @@ export async function handleAdminEmergencyDisableAllRequest(db, request, options const acceptHeader = getHeader(request, 'accept') || ''; const contentType = getHeader(request, 'content-type') || ''; - if (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html')) { + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 302, headers: { Location: '/admin?tab=settings' } @@ -2149,10 +2151,11 @@ export async function handleAdminDeleteContactRequest(db, request, options = {}) await deleteMerchantContact(db, { shop, contactId }); } - if (contentType.includes('application/x-www-form-urlencoded')) { + const acceptHeader = getHeader(request, 'accept') || ''; + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 303, - headers: { Location: '/api/admin?tab=contacts' } + headers: { Location: '/admin?tab=contacts' } }); } @@ -2208,10 +2211,11 @@ export async function handleAdminDeletePracticeContactsRequest(db, request, opti deleted = await deleteMerchantPracticeContacts(db, { shop, ownerId }); } - if (contentType.includes('application/x-www-form-urlencoded')) { + const acceptHeader = getHeader(request, 'accept') || ''; + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 303, - headers: { Location: '/api/admin?tab=contacts' } + headers: { Location: '/admin?tab=contacts' } }); } @@ -2298,15 +2302,20 @@ export async function handleAdminCustomFeatureRequest(db, request, options = {}) }); } - if (contentType.includes('application/x-www-form-urlencoded')) { + const acceptHeader = getHeader(request, 'accept') || ''; + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 303, - headers: { Location: '/api/admin?tab=settings&request_sent=1' } + headers: { Location: '/admin?tab=settings¬ice=request_sent' } }); } return Response.json( - { success: true, message: 'Thank you for your request. The developer will get back to you shortly.' }, + { + success: true, + notice: 'request_sent', + message: 'Thanks, your request was sent. The developer will reply to the email you gave.' + }, { status: 200, headers: { 'Content-Type': 'application/json' } } ); } catch (err) { @@ -2376,15 +2385,20 @@ export async function handleAdminFeedbackRequest(db, request, options = {}) { }); } - if (contentType.includes('application/x-www-form-urlencoded')) { + const acceptHeader = getHeader(request, 'accept') || ''; + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { return new Response(null, { status: 303, - headers: { Location: '/api/admin?tab=settings&feedback_saved=1' } + headers: { Location: '/admin?tab=settings¬ice=feedback_saved' } }); } return Response.json( - { success: true, message: 'Thank you for your feedback!' }, + { + success: true, + notice: 'feedback_saved', + message: 'Thanks, your feedback was saved.' + }, { status: 200, headers: { 'Content-Type': 'application/json' } } ); } catch (err) { @@ -2439,6 +2453,14 @@ export async function handleAdminMarketingOptInRequest(db, request, options = {} await updateShopMarketingOptIn(db, { shop, marketingOptIn }); } + const acceptHeader = getHeader(request, 'accept') || ''; + if (!acceptHeader.includes('application/json') && (contentType.includes('application/x-www-form-urlencoded') || acceptHeader.includes('text/html'))) { + return new Response(null, { + status: 303, + headers: { Location: '/admin?tab=settings' } + }); + } + return Response.json( { success: true, marketingOptIn }, { status: 200, headers: { 'Content-Type': 'application/json' } } diff --git a/docs/BUILD_PLAN.md b/docs/BUILD_PLAN.md index a42dc4a..bc1de29 100644 --- a/docs/BUILD_PLAN.md +++ b/docs/BUILD_PLAN.md @@ -122,7 +122,7 @@ - Lifecycle: `app/uninstalled` deletes the `Session` row while keeping `ShopProfile` with `uninstalledAt` timestamp; `shop/redact` purges all shop records. - UI: Settings opt-in card displays a disabled checkbox with `"Your store contact email is still being loaded. Reload this page."` when `ShopProfile.email` is absent (never displays `"this email"`), and custom request cards prefill `replyEmail` when present. Shopper consent text uses `ShopProfile.shopName` when available. - Friendly root landing page: `GET /` (or `/admin`, `/app`) outside admin iframe with no session serves status 200 HTML with `"Practitioner Protocols runs inside your Shopify admin. Open it from your Shopify admin's Apps list."`, link to `/privacy`, and zero login or shop domain input fields. - - Automated unit test coverage: 580 passing tests across 132 suites (`npm test`). + - Automated unit test coverage: 581 passing tests across 132 suites (`npm test`). ## Later Practitioner application form · aggregate "client orders" count on protocol cards · protocol version history · Salesforce rollup via Bridge Recipes. diff --git a/test/admin.test.js b/test/admin.test.js index 2de1e67..6fd19b0 100644 --- a/test/admin.test.js +++ b/test/admin.test.js @@ -1731,6 +1731,63 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { assert.ok(html.includes('name="replyEmail"'), 'Must render custom request reply email input'); assert.ok(html.includes('custom_owner@test.myshopify.com'), 'Must pre-fill admin reply email from shopProfile'); }); + + it('renders allow-listed notice banners in Settings tab and ignores unknown notice keys', () => { + // 1. feedback_saved notice + const htmlFeedback = renderAdminHtml({ + shop: testShop, + activeTab: 'settings', + notice: 'feedback_saved' + }); + assert.ok(htmlFeedback.includes('id="settings-notice-banner"'), 'Must render settings notice banner container'); + assert.ok(htmlFeedback.includes('Polaris-Banner--statusSuccess'), 'Must have success status class'); + assert.ok(htmlFeedback.includes('Thanks, your feedback was saved.'), 'Must display feedback saved message'); + + // 2. request_sent notice + const htmlRequest = renderAdminHtml({ + shop: testShop, + activeTab: 'settings', + notice: 'request_sent' + }); + assert.ok(htmlRequest.includes('id="settings-notice-banner"')); + assert.ok(htmlRequest.includes('Thanks, your request was sent. The developer will reply to the email you gave.')); + + // 3. settings_saved notice + const htmlSettings = renderAdminHtml({ + shop: testShop, + activeTab: 'settings', + notice: 'settings_saved' + }); + assert.ok(htmlSettings.includes('id="settings-notice-banner"')); + assert.ok(htmlSettings.includes('Settings saved successfully.')); + + // 4. unknown notice value renders nothing + const htmlUnknown = renderAdminHtml({ + shop: testShop, + activeTab: 'settings', + notice: 'unknown_notice_key' + }); + assert.ok(!htmlUnknown.includes('id="settings-notice-banner"'), 'Unknown notice must not render banner'); + assert.ok(!htmlUnknown.includes('unknown_notice_key'), 'Unknown notice value must not be rendered'); + + // 5. malicious notice attempt renders nothing and does not inject XSS + const htmlMalicious = renderAdminHtml({ + shop: testShop, + activeTab: 'settings', + notice: '' + }); + assert.ok(!htmlMalicious.includes('id="settings-notice-banner"')); + assert.ok(!htmlMalicious.includes('')); + + // Script syntax verification + const matches = [...htmlFeedback.matchAll(/]*type=["']application\/json["'])>([\s\S]*?)<\/script>/gi)]; + for (let i = 0; i < matches.length; i++) { + assert.doesNotThrow( + () => new vm.Script(matches[i][1]), + `Admin script index ${i} with notice banner must parse without SyntaxError` + ); + } + }); }); describe('Admin Session Token Verification', () => { diff --git a/test/routes.test.js b/test/routes.test.js index 52f7d1f..ee7d28a 100644 --- a/test/routes.test.js +++ b/test/routes.test.js @@ -3740,7 +3740,25 @@ describe('HTTP Routes & Request Handlers (app/lib/protocols/routes.js)', () => { }); const formRes = await handleAdminCustomFeatureRequest(optinDb, formReq, { apiSecret }); assert.equal(formRes.status, 303); - assert.ok(formRes.headers.get('Location').includes('request_sent=1')); + assert.equal(formRes.headers.get('Location'), '/admin?tab=settings¬ice=request_sent'); + + // URL-encoded with Accept: application/json returns 200 JSON with notice and no redirect + const ajaxFormReq = new Request(`https://${otherShop}/api/admin/feedback/custom-request`, { + method: 'POST', + headers: { + Authorization: `Bearer ${otherToken}`, + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }, + body: 'message=Need+JSON+response&replyEmail=merchant%40example.com' + }); + const ajaxFormRes = await handleAdminCustomFeatureRequest(optinDb, ajaxFormReq, { apiSecret }); + assert.equal(ajaxFormRes.status, 200); + assert.equal(ajaxFormRes.headers.get('Location'), null); + const ajaxFormData = await ajaxFormRes.json(); + assert.equal(ajaxFormData.success, true); + assert.equal(ajaxFormData.notice, 'request_sent'); + assert.ok(ajaxFormData.message.includes('Thanks')); // 3. 4th request in same hour on customLimiter is rate-limited (HTTP 429) const res4 = await handleAdminCustomFeatureRequest(optinDb, validJsonReq('Request 4'), { apiSecret, rateLimiter: customLimiter }); @@ -3794,11 +3812,43 @@ describe('HTTP Routes & Request Handlers (app/lib/protocols/routes.js)', () => { assert.equal(res.status, 200); const data = await res.json(); assert.equal(data.success, true); + assert.equal(data.notice, 'feedback_saved'); assert.equal(feedbackDb.feedback.length, 1); assert.equal(feedbackDb.feedback[0].rating, 5); assert.equal(feedbackDb.feedback[0].message, 'Great app experience!'); assert.equal(feedbackDb.profiles[0].marketingOptIn, true); + // URL-encoded with Accept: application/json returns 200 JSON with notice and no redirect + const urlencodedJsonReq = new Request(`https://${testShop}/api/admin/feedback`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }, + body: '_is_feedback_form=1&rating=4&message=Solid+workflow&marketingOptIn=1' + }); + const urlencodedJsonRes = await handleAdminFeedbackRequest(feedbackDb, urlencodedJsonReq, { apiSecret }); + assert.equal(urlencodedJsonRes.status, 200); + assert.equal(urlencodedJsonRes.headers.get('Location'), null); + const urlencodedJsonData = await urlencodedJsonRes.json(); + assert.equal(urlencodedJsonData.success, true); + assert.equal(urlencodedJsonData.notice, 'feedback_saved'); + assert.ok(urlencodedJsonData.message.includes('Thanks')); + + // URL-encoded without Accept: application/json returns 303 redirect to /admin?tab=settings¬ice=feedback_saved + const plainFormReq = new Request(`https://${testShop}/api/admin/feedback`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: '_is_feedback_form=1&rating=5&message=Great' + }); + const plainFormRes = await handleAdminFeedbackRequest(feedbackDb, plainFormReq, { apiSecret }); + assert.equal(plainFormRes.status, 303); + assert.equal(plainFormRes.headers.get('Location'), '/admin?tab=settings¬ice=feedback_saved'); + // Invalid rating returns 400 const badRatingReq = new Request(`https://${testShop}/api/admin/feedback`, { method: 'POST',