Skip to content

feat(redirects): honor the query a redirect source was scoped to - #520

Draft
igoramf wants to merge 2 commits into
fix/redirect-csv-query-self-loopfrom
feat/redirect-query-scoped
Draft

igoramf wants to merge 2 commits into
fix/redirect-csv-query-self-loopfrom
feat/redirect-query-scoped

Conversation

@igoramf

@igoramf igoramf commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Empilhado no #519. O base branch é fix/redirect-csv-query-self-loop, então o diff aqui mostra só o incremento. Mergear #519 primeiro.

O problema que sobra depois do #519

O #519 mata o loop descartando a regra. Isso está certo para um fix de incidente, mas cobra um preço: a linha descartada era um redirect legítimo.

normalizePath reduz a origem ao pathname, então uma regra escrita contra uma query legada não tem como dizer "só para essa query":

https://www.montecarlo.com.br/relogios?map=category-1,/relogios/todos,PERMANENT

Hoje ela vira uma regra para /relogios inteiro — redirecionando todo visitante da categoria, inclusive quem nunca teve a query. Quando o destino coincide com o próprio path, isso vira o loop do #519; quando não coincide, o estrago é mais silencioso: a página existe, mas ninguém consegue chegar nela.

O loader Fresh que este SDK substituiu casava a href inteira (isHref: true), então essas regras funcionavam. Todo site que migra de Fresh para TanStack as perde.

O que muda

  • Redirect.search carrega a query da origem. Essas regras vivem em RedirectMap.scoped, indexadas por pathname, inalcançáveis a partir de um path pelado.
  • matchRedirect(pathname, map, search?) — terceiro argumento opcional. Quem não passa mantém o comportamento de hoje, então é aditivo: nenhum call site existente quebra.
  • Regra com query ganha da regra de path puro no mesmo pathname — é o match mais específico.
  • Match por subconjunto, não igualdade: utm_source, gclid, fbclid anexados à request não derrubam a regra.
  • workerEntry.ts passa url.search.

Comportamento

Com a regra /relogios?map=category-1 → /relogios/todos:

Request Resultado
/relogios?map=category-1 301 → /relogios/todos
/relogios?map=category-1&utm_source=news 301 → /relogios/todos
/relogios passa direto
/relogios?map=outra-coisa passa direto

E a linha do incidente volta a fazer sentido em vez de ser descartada:

Request #519 sozinho com este PR
/aliancas passa direto passa direto
/aliancas?map=category-1 passa direto (regra perdida) 301 → /aliancas

Testes

packages/blocks/src/sdk/redirectsQueryScoped.test.ts, 9 casos: query exata, prefixo ?, params extras tolerados, regra multi-param exigindo todos, precedência sobre path puro, várias regras no mesmo pathname, blocos de CMS além de CSV, e regras sem query intocadas.

Suíte do pacote: 756 passed (57 arquivos). Typecheck do monorepo: os 6 erros que aparecem são pré-existentes em blocks-cli/scripts/migrate — mesmo número no main, confirmado com git stash.

Ponto de review

A mudança de API é matchRedirect ganhando um parâmetro e RedirectMap ganhando um campo. Ambos aditivos, mas RedirectMap é um tipo exportado — quem construir um à mão (não via loadRedirects) precisa do campo scoped. Se preferir, dá para deixá-lo opcional e tratar undefined; achei mais honesto exigir, já que loadRedirects sempre preenche.

🤖 Generated with Claude Code


Summary by cubic

Restores the query-scoped redirect rules that the #519 fix was discarding. A source like /relogios?map=category-1 previously lost its query, widening into a rule for the whole path — looping against its own target or silently hijacking the page — and now carries it and matches it at request time.

  • Redirect.search holds the source query; these rules live in RedirectMap.scoped, keyed by pathname and unreachable from a bare path.
  • matchRedirect(pathname, map, search?) gains an optional third argument; existing callers keep today's behavior.
  • workerEntry passes url.search so the rules fire in the worker.
  • Matching is a subset of the request params, so utm_* or gclid appended to the request don't defeat a rule.
  • A scoped rule wins over a bare-path rule on the same pathname.

