From c4d22dcc8b44b132d67efdc10b6cd24ec1fbfb0a Mon Sep 17 00:00:00 2001 From: arsalan-arshad Date: Thu, 5 Nov 2026 20:07:51 +0500 Subject: [PATCH 1/2] fix(auth): implement Shopify token exchange for managed install, friendly root page, and UI hardening --- PROJECT_CONTEXT.md | 38 +++ README.md | 7 +- app/lib/protocols/admin.js | 24 +- app/lib/protocols/contacts.js | 10 +- app/lib/protocols/exchange.js | 218 ++++++++++++ app/lib/protocols/routes.js | 28 +- docs/BUILD_PLAN.md | 8 + docs/SPEC.md | 4 + package.json | 2 +- server.js | 98 +++++- test/admin.test.js | 18 +- test/exchange.test.js | 616 ++++++++++++++++++++++++++++++++++ test/routes.test.js | 10 + test/server.test.js | 10 +- 14 files changed, 1068 insertions(+), 23 deletions(-) create mode 100644 app/lib/protocols/exchange.js create mode 100644 test/exchange.test.js diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index ef56be5..d3563d2 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -1061,4 +1061,42 @@ Run the five spikes in a day or two on a dev store; write the answers into secti 9. **Automated Test Coverage:** - 566 unit tests passing across 123 suites (`npm test`). Zero failures. +### 2026-11-05: Shopify Managed Installation & Token Exchange Hardening (Branch fix/token-exchange) +1. **Root Cause Resolution (Empty Session & ShopProfile):** + - Apps installed through Shopify Managed Installation do not redirect through `/api/auth` -> `/api/auth/callback` on embed load. + - Consequently, the `Session` table remained empty and `ShopProfile` had no offline token to query GraphQL. + - Result: Settings card showed "contact me at this email" with no email and empty contact fields. +2. **Shopify Token Exchange Implementation (`app/lib/protocols/exchange.js`):** + - Implemented RFC 8693 token exchange via `POST https://{shop}/admin/oauth/access_token` with parameters: + - `client_id`: app API key + - `client_secret`: app API secret + - `grant_type`: `urn:ietf:params:oauth:grant-type:token-exchange` + - `subject_token`: App Bridge `id_token` (from query param on document requests or `Authorization: Bearer` on API requests) + - `subject_token_type`: `urn:ietf:params:oauth:token-type:id_token` + - `requested_token_type`: `urn:shopify:params:oauth:token-type:offline-access-token` + - `expiring`: `0` + - Requests use a strict 5-second timeout via `AbortSignal`. +3. **Session Persistence, Encryption & Profile Sync:** + - On exchange success, upserts `Session` with `id="offline_"`, `shop`, `state="authenticated"`, `isOnline=false`, `scope="read_orders"`, and AES-256-GCM encrypted `accessToken`. + - Awaits `syncShopProfile` to query Admin GraphQL (`name, email, shopOwnerName, plan, countryCodeV2`) and upsert `ShopProfile`. Failure logs a single non-PII warning and never blocks page rendering. +4. **Concurrency Guard & Negative Caching:** + - Per-shop in-flight lock (`inFlightExchanges`) deduplicates concurrent admin requests to exactly one token exchange call. + - 60-second negative cache (`negativeCache`) records failed exchanges to protect Shopify API rate limits and avoid request storms. +5. **Non-PII Error Logging & Privacy:** + - On HTTP 400 or network failure, logs strictly `[TokenExchange] failed shop= status=`. Never logs tokens, ID tokens, secrets, or response bodies. +6. **Lifecycle & Webhooks Compliance:** + - `app/uninstalled`: deletes the `Session` row for the uninstalled shop (revoking stored credentials immediately) while retaining `ShopProfile` with `uninstalledAt = NOW()`. + - `shop/redact`: permanently wipes all `Session`, `ShopProfile`, `ShopperContact`, `MerchantFeedback`, `Protocol`, and `Setting` records. + - Confirmed `shopify.app.toml` does not specify `use_legacy_install_flow`. Legacy OAuth routes in `server.js` marked as fallback only. +7. **UI Hardening & Loading States:** + - Settings tab opt-in card: if `ShopProfile.email` is missing, renders the checkbox disabled with `"Your store contact email is still being loaded. Reload this page."` (completely removes `"this email"`). + - Custom feature request card prefills `replyEmail` from `ShopProfile.email` when available, otherwise renders empty. + - Shopper consent text uses `ShopProfile.shopName` when available, falling back to shop domain (`shop`). +8. **Friendly Root Page (`GET /`, `/admin`, `/app`):** + - Direct navigation outside embedded iframe with no shop, no id_token, and no session returns status 200 HTML with security headers, `noindex, nofollow`, and friendly message: `"Practitioner Protocols runs inside your Shopify admin. Open it from your Shopify admin's Apps list."` with a link to `/privacy`. + - Contains zero `` or `
` login/domain elements to ensure compliance with Shopify App Review guidelines. +9. **Automated Test Coverage:** + - Added `test/exchange.test.js` covering RFC 8693 request parameter compliance, encrypted session write, profile sync, second-request bypass, in-flight concurrency lock deduplication, negative cache cooldown, 400 non-blocking render, privacy logging, `app/uninstalled` session cleanup, UI disabled state, and friendly root page. + - 578 unit tests passing across 132 suites (`npm test`). Zero failures. + diff --git a/README.md b/README.md index 4e8fa58..ae38f41 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 (566/566 Unit Tests Passing across 123 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 (578/578 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`). Covered by 566 automated unit tests across 123 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 offline access tokens without interactive redirects, with encrypted storage at rest via AES-256-GCM and non-PII failure logging, friendly status 200 root page, and fallback legacy OAuth. Covered by 578 automated unit tests across 132 suites. --- @@ -267,6 +267,7 @@ psql $DATABASE_URL -f prisma/migrations/20261022_add_currency_to_stat_unique_and │ └── migrations/ # Versioned SQL DDL migrations ├── test/ │ ├── token.test.js # Token entropy & format tests +│ ├── crypto.test.js # AES-256-GCM token encryption & plaintext fallback tests │ ├── validation.test.js # Input bounds & PII rejection barrier tests │ ├── permissions.test.js # Role & ownership isolation tests │ ├── attribution.test.js # Cart payload & mixed-cart attribution tests @@ -278,6 +279,8 @@ psql $DATABASE_URL -f prisma/migrations/20261022_add_currency_to_stat_unique_and │ ├── rate-limit.test.js # Sliding window rate limiter tests │ ├── webhooks.test.js # GDPR compliance & orders/paid webhook tests │ ├── routes.test.js # HTTP API controllers & router tests +│ ├── contacts.test.js # Shopper opt-in, consent & merchant feedback tests +│ ├── exchange.test.js # Shopify App Bridge token exchange & managed install tests │ ├── server.test.js # OAuth 2.0 flow, CSP headers, config guards & shopify.app.toml tests │ └── database.integration.test.js # PostgreSQL integration tests ├── server.js # Node.js server entry, OAuth flow, admin & proxy router diff --git a/app/lib/protocols/admin.js b/app/lib/protocols/admin.js index 91de7ce..ce66b5c 100644 --- a/app/lib/protocols/admin.js +++ b/app/lib/protocols/admin.js @@ -1195,7 +1195,8 @@ export function verifyAdminSessionToken(token, options = {}) { userId: payload.sub || 'gid://shopify/User/admin', shop: shopFromDest || expectedShop || '', role: 'admin', - payload + payload, + idToken: token }; } @@ -1269,11 +1270,13 @@ export function extractAdminSession(req, options = {}) { ADMIN_ERROR_CODES.UNAUTHORIZED ); } - return verifyAdminSessionToken(rawToken, { + const verifiedSession = verifyAdminSessionToken(rawToken, { apiSecret, apiKey, expectedShop: shopParam || expectedShop }); + verifiedSession.idToken = rawToken; + return verifiedSession; } // Demo fallback @@ -1906,10 +1909,17 @@ export function renderAdminHtml(options = {}) {

