Repository navigation
feat(magento): initial scaffold port from deco-cx/apps to apps-start - #61
Conversation
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]>
There was a problem hiding this comment.
3 issues found across 8 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
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]>
There was a problem hiding this comment.
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
…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]>
There was a problem hiding this comment.
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
|
🎉 This PR is included in version 2.1.0 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
…#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]>
Summary
Brings the
website/matchers/location.tsbuiltin matcher back to parity withdeco-cx/apps/website/matchers/location.ts. The current implementation diverged in three places that surface as broken regional segmentation in production:cf-region— the name — instead ofcf-region-code— the ISO code), so a rule typed asSPnever matched a Brazilian visitor.regionNamefallback the original doesn't have, and silently treating Map-mode entries ({coordinates: "lat,lng,radius"}) as vacuouslytrue. Any rule authored through the admin's Map UI matched every visitor.injectGeoCookiespropagated geo only via__cf_geo_*cookies — consumers using the upstream patternrequest.headers.get("cf-region-code")gotnull.Discovered while debugging a Casa & Video segmentation incident where the merchant's "Rio variant" never displayed.
Changes
src/matchers/builtins.ts— full rewrite ofgetGeoData/matchLocation/locationMatchermirroring upstream's closure pattern, plus an inlinehaversineWithinRadius(~12 lines) so Map-mode entries actually evaluate.src/admin/schema.ts— schema now declares the(Location | Map)union the admin writes: addscoordinatesfield; addsexamples(SP,RJ,47,-23.55,-46.63,5000) anddescriptionon every input, including the long-form note thatregionCodematches the rawcf-region-codevalue (numeric codes work iff CF returns them).src/sdk/workerEntry.ts—injectGeoCookiesnow 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 includeregionId: geoRegioninbuildSegmentby 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:include SPinclude RJinclude '47'country='Brasil'haversine SP 50kmhaversine Rio 50kmA full
multivariate/section.tsflag 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 typechecknpm run buildnpx vitest run src/matchers/builtins.test.ts(22 tests passing)npx vitest run(709 tests passing — no regressions)storefront-tanstack/miamivia patched node_modules: variant resolving per region; cache key splits viar=SP/r=RJsegmentNotes 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.tsupdated to includeregionId: cf-region-codeinbuildSegment— 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/magentofor 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(...), andmagentoFetch()with Bearer auth,Referer, and optionalx-origin-header.magento/loaders/features.ts: returns feature flags from config.magento/loaders/cart.ts: readsdataservices_cart_idand fetches the active cart; returnsnullwhen missing or404.magento/middleware.ts: passthrough scaffold matching@decocms/apps/commercemiddleware shape.magento/types.tsandmagento/index.ts: shared types and re-exports;package.jsonadds@decocms/apps/magento/*export paths.Bug Fixes
magento/topackage.jsonfilesso the app ships in the npm tarball.siteandcartIdin the cart loader path to prevent path injection.magentoFetch()strips all Magento identity headers on cross-origin URLs (Authorization,x-origin-header, forcedReferer) and only attaches them for same-origin requests./rest/:site/V1/carts/:cartId(fixes missing/restprefix).magento/**tobiome.jsonincludes so linting covers the new package.Written for commit 9c76c6d. Summary will update on new commits.