Migration

  • RedirectMap.scoped is a new required field; maps built by hand, not via loadRedirects, need to add it.

Written for commit 3c86eeb. Summary will update on new commits.

Review in cubic

igoramf and others added 2 commits September 1, 2026 07:55
… loop

A rule whose source and target resolve to the same page answers every request
with a redirect back to the URL just asked for: ERR_TOO_MANY_REDIRECTS.

Bulk migration exports carry these rows, and `normalizePath` manufactures more:
it reduces an absolute `from` to `new URL(p).pathname`, which drops the query.
A row scoped to one legacy query

    https://www.example.com/aliancas?map=category-1  ->  /aliancas

therefore becomes `/aliancas -> /aliancas` and takes the page down. One
production storefront hit this twice from the same CSV — once on `/`, via a
`http://blog.example.com/,/` row, and once on a category page.

The Fresh loader this SDK replaced (deco-cx/apps
`website/loaders/redirectsFromCsv.ts`) had a `from === to` guard for exactly
this. Restore it, comparing after normalization so the collapsed rows above are
caught too.

Host is compared whenever both sides carry one, so a genuine cross-origin
redirect to the same path (`/x -> https://other.example.com/x`) still fires.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Stacked on #519, which stops query-scoped rows from looping by discarding them.
This restores what they are supposed to do.

`normalizePath` reduces a source to its pathname, so a rule written against one
legacy query — `https://site/relogios?map=category-1 -> /relogios/todos` — had
no way to express "only for that query". #519 drops such a row when it collapses
onto its own target; every other one silently widens into a rule for the whole
page, redirecting visitors who never had the query.

The Fresh loader this SDK replaced (deco-cx/apps
`website/loaders/redirectsFromCsv.ts`) matched the entire href, so these rules
worked. Sites migrating off it lose them today.

- `Redirect.search` carries the query the source was scoped to. Those rules live
  in `RedirectMap.scoped`, keyed by pathname, unreachable from a bare path.
- `matchRedirect(pathname, map, search?)` — new optional third argument.
  Existing callers keep today's behaviour, so this is additive.
- A scoped rule wins over a bare-path rule on the same pathname: it is the more
  specific match.
- Matching is a subset of params, not equality, so utm_*/gclid appended to the
  request do not defeat the rule.
- `workerEntry` passes `url.search`.

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

Copy link
Copy Markdown
Contributor

Cross-reference: #647 implements query-scoped sources the way Fresh's router did — exact.get(pathname + search) ?? exact.get(pathname), exact string match — rather than a separate subset-matching map. Query rows stay in the decofile so the fast-deploy KV lookup remains one read, keyed by pathname. Leaving the decision on which approach to land with the maintainers.

guitavano pushed a commit that referenced this pull request Oct 9, 2026
… handlers (307, query kept, no double-encode) (#647)

## Update — Fresh semantics are opt-in

The Fresh semantics below change what every site **already** on
`@decocms/*` answers on upgrade (302 → 307, `/Old` no longer matching
`/old`, the query now in `Location`). They are now **opt-in per site**:

```ts
createDecoWorkerEntry(serverEntry, { redirects: { semantics: "fresh" } });
```

(`setRedirectSemantics` in `@decocms/blocks/sdk/redirects` for code
outside the worker entry). The default, `"legacy"`, keeps today's
answers: case- and trailing-slash-insensitive match, temporary → 302,
query dropped.

**In both semantics** (rules that could never be served correctly):
- self-redirects dropped — `from === to`, and in `"legacy"` also the
ones folding creates (`/Calca/p → /calca/p`, `/x → /x?utm=1`), which
loop forever on `main`;
- `Location` not double-encoded (`%20` stays `%20`; non-ASCII/space
still encoded);
- a query-scoped source (`/x?map=ft`) matches `pathname + search` before
`pathname` (it never matched before);
- the CSV is parsed like Fresh's (`,`/`;` split,
`type`/`discardQueryParameters` by value, `forcePermanentRedirects`).

