Skip to content

feat(magento): initial scaffold port from deco-cx/apps to apps-start - #61

Merged
JonasJesus42 merged 5 commits into
mainfrom
JonasJesus42/magento-port
Jun 2, 2026
Merged

JonasJesus42 merged 5 commits into
mainfrom
JonasJesus42/magento-port

Conversation

@JonasJesus42

@JonasJesus42 JonasJesus42 commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Brings the website/matchers/location.ts builtin matcher back to parity with deco-cx/apps/website/matchers/location.ts. The current implementation diverged in three places that surface as broken regional segmentation in production:

  1. Reading the wrong CF header (cf-region — the name — instead of cf-region-code — the ISO code), so a rule typed as SP never matched a Brazilian visitor.
  2. AND'ing a regionName fallback the original doesn't have, and silently treating Map-mode entries ({coordinates: "lat,lng,radius"}) as vacuously true. Any rule authored through the admin's Map UI matched every visitor.
  3. injectGeoCookies propagated geo only via __cf_geo_* cookies — consumers using the upstream pattern request.headers.get("cf-region-code") got null.

Discovered while debugging a Casa & Video segmentation incident where the merchant's "Rio variant" never displayed.

Changes

  • src/matchers/builtins.ts — full rewrite of getGeoData / matchLocation / locationMatcher mirroring upstream's closure pattern, plus an inline haversineWithinRadius (~12 lines) so Map-mode entries actually evaluate.
  • src/admin/schema.ts — schema now declares the (Location | Map) union the admin writes: adds coordinates field; adds examples (SP, RJ, 47, -23.55,-46.63,5000) and description on every input, including the long-form note that regionCode matches the raw cf-region-code value (numeric codes work iff CF returns them).
  • src/sdk/workerEntry.ts — injectGeoCookies now also mirrors ASCII-safe geo fields back as request headers (cf-region-code, cf-ipcountry, cf-iplatitude, cf-iplongitude) so the matcher's header-first read order works even when TanStack re-wraps the request.
  • scripts/migrate/templates/server-entry.ts — both VTEX and non-VTEX templates now include regionId: geoRegion in buildSegment by default. Without this, the first geo-resolved response gets cached and served across regions, defeating the matcher even when it's working correctly.
  • src/matchers/builtins.test.ts — NEW, 22 tests covering typed mode (SP / RJ / numeric "47" parity / case-insensitive), empty-entry semantics, exclude short-circuit, haversine in/out radius, country aliasing ("Brasil" → BR), and the header / request.cf / cookie fallback chain.

End-to-end validation

Tested against storefront-tanstack (@decocms/[email protected]) by patching the installed bundle with this PR's logic:

Scenario include SP include RJ include '47' country='Brasil' haversine SP 50km haversine Rio 50km
simulate=SP ✅ T F F ✅ T ✅ T F
simulate=RJ F ✅ T F ✅ T F ✅ T
simulate=SC F F F ✅ T F F
simulate=47 F F ✅ T ✅ T n/a n/a
simulate=MG F F F ✅ T F F

A full multivariate/section.ts flag on the home Carousel section rendered the correct per-region variant (RJ / SP / fallback) end-to-end with the patched bundle. Server log confirmed the new matcher path was being executed.

Test plan

  • npm run typecheck
  • npm run build
  • npx vitest run src/matchers/builtins.test.ts (22 tests passing)
  • Full suite npx vitest run (709 tests passing — no regressions)
  • Manual smoke on storefront-tanstack/miami via patched node_modules: variant resolving per region; cache key splits via r=SP / r=RJ segment
  • Verify in production after release — Bagaggio (50% ramp Monday) is the first natural test bed; Miess (conversation starting Monday) and Granado (live early July) follow

Notes for the next consumer bump

When sites pull this release, they get the matcher fix automatically. The cache-segmentation fix lands automatically only on freshly migrated sites (template updated). Existing sites need their src/worker-entry.ts updated to include regionId: cf-region-code in buildSegment — without that, the matcher works but cache leaks across regions. We should call this out in the release notes.

🤖 Generated with Claude Code


Summary by cubic

