# LJWellness Storefront (`ljwellness-vs3`) ↔ Artisan 2nd Brain Integration & Security Spec (`ljw-storefront-v1`)

**Target Repository:** `ljwellness-vs3` (`https://staging.ljwellness.net` / `https://ljwellness.net`, Namecheap cPanel Node.js)  
**Partner App (Office & Production Center):** `Artisan 2nd Brain` (`https://artisan.ljwellness.net` on Namecheap cPanel Node.js — also referred to as `StudioOS` in the earlier Storefront brief)  
**Priority Phase:** Phase 1 — **Connection, Security, Staging Isolation & Catalog Agreement** *(before activating live Stripe sales links or real finished inventory)*

---

## 1. Security Rules (Non-Negotiable)

1. **Zero secrets in browser/React code**:
   - NEVER place `STUDIOOS_BRIDGE_KEY`, `STUDIOOS_HMAC_SECRET`, or any bridge credentials inside `src/` or `VITE_*` variables.
   - All calls to StudioOS MUST happen server-to-server inside `ljwellness-vs3`'s Express server (`server.ts` → `server.bundle.mjs`).
2. **Server-to-Server Authentication (`X-Bridge-Key` + Replay-Safe `HMAC-SHA256`)**:
   - Every outbound request from `ljwellness-vs3` to StudioOS AND every inbound sync from StudioOS to `ljwellness-vs3` MUST include:
     - `X-Bridge-Key`: `<shared secret>`
     - `X-Bridge-Timestamp`: `<unix epoch seconds>` (e.g. `Math.floor(Date.now() / 1000)`)
     - `X-Bridge-Signature`: `sha256=<hex HMAC-SHA256 over "${timestamp}.${rawJsonBody}">`
   - Reject any request whose `X-Bridge-Timestamp` is outside a **±300 second (5-minute)** window.
   - Verify keys and HMAC hex digests with `crypto.timingSafeEqual`.
3. **HTTPS Only**:
   - All Storefront ↔ Artisan bridge traffic MUST use HTTPS. Never send `X-Bridge-Key`, bearer credentials, or signed payloads over HTTP.
4. **Strict Staging vs. Production Environment Isolation**:
   - **CRITICAL:** Storefront's existing `stagingMode` (`'bulk_studio' | 'direct_homeowner'`) is a **delivery/fulfillment preference**, NOT an environment indicator.
   - `ljwellness-vs3` Express server MUST explicitly attach:
     ```ts
     environment: process.env.LJWELLNESS_ENV === 'production' ? 'production' : 'staging'
     ```
     *(If `req.hostname.toLowerCase().startsWith('staging.')`, always force `'staging'`.)*
   - Payloads with `environment: "staging"` are quarantined inside StudioOS's `storefront_staging_events` sandbox and NEVER touch live CRM, tasks, ledger, or inventory.
5. **No Fake Paid Orders & PII Health Data Minimization**:
   - NEVER send `eventType: "retail_paid_order"` until Stripe Checkout + server-side Stripe webhook verification is implemented. Until then, send `b2b_inquiry`, `b2b_sample_request`, or `retail_preorder`.
   - For `eczema` and `menopause` submissions, send structured `lineItems[]` and customer contact info cleanly; avoid relying on free-text `skinOrRitualFocus` medical symptom details for downstream fulfillment (StudioOS automatically redacts sensitive health free-text at intake).

---

## 2. Namecheap cPanel Environment Variables

Add these variables in **Namecheap cPanel → Setup Node.js App → Environment Variables** (and document placeholders in `.env.example`, never committing real values):

```env
# Set to "staging" on staging.ljwellness.net, "production" ONLY on live ljwellness.net
LJWELLNESS_ENV=staging

# StudioOS Base URL (no trailing slash — Namecheap cPanel Artisan subdomain)
STUDIOOS_URL=https://artisan.ljwellness.net

# Shared random secrets matching STOREFRONT_BRIDGE_KEY & STOREFRONT_HMAC_SECRET in StudioOS
STUDIOOS_BRIDGE_KEY=REPLACE_WITH_SHARED_32_PLUS_CHAR_KEY
STUDIOOS_HMAC_SECRET=REPLACE_WITH_SHARED_32_PLUS_CHAR_HMAC_SECRET
```

---

## 3. StudioOS Endpoints Ready for Storefront Calls

- **Public Health Check:**
  - `GET ${STUDIOOS_URL}/api/storefront/health`
- **Inbound Lead / Quote / Order Sync (Triggers Internal Arty Dossier):**
  - `POST ${STUDIOOS_URL}/api/storefront/inbound`
- **Pull Canonical Agreed Catalog (B2B + Multi-Product Eczema & Menopause):**
  - `GET ${STUDIOOS_URL}/api/storefront/catalog` *(Requires `X-Bridge-Key`, `X-Bridge-Timestamp`, and `X-Bridge-Signature` computed over `"${timestamp}."` with empty body string)*
- **Private Studio Reference Data:**
  - `GET ${STUDIOOS_URL}/api/storefront/reference-data` is for authenticated Artisan Studio Owners only. Storefront must not call it; BOM formulas, inventory quantities, pricing rules, COGS, and margins are private.

> **Zero External Contact Guarantee:** StudioOS (`Arty`) NEVER sends outbound emails, SMS, webhooks, or Stripe invoices to external clients. Inbound responses contain acknowledgement/status fields only; proprietary COGS, margins, pricing, BOM, and inventory data remain inside Artisan for Myrna to review.

---

## 4. Express Routes to Implement in `ljwellness-vs3/server.ts`

Keep `rawBody` capture on `express.json`:
```ts
app.use(express.json({
  limit: '1mb',
  verify: (req: any, _res, buf) => {
    req.rawBody = buf;
  },
}));
```

### A. `POST /api/sync/studio` (Browser Form → Express Relay → StudioOS)
- Triggered cleanly by `TradeQuoteForm.tsx`, `ClosingGiftBuilder.tsx`, `EczemaProductPage.tsx`, and Menopause forms right after their submission (without blocking customer form confirmation if StudioOS is temporarily offline — log delivery status and retry or surface admin status).
- Server validates input, attaches `environment` (`'staging' | 'production'`), `idempotencyKey` (stable unique key per submission, e.g. Firestore doc ID or `sf_${referenceCode}`), `track` (`'b2b' | 'eczema' | 'menopause'`), `locale` (`'en' | 'fr' | 'bilingual'`), `province`, `fulfillmentPreference` (`'bulk_studio' | 'direct_homeowner'`), and structured `lineItems[]`.
- Signs `rawBody` with `X-Bridge-Timestamp` + `X-Bridge-Signature` (`sha256=<hmac>`) and `X-Bridge-Key`, then POSTs to `${STUDIOOS_URL}/api/storefront/inbound`.

#### Exact Inbound JSON Payload Expected by StudioOS:
StudioOS accepts both the Storefront `contact` shape and normalized parser fields (`requestType`, `client`, `projectDetails`, `timeline.requestedDeliveryDate`, `payment`, `externalOrderId` / `emailMessageId` for idempotency):
```json
{
  "schemaVersion": "ljw-storefront-v1",
  "idempotencyKey": "b2b_ref_LJW_9F2A1C",
  "externalOrderId": "b2b_ref_LJW_9F2A1C",
  "environment": "staging",
  "eventType": "b2b_inquiry",
  "requestType": "quote_request",
  "track": "b2b",
  "referenceCode": "LJW-B2B-9F2A1C",
  "occurredAt": "2026-11-24T11:00:00.000Z",
  "locale": "bilingual",
  "province": "QC",
  "fulfillmentPreference": "bulk_studio",
  "targetDeliveryWindow": "Next 30 Days",
  "timeline": {
    "requestedDeliveryDate": "2026-12-20"
  },
  "contact": {
    "firmName": "Studio Architecture Nord",
    "contactName": "Claire Beaumont",
    "email": "claire@archnord.ca",
    "phone": "514-555-0192",
    "partnerRole": "Architect"
  },
  "projectDetails": {
    "developmentName": "Tour Saint-Laurent",
    "addressOrLocation": "Montreal, QC",
    "unitCount": 24,
    "audienceMode": "homeowner",
    "scentProfile": "Atlas Cedar & Bergamot"
  },
  "lineItems": [
    {
      "sku": "LJW-B2B-ARC-02",
      "storefrontSlug": "architectural-sanctuary",
      "variantKey": "default",
      "name": "02. The Architectural Sanctuary",
      "boxEdition": "Builder Wholesale Run",
      "qty": 12,
      "unitPriceCad": 165
    }
  ],
  "subtotalCad": 1980,
  "discountCad": 99,
  "coBrandingOptions": ["embossed-arch-card", "jesmonite-color-match"],
  "requestSampleKit": true,
  "appliedCouponCode": "",
  "notes": "Handover binder specs in French and English."
}
```
> **Note for Retail Eczema & Menopause (`EczemaProductPage.tsx` / `SubdomainHubs.tsx`):** Send structured `lineItems[]` directly (not only a flattened text string!), using `eventType: "retail_preorder"` until Stripe payments are wired, and send `storefrontSlug` + `variantKey` (e.g. `oat-borage-barrier-balm`, `100ml`, or `peri-cooling-mist`, `100ml`).
> **Staging behavior:** Payloads with `environment: "staging"` are written to the isolated `storefront_staging_events` collection, skip live CRM/workshop writes, and use deterministic evaluation without a Gemini API call. The HTTP response is an acknowledgement only; dossier and costing details stay in Artisan. Staging dossier/queue previews are memory-only and can be lost when the Node.js worker restarts.

