Extension management improvements (#5552) * feat: enhance asset management with extension categories Co-authored-by: Copilot <copilot@github.com> * fix: enhance extension name validation in server endpoints * feat: display extension author in the extensions list * fix: unify server error response format Co-authored-by: Copilot <copilot@github.com> * feat: add splash on installing third-party for the first time * fix: add URL format validation, unify validation error messages Co-authored-by: Copilot <copilot@github.com> * fix: apply object freeze to EMPTY_AUTHOR value Co-authored-by: Copilot <copilot@github.com> * fix: typecheck extensionName in API requests Co-authored-by: Copilot <copilot@github.com> * feat: add feature flag guard to extensions endpoints Co-authored-by: Copilot <copilot@github.com> * fix: parse URL before checking Co-authored-by: Copilot <copilot@github.com> * fix: use case insensitive regex check * fix: make debug log more useful Co-authored-by: Copilot <copilot@github.com> * fix: add pre-validation of URL format and protocol Co-authored-by: Copilot <copilot@github.com> * fix: leaner installation success toast * fix: settings data loss when extensions are disabled * fix: don't try to auto-focus elements that don't exist Co-authored-by: Copilot <copilot@github.com> * fix: set Popup.defaultResult to negative Co-authored-by: Copilot <copilot@github.com> * revert: restore undefined default result --------- Co-authored-by: Copilot <copilot@github.com>
Signed| @@ -97,13 +97,23 @@ label[for="extensions_autoconnect"] { | ||
| 97 | 97 | font-size: 1.05em; |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | 100 | .extensions_info :is(.extension_version, .extension_author) { |
| 101 | 101 | opacity: 0.8; |
| 102 | 102 | font-size: 0.8em; |
| 103 | 103 | font-weight: normal; |
| 104 | 104 | margin-left: 2px; |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | +.extensions_info :is(.extension_version, .extension_author):empty { | |
| 108 | + display: none; | |
| 109 | +} | |
| 110 | + | |
| 111 | +.extensions_info .extension_author { | |
| 112 | + display: inline-flex; | |
| 113 | + gap: 2px; | |
| 114 | + align-items: baseline; | |
| 115 | +} | |
| 116 | + | |
| 107 | 117 | .extensions_info .extension_block a { |
| 108 | 118 | color: var(--SmartThemeBodyColor); |
| 109 | 119 | } |
| @@ -7953,6 +7953,10 @@ export async function getSettings(initLoaderHandle = null) { | ||
| 7953 | 7953 | const isVersionChanged = settings.currentVersion !== currentVersion; |
| 7954 | 7954 | await loadExtensionSettings(settings, isVersionChanged, enableAutoUpdate); |
| 7955 | 7955 | await eventSource.emit(event_types.EXTENSION_SETTINGS_LOADED); |
| 7956 | + } else { | |
| 7957 | + Object.assign(extension_settings, (settings.extension_settings ?? {})); | |
| 7958 | + $('#third_party_extension_button').addClass('disabled'); | |
| 7959 | + $('#extensions_details').addClass('disabled'); | |
| 7956 | 7960 | } |
| 7957 | 7961 | |
| 7958 | 7962 | firstRun = !!settings.firstRun; |
| @@ -61,6 +61,19 @@ let manifests = {}; | ||
| 61 | 61 | */ |
| 62 | 62 | const defaultUrl = 'http://localhost:5100'; |
| 63 | 63 | |
| 64 | +/** | |
| 65 | + * Checks if the extension is officially supported by its URL pattern. | |
| 66 | + * @param {string} url URL to check | |
| 67 | + * @returns {boolean} True if the URL matches the pattern, false otherwise (or not a valid URL) | |
| 68 | + */ | |
| 69 | +export const isOfficialExtension = (url) => { | |
| 70 | + try { | |
| 71 | + return /^https:\/\/github\.com\/SillyTavern\/(.+)$/i.test(new URL(url).href); | |
| 72 | + } catch (e) { | |
| 73 | + return false; | |
| 74 | + } | |
| 75 | +}; | |
| 76 | + | |
| 64 | 77 | let requiresReload = false; |
| 65 | 78 | let stateChanged = false; |
| 66 | 79 | let saveMetadataTimeout = null; |
| @@ -928,6 +941,7 @@ function generateExtensionHtml(name, manifest, isActive, isDisabled, isExternal, | ||
| 928 | 941 | ${originHtml} |
| 929 | 942 | <span class="${isActive ? 'extension_enabled' : isDisabled ? 'extension_disabled' : 'extension_missing'}"> |
| 930 | 943 | <span class="extension_name">${DOMPurify.sanitize(displayName)}</span> |
| 944 | + <span class="extension_author"></span> | |
| 931 | 945 | <span class="extension_version">${DOMPurify.sanitize(displayVersion)}</span> |
| 932 | 946 | ${modulesInfo} |
| 933 | 947 | </span> |
| @@ -1557,9 +1571,53 @@ async function switchExtensionBranch(extensionName, isGlobal, branch) { | ||
| 1557 | 1571 | * Installs a third-party extension via the API. |
| 1558 | 1572 | * @param {string} url Extension repository URL |
| 1559 | 1573 | * @param {boolean} global Is the extension global? |
| 1560 | - * @returns {Promise<void>} | |
| 1574 | + * @param {string} [branch] Optional branch to install, if not provided the default branch will be used | |
| 1575 | + * @returns {Promise<boolean>} True if the extension was installed successfully, false otherwise | |
| 1561 | 1576 | */ |
| 1562 | 1577 | export async function installExtension(url, global, branch = '') { |
| 1578 | + try { | |
| 1579 | + const parsedUrl = new URL(url); | |
| 1580 | + if (!['http:', 'https:'].includes(parsedUrl.protocol)) { | |
| 1581 | + throw new Error('Invalid URL protocol'); | |
| 1582 | + } | |
| 1583 | + | |
| 1584 | + // Normalize the URL (resolve relative paths, remove redundant segments, etc.) | |
| 1585 | + url = parsedUrl.href; | |
| 1586 | + } catch (error) { | |
| 1587 | + console.error('Invalid URL:', error); | |
| 1588 | + toastr.error(t`Only valid HTTP and HTTPS URLs are allowed.`, t`Invalid URL`); | |
| 1589 | + return false; | |
| 1590 | + } | |
| 1591 | + | |
| 1592 | + if (!isOfficialExtension(url)) { | |
| 1593 | + const extensionInstallationWarningKey = 'extensionInstallationWarningShown'; | |
| 1594 | + if (accountStorage.getItem(extensionInstallationWarningKey)) { | |
| 1595 | + console.debug('Bypassed URL check for third-party extension (account preference).', url); | |
| 1596 | + } else { | |
| 1597 | + let dismissWarning = false; | |
| 1598 | + const confirmation = await Popup.show.confirm( | |
| 1599 | + t`Install a third-party extension?`, | |
| 1600 | + await renderTemplateAsync('thirdPartyExtensionWarning'), | |
| 1601 | + { | |
| 1602 | + customInputs: [{ id: 'dontAskAgain', type: 'checkbox', label: t`Don't show this warning again`, defaultState: false }], | |
| 1603 | + onClose: (popup) => { | |
| 1604 | + if (!popup.result) { | |
| 1605 | + return; | |
| 1606 | + } | |
| 1607 | + dismissWarning = Boolean(popup.inputResults?.get('dontAskAgain') ?? false); | |
| 1608 | + }, | |
| 1609 | + okButton: t`Yes, install it`, | |
| 1610 | + cancelButton: t`No, cancel`, | |
| 1611 | + }); | |
| 1612 | + if (!confirmation) { | |
| 1613 | + return false; | |
| 1614 | + } | |
| 1615 | + if (dismissWarning) { | |
| 1616 | + accountStorage.setItem(extensionInstallationWarningKey, '1'); | |
| 1617 | + } | |
| 1618 | + } | |
| 1619 | + } | |
| 1620 | + | |
| 1563 | 1621 | console.debug('Extension installation started', url); |
| 1564 | 1622 | |
| 1565 | 1623 | toastr.info(t`Please wait...`, t`Installing extension`); |
| @@ -1578,11 +1636,11 @@ export async function installExtension(url, global, branch = '') { | ||
| 1578 | 1636 | const text = await request.text(); |
| 1579 | 1637 | toastr.warning(text || request.statusText, t`Extension installation failed`, { timeOut: 5000 }); |
| 1580 | 1638 | console.error('Extension installation failed', request.status, request.statusText, text); |
| 1581 | 1639 | return false; |
| 1582 | 1640 | } |
| 1583 | 1641 | |
| 1584 | 1642 | const response = await request.json(); |
| 1585 | 1643 | toastr.success(t`Extension '${response.display_name}' by ${response.author} (version ${response.version}) has been installed successfully!`, t`Extension installation successful`); |
| 1586 | 1644 | console.debug(`Extension "${response.display_name}" has been installed successfully at ${response.extensionPath}`); |
| 1587 | 1645 | await loadExtensionSettings({}, false, false); |
| 1588 | 1646 | await eventSource.emit(event_types.EXTENSION_SETTINGS_LOADED, response); |
| @@ -1591,6 +1649,8 @@ export async function installExtension(url, global, branch = '') { | ||
| 1591 | 1649 | const extensionName = `third-party/${response.folderName}`; |
| 1592 | 1650 | await callExtensionHook(extensionName, 'install'); |
| 1593 | 1651 | } |
| 1652 | + | |
| 1653 | + return true; | |
| 1594 | 1654 | } |
| 1595 | 1655 | |
| 1596 | 1656 | /** |
| @@ -1701,6 +1761,18 @@ async function checkForUpdatesManual(sortFn, abortSignal) { | ||
| 1701 | 1761 | } |
| 1702 | 1762 | } |
| 1703 | 1763 | |
| 1764 | + const authorElement = extensionBlock.querySelector('.extension_author'); | |
| 1765 | + if (authorElement) { | |
| 1766 | + const author = getAuthorFromUrl(origin) || EMPTY_AUTHOR; | |
| 1767 | + if (author.name) { | |
| 1768 | + const icon = document.createElement('i'); | |
| 1769 | + icon.classList.add('fa-solid', 'fa-at', 'fa-xs'); | |
| 1770 | + const name = document.createElement('span'); | |
| 1771 | + name.textContent = author.name; | |
| 1772 | + authorElement.append(icon, name); | |
| 1773 | + } | |
| 1774 | + } | |
| 1775 | + | |
| 1704 | 1776 | const versionElement = extensionBlock.querySelector('.extension_version'); |
| 1705 | 1777 | if (versionElement) { |
| 1706 | 1778 | versionElement.textContent += ` (${branch}-${commitHash.substring(0, 7)})`; |
| @@ -2057,6 +2129,39 @@ export async function openThirdPartyExtensionMenu(suggestUrl = '') { | ||
| 2057 | 2129 | await installExtension(url, global, branchName); |
| 2058 | 2130 | } |
| 2059 | 2131 | |
| 2132 | +/** | |
| 2133 | + * Sentinel value representing an empty author, used when author information cannot be extracted from a URL. | |
| 2134 | + * @type {{name: string, url: string}} | |
| 2135 | + */ | |
| 2136 | +export const EMPTY_AUTHOR = Object.freeze({ | |
| 2137 | + name: '', | |
| 2138 | + url: '', | |
| 2139 | +}); | |
| 2140 | + | |
| 2141 | +/** | |
| 2142 | + * Extracts the repository author from a given URL. | |
| 2143 | + * @param {string} url - The URL of the repository. | |
| 2144 | + * @returns {{name: string, url: string}} Object containing the author's name and URL, or empty strings if not found. | |
| 2145 | + */ | |
| 2146 | +export function getAuthorFromUrl(url) { | |
| 2147 | + const result = structuredClone(EMPTY_AUTHOR); | |
| 2148 | + | |
| 2149 | + try { | |
| 2150 | + const parsedUrl = new URL(url); | |
| 2151 | + const pathSegments = parsedUrl.pathname.split('/').filter(s => s.length > 0); | |
| 2152 | + | |
| 2153 | + // TODO: Handle non-GitHub URLs if needed | |
| 2154 | + if (parsedUrl.host === 'github.com' && pathSegments.length >= 2) { | |
| 2155 | + result.name = pathSegments[0]; | |
| 2156 | + result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`; | |
| 2157 | + } | |
| 2158 | + } catch (error) { | |
| 2159 | + console.debug('Error parsing URL:', error); | |
| 2160 | + } | |
| 2161 | + | |
| 2162 | + return result; | |
| 2163 | +} | |
| 2164 | + | |
| 2060 | 2165 | export async function initExtensions() { |
| 2061 | 2166 | await addExtensionsButtonAndMenu(); |
| 2062 | 2167 | $('#extensionsMenuButton').css('display', 'flex'); |
| @@ -5,7 +5,7 @@ TODO: | ||
| 5 | 5 | |
| 6 | 6 | import { DOMPurify } from '../../../lib.js'; |
| 7 | 7 | import { getRequestHeaders, processDroppedFiles, eventSource, event_types } from '../../../script.js'; |
| 8 | 8 | import { deleteExtension, EMPTY_AUTHOR, extensionNames, getAuthorFromUrl, getContext, installExtension, renderExtensionTemplateAsync, isOfficialExtension } from '../../extensions.js'; |
| 9 | 9 | import { POPUP_TYPE, Popup, callGenericPopup } from '../../popup.js'; |
| 10 | 10 | import { executeSlashCommandsWithOptions } from '../../slash-commands.js'; |
| 11 | 11 | import { accountStorage } from '../../util/AccountStorage.js'; |
| @@ -60,35 +60,6 @@ const KNOWN_TYPES = { | ||
| 60 | 60 | 'blip': t`Blip sounds`, |
| 61 | 61 | }; |
| 62 | 62 | |
| 63 | -const EMPTY_AUTHOR = { | |
| 64 | - name: '', | |
| 65 | - url: '', | |
| 66 | -}; | |
| 67 | - | |
| 68 | -/** | |
| 69 | - * Extracts the repository author from a given URL. | |
| 70 | - * @param {string} url - The URL of the repository. | |
| 71 | - * @returns {{name: string, url: string}} Object containing the author's name and URL, or empty strings if not found. | |
| 72 | - */ | |
| 73 | -function getAuthorFromUrl(url) { | |
| 74 | - const result = structuredClone(EMPTY_AUTHOR); | |
| 75 | - | |
| 76 | - try { | |
| 77 | - const parsedUrl = new URL(url); | |
| 78 | - const pathSegments = parsedUrl.pathname.split('/').filter(s => s.length > 0); | |
| 79 | - | |
| 80 | - // TODO: Handle non-GitHub URLs if needed | |
| 81 | - if (parsedUrl.host === 'github.com' && pathSegments.length >= 2) { | |
| 82 | - result.name = pathSegments[0]; | |
| 83 | - result.url = `${parsedUrl.protocol}//${parsedUrl.hostname}/${result.name}`; | |
| 84 | - } | |
| 85 | - } catch (error) { | |
| 86 | - console.debug(DEBUG_PREFIX, 'Error parsing URL:', error); | |
| 87 | - } | |
| 88 | - | |
| 89 | - return result; | |
| 90 | -} | |
| 91 | - | |
| 92 | 63 | async function downloadAssetsList(url) { |
| 93 | 64 | updateCurrentAssets().then(async function () { |
| 94 | 65 | fetch(url, { cache: 'no-cache' }) |
| @@ -153,7 +124,15 @@ async function downloadAssetsList(url) { | ||
| 153 | 124 | element.off('click'); |
| 154 | 125 | label.removeClass('fa-download'); |
| 155 | 126 | this.classList.add('asset-download-button-loading'); |
| 156 | 127 | const result = await installAsset(asset.url, assetType, asset.id); |
| 128 | + if (!result) { | |
| 129 | + this.classList.remove('asset-download-button-loading'); | |
| 130 | + label.addClass('fa-download'); | |
| 131 | + label.removeClass('fa-spinner'); | |
| 132 | + label.removeClass('fa-spin'); | |
| 133 | + element.on('click', assetInstall); | |
| 134 | + return; | |
| 135 | + } | |
| 157 | 136 | label.addClass('fa-check'); |
| 158 | 137 | this.classList.remove('asset-download-button-loading'); |
| 159 | 138 | element.on('click', assetDelete); |
| @@ -248,8 +227,15 @@ async function downloadAssetsList(url) { | ||
| 248 | 227 | |
| 249 | 228 | assetBlock.addClass('asset-block'); |
| 250 | 229 | |
| 230 | + if (assetType === 'extension') { | |
| 231 | + const extensionBlockList = isOfficialExtension(asset.url) | |
| 232 | + ? assetTypeMenu.find('.assets-list-extensions-official .assets-list-extensions') | |
| 233 | + : assetTypeMenu.find('.assets-list-extensions-community .assets-list-extensions'); | |
| 234 | + extensionBlockList.append(assetBlock); | |
| 235 | + } else { | |
| 251 | 236 | assetTypeMenu.append(assetBlock); |
| 252 | 237 | } |
| 238 | + } | |
| 253 | 239 | assetTypeMenu.appendTo('#assets_menu'); |
| 254 | 240 | assetTypeMenu.on('click', 'a.asset_preview', previewAsset); |
| 255 | 241 | } |
| @@ -322,9 +308,9 @@ async function installAsset(url, assetType, filename) { | ||
| 322 | 308 | try { |
| 323 | 309 | if (category === 'extension') { |
| 324 | 310 | console.debug(DEBUG_PREFIX, 'Installing extension ', url); |
| 325 | 311 | const result = await installExtension(url, false); |
| 326 | 312 | console.debug(DEBUG_PREFIX, 'Extension installed.'); |
| 327 | 313 | return result; |
| 328 | 314 | } |
| 329 | 315 | |
| 330 | 316 | const body = { url, category, filename }; |
| @@ -343,10 +329,12 @@ async function installAsset(url, assetType, filename) { | ||
| 343 | 329 | await processDroppedFiles([file]); |
| 344 | 330 | console.debug(DEBUG_PREFIX, 'Character downloaded.'); |
| 345 | 331 | } |
| 332 | + return true; | |
| 346 | 333 | } |
| 334 | + return false; | |
| 347 | 335 | } catch (err) { |
| 348 | 336 | console.log(err); |
| 349 | 337 | return []false; |
| 350 | 338 | } |
| 351 | 339 | } |
| 352 | 340 | |
| @@ -398,9 +386,13 @@ async function openCharacterBrowser(forceDefault) { | ||
| 398 | 386 | |
| 399 | 387 | downloadButton.toggle(!isInstalled).on('click', async () => { |
| 400 | 388 | downloadButton.toggleClass('fa-download fa-spinner fa-spin'); |
| 401 | 389 | const result = await installAsset(character.url, 'character', character.id); |
| 390 | + if (result) { | |
| 402 | 391 | downloadButton.hide(); |
| 403 | 392 | checkMark.show(); |
| 393 | + } else { | |
| 394 | + downloadButton.toggleClass('fa-download fa-spinner fa-spin'); | |
| 395 | + } | |
| 404 | 396 | }); |
| 405 | 397 | |
| 406 | 398 | checkMark.toggle(isInstalled); |
| @@ -2,3 +2,21 @@ | ||
| 2 | 2 | <span data-i18n="extension_install_1">To download extensions from this page, you need to have </span><a href="https://git-scm.com/downloads" target="_blank">Git</a><span data-i18n="extension_install_2"> installed.</span><br> |
| 3 | 3 | <span data-i18n="extension_install_3">Click the </span><i class="fa-solid fa-sm fa-arrow-up-right-from-square"></i><span data-i18n="extension_install_4"> icon to visit the Extension's repo for tips on how to use it.</span> |
| 4 | 4 | </div> |
| 5 | +<div class="assets-list-extensions-official"> | |
| 6 | + <h2 data-i18n="Official Extensions">Official Extensions</h2> | |
| 7 | + <div class="info-block hint"> | |
| 8 | + <small class="assets-list-description" data-i18n="These extensions are maintained by the SillyTavern team."> | |
| 9 | + These extensions are maintained by the SillyTavern team. | |
| 10 | + </small> | |
| 11 | + </div> | |
| 12 | + <div class="assets-list-extensions"></div> | |
| 13 | +</div> | |
| 14 | +<div class="assets-list-extensions-community"> | |
| 15 | + <h2 data-i18n="Community Extensions">Community Extensions</h2> | |
| 16 | + <div class="info-block warning"> | |
| 17 | + <small data-i18n="Community extensions are not reviewed or verified by the SillyTavern team. Please exercise caution when installing."> | |
| 18 | + Community extensions are not reviewed or verified by the SillyTavern team. Please exercise caution when installing. | |
| 19 | + </small> | |
| 20 | + </div> | |
| 21 | + <div class="assets-list-extensions"></div> | |
| 22 | +</div> | |
| @@ -27,15 +27,20 @@ | ||
| 27 | 27 | margin-bottom: 0.25em; |
| 28 | 28 | } |
| 29 | 29 | |
| 30 | +.assets-list-div h2 { | |
| 31 | + margin: 0; | |
| 32 | + font-size: 1.1em; | |
| 33 | +} | |
| 34 | + | |
| 30 | 35 | .assets-list-div h3 { |
| 31 | 36 | text-transform: capitalize; |
| 32 | 37 | } |
| 33 | 38 | |
| 34 | 39 | .assets-list-div i.asset-block a { |
| 35 | 40 | color: inherit; |
| 36 | 41 | } |
| 37 | 42 | |
| 38 | 43 | .assets-list-div>i .asset-block { |
| 39 | 44 | display: flex; |
| 40 | 45 | flex-direction: row; |
| 41 | 46 | align-items: center; |
| @@ -46,7 +51,7 @@ | ||
| 46 | 51 | border-bottom: 1px solid var(--SmartThemeBorderColor); |
| 47 | 52 | } |
| 48 | 53 | |
| 49 | 54 | .assets-list-div i.asset-block span:first-of-type { |
| 50 | 55 | font-weight: bold; |
| 51 | 56 | } |
| 52 | 57 | |
| @@ -198,3 +203,11 @@ | ||
| 198 | 203 | .asset-name>b { |
| 199 | 204 | font-weight: 600; |
| 200 | 205 | } |
| 206 | + | |
| 207 | +div:is(.assets-list-extensions-official, .assets-list-extensions-community):has(.assets-list-extensions:empty) { | |
| 208 | + display: none; | |
| 209 | +} | |
| 210 | + | |
| 211 | +div:is(.assets-list-extensions-official, .assets-list-extensions-community) { | |
| 212 | + margin-top: 10px; | |
| 213 | +} | |
| @@ -718,6 +718,10 @@ export class Popup { | ||
| 718 | 718 | } |
| 719 | 719 | } |
| 720 | 720 | |
| 721 | + if (!control) { | |
| 722 | + return; | |
| 723 | + } | |
| 724 | + | |
| 721 | 725 | if (applyAutoFocus) { |
| 722 | 726 | control.setAttribute('autofocus', ''); |
| 723 | 727 | // Manually enable tabindex too, as this might only be applied by the interactable functionality in the background, but too late for HTML autofocus |
| @@ -0,0 +1,18 @@ | ||
| 1 | +<p> | |
| 2 | + <em data-i18n="The URL you provided does not seem to be an official SillyTavern extension repository."> | |
| 3 | + The URL you provided does not seem to be an official SillyTavern extension repository. | |
| 4 | + </em> | |
| 5 | +</p> | |
| 6 | +<p class="info-block error"> | |
| 7 | + <span data-i18n="Using third-party extensions can have unintended side effects and may pose security risks."> | |
| 8 | + Using third-party extensions can have unintended side effects and may pose security risks. | |
| 9 | + </span> | |
| 10 | + <span data-i18n="Always make sure you trust the source before importing an extension. We are not responsible for any damage caused by third-party extensions."> | |
| 11 | + Always make sure you trust the source before importing an extension. We are not responsible for any damage caused by third-party extensions. | |
| 12 | + </span> | |
| 13 | +</p> | |
| 14 | +<p> | |
| 15 | + <b data-i18n="Are you sure you want to proceed?"> | |
| 16 | + Are you sure you want to proceed? | |
| 17 | + </b> | |
| 18 | +</p> | |
| @@ -6,7 +6,7 @@ import sanitize from 'sanitize-filename'; | ||
| 6 | 6 | import { CheckRepoActions, default as simpleGit } from 'simple-git'; |
| 7 | 7 | |
| 8 | 8 | import { PUBLIC_DIRECTORIES } from '../constants.js'; |
| 9 | 9 | import { getConfigValue, isValidUrl } from '../util.js'; |
| 10 | 10 | import { createGitClient } from '../git/client.js'; |
| 11 | 11 | |
| 12 | 12 | const gitBackend = getConfigValue('git.backend', 'auto'); |
| @@ -65,6 +65,15 @@ async function checkIfRepoIsUpToDate(extensionPath) { | ||
| 65 | 65 | |
| 66 | 66 | export const router = express.Router(); |
| 67 | 67 | |
| 68 | +// Feature flag guard: don't allow calling any of the endpoints if extensions are disabled | |
| 69 | +router.use((_, response, next) => { | |
| 70 | + const enabled = !!getConfigValue('extensions.enabled', true, 'boolean'); | |
| 71 | + if (!enabled) { | |
| 72 | + return response.status(400).send('Bad Request: Extensions are disabled.'); | |
| 73 | + } | |
| 74 | + next(); | |
| 75 | +}); | |
| 76 | + | |
| 68 | 77 | /** |
| 69 | 78 | * HTTP POST handler function to clone a git repository from a provided URL, read the extension manifest, |
| 70 | 79 | * and return extension information and path. |
| @@ -75,11 +84,23 @@ export const router = express.Router(); | ||
| 75 | 84 | * @returns {void} |
| 76 | 85 | */ |
| 77 | 86 | router.post('/install', async (request, response) => { |
| 78 | - if (!request.body.url) { | |
| 87 | + try { | |
| 79 | - return response.status(400).send('Bad Request: URL is required in the request body.'); | |
| 88 | + const { url, global, branch } = request.body; | |
| 89 | + | |
| 90 | + if (global && !request.user.profile.admin) { | |
| 91 | + console.error(`User ${request.user.profile.handle} does not have permission to install global extensions.`); | |
| 92 | + return response.status(403).send('Forbidden: No permission to install global extensions.'); | |
| 93 | + } | |
| 94 | + | |
| 95 | + if (!isValidUrl(url)) { | |
| 96 | + return response.status(400).send('Bad Request: A valid URL is required in the request body.'); | |
| 97 | + } | |
| 98 | + | |
| 99 | + const parsedUrl = new URL(url); | |
| 100 | + if (!['http:', 'https:'].includes(parsedUrl.protocol)) { | |
| 101 | + return response.status(400).send('Bad Request: Only HTTP and HTTPS protocols are supported for the Extension URL.'); | |
| 80 | 102 | } |
| 81 | 103 | |
| 82 | - try { | |
| 83 | 104 | const git = createGitClient({ backend: gitBackend }); |
| 84 | 105 | |
| 85 | 106 | // make sure the third-party directory exists |
| @@ -91,15 +112,13 @@ router.post('/install', async (request, response) => { | ||
| 91 | 112 | fs.mkdirSync(PUBLIC_DIRECTORIES.globalExtensions); |
| 92 | 113 | } |
| 93 | 114 | |
| 94 | 115 | const {basePath url,= global, branch? }PUBLIC_DIRECTORIES.globalExtensions =: request.bodyuser.directories.extensions; |
| 95 | - | |
| 116 | + const extensionNameSanitized = sanitize(path.basename(parsedUrl.pathname, '.git')); | |
| 96 | 117 | if (global && !request.user.profile.adminextensionNameSanitized) { |
| 97 | - console.error(`User ${request.user.profile.handle} does not have permission to install global extensions.`); | |
| 118 | + return response.status(400).send('Could not determine the extension name from the URL. Please provide a valid git repository URL.'); | |
| 98 | - return response.status(403).send('Forbidden: No permission to install global extensions.'); | |
| 99 | 119 | } |
| 100 | 120 | |
| 101 | - const basePath = global ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; | |
| 121 | + const extensionPath = path.join(basePath, extensionNameSanitized); | |
| 102 | - const extensionPath = path.join(basePath, sanitize(path.basename(url, '.git'))); | |
| 103 | 122 | |
| 104 | 123 | if (fs.existsSync(extensionPath)) { |
| 105 | 124 | return response.status(409).send(`Directory already exists at ${extensionPath}`); |
| @@ -109,16 +128,16 @@ router.post('/install', async (request, response) => { | ||
| 109 | 128 | if (branch) { |
| 110 | 129 | cloneOptions.branch = branch; |
| 111 | 130 | } |
| 112 | 131 | await git.clone(urlparsedUrl.href, extensionPath, cloneOptions); |
| 113 | 132 | console.info(`Extension has been cloned to ${extensionPath} from ${urlparsedUrl.href} at ${branch || '(default)'} branch`); |
| 114 | 133 | |
| 115 | 134 | const { version, author, display_name } = await getManifest(extensionPath); |
| 116 | 135 | const folderName = path.basename(extensionPath); |
| 117 | 136 | |
| 118 | 137 | return response.send({ version, author, display_name, extensionPath, folderName }); |
| 119 | 138 | } catch (error) { |
| 120 | 139 | console.error('Importing custom contentextension failed', error); |
| 121 | 140 | return response.status(500).send(`'Internal Server Error:. ${errorCheck the server logs for more details.message}`'); |
| 122 | 141 | } |
| 123 | 142 | }); |
| 124 | 143 | |
| @@ -134,12 +153,16 @@ router.post('/install', async (request, response) => { | ||
| 134 | 153 | * @returns {void} |
| 135 | 154 | */ |
| 136 | 155 | router.post('/update', async (request, response) => { |
| 137 | - if (!request.body.extensionName) { | |
| 156 | + try { | |
| 138 | - return response.status(400).send('Bad Request: extensionName is required in the request body.'); | |
| 157 | + if (typeof request.body.extensionName !== 'string') { | |
| 158 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 139 | 159 | } |
| 140 | 160 | |
| 141 | - try { | |
| 142 | 161 | const { extensionName, global } = request.body; |
| 162 | + const extensionNameSanitized = sanitize(extensionName); | |
| 163 | + if (!extensionNameSanitized) { | |
| 164 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 165 | + } | |
| 143 | 166 | |
| 144 | 167 | if (global && !request.user.profile.admin) { |
| 145 | 168 | console.error(`User ${request.user.profile.handle} does not have permission to update global extensions.`); |
| @@ -147,7 +170,7 @@ router.post('/update', async (request, response) => { | ||
| 147 | 170 | } |
| 148 | 171 | |
| 149 | 172 | const basePath = global ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; |
| 150 | 173 | const extensionPath = path.join(basePath, sanitize(extensionName)extensionNameSanitized); |
| 151 | 174 | |
| 152 | 175 | if (!fs.existsSync(extensionPath)) { |
| 153 | 176 | return response.status(404).send(`Directory does not exist at ${extensionPath}`); |
| @@ -179,10 +202,14 @@ router.post('/update', async (request, response) => { | ||
| 179 | 202 | |
| 180 | 203 | router.post('/branches', async (request, response) => { |
| 181 | 204 | try { |
| 182 | - const { extensionName, global } = request.body; | |
| 205 | + if (typeof request.body.extensionName !== 'string') { | |
| 206 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 207 | + } | |
| 183 | 208 | |
| 184 | - if (!extensionName) { | |
| 209 | + const { extensionName, global } = request.body; | |
| 185 | - return response.status(400).send('Bad Request: extensionName is required in the request body.'); | |
| 210 | + const extensionNameSanitized = sanitize(extensionName); | |
| 211 | + if (!extensionNameSanitized) { | |
| 212 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 186 | 213 | } |
| 187 | 214 | |
| 188 | 215 | if (global && !request.user.profile.admin) { |
| @@ -191,7 +218,7 @@ router.post('/branches', async (request, response) => { | ||
| 191 | 218 | } |
| 192 | 219 | |
| 193 | 220 | const basePath = global ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; |
| 194 | 221 | const extensionPath = path.join(basePath, sanitize(extensionName)extensionNameSanitized); |
| 195 | 222 | |
| 196 | 223 | if (!fs.existsSync(extensionPath)) { |
| 197 | 224 | return response.status(404).send(`Directory does not exist at ${extensionPath}`); |
| @@ -224,10 +251,14 @@ router.post('/branches', async (request, response) => { | ||
| 224 | 251 | |
| 225 | 252 | router.post('/switch', async (request, response) => { |
| 226 | 253 | try { |
| 227 | - const { extensionName, branch, global } = request.body; | |
| 254 | + if (typeof request.body.extensionName !== 'string') { | |
| 255 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 256 | + } | |
| 228 | 257 | |
| 229 | - if (!extensionName || !branch) { | |
| 258 | + const { extensionName, branch, global } = request.body; | |
| 230 | - return response.status(400).send('Bad Request: extensionName and branch are required in the request body.'); | |
| 259 | + const extensionNameSanitized = sanitize(extensionName); | |
| 260 | + if (!extensionNameSanitized || !branch) { | |
| 261 | + return response.status(400).send('Bad Request: A valid extensionName and branch are required in the request body.'); | |
| 231 | 262 | } |
| 232 | 263 | |
| 233 | 264 | if (global && !request.user.profile.admin) { |
| @@ -236,7 +267,7 @@ router.post('/switch', async (request, response) => { | ||
| 236 | 267 | } |
| 237 | 268 | |
| 238 | 269 | const basePath = global ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; |
| 239 | 270 | const extensionPath = path.join(basePath, sanitize(extensionName)extensionNameSanitized); |
| 240 | 271 | |
| 241 | 272 | if (!fs.existsSync(extensionPath)) { |
| 242 | 273 | return response.status(404).send(`Directory does not exist at ${extensionPath}`); |
| @@ -283,10 +314,14 @@ router.post('/switch', async (request, response) => { | ||
| 283 | 314 | |
| 284 | 315 | router.post('/move', async (request, response) => { |
| 285 | 316 | try { |
| 286 | - const { extensionName, source, destination } = request.body; | |
| 317 | + if (typeof request.body.extensionName !== 'string') { | |
| 318 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 319 | + } | |
| 287 | 320 | |
| 288 | - if (!extensionName || !source || !destination) { | |
| 321 | + const { extensionName, source, destination } = request.body; | |
| 289 | - return response.status(400).send('Bad Request. Not all required parameters are provided.'); | |
| 322 | + const extensionNameSanitized = sanitize(extensionName); | |
| 323 | + if (!extensionNameSanitized || !source || !destination) { | |
| 324 | + return response.status(400).send('Bad Request: A valid extensionName, source, and destination are required in the request body.'); | |
| 290 | 325 | } |
| 291 | 326 | |
| 292 | 327 | if (!request.user.profile.admin) { |
| @@ -296,8 +331,8 @@ router.post('/move', async (request, response) => { | ||
| 296 | 331 | |
| 297 | 332 | const sourceDirectory = source === 'global' ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; |
| 298 | 333 | const destinationDirectory = destination === 'global' ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; |
| 299 | 334 | const sourcePath = path.join(sourceDirectory, sanitize(extensionName)extensionNameSanitized); |
| 300 | 335 | const destinationPath = path.join(destinationDirectory, sanitize(extensionName)extensionNameSanitized); |
| 301 | 336 | |
| 302 | 337 | if (!fs.existsSync(sourcePath) || !fs.statSync(sourcePath).isDirectory()) { |
| 303 | 338 | console.error(`Source directory does not exist at ${sourcePath}`); |
| @@ -336,14 +371,19 @@ router.post('/move', async (request, response) => { | ||
| 336 | 371 | * @returns {void} |
| 337 | 372 | */ |
| 338 | 373 | router.post('/version', async (request, response) => { |
| 339 | - if (!request.body.extensionName) { | |
| 374 | + try { | |
| 340 | - return response.status(400).send('Bad Request: extensionName is required in the request body.'); | |
| 375 | + if (typeof request.body.extensionName !== 'string') { | |
| 376 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 341 | 377 | } |
| 342 | 378 | |
| 343 | - try { | |
| 344 | 379 | const { extensionName, global } = request.body; |
| 380 | + const extensionNameSanitized = sanitize(extensionName); | |
| 381 | + if (!extensionNameSanitized) { | |
| 382 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 383 | + } | |
| 384 | + | |
| 345 | 385 | const basePath = global ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; |
| 346 | 386 | const extensionPath = path.join(basePath, sanitize(extensionName)extensionNameSanitized); |
| 347 | 387 | |
| 348 | 388 | if (!fs.existsSync(extensionPath)) { |
| 349 | 389 | return response.status(404).send(`Directory does not exist at ${extensionPath}`); |
| @@ -367,31 +407,35 @@ router.post('/version', async (request, response) => { | ||
| 367 | 407 | // get only the working branch |
| 368 | 408 | const currentBranchName = currentBranch.current; |
| 369 | 409 | await git.fetch('origin'); |
| 370 | 410 | console.debug(extensionNameextensionNameSanitized, currentBranchName, currentCommitHash); |
| 371 | 411 | const { isUpToDate, remoteUrl } = await checkIfRepoIsUpToDate(extensionPath); |
| 372 | 412 | |
| 373 | 413 | return response.send({ currentBranchName, currentCommitHash, isUpToDate, remoteUrl }); |
| 374 | 414 | } catch (error) { |
| 375 | 415 | console.error('Getting extension version failed', error); |
| 376 | 416 | return response.status(500).send(`'Internal Server Error:. ${errorCheck the server logs for more details.message}`'); |
| 377 | 417 | } |
| 378 | 418 | }); |
| 379 | 419 | |
| 380 | 420 | /** |
| 381 | 421 | * HTTP POST handler function to delete a git repository based on the extension name provided in the request body. |
| 382 | 422 | * |
| 383 | 423 | * @param {Object} request - HTTP Request object, expects a JSON body with a 'urlextensionName' property. |
| 384 | 424 | * @param {Object} response - HTTP Response object used to respond to the HTTP request. |
| 385 | 425 | * |
| 386 | 426 | * @returns {void} |
| 387 | 427 | */ |
| 388 | 428 | router.post('/delete', async (request, response) => { |
| 389 | - if (!request.body.extensionName) { | |
| 429 | + try { | |
| 390 | - return response.status(400).send('Bad Request: extensionName is required in the request body.'); | |
| 430 | + if (typeof request.body.extensionName !== 'string') { | |
| 431 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 391 | 432 | } |
| 392 | 433 | |
| 393 | - try { | |
| 394 | 434 | const { extensionName, global } = request.body; |
| 435 | + const extensionNameSanitized = sanitize(extensionName); | |
| 436 | + if (!extensionNameSanitized) { | |
| 437 | + return response.status(400).send('Bad Request: A valid extensionName is required in the request body.'); | |
| 438 | + } | |
| 395 | 439 | |
| 396 | 440 | if (global && !request.user.profile.admin) { |
| 397 | 441 | console.error(`User ${request.user.profile.handle} does not have permission to delete global extensions.`); |
| @@ -399,7 +443,7 @@ router.post('/delete', async (request, response) => { | ||
| 399 | 443 | } |
| 400 | 444 | |
| 401 | 445 | const basePath = global ? PUBLIC_DIRECTORIES.globalExtensions : request.user.directories.extensions; |
| 402 | 446 | const extensionPath = path.join(basePath, sanitize(extensionName)extensionNameSanitized); |
| 403 | 447 | |
| 404 | 448 | if (!fs.existsSync(extensionPath)) { |
| 405 | 449 | return response.status(404).send(`Directory does not exist at ${extensionPath}`); |
| @@ -410,8 +454,8 @@ router.post('/delete', async (request, response) => { | ||
| 410 | 454 | |
| 411 | 455 | return response.send(`Extension has been deleted at ${extensionPath}`); |
| 412 | 456 | } catch (error) { |
| 413 | 457 | console.error('Deleting custom contentextension failed', error); |
| 414 | 458 | return response.status(500).send(`'Internal Server Error:. ${errorCheck the server logs for more details.message}`'); |
| 415 | 459 | } |
| 416 | 460 | }); |
| 417 | 461 | |