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
23 changes: 23 additions & 0 deletions PROJECT_CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -1117,5 +1117,28 @@ Run the five spikes in a day or two on a dev store; write the answers into secti
- Added test verifying truncated single-line logging on GraphQL `errors`.
- 578 unit tests passing across 132 suites (`npm test`).

### 2026-11-06: Expiring Offline Access Tokens for Shopify Managed Installation (Branch fix/expiring-offline-token)
1. **Root Cause Resolution (Admin GraphQL HTTP 403 on Non-Expiring Offline Tokens):**
- Live testing showed token exchange succeeded, but subsequent Admin GraphQL calls failed with HTTP 403 ("Non-expiring access tokens are no longer accepted for the Admin API").
- Shopify requires all public apps calling the Admin API to use expiring offline access tokens (1-hour lifespan, `expires_in: 3600`) by setting `expiring: 1` during token exchange.
2. **RFC 8693 Token Exchange (`expiring: 1`):**
- `performTokenExchange` in `app/lib/protocols/exchange.js` updated to pass `expiring: 1` in the JSON request body.
- Parses and returns `{ accessToken, scope, expiresIn, refreshToken, refreshTokenExpiresIn }`.
3. **Session Usability & Automatic Re-Exchange on Admin Request:**
- In `ensureOfflineSession`, a Session row is treated as USABLE only if `expires` is NOT NULL and `expires > now + 5 minutes`.
- If missing, NULL `expires` (legacy non-expiring token), or expiring within 5 minutes, automatically performs an RFC 8693 token exchange using the fresh `id_token` present on every admin request.
- Does NOT store the `refreshToken` (leaving `Session.refreshToken` and `Session.refreshTokenExpires` NULL for fewer secrets at rest).
- Does NOT build a separate background refresh flow: Practitioner Protocols executes Admin API calls strictly in response to embedded-admin requests, so re-exchange via the incoming `id_token` on admin load is sufficient.
4. **Immediate & Fallback Profile Sync:**
- On successful token exchange, immediately invokes `syncShopProfile` with the newly minted access token in the same request.
- In `syncShopProfile` fallback lookup, checks that the stored session has non-null `expires > now + 5 minutes` before attempting Admin GraphQL queries.
- On non-OK HTTP response from Admin GraphQL, logs the HTTP status and first 200 characters of response text (`[ShopProfile] Failed to fetch shop profile for <shop>: HTTP <status> - <snippet>`) without leaking tokens or request details.
5. **Documentation & Privacy Alignment:**
- Updated README, `docs/SPEC.md`, and the `/privacy` page in `server.js` to state that the app holds a short-lived (1 hour) offline access token, encrypted at rest, re-acquired on admin load, deleted on uninstall, with zero refresh tokens stored.
6. **Automated Test Coverage:**
- 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).




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

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

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

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

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

---

Expand Down
23 changes: 18 additions & 5 deletions app/lib/protocols/contacts.js
Original file line number Diff line number Diff line change
Expand Up @@ -605,12 +605,16 @@ export async function syncShopProfile(db, { shop, accessToken = null, fetchFn =
let token = accessToken;
if (!token) {
const sessionRes = await db.query(
'SELECT "accessToken" FROM "Session" WHERE "shop" = $1 AND "isOnline" = false',
'SELECT "accessToken", "expires" FROM "Session" WHERE "shop" = $1 AND "isOnline" = false LIMIT 1',
[shop]
);
const stored = sessionRes?.rows?.[0]?.accessToken;
if (stored) {
token = decryptAccessToken(stored);
const row = sessionRes?.rows?.[0];
if (row && row.accessToken && row.expires) {
const expiresAt = new Date(row.expires).getTime();
const fiveMinutesFromNow = Date.now() + 5 * 60 * 1000;
if (expiresAt > fiveMinutesFromNow) {
token = decryptAccessToken(row.accessToken);
}
}
}

Expand Down Expand Up @@ -651,7 +655,16 @@ export async function syncShopProfile(db, { shop, accessToken = null, fetchFn =
}

if (!res.ok) {
console.warn(`[ShopProfile] Failed to fetch shop profile for ${shop}: HTTP ${res.status}`);
let snippet = '';
if (typeof res.text === 'function') {
try {
const text = await res.text();
if (text) {
snippet = ` - ${text.trim().slice(0, 200)}`;
}
} catch (_) {}
}
console.warn(`[ShopProfile] Failed to fetch shop profile for ${shop}: HTTP ${res.status}${snippet}`);
return null;
}

Expand Down
Loading
Loading