#### Inbound Acknowledgement Response

`POST /api/storefront/inbound` returns HTTP `202` for a new event or `200` for a duplicate:
```json
{
  "accepted": true,
  "deduplicated": false,
  "environment": "staging",
  "isolatedToSandbox": true,
  "crmLeadCreated": false,
  "eventId": "event-id",
  "referenceCode": "LJW-B2B-9F2A1C",
  "receivedAt": "2026-11-24T11:00:00.000Z",
  "externalEmailsSent": false,
  "dossierStatus": "pending_review"
}
```
When Firestore persistence is unavailable, Artisan returns HTTP `503` with `accepted: false`; Storefront may retry using the same idempotency key.

### B. `POST /api/studio/catalog-sync` (StudioOS Push → Storefront Firestore `storeProducts`)
- Authenticated using `X-Bridge-Key` + `X-Bridge-Timestamp` (±300s) + `X-Bridge-Signature` (`HMAC-SHA256` over `${timestamp}.${rawBody}`).
- Receives StudioOS's `StorefrontAgreementCatalog`:
  - `brandPositioning`: confirms `primaryFace: "b2b"`, `secondaryTracks: ["eczema", "menopause"]`, `currency: "CAD"`
  - `products[]`: `{ sku, storefrontSlug, variantKey, track, kind, nameEn, nameFr, formatLabel, priceCad, status, stockAvailable, cureLeadDays, cureReadyDate, moq, activeOnStorefront }`
- **Allow-list updates only:** Update commercial truth fields (`sku`, `variantKey`, `priceCad` / variant prices, `status` (`preorder | sample_only | in_development | in_stock | sold_out`), `stockAvailable`, `cureLeadDays`, `cureReadyDate`, `moq`, `nameEn`, `nameFr`, `activeOnStorefront`) in `storeProducts` without overwriting Storefront product photos, layout copy, or hero imagery.

### C. `GET /api/health`
- Keep returning `{ "ok": true, "service": "ljwellness-admin-api", "environment": process.env.LJWELLNESS_ENV || "staging" }` so StudioOS's **Test Storefront Health** button succeeds cleanly.

---

## 5. Brand Positioning & Multi-Product SKU Agreement Rules

1. **B2B is the Primary Brand Face**: Luxury Builders, Architects, Developers, and Realtors (`residence-welcome` → `LJW-B2B-RES-01`, `architectural-sanctuary` → `LJW-B2B-ARC-02`, `bespoke-estate` → `LJW-B2B-BES-03`, Paid Sample Box → `LJW-B2B-SMP-00`, and 5 co-branding add-ons).
2. **Multi-Product Skincare Expansion (`eczema` & `menopause`)**:
   - Storefront `storeProducts` & product detail pages must allow multiple active/upcoming SKUs under both `eczema` and `menopause` (including upcoming *Say It Plain* menopause SKUs synced from StudioOS's **B2B + Skincare Agreement** table).
   - Storefront should read `status` (`preorder`, `sample_only`, `in_development`, `in_stock`, `sold_out`) from the synced catalog rather than hardcoding "Available Now" while manufacturing and Stripe links are still being finalized.