- + ${shopProfile?.email ? ` + + ` : ` + + `}
@@ -1942,7 +1952,7 @@ export function renderAdminHtml(options = {}) {
- +
This sends a request to the app developer. We'll only use your email to reply.
diff --git a/app/lib/protocols/contacts.js b/app/lib/protocols/contacts.js index e0c0eb4..01ee3ae 100644 --- a/app/lib/protocols/contacts.js +++ b/app/lib/protocols/contacts.js @@ -238,10 +238,18 @@ export async function saveShopperContact(db, { const ownerId = protocol.ownerId; const practiceName = protocol.practiceName || null; + let shopDisplayName = shop; + try { + const profile = await getShopProfile(db, { shop }); + if (profile?.shopName) { + shopDisplayName = profile.shopName; + } + } catch {} + // Resolve canonical consent text server-side (forged client text is ignored) const canonicalConsentText = getCanonicalConsentText(versionNum, { practiceName, - shopName: shop + shopName: shopDisplayName }); const now = new Date(); diff --git a/app/lib/protocols/exchange.js b/app/lib/protocols/exchange.js new file mode 100644 index 0000000..c7393b4 --- /dev/null +++ b/app/lib/protocols/exchange.js @@ -0,0 +1,218 @@ +/** + * @file Shopify Token Exchange Service (Shopify Managed Installation). + * + * Implements RFC 8693 token exchange for Shopify embedded applications: + * exchanges an App Bridge session token (id_token) for an offline access token + * without running the interactive browser redirect OAuth flow. + * + * Reference: https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens/token-exchange + */ + +import { encryptAccessToken } from './crypto.js'; +import { syncShopProfile } from './contacts.js'; + +export const GRANT_TYPE_TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange'; +export const TOKEN_TYPE_ID_TOKEN = 'urn:ietf:params:oauth:token-type:id_token'; +export const TOKEN_TYPE_OFFLINE_ACCESS = 'urn:shopify:params:oauth:token-type:offline-access-token'; + +/** In-flight exchange promises per shop to prevent concurrent exchange storms */ +const inFlightExchanges = new Map(); + +/** Negative result cache: maps shop domain to timestamp (ms) of failure */ +const negativeCache = new Map(); + +/** Negative cache TTL: 60 seconds */ +export const NEGATIVE_CACHE_TTL_MS = 60 * 1000; + +/** + * Resets token exchange in-memory caches (for unit and integration tests). + */ +export function _resetTokenExchangeCaches() { + inFlightExchanges.clear(); + negativeCache.clear(); +} + +/** + * Performs raw HTTP token exchange with Shopify Admin OAuth endpoint. + * Strictly logs non-sensitive status lines on failure; never logs tokens, + * id_tokens, client secrets, or response bodies. + * + * @param {{ + * shop: string, + * idToken: string, + * apiKey: string, + * apiSecret: string, + * fetchFn?: typeof fetch + * }} params + * @returns {Promise<{ accessToken: string, scope: string } | null>} + */ +export async function performTokenExchange({ + shop, + idToken, + apiKey, + apiSecret, + fetchFn = fetch +}) { + if (!shop || !idToken || !apiKey || !apiSecret) { + return null; + } + + const endpoint = `https://${shop}/admin/oauth/access_token`; + const bodyParams = new URLSearchParams({ + client_id: apiKey, + client_secret: apiSecret, + grant_type: GRANT_TYPE_TOKEN_EXCHANGE, + subject_token: idToken, + subject_token_type: TOKEN_TYPE_ID_TOKEN, + requested_token_type: TOKEN_TYPE_OFFLINE_ACCESS, + expiring: '0' + }); + + try { + const controller = typeof AbortController !== 'undefined' ? new AbortController() : null; + const timeoutId = controller ? setTimeout(() => controller.abort(), 5000) : null; + + const res = await fetchFn(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Accept': 'application/json' + }, + body: bodyParams.toString(), + signal: controller?.signal + }); + + if (timeoutId) clearTimeout(timeoutId); + + if (!res.ok) { + console.warn(`[TokenExchange] failed shop=${shop} status=${res.status}`); + return null; + } + + const data = await res.json(); + if (!data || !data.access_token) { + console.warn(`[TokenExchange] failed shop=${shop} status=502`); + return null; + } + + return { + accessToken: data.access_token, + scope: data.scope || 'read_orders' + }; + } catch (err) { + const status = err?.name === 'AbortError' ? 'timeout' : (err?.status || 'network_error'); + console.warn(`[TokenExchange] failed shop=${shop} status=${status}`); + return null; + } +} + +/** + * Ensures an offline session exists for the given shop. + * If missing and valid credentials exist, performs token exchange, upserts Session, + * and synchronizes ShopProfile via GraphQL (non-blocking on failure). + * + * Concurrency & Caching: + * - Employs a per-shop in-flight lock to deduplicate concurrent exchange requests. + * - Caches negative results for 60 seconds to protect Shopify rate limits. + * + * @param {any} db Database client + * @param {{ + * shop: string, + * idToken: string, + * apiKey: string, + * apiSecret: string, + * fetchFn?: typeof fetch + * }} params + * @returns {Promise<{ shop: string, success: boolean } | null>} + */ +export async function ensureOfflineSession(db, { + shop, + idToken, + apiKey, + apiSecret, + fetchFn = fetch +}) { + if (!db || !shop || !idToken || !apiKey || !apiSecret) { + return null; + } + + // 1. Check if offline session already exists in DB + try { + const existing = await db.query( + 'SELECT "id" FROM "Session" WHERE "shop" = $1 AND "isOnline" = false LIMIT 1', + [shop] + ); + if (existing?.rows?.length > 0) { + return { shop, success: true, existing: true }; + } + } catch (err) { + // If DB check fails, continue or return null + } + + // 2. Check 60-second negative cache + const failedAt = negativeCache.get(shop); + if (failedAt && Date.now() - failedAt < NEGATIVE_CACHE_TTL_MS) { + return null; + } + + // 3. Deduplicate concurrent requests with per-shop in-flight lock + if (inFlightExchanges.has(shop)) { + return await inFlightExchanges.get(shop); + } + + const exchangePromise = (async () => { + try { + const exchangeResult = await performTokenExchange({ + shop, + idToken, + apiKey, + apiSecret, + fetchFn + }); + + if (!exchangeResult) { + negativeCache.set(shop, Date.now()); + return null; + } + + // Success: clear negative cache + negativeCache.delete(shop); + + // Upsert Session with encrypted access token + const encryptedToken = encryptAccessToken(exchangeResult.accessToken); + await db.query( + `INSERT INTO "Session" ("id", "shop", "state", "isOnline", "scope", "accessToken") + VALUES ($1, $2, $3, false, $4, $5) + ON CONFLICT ("id") DO UPDATE SET + "shop" = EXCLUDED."shop", + "state" = EXCLUDED."state", + "scope" = EXCLUDED."scope", + "accessToken" = EXCLUDED."accessToken"`, + [`offline_${shop}`, shop, 'authenticated', exchangeResult.scope, encryptedToken] + ); + + // Synchronize ShopProfile (awaited, non-blocking on failure) + try { + await syncShopProfile(db, { + shop, + accessToken: exchangeResult.accessToken, + apiKey, + apiSecret, + fetchFn + }); + } catch (syncErr) { + console.warn(`[ShopProfile] Failed to sync profile for ${shop} on token exchange: ${syncErr?.message || 'Unknown error'}`); + } + + return { shop, success: true }; + } catch (err) { + negativeCache.set(shop, Date.now()); + return null; + } finally { + inFlightExchanges.delete(shop); + } + })(); + + inFlightExchanges.set(shop, exchangePromise); + return await exchangePromise; +} diff --git a/app/lib/protocols/routes.js b/app/lib/protocols/routes.js index a49c15b..17b4cab 100644 --- a/app/lib/protocols/routes.js +++ b/app/lib/protocols/routes.js @@ -39,6 +39,7 @@ import { } from './catalog.js'; import { generateShareToken } from './token.js'; import { renderPortalLiquid } from './portal.js'; +import { ensureOfflineSession } from './exchange.js'; import { saveShopperContact, listPractitionerContacts, @@ -89,6 +90,7 @@ export { extractAdminSession, renderAdminHtml, renderAdminBootstrapHtml, + ensureOfflineSession, SHOPIFY_DOMAIN_REGEX }; @@ -1143,11 +1145,23 @@ export async function handleAppProxyRequest(db, request, options = {}) { } } + let shopDisplayName = shop; + if (db && shop) { + try { + const profile = await getShopProfile(db, { shop }); + if (profile?.shopName) { + shopDisplayName = profile.shopName; + } + } catch { + // Non-fatal fallback + } + } + // 6. Render Liquid template const liquid = renderProtocolLiquid({ protocol, practiceName: protocol?.practiceName || '', - shopName: shop, + shopName: shopDisplayName, isLoggedInPractitioner: isHandout ? false : isLoggedInPractitioner, isHandout, handoutText, @@ -1727,10 +1741,20 @@ export async function handleAdminDashboardRequest(db, request, options = {}) { let shopProfile = options.demoData?.shopProfile || null; if (db && !session.isDemo) { + if (session.idToken) { + await ensureOfflineSession(db, { + shop, + idToken: session.idToken, + apiKey: options.apiKey, + apiSecret: options.apiSecret, + fetchFn: options.fetchFn + }); + } + let currentProfile = await getShopProfile(db, { shop }); const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000; if (!currentProfile || !currentProfile.updatedAt || new Date(currentProfile.updatedAt).getTime() < sevenDaysAgo) { - await syncShopProfile(db, { shop }); + await syncShopProfile(db, { shop, fetchFn: options.fetchFn }); currentProfile = await getShopProfile(db, { shop }); } shopProfile = currentProfile; diff --git a/docs/BUILD_PLAN.md b/docs/BUILD_PLAN.md index 3409bd6..42188fa 100644 --- a/docs/BUILD_PLAN.md +++ b/docs/BUILD_PLAN.md @@ -115,6 +115,14 @@ - CLI scripts: `scripts/contacts.mjs` listing opted-in installed shops, custom feature requests, and shopper contacts; `scripts/stats.mjs` reporting aggregate platform metrics. - Updated `/privacy`, `README.md`, `docs/SPEC.md`, and `PROJECT_CONTEXT.md` honestly stating data handling practices and unverified email disclosure. - Automated unit test coverage: 566 passing tests across 123 suites (`npm test`). +- [x] **Shopify Managed Installation & Token Exchange Hardening (IMPLEMENTED, PENDING LIVE DEV-STORE VERIFICATION)**: + - Fixed empty `Session` and `ShopProfile` bug on stores installing via Shopify Managed Installation: embedded admin requests without stored offline sessions perform RFC 8693 token exchange via `POST https://{shop}/admin/oauth/access_token` (`grant_type=urn:ietf:params:oauth:grant-type:token-exchange`, `subject_token=`, `subject_token_type=urn:ietf:params:oauth:token-type:id_token`, `requested_token_type=urn:shopify:params:oauth:token-type:offline-access-token`, `expiring=0`) with a 5s timeout. + - Upserts `Session` with `id="offline_"`, `state="authenticated"`, and AES-256-GCM encrypted `accessToken`. Calls `syncShopProfile` non-blocking to populate store name, email, plan, and country via GraphQL. + - Concurrency & Error Safeguards: Per-shop in-flight lock to deduplicate concurrent exchange requests, 60-second negative cache on exchange failure to protect rate limits, non-PII logging (`[TokenExchange] failed shop= status=`) with zero token, secret, or body exposure, and normal page rendering on 400 invalid tokens. + - 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: 578 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/docs/SPEC.md b/docs/SPEC.md index f32f7ee..132c3e5 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -68,6 +68,10 @@ Always `noindex`. Prices are always the store's live retail price — a protocol > [!NOTE] > **Decision Record (Owner Decision, 2026-11-05 — M11):** > The "zero shopper PII" rule is relaxed ONLY for an explicit, opt-in "stay in touch" contact entered by the shopper on a protocol recommendation page. Nothing else changes: browsing shoppers still have zero PII collected or stored, and opted-in contacts store NO protocolId, NO order ID, NO purchased product or health data, NO IP address, and NO user agent. + +> [!NOTE] +> **Authentication & Token Architecture (Shopify Managed Installation):** +> Under Shopify's managed installation architecture, embedded applications acquire offline access tokens via App Bridge token exchange (RFC 8693) on admin request without browser redirect loops. Offline access tokens are stored encrypted at rest using AES-256-GCM (`enc:v1:::`) when `SESSION_ENCRYPTION_KEY` is configured. Legacy OAuth routes (`/api/auth` and `/api/auth/callback`) are preserved as a fallback only. Top-level direct navigation outside the Shopify admin with no session serves a friendly, noindex status 200 landing page directing the merchant to their Apps list with a link to `/privacy`, with zero login or domain inputs. > - **Canonical Consent Enforcement:** Server-defined canonical text is enforced per version; client-supplied text is ignored and unknown versions rejected. > - **Email Verification Honesty:** The application does not send emails or verify addresses. All exports and docs honestly label contacts as `Verified = "no"` so merchants confirm subscriptions in their email tools. > - **Rate Limiting:** Dedicated sliding-window rate limit of 5 requests/hour per client key on shopper opt-in subscriptions. diff --git a/package.json b/package.json index b2a92fc..e576427 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "scripts": { "start": "node server.js", "migrate": "node scripts/migrate.js", - "test": "node --test test/token.test.js test/crypto.test.js test/validation.test.js test/permissions.test.js test/attribution.test.js test/handout.test.js test/proxy.test.js test/webhooks.test.js test/portal.test.js test/admin.test.js test/rate-limit.test.js test/routes.test.js test/catalog.test.js test/contacts.test.js test/server.test.js", + "test": "node --test test/token.test.js test/crypto.test.js test/validation.test.js test/permissions.test.js test/attribution.test.js test/handout.test.js test/proxy.test.js test/webhooks.test.js test/portal.test.js test/admin.test.js test/rate-limit.test.js test/routes.test.js test/catalog.test.js test/contacts.test.js test/server.test.js test/exchange.test.js", "test:db": "node --test test/database.integration.test.js", "test:all": "node --test test/**/*.test.js" }, diff --git a/server.js b/server.js index f9a11a6..613f191 100644 --- a/server.js +++ b/server.js @@ -425,6 +425,80 @@ export function verifyOAuthState(cookieVal, queryState, secret) { return false; } +/** + * Renders the friendly public root page (status 200). + * Displays when a merchant or visitor navigates directly to the app URL outside Shopify admin + * without shop, id_token, or session. + * Contains no shop-domain input field or login form (to comply with Shopify app review rules). + * + * @returns {string} + */ +export function renderFriendlyRootHtml() { + return ` + + + + + Practitioner Protocols + + + + +
+

Practitioner Protocols

+

Practitioner Protocols runs inside your Shopify admin. Open it from your Shopify admin's Apps list.

+

Privacy Policy

+
+ +`; +} + /** * Renders the clean, public HTML privacy policy page. * Strictly honest language, zero client PII stored, read_orders aggregate attribution only, @@ -529,7 +603,7 @@ export function renderPrivacyHtml({ contactEmail = '' } = {}) {

To operate recommendation workflows for direct-to-consumer and professional brands, the application stores only:

  • Shop Domain: The store domain (e.g. example.myshopify.com) to scope protocols and settings.
  • -
  • Offline Access Token: Stored encrypted at rest using AES-256-GCM to verify platform webhooks and authenticate merchant admin operations.
  • +
  • Offline Access Token: Acquired through Shopify managed installation using App Bridge token exchange (RFC 8693, with legacy OAuth fallback) and stored encrypted at rest using AES-256-GCM when SESSION_ENCRYPTION_KEY is configured to verify platform webhooks and authenticate merchant admin operations.
  • Practitioner Approval Records: Professional practice names and approval statuses as authorized by the merchant.
  • Protocols and Share Tokens: Protocol titles, intro messages, selected product variant identifiers (GIDs and handles), recommended quantities, usage directions, and unguessable cryptographic share tokens.
  • Aggregate Attribution Counts: Monthly aggregate order counts and attributed gross revenue per protocol and practice.
  • @@ -642,7 +716,9 @@ export function createRequestListener(options = {}) { return; } - // OAuth Install Initiation: /api/auth or /auth +// Legacy OAuth Install Initiation: /api/auth or /auth (Fallback only) + // Note: Under Shopify Managed Installation, the embedded App Bridge token exchange + // flow is primary. This legacy OAuth endpoint is kept as a fallback. if (pathname === '/api/auth' || pathname === '/auth') { const shop = (url.searchParams.get('shop') || '').toLowerCase().trim(); if (!shop || !SHOPIFY_DOMAIN_REGEX.test(shop)) { @@ -667,7 +743,8 @@ export function createRequestListener(options = {}) { return; } - // OAuth Callback: /api/auth/callback or /auth/callback +// Legacy OAuth Callback: /api/auth/callback or /auth/callback (Fallback only) + // Note: Primary authentication uses Shopify managed install + App Bridge token exchange. if (pathname === '/api/auth/callback' || pathname === '/auth/callback') { const shop = (url.searchParams.get('shop') || '').toLowerCase().trim(); const code = url.searchParams.get('code'); @@ -818,7 +895,7 @@ export function createRequestListener(options = {}) { if (databaseUrl && hasSession) { const webReq = await toWebRequest(req); let webRes; - const handlerOpts = { apiSecret, apiKey, isDemoMode: false }; + const handlerOpts = { apiSecret, apiKey, isDemoMode: false, fetchFn: options.fetchFn }; if (pathname === '/api/admin/practitioners') { webRes = await handleAdminPractitionersListRequest(pool, webReq, handlerOpts); @@ -970,6 +1047,7 @@ export function createRequestListener(options = {}) { apiSecret, apiKey, isDemoMode: false, + fetchFn: options.fetchFn, }); // If token is invalid/expired (401) and request is inside embedded iframe, @@ -1018,8 +1096,16 @@ export function createRequestListener(options = {}) { return; } - res.writeHead(401, { 'Content-Type': 'text/plain' }); - res.end('Authentication required: Missing shop or admin session'); + // Friendly root page: when GET / (or /admin, /app) arrives with no shop, no id_token and no session + const rootHtml = renderFriendlyRootHtml(); + res.writeHead(200, { + 'Content-Type': 'text/html; charset=utf-8', + 'Content-Security-Policy': "default-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'none';", + 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'strict-origin-when-cross-origin', + 'X-Robots-Tag': 'noindex, nofollow' + }); + res.end(rootHtml); return; } diff --git a/test/admin.test.js b/test/admin.test.js index 87e63e5..2de1e67 100644 --- a/test/admin.test.js +++ b/test/admin.test.js @@ -53,7 +53,8 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { protocols: (initialState.protocols || []).map(p => ({ ...p })), lines: (initialState.lines || []).map(l => ({ ...l })), settings: (initialState.settings || []).map(s => ({ ...s })), - orderStats: (initialState.orderStats || []).map(o => ({ ...o })) + orderStats: (initialState.orderStats || []).map(o => ({ ...o })), + sessions: (initialState.sessions || []).map(s => ({ ...s })) }; return { @@ -365,6 +366,12 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { return { rows }; } + if (sql.includes('FROM "Session"')) { + const shop = params[0]; + const session = state.sessions.find(s => s.shop === shop); + return { rows: session ? [session] : [] }; + } + return { rows: [] }; } }; @@ -1224,6 +1231,15 @@ describe('Merchant Admin Layer (app/lib/protocols/admin.js)', () => { const testToken = 'tok_live_1022'; const mockDb = createMockDb({ + sessions: [ + { + id: `offline_${webhookShop}`, + shop: webhookShop, + accessToken: 'mock_token', + isOnline: false, + scope: 'read_orders' + } + ], profiles: [ { id: 'prof_1', diff --git a/test/exchange.test.js b/test/exchange.test.js new file mode 100644 index 0000000..a14d17c --- /dev/null +++ b/test/exchange.test.js @@ -0,0 +1,616 @@ +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import vm from 'node:vm'; +import { + performTokenExchange, + ensureOfflineSession, + _resetTokenExchangeCaches, + GRANT_TYPE_TOKEN_EXCHANGE, + TOKEN_TYPE_ID_TOKEN, + TOKEN_TYPE_OFFLINE_ACCESS, + NEGATIVE_CACHE_TTL_MS +} from '../app/lib/protocols/exchange.js'; +import { decryptAccessToken } from '../app/lib/protocols/crypto.js'; +import { renderAdminHtml, createAdminSessionToken } from '../app/lib/protocols/admin.js'; +import { handleAdminDashboardRequest } from '../app/lib/protocols/routes.js'; +import { handleAppUninstalled } from '../app/lib/protocols/webhooks.js'; +import { getCanonicalConsentText, saveShopperContact } from '../app/lib/protocols/contacts.js'; +import { createRequestListener } from '../server.js'; + +describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/exchange.js)', () => { + const testShop = 'wellness-store.myshopify.com'; + const apiKey = 'test_api_client_key_123'; + const apiSecret = 'test_api_client_secret_xyz'; + const validIdToken = createAdminSessionToken({ + userId: 'gid://shopify/User/admin_1', + shop: testShop, + apiKey, + expiresInSec: 3600 + }, apiSecret); + + beforeEach(() => { + _resetTokenExchangeCaches(); + process.env.SESSION_ENCRYPTION_KEY = '0123456789abcdef0123456789abcdef'; + }); + + afterEach(() => { + _resetTokenExchangeCaches(); + }); + + /** + * High-fidelity in-memory SQL mock DB tracking state and queries. + */ + function createTestDb(initial = {}) { + const state = { + sessions: (initial.sessions || []).map(s => ({ ...s })), + shopProfiles: (initial.shopProfiles || []).map(p => ({ ...p })), + protocols: (initial.protocols || []).map(pr => ({ ...pr })), + shopperContacts: [], + queries: [] + }; + + return { + state, + async query(sql, params = []) { + state.queries.push({ sql, params }); + + // DELETE Session (e.g. app/uninstalled) + if (sql.includes('DELETE FROM "Session"')) { + const shop = params[0]; + const before = state.sessions.length; + state.sessions = state.sessions.filter(s => s.shop !== shop); + return { rowCount: before - state.sessions.length, rows: [] }; + } + + // SELECT Session + if (sql.includes('SELECT') && sql.includes('FROM "Session"')) { + const shop = params[0]; + const session = state.sessions.find(s => s.shop === shop && (params.length === 1 || s.isOnline === false)); + return { rows: session ? [{ ...session }] : [] }; + } + + // INSERT / UPSERT Session + if (sql.includes('INSERT INTO "Session"')) { + const [id, shop, stateVal, isOnline, scope, accessToken] = [ + params[0], params[1], params[2], false, params[3], params[4] + ]; + const idx = state.sessions.findIndex(s => s.id === id); + const row = { id, shop, state: stateVal, isOnline, scope, accessToken }; + if (idx >= 0) { + state.sessions[idx] = row; + } else { + state.sessions.push(row); + } + return { rowCount: 1, rows: [row] }; + } + + // SELECT ShopProfile + if (sql.includes('FROM "ShopProfile"') && sql.includes('"shop" = $1')) { + const shop = params[0]; + const profile = state.shopProfiles.find(p => p.shop === shop); + return { rows: profile ? [{ ...profile }] : [] }; + } + + // INSERT / UPSERT ShopProfile + if (sql.includes('INSERT INTO "ShopProfile"')) { + const [shop, shopName, ownerName, email, planName, country] = params; + const idx = state.shopProfiles.findIndex(p => p.shop === shop); + const row = { + id: `prof_${shop}`, + shop, + shopName, + ownerName, + email, + planName, + country, + installedAt: new Date().toISOString(), + uninstalledAt: null, + marketingOptIn: false, + updatedAt: new Date().toISOString() + }; + if (idx >= 0) { + state.shopProfiles[idx] = { ...state.shopProfiles[idx], ...row }; + } else { + state.shopProfiles.push(row); + } + return { rowCount: 1, rows: [row] }; + } + + // UPDATE ShopProfile uninstalledAt (app/uninstalled) + if (sql.includes('UPDATE "ShopProfile"') && sql.includes('"uninstalledAt" = NOW()')) { + const shop = params[0]; + const prof = state.shopProfiles.find(p => p.shop === shop); + if (prof) { + prof.uninstalledAt = new Date().toISOString(); + prof.updatedAt = new Date().toISOString(); + } + return { rowCount: prof ? 1 : 0, rows: prof ? [prof] : [] }; + } + + // SELECT Protocol + if (sql.includes('FROM "Protocol"') && (sql.includes('token') || sql.includes('"token"'))) { + const token = params.find(p => typeof p === 'string' && p.startsWith('tok_')); + const proto = state.protocols.find(p => p.token === token); + return { rows: proto ? [{ ...proto }] : [] }; + } + + // INSERT ShopperContact + if (sql.includes('INSERT INTO "ShopperContact"')) { + const [shop, ownerId, email, firstName, consentText, consentVersion, consentedAt] = params; + state.shopperContacts.push({ shop, ownerId, email, firstName, consentText, consentVersion, consentedAt }); + return { rowCount: 1, rows: [{ id: 'sc_1' }] }; + } + + return { rows: [] }; + } + }; + } + + describe('1. Raw Token Exchange Request Specifications', () => { + it('sends POST request to https://{shop}/admin/oauth/access_token with exact RFC 8693 parameters matching docs', async () => { + let capturedUrl = ''; + let capturedOptions = null; + + const fakeFetch = async (url, options) => { + capturedUrl = String(url); + capturedOptions = options; + return { + ok: true, + status: 200, + async json() { + return { + access_token: 'mock_shpat_offline_token_test_123', + scope: 'read_orders' + }; + } + }; + }; + + const result = await performTokenExchange({ + shop: testShop, + idToken: validIdToken, + apiKey, + apiSecret, + fetchFn: fakeFetch + }); + + assert.ok(result); + assert.equal(result.accessToken, 'mock_shpat_offline_token_test_123'); + assert.equal(result.scope, 'read_orders'); + + // Verify endpoint and method + assert.equal(capturedUrl, `https://${testShop}/admin/oauth/access_token`); + assert.equal(capturedOptions.method, 'POST'); + assert.equal(capturedOptions.headers['Content-Type'], 'application/x-www-form-urlencoded'); + assert.equal(capturedOptions.headers['Accept'], 'application/json'); + + // Verify exact URL-encoded body parameters matching Shopify token exchange docs + const bodyParams = new URLSearchParams(capturedOptions.body); + assert.equal(bodyParams.get('client_id'), apiKey); + assert.equal(bodyParams.get('client_secret'), apiSecret); + assert.equal(bodyParams.get('grant_type'), GRANT_TYPE_TOKEN_EXCHANGE); + assert.equal(bodyParams.get('subject_token'), validIdToken); + assert.equal(bodyParams.get('subject_token_type'), TOKEN_TYPE_ID_TOKEN); + assert.equal(bodyParams.get('requested_token_type'), TOKEN_TYPE_OFFLINE_ACCESS); + assert.equal(bodyParams.get('expiring'), '0'); + }); + }); + + describe('2. Session Persistence, Encryption & Profile Sync', () => { + it('exchange success writes an encrypted Session row and synchronizes ShopProfile', async () => { + const db = createTestDb(); + let exchangeCalls = 0; + let graphqlCalls = 0; + + const fakeFetch = async (url, options) => { + const urlStr = String(url); + if (urlStr.includes('/admin/oauth/access_token')) { + exchangeCalls++; + return { + ok: true, + status: 200, + async json() { + return { access_token: 'mock_offline_raw_token_xyz', scope: 'read_orders' }; + } + }; + } + if (urlStr.includes('/admin/api/')) { + graphqlCalls++; + return { + ok: true, + status: 200, + async json() { + return { + data: { + shop: { + name: 'Elite Natural Health', + email: 'owner@elitenaturalhealth.com', + shopOwnerName: 'Dr. Jane Smith', + plan: { publicDisplayName: 'Shopify Plus' }, + billingAddress: { countryCodeV2: 'CA' } + } + } + }; + } + }; + } + throw new Error(`Unexpected URL: ${urlStr}`); + }; + + const res = await ensureOfflineSession(db, { + shop: testShop, + idToken: validIdToken, + apiKey, + apiSecret, + fetchFn: fakeFetch + }); + + assert.ok(res); + assert.equal(res.success, true); + assert.equal(exchangeCalls, 1); + assert.equal(graphqlCalls, 1); + + // Verify Session row + const savedSession = db.state.sessions.find(s => s.shop === testShop); + assert.ok(savedSession, 'Session row must be written'); + assert.equal(savedSession.id, `offline_${testShop}`); + assert.equal(savedSession.isOnline, false); + assert.equal(savedSession.state, 'authenticated'); + assert.equal(savedSession.scope, 'read_orders'); + + // Verify token encryption format enc:v1::: + assert.match(savedSession.accessToken, /^enc:v1:[0-9a-f]{24}:[0-9a-f]{32}:[0-9a-f]+$/); + const decrypted = decryptAccessToken(savedSession.accessToken); + assert.equal(decrypted, 'mock_offline_raw_token_xyz'); + + // Verify ShopProfile was synced + const savedProfile = db.state.shopProfiles.find(p => p.shop === testShop); + assert.ok(savedProfile, 'ShopProfile row must be written'); + assert.equal(savedProfile.shopName, 'Elite Natural Health'); + assert.equal(savedProfile.email, 'owner@elitenaturalhealth.com'); + assert.equal(savedProfile.ownerName, 'Dr. Jane Smith'); + assert.equal(savedProfile.planName, 'Shopify Plus'); + assert.equal(savedProfile.country, 'CA'); + }); + + it('second request does not exchange again when Session already exists', async () => { + const db = createTestDb({ + sessions: [ + { + id: `offline_${testShop}`, + shop: testShop, + isOnline: false, + scope: 'read_orders', + accessToken: 'enc:mock_existing_token' + } + ] + }); + + let fetchCalled = false; + const fakeFetch = async () => { + fetchCalled = true; + throw new Error('Should not call fetch when session exists'); + }; + + const res = await ensureOfflineSession(db, { + shop: testShop, + idToken: validIdToken, + apiKey, + apiSecret, + fetchFn: fakeFetch + }); + + assert.ok(res); + assert.equal(res.existing, true); + assert.equal(fetchCalled, false, 'Must not call fetch when offline session is present'); + }); + }); + + describe('3. Concurrency Lock & Deduplication', () => { + it('two concurrent requests trigger exactly one token exchange request', async () => { + const db = createTestDb(); + let exchangeCalls = 0; + + const fakeFetch = async (url) => { + const urlStr = String(url); + if (urlStr.includes('/admin/oauth/access_token')) { + exchangeCalls++; + // Simulate slight network latency + await new Promise(r => setTimeout(r, 25)); + return { + ok: true, + status: 200, + async json() { + return { access_token: 'mock_concurrent_token_456', scope: 'read_orders' }; + } + }; + } + return { + ok: true, + status: 200, + async json() { + return { data: { shop: { name: 'Concurrent Shop', email: 'c@example.com' } } }; + } + }; + }; + + const [res1, res2] = await Promise.all([ + ensureOfflineSession(db, { shop: testShop, idToken: validIdToken, apiKey, apiSecret, fetchFn: fakeFetch }), + ensureOfflineSession(db, { shop: testShop, idToken: validIdToken, apiKey, apiSecret, fetchFn: fakeFetch }) + ]); + + assert.ok(res1); + assert.ok(res2); + assert.equal(res1.success, true); + assert.equal(res2.success, true); + assert.equal(exchangeCalls, 1, 'In-flight lock must deduplicate concurrent exchange requests to exactly 1'); + }); + }); + + describe('4. Error Handling, Privacy Logging & Negative Cache', () => { + it('logs non-PII status line on 400 response without leaking tokens or response body, and caches failure', async () => { + const db = createTestDb(); + const origWarn = console.warn; + const warnings = []; + console.warn = (...args) => warnings.push(args.join(' ')); + + let fetchCount = 0; + const fakeFetch = async () => { + fetchCount++; + return { + ok: false, + status: 400, + async json() { + return { error: 'invalid_subject_token', error_description: 'Token expired' }; + } + }; + }; + + try { + const res = await ensureOfflineSession(db, { + shop: testShop, + idToken: validIdToken, + apiKey, + apiSecret, + fetchFn: fakeFetch + }); + + assert.equal(res, null); + assert.equal(fetchCount, 1); + + // Verify log: [TokenExchange] failed shop= status=400 + assert.equal(warnings.length, 1); + assert.equal(warnings[0], `[TokenExchange] failed shop=${testShop} status=400`); + assert.ok(!warnings[0].includes(validIdToken)); + assert.ok(!warnings[0].includes(apiKey)); + assert.ok(!warnings[0].includes(apiSecret)); + assert.ok(!warnings[0].includes('invalid_subject_token')); + + // Verify Negative Cache (60 seconds): immediate second attempt skips fetch + const res2 = await ensureOfflineSession(db, { + shop: testShop, + idToken: validIdToken, + apiKey, + apiSecret, + fetchFn: fakeFetch + }); + assert.equal(res2, null); + assert.equal(fetchCount, 1, 'Negative cache must prevent hammering Shopify during the 60s cooldown'); + } finally { + console.warn = origWarn; + } + }); + + it('400 token exchange failure still allows handleAdminDashboardRequest to render page normally', async () => { + const db = createTestDb(); + const fakeFetch = async () => ({ + ok: false, + status: 400, + async json() { return { error: 'invalid_subject_token' }; } + }); + + const req = new Request(`https://${testShop}/admin?tab=settings`, { + headers: { Authorization: `Bearer ${validIdToken}` } + }); + + const res = await handleAdminDashboardRequest(db, req, { + apiKey, + apiSecret, + expectedShop: testShop, + fetchFn: fakeFetch + }); + + assert.equal(res.status, 200); + const html = await res.text(); + assert.ok(html.includes('Polaris-Page')); + assert.ok(html.includes('Contact & feedback')); + // Verify inline scripts parse cleanly + const scriptMatches = [...html.matchAll(/]*>([\s\S]*?)<\/script>/gi)]; + for (const match of scriptMatches) { + if (!match[0].includes('src=')) { + assert.doesNotThrow(() => new vm.Script(match[1])); + } + } + }); + }); + + describe('5. App Uninstallation Behavior', () => { + it('app/uninstalled deletes Session row but preserves ShopProfile with uninstalledAt timestamp', async () => { + const db = createTestDb({ + sessions: [ + { id: `offline_${testShop}`, shop: testShop, isOnline: false, accessToken: 'token' } + ], + shopProfiles: [ + { shop: testShop, shopName: 'Herbal Wellness', email: 'info@herbal.com', uninstalledAt: null } + ] + }); + + const uninstalledResult = await handleAppUninstalled(db, { domain: testShop }); + assert.equal(uninstalledResult.success, true); + assert.equal(uninstalledResult.sessionsRevoked, 1); + + // Session row deleted + assert.equal(db.state.sessions.length, 0); + + // ShopProfile preserved with uninstalledAt set + const profile = db.state.shopProfiles.find(p => p.shop === testShop); + assert.ok(profile); + assert.ok(profile.uninstalledAt); + }); + }); + + describe('6. UI Hardening: Settings Opt-In Card & Custom Requests', () => { + it('Settings opt-in card shows disabled checkbox with reload text when ShopProfile.email is missing, and never shows "this email"', () => { + const htmlWithoutEmail = renderAdminHtml({ + shop: testShop, + apiKey, + profiles: [], + starters: [], + report: { summary: { totalOrders: 0, totalUnits: 0, totalRevenueFormatted: '$0.00' }, rows: [] }, + settings: { identityMode: 'tag' }, + shopProfile: null, // missing email + activeTab: 'settings' + }); + + assert.ok(!htmlWithoutEmail.includes('this email')); + assert.ok(htmlWithoutEmail.includes('Your store contact email is still being loaded. Reload this page.')); + assert.ok(htmlWithoutEmail.includes('disabled')); + }); + + it('Settings opt-in card displays merchant email when ShopProfile.email is present', () => { + const htmlWithEmail = renderAdminHtml({ + shop: testShop, + apiKey, + profiles: [], + starters: [], + report: { summary: { totalOrders: 0, totalUnits: 0, totalRevenueFormatted: '$0.00' }, rows: [] }, + settings: { identityMode: 'tag' }, + shopProfile: { email: 'drjane@integrative.clinic', marketingOptIn: false }, + activeTab: 'settings' + }); + + assert.ok(!htmlWithEmail.includes('this email')); + assert.ok(htmlWithEmail.includes('drjane@integrative.clinic')); + assert.ok(!htmlWithEmail.includes('Your store contact email is still being loaded.')); + }); + + it('custom request card prefills replyEmail from ShopProfile.email when present, and leaves empty when absent', () => { + const htmlPrefilled = renderAdminHtml({ + shop: testShop, + apiKey, + profiles: [], + starters: [], + report: { summary: { totalOrders: 0, totalUnits: 0, totalRevenueFormatted: '$0.00' }, rows: [] }, + settings: { identityMode: 'tag' }, + shopProfile: { email: 'prefilled@shop.com' }, + activeTab: 'settings' + }); + assert.ok(htmlPrefilled.includes('value="prefilled@shop.com"')); + + const htmlEmpty = renderAdminHtml({ + shop: testShop, + apiKey, + profiles: [], + starters: [], + report: { summary: { totalOrders: 0, totalUnits: 0, totalRevenueFormatted: '$0.00' }, rows: [] }, + settings: { identityMode: 'tag' }, + shopProfile: null, + activeTab: 'settings' + }); + assert.ok(htmlEmpty.includes('name="replyEmail" maxlength="254" value=""')); + }); + }); + + describe('7. Shopper Consent Text Resolution', () => { + it('uses ShopProfile.shopName in canonical consent text when available, falling back to shop domain', async () => { + const dbWithShopName = createTestDb({ + shopProfiles: [ + { shop: testShop, shopName: 'Summit Holistic Health' } + ], + protocols: [ + { id: 'proto_1', shop: testShop, token: 'tok_summit', ownerId: 'gid://shopify/Customer/1', practiceName: 'Summit Care', status: 'active' } + ] + }); + + await saveShopperContact(dbWithShopName, { + shop: testShop, + token: 'tok_summit', + email: 'patient@example.com', + consent: true + }); + + const contact = dbWithShopName.state.shopperContacts[0]; + assert.ok(contact); + assert.equal( + contact.consentText, + 'I agree to receive emails from Summit Care and Summit Holistic Health with product recommendations and offers. I can unsubscribe at any time.' + ); + + // Fallback when ShopProfile is absent + const dbWithoutShopName = createTestDb({ + protocols: [ + { id: 'proto_2', shop: testShop, token: 'tok_fallback', ownerId: 'gid://shopify/Customer/2', practiceName: 'Fallback Care', status: 'active' } + ] + }); + + await saveShopperContact(dbWithoutShopName, { + shop: testShop, + token: 'tok_fallback', + email: 'patient2@example.com', + consent: true + }); + + const contact2 = dbWithoutShopName.state.shopperContacts[0]; + assert.ok(contact2); + assert.equal( + contact2.consentText, + `I agree to receive emails from Fallback Care and ${testShop} with product recommendations and offers. I can unsubscribe at any time.` + ); + }); + }); + + describe('8. Friendly Root Page (GET /)', () => { + it('returns status 200, security headers, noindex, friendly copy with link to /privacy, and no login or domain input field', async () => { + const listener = createRequestListener({ + databaseUrl: 'postgresql://fake:fake@localhost:5432/fake', + shopifyApiSecret: apiSecret, + shopifyApiKey: apiKey + }); + + let responseStatus = 0; + const responseHeaders = {}; + let responseBody = ''; + + const req = { + method: 'GET', + url: '/', + headers: { host: 'app.example.com' }, + [Symbol.asyncIterator]: async function* () {} + }; + + const res = { + setHeader(k, v) { responseHeaders[k.toLowerCase()] = v; }, + writeHead(status, headers = {}) { + responseStatus = status; + for (const [k, v] of Object.entries(headers)) { + responseHeaders[k.toLowerCase()] = v; + } + }, + end(data) { responseBody = data || ''; } + }; + + await listener(req, res); + + assert.equal(responseStatus, 200); + assert.ok(responseHeaders['content-type'].includes('text/html')); + assert.equal(responseHeaders['x-robots-tag'], 'noindex, nofollow'); + assert.equal(responseHeaders['x-content-type-options'], 'nosniff'); + assert.ok(responseBody.includes('Practitioner Protocols runs inside your Shopify admin. Open it from your Shopify admin\'s Apps list.')); + assert.ok(responseBody.includes('href="/privacy"')); + + // Ensure no shop-domain input field and no login form (Shopify app review compliance) + assert.ok(!responseBody.includes(' { return { rows }; } + if (sql.includes('FROM "Session"')) { + const shop = params[0]; + const session = state.sessions.find(s => s.shop === shop); + return { rows: session ? [session] : [] }; + } + + if (sql.includes('INSERT INTO "Session"')) { + return { rowCount: 1, rows: [{ id: params[0] }] }; + } + return { rows: [] }; } }; diff --git a/test/server.test.js b/test/server.test.js index a21bf52..07bdb2b 100644 --- a/test/server.test.js +++ b/test/server.test.js @@ -950,7 +950,7 @@ describe('Server & Configuration Hardening (server.js, shopify.app.toml, README. assert.ok(res.headers.Location.includes(prodShop)); }); - it('GET / returns 401 on top-level direct navigation with no shop and no session', async () => { + it('GET / serves friendly 200 root page on top-level direct navigation with no shop and no session', async () => { const req = createMockReq({ method: 'GET', url: '/', @@ -958,8 +958,12 @@ describe('Server & Configuration Hardening (server.js, shopify.app.toml, README. const res = createMockRes(); await prodListener(req, res); - assert.equal(res.statusCode, 401); - assert.ok(res.body.includes('Authentication required')); + assert.equal(res.statusCode, 200); + assert.ok(res.headers['Content-Type'].includes('text/html')); + assert.ok(res.body.includes('Practitioner Protocols runs inside your Shopify admin. Open it from your Shopify admin\'s Apps list.')); + assert.ok(res.body.includes('href="/privacy"')); + assert.ok(!res.body.includes(' { From 210476ac20aa9828816b376f94e83673894dcf26 Mon Sep 17 00:00:00 2001 From: arsalan-arshad Date: Fri, 6 Nov 2026 01:43:09 +0500 Subject: [PATCH 2/2] fix(auth): send token exchange payload as JSON and add GraphQL sync timeout --- app/lib/protocols/contacts.js | 25 +++++++++++++------- app/lib/protocols/exchange.js | 10 ++++---- test/contacts.test.js | 44 ++++++++++++++++++++++++----------- test/exchange.test.js | 20 ++++++++-------- 4 files changed, 63 insertions(+), 36 deletions(-) diff --git a/app/lib/protocols/contacts.js b/app/lib/protocols/contacts.js index 01ee3ae..cd600aa 100644 --- a/app/lib/protocols/contacts.js +++ b/app/lib/protocols/contacts.js @@ -632,14 +632,23 @@ export async function syncShopProfile(db, { shop, accessToken = null, fetchFn = } }`; - const res = await fetchFn(`https://${shop}/admin/api/2026-10/graphql.json`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Shopify-Access-Token': token - }, - body: JSON.stringify({ query }) - }); + const controller = typeof AbortController !== 'undefined' ? new AbortController() : null; + const timeoutId = controller ? setTimeout(() => controller.abort(), 5000) : null; + + let res; + try { + res = await fetchFn(`https://${shop}/admin/api/2026-10/graphql.json`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Shopify-Access-Token': token + }, + body: JSON.stringify({ query }), + signal: controller?.signal + }); + } finally { + if (timeoutId) clearTimeout(timeoutId); + } if (!res.ok) { console.warn(`[ShopProfile] Failed to fetch shop profile for ${shop}: HTTP ${res.status}`); diff --git a/app/lib/protocols/exchange.js b/app/lib/protocols/exchange.js index c7393b4..07ee363 100644 --- a/app/lib/protocols/exchange.js +++ b/app/lib/protocols/exchange.js @@ -58,15 +58,15 @@ export async function performTokenExchange({ } const endpoint = `https://${shop}/admin/oauth/access_token`; - const bodyParams = new URLSearchParams({ + const payload = { client_id: apiKey, client_secret: apiSecret, grant_type: GRANT_TYPE_TOKEN_EXCHANGE, subject_token: idToken, subject_token_type: TOKEN_TYPE_ID_TOKEN, requested_token_type: TOKEN_TYPE_OFFLINE_ACCESS, - expiring: '0' - }); + expiring: 0 + }; try { const controller = typeof AbortController !== 'undefined' ? new AbortController() : null; @@ -75,10 +75,10 @@ export async function performTokenExchange({ const res = await fetchFn(endpoint, { method: 'POST', headers: { - 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-Type': 'application/json', 'Accept': 'application/json' }, - body: bodyParams.toString(), + body: JSON.stringify(payload), signal: controller?.signal }); diff --git a/test/contacts.test.js b/test/contacts.test.js index 0c26472..60aefaa 100644 --- a/test/contacts.test.js +++ b/test/contacts.test.js @@ -667,23 +667,29 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', }; // 1. Success path - const fakeFetchSuccess = async () => ({ - ok: true, - json: async () => ({ - data: { - shop: { - name: 'Holistic Care', - email: 'info@holistic.com', - shopOwnerName: 'Alice Green', - plan: { publicDisplayName: 'Advanced' }, - billingAddress: { countryCodeV2: 'GB' } + let capturedSignal = null; + const fakeFetchSuccess = async (url, options) => { + capturedSignal = options?.signal; + return { + ok: true, + json: async () => ({ + data: { + shop: { + name: 'Holistic Care', + email: 'info@holistic.com', + shopOwnerName: 'Alice Green', + plan: { publicDisplayName: 'Advanced' }, + billingAddress: { countryCodeV2: 'GB' } + } } - } - }) - }); + }) + }; + }; const res = await syncShopProfile(mockDb, { shop: 'holistic.myshopify.com', fetchFn: fakeFetchSuccess }); assert.ok(res); + assert.ok(capturedSignal, 'Must pass AbortSignal to GraphQL fetch'); + assert.equal(typeof capturedSignal.aborted, 'boolean'); assert.equal(res.shopName, 'Holistic Care'); assert.equal(res.email, 'info@holistic.com'); assert.equal(res.ownerName, 'Alice Green'); @@ -705,6 +711,18 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', assert.equal(failRes, null); assert.equal(warnings.length, 1); assert.match(warnings[0], /Failed to fetch shop profile/); + + // 3. Aborted/timed out fetch must be handled gracefully without throwing + const fakeFetchTimeout = async () => { + const err = new Error('The operation was aborted'); + err.name = 'AbortError'; + throw err; + }; + + const timeoutRes = await syncShopProfile(mockDb, { shop: 'holistic.myshopify.com', fetchFn: fakeFetchTimeout }); + assert.equal(timeoutRes, null); + assert.equal(warnings.length, 2); + assert.match(warnings[1], /The operation was aborted/); } finally { console.warn = origWarn; } diff --git a/test/exchange.test.js b/test/exchange.test.js index a14d17c..aff2585 100644 --- a/test/exchange.test.js +++ b/test/exchange.test.js @@ -181,18 +181,18 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ // Verify endpoint and method assert.equal(capturedUrl, `https://${testShop}/admin/oauth/access_token`); assert.equal(capturedOptions.method, 'POST'); - assert.equal(capturedOptions.headers['Content-Type'], 'application/x-www-form-urlencoded'); + assert.equal(capturedOptions.headers['Content-Type'], 'application/json'); assert.equal(capturedOptions.headers['Accept'], 'application/json'); - // Verify exact URL-encoded body parameters matching Shopify token exchange docs - const bodyParams = new URLSearchParams(capturedOptions.body); - assert.equal(bodyParams.get('client_id'), apiKey); - assert.equal(bodyParams.get('client_secret'), apiSecret); - assert.equal(bodyParams.get('grant_type'), GRANT_TYPE_TOKEN_EXCHANGE); - assert.equal(bodyParams.get('subject_token'), validIdToken); - assert.equal(bodyParams.get('subject_token_type'), TOKEN_TYPE_ID_TOKEN); - assert.equal(bodyParams.get('requested_token_type'), TOKEN_TYPE_OFFLINE_ACCESS); - assert.equal(bodyParams.get('expiring'), '0'); + // Verify exact JSON body parameters matching Shopify token exchange docs + const bodyParams = JSON.parse(capturedOptions.body); + assert.equal(bodyParams.client_id, apiKey); + assert.equal(bodyParams.client_secret, apiSecret); + assert.equal(bodyParams.grant_type, GRANT_TYPE_TOKEN_EXCHANGE); + assert.equal(bodyParams.subject_token, validIdToken); + assert.equal(bodyParams.subject_token_type, TOKEN_TYPE_ID_TOKEN); + assert.equal(bodyParams.requested_token_type, TOKEN_TYPE_OFFLINE_ACCESS); + assert.equal(bodyParams.expiring, 0); }); });