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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions PROJECT_CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>"`, `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=<shop> status=<n>`. 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 `<input>` or `<form>` 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.


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

> **Open-Source (MIT)** | Built for the Shopify Merchant & Developer Community | Open for PRs & Discussions
>
> ⚙️ **Status: Complete Engine, Admin & Storefront Modules Verified (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**

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

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

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

---

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading