Open-Source (MIT) | Built for the Shopify Merchant & Developer Community | Open for PRs & Discussions
🚀 Live Interactive Demo: https://practitioner.arsalandev.studio/demo — Test-drive all 4 roles (Practitioner Portal, Client Storefront Page, Printable QR Handout, and Merchant Admin) live with zero setup.
⚙️ Status: Complete Engine, Admin & Storefront Modules Verified (606/606 Unit Tests Passing across 133 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
Artwork is AI-generated (text-free vector artwork via Imagen 3; typography composited via code). Details in assets/listing/README.md and assets/brand/README.md.
The problem: Many direct-to-consumer and professional brands sell through practitioners — dermatologists, physical therapists, veterinarians, personal trainers, salons, and wellness clinics. The practitioner recommends a curated set of products in the clinic; the client forgets half of it, searches online, and buys somewhere else. The brand never learns which practices actually drive retail sales. The model that solves this (a "protocol": a named, reusable list of products with usage directions, shared by link) exists only inside closed supplement dispensaries. A brand running its own Shopify store has had no open equivalent.
The approach: A protocol is a reusable, professional product recommendation list. The practitioner builds it once, shares one permanent link or QR code with any number of clients, and the client lands on a theme-native storefront page where one tap adds everything to their cart at normal retail prices. The brand sees, in aggregate, which practices and protocols drive sales.
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 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 at practitioner.arsalandev.studio 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 584 automated unit tests across 132 suites. Includes dedicated "How to Use" guide tab (?tab=guide) covering storefront navigation menu setup, 3-role workflows, and 5-minute testing walkthrough.
Test-drive the complete application live without requiring a Shopify development store, login, or credentials:
👉 https://practitioner.arsalandev.studio/demo (or /try)
The live demo provides an interactive top showcase bar with instant role switching:
- Practitioner Portal (
/demo?view=portal) — View active protocols, client roster, starter templates, and open the interactive protocol editor modal with live product search and variant hydration. - Client Landing Page (
/demo?view=client) — Experience the client-facing recommendation page with dosages, usage notes, and 1-tap "Add all to cart". - Printable QR Handout (
/demo?view=handout) — View and print self-contained US Letter and A4 clinical routines with vector QR codes. - Merchant Admin (
/demo?view=admin) — Navigate the embedded Polaris merchant dashboard across Practitioners, Starter Templates, Attribution Reports, and Settings.
A. Share Tokens & Cryptography (app/lib/protocols/token.js)
- Unguessable, URL-safe random alphanumeric tokens (
$\ge 16$ characters) usingcrypto.randomBytes. - Over 95 bits of cryptographic entropy, preventing enumeration attacks.
- Validated via
isValidShareToken.
B. Input Validation & Privacy Barrier (app/lib/protocols/validation.js)
-
Strict Zero-PII Enforcement: Rejects any top-level or nested
lines[]key matching/(?:patient|client|ssn|health|medical|diagnosis|condition)/iwithPII_NOT_ALLOWED. - Protocol name (1–60 chars), optional intro note (
$\le 500$ chars), display name ($\le 60$ chars). - Product lines (1–20 items), quantities (1–10 integers), and line usage instructions (
$\le 200$ chars). - Prohibits duplicate variant GIDs within a single protocol (
DUPLICATE_VARIANT). - Enforces Shopify Variant GID format (
gid://shopify/ProductVariant/<id>) and max length (100 characters). - Enforces product handle format (
^[a-z0-9][a-z0-9-]{0,254}$). Known limitation: products whose Shopify handle contains non-Latin characters cannot be added yet. - Restricts
disabledstatus modification and starter creation to administrators only.
C. Permissions & Multi-Tenant Isolation (app/lib/protocols/permissions.js)
- Tag Mode (any Shopify plan): Customer tagged
practitioner. Owner =customer. - B2B Company Mode: B2B company contact. Owner =
company. - Backend-enforced authorization across all actions (
read,create,edit,archive,restore,duplicate,delete). Cross-owner access is strictly blocked (FORBIDDEN_OWNERSHIP_MISMATCH). - Complete HTTP status code mapping across all 9 denial reasons (401, 403, 404, 400).
- Starter Template Protection: Brand starter templates are read-only and duplicable by practitioners, but cannot be modified, archived, or deleted by non-admins.
- Disabled Isolation: Protocols set to
disabledcannot be accessed or modified by non-admins.
D. Storefront App Proxy & Client Page (app/lib/protocols/proxy.js)
- Fails Closed on Missing/Invalid Signature: Requires valid
apiSecretand timing-safe HMAC SHA-256 validation (crypto.timingSafeEqual). Missing secret yields 500; invalid/missing signature yields 401. - Theme-Native Liquid: Generates
application/liquidresponses rendered insidetheme.liquid. - Liquid Injection Neutralization: Neutralizes Liquid template tags (
{{,}},{%,%}) in HTML, attributes, and script tags via HTML entities and Unicode escapes to prevent template injection when evaluated by Shopify's App Proxy. - Search Engine Isolation: Injects
<meta name="robots" content="noindex, nofollow">across all states. - Protocol Lifecycle States:
active: Renders practice branding, intro notes, product cards with usage notes, and 1-tap "Add all to cart" via Cart AJAX (POST /cart/add.js) carrying hidden line item properties (_protocol_token,_protocol_id,_protocol_usage).archived: Friendly "Protocol No Longer Active" card.disabled: Friendly "Protocol No Longer Active" card.not_found: Friendly "Protocol Not Found" card.
- Professional Preview Banner: Displays "You're signed in as a professional. Clients will see retail prices." when
logged_in_customer_idmatches the practitioner. - Catalog Resolver Architecture: See
docs/PROPOSAL_CATALOG_RESOLVER.mdfor how product titles, prices, and stock statuses are resolved on the client page without requiring expanded Admin scopes.
E. Practitioner Portal (app/lib/protocols/portal.js)
-
Protocol Library: Library card view with line counters, live retail price total calculation (
calculateProtocolRetailTotal), starter template badges, and out-of-stock notices ("1 product no longer available"). -
Interactive Protocol Editor (Milestone M3): Built-in modal editor (
#protocol-editor-modal) featuring live catalog product search (searchCatalogProducts,/search/suggest.json), on-select variant hydration (/products/<handle>.js) converting prices from minor units, quantity stepper (1–10), optional line usage instructions ($\le 200$ chars), duplicate line prevention, live retail total recalculation viaformatMoneywithout hard-coded$, and App Proxy persistence (action=createandaction=update). -
Protocol Lifecycle Management (Milestone M9b-3b — Verified Live on Dev Store): In-page archive, restore, and duplicate-as-template actions via App Proxy mutating JSON POST requests (
action=archive,action=restore,action=duplicate). Enforces exactapplication/jsonCSRF media type,Sec-Fetch-Site: same-origincheck, and Rule 4 ownership isolation (returns 404 for cross-owner / cross-shop access to prevent enumeration; starters return 403 on archive). Includes in-page confirmation UI for archiving (inline Confirm/Cancel, zerowindow.confirm/alert/promptdialogs), dedicated "Archived Protocols" section with one-click restore, and "Use as template" on starter cards. Verified live on dev store (unverified live: checkout to orders/paid, logged-out guest view, handoutText/footerDisclaimer, real printing, duplicate-from-starter, cross-owner/cross-shop denial, non-Latin handles). -
Concurrent Edit Detection: Compares
updatedAtto warn practitioners in the same practice if another member edited the protocol simultaneously (PEER_PRACTITIONER_EDIT).
F. Vector QR Code & Printable Handout (app/lib/protocols/qr.js, handout.js)
- Pure JavaScript ISO/IEC 18004 QR generator (zero external dependencies, zero native binaries).
- Output: Scalable, crisp vector SVG with Reed-Solomon Error Correction Level M (15% recovery).
- Print-ready single-page HTML/CSS handout with
@media printrules for US Letter and A4, XSS-escaped dynamic fields, practice branding, routine table, and embedded QR code.
G. Order Attribution & Reports (app/lib/protocols/attribution.js, admin.js)
- Mixed-Cart Isolation: Webhook extractor isolates lines carrying
_protocol_tokenand_protocol_id, ignoring organic store items. - Discounted Revenue Accounting: Revenue is calculated strictly from discounted line totals (
total_discountordiscount_allocations) in minor currency units (cents). - Atomic Multi-Protocol Updates: Transactional processing with single-client checkout guarantees atomicity across multiple attributed protocols in an order.
- Currency Isolation: Monthly stats are partitioned by currency
(shop, protocolId, month, currency)so multi-currency stores do not mix amounts. - RFC 4180 CSV Export: Exports monthly attribution reports with proper escaping, quotes, and CRLF line terminators (strictly aggregate counters; zero client PII).
H. Merchant Admin Management (app/lib/protocols/admin.js)
- Embedded Polaris Admin UI (Milestones M6 & M9a): Embedded Polaris admin with responsive tab navigation: Practitioners, Starter Templates, Attribution & Reports, and Settings. In production mode (
DATABASE_URLconfigured), the embedded admin is served onGET /,GET /admin, andGET /appusing Shopify App Bridge ID tokens and HS256 session verification (renderAdminHtml,renderAdminBootstrapHtml; verified live on dev storeai-agent-app-h9qwnwd8). In local demo mode (DATABASE_URLunset), serves standalone interactive demo previews. - App Bridge HS256 Session Token Verification: Pure
node:cryptoHMAC-SHA256 signature verification (verifyAdminSessionToken,extractAdminSession) usingcrypto.timingSafeEqualwith zero external dependencies, validating expiration, clock skew, destination shop, and client ID audience. - Practitioner Approvals & Anti-Impersonation: Merchant controls practice names (
PractitionerProfile) via inline editing to prevent unauthorized clinic representation alongside approve and revoke actions. - Starter Templates Builder: Accessible modal (
#create-starter-modal) allowing brand administrators to author and publish multi-line starter templates (isStarter = true). - Attribution Reports & Parameterized CSV Export: Monthly order and unit rollups with dynamic month-filtered RFC 4180 CSV download (
/api/admin/attribution.csv?month=YYYY-MM). - Emergency Disable Switch: Single-protocol disable or storewide emergency killswitch (
status: 'disabled'). - App Settings: Configures storefront identity mode (
tagvscompany), custom legal disclaimers, and print instructions.
I. Automated OAuth 2.0 & Embedded Security (server.js, docs/SHOPIFY_APP_STORE_AUDIT.md)
-
Seamless Installation Flow:
GET /api/authvalidates store domain against RFC 1034 format, generates a 16-byte random state nonce, signs it in anHttpOnly; Secure; SameSite=Laxcookie (Max-Age=600,Path=/api/auth), and issues a 302 redirect to Shopify's OAuth authorize endpoint (scope=read_orders). -
Constant-Time HMAC & OAuth State Verification:
GET /api/auth/callbackverifies query parameter signature usingverifyOAuthHmacwithcrypto.timingSafeEqualand validates the state parameter against the signed cookie with a 600-second expiration check, clearing the cookie upon verification. -
Session Persistence: Exchanges authorization code for permanent offline access token and upserts into PostgreSQL
Sessiontable (offline_${shop}) storing'authenticated'inSession.state. -
Shopify Content Security Policy (CSP) & HSTS: Emits
Strict-Transport-Security: max-age=31536000; includeSubDomainsacross all responses, and setsContent-Security-Policy: frame-ancestors https://${shop} https://admin.shopify.com;with complete script, style, and connect directives for embedded admin pages (frame-ancestors 'none';for public pages). -
Public Privacy Policy Page (
server.js,/privacy): Public HTML page (status 200, UTF-8, zero authentication required) explicitly detailing what data is stored (shop domain, offline token, practice approvals, protocols, aggregate attribution counts) versus what is NOT stored (zero shopper PII, zero patient/health data, read_orders aggregate-only attribution), data retention/deletion via compliance webhooks, sub-processors (Railway, Shopify), and optional contact email viaPRIVACY_CONTACT_EMAIL. Zero health claims.
J. Security Hardening & Rate Limiter (app/lib/protocols/rate-limit.js)
- In-memory sliding-window log rate limiter with zero external dependencies, instantiated by default in
routes.js. - Prevents token enumeration, scraping, and brute-force attacks on public App Proxy endpoints (returns Liquid 429 error template after threshold).
- Auto-pruning with
maxKeyseviction cap and unreferenced cleanup intervals to prevent memory leaks. - Employs RFC-compliant HTTP headers (
X-RateLimit-Limit,X-RateLimit-Remaining,Retry-After). - Anti-spoofing client IP extraction:
TRUSTED_PROXY_HOPS(env var, default1): Configures the number of trusted reverse proxy hops from the rightmostX-Forwarded-Forentry (behind Shopify App Proxy and edge infrastructure, the exact hop count is unverified; see Spike S2).TRUST_CF_CONNECTING_IP(env var, defaultfalse): Opt-in trust forCF-Connecting-IPheader; only enable when deployed directly behind Cloudflare.- Falls back to
X-Real-IP, direct socket address, or shared'unknown'bucket. Attacker-controlled leftmost headers cannot manipulate rate limit buckets.
K. Mandatory Compliance Webhooks (app/lib/protocols/webhooks.js)
- Atomic Webhook Idempotency & Rollback: Tracks processed webhook IDs in
ProcessedWebhooktable inside the exact same database transaction as monthly stat upserts. If stat counting fails, the idempotency marker is rolled back so Shopify delivery retries can succeed. True duplicates return{ updatedCount: 0, duplicate: true }. RequiresX-Shopify-Webhook-Idheader (rejects missing header with 400 onorders/paid). Zero order IDs or customer IDs are ever stored inProcessedWebhook. Includes parameterized retention pruning (pruneProcessedWebhooks). customers/data_request: Shopify discards compliance webhook response bodies. By architectural design, the app accepts zero shopper or patient PII (clientPii: null,clientDataStored: false). Practitioner data (practice profiles and authored protocols) can be inspected, but an automated out-of-band delivery channel to merchants is not yet implemented.customers/redact: Tag mode removes practitioner profile and archives/deletes protocols; Company mode preserves company protocols and scrubs personal creator references. Propagates database errors to trigger Shopify retries.shop/redact: Deletes all shop protocols, lines, stats, profiles, settings, sessions, andProcessedWebhookrecords. Propagates failures.app/uninstalled: Revokes all active shop sessions immediately.
flowchart TD
subgraph Practitioner ["Practitioner (Signed In)"]
UI["Portal UI & Library\n(Tag Mode: Customer · B2B Mode: Company)"]
ED["Interactive Protocol Editor Modal\n(Catalog search, line curation, live total)"]
SH["Share Kit\n(Vector QR SVG, Printable Handout)"]
end
subgraph App ["App Core & Database"]
SEC["HMAC & Rate Limiting Guard\n(timingSafeEqual, Sliding Window)"]
API["Protocol API & Service Layer\n(Backend Permission Checks)"]
DB[("PostgreSQL via Prisma\nProtocol · Lines · Profiles · OrderStats · WebhookLog")]
RL["RFC 4180 CSV Reports\n(Aggregate Monthly Counters)"]
WH["Webhook Router\n(orders/paid · GDPR Compliance)"]
end
subgraph Client ["Client (Storefront Visitor)"]
PX["App Proxy Page\n/apps/protocols/:token (Liquid, noindex)"]
CART["Cart AJAX POST /cart/add.js\n(_protocol_token, _protocol_id)"]
end
UI --> API
ED --> API
SH --> API
API --- DB
SEC --- PX
PX --- DB
PX --> CART
CART -->|"orders/paid"| WH
WH --- DB
DB --- RL
The PostgreSQL data model is defined in prisma/schema.prisma:
-
Protocol: ID, shop, token (unique,$\ge 16$ chars), name ($\le 60$ ), introNote ($\le 500$ ), displayName, ownerType (customerorcompany), ownerId, createdBy, updatedBy, status (active,archived,disabled), isStarter, sourceProtocolId, timestamps. -
ProtocolLine: ID, protocolId (cascade delete), position, variantGid, quantity (1–10), usageNote ($\le 200$ ), productHandle (nullable,$\le 255$ chars), unique on(protocolId, variantGid). -
PractitionerProfile: ID, shop, ownerType, ownerGid, practiceName (merchant-controlled), logoUrl, isApproved, unique on(shop, ownerGid). -
ProtocolOrderStat: ID, shop, protocolId, ownerId, month (YYYY-MM), orders, units, revenueMinor (BigInt, cents), currency, unique on(shop, protocolId, month, currency). -
ProcessedWebhook: ID, shop, webhookId, topic, processedAt, unique on(shop, webhookId). -
Setting: Shop (PK), identityMode (tagvscompany), footerDisclaimer, handoutText. -
Session: Shopify session storage table matching@shopify/shopify-app-session-storage-prisma.
- Node.js
$\ge 22.12$ (tested on Node v22 and Node v24) - PostgreSQL 16 (for optional live database integration tests)
cd 04-practitioner-protocols
npm installThe project features a deterministic test suite using native Node.js test runner (node:test):
# Run all 566 pure unit tests using mock database interfaces (zero external network dependencies, ~130ms):
npm test
# Run PostgreSQL live database integration tests against a running Postgres instance:
npm run test:dbDatabase Tests & Migrations Note:
npm testruns 566 pure unit tests across 123 suites against deterministic mock database interfaces. Real PostgreSQL coverage exists whennpm run test:dbis run against PostgreSQL running onlocalhost:5432with databasepractitioner_protocolsand migrations applied. The live integration test suite verifies 10/10 tests against real PostgreSQL, including row-level locking (FOR UPDATE), transaction rollbacks, multi-line replacement, webhook idempotency, and GDPR compliance.
The server supports both in-memory demo mode and persistent PostgreSQL mode. Configure the following variables in production:
| Variable | Description | Default / Example |
|---|---|---|
DATABASE_URL |
PostgreSQL connection string. | postgres://user:pass@host:5432/db |
DATABASE_SSL |
PostgreSQL SSL/TLS mode: require (validates certificates) or no-verify (opt-in skip verification). |
Unset (defaults to false for localhost and *.railway.internal) |
SHOPIFY_API_KEY |
Client ID from Shopify Partner Dashboard. | 840a22df2708a4a51a443180b8c332db |
SHOPIFY_API_SECRET |
Client Secret from Shopify Partner Dashboard. Required for HMAC verification. | shpss_... |
PORT |
HTTP server port. | 3000 |
TRUSTED_PROXY_HOPS |
Number of trusted reverse-proxy hops for IP extraction. | 1 |
TRUST_CF_CONNECTING_IP |
Set to true only when the app is directly fronted by Cloudflare. |
false |
When running against a live PostgreSQL database, apply versioned DDL migrations with ledger tracking (_pp_migrations):
# Automated migration runner (runs with ledger tracking & transaction safety):
npm run migrateOn Railway, migrations run automatically via preDeployCommand: "npm run migrate" in railway.json.
Alternatively, apply raw SQL files directly:
# 1. Initial schema:
psql $DATABASE_URL -f prisma/migrations/20261021_init/migration.sql
# 2. Currency unique key & webhook idempotency table:
psql $DATABASE_URL -f prisma/migrations/20261022_add_currency_to_stat_unique_and_idempotency/migration.sql04-practitioner-protocols/
├── app/
│ └── lib/
│ └── protocols/
│ ├── token.js # Cryptographic share token generator & validator
│ ├── validation.js # Schema validation & zero-PII enforcement barrier
│ ├── permissions.js # Authorization guard (Tag vs B2B Company mode)
│ ├── attribution.js # Cart AJAX payload builder & webhook line extractor
│ ├── qr.js # Pure vector QR SVG generator (GF(256) Reed-Solomon)
│ ├── handout.js # Printable HTML/CSS handout generator (Letter & A4)
│ ├── proxy.js # App Proxy & OAuth HMAC verifiers & theme Liquid renderer
│ ├── catalog.js # Batch variant GraphQL resolver & enrichment (M2)
│ ├── portal.js # Practitioner portal library, editor modal, & concurrent edit check
│ ├── admin.js # Merchant admin Polaris UI, session tokens, & RFC 4180 CSV export
│ ├── rate-limit.js # In-memory sliding-window rate limiter
│ ├── webhooks.js # Shopify compliance & order attribution webhooks
│ ├── service.js # Transactional PostgreSQL service layer (withTransaction)
│ └── routes.js # HTTP request controllers & webhook router
├── assets/
│ ├── brand/ # Brand hero banner and social preview thumbnail
│ └── listing/ # App Store icon and feature image (AI-generated)
├── docs/
│ ├── BUILD_PLAN.md # Milestones and progress tracker
│ ├── M1_CONTRACT.md # Runtime contract specification
│ ├── PROPOSAL_CATALOG_RESOLVER.md # Storefront API variant resolution proposal
│ ├── SHOPIFY_APP_STORE_AUDIT.md # Shopify App Store Review self-audit & PCD justification
│ ├── SPEC.md # Comprehensive architectural specification
│ └── SPIKES_CHECKLIST.md # Empirical dev store spikes plan & findings (S1–S5)
├── prisma/
│ ├── schema.prisma # PostgreSQL data models
│ └── 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
│ ├── handout.test.js # QR SVG & printable handout tests
│ ├── proxy.test.js # App Proxy & OAuth HMAC, Liquid states, & timestamp tests
│ ├── catalog.test.js # Catalog resolver batch GraphQL & fallback tests
│ ├── portal.test.js # Library, editor modal, & concurrent-edit tests
│ ├── admin.test.js # Approvals, starters, disable, session tokens, & CSV tests
│ ├── 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
├── CLAUDE.md # Repository conventions & safety agreements
├── PROJECT_CONTEXT.md # Append-only chronological engineering log
├── shopify.app.toml # App manifest (read_orders scope, compliance webhooks)
└── package.json # Native ESM package manifest
-
Zero Client/Patient PII: Validated across all layers. The app rejects client-identifying or clinical keys (
patientName,clientEmail,medicalDiagnosis, etc.) both at top level and inside line items (PII_NOT_ALLOWED). -
Fail-Closed Cryptography: All HMAC signatures (App Proxy and Webhooks) are verified using
crypto.timingSafeEqual. App Proxy routes fail closed with HTTP 500 whenapiSecretis missing and HTTP 401 when signatures are invalid. -
Liquid Injection Defense: Delimiters (
{{,}},{%,%}) in user-supplied strings are neutralized via HTML entities and Unicode escapes, preventing server-side template injection when Shopify parses App Proxy Liquid. -
Fully Parameterized SQL: Database interactions use parameterized queries (
$1, $2, ...) inside a connection pool safewithTransactionwrapper ensuring single-client checkout and atomic rollbacks. -
No Search Indexing: App Proxy responses unconditionally include
<meta name="robots" content="noindex, nofollow">to prevent indexing of recommendation links. - Anti-Spoofing Rate Limiting: Public proxy routes are guarded by sliding-window rate limiting enabled by default, using rightmost proxy IP extraction to prevent header spoofing.
-
Transactional Webhook Idempotency & Error Propagation: Webhooks track
X-Shopify-Webhook-Idatomically within the order attribution transaction. All webhook dispatch and database errors propagate retryable 5xx responses.
- License: MIT License — Open for the Shopify merchant and developer community.
- Maintainer: Arsalan Arshad (arsalanarshad.dev@gmail.com)