**KV-keyed redirects stay semantics-agnostic** (the sync runs where the
worker's choice is unknown): keys are `normalizePath` again — folded,
byte-identical to `main` — and each value carries the source as written,
as an array when several sources fold to one key
(`ExactRedirect.shadowed`). `selectExactRedirect` serves the last rule
for `"legacy"` (as `main`) and the byte-for-byte one for `"fresh"`.
Temporary is stored as 307 and answered 302 under `"legacy"`. Values
written before `from` existed are still read.

**Checked against `main`'s implementation with the redirect blocks of
two live `@decocms/tanstack` sites** (every rule ×
case/trailing-slash/query variants, in-memory and KV paths):
- site A (9 rules): 54/54 probes and 9/9 KV keys identical;
- site B (170 rules): 1008/1020 identical; the 12 differences are its 2
self-redirect rules (`/kit-…` → itself), which answer a 301 loop on
`main` and are now dropped.

Tests: `redirects.test.ts` now runs under `"fresh"`; new
`redirects.legacy.test.ts` (16) pins the default; `kvRedirects.test.ts`
(+3) covers folded lookup and both selections; `workerEntry.test.ts`
runs the Fresh cases with the option and adds an end-to-end legacy case.
`blocks`/`tanstack` typecheck clean; same pre-existing failures as
before (`loader`/`layoutCacheRace` on Node 22 without `URLPattern`, 3
draft-preview/CDN in `workerEntry.test.ts`).

The section below describes the `"fresh"` semantics.

---

## Problem

`@decocms/blocks/sdk/redirects` materializes a site's `redirects.csv`
(and `website/loaders/redirect(s).ts` blocks) with rules that differ
from the Fresh loaders/handlers it replaced. Validating
deco-sites/oficina-tanstack (5 835-row CSV) against the Fresh production
site, every one of them changed what a visitor gets:

| | Fresh (deco-apps) | `main` | Effect measured on the site |
|---|---|---|---|
| Source key | `pathname` (or `pathname + search`), byte for byte |
`normalizePath`: lower-cased, trailing slash dropped, `/` forced |
`/Calca-Linho-Santorini-Off-White-0077631037/p → /calca-…/p` became a
self-redirect: **3 live PDPs looped (`ERR_TOO_MANY_REDIRECTS`)**. Rows
differing only by case/slash overwrote each other (`/meia-pima-…/p` sent
to the `…/p/` row's destination). 206 lower-case paths that 404 in prod
started redirecting. |
| `type` | `permanent` → 301, anything else → 307 (exact compare) |
`permanent`/`301` → 301, else **302** | 107/310 sampled URLs: prod 307,
candidate 302 (82 % of the file is `PERMANENT`, which is 307 in Fresh).
|
| Query string | appended to `Location` unless `discardQueryParameters`
| dropped | `?utm_source=qa&gclid=x` lost on every CSV redirect —
campaign attribution. |
| `?query` in source | matches `pathname + search` first | never matches
(key kept the `?`, lookup used `pathname` only) |
`/garrafa-kouda-preta-…/p?listName=Kouda`: prod 307 →
`/roupas/acessorios?listName=Kouda`; candidate served the PDP. |
| `Location` | `to` as written | `encodeURI(to)` |
`…/Regulamento%20Oficina….pdf` → `%2520` → CDN 403. |
| `from === to` | dropped at load | kept | loop |

Full report with the 310-row table (prod × candidate, line by line):
`.context/qa-162-redirects.md` in deco-sites/oficina-tanstack#479.

## Reference behaviour

deco-apps as pinned by the Fresh site (`oficina-dev/deco-apps@60695e7`):
-
[`website/loaders/redirectsFromCsv.ts`](https://github.com/oficina-dev/deco-apps/blob/60695e70370e41b0b532066563c6e564b52c58e2/website/loaders/redirectsFromCsv.ts)
— field split `/,|;(?=(?:(?:[^"]*"){2})*[^"]*$)/`,
`type`/`discardQueryParameters` found by value (`findAndRemove`), `if
(!from || !to || from === to) continue`, `isHref: true`.
-
[`website/handlers/router.ts`](https://github.com/oficina-dev/deco-apps/blob/60695e70370e41b0b532066563c6e564b52c58e2/website/handlers/router.ts)
— `hrefRoutes[pathname + search] ?? hrefRoutes[pathname]`, exact,
case-sensitive.
-
[`website/handlers/redirect.ts`](https://github.com/oficina-dev/deco-apps/blob/60695e70370e41b0b532066563c6e564b52c58e2/website/handlers/redirect.ts)
— `temporary → 307`, `permanent → 301`, `Location = to + request query`
unless `discardQueryParameters`.

Curated blocks (`website/loaders/redirects.ts`) go through the same
router/handler, so the same semantics apply to them here.

## Fix

`packages/blocks/src/sdk/redirects.ts`
- `normalizePath` strips the origin of an absolute source and nothing
else (case, trailing slash and query are part of the URL). It is still
the KV key contract; the request pathname is already in that form.
- `matchRedirect` / `matchExactRedirect` take the request's `search` and
look up `pathname + search` before `pathname`.
- `parseRedirectsCsv` uses Fresh's split and reads `type` /
`discardQueryParameters` by value in any column;
`forcePermanentRedirects` is honoured (the loader prop).
- `permanent` → 301, anything else → 307. The `301` spelling the
previous parser accepted is kept.
- `from === to` rows dropped at load (CSV and blocks).
- New `redirectLocation(redirect, search)`: `to` + the request's query
sorted by key (pairs kept as sent — what the Fresh runtime handed the
handler), honouring `discardQueryParameters`; only characters a header
cannot carry are percent-encoded, so an existing `%20` stays `%20`.
- `splitExactRedirects` keeps query-scoped rules in the decofile (like
globs), so the fast-deploy KV lookup stays one read per request, keyed
by pathname. `ExactRedirect`/`StoredRedirect` carry
`discardQueryParameters`.

`packages/tanstack/src/sdk/workerEntry.ts` passes `url.search` and
answers with `redirectLocation`. `kvRedirects.ts` reads the new value
shape. `packages/blocks-cli/scripts/lib/csv-redirects.ts` carries
`discardQueryParameters` and `forcePermanentRedirects` into the
synthetic block. `docs/fast-deploy.md` updated.

## Behaviour change under `semantics: "fresh"` (opt-in — the default
keeps today's answers)

A site that opts in answers its redirects like the Fresh site it was
migrated from:
1. **Temporary redirects are 307, not 302.** Same semantics for GET; 307
is what Fresh served.
2. **Matching is case-sensitive and trailing-slash exact.** A rule
written as `/Old` no longer matches `/old`. Fresh never matched that
way, so a migrated CSV cannot have depended on it; a rule authored after
migration that relied on the folding would need its source fixed.
3. The request's query now travels with the `Location` (including
`?asJson`, so a client following the redirect still gets JSON — test
updated accordingly).
4. ~~KV redirect keys change shape~~ — superseded by the update above:
keys stay folded; the value carries the source.

Not reproduced on purpose, because it is site-level ordering in Fresh
rather than redirect semantics: Fresh answered a trailing-slash request
with a 307 strip *before* the CSV, so a `from` ending in `/` was dead
there; here it matches `/x/` requests. The reference site handles that
in its own worker entry.

## Validation

Replayed the 310 probes of the QA sample (real CSV, prod's first hop
recorded) through the new SDK: **285/310 identical** (status +
`Location`); 18 are trailing-slash sources (the site-level ordering
above); 5 are URLs with no rule where prod answers the site's own
lower-case 301; 2 are probes where prod itself returned `ENOTFOUND`
(malformed probe URL, and the CSV has the slash-prefixed duplicate the
SDK matched).

## Tests

- New `packages/blocks/src/sdk/redirects.test.ts` (27 cases, built from
the real rows): case/slash-exact matching, percent-encoded pathname,
no-leading-slash and non-ASCII sources never match, query-scoped
precedence, status table (`PERMANENT` → 307, `forcePermanentRedirects`),
columns by value, `;` split, CRLF, self-redirects, `redirectLocation`
(sorted query, discard, `%20` kept, non-ASCII encoded),
`splitExactRedirects` (query rows stay, flag carried).
- `workerEntry.test.ts`: +2 end-to-end cases (query appended/discarded;
query-scoped before bare path and `/Calca/p → /calca/p` is a redirect,
not a loop); 302 → 307 and `?asJson` expectations updated.
- `csv-redirects.test.ts`: +1 (`discardQueryParameters` +
`forcePermanentRedirects`); `splitExactRedirects.test.ts`,
`kvRedirects.test.ts`, `fast-deploy-kv.test.ts`: 302 → 307 /
key-contract expectations updated.

Ran per package: `blocks` 895 passed (the 40 failures in
`layoutCacheRace.test.ts` / `loader.test.ts` fail identically on
`main`), `tanstack` 280 passed (3 draft-preview failures identical on
`main`), `blocks-cli` 849 passed. `tsc --noEmit` clean for `blocks` and
`tanstack` (`blocks-cli` has pre-existing errors in
`scripts/migrate/*.test.ts`, untouched). `biome check` clean on the
files changed (remaining warnings in
`workerEntry.ts`/`index.ts`/`fast-deploy-kv.test.ts` are pre-existing on
`main`).

## Related

Supersedes the approach in the draft PRs #519 (self-loop guard on the
folded key), #520 (query-scoped rules via a separate map) and #521
(case-insensitive `PERMANENT`, quoted-field split): with exact keys the
loop and the collision disappear at the source, `pathname + search`
lookup is what Fresh did, and `PERMANENT` is deliberately 307 because
that is what the Fresh site serves. The quoted-field split is not Fresh
behaviour either (its regex only quote-guards `;`).

Found while validating deco-sites/oficina-tanstack#479.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Aligns redirect handling in `@decocms/blocks/sdk/redirects` and the
TanStack worker with the Fresh loaders and handlers it replaced. The
Fresh semantics are now opt-in per site via `createDecoWorkerEntry({
redirects: { semantics: "fresh" } })`; the default `"legacy"` keeps what
sites already on `@decocms/*` answer today, so enabling `"fresh"` for
one site changes nothing for the others.

**Behavior change**
- `"fresh"`: sources match the request's pathname byte for byte (case,
trailing slash, query included) instead of a lower-cased, slash-folded
key, which turned `/Calca-x/p → /calca-x/p` into a self-redirect that
looped on three live PDPs. Temporary redirects answer 307 instead of
302, query-scoped rules match `pathname + search` before the bare path,
and the request's query is appended to `Location` unless
`discardQueryParameters` is set.
- Both semantics: `from === to` rows are dropped at load, `Location` is
no longer double-encoded (`%20` stays `%20`), and the CSV is parsed like
Fresh's (`type`/`discardQueryParameters` read by value, `;` split
outside quotes).
- KV keys stay folded (`redirect:<id>:<path>` via `normalizePath`, as on
`main`); each value now carries the source as written plus every rule
folding to the same key, so the request-time reader can serve either
semantics. `docs/fast-deploy.md` documents the value shape and the
folded-key contract in both semantics.

<sup>Written for commit 8198bdf.
Summary will update on new commits.</sup>

<a href="https://cubic.dev/pr/decocms/blocks/pull/647?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/decocms/blocks/647?returnTo=https%3A%2F%2Fgithub.com%2Fdecocms%2Fblocks%2Fpull%2F647&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
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