From a90207903d02aded61253ca6d442069b74ed4560 Mon Sep 17 00:00:00 2001 From: arsalan-arshad Date: Fri, 6 Nov 2026 02:49:00 +0500 Subject: [PATCH] fix(auth): use expiring offline tokens --- PROJECT_CONTEXT.md | 23 ++++++ README.md | 4 +- app/lib/protocols/contacts.js | 23 ++++-- app/lib/protocols/exchange.js | 62 +++++++++++----- docs/BUILD_PLAN.md | 2 +- docs/SPEC.md | 4 +- server.js | 2 +- test/contacts.test.js | 29 ++++++-- test/exchange.test.js | 132 +++++++++++++++++++++++++++++++--- 9 files changed, 237 insertions(+), 44 deletions(-) diff --git a/PROJECT_CONTEXT.md b/PROJECT_CONTEXT.md index 63de185..a791f08 100644 --- a/PROJECT_CONTEXT.md +++ b/PROJECT_CONTEXT.md @@ -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 : HTTP - `) 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). + + diff --git a/README.md b/README.md index ae38f41..8aea48d 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 (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**

A curated list card of generic unbranded wellness products converging into a single coral QR code link node on deep teal background. @@ -28,7 +28,7 @@ **Privacy by design:** Protocols never accept or store health, medical, or diagnostic data. Browsing shoppers have zero personal information collected or stored. Under an explicit owner decision (dated 2026-11-05), the zero-PII rule is relaxed strictly for an explicit, opt-in "Stay in touch" contact submitted by the shopper on a protocol recommendation page (email, optional first name, timestamp, and verifiable consent text). No protocol, order, or product data is ever linked to the contact. Attribution is tracked solely via aggregate monthly counters. A public privacy policy is served at [`/privacy`](file:///Users/macbook/work/shopify/04-practitioner-protocols/server.js) documenting data handling, explicit consent, compliance webhooks, and sub-processors. -**Current build stage:** The pure engine logic, security controls, cryptographic primitives, Liquid renderers, catalog resolver, rate limiters, validation barriers, and PostgreSQL database queries are fully built and covered by 507 automated unit tests across 111 suites using mock database interfaces. Real PostgreSQL query execution, transaction behavior, constraints, row-level locking (`FOR UPDATE`), and migrations are verified against a live PostgreSQL instance via `npm run test:db` (11 integration tests run against a live PostgreSQL instance, skipping with a notice when none is reachable). The app is deployed live on Railway (`practitioner-protocols-production.up.railway.app`) with internal PostgreSQL and automated migration tracking. Spikes S2 (sitemap exclusion, `noindex`, and proxy header), S3 (hidden line property attribution persistence in storefront checkout and `orders/paid` webhook payload), S4 (20 lines in a single cart batch add), S5 (retail vs B2B pricing), and S6 (storefront predictive search and variant hydration contract; Option A chosen) are verified on live dev store `ai-agent-app-h9qwnwd8.myshopify.com`; Spike S1 is verified on the Plus dev store only. In production mode with `DATABASE_URL` configured, the embedded merchant admin is verified live on the dev store (Milestone M9a; `GET /`, `GET /admin`, `GET /app` served via App Bridge ID tokens and HS256 session verification), including the self-enrolment toggle and pending practitioner review table with customer admin deep links (Milestone M9b-1; verified live on dev store); for Milestone M9b-2, verified live on the dev store: enrol round trip (JSON POST through the App Proxy), pending portal state with requested name, admin pending row with customer deep link, merchant approval, approved portal display, form-encoded and `text/plain;application/json` POSTs returning 415, and unknown action returning 400 (the per-customer rate limit of 5/hr, the pending cap of 200, `customers/redact` profile deletion, and `Sec-Fetch-Site` handling are covered by automated unit tests and were not exercised live); for Milestone M9b-3a (protocol authoring and client page hydration), VERIFIED LIVE on the dev store: editor search with real products and CAD prices, protocol save, share-page hydration, Add all with _protocol_token/_protocol_id/_protocol_usage in the cart, checkout to orders/paid (webhook 200, stat row written), edit round trip (qty and note persisted, token unchanged), list card item count, handout page layout; migration adding nullable `productHandle` to `ProtocolLine`, validation and persistence, client-side predictive search (`/search/suggest.json`) and variant hydration (`/products/.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/.js`, and removal of `createFakeVariantResolver` from the production App Proxy pipeline. Follow-up hotfix loaded protocol lines on portal queries (`json_agg` + `linesCount`) to eliminate edit data loss, removed fake retail total (`$0.00`) from cards to show only item count, and implemented print-friendly handout mode (`?handout=1`) in `renderProtocolLiquid`. Milestone M9b-3b (protocol lifecycle: archive, restore, duplicate-as-template for starters with CSRF, duplicate-from-starter, Rule 4 ownership isolation, in-page confirm UI, and Archived section) is VERIFIED LIVE on the dev store. Remaining NOT-verified live list: logged-out guest view, handoutText/footerDisclaimer rendering, real printing, live cross-owner/cross-shop denial, non-Latin handles (known limitation), discounted-order attribution live, and new CSP inside real admin iframe. Note: the admin attribution report page displayed zeros for live data until a contract mismatch between `getAttributionReport` and `renderAttributionTab` was resolved by unifying `{ month, summary, rows, byPractice, byProtocol }` across the data service, renderer, demo data, and RFC 4180 CSV export with `Intl.NumberFormat` currency formatting. Pre-submission hardening is complete with HMAC-signed OAuth state cookies, public `/privacy` page, `Strict-Transport-Security` on all responses, expanded embedded App Bridge CSP, admin starter catalog product search UX, individual mode settings label, and `.github/CODEOWNERS`. Milestone M11 implements shopper opt-in contact capture (server-defined canonical consent text, dedicated 5/hr rate limiter, case-insensitive email deduplication, RFC 4180 CSV export with `Verified = "no"`) and merchant contact & feedback (`ShopProfile` sync via Admin GraphQL, AES-256-GCM session token encryption at rest, "Contact & feedback" card with 1–5 rating and marketing opt-in checkbox, `scripts/contacts.mjs` and `scripts/stats.mjs`). Under Shopify Managed Installation, authentication uses App Bridge token exchange (RFC 8693) to acquire 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/.js`) in the practitioner editor with `textContent` rendering, client page variant hydration from `/products/.js`, and removal of `createFakeVariantResolver` from the production App Proxy pipeline. Follow-up hotfix loaded protocol lines on portal queries (`json_agg` + `linesCount`) to eliminate edit data loss, removed fake retail total (`$0.00`) from cards to show only item count, and implemented print-friendly handout mode (`?handout=1`) in `renderProtocolLiquid`. Milestone M9b-3b (protocol lifecycle: archive, restore, duplicate-as-template for starters with CSRF, duplicate-from-starter, Rule 4 ownership isolation, in-page confirm UI, and Archived section) is VERIFIED LIVE on the dev store. Remaining NOT-verified live list: logged-out guest view, handoutText/footerDisclaimer rendering, real printing, live cross-owner/cross-shop denial, non-Latin handles (known limitation), discounted-order attribution live, and new CSP inside real admin iframe. Note: the admin attribution report page displayed zeros for live data until a contract mismatch between `getAttributionReport` and `renderAttributionTab` was resolved by unifying `{ month, summary, rows, byPractice, byProtocol }` across the data service, renderer, demo data, and RFC 4180 CSV export with `Intl.NumberFormat` currency formatting. Pre-submission hardening is complete with HMAC-signed OAuth state cookies, public `/privacy` page, `Strict-Transport-Security` on all responses, expanded embedded App Bridge CSP, admin starter catalog product search UX, individual mode settings label, and `.github/CODEOWNERS`. Milestone M11 implements shopper opt-in contact capture (server-defined canonical consent text, dedicated 5/hr rate limiter, case-insensitive email deduplication, RFC 4180 CSV export with `Verified = "no"`) and merchant contact & feedback (`ShopProfile` sync via Admin GraphQL, AES-256-GCM session token encryption at rest, "Contact & feedback" card with 1–5 rating and marketing opt-in checkbox, `scripts/contacts.mjs` and `scripts/stats.mjs`). Under Shopify Managed Installation, authentication uses App Bridge token exchange (RFC 8693) to acquire expiring offline access tokens (1-hour lifetime, `expiring: 1`) without interactive redirects, with encrypted storage at rest via AES-256-GCM, non-PII failure logging, friendly status 200 root page, and fallback legacy OAuth. The app holds a short-lived (1 hour) offline access token, re-acquired on admin load when missing or expiring within 5 minutes, and deleted on uninstallation; no refresh token is stored (fewer secrets at rest) and no separate refresh flow is built because the app makes no Admin API calls outside embedded-admin requests. Covered by 580 automated unit tests across 132 suites. --- diff --git a/app/lib/protocols/contacts.js b/app/lib/protocols/contacts.js index 55a0289..688660b 100644 --- a/app/lib/protocols/contacts.js +++ b/app/lib/protocols/contacts.js @@ -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); + } } } @@ -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; } diff --git a/app/lib/protocols/exchange.js b/app/lib/protocols/exchange.js index 07ee363..19a6a04 100644 --- a/app/lib/protocols/exchange.js +++ b/app/lib/protocols/exchange.js @@ -65,7 +65,7 @@ export async function performTokenExchange({ subject_token: idToken, subject_token_type: TOKEN_TYPE_ID_TOKEN, requested_token_type: TOKEN_TYPE_OFFLINE_ACCESS, - expiring: 0 + expiring: 1 }; try { @@ -97,7 +97,10 @@ export async function performTokenExchange({ return { accessToken: data.access_token, - scope: data.scope || 'read_orders' + scope: data.scope || 'read_orders', + expiresIn: typeof data.expires_in === 'number' ? data.expires_in : 3600, + refreshToken: data.refresh_token || null, + refreshTokenExpiresIn: typeof data.refresh_token_expires_in === 'number' ? data.refresh_token_expires_in : null }; } catch (err) { const status = err?.name === 'AbortError' ? 'timeout' : (err?.status || 'network_error'); @@ -107,9 +110,19 @@ export async function performTokenExchange({ } /** - * 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). + * Ensures an offline session exists and is currently valid for the given shop. + * + * Expiring Offline Tokens Policy: + * Shopify mandates expiring offline access tokens for public apps calling the Admin API. + * A session is considered 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, + * performs an RFC 8693 token exchange using the fresh `id_token` provided with the request. + * + * Zero Refresh Token Storage: + * Refresh tokens are intentionally NOT stored in the database to minimize secrets at rest. + * Because Practitioner Protocols executes Admin API calls strictly in response to merchant + * embedded-admin actions (and never in offline background workers), acquiring a fresh token + * via id_token exchange on admin request renders an asynchronous refresh flow unnecessary. * * Concurrency & Caching: * - Employs a per-shop in-flight lock to deduplicate concurrent exchange requests. @@ -123,7 +136,7 @@ export async function performTokenExchange({ * apiSecret: string, * fetchFn?: typeof fetch * }} params - * @returns {Promise<{ shop: string, success: boolean } | null>} + * @returns {Promise<{ shop: string, success: boolean, existing?: boolean } | null>} */ export async function ensureOfflineSession(db, { shop, @@ -136,17 +149,22 @@ export async function ensureOfflineSession(db, { return null; } - // 1. Check if offline session already exists in DB + // 1. Check if offline session already exists in DB and is still usable (> 5 mins remaining) try { const existing = await db.query( - 'SELECT "id" FROM "Session" WHERE "shop" = $1 AND "isOnline" = false LIMIT 1', + 'SELECT "id", "accessToken", "expires" FROM "Session" WHERE "shop" = $1 AND "isOnline" = false LIMIT 1', [shop] ); - if (existing?.rows?.length > 0) { - return { shop, success: true, existing: true }; + const row = existing?.rows?.[0]; + if (row && row.expires) { + const expiresAt = new Date(row.expires).getTime(); + const fiveMinutesFromNow = Date.now() + 5 * 60 * 1000; + if (expiresAt > fiveMinutesFromNow) { + return { shop, success: true, existing: true }; + } } } catch (err) { - // If DB check fails, continue or return null + // If DB check fails, continue to token exchange } // 2. Check 60-second negative cache @@ -178,20 +196,30 @@ export async function ensureOfflineSession(db, { // Success: clear negative cache negativeCache.delete(shop); - // Upsert Session with encrypted access token + // Expiration timestamp: now + expiresIn seconds (~3600s) + const expiresInSec = typeof exchangeResult.expiresIn === 'number' ? exchangeResult.expiresIn : 3600; + const expiresDate = new Date(Date.now() + expiresInSec * 1000); + + // Upsert Session with encrypted access token and expires date. + // Refresh token is intentionally NOT stored (fewer secrets at rest). + // Every embedded admin request provides a fresh id_token, so re-exchange + // on admin load is sufficient; no background refresh flow is required. const encryptedToken = encryptAccessToken(exchangeResult.accessToken); await db.query( - `INSERT INTO "Session" ("id", "shop", "state", "isOnline", "scope", "accessToken") - VALUES ($1, $2, $3, false, $4, $5) + `INSERT INTO "Session" ("id", "shop", "state", "isOnline", "scope", "accessToken", "expires", "refreshToken", "refreshTokenExpires") + VALUES ($1, $2, $3, false, $4, $5, $6, NULL, NULL) 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] + "accessToken" = EXCLUDED."accessToken", + "expires" = EXCLUDED."expires", + "refreshToken" = NULL, + "refreshTokenExpires" = NULL`, + [`offline_${shop}`, shop, 'authenticated', exchangeResult.scope, encryptedToken, expiresDate] ); - // Synchronize ShopProfile (awaited, non-blocking on failure) + // Synchronize ShopProfile with NEW token in the same request (awaited, non-blocking on failure) try { await syncShopProfile(db, { shop, diff --git a/docs/BUILD_PLAN.md b/docs/BUILD_PLAN.md index 42188fa..a42dc4a 100644 --- a/docs/BUILD_PLAN.md +++ b/docs/BUILD_PLAN.md @@ -122,7 +122,7 @@ - Lifecycle: `app/uninstalled` deletes the `Session` row while keeping `ShopProfile` with `uninstalledAt` timestamp; `shop/redact` purges all shop records. - UI: Settings opt-in card displays a disabled checkbox with `"Your store contact email is still being loaded. Reload this page."` when `ShopProfile.email` is absent (never displays `"this email"`), and custom request cards prefill `replyEmail` when present. Shopper consent text uses `ShopProfile.shopName` when available. - Friendly root landing page: `GET /` (or `/admin`, `/app`) outside admin iframe with no session serves status 200 HTML with `"Practitioner Protocols runs inside your Shopify admin. Open it from your Shopify admin's Apps list."`, link to `/privacy`, and zero login or shop domain input fields. - - Automated unit test coverage: 578 passing tests across 132 suites (`npm test`). + - Automated unit test coverage: 580 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 0cc1172..6a91b3f 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -63,7 +63,7 @@ Always `noindex`. Prices are always the store's live retail price — a protocol | `ShopperContact` | id, shop, ownerId, email (lowercased, max 254), firstName (optional, max 60), consentText, consentVersion, consentedAt, source ('protocol_page'), createdAt — **explicit opt-in only**; unique (shop, ownerId, email) | | `MerchantFeedback` | id, shop, shopName, ownerName, replyEmail, planName, country, message (max 1000), rating (1–5, optional), kind ('feedback' / 'custom_request'), createdAt | | `ShopProfile` | id, shop (unique), shopName, ownerName, email, planName, country (store country from `shopAddress.countryCodeV2`), installedAt, uninstalledAt (nullable), marketingOptIn (boolean), marketingOptInAt (nullable), createdAt, updatedAt — synchronized via Admin GraphQL `shop` query | -| `Session` | id, shop, state, isOnline, scope, accessToken (**encrypted at rest using AES-256-GCM**, `enc:v1:::`), createdAt, updatedAt | +| `Session` | id, shop, state, isOnline, scope, accessToken (**encrypted at rest using AES-256-GCM**, `enc:v1:::`), expires (DateTime, 1-hour lifespan), refreshToken (NULL, not stored), refreshTokenExpires (NULL), createdAt, updatedAt | > [!NOTE] > **Decision Record (Owner Decision, 2026-11-05 — M11):** @@ -71,7 +71,7 @@ Always `noindex`. Prices are always the store's live retail price — a protocol > [!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. +> Under Shopify's managed installation architecture, embedded applications acquire short-lived (1-hour) expiring offline access tokens via App Bridge token exchange (RFC 8693, `expiring: 1`) on admin request without browser redirect loops. Tokens are stored encrypted at rest using AES-256-GCM (`enc:v1:::`) with expiration timestamp (`expires`), and re-acquired on admin load when missing or expiring within 5 minutes. Refresh tokens are intentionally not stored (fewer secrets at rest) and no separate refresh flow is built because the app makes no Admin API calls outside embedded-admin requests. Deleted immediately on app uninstallation. 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/server.js b/server.js index 24e2d58..4456db3 100644 --- a/server.js +++ b/server.js @@ -603,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: 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.
  • +
  • Offline Access Token: The app holds a short-lived (1 hour) offline access token, acquired through Shopify managed installation using App Bridge token exchange (RFC 8693) and re-acquired on admin load. Stored encrypted at rest using AES-256-GCM when SESSION_ENCRYPTION_KEY is configured, and deleted immediately on app uninstallation. No refresh token is stored.
  • 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.
  • diff --git a/test/contacts.test.js b/test/contacts.test.js index b464cc7..d7b271f 100644 --- a/test/contacts.test.js +++ b/test/contacts.test.js @@ -654,8 +654,8 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', let storedProfile = null; const mockDb = { async query(sql, params) { - if (sql.includes('SELECT "accessToken" FROM "Session"')) { - return { rows: [{ accessToken: 'mock_shpat_valid_token' }] }; + if (sql.includes('SELECT "accessToken"') && sql.includes('FROM "Session"')) { + return { rows: [{ accessToken: 'mock_shpat_valid_token', expires: new Date(Date.now() + 3600 * 1000).toISOString() }] }; } if (sql.includes('INSERT INTO "ShopProfile"')) { const [shop, shopName, ownerName, email, planName, country] = params; @@ -701,7 +701,7 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', assert.equal(res.planName, 'Advanced'); assert.equal(res.country, 'GB'); - // 2. Failed fetch must never throw or block + // 2. Failed fetch must never throw or block and logs status with response snippet const origWarn = console.warn; const warnings = []; console.warn = (...args) => warnings.push(args.join(' ')); @@ -709,13 +709,14 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', try { const fakeFetchFail = async () => ({ ok: false, - status: 500 + status: 403, + text: async () => 'Non-expiring access tokens are no longer accepted for the Admin API' }); const failRes = await syncShopProfile(mockDb, { shop: 'holistic.myshopify.com', fetchFn: fakeFetchFail }); assert.equal(failRes, null); assert.equal(warnings.length, 1); - assert.match(warnings[0], /Failed to fetch shop profile for holistic\.myshopify\.com: HTTP 500/); + assert.match(warnings[0], /Failed to fetch shop profile for holistic\.myshopify\.com: HTTP 403 - Non-expiring access tokens are no longer accepted for the Admin API/); // 3. Aborted/timed out fetch must be handled gracefully without throwing const fakeFetchTimeout = async () => { @@ -742,6 +743,24 @@ describe('Contacts & Merchant Feedback Service (app/lib/protocols/contacts.js)', assert.equal(gqlErrRes, null); assert.equal(warnings.length, 3); assert.match(warnings[2], /^\[ShopProfile\] GraphQL error for holistic\.myshopify\.com: A{200}$/); + + // 5. Expired or null-expires session does not attempt GraphQL fetch + let uncalledFetch = false; + const fakeFetchNever = async () => { + uncalledFetch = true; + return { ok: true }; + }; + const expiredDb = { + async query(sql) { + if (sql.includes('FROM "Session"')) { + return { rows: [{ accessToken: 'mock_token', expires: null }] }; + } + return { rows: [] }; + } + }; + const expiredRes = await syncShopProfile(expiredDb, { shop: 'holistic.myshopify.com', fetchFn: fakeFetchNever }); + assert.equal(expiredRes, null); + assert.equal(uncalledFetch, false, 'Must not query GraphQL if stored token has NULL expires'); } finally { console.warn = origWarn; } diff --git a/test/exchange.test.js b/test/exchange.test.js index f81e4d3..12bbb24 100644 --- a/test/exchange.test.js +++ b/test/exchange.test.js @@ -71,11 +71,11 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ // 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 [id, shop, stateVal, isOnline, scope, accessToken, expires, refreshToken, refreshTokenExpires] = [ + params[0], params[1], params[2], false, params[3], params[4], params[5] ?? null, params[6] ?? null, params[7] ?? null ]; const idx = state.sessions.findIndex(s => s.id === id); - const row = { id, shop, state: stateVal, isOnline, scope, accessToken }; + const row = { id, shop, state: stateVal, isOnline, scope, accessToken, expires, refreshToken, refreshTokenExpires }; if (idx >= 0) { state.sessions[idx] = row; } else { @@ -160,7 +160,10 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ async json() { return { access_token: 'mock_shpat_offline_token_test_123', - scope: 'read_orders' + scope: 'read_orders', + expires_in: 3600, + refresh_token: 'mock_shprt_refresh_token_test', + refresh_token_expires_in: 7776000 }; } }; @@ -177,6 +180,9 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ assert.ok(result); assert.equal(result.accessToken, 'mock_shpat_offline_token_test_123'); assert.equal(result.scope, 'read_orders'); + assert.equal(result.expiresIn, 3600); + assert.equal(result.refreshToken, 'mock_shprt_refresh_token_test'); + assert.equal(result.refreshTokenExpiresIn, 7776000); // Verify endpoint and method assert.equal(capturedUrl, `https://${testShop}/admin/oauth/access_token`); @@ -192,12 +198,12 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ 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); + assert.equal(bodyParams.expiring, 1); }); }); describe('2. Session Persistence, Encryption & Profile Sync', () => { - it('exchange success writes an encrypted Session row and synchronizes ShopProfile', async () => { + it('exchange success writes an encrypted Session row with expires ~now+3600s and NULL refresh token', async () => { const db = createTestDb(); let exchangeCalls = 0; let graphqlCalls = 0; @@ -210,7 +216,13 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ ok: true, status: 200, async json() { - return { access_token: 'mock_offline_raw_token_xyz', scope: 'read_orders' }; + return { + access_token: 'mock_offline_raw_token_xyz', + scope: 'read_orders', + expires_in: 3600, + refresh_token: 'mock_shprt_refresh_token_xyz', + refresh_token_expires_in: 7776000 + }; } }; } @@ -257,6 +269,13 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ assert.equal(savedSession.isOnline, false); assert.equal(savedSession.state, 'authenticated'); assert.equal(savedSession.scope, 'read_orders'); + assert.ok(savedSession.expires, 'Session expires must be set'); + const expiresTime = new Date(savedSession.expires).getTime(); + const expectedMin = Date.now() + 3550 * 1000; + const expectedMax = Date.now() + 3650 * 1000; + assert.ok(expiresTime >= expectedMin && expiresTime <= expectedMax, 'Session expires must be ~now + 3600s'); + assert.equal(savedSession.refreshToken, null, 'Refresh token must NOT be stored'); + assert.equal(savedSession.refreshTokenExpires, null, 'Refresh token expires must be NULL'); // Verify token encryption format enc:v1::: assert.match(savedSession.accessToken, /^enc:v1:[0-9a-f]{24}:[0-9a-f]{32}:[0-9a-f]+$/); @@ -273,7 +292,7 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ assert.equal(savedProfile.country, 'CA'); }); - it('second request does not exchange again when Session already exists', async () => { + it('a Session valid for >5 minutes does NOT trigger an exchange', async () => { const db = createTestDb({ sessions: [ { @@ -281,7 +300,8 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ shop: testShop, isOnline: false, scope: 'read_orders', - accessToken: 'enc:mock_existing_token' + accessToken: 'enc:mock_existing_token', + expires: new Date(Date.now() + 30 * 60 * 1000).toISOString() } ] }); @@ -289,7 +309,7 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ let fetchCalled = false; const fakeFetch = async () => { fetchCalled = true; - throw new Error('Should not call fetch when session exists'); + throw new Error('Should not call fetch when valid session exists'); }; const res = await ensureOfflineSession(db, { @@ -302,7 +322,97 @@ describe('Shopify Token Exchange & Managed Install Hardening (app/lib/protocols/ assert.ok(res); assert.equal(res.existing, true); - assert.equal(fetchCalled, false, 'Must not call fetch when offline session is present'); + assert.equal(fetchCalled, false, 'Must not call fetch when valid session is present'); + }); + + it('a Session with expires NULL triggers a re-exchange', async () => { + const db = createTestDb({ + sessions: [ + { + id: `offline_${testShop}`, + shop: testShop, + isOnline: false, + scope: 'read_orders', + accessToken: 'enc:mock_existing_token', + expires: null + } + ] + }); + + let exchangeCalled = false; + const fakeFetch = async (url) => { + const urlStr = String(url); + if (urlStr.includes('/admin/oauth/access_token')) { + exchangeCalled = true; + return { + ok: true, + status: 200, + json: async () => ({ + access_token: 'mock_re_exchanged_token', + scope: 'read_orders', + expires_in: 3600 + }) + }; + } + return { ok: true, json: async () => ({ data: { shop: { name: 'Test' } } }) }; + }; + + const res = await ensureOfflineSession(db, { + shop: testShop, + idToken: validIdToken, + apiKey, + apiSecret, + fetchFn: fakeFetch + }); + + assert.ok(res); + assert.equal(res.success, true); + assert.equal(exchangeCalled, true, 'Must trigger re-exchange when expires is NULL'); + }); + + it('a Session expiring within 5 minutes triggers a re-exchange', async () => { + const db = createTestDb({ + sessions: [ + { + id: `offline_${testShop}`, + shop: testShop, + isOnline: false, + scope: 'read_orders', + accessToken: 'enc:mock_existing_token', + expires: new Date(Date.now() + 4 * 60 * 1000).toISOString() // 4 minutes remaining (< 5m) + } + ] + }); + + let exchangeCalled = false; + const fakeFetch = async (url) => { + const urlStr = String(url); + if (urlStr.includes('/admin/oauth/access_token')) { + exchangeCalled = true; + return { + ok: true, + status: 200, + json: async () => ({ + access_token: 'mock_refreshed_token', + scope: 'read_orders', + expires_in: 3600 + }) + }; + } + return { ok: true, json: async () => ({ data: { shop: { name: 'Test' } } }) }; + }; + + const res = await ensureOfflineSession(db, { + shop: testShop, + idToken: validIdToken, + apiKey, + apiSecret, + fetchFn: fakeFetch + }); + + assert.ok(res); + assert.equal(res.success, true); + assert.equal(exchangeCalled, true, 'Must trigger re-exchange when expiring within 5 minutes'); }); });