Fix URL calculation in clone input box (#29470) (#29473)

Backport #29470 by @silverwind

Ported the function as-is and added comments so we don't forget about
this in the future.

Fixes: https://github.com/go-gitea/gitea/issues/29462

Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
Giteabot 2024-02-28 23:25:53 +08:00 committed by GitHub
parent eabcfd3f7d
commit 222f93822e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 9 deletions

View File

@ -24,14 +24,22 @@
const btn = isSSH ? sshBtn : httpsBtn; const btn = isSSH ? sshBtn : httpsBtn;
if (!btn) return; if (!btn) return;
let link = btn.getAttribute('data-link'); // NOTE: Keep this function in sync with the one in the js folder
if (link.startsWith('http://') || link.startsWith('https://')) { function toOriginUrl(urlStr) {
// use current protocol/host as the clone link try {
const url = new URL(link); if (urlStr.startsWith('http://') || urlStr.startsWith('https://') || urlStr.startsWith('/')) {
url.protocol = window.location.protocol; const {origin, protocol, hostname, port} = window.location;
url.host = window.location.host; const url = new URL(urlStr, origin);
link = url.toString(); url.protocol = protocol;
url.hostname = hostname;
url.port = port || (protocol === 'https:' ? '443' : '80');
return url.toString();
}
} catch {}
return urlStr;
} }
const link = toOriginUrl(btn.getAttribute('data-link'));
for (const el of document.getElementsByClassName('js-clone-url')) { for (const el of document.getElementsByClassName('js-clone-url')) {
el[el.nodeName === 'INPUT' ? 'value' : 'textContent'] = link; el[el.nodeName === 'INPUT' ? 'value' : 'textContent'] = link;
} }

View File

@ -1,7 +1,8 @@
// Convert an absolute or relative URL to an absolute URL with the current origin // Convert an absolute or relative URL to an absolute URL with the current origin. It only
// processes absolute HTTP/HTTPS URLs or relative URLs like '/xxx' or '//host/xxx'.
// NOTE: Keep this function in sync with clone_script.tmpl
export function toOriginUrl(urlStr) { export function toOriginUrl(urlStr) {
try { try {
// only process absolute HTTP/HTTPS URL or relative URLs ('/xxx' or '//host/xxx')
if (urlStr.startsWith('http://') || urlStr.startsWith('https://') || urlStr.startsWith('/')) { if (urlStr.startsWith('http://') || urlStr.startsWith('https://') || urlStr.startsWith('/')) {
const {origin, protocol, hostname, port} = window.location; const {origin, protocol, hostname, port} = window.location;
const url = new URL(urlStr, origin); const url = new URL(urlStr, origin);