From ca4d447d7333ea8f2f2d2f612b89ef4e57741f12 Mon Sep 17 00:00:00 2001
From: Do Siki
Date: Tue, 29 Sep 2026 02:00:48 +0200
Subject: [PATCH] feat(web): open every external link in a new tab, derived
from the URL (MITHOME-124)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
General rule: links to another host open in a new tab with
rel="noopener noreferrer"; internal paths, mailto: and tel: stay in the
same tab. Behaviour was inconsistent before — the home Webmail button
opened in the same tab while the other webmail links did not, and the
CTA and header relied on a manual "external" switch.
src/lib/external-link.ts decides from the URL (externalLinkProps for
JSX, openExternalLinksInNewTab for CMS-provided HTML in About paragraphs,
legal pages and the GDPR label). All link sites use it; the manual
"external" CTA checkbox and NavigationItem flag are removed so the rule
cannot be bypassed. Rule documented in architecture.md and CLAUDE.md;
staging smoke SMOKE-07 checks every external homepage link.
Co-Authored-By: Claude Opus 5.5
---
.agent/steering/architecture.md | 3 +-
CLAUDE.md | 3 +-
proto/e2e/staging-smoke.spec.ts | 12 ++++
proto/scripts/migrate-content-to-payload.ts | 10 +--
proto/src/components/Footer.tsx | 3 +
proto/src/components/Header.test.tsx | 16 ++++-
proto/src/components/Header.tsx | 11 ++-
proto/src/components/views/AboutView.tsx | 3 +-
proto/src/components/views/ContactView.tsx | 6 +-
proto/src/components/views/HomeView.tsx | 8 +--
proto/src/components/views/LegalPageView.tsx | 13 ++--
proto/src/components/views/ServicesView.tsx | 4 +-
proto/src/globals/Home.ts | 2 +-
proto/src/globals/fields/ctaLink.ts | 3 +-
proto/src/lib/external-link.test.ts | 73 ++++++++++++++++++++
proto/src/lib/external-link.ts | 56 +++++++++++++++
proto/src/payload-config.test.ts | 7 +-
proto/src/types/site.ts | 2 -
18 files changed, 200 insertions(+), 35 deletions(-)
create mode 100644 proto/src/lib/external-link.test.ts
create mode 100644 proto/src/lib/external-link.ts
diff --git a/.agent/steering/architecture.md b/.agent/steering/architecture.md
index 52acb01..244ce54 100644
--- a/.agent/steering/architecture.md
+++ b/.agent/steering/architecture.md
@@ -35,7 +35,8 @@ A projekt egy **Next.js 15 alapú marketing weboldal** a mozdIT Bt. számára, A
2. **Stateless API**: A backend API teljesen stateless — session-t a kliens kezel.
3. **Observability**: Minden szerveroldali hiba legyen logolva strukturált Winston-bejegyzésként stdout/stderr-re; az alkalmazás ne küldjön közvetlenül távoli logszolgáltatásnak. API-válaszok egységes formátuma: `{ success, data, error }`.
4. **Security-by-design**: Input validáció minden API route-on, secrets csak env változókból.
-5. **Component-first**: Komponensek Server Component-ek alapértelmezetten — csak indokolt esetben adj `"use client"` direktívát.
+5. **Külső linkek mindig új lapon** (MITHOME-124, általános szabály): minden más hostra mutató http(s) link `target="_blank"` + `rel="noopener noreferrer"` attribútumot kap. Belső útvonal, `mailto:` és `tel:` ugyanazon a lapon marad. A döntés **a címből** születik, sosem kézi kapcsolóból: JSX-ben ``, CMS-ből érkező HTML-nél `openExternalLinksInNewTab(html)` (`proto/src/lib/external-link.ts`). Kézzel írt `target="_blank"` vagy „external” mező ne kerüljön a kódba.
+6. **Component-first**: Komponensek Server Component-ek alapértelmezetten — csak indokolt esetben adj `"use client"` direktívát.
## Adatfolyam (Request Lifecycle)
diff --git a/CLAUDE.md b/CLAUDE.md
index 6476529..2fa9a80 100755
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -24,7 +24,8 @@
4. **Commit**: Conventional Commits (`feat:`, `fix:`, `docs:`, `chore:`)
5. **Fájlméret**: soft limit 300 sor, hard limit 400 sor
6. **Language**: kód+commit = English, kommunikáció+docs = Magyar
-7. **OpenSpec**: nagyobb feature/API/adatmodell/architektúra változáshoz `/opsx-propose`, majd jóváhagyott specifikációra `/opsx-apply`; a Plane MITHOME és `TODO.md` marad a feladat- és státuszkezelés
+7. **Külső link = új lap**: minden külső link új lapon nyílik; mindig a `proto/src/lib/external-link.ts` helperrel (`externalLinkProps`, `openExternalLinksInNewTab`), nincs kézi kapcsoló (MITHOME-124)
+8. **OpenSpec**: nagyobb feature/API/adatmodell/architektúra változáshoz `/opsx-propose`, majd jóváhagyott specifikációra `/opsx-apply`; a Plane MITHOME és `TODO.md` marad a feladat- és státuszkezelés
---
diff --git a/proto/e2e/staging-smoke.spec.ts b/proto/e2e/staging-smoke.spec.ts
index f45e1d9..a480b82 100644
--- a/proto/e2e/staging-smoke.spec.ts
+++ b/proto/e2e/staging-smoke.spec.ts
@@ -63,6 +63,18 @@ for (const [locale, contactPath] of [['hu', '/hu/kapcsolat'], ['en', '/en/contac
})
}
+// MITHOME-124: external links always open in a new tab (the home Webmail
+// button used to open in the same tab while other webmail links did not).
+test('SMOKE-07: external links on the homepage open in a new tab', async ({ page }) => {
+ await page.goto('/hu')
+ const external = page.locator('a[href^="http"]:not([href^="' + new URL(page.url()).origin + '"])')
+ expect(await external.count()).toBeGreaterThan(0)
+ for (const link of await external.all()) {
+ await expect(link).toHaveAttribute('target', '_blank')
+ await expect(link).toHaveAttribute('rel', /noopener/)
+ }
+})
+
test('SMOKE-05: empty contact form is blocked client-side without API submission', async ({ page }) => {
let contactPostCount = 0
page.on('request', request => {
diff --git a/proto/scripts/migrate-content-to-payload.ts b/proto/scripts/migrate-content-to-payload.ts
index 9286781..9cad8bd 100644
--- a/proto/scripts/migrate-content-to-payload.ts
+++ b/proto/scripts/migrate-content-to-payload.ts
@@ -52,14 +52,16 @@ function toStringArray(items: readonly string[]): { value: string }[] {
return items.map((value) => ({ value }))
}
-type CtaJson = { text: string; href: string; external?: boolean }
+// `external` in the legacy JSON is ignored: new-tab behaviour is derived
+// from the URL itself (MITHOME-124).
+type CtaJson = { text: string; href: string }
/** MITHOME-123: internal JSON paths become page links, the rest stay URLs. */
-function toCtaLink({ text, href, external }: CtaJson) {
+function toCtaLink({ text, href }: CtaJson) {
const page = internalPathToPageKey(href)
return page
- ? { text, linkType: 'page' as const, page, external }
- : { text, linkType: 'url' as const, href, external }
+ ? { text, linkType: 'page' as const, page }
+ : { text, linkType: 'url' as const, href }
}
function buildHomeData(json: typeof homeJson) {
diff --git a/proto/src/components/Footer.tsx b/proto/src/components/Footer.tsx
index 6b63b82..f484aad 100755
--- a/proto/src/components/Footer.tsx
+++ b/proto/src/components/Footer.tsx
@@ -4,6 +4,7 @@ import { siteConfig } from '@/config/site'
import Link from 'next/link'
import type { NavigationItem } from '@/types/site'
import type { Locale } from '@/lib/i18n'
+import { externalLinkProps } from '@/lib/external-link'
type FooterServiceItem = { id: string; title: string; icon: string }
@@ -97,6 +98,7 @@ export default function Footer({ nav, legalLinks, homeHref, description, contact
{
@@ -165,6 +167,7 @@ export default function Footer({ nav, legalLinks, homeHref, description, contact
{
diff --git a/proto/src/components/Header.test.tsx b/proto/src/components/Header.test.tsx
index 7603fbf..bdbf2d0 100755
--- a/proto/src/components/Header.test.tsx
+++ b/proto/src/components/Header.test.tsx
@@ -168,4 +168,18 @@ describe('Header', () => {
const mobileMenu = container.querySelector('.md\\:hidden.overflow-hidden')
expect(mobileMenu).toBeInTheDocument()
})
-})
\ No newline at end of file
+
+ // MITHOME-124: every external link opens in a new tab, derived from the URL.
+ it('should open external nav links in a new tab and keep internal ones in place', () => {
+ const nav = [...getMainNavigation('hu'), { label: 'Webmail', href: 'https://mail.mozdit.hu' }]
+ render()
+
+ for (const link of screen.getAllByRole('link', { name: /Webmail/ })) {
+ expect(link).toHaveAttribute('target', '_blank')
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer')
+ }
+ for (const link of screen.getAllByRole('link', { name: 'Rólunk' })) {
+ expect(link).not.toHaveAttribute('target')
+ }
+ })
+})
diff --git a/proto/src/components/Header.tsx b/proto/src/components/Header.tsx
index e0aa15a..454d77e 100755
--- a/proto/src/components/Header.tsx
+++ b/proto/src/components/Header.tsx
@@ -6,6 +6,7 @@ import { ThemeToggle } from './ThemeProvider'
import Link from 'next/link'
import Image from 'next/image'
import type { NavigationItem } from '@/types/site'
+import { externalLinkProps, isExternalHref } from '@/lib/external-link'
type HeaderProps = {
nav: NavigationItem[]
@@ -74,8 +75,7 @@ export default function Header({ nav, homeHref, a11y }: HeaderProps) {
{item.label}
- {item.external && (
+ {isExternalHref(item.href) && (
@@ -161,8 +161,7 @@ export default function Header({ nav, homeHref, a11y }: HeaderProps) {
setIsMenuOpen(false)}
className={`block px-4 py-3 rounded-lg text-base font-medium transition-all duration-200 ${
item.primary ? 'btn btn-primary text-white mt-2' : ''
@@ -189,7 +188,7 @@ export default function Header({ nav, homeHref, a11y }: HeaderProps) {
>
{item.label}
- {item.external && (
+ {isExternalHref(item.href) && (
diff --git a/proto/src/components/views/AboutView.tsx b/proto/src/components/views/AboutView.tsx
index a2fef78..d261ff6 100755
--- a/proto/src/components/views/AboutView.tsx
+++ b/proto/src/components/views/AboutView.tsx
@@ -1,5 +1,6 @@
import { localePath, type Locale } from '@/lib/i18n'
import type { getAboutContent } from '@/lib/payload-content'
+import { openExternalLinksInNewTab } from '@/lib/external-link'
type AboutViewProps = {
content: Awaited>
@@ -55,7 +56,7 @@ export default function AboutView({ content: pageContent, locale }: AboutViewPro
{pageContent.story.paragraphs.map((paragraph, index) => (
))}
diff --git a/proto/src/components/views/ContactView.tsx b/proto/src/components/views/ContactView.tsx
index 17ddd1a..efcc30e 100755
--- a/proto/src/components/views/ContactView.tsx
+++ b/proto/src/components/views/ContactView.tsx
@@ -4,6 +4,7 @@ import { useState } from 'react'
import { siteConfig } from '@/config/site'
import { localePath, type Locale } from '@/lib/i18n'
import type { getContactContent } from '@/lib/payload-content'
+import { externalLinkProps, openExternalLinksInNewTab } from '@/lib/external-link'
type ContactViewProps = {
content: Awaited>
@@ -237,7 +238,7 @@ export default function ContactView({ content: pageContent, contactEmail, footer
/>
{errors.gdprConsent && {errors.gdprConsent}
}
@@ -303,8 +304,7 @@ export default function ContactView({ content: pageContent, contactEmail, footer
// Szolgáltatások oldalon) — javítva a tényleges webmail
// URL-re.
href={webmailHref}
- target="_blank"
- rel="noopener noreferrer"
+ {...externalLinkProps(webmailHref)}
className="text-blue-600 hover:text-blue-700"
>
{pageContent.info.webmail.linkText}
diff --git a/proto/src/components/views/HomeView.tsx b/proto/src/components/views/HomeView.tsx
index 7b2e228..94ef479 100755
--- a/proto/src/components/views/HomeView.tsx
+++ b/proto/src/components/views/HomeView.tsx
@@ -1,6 +1,7 @@
import Image from 'next/image'
import { localePath, type Locale } from '@/lib/i18n'
import type { getHomeContent, PartnerView } from '@/lib/payload-content'
+import { externalLinkProps } from '@/lib/external-link'
type HomeViewProps = {
content: Awaited>
@@ -69,8 +70,7 @@ export default function HomeView({ content: pageContent, partners, locale }: Hom
>
')
- .replace(/• \*\*(.*?)\*\*/g, '
• $1')
- .replace(/^/, '
')
- .replace(/$/, '
')
+ __html: openExternalLinksInNewTab(
+ section.content
+ .replace(/\n\n/g, '')
+ .replace(/• \*\*(.*?)\*\*/g, '
• $1')
+ .replace(/^/, '
')
+ .replace(/$/, '
'),
+ )
}}
/>
diff --git a/proto/src/components/views/ServicesView.tsx b/proto/src/components/views/ServicesView.tsx
index 9fe35fa..1320326 100755
--- a/proto/src/components/views/ServicesView.tsx
+++ b/proto/src/components/views/ServicesView.tsx
@@ -1,5 +1,6 @@
import { localePath, type Locale } from '@/lib/i18n'
import type { getHomeContent, getServicesContent } from '@/lib/payload-content'
+import { externalLinkProps } from '@/lib/external-link'
type ServicesViewProps = {
content: Awaited>
@@ -143,8 +144,7 @@ export default function ServicesView({ content: pageContent, homeServices, featu
// target="_blank"-kal a "Webmail belépés" gombhoz — javítva a
// tényleges webmail URL-re.
href={webmailHref}
- target="_blank"
- rel="noopener noreferrer"
+ {...externalLinkProps(webmailHref)}
className="inline-block border-2 border-white text-white hover:bg-white hover:text-gray-900 font-medium px-8 py-3 rounded-md transition-colors"
>
{pageContent.cta.secondaryButton}
diff --git a/proto/src/globals/Home.ts b/proto/src/globals/Home.ts
index b5686df..e131475 100644
--- a/proto/src/globals/Home.ts
+++ b/proto/src/globals/Home.ts
@@ -13,7 +13,7 @@ import { globalVersions } from '../lib/payload-versions'
* kihagyjuk, nehogy két, egymásnak ellentmondó forrás legyen.
*
* MITHOME-111 lokalizáció: minden fordítható szöveg `localized: true`; az
- * `icon`, a sor-`id` és az `external` közös. WHY a `cta.*.href` is
+ * `icon` és a sor-`id` közös. WHY a `cta.*.href` is
* lokalizált: egy külső cél nyelvenként eltérhet. Belső oldalra a CTA
* oldalválasztóval mutat (MITHOME-123, fields/ctaLink.ts) — a nyelvhelyes
* útvonalat a frontend számolja (/hu/kapcsolat vs /en/contact). A
diff --git a/proto/src/globals/fields/ctaLink.ts b/proto/src/globals/fields/ctaLink.ts
index b131110..3a8edda 100644
--- a/proto/src/globals/fields/ctaLink.ts
+++ b/proto/src/globals/fields/ctaLink.ts
@@ -21,6 +21,8 @@ const isPageLink = (sibling: Sibling) => (sibling?.linkType ?? 'page') === 'page
*
* WHY custom `validate` instead of `required`: `page` and `href` are only
* required for their own link type; the other one is hidden and empty.
+ * WHY no "open in new tab" switch: external links always open in a new
+ * tab, decided from the URL (MITHOME-124, src/lib/external-link.ts).
* DECISION: `href` stays localized (MITHOME-111) — an external target may
* differ per language; `linkType`/`page` are shared across locales.
*/
@@ -57,7 +59,6 @@ export function ctaLinkGroup(name: string): GroupField {
validate: (value: unknown, { siblingData }: { siblingData: Sibling }) =>
isPageLink(siblingData) || Boolean(value) || 'Add meg az URL-t.',
},
- { name: 'external', type: 'checkbox', defaultValue: false },
],
}
}
diff --git a/proto/src/lib/external-link.test.ts b/proto/src/lib/external-link.test.ts
new file mode 100644
index 0000000..90d3f19
--- /dev/null
+++ b/proto/src/lib/external-link.test.ts
@@ -0,0 +1,73 @@
+import { externalLinkProps, isExternalHref, openExternalLinksInNewTab } from './external-link'
+
+const SITE = 'https://stage.mozdit.hu'
+
+describe('isExternalHref (MITHOME-124)', () => {
+ it.each([
+ 'https://mail.mozdit.hu',
+ 'http://example.com/path',
+ '//cdn.example.com/x.png',
+ 'HTTPS://PARTNER.EXAMPLE',
+ ])('should treat %s as external', (href) => {
+ expect(isExternalHref(href, SITE)).toBe(true)
+ })
+
+ it.each([
+ '/hu/kapcsolat',
+ '#top',
+ '?q=1',
+ 'relative/path',
+ 'mailto:info@mozdit.hu',
+ 'tel:+3612345678',
+ 'https://stage.mozdit.hu/hu/rolunk',
+ '',
+ ])('should treat %s as internal (same tab)', (href) => {
+ expect(isExternalHref(href, SITE)).toBe(false)
+ })
+
+ it('should not throw on malformed absolute URLs', () => {
+ expect(isExternalHref('https://', SITE)).toBe(false)
+ })
+
+ it('should fall back to treating every absolute http(s) URL as external without a valid site URL', () => {
+ expect(isExternalHref('https://stage.mozdit.hu', 'not a url')).toBe(true)
+ })
+})
+
+describe('externalLinkProps', () => {
+ it('should open external links in a new tab without leaking the opener', () => {
+ expect(externalLinkProps('https://mail.mozdit.hu', SITE)).toEqual({
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ })
+ })
+
+ it('should return no props for internal links', () => {
+ expect(externalLinkProps('/en/contact', SITE)).toEqual({})
+ })
+})
+
+describe('openExternalLinksInNewTab', () => {
+ it('should add target and rel to external anchors in CMS HTML', () => {
+ expect(openExternalLinksInNewTab('Lásd NAIH.', SITE)).toBe(
+ 'Lásd NAIH.',
+ )
+ })
+
+ it('should replace an existing target/rel on external anchors', () => {
+ expect(
+ openExternalLinksInNewTab(`N`, SITE),
+ ).toBe(`N`)
+ })
+
+ it('should leave internal anchors, mailto links and other tags untouched', () => {
+ const html =
+ 'Az adatkezelési tájékoztatót, írjon, GDPR.
'
+ expect(openExternalLinksInNewTab(html, SITE)).toBe(html)
+ })
+
+ it('should handle several anchors in one string', () => {
+ const out = openExternalLinksInNewTab('A B C', SITE)
+ expect(out.match(/target="_blank"/g)).toHaveLength(2)
+ })
+})
diff --git a/proto/src/lib/external-link.ts b/proto/src/lib/external-link.ts
new file mode 100644
index 0000000..c763674
--- /dev/null
+++ b/proto/src/lib/external-link.ts
@@ -0,0 +1,56 @@
+/**
+ * MITHOME-124 — general rule: every external link opens in a new tab.
+ *
+ * "External" = an absolute http(s) or protocol-relative URL whose host is
+ * not the site's own host. Internal paths, anchors, `mailto:` and `tel:`
+ * stay in the same tab.
+ *
+ * DECISION: decided from the URL itself, never from a manual flag — a
+ * per-link "external" switch would allow exceptions to the rule (the old
+ * CTA checkbox and the webmail button drifted apart exactly that way).
+ */
+import { siteConfig } from '@/config/site'
+
+const NEW_TAB_PROPS = { target: '_blank', rel: 'noopener noreferrer' } as const
+
+type NewTabProps = typeof NEW_TAB_PROPS | Record
+
+function hostOf(url: string): string | undefined {
+ try {
+ return new URL(url).host.toLowerCase()
+ } catch {
+ return undefined
+ }
+}
+
+export function isExternalHref(href: string, siteUrl: string = siteConfig.general.url): boolean {
+ const normalized = href.trim()
+ if (!/^(https?:)?\/\//i.test(normalized)) return false
+ const host = hostOf(normalized.startsWith('//') ? `https:${normalized}` : normalized)
+ if (!host) return false
+ return host !== hostOf(siteUrl)
+}
+
+/** Spread onto an ``: ``. */
+export function externalLinkProps(href: string, siteUrl?: string): NewTabProps {
+ return isExternalHref(href, siteUrl) ? NEW_TAB_PROPS : {}
+}
+
+const ANCHOR_OPEN_TAG = /]*)>/gi
+const HREF_ATTR = /\bhref\s*=\s*(["'])(.*?)\1/i
+const TARGET_OR_REL_ATTR = /\s+(?:target|rel)\s*=\s*(["']).*?\1/gi
+
+/**
+ * Applies the rule to CMS-provided HTML (rendered with
+ * dangerouslySetInnerHTML), where JSX props cannot be spread.
+ * TRADEOFF: regex over a full HTML parser — the input is short, admin-
+ * authored markup; an unparseable anchor is left as is (same tab).
+ */
+export function openExternalLinksInNewTab(html: string, siteUrl?: string): string {
+ return html.replace(ANCHOR_OPEN_TAG, (tag: string, attrs: string) => {
+ const href = HREF_ATTR.exec(attrs)?.[2]
+ if (href === undefined || !isExternalHref(href, siteUrl)) return tag
+ const cleaned = attrs.replace(TARGET_OR_REL_ATTR, '')
+ return ``
+ })
+}
diff --git a/proto/src/payload-config.test.ts b/proto/src/payload-config.test.ts
index 21dd810..e43bde2 100644
--- a/proto/src/payload-config.test.ts
+++ b/proto/src/payload-config.test.ts
@@ -172,7 +172,7 @@ describe('Payload globals', () => {
function expected(finding: Finding): boolean {
if (finding.path.endsWith('(container)')) return false
if (finding.path.endsWith('[]')) return true
- // Checkbox/radio/select (external, linkType, page) are structural.
+ // Checkbox/radio/select (linkType, page) are structural.
if (finding.type !== 'text' && finding.type !== 'textarea') return false
return !SHARED_TEXT_FIELDS.has(finding.path.split('.').pop()!)
}
@@ -186,13 +186,14 @@ describe('Payload globals', () => {
},
)
- it('should localize the CTA URL but share the link type, page and external flag', () => {
+ it('should localize the CTA URL but share the link type and page', () => {
const findings = walk(Home.fields as Node[], '', [])
const byPath = Object.fromEntries(findings.map((f) => [f.path, f.localized]))
expect(byPath['hero.cta.primary.href']).toBe(true)
expect(byPath['hero.cta.primary.linkType']).toBe(false)
expect(byPath['hero.cta.primary.page']).toBe(false)
- expect(byPath['hero.cta.primary.external']).toBe(false)
+ // MITHOME-124: no manual new-tab switch — derived from the URL.
+ expect(byPath).not.toHaveProperty('hero.cta.primary.external')
})
})
diff --git a/proto/src/types/site.ts b/proto/src/types/site.ts
index b9d77dc..caeeff8 100755
--- a/proto/src/types/site.ts
+++ b/proto/src/types/site.ts
@@ -19,7 +19,6 @@ export interface GeneralConfig {
export interface NavigationItem {
label: string
href: string
- external?: boolean
primary?: boolean
}
@@ -36,7 +35,6 @@ export interface HeroSectionConfig {
primary: {
text: string
href: string
- external?: boolean
}
secondary?: {
text: string