Repository navigation
fix(api): identify B2B sessions by organizational unit and contract - #3559
Conversation
Build session.b2b, accountProfile and the My Account B2B gate from the unitId and the contract instead of the isRepresentative claim, which can be true outside B2B and was dropped by an earlier token refresh path.
|
|
||
| if (jwt?.isRepresentative) { | ||
| if (jwt?.unitId?.trim()) { | ||
| const sessionData = await commerce.session('').catch(() => null) |
There was a problem hiding this comment.
[Evolvability.Organizational] 🟡 RESTRICT
The 'is this shopper a B2B representative' check is now implemented three different ways in this PR: query.ts only requires a non-blank jwt.unitId; validateSessionHelpers.buildB2bSession (via resolveB2bUnitId/firstNonBlank) requires both a unit AND a resolved customerId/contract; and packages/core/getIsRepresentative requires both jwt.unitId AND jwt.customerId. query.ts never calls the new resolveB2bUnitId helper and doesn't check customerId at all, so a shopper with a unitId but no contract could be routed into the B2B branch of accountProfile while packages/core's getIsRepresentative (used for UI gating) would classify the same shopper as non-representative.
Action: Reuse resolveB2bUnitId (and an equivalent contract/customerId check) in query.ts instead of inlining jwt?.unitId?.trim(), so the three call sites agree on what makes a shopper 'B2B'.
To dismiss: reply /dk-review dismiss [reason] under this comment
There was a problem hiding this comment.
Fixed in ab97c85. accountProfile now uses resolveB2bUnitId and resolves the contract with the same chain as buildB2bSession (session active contract, authentication.customerId, then the JWT). A unit without a contract falls back to the user profile, so the resolver, buildB2bSession and getIsB2BBuyer agree on what a B2B buyer is.
|
|
||
| if (jwt?.isRepresentative) { | ||
| if (jwt?.unitId?.trim()) { | ||
| const sessionData = await commerce.session('').catch(() => null) |
There was a problem hiding this comment.
[Functional.Check] 🟡 RESTRICT
jwt?.unitId?.trim() calls .trim() directly on the JWT claim without verifying it is a string first. The sibling change in packages/core/src/sdk/account/getIsRepresentative.ts explicitly guards with isNonBlankString (typeof check) precisely because JWT claim shapes aren't guaranteed — and a dedicated test ('with non-string claims') was added there to cover it. query.ts has no equivalent guard and no equivalent test, so a non-string unitId claim would throw inside the resolver.
Action: Use the same type-safe check (e.g. the new resolveB2bUnitId helper, or an isNonBlankString-style guard) here instead of calling .trim() on an untyped claim.
To dismiss: reply /dk-review dismiss [reason] under this comment
There was a problem hiding this comment.
Fixed in ab97c85. The resolver no longer calls .trim() on the claim: it goes through resolveB2bUnitId/firstNonBlank, which skip non-string values. Covered by the new "treats non-string unit and contract claims as missing" test in query.test.ts.
| describe('buildB2bSession', () => { | ||
| it('returns null when the shopper is not a representative', () => { | ||
| const emptyArgs = { | ||
| authentication: null, |
There was a problem hiding this comment.
[Functional.Support] 🟡 RESTRICT
These tests pin down a behavioral change to how B2B representative sessions are derived: buildB2bSession no longer accepts an isRepresentative flag and instead infers representative status purely from the presence of a unit + resolved contract, and getIsRepresentative/Query.accountProfile now ignore the JWT's isRepresentative claim entirely. This is a change to session/authentication-adjacent logic that decides which identity (shopper vs. representative) a request resolves to. AGENTS.md's Security & Data Handling section requires that modifications to authentication mechanisms get explicit human approval recorded in the PR description — nothing in the provided diff/PR context shows that approval was recorded.
Action: Confirm this change was reviewed as an authentication/session-resolution change and record explicit approval in the PR description, per AGENTS.md.
Source: AGENTS.md#security--data-handling
To dismiss: reply /dk-review dismiss [reason] under this comment
There was a problem hiding this comment.
Addressed. The PR description now has a "Security review" section describing the authorization impact (who gets the contract-level account data) and recording the approval of the new B2B session rule by @eduardoformiga.
DK Review — Audit SummaryVerdict:
Only BLOCK and RESTRICT findings anchored to a changed line are commented inline on the diff. The other 4 findings below open no review thread. Scenarios evaluated: feature-flags, general-review, quality-ratchet
📋 Findings (8)RESTRICT
SUGGEST
DK Review v1.0.0 | To dismiss a finding: reply |
Rename getIsRepresentative to getIsB2BBuyer and the isRepresentative props to isB2BBuyer, read session.b2b presence in the navigation, and stop reading the isRepresentative JWT claim in the API. StoreB2B.isRepresentative, B2bInfo.isRepresentative and the OrganizationSignInButton prop stay as deprecated aliases.
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
|
|
||
| if (jwt?.isRepresentative) { | ||
| if (jwt?.unitId?.trim()) { | ||
| const sessionData = await commerce.session('').catch(() => null) |
There was a problem hiding this comment.
[Functional.Check] 🟡 RESTRICT
The new gate jwt?.unitId?.trim() calls .trim() without first verifying unitId is a string. If the decoded JWT claim is present but not a string (malformed/legacy token), this throws a TypeError and crashes the accountProfile resolver. The same PR adds a type-safe isNonBlankString guard in getIsB2BBuyer.ts (and even tests it against non-string claims), but that guard isn't reused here.
Action: Reuse a shared isNonBlankString-style guard (check typeof unitId === 'string') before calling .trim(), consistent with getIsB2BBuyer.
To dismiss: reply /dk-review dismiss [reason] under this comment
There was a problem hiding this comment.
Fixed in ab97c85, same change as the thread above: the gate uses resolveB2bUnitId, which only accepts non-blank strings, with a test for non-string claims.
| } | ||
|
|
||
| function firstNonBlank(...values: Array<string | null | undefined>): string { | ||
| for (const value of values) { |
There was a problem hiding this comment.
[Functional.Check] 🟡 RESTRICT
firstNonBlank (used by resolveB2bUnitId and the new buildB2bSession customerId resolution chain) calls value?.trim() without checking typeof value === 'string'. The parameters come from JWT claims and session/authentication namespace values that are only nominally typed as strings; if the actual runtime value is non-string (e.g. a malformed token or unexpected session payload shape), this throws instead of degrading gracefully, unlike the isNonBlankString helper added elsewhere in this same PR.
Action: Add a typeof value === 'string' check inside firstNonBlank before calling .trim().
To dismiss: reply /dk-review dismiss [reason] under this comment
There was a problem hiding this comment.
Fixed in ab97c85. firstNonBlank now takes unknown values and checks typeof value === "string" before trimming. Covered by "returns null when the claims are not strings" in validateSessionHelpers.test.ts.
|
|
||
| if (jwt?.isRepresentative) { | ||
| if (jwt?.unitId?.trim()) { | ||
| const sessionData = await commerce.session('').catch(() => null) |
There was a problem hiding this comment.
[Functional.Logic] 🟡 RESTRICT
accountProfile now treats a shopper as B2B solely based on jwt?.unitId?.trim(), while the two other B2B-detection implementations introduced in this same PR (getIsB2BBuyer in core, and resolveB2bUnitId/buildB2bSession in the API) both require a non-blank unitId AND a non-blank customerId/contract before treating the session as B2B. If a JWT can ever carry a unitId without a customerId, this resolver will take the B2B/contract branch while the rest of the app (navbar, account layout, page gating) would not consider the user a B2B buyer, producing inconsistent behavior across the product.
Action: Reuse the same unit+customerId check (e.g. via resolveB2bUnitId plus a customerId check, or a shared helper) in accountProfile instead of a standalone unitId check.
To dismiss: reply /dk-review dismiss [reason] under this comment
There was a problem hiding this comment.
Fixed in ab97c85. accountProfile now requires both the unit and a resolved contract before taking the B2B branch, consistent with buildB2bSession and getIsB2BBuyer. Tests cover a unit without a contract (user profile) and a contract coming only from the session.
…d non-string claims
|
| let contract = null | ||
| if (isRepresentative && profile?.id?.value) { | ||
| if (resolveB2bUnitId(authentication, unitId) && profile?.id?.value) { | ||
| try { |
There was a problem hiding this comment.
[Functional.Logic] 🟡 RESTRICT
validateSession fetches the B2B contract keyed only by profile.id.value (if (resolveB2bUnitId(authentication, unitId) && profile?.id?.value) { contract = await getContractById({ contractId: profile.id.value }) }), but buildB2bSession now resolves the returned customerId field with a different priority chain that puts shopper.activeContractId.value first (validateSessionHelpers.ts: firstNonBlank(args.shopper?.activeContractId?.value, args.authentication?.customerId?.value, args.customerId)). resolveActiveContractIdFromSession in utils/contract.ts documents these three session fields (shopper.activeContractId, authentication.customerId, profile.id) as independent values that can disagree — it exists precisely as a fallback chain for the availableContracts resolver. No code in this repo writes shopper.activeContractId; it is set externally by VTEX Session Manager/buyer-portal when a shopper switches their active contract, so there is no guarantee profile.id.value is refreshed in lockstep. When they diverge, buildB2bSession returns a b2b.customerId for the newly active contract while b2b.contractName (derived from the contract fetched via the stale profile.id.value) still reflects the previous contract — surfacing a contract id and organization name that belong to two different contracts.
Action: Fetch the contract (and gate the fetch) using the same contractId priority chain used for customerId in buildB2bSession (shopper.activeContractId → authentication.customerId → jwt customerId), e.g. reuse resolveActiveContractIdFromSession/firstNonBlank for the getContractById call in validateSession.ts instead of hardcoding profile.id.value.
To dismiss: reply /dk-review dismiss [reason] under this comment
|
|
||
| if (jwt?.isRepresentative) { | ||
| if (resolveB2bUnitId(null, jwt.unitId)) { | ||
| const sessionData = await commerce.session('').catch(() => null) |
There was a problem hiding this comment.
[Functional.Logic] 🟡 RESTRICT
accountProfile's B2B gate resolveB2bUnitId(null, jwt.unitId) only ever consults the JWT's unitId claim (authentication is hard-coded to null), while validateSession.ts/buildB2bSession prefer the live session's authentication.unitId and only fall back to the JWT claim. Since this PR ships an organizational-unit switcher (OrganizationDrawer 'switch' view) that updates the session without reissuing the JWT, a shopper whose unit changes mid-session (or who never had a unit in the original JWT) can have accountProfile silently fall through to the b2c branch even though session.b2b reports them as a B2B buyer elsewhere in the app.
Action: Fetch the session first (or restructure the resolver) so the gate can use resolveB2bUnitId(authentication, jwt.unitId) the same way validateSession.ts does, keeping the two resolvers' B2B determination consistent.
To dismiss: reply /dk-review dismiss [reason] under this comment
| let contract = null | ||
| if (isRepresentative && profile?.id?.value) { | ||
| if (resolveB2bUnitId(authentication, unitId) && profile?.id?.value) { | ||
| try { |
There was a problem hiding this comment.
[agents-md.auth-approval-required] 🟡 RESTRICT
This PR changes how B2B/representative status is derived from the VTEX ID JWT and session authentication claims (resolveJwtClaims, resolveB2bUnitId, buildB2bSession), and that derivation now also gates page-level authorization (e.g. user-details.tsx redirects unauthenticated-for-B2B users). The repository's AGENTS.md states: 'Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description.' Please confirm this approval is recorded.
Action: Add a note in the PR description documenting the human review/approval of this authentication-claim behavior change, per AGENTS.md's Security & Data Handling policy.
Source: AGENTS.md#security--data-handling
To dismiss: reply /dk-review dismiss [reason] under this comment
| describe('buildB2bSession', () => { | ||
| it('returns null when the shopper is not a representative', () => { | ||
| const emptyArgs = { | ||
| authentication: null, |
There was a problem hiding this comment.
[Functional.Security] 🟡 RESTRICT
The diff removes the isRepresentative flag entirely from B2B session/JWT-claim resolution (buildB2bSession, resolveJwtClaims, Query.accountProfile) and replaces it with implicit B2B-buyer detection based on presence of a unit + contract claim. This changes how authorization-relevant session state is derived from the JWT, which falls under 'Modifications to authentication ... mechanisms require explicit human approval recorded in the PR description' per AGENTS.md Security & Data Handling.
Action: Confirm the PR description explicitly documents and records human approval for this change to JWT/session-based B2B authorization logic before merging.
To dismiss: reply /dk-review dismiss [reason] under this comment

0 New Issues
0 Fixed Issues
0 Accepted Issues
What's the purpose of this pull request?
FastStore decides whether a shopper is a B2B buyer from the
isRepresentativeclaim in the VTEX ID token. That flag is not the rule Buyer Portal uses: it identifies a B2B buyer by the organizational unit (unitId) plus a contract (customerId). The flag can betrueoutside B2B, and an earlier token refresh path dropped it (and theunitId), turning B2B buyers into B2C ones.Because
session.b2bwasnullwhenever the flag was off, every client fix that depends on it (PLP refetch, contract switching, refresh token, Quotes and Cards in My Account) silently skipped buyers who have a unit and a contract but no flag.How it works?
buildB2bSession(@faststore/api): returnsb2bonly when there is a unit and a contract. The unit comes from the sessionauthenticationnamespace or the JWT; the contract from the session's active contract, thenauthentication.customerId, then the JWT. Blank values fall through. TheisRepresentativeargument is gone; the field in the returned object staystrue, so existing consumers that read it as "B2B member" keep working.validateSession: the contract lookup is gated on the unit instead of the flag.accountProfile: follows the same rule. It returns the contract information when the token has a unit and a contract is found (session active contract,authentication.customerId, then the JWT), regardless of the flag. A unit without a contract, or a token without a unit (even if flagged as representative), gets the user profile.getIsB2BBuyer(@faststore/core, formerlygetIsRepresentative): true when the token carries a non-blankunitIdandcustomerId. It gates the organization drawer and the B2B pages in My Account. TheisRepresentativeprops in the account and navigation components are renamed toisB2BBuyer, and the navigation readssession.b2bpresence instead ofb2b.isRepresentative.isRepresentativeclaim is no longer read by FastStore.resolveJwtClaimsstops returning it.Deprecations (no breaking change)
StoreB2B.isRepresentative(GraphQL) is marked@deprecated. It is still returned astruewheneverb2bis set; check thatb2bis not null instead.B2bInfo.isRepresentative(@faststore/sdk) is marked@deprecatedwith the same meaning.OrganizationSignInButton_unstableaccepts the newisB2BBuyerprop and keepsisRepresentativeas a deprecated alias.Removal of these is left for the next major.
Security review
This changes how a session is classified as B2B, which decides who sees the contract-level account data: a unit member with a contract now gets it even without the
isRepresentativeflag, and a flagged token without a unit no longer does. The rule matches Buyer Portal and the order authorization, which already moved fromisRepresentativeto the unit. Change to the B2B session identification rule approved by @eduardoformiga.How to test it?
session.b2bis filled, the organization drawer and My Account B2B pages show up.session.b2bisnulland My Account shows the B2C menu.cd packages/api && pnpm test:unitandcd packages/core && pnpm vitest run --project node test/sdk/account/getIsB2BBuyer.test.tsplus the account and navigation browser tests.Starters Deploy Preview
Use the CodeSandbox build generated for this PR.
References
isB2BSessionin fix(core): keep the B2B contract across contract switch and token refresh #3525, which already requiresunitIdandcustomerId.Checklist