feat(sub): allow switching the inline QR code format on the subscription page (#7157)

The large QR card on the subscription page always encoded the raw link, so a Clash/Mihomo or JSON user who scanned it got a profile their client could not parse.

Add a SUB / JSON / CLASH switch under the card for the enabled formats. The card starts on the format of the route the page was opened through: the server puts subFormat into the page data, so the /mihomo/ and /clash-legacy/ aliases start on CLASH as well.
This commit is contained in:
Justin
2026-11-24 19:36:56 +08:00
committed by GitHub
parent 4b36cc1635
commit 809b7c5501
8 changed files with 207 additions and 13 deletions
+1
View File
@@ -14,6 +14,7 @@ interface SubPageData {
subUrl?: string;
subJsonUrl?: string;
subClashUrl?: string;
subFormat?: 'raw' | 'json' | 'clash';
subTitle?: string;
subSupportUrl?: string;
subUpdates?: number;
+55 -9
View File
@@ -1,33 +1,70 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, QRCode, Tag } from 'antd';
import { Button, QRCode, Segmented, Tag } from 'antd';
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import SubQrButton from './SubQrButton';
type SubLinkKind = 'SUB' | 'JSON' | 'CLASH';
interface SubLinkRow {
kind: SubLinkKind;
color: string;
url: string;
title: string;
downloadable: boolean;
}
type SubPageFormat = NonNullable<SubPageData['subFormat']>;
interface SubLinksTabProps {
subUrl: string;
subJsonUrl: string;
subClashUrl: string;
format: SubPageFormat;
onCopy: (value: string) => void;
}
const appendRawView = (url: string) => `${url}${url.includes('?') ? '&' : '?'}view=raw`;
export default function SubLinksTab({ subUrl, subJsonUrl, subClashUrl, onCopy }: SubLinksTabProps) {
// The server names the format of the route that rendered the page; aliases
// such as /mihomo/ and /clash-legacy/ never match a row URL, so paths cannot.
const QR_KIND_BY_FORMAT: Record<SubPageFormat, SubLinkKind> = {
raw: 'SUB',
json: 'JSON',
clash: 'CLASH',
};
export default function SubLinksTab({
subUrl,
subJsonUrl,
subClashUrl,
format,
onCopy,
}: SubLinksTabProps) {
const { t } = useTranslation();
const subLabel = t('pages.settings.subSettings');
const rows = [
{ kind: 'SUB', color: 'green', url: subUrl, title: subLabel, downloadable: false },
const rows: SubLinkRow[] = [
{ kind: 'SUB' as const, color: 'green', url: subUrl, title: subLabel, downloadable: false },
{
kind: 'JSON',
kind: 'JSON' as const,
color: 'purple',
url: subJsonUrl,
title: `${subLabel} JSON`,
downloadable: true,
},
{ kind: 'CLASH', color: 'gold', url: subClashUrl, title: 'Clash / Mihomo', downloadable: true },
{
kind: 'CLASH' as const,
color: 'gold',
url: subClashUrl,
title: 'Clash / Mihomo',
downloadable: true,
},
].filter((row) => row.url);
const [selectedKind, setSelectedKind] = useState<SubLinkKind>(QR_KIND_BY_FORMAT[format]);
const activeRow = rows.find((row) => row.kind === selectedKind) ?? rows[0];
return (
<div className="sub-rows">
{rows.map((row) => (
@@ -64,11 +101,11 @@ export default function SubLinksTab({ subUrl, subJsonUrl, subClashUrl, onCopy }:
</div>
</div>
))}
{subUrl && (
{activeRow && (
<div className="sub-qr-card">
<div className="sub-qr-code">
<QRCode
value={subUrl}
value={activeRow.url}
size={112}
type="svg"
bordered={false}
@@ -76,9 +113,18 @@ export default function SubLinksTab({ subUrl, subJsonUrl, subClashUrl, onCopy }:
bgColor="#ffffff"
/>
</div>
<div>
<div className="sub-qr-body">
<div className="sub-qr-title">{t('subscription.scanTitle')}</div>
<div className="sub-muted">{t('subscription.scanHint')}</div>
{rows.length > 1 && (
<Segmented<SubLinkKind>
size="small"
className="sub-qr-segmented"
value={activeRow.kind}
onChange={setSelectedKind}
options={rows.map((row) => ({ value: row.kind, label: row.kind }))}
/>
)}
</div>
</div>
)}
+8
View File
@@ -397,6 +397,10 @@ a.sub-row-title:hover {
line-height: 0;
}
.sub-qr-body {
min-width: 0;
}
.sub-qr-title {
margin-bottom: 4px;
font-size: 15px;
@@ -404,6 +408,10 @@ a.sub-row-title:hover {
color: var(--ant-color-text);
}
.sub-qr-segmented {
margin-top: 10px;
}
/* apps */
.sub-apps {
display: flex;
+2
View File
@@ -27,6 +27,7 @@ const sId = subData.sId || '';
const subUrl = subData.subUrl || '';
const subJsonUrl = subData.subJsonUrl || '';
const subClashUrl = subData.subClashUrl || '';
const subFormat = subData.subFormat || 'raw';
const subTitle = subData.subTitle || '';
const subSupportUrl = subData.subSupportUrl || '';
const updateHours = Number(subData.subUpdates || 0);
@@ -99,6 +100,7 @@ export default function SubPage() {
subUrl={subUrl}
subJsonUrl={subJsonUrl}
subClashUrl={subClashUrl}
format={subFormat}
onCopy={copy}
/>
),
+81
View File
@@ -0,0 +1,81 @@
import { fireEvent, render, within } from '@testing-library/react';
import { QRCode } from 'antd';
import { describe, expect, it, vi } from 'vitest';
import SubLinksTab from '@/pages/sub/SubLinksTab';
import { renderWithProviders } from './test-utils';
const SUB_URL = 'https://vpn.example.com/sub/abc';
const JSON_URL = 'https://vpn.example.com/json/abc';
const CLASH_URL = 'https://vpn.example.com/clash/abc';
function expectedQrMarkup(value: string): string {
const { container, unmount } = render(
<QRCode
value={value}
size={112}
type="svg"
bordered={false}
color="#000000"
bgColor="#ffffff"
/>,
);
const html = container.querySelector('svg')?.innerHTML ?? '';
unmount();
return html;
}
describe('SubLinksTab inline QR card', () => {
it('switches the inline QR code between enabled subscription formats', () => {
const view = renderWithProviders(
<SubLinksTab
subUrl={SUB_URL}
subJsonUrl={JSON_URL}
subClashUrl={CLASH_URL}
format="raw"
onCopy={vi.fn()}
/>,
);
const card = view.container.querySelector('.sub-qr-card') as HTMLElement;
expect(card).not.toBeNull();
const qrSvg = () => card.querySelector('.sub-qr-code svg')?.innerHTML;
expect(qrSvg()).toBe(expectedQrMarkup(SUB_URL));
expect(qrSvg()).not.toBe(expectedQrMarkup(CLASH_URL));
fireEvent.click(within(card).getByText('CLASH'));
expect(qrSvg()).toBe(expectedQrMarkup(CLASH_URL));
fireEvent.click(within(card).getByText('JSON'));
expect(qrSvg()).toBe(expectedQrMarkup(JSON_URL));
});
it.each([
['clash', CLASH_URL],
['json', JSON_URL],
] as const)('starts on the %s QR code when that route rendered the page', (format, url) => {
const view = renderWithProviders(
<SubLinksTab
subUrl={SUB_URL}
subJsonUrl={JSON_URL}
subClashUrl={CLASH_URL}
format={format}
onCopy={vi.fn()}
/>,
);
const card = view.container.querySelector('.sub-qr-card') as HTMLElement;
expect(card.querySelector('.sub-qr-code svg')?.innerHTML).toBe(expectedQrMarkup(url));
});
it('offers no switcher when only the raw subscription is enabled', () => {
const view = renderWithProviders(
<SubLinksTab subUrl={SUB_URL} subJsonUrl="" subClashUrl="" format="raw" onCopy={vi.fn()} />,
);
const card = view.container.querySelector('.sub-qr-card') as HTMLElement;
expect(card.querySelector('.sub-qr-code svg')?.innerHTML).toBe(expectedQrMarkup(SUB_URL));
expect(card.querySelector('.ant-segmented')).toBeNull();
});
});
+12 -4
View File
@@ -28,6 +28,11 @@ import (
const (
subMihomoPath = "/mihomo/"
subClashLegacyPath = "/clash-legacy/"
// Which subscription format the route that rendered the page serves.
subPageFormatRaw = "raw"
subPageFormatJSON = "json"
subPageFormatClash = "clash"
)
// writeSubError translates a service-layer result into an HTTP response.
@@ -400,7 +405,7 @@ func (a *SUBController) configuredSubscriptionPathOwner(candidate string) string
// info is for the content a client app imports — the raw subscription body. A
// browser viewing the HTML info page gets clean, name-only remarks (usage is
// shown in the page summary).
func (a *SUBController) maybeServeSubPage(c *gin.Context) bool {
func (a *SUBController) maybeServeSubPage(c *gin.Context, format string) bool {
accept := c.GetHeader("Accept")
wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html")
if !wantsHTML {
@@ -410,6 +415,7 @@ func (a *SUBController) maybeServeSubPage(c *gin.Context) bool {
if !ok {
return true
}
page.Format = format
a.serveSubPage(c, page.BasePath, page)
return true
}
@@ -424,6 +430,7 @@ func (a *SUBController) maybeServeSubInfo(c *gin.Context) bool {
}
info := a.subPageContext(page)
delete(info, "links")
delete(info, "subFormat")
info["emails"] = dedupeEmails(page.Emails)
c.JSON(http.StatusOK, info)
return true
@@ -480,7 +487,7 @@ func (a *SUBController) subs(c *gin.Context) {
logSubscriptionRoute(userAgent, "info")
return
}
if a.maybeServeSubPage(c) {
if a.maybeServeSubPage(c, subPageFormatRaw) {
logSubscriptionRoute(userAgent, "html")
return
}
@@ -705,6 +712,7 @@ func (a *SUBController) subPageContext(page PageData) map[string]any {
"subUrl": page.SubUrl,
"subJsonUrl": page.SubJsonUrl,
"subClashUrl": page.SubClashUrl,
"subFormat": page.Format,
"subTitle": page.SubTitle,
"subSupportUrl": page.SubSupportUrl,
"subUpdates": updateHours,
@@ -825,7 +833,7 @@ func (a *SUBController) subJsons(c *gin.Context) {
a.recordSubscriptionFetch(c)
return
}
if a.maybeServeSubPage(c) {
if a.maybeServeSubPage(c, subPageFormatJSON) {
return
}
if !a.enforceHwid(c) {
@@ -887,7 +895,7 @@ func (a *SUBController) subClash(c *gin.Context, legacy bool) {
a.recordSubscriptionFetch(c)
return
}
if a.maybeServeSubPage(c) {
if a.maybeServeSubPage(c, subPageFormatClash) {
return
}
if !a.enforceHwid(c) {
+47
View File
@@ -128,3 +128,50 @@ func TestSubInfoEndpoint_HTMLPageStillWinsWithoutFormatParam(t *testing.T) {
t.Fatalf("injected page data must carry isOnline; body=%s", w.Body.String())
}
}
func TestSubPageDataNamesTheFormatOfTheVisitedRoute(t *testing.T) {
gin.SetMode(gin.TestMode)
initSubDB(t)
seedInfoEndpointSub(t, "fmt-sub", "fmt@x")
for key, value := range map[string]string{
"subPath": "/sub/", "subJsonPath": "/json/", "subClashPath": "/clash/",
"subJsonEnable": "true", "subClashEnable": "true",
} {
if err := database.GetDB().Where("key = ?", key).Delete(&model.Setting{}).Error; err != nil {
t.Fatalf("clear %s: %v", key, err)
}
if err := database.GetDB().Create(&model.Setting{Key: key, Value: value}).Error; err != nil {
t.Fatalf("set %s: %v", key, err)
}
}
oldDistFS := distFS
distFS = testDistFS
t.Cleanup(func() { distFS = oldDistFS })
router, err := (&Server{}).initRouter()
if err != nil {
t.Fatal(err)
}
for path, want := range map[string]string{
"/sub/fmt-sub": "raw",
"/json/fmt-sub": "json",
"/clash/fmt-sub": "clash",
"/mihomo/fmt-sub": "clash",
"/clash-legacy/fmt-sub": "clash",
} {
t.Run(path, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Host = "sub.example.com"
req.Header.Set("Accept", "text/html")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
}
if marker := `"subFormat":"` + want + `"`; !strings.Contains(w.Body.String(), marker) {
t.Fatalf("page data lacks %s; body=%s", marker, w.Body.String())
}
})
}
}
+1
View File
@@ -3384,6 +3384,7 @@ type PageData struct {
SubUrl string
SubJsonUrl string
SubClashUrl string
Format string
SubTitle string
SubSupportUrl string
SubAnnounce string