Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 58 additions & 18 deletions web/src/components/layout/Footer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,59 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/

import React, { useEffect, useState, useMemo, useContext } from 'react';
import React, {
useCallback,
useContext,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { Typography } from '@douyinfe/semi-ui';
import { getFooterHTML, getLogo, getSystemName } from '../../helpers';
import {
getFooterRenderMode,
normalizeFooterValue,
} from '../../helpers/footer';
import { StatusContext } from '../../context/Status';

const FooterBar = () => {
const { t } = useTranslation();
const [footer, setFooter] = useState(getFooterHTML());
const iframeRef = useRef(null);
const [iframeHeight, setIframeHeight] = useState(240);
const [statusState] = useContext(StatusContext);
const systemName = getSystemName();
const logo = getLogo();
const [statusState] = useContext(StatusContext);
const isDemoSiteMode = statusState?.status?.demo_site_enabled || false;
const footerValue = useMemo(
() =>
normalizeFooterValue(statusState?.status?.footer_html ?? getFooterHTML()),
[statusState?.status?.footer_html],
);
const footerRenderMode = useMemo(
() => getFooterRenderMode(footerValue),
[footerValue],
);

const handleFooterFrameLoad = useCallback(() => {
try {
const iframeDocument = iframeRef.current?.contentDocument;
if (!iframeDocument) {
return;
}

const loadFooter = () => {
let footer_html = localStorage.getItem('footer_html');
if (footer_html) {
setFooter(footer_html);
const nextHeight = Math.max(
iframeDocument.documentElement?.scrollHeight || 0,
iframeDocument.body?.scrollHeight || 0,
);

if (nextHeight > 0) {
setIframeHeight(nextHeight);
}
} catch {
// Cross-origin iframe documents cannot be measured, so keep the fallback height.
}
};
}, []);
Comment on lines +62 to +80

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.

⚠️ Potential issue | 🟡 Minor

Reset iframe height when source/mode changes to keep fallback behavior correct.

If a previous same-origin footer set a large measured height, then a new cross-origin iframe can fail measurement and keep the old large height instead of the intended fallback.

🧩 Minimal fix
 import React, {
   useCallback,
   useContext,
+  useEffect,
   useMemo,
   useRef,
   useState,
 } from 'react';
@@
   const handleFooterFrameLoad = useCallback(() => {
@@
   }, []);
+
+  useEffect(() => {
+    if (footerRenderMode === 'iframe') {
+      setIframeHeight(240);
+    }
+  }, [footerRenderMode, footerValue]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleFooterFrameLoad = useCallback(() => {
try {
const iframeDocument = iframeRef.current?.contentDocument;
if (!iframeDocument) {
return;
}
const loadFooter = () => {
let footer_html = localStorage.getItem('footer_html');
if (footer_html) {
setFooter(footer_html);
const nextHeight = Math.max(
iframeDocument.documentElement?.scrollHeight || 0,
iframeDocument.body?.scrollHeight || 0,
);
if (nextHeight > 0) {
setIframeHeight(nextHeight);
}
} catch {
// Cross-origin iframe documents cannot be measured, so keep the fallback height.
}
};
}, []);
const handleFooterFrameLoad = useCallback(() => {
try {
const iframeDocument = iframeRef.current?.contentDocument;
if (!iframeDocument) {
return;
}
const nextHeight = Math.max(
iframeDocument.documentElement?.scrollHeight || 0,
iframeDocument.body?.scrollHeight || 0,
);
if (nextHeight > 0) {
setIframeHeight(nextHeight);
}
} catch {
// Cross-origin iframe documents cannot be measured, so keep the fallback height.
}
}, []);
useEffect(() => {
if (footerRenderMode === 'iframe') {
setIframeHeight(240);
}
}, [footerRenderMode, footerValue]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/layout/Footer.jsx` around lines 62 - 80, The measured
iframe height can persist across src/mode changes and prevent the fallback from
applying for cross-origin content; update the component to reset the iframe
height whenever the iframe source or display mode changes by adding a useEffect
that watches the footer source/mode props and calls setIframeHeight to the
fallback (or null/0 whatever this component treats as "use fallback"), and also
consider setting the fallback inside handleFooterFrameLoad's catch path using
iframeRef and setIframeHeight so cross-origin failures revert to the fallback;
reference handleFooterFrameLoad, iframeRef, and setIframeHeight when making this
change.


const currentYear = new Date().getFullYear();

Expand Down Expand Up @@ -214,18 +247,25 @@ const FooterBar = () => {
[logo, systemName, t, currentYear, isDemoSiteMode],
);

useEffect(() => {
loadFooter();
}, []);

return (
<div className='w-full'>
{footer ? (
<div className='relative'>
<div
className='custom-footer'
dangerouslySetInnerHTML={{ __html: footer }}
></div>
{footerRenderMode !== 'default' ? (
<div className='relative pb-8'>
{footerRenderMode === 'iframe' ? (
<iframe
ref={iframeRef}
title={t('页脚')}
src={footerValue}
className='custom-footer-frame'
style={{ height: `${iframeHeight}px` }}
onLoad={handleFooterFrameLoad}
/>
) : (
<div
className='custom-footer'
dangerouslySetInnerHTML={{ __html: footerValue }}
></div>
Comment on lines +272 to +275

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether footer content is currently sanitized before reaching dangerouslySetInnerHTML.
rg -n "dangerouslySetInnerHTML|normalizeFooterValue|sanitize|DOMPurify" web/src/components/layout/Footer.jsx web/src/helpers/footer.js

Repository: QuantumNous/new-api

Length of output: 514


🏁 Script executed:

cat -n web/src/helpers/footer.js

Repository: QuantumNous/new-api

Length of output: 1711


🏁 Script executed:

sed -n '45,60p' web/src/components/layout/Footer.jsx

Repository: QuantumNous/new-api

Length of output: 529


🏁 Script executed:

rg -l "dompurify|DOMPurify" web/

Repository: QuantumNous/new-api

Length of output: 75


🏁 Script executed:

fd package.json web/ | xargs grep -l "dompurify" 2>/dev/null || echo "Not found in direct grep"

Repository: QuantumNous/new-api

Length of output: 87


🏁 Script executed:

cat web/package.json | grep -A 5 -B 5 "dompurify" || echo "dompurify not in package.json"

Repository: QuantumNous/new-api

Length of output: 92


🏁 Script executed:

cat web/package.json | head -50

Repository: QuantumNous/new-api

Length of output: 1555


🏁 Script executed:

grep -A 10 "dompurify" web/bun.lock | head -20

Repository: QuantumNous/new-api

Length of output: 3988


🏁 Script executed:

rg -n "footer_html|getFooterHTML" web/src/ -A 2 -B 2

Repository: QuantumNous/new-api

Length of output: 2576


Sanitize footer HTML before rendering to avoid XSS.

footerValue is rendered with dangerouslySetInnerHTML without sanitization. The normalizeFooterValue() function only performs .trim()—it does not sanitize HTML. Since footer_html originates from server configuration (status.footer_html) and is persisted in localStorage, unsanitized rendering creates a stored XSS risk if this configuration is attacker-controlled or misconfigured by administrators.

Use DOMPurify (already available as a transitive dependency of mermaid) to sanitize the HTML before rendering:

Proposed fix
 import React, {
   useCallback,
   useContext,
   useMemo,
   useRef,
   useState,
 } from 'react';
+import DOMPurify from 'dompurify';
@@
   const footerRenderMode = useMemo(
     () => getFooterRenderMode(footerValue),
     [footerValue],
   );
+  const sanitizedFooterHtml = useMemo(
+    () => DOMPurify.sanitize(footerValue),
+    [footerValue],
+  );
@@
           ) : (
             <div
               className='custom-footer'
-              dangerouslySetInnerHTML={{ __html: footerValue }}
+              dangerouslySetInnerHTML={{ __html: sanitizedFooterHtml }}
             ></div>
           )}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<div
className='custom-footer'
dangerouslySetInnerHTML={{ __html: footerValue }}
></div>
<div
className='custom-footer'
dangerouslySetInnerHTML={{ __html: sanitizedFooterHtml }}
></div>
🧰 Tools
🪛 Biome (2.4.6)

[error] 274-274: Avoid passing content using the dangerouslySetInnerHTML prop.

(lint/security/noDangerouslySetInnerHtml)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/layout/Footer.jsx` around lines 272 - 275, The footer is
rendered via dangerouslySetInnerHTML using footerValue (produced by
normalizeFooterValue) which only trims and does not sanitize; update the
component to sanitize footerValue before assignment (or inside
normalizeFooterValue) using DOMPurify (import DOMPurify from 'dompurify') and
pass DOMPurify.sanitize(footerValue) to the dangerouslySetInnerHTML prop so
stored XSS cannot occur; ensure you only sanitize where
footer_html/status.footer_html is used and keep the symbol names:
normalizeFooterValue, footerValue, and the div with dangerouslySetInnerHTML.

)}
<div className='absolute bottom-2 right-4 text-xs !text-semi-color-text-2 opacity-70'>
<span>{t('设计与开发由')} </span>
<a
Expand Down
19 changes: 18 additions & 1 deletion web/src/components/settings/OtherSetting.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
Card,
} from '@douyinfe/semi-ui';
import { API, showError, showSuccess, timestamp2string } from '../../helpers';
import { getStatusOptionPatch } from '../../helpers/statusOption';
import { marked } from 'marked';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../context/Status';
Expand Down Expand Up @@ -66,6 +67,22 @@ const OtherSetting = () => {
const { success, message } = res.data;
if (success) {
setInputs((inputs) => ({ ...inputs, [key]: value }));
const statusOptionPatch = getStatusOptionPatch(key, value);
if (statusOptionPatch) {
const nextStatus = {
...(statusState?.status || {}),
[statusOptionPatch.statusKey]: statusOptionPatch.value,
};
statusDispatch({ type: 'set', payload: nextStatus });
if (statusOptionPatch.value) {
localStorage.setItem(
statusOptionPatch.storageKey,
statusOptionPatch.value,
);
} else {
localStorage.removeItem(statusOptionPatch.storageKey);
}
}
} else {
showError(message);
}
Expand Down Expand Up @@ -486,7 +503,7 @@ const OtherSetting = () => {
<Form.Input
label={t('页脚')}
placeholder={t(
'在此输入新的页脚,留空则使用默认页脚,支持 HTML 代码',
'在此输入新的页脚,留空则使用默认页脚,支持 HTML 代码或 http/https 页面链接',
)}
field={'Footer'}
onChange={handleInputChange}
Expand Down
46 changes: 46 additions & 0 deletions web/src/helpers/footer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

/**
* 规范化页脚配置值,统一将非字符串输入视为空值。
* @param {unknown} footer - 原始页脚配置值
* @returns {string} 去除首尾空白后的页脚内容,或空字符串
*/
export function normalizeFooterValue(footer) {
return typeof footer === 'string' ? footer.trim() : '';
}

/**
* 根据页脚内容判断前端应使用的渲染模式。
* @param {unknown} footer - 原始页脚配置值
* @returns {'default' | 'iframe' | 'html'} 页脚渲染模式
*/
export function getFooterRenderMode(footer) {
const normalizedFooter = normalizeFooterValue(footer);

if (!normalizedFooter) {
return 'default';
}

if (/^https?:\/\//i.test(normalizedFooter)) {
return 'iframe';
}

return 'html';
}
22 changes: 22 additions & 0 deletions web/src/helpers/footer.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';

import { getFooterRenderMode } from './footer.js';

test('treats http and https footer values as iframe embeds', () => {
assert.equal(
getFooterRenderMode('https://veriai.chat/landing/footer.html'),
'iframe',
);
assert.equal(getFooterRenderMode('http://example.com/footer.html'), 'iframe');
});

test('treats HTML fragments as inline footer content', () => {
assert.equal(getFooterRenderMode('<div>Footer</div>'), 'html');
});

test('falls back to the built-in footer for blank values', () => {
assert.equal(getFooterRenderMode(''), 'default');
assert.equal(getFooterRenderMode(' '), 'default');
assert.equal(getFooterRenderMode(null), 'default');
});
37 changes: 37 additions & 0 deletions web/src/helpers/paymentWebhook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

/**
* 构建支付渠道的 webhook 回调地址。
* @param {string | null | undefined} serverAddress - 后台配置的站点地址
* @param {string} provider - 支付渠道标识
* @param {string} [fallbackBaseLabel=''] - 站点地址缺失时使用的展示占位
* @returns {string} 标准化后的 webhook 地址
*/
export function getPaymentWebhookUrl(
serverAddress,
provider,
fallbackBaseLabel = '',
) {
const normalizedServerAddress = String(serverAddress || '')
.trim()
.replace(/\/+$/, '');
const baseUrl = normalizedServerAddress || fallbackBaseLabel;
return `${baseUrl}/api/${provider}/webhook`;
}
22 changes: 22 additions & 0 deletions web/src/helpers/paymentWebhook.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';

import { getPaymentWebhookUrl } from './paymentWebhook.js';

test('builds creem webhook url from server address', () => {
assert.equal(
getPaymentWebhookUrl('https://veriai.chat/', 'creem'),
'https://veriai.chat/api/creem/webhook',
);
});

test('uses caller-provided fallback when server address is missing', () => {
assert.equal(
getPaymentWebhookUrl('', 'creem', 'Website Address'),
'Website Address/api/creem/webhook',
);
});

test('returns a relative webhook path when no fallback is provided', () => {
assert.equal(getPaymentWebhookUrl('', 'creem'), '/api/creem/webhook');
});
44 changes: 44 additions & 0 deletions web/src/helpers/statusOption.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

const STATUS_OPTION_FIELD_MAP = {
SystemName: 'system_name',
Logo: 'logo',
Footer: 'footer_html',
};

/**
* 将设置项更新转换为需要同步到状态上下文的补丁对象。
* @param {string} key - 设置项键名
* @param {unknown} value - 设置项值
* @returns {{statusKey: string, storageKey: string, value: string} | null} 可同步的状态补丁
*/
export function getStatusOptionPatch(key, value) {
const statusKey = STATUS_OPTION_FIELD_MAP[key];

if (!statusKey) {
return null;
}

return {
statusKey,
storageKey: statusKey,
value: typeof value === 'string' ? value : '',
};
}
19 changes: 19 additions & 0 deletions web/src/helpers/statusOption.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';

import { getStatusOptionPatch } from './statusOption.js';

test('maps footer option updates to footer_html status data', () => {
assert.deepEqual(
getStatusOptionPatch('Footer', 'https://veriai.chat/landing/footer.html'),
{
statusKey: 'footer_html',
storageKey: 'footer_html',
value: 'https://veriai.chat/landing/footer.html',
},
);
});

test('returns null for options that are not mirrored into status', () => {
assert.equal(getStatusOptionPatch('About', '<div>About</div>'), null);
});
1 change: 1 addition & 0 deletions web/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2415,6 +2415,7 @@
"缩词": "Shorten",
"缺省 MaxTokens": "Default MaxTokens",
"网站地址": "Website Address",
"Webhook 填:": "Webhook:",
"网站域名标识": "Website Domain ID",
"网络连接失败,请检查网络设置或稍后重试": "Network connection failed, please check network settings or try again later",
"网络配置": "Network Configuration",
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,7 @@
"缩词": "Raccourcir",
"缺省 MaxTokens": "MaxTokens par défaut",
"网站地址": "Adresse du site web",
"Webhook 填:": "Webhook :",
"网站域名标识": "ID de domaine du site Web",
"网络连接失败,请检查网络设置或稍后重试": "Network connection failed, please check network settings or try again later",
"网络配置": "Network Configuration",
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -2354,6 +2354,7 @@
"缩词": "短縮",
"缺省 MaxTokens": "デフォルト MaxTokens",
"网站地址": "ウェブサイトURL",
"Webhook 填:": "Webhook:",
"网站域名标识": "ウェブサイトドメインID",
"网络连接失败,请检查网络设置或稍后重试": "Network connection failed, please check network settings or try again later",
"网络配置": "Network Configuration",
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -2387,6 +2387,7 @@
"缩词": "Сокращение",
"缺省 MaxTokens": "MaxTokens по умолчанию",
"网站地址": "Адрес веб-сайта",
"Webhook 填:": "Webhook:",
"网站域名标识": "Идентификатор домена веб-сайта",
"网络连接失败,请检查网络设置或稍后重试": "Network connection failed, please check network settings or try again later",
"网络配置": "Network Configuration",
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -2664,6 +2664,7 @@
"缩词": "Rút gọn",
"缺省 MaxTokens": "MaxTokens mặc định",
"网站地址": "Địa chỉ trang web",
"Webhook 填:": "Webhook:",
"网站域名标识": "Định danh tên miền trang web",
"网络": "Mạng",
"网络连接失败,请检查网络设置或稍后重试": "Network connection failed, please check network settings or try again later",
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -1918,6 +1918,7 @@
"缩词": "缩词",
"缺省 MaxTokens": "缺省 MaxTokens",
"网站地址": "网站地址",
"Webhook 填:": "Webhook 填:",
"网站域名标识": "网站域名标识",
"网络连接失败,请检查网络设置或稍后重试": "网络连接失败,请检查网络设置或稍后重试",
"网络配置": "网络配置",
Expand Down
1 change: 1 addition & 0 deletions web/src/i18n/locales/zh-TW.json
Original file line number Diff line number Diff line change
Expand Up @@ -1925,6 +1925,7 @@
"缩词": "縮詞",
"缺省 MaxTokens": "缺省 MaxTokens",
"网站地址": "網站位址",
"Webhook 填:": "Webhook 填:",
"网站域名标识": "網站域名標識",
"网络连接失败,请检查网络设置或稍后重试": "網路連接失敗,請檢查網路設定或稍後重試",
"网络配置": "網路設定",
Expand Down
Loading