Skip to content

fix(redirects): drop self-redirects at load time instead of serving a loop - #519

Draft
igoramf wants to merge 1 commit into
7.xfrom
fix/redirect-csv-query-self-loop
Draft

igoramf wants to merge 1 commit into
7.xfrom
fix/redirect-csv-query-self-loop

Conversation

@igoramf

@igoramf igoramf commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Primeiro de três PRs saídos do mesmo incidente. Este é o fix do bug; os outros dois estão listados no fim.

O bug

Uma regra cuja origem e destino resolvem para a mesma página responde toda request com um redirect para a URL que o browser acabou de pedir → ERR_TOO_MANY_REDIRECTS.

Exports de migração em massa trazem essas linhas prontas, e o normalizePath fabrica mais: ele reduz um from absoluto a new URL(p).pathname, e pathname não inclui a query. Então uma linha que só queria limpar uma URL legada de categoria:

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

vira exact["/aliancas"] = { to: "/aliancas" } e derruba a página inteira.

Aconteceu duas vezes no mesmo storefront, a partir do mesmo CSV:

Linha Página derrubada
http://blog.montecarlo.com.br/,/,PERMANENT home
https://www.montecarlo.com.br/aliancas?map=category-1,/aliancas,PERMANENT /aliancas

Nas duas vezes o contorno foi apagar a linha do CSV. Isso não escala: são ~3000 linhas de dump, e qualquer sync futuro reintroduz.

Por que o loader Fresh não tinha isso

deco-cx/[email protected]/website/loaders/redirectsFromCsv.ts, que este SDK substituiu:

if (!from || !to || from === to) continue;

O guard existia. O port perdeu. Este PR devolve, comparando depois da normalização — é justamente aí que as linhas acima colapsam.

Comportamento

Regra Antes Depois
/a → /a loop descartada no load
https://site/x?q=1 → /x loop descartada no load
http://blog.site/ → / loop descartada no load
/a/ → /a, /A → /a loop descartada no load
/x → /x?ref=1 loop (o destino recasa) descartada no load
/x → https://other.site/x ok ok — host difere
/old → /new, /blog/* → /news/* ok ok

O host é comparado sempre que os dois lados carregam um, então redirect cross-origin para o mesmo path continua disparando.

Testes

packages/blocks/src/sdk/redirects.test.ts, 9 casos montados sobre as linhas reais do CSV do incidente. 7 falham no main:

git stash -- packages/blocks/src/sdk/redirects.ts
vitest run packages/blocks/src/sdk/redirects.test.ts
→ Tests  7 failed | 2 passed (9)

Com o patch: 9/9. Suíte do pacote: 756 passed (56 arquivos).

Trade-off que este PR assume

O guard descarta a regra em vez de consertá-la. ?map=category-1 → /aliancas é um redirect legítimo, que o Fresh honra hoje casando a href inteira (isHref: true), e aqui ele morre silenciosamente. É a escolha certa para um fix de loop — melhor perder um redirect do que derrubar uma página — mas é perda de comportamento.

Restaurar isso é o assunto do PR seguinte, empilhado neste:

🤖 Generated with Claude Code

@igoramf
igoramf force-pushed the fix/redirect-csv-query-self-loop branch from 06855ee to 6f611cc Compare September 1, 2026 10:55
@igoramf igoramf changed the title fix(redirects): query-scoped CSV rows no longer hijack (and loop on) the bare path fix(redirects): drop self-redirects at load time instead of serving a loop Sep 1, 2026
… 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]>

Copy link
Copy Markdown
Contributor

Cross-reference: #647 addresses the same loop from the other end — the source key is no longer folded (no lower-casing / trailing-slash strip), so /Calca-x/p → /calca-x/p is a redirect rather than a loop, and the Fresh from === to guard is restored on top. Validated against the Fresh production site on a 5 835-row CSV (310 probes replayed). 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]>
@tlgimenes
tlgimenes changed the base branch from main to 7.x October 12, 2026 19:08
@tlgimenes

Copy link
Copy Markdown
Contributor

Retargeted to 7.x: main is now v8 (@decocms/blocks 8.1.0, #671). The v7 line continues on the 7.x branch and releases to npm as @decocms/blocks@latest-7 (7.78.1 is out); v7-only packages (tanstack, nextjs, blocks-admin, blocks-cli, …) keep latest from 7.x.

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.

3 participants