Ports Magento integration to @decocms/apps/magento for TanStack Start. Adds the config surface and two reference loaders to unblock Magento sites, with packaging, credential safety, lint coverage fixes, and unit tests covering client, features, and cart.

  • New Features

    • magento/client.ts: configureMagento(...), getMagentoConfig(), initMagentoFromBlocks(...), and magentoFetch() with Bearer auth, Referer, and optional x-origin-header.
    • magento/loaders/features.ts: returns feature flags from config.
    • magento/loaders/cart.ts: reads dataservices_cart_id and fetches the active cart; returns null when missing or 404.
    • magento/middleware.ts: passthrough scaffold matching @decocms/apps/commerce middleware shape.
    • magento/types.ts and magento/index.ts: shared types and re-exports; package.json adds @decocms/apps/magento/* export paths.
  • Bug Fixes

    • Publishing: added magento/ to package.json files so the app ships in the npm tarball.
    • Security: encode site and cartId in the cart loader path to prevent path injection.
    • Security: magentoFetch() strips all Magento identity headers on cross-origin URLs (Authorization, x-origin-header, forced Referer) and only attaches them for same-origin requests.
    • Correctness: cart loader now hits /rest/:site/V1/carts/:cartId (fixes missing /rest prefix).
    • Tooling: added magento/** to biome.json includes so linting covers the new package.

Written for commit 9c76c6d. Summary will update on new commits.

Review in cubic

Starts the Magento app port to @decocms/apps following the same shape as
vtex/ and shopify/. This first commit lands the configure surface and 2
reference loaders (features, cart) — enough to unblock real consumer
sites; the remaining ~20 loaders/actions are itemized in
magento/README.md and will follow in separate commits.

Contents:
- magento/client.ts — configureMagento({ baseUrl, apiKey, storeId, ... })
  with module-global state, mirroring configureVtex. magentoFetch()
  helper attaches Bearer auth + Referer + optional x-origin-header on
  every call. initMagentoFromBlocks(blocks) resolves the CMS block's
  `__resolveType: "website/loaders/secret.ts"` references via env vars,
  same fallback granadobr-tanstack already uses in production.
- magento/types.ts — MagentoCart + MagentoCartItem shapes used by the
  ported loaders.
- magento/loaders/features.ts — returns the resolved Features block
  from the config. The simplest loader, used as the smoke test.
- magento/loaders/cart.ts — fetches the customer's active cart by
  reading `dataservices_cart_id` cookie via @decocms/start/sdk/cookie
  and calling the Magento admin REST endpoint. Returns null for
  anonymous sessions (expected) and on 404 (expired cookie).
- magento/middleware.ts — passthrough today; the legacy
  changeCardIdAfterCheckout reconciliation flow is deferred to a
  follow-up PR.
- magento/index.ts — re-export entry, parallel to vtex/index.ts.
- package.json — adds @decocms/apps/magento/* exports.

Motivation:
deco-sites/granadobr-tanstack (Granado, Brazilian cosmetics) just
migrated from Fresh/Deno to TanStack Start. Its parity audit reported
a HIGH severity finding:

  invoke(magento/loaders/features) failed: handler not found

…because no @decocms/apps/magento/* resolver existed. The site is
working around it with an in-site adapter that re-uses the legacy
mod.ts shape; this PR begins the upstream fix so the next Magento
storefront doesn't need to repeat the work.

Companion issue: #60

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 8 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread package.json Resolved
Comment thread magento/loaders/cart.ts Resolved
Comment thread magento/client.ts Resolved
JonasJesus42 and others added 2 commits June 2, 2026 16:59
1. package.json: `magento/` was in `exports` but not `files`. npm publish
   excludes any path not listed under `files`, so the entire magento
   folder would be missing from the published tarball — every consumer
   site would get module-resolution errors. Added `magento/` to the
   array alongside commerce/shopify/vtex/etc.

2. magento/loaders/cart.ts: cartId comes from a request cookie
   (`dataservices_cart_id`) and was spliced into the admin REST path
   unencoded. Wrapped both `site` and `cartId` in encodeURIComponent so
   user input can't break out of the path segment to tack on query or
   fragment parts that would hit a different endpoint with the
   privileged Bearer token attached.

3. magento/client.ts: magentoFetch() accepted any `path` value, including
   absolute URLs to arbitrary hosts. The auth headers (Bearer, Referer,
   x-origin-header) were attached unconditionally, so a caller passing
   `https://attacker.example/...` would leak the Magento admin token.
   Now constructs a URL up front, compares its origin against the
   configured baseUrl, and force-disables `authenticated` when the
   request is cross-origin. Genuine third-party calls remain possible
   via the explicit `authenticated: false` opt-out.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Biome's includes array was missing magento/**, so the new package was
skipped by lint entirely. Added it to the includes alongside the other
apps. Also ran biome --write to convert space indentation to tab (project
convention) across the 5 magento source files.

Note: the test job also surfaces pre-existing lint errors in vtex/__tests__/
client-set-cookie-forward.test.ts and website/components/__tests__/
OneDollarStats.test.ts. Those are unrelated to this PR — they were already
failing on main before any magento file was added. Splitting that into a
separate PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 7 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread magento/client.ts Resolved
JonasJesus42 and others added 2 commits June 2, 2026 17:45
…ests

Cubic's second pass caught that the previous fix only suppressed the
Bearer token but still leaked `x-origin-header` (an opaque secret) and
a forced `Referer` pointing at the Magento storefront URL whenever a
caller passed an absolute non-Magento URL.

Now `buildHeaders` takes an explicit `attachMagentoIdentity` flag.
`magentoFetch` sets it to `target.origin === baseUrl.origin`, so a
cross-origin call gets only whatever headers the caller passed in their
`opts.headers` — no Magento-side credentials, no origin-header secret,
no forced Referer.

Callers wanting a genuinely cross-origin GET should still flip
`authenticated: false` at the call site for intent, but security no
longer relies on that single flag being correct.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…eno prod)

Adds 21 unit tests across 3 files covering the surfaces this PR ports.
Tests pin behavior the Fresh/Deno production code (deco-cx/apps/magento)
established, so future refactors of the apps-start port can refactor
freely without drifting from prod.

magento/__tests__/client.test.ts (12 tests):
  configureMagento / getMagentoConfig:
    - throws before configure (no implicit defaults)
    - returns the configured value after configure
  magentoFetch — same-origin:
    - attaches Authorization + x-origin-header + forced Referer
    - resolves relative path against baseUrl
    - authenticated:false drops Bearer (still attaches origin/referer)
    - preserves caller-supplied Referer (no force-overwrite)
  magentoFetch — cross-origin guard:
    - strips Bearer (regression for cubic finding #1)
    - strips x-origin-header (regression for cubic finding #2)
    - strips forced Referer (regression for cubic finding #2)
    - forwards caller-supplied headers through
    - same-origin absolute URL still gets identity headers

magento/__tests__/features.test.ts (2 tests):
  - returns the configured features object
  - returns {} when features omitted

magento/__tests__/cart.test.ts (7 tests):
  - returns null when no cookie (matches prod's `if (!cartId) return null`)
  - reads dataservices_cart_id cookie (JSON-quoted form)
  - reads dataservices_cart_id cookie (raw form, no quotes)
  - props.cartId override beats the cookie
  - URL-encodes cartId — regression for cubic finding #3 (path injection)
  - 404 returns null (expired cookie)
  - non-404 errors throw
  - cart fetch attaches Bearer + x-origin-header (same-origin)

Drive-by fix: cart loader was hitting /:site/V1/carts/:cartId, but Magento
exposes the cart endpoint at /rest/:site/V1/carts/:cartId — the /rest/
prefix is mandatory and matches the legacy clientAdmin's typed key
`GET /rest/:site/V1/carts/:cartId`. Tests pin the corrected path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 4 files (changes from recent commits).

You’re at about 91% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread magento/loaders/cart.ts Resolved
@JonasJesus42
JonasJesus42 merged commit 4b80931 into main Jun 2, 2026
1 of 2 checks passed
@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

🎉 This PR is included in version 2.1.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

JonasJesus42 added a commit that referenced this pull request Jun 2, 2026
…#63)

Third PR in the magento-port series (after #61 scaffold + #62 utils
foundation). Lands the two simplest actions — both are self-contained
HTTP/GraphQL POSTs with no Granado-specific dependencies.

Files (4 new, 1 modified):

  magento/types.ts (modified)
    + NewsletterData              { success, message }
    + ProductStockAlertResponse   { data?: { productStockAlert: ... } }

  magento/actions/newsletter/subscribe.ts (new)
    POSTs to /rest/:site/V1/newsletter/subscribed with the customer
    email and the resolved storeId. Verbatim port of the legacy 3-arg
    loader, but reads config from getMagentoConfig() and uses
    magentoFetch (so auth/origin/Referer headers come along
    automatically on same-origin). Returns null on success:false or
    non-2xx; payload otherwise — matches prod behavior.

  magento/actions/product/stockAlert.ts (new)
    Fires the ProductStockAlert GraphQL mutation against <baseUrl>/
    graphql. The legacy version called ctx.clientGraphql.query with a
    STALE cache hint, but mutations are write-only — no cache effect.
    Port omits the hint; behavior is observationally identical from a
    consumer's perspective. Returns { data: { productStockAlert } } or
    { error: string }.

  magento/__tests__/newsletter-subscribe.test.ts (new — 6 tests)
    - POSTs to encoded path
    - Body shape { email, store_id: number }
    - storeId coerced to number even when CMS holds it as string
    - Returns payload on success
    - Returns null on success:false (Magento failure shape)
    - Returns null on non-2xx HTTP status

  magento/__tests__/product-stockAlert.test.ts (new — 4 tests)
    - POSTs to <baseUrl>/graphql with the mutation body
    - Returns { data: { productStockAlert } } on success
    - Returns { error } when GraphQL payload lacks productStockAlert
    - Returns { error } when fetch throws

Test totals: 7 files / 59 tests passing in ~165ms.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant