Skip to content

fix(core): use authenticator route for setpassword#3380

Merged
eduardoformiga merged 2 commits into
devfrom
feat/replace-vtexid-setpassword-route
Jun 17, 2026
Merged

fix(core): use authenticator route for setpassword#3380
eduardoformiga merged 2 commits into
devfrom
feat/replace-vtexid-setpassword-route

Conversation

@renatomaurovtex

@renatomaurovtex renatomaurovtex commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Migrates the My Account → Security → Reset password flow off the deprecated VTEX ID endpoint onto the new authenticator route, per SFS-3056.

  • US-1 — Successful reset: useSetPassword now posts to /api/authenticator/pub/authentication/classic/setpassword?expireSessions=true&an={accountName} instead of /api/vtexid/pub/authentication/classic/setpassword. Method (POST), credentials: 'include', the multipart/form-data body (login, currentPassword, newPassword, accesskey, recaptcha) and the authStatus → authMessage mapping are all unchanged, so the success/error toasts and drawer behavior stay identical.
  • US-2 — Error mapping: existing authStatus values (wrongcredentials, invalidemail, etc.) still resolve to the same user-facing messages; the non-2xx and thrown-error paths are untouched.
  • US-3 — accountName propagation: the account name is now passed explicitly via the an query string (encodeURIComponent-ed), sourced from the useSetPassword(accountName) argument already plumbed through SecurityDrawer, with a defensive fallback to config.api.storeId so an is never empty.

The change is isolated to packages/core/src/sdk/account/useSetPassword.ts. No public API, GraphQL schema, codegen, or UI changes.

Tests

Adds packages/core/test/sdk/account/useSetPassword.test.ts covering:

  • the new authenticator URL with expireSessions=true&an=… (and absence of /api/vtexid/);
  • POST + credentials: 'include' + form-data body shape;
  • success path (authStatus: success);
  • error mapping (wrongcredentialsWrong credentials);
  • accountName fallback to config.api.storeId.

All 5 new tests pass. Pre-existing failures in test/pages/api/graphql.test.ts and test/utils/cookieCacheBusting.test.ts are unrelated (verified they fail without this change; the former belongs to the separate, not-yet-implemented BFF 4xx forwarding spec).

Out of scope

  • Migrating the other /api/vtexid/pub/... callers (startlogin inside the same hook, logout in OrganizationDrawer) — tracked as follow-ups.
  • GraphQL password.graphql types (this flow is REST-only).

Spec

specs/replace-vtexid-setpassword-route.md (status: Done). The specs/ directory is git-ignored in this repo, so the spec file is not part of this PR.

Made with Cursor

Summary by CodeRabbit

  • Refactor

    • Improved password-change flow with tighter authentication integration, consistent account identification fallback, and better session-expiry handling for more reliable credential updates.
  • Tests

    • Added end-to-end tests covering password submission, credential validation, authentication responses, and account fallback behavior to ensure correct success/error messaging.

Migrate the My Account "Reset password" flow off the deprecated VTEX ID
endpoint (/api/vtexid/pub/authentication/classic/setpassword) onto the new
authenticator route
(/api/authenticator/pub/authentication/classic/setpassword), passing the
account name explicitly via the `an` query string and falling back to
config.api.storeId when it is missing.

The hook's public surface (useSetPassword / setPassword) and the request
body, method, credentials, and authStatus error mapping are unchanged.

Adds unit coverage for useSetPassword (URL composition, body, success and
error paths, accountName fallback).

Ref: SFS-3056
Co-authored-by: Cursor <cursoragent@cursor.com>
@renatomaurovtex
renatomaurovtex requested a review from a team as a code owner June 4, 2026 19:00
@renatomaurovtex
renatomaurovtex requested review from gabpaladino and renatamottam and removed request for a team June 4, 2026 19:00
@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 25d699d3-e583-4cd9-a0a5-ca5548587dab

📥 Commits

Reviewing files that changed from the base of the PR and between c48a56a and a59fb4b.

📒 Files selected for processing (2)
  • packages/core/src/sdk/account/useSetPassword.ts
  • packages/core/test/sdk/account/useSetPassword.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/src/sdk/account/useSetPassword.ts
  • packages/core/test/sdk/account/useSetPassword.test.ts

Walkthrough

useSetPassword now encodes an account identifier as an, posts to authenticator setpassword with an, and calls the authenticator start endpoint with the same an. Tests validate endpoints, query params, FormData bodies, credentials, fallback storeId, and response mapping.

Changes

Set-Password Endpoint Migration

Layer / File(s) Summary
Implementation: setPassword and startLogin updates
packages/core/src/sdk/account/useSetPassword.ts
Derives an = encodeURIComponent(accountName ?? config.api.storeId), calls /api/authenticator/.../setpassword?expireSessions=true&an=${an} with FormData, updates startLogin to /api/authenticator/pub/authentication/start?an=${an} and reduces posted fields; updates useCallback deps.
Tests: request assertions and response mapping
packages/core/test/sdk/account/useSetPassword.test.ts
Adds Vitest jsdom tests that mock discovery.config and fetch; assert setpassword and start endpoints use an, credentials: 'include', expected FormData fields, fallback to config.api.storeId, and mapping of authStatus to { success, message }.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

hotfix

Suggested reviewers

  • eduardoformiga
  • lucasfp13

Poem

🔐 A hook that learns an encoded name,
Routes to auth so calls stay the same,
Tests keep watch on FormData flow,
Credentials included — ready to go!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: migrating the setPassword flow from the deprecated /api/vtexid route to the new /api/authenticator route, which is the primary objective of the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/replace-vtexid-setpassword-route

Comment @coderabbitai help to get the list of available commands and usage tips.

@codesandbox-ci

codesandbox-ci Bot commented Jun 4, 2026

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/core/src/sdk/account/useSetPassword.ts (1)

42-121: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Add accountName to the useCallback dependency array.

The setPassword callback uses accountName (lines 46, 56) but omits it from the dependency array. If accountName changes between renders, the callback will continue using the stale value, sending the wrong account identifier to the API.

🔧 Proposed fix
-  }, [])
+  }, [accountName])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/sdk/account/useSetPassword.ts` around lines 42 - 121, The
setPassword callback (defined with useCallback) closes over accountName but the
dependency array is empty, which can cause stale accountName to be used; update
the useCallback dependencies to include accountName (and any other external
values like config or authMessage if they are not stable) so setPassword
recalculates when accountName changes, e.g., add accountName to the dependency
array of the useCallback that defines setPassword.
🧹 Nitpick comments (1)
packages/core/test/sdk/account/useSetPassword.test.ts (1)

44-147: 💤 Low value

Consider adding a test for special characters in accountName.

While URL encoding is handled correctly in the implementation, an explicit test verifying that special characters (spaces, &, =, etc.) in accountName are properly encoded in the query string would strengthen confidence in edge cases.

💡 Example test case
it('properly URL-encodes special characters in accountName', async () => {
  mockFetch
    .mockResolvedValueOnce(okResponse({}))
    .mockResolvedValueOnce(okResponse({ authStatus: 'success' }))

  const { result } = renderHook(() => useSetPassword('my store & co'))

  await act(async () => {
    await result.current.setPassword(validInput)
  })

  const url = String(getSetPasswordCall()?.[0])
  expect(url).toContain('an=my%20store%20%26%20co')
})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/sdk/account/useSetPassword.test.ts` around lines 44 - 147,
Add a test in the useSetPassword suite to verify accountName URL-encoding: mock
responses with mockFetch (using okResponse), render the hook with a name
containing special characters (e.g., "my store & co") via renderHook(() =>
useSetPassword('my store & co')), call result.current.setPassword(validInput)
inside act, then inspect getSetPasswordCall() and assert the request URL
contains the properly encoded query parameter (an=my%20store%20%26%20co).
Reference useSetPassword, getSetPasswordCall, mockFetch, okResponse, and
validInput when adding the test.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/core/src/sdk/account/useSetPassword.ts`:
- Around line 42-121: The setPassword callback (defined with useCallback) closes
over accountName but the dependency array is empty, which can cause stale
accountName to be used; update the useCallback dependencies to include
accountName (and any other external values like config or authMessage if they
are not stable) so setPassword recalculates when accountName changes, e.g., add
accountName to the dependency array of the useCallback that defines setPassword.

---

Nitpick comments:
In `@packages/core/test/sdk/account/useSetPassword.test.ts`:
- Around line 44-147: Add a test in the useSetPassword suite to verify
accountName URL-encoding: mock responses with mockFetch (using okResponse),
render the hook with a name containing special characters (e.g., "my store &
co") via renderHook(() => useSetPassword('my store & co')), call
result.current.setPassword(validInput) inside act, then inspect
getSetPasswordCall() and assert the request URL contains the properly encoded
query parameter (an=my%20store%20%26%20co). Reference useSetPassword,
getSetPasswordCall, mockFetch, okResponse, and validInput when adding the test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4ea60d6f-5461-46bf-a02c-285ae75edf83

📥 Commits

Reviewing files that changed from the base of the PR and between 25a03d5 and c48a56a.

📒 Files selected for processing (2)
  • packages/core/src/sdk/account/useSetPassword.ts
  • packages/core/test/sdk/account/useSetPassword.test.ts

@eduardoformiga

Copy link
Copy Markdown
Member

Testei com as mudanças na loja de b2b e o fluxo não funcionou, está dando mensagem de InvalidToken.
referencia: https://vtex.slack.com/archives/C08P582BAKH/p1781124705319119

Updated the setPassword function to explicitly pass the account name as a query parameter in the startLogin request. This change improves the URL composition for the authentication process. Additionally, added unit tests to verify the new behavior, ensuring that the correct API endpoints and request bodies are used.

Ref: SFS-3056
@pkg-pr-new

pkg-pr-new Bot commented Jun 11, 2026

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@a59fb4b

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@a59fb4b

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@a59fb4b

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@a59fb4b

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@a59fb4b

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@a59fb4b

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@a59fb4b

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@a59fb4b

commit: a59fb4b

@sonar-workflows

Copy link
Copy Markdown

@eduardoformiga eduardoformiga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Blocker resolvido internamente, podemos seguir com o merge.

@eduardoformiga
eduardoformiga merged commit a155269 into dev Jun 17, 2026
12 of 13 checks passed
@eduardoformiga
eduardoformiga deleted the feat/replace-vtexid-setpassword-route branch June 17, 2026 16:55
@eduardoformiga eduardoformiga mentioned this pull request Jun 17, 2026
2 tasks
eduardoformiga added a commit that referenced this pull request Jun 17, 2026
## Summary

Graduate the `4.3.0-dev.8` prerelease cycle to the stable `4.3.0`
release on `latest`.

Merging this PR triggers CD on `main`, which runs `lerna version
--conventional-graduate` and publishes all `@faststore/*` packages to
the `latest` dist-tag.

### Features
- Password Protection (v4) (#3276)
- File upload via Order Entry Service (OES) (#3334)
- Add sitemap to CMS Landing Page content-type (#3386)

### Bug Fixes
- **core:** use authenticator route for setpassword (#3380)
- migrate partytown `@builder.io` → `@qwik.dev@0.14.0` (#3394)
- **api:** use account-scoped cookie in orderEntry headers (#3395)
- forward auth token only via account-scoped cookie (#3381)
- **core:** propagate upstream error status instead of always 500
(#3379)

## Pre-flight (faststore-release skill)
- Working tree clean; `release.yml` has `fetch-depth: 0`
- All 8 packages have `repository.url`
- No breaking changes since `v4.2.0`
- `dev → main` merges cleanly (no CHANGELOG/codegen conflicts)
- No unmerged hotfixes on `main` (accidental `4.2.1` was fully reverted
in #3375)

## Test plan
- [ ] CI green on this PR
- [ ] After merge, confirm CD publishes all 8 packages at `4.3.0` under
`latest`

Made with [Cursor](https://cursor.com)

---------

Co-authored-by: Matheus P. Silva <cout.matheusps@gmail.com>
Co-authored-by: vtexgithubbot <vtexgithubbot@github.com>
Co-authored-by: Lucas Feijó <lucas.portela@vtex.com>
Co-authored-by: Luiz Falcão <39093175+llfalcao@users.noreply.github.com>
Co-authored-by: Artur Santiago <artur.santiago@cubos.io>
Co-authored-by: Larícia Mota <laricia.mota@vtex.com.br>
Co-authored-by: Sahan Jayawardana <sahan@clouda.io>
Co-authored-by: Mateus Pontes <mateuspo10@gmail.com>
Co-authored-by: Matheus Martins <mathews_2010@outlook.com>
Co-authored-by: renatomaurovtex <167437775+renatomaurovtex@users.noreply.github.com>
Co-authored-by: Leandro Rodrigues <leandro.rodrigues@vtex.com>
Co-authored-by: Fanny Chien <fanny.chien@vtex.com>
Co-authored-by: Arthur Andrade <arthurfelandrade@gmail.com>
Co-authored-by: Leandro Rodrigues <leandro.swf@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Thiago Pereira <thiago.pereira@vtex.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Giuliana Rigaud <62848434+giurigaud@users.noreply.github.com>
Co-authored-by: renato <renato.neto@cubos.io>
Co-authored-by: Bruna Santos <brunassdev@gmail.com>
Co-authored-by: BrunaCubos <104789782+BrunaCubos@users.noreply.github.com>
Co-authored-by: Ícaro Oliveira <icarovinici@gmail.com>
Co-authored-by: Bruna Santos <bruna.santos@cubos.io>
Co-authored-by: Everton Ataide <everton.ataide@vtex.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Otavio Moreira Meirelles <otavio.meirelles@vtex.com>
Co-authored-by: Marco Cardoso <marcopaulo@outlook.com>
Co-authored-by: Gabriel Paladino <gabpaladino@users.noreply.github.com>
Co-authored-by: CodeRabbit <noreply@coderabbit.ai>
Co-authored-by: dk-portal[bot] <134092483+dk-portal[bot]@users.noreply.github.com>
Co-authored-by: Rodrigo Tavares <rodrigo.tavares@vtex.com>
Co-authored-by: vitorflg <vitor.gomes@vtex.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Válber Laux <valber.laux@vtex.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants