From d3f3fe926a0514932f29f2c20ac40b9b8402ac7d Mon Sep 17 00:00:00 2001 From: Olivier Date: Sun, 25 Oct 2026 20:39:33 -0400 Subject: [PATCH] fix: scope tokens per host, harden Gitea support, port upstream fixes Fork fixes: - Global token is GitHub-only; never sent to Gitea/Forgejo hosts - Gitea: download assets via browser_download_url (+token) so private repos work - Gitea URL parsing keeps port and sub-path installs, strips browser sub-pages - GitHub detected by hostname, not substring - Gitea releases: follow pagination (X-Total-Count), skip drafts - Gitea token validation against the repo; 404 is no longer "valid" - Settings tab and migration log use this plugin's own id/folder - Check-only mode no longer reinstalls/enables a missing plugin folder - reloadPlugin reports load failures (enablePlugin resolves false) - Repository / release-notes links work for both providers Ported from upstream BRAT 2.2.0: - Release sort: semver tags first, date fallback - Null-safe version comparison, JSON shape guards - Drop obsidian-daily-notes-interface (read daily note format directly) - Notice.messageEl, CSS without !important, console.debug/error --- README.md | 7 +- package.json | 3 +- src/features/BetaPlugins.ts | 197 +++++++++---------- src/features/communityUtils.ts | 4 +- src/features/themes.ts | 31 ++- src/main.ts | 13 +- src/migrations.ts | 21 +- src/providers/GitHubProvider.ts | 116 +++++------ src/providers/GiteaProvider.ts | 331 +++++++++++++++++--------------- src/providers/PluginProvider.ts | 7 +- src/providers/index.ts | 70 +++---- src/providers/releases.ts | 69 +++++++ src/settings.ts | 9 +- src/ui/AddNewPluginModal.ts | 63 ++---- src/ui/AddNewTheme.ts | 14 +- src/ui/PluginCommands.ts | 9 +- src/ui/SettingsTab.ts | 8 +- src/utils/BratAPI.ts | 13 +- src/utils/logging.ts | 52 ++++- src/utils/notifications.ts | 2 +- styles.css | 4 +- 21 files changed, 548 insertions(+), 495 deletions(-) create mode 100644 src/providers/releases.ts diff --git a/README.md b/README.md index f210dc0..a92887c 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,12 @@ Open the BRAT command palette and choose **"Add a beta plugin for testing"**, th | **GitHub** | `user/repo` or `https://github.com/user/repo` | `TfTHacker/obsidian42-brat` | | **Gitea** | `https://git.your-instance.com/user/repo` | `https://gitea.mithrilforge.dev/olivier/BindThem` | -The plugin auto-detects the provider from the URL. Each plugin entry stores its own Gitea instance URL and optional access token. +The plugin auto-detects the provider from the URL host: `github.com` is GitHub, any other host is Gitea/Forgejo. Gitea addresses may include a port (`https://git.lan:3000/user/repo`) or a sub-path install (`https://example.com/gitea/user/repo`); a pasted browser URL such as `…/user/repo/releases/tag/v1.0` is reduced to the repository. + +### Access tokens + +- **Global token** (settings): GitHub only. It is never sent to a Gitea/Forgejo host. +- **Per-plugin token**: set in the add-plugin dialog; sent only to that plugin's host. Use it for private Gitea repos. ## Installation diff --git a/package.json b/package.json index e5bcb71..c2b7a18 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,6 @@ "typescript": "5.9.2" }, "dependencies": { - "obsidian-daily-notes-interface": "^0.9.4", "semver": "^7.7.2" } -} \ No newline at end of file +} diff --git a/src/features/BetaPlugins.ts b/src/features/BetaPlugins.ts index 76aa2da..d4141c6 100644 --- a/src/features/BetaPlugins.ts +++ b/src/features/BetaPlugins.ts @@ -6,6 +6,7 @@ import { Platform, requireApiVersion, } from "obsidian"; +import { compare as compareVersions, coerce as semverCoerce } from "semver"; import { confirm } from "src/ui/ConfirmModal"; import { ProviderRateLimitError, @@ -20,9 +21,6 @@ import { isConnectedToInternet } from "../utils/internetconnection"; import { toastMessage } from "../utils/notifications"; import type { ReleaseFiles } from "./BetaPluginsTypes"; -const compareVersions = require("semver/functions/compare"); -const semverCoerce = require("semver/functions/coerce"); - interface PluginManifestEx extends PluginManifest { brat: { isIncompatible?: boolean; @@ -57,30 +55,17 @@ export default class BetaPlugins { } /** - * Look up the Gitea instance URL stored per-plugin in settings (if any). - * For plugins added before Gitea support, this could be empty. + * Token to send for a repository: its own secret if one is set, otherwise + * the global token, which is a GitHub token and is never sent to other hosts. */ - private getGiteaUrlForRepo(repoPath: string): string { - const entry = this.plugin.settings.pluginSubListFrozenVersion.find( - (p) => p.repo === repoPath, - ); - return entry?.giteaUrl ?? ""; - } - - /** - * Retrieves the token value for a given plugin. - * Checks per-repo secret first, then global token. - */ - private async getTokenForRepo(repoPath: string, secretName?: string): Promise { - if (secretName) { - return (await this.plugin.app.secretStorage.getSecret(secretName)) || ""; + resolveToken(parsed: ParsedRepo, secretName = ""): string { + const { secretStorage } = this.plugin.app; + if (secretName.trim() !== "") { + return secretStorage.getSecret(secretName) ?? ""; } - if (this.plugin.settings.globalTokenName) { - return ( - (await this.plugin.app.secretStorage.getSecret( - this.plugin.settings.globalTokenName, - )) || "" - ); + const { globalTokenName } = this.plugin.settings; + if (parsed.isGitHub && globalTokenName) { + return secretStorage.getSecret(globalTokenName) ?? ""; } return ""; } @@ -124,7 +109,6 @@ export default class BetaPlugins { reportIssues = false, specifyVersion = "", privateApiKey = "", - giteaUrl = "", ): Promise { const noticeTimeout = 15; @@ -193,31 +177,28 @@ export default class BetaPlugins { return null; } - // Version mismatch handling (same as original BRAT) - try { - const expectedVersion = semverCoerce(release.tag_name, { - includePrerelease: true, - loose: true, - }); - const manifestVersion = semverCoerce(manifestJson.version, { - includePrerelease: true, - loose: true, - }); - if ( - expectedVersion && - manifestVersion && - compareVersions(expectedVersion, manifestVersion) !== 0 - ) { - if (reportIssues) - toastMessage( - this.plugin, - `${repositoryPath}\nVersion mismatch: release tag '${release.tag_name}' vs manifest '${manifestJson.version}'. Using release version.`, - noticeTimeout, - ); - manifestJson.version = expectedVersion.version; - } - } catch { - // Ignore comparison errors + // Improve robustness: if semver coercion fails, compare raw versions. + const expectedVersion = semverCoerce(release.tag_name, { + includePrerelease: true, + loose: true, + }); + const manifestVersion = semverCoerce(manifestJson.version, { + includePrerelease: true, + loose: true, + }); + const hasVersionMismatch = + expectedVersion && manifestVersion + ? compareVersions(expectedVersion.version, manifestVersion.version) !== 0 + : expectedVersion !== null && manifestJson.version !== release.tag_name; + + if (hasVersionMismatch && expectedVersion) { + if (reportIssues) + toastMessage( + this.plugin, + `${repositoryPath}\nVersion mismatch: release tag '${release.tag_name}' vs manifest '${manifestJson.version}'. Using release version.`, + noticeTimeout, + ); + manifestJson.version = expectedVersion.version; } return manifestJson; @@ -257,7 +238,7 @@ export default class BetaPlugins { if (reportIssues) toastMessage( this.plugin, - `${repositoryPath}\nUnspecified error: ${error}. Enable debug for more info.`, + `${repositoryPath}\nUnspecified error: ${String(error)}. Enable debug for more info.`, noticeTimeout, ); return null; @@ -272,7 +253,6 @@ export default class BetaPlugins { getManifest: boolean, specifyVersion = "", tokenValue = "", - giteaUrl = "", ): Promise { const { provider, parsed } = this.resolveProvider(repositoryPath); @@ -287,11 +267,12 @@ export default class BetaPlugins { ); if (!release) { - return Promise.reject("No release found"); + throw new Error("No release found"); } const reallyGetManifestOrNot = getManifest || specifyVersion !== ""; - console.log({ reallyGetManifestOrNot, version: release.tag_name }); + if (this.plugin.settings.debuggingMode) + console.debug({ reallyGetManifestOrNot, version: release.tag_name }); return { mainJs: await provider.getAsset( @@ -360,7 +341,7 @@ export default class BetaPlugins { ): Promise { try { if (this.plugin.settings.debuggingMode) { - console.log( + console.debug( "BRAT: addPlugin", repositoryPath, updatePluginFiles, @@ -373,29 +354,18 @@ export default class BetaPlugins { ); } - // Resolve provider for this repo - const { provider, parsed } = this.resolveProvider(repositoryPath); + const { parsed } = this.resolveProvider(repositoryPath); // Retrieve token - let tokenValue = ""; - if (secretName && secretName.trim() !== "") { - tokenValue = - (await this.plugin.app.secretStorage.getSecret(secretName)) || ""; - if (!tokenValue) { - toastMessage( - this.plugin, - `Secret not found for token name: ${secretName}. Please add it to SecretStorage or clear the token name for this plugin.`, - 10, - ); - } - } else if (this.plugin.settings.globalTokenName) { - tokenValue = - (await this.plugin.app.secretStorage.getSecret( - this.plugin.settings.globalTokenName, - )) || ""; + const tokenValue = this.resolveToken(parsed, secretName); + if (secretName.trim() !== "" && !tokenValue) { + toastMessage( + this.plugin, + `Secret not found for token name: ${secretName}. Please add it to SecretStorage or clear the token name for this plugin.`, + 10, + ); } - const giteaUrl = this.getGiteaUrlForRepo(repositoryPath); const noticeTimeout = 10; // Attempt to get manifest (check for beta/pre-release first) @@ -405,7 +375,6 @@ export default class BetaPlugins { true, specifyVersion, tokenValue, - giteaUrl, ); const usingBetaManifest: boolean = !!primaryManifest; if (!usingBetaManifest) @@ -415,7 +384,6 @@ export default class BetaPlugins { true, specifyVersion, tokenValue, - giteaUrl, ); if (primaryManifest === null) { @@ -473,7 +441,6 @@ export default class BetaPlugins { usingBetaManifest, specifyVersion, tokenValue, - giteaUrl, ); if (usingBetaManifest || rFiles.manifest === "") @@ -544,8 +511,6 @@ export default class BetaPlugins { specifyVersion, isIncompatible, secretName, - // Store Gitea URL if this is a Gitea repo - parsed.isGitHub ? "" : parsed.rawBaseUrl, ); if (enableAfterInstall) { // @ts-expect-error @@ -583,13 +548,19 @@ export default class BetaPlugins { const vaultAdapter = this.plugin.app.vault.adapter; if (!(await vaultAdapter.exists(localManifestPath))) { // Plugin folder is empty/missing (deleted by sync, by hand, ...). + if (seeIfUpdatedOnly) { + const msg = `${repositoryPath}\nPlugin folder is missing; run "Check for updates and update" to reinstall it.`; + await this.plugin.log(msg, true); + toastMessage(this.plugin, msg, 30); + return false; + } // Reinstall it. updatePlugin() hard-codes enableAfterInstall=false // for plain updates, which here would leave the plugin installed // but disabled, so use the user's setting instead. return await this.addPlugin( repositoryPath, false, - usingBetaManifest, + false, false, specifyVersion, false, @@ -618,18 +589,21 @@ export default class BetaPlugins { includePrerelease: true, loose: true, }); - if ( - localVersion && - remoteVersion && - compareVersions(localVersion, remoteVersion) === -1 - ) { + const hasNewerRemote = + localVersion && remoteVersion + ? compareVersions(localVersion.version, remoteVersion.version) === -1 + : localManifestJson.version !== primaryManifest.version; + if (hasNewerRemote) { + const releaseNotesUrl = `${parsed.webUrl}/releases/tag/${primaryManifest.version}`; const releaseFiles = await getRelease(); if (releaseFiles === null) return false; if (seeIfUpdatedOnly) { const msg = `Update available for ${primaryManifest.id}: ${localManifestJson.version} → ${primaryManifest.version}. `; await this.plugin.log(msg, true); - toastMessage(this.plugin, msg, 30); + toastMessage(this.plugin, msg, 30, () => { + window.open(releaseNotesUrl); + }); return false; } @@ -642,9 +616,11 @@ export default class BetaPlugins { const reloaded = await this.reloadPlugin(primaryManifest.id); const msg = reloaded ? `${primaryManifest.id}\nUpdated: ${localManifestJson.version} → ${primaryManifest.version}. ` - : `${primaryManifest.id}\nUpdated files to ${primaryManifest.version}, but failed to re-enable automatically. Enable it manually in Community Plugins.`; + : `${primaryManifest.id}\nUpdated files to ${primaryManifest.version}, but the plugin failed to load (see the developer console). Re-enable it in Community Plugins.`; await this.plugin.log(msg, true); - toastMessage(this.plugin, msg, reloaded ? 30 : 0); + toastMessage(this.plugin, msg, reloaded ? 30 : 0, () => { + window.open(releaseNotesUrl); + }); return reloaded; } @@ -667,35 +643,36 @@ export default class BetaPlugins { } /** - * reloads a plugin + * Disables then re-enables a plugin so its new files are loaded. + * + * Obsidian's enablePlugin() resolves to false when the plugin fails to + * load (its onload throws) instead of throwing. enablePluginAndSave() then + * reports true for the same broken plugin, so its result can't prove a + * reload: it only keeps the plugin in the saved enabled list, so it is + * retried at the next start. Any failure returns false. */ async reloadPlugin(pluginName: string): Promise { // @ts-expect-error const { plugins } = this.plugin.app; + let failure: string; try { await plugins.disablePlugin(pluginName); - await plugins.enablePlugin(pluginName); - return true; + if ((await plugins.enablePlugin(pluginName)) === true) return true; + failure = "the plugin failed to load"; } catch (e) { - const errorMessage = e instanceof Error ? e.message : String(e); + failure = e instanceof Error ? e.message : String(e); console.error(`BRAT: Failed to reload plugin ${pluginName}`, e); - await this.plugin.log( - `Failed to reload ${pluginName} after update: ${errorMessage}`, - true, - ); - try { - await plugins.enablePluginAndSave(pluginName); - return true; - } catch (e2) { - const fallbackMessage = e2 instanceof Error ? e2.message : String(e2); - console.error(`BRAT: Fallback re-enable failed for ${pluginName}`, e2); - await this.plugin.log( - `Fallback re-enable also failed for ${pluginName}: ${fallbackMessage}`, - true, - ); - return false; - } } + await this.plugin.log( + `Failed to reload ${pluginName} after update: ${failure}`, + true, + ); + try { + await plugins.enablePluginAndSave(pluginName); + } catch (e2) { + console.error(`BRAT: Could not keep ${pluginName} enabled`, e2); + } + return false; } async updatePlugin( @@ -725,7 +702,7 @@ export default class BetaPlugins { onlyCheckDontUpdate = false, ): Promise { if (!(await isConnectedToInternet())) { - console.log("BRAT: No internet detected."); + console.debug("BRAT: No internet detected."); return; } let newNotice: Notice | undefined; diff --git a/src/features/communityUtils.ts b/src/features/communityUtils.ts index e57b9d6..7ad6c12 100644 --- a/src/features/communityUtils.ts +++ b/src/features/communityUtils.ts @@ -37,7 +37,7 @@ export const grabCommmunityPluginList = async ( ? null : (response.json as CommunityPlugin[]); } catch (error) { - if (debugLogging) console.log("error in grabCommmunityPluginList", error); + if (debugLogging) console.error("error in grabCommmunityPluginList", error); return null; } }; @@ -55,7 +55,7 @@ export const grabCommmunityThemesList = async ( const response: RequestUrlResponse = await requestUrl({ url: themesUrl }); return response.status === 404 ? null : (response.json as CommunityTheme[]); } catch (error) { - if (debugLogging) console.log("error in grabCommmunityThemesList", error); + if (debugLogging) console.error("error in grabCommmunityThemesList", error); return null; } }; \ No newline at end of file diff --git a/src/features/themes.ts b/src/features/themes.ts index 2adc746..dda118f 100644 --- a/src/features/themes.ts +++ b/src/features/themes.ts @@ -1,27 +1,20 @@ import { Notice, normalizePath } from "obsidian"; -import type { ThemeManifest } from "obsidian-typings"; import { parseWithProvider } from "src/providers"; +import type { ParsedRepo, PluginProvider } from "src/providers/PluginProvider"; import type BratPlugin from "../main"; import { addBetaThemeToList, + checksumForString, updateBetaThemeLastUpdateChecksum, } from "../settings"; import { isConnectedToInternet } from "../utils/internetconnection"; import { toastMessage } from "../utils/notifications"; -/** - * Utility: simple string checksum for tracking theme changes - */ -function checksum(str: string): number { - let sum = 0; - for (let i = 0; i < str.length; i++) { - sum += str.charCodeAt(i); - } - return sum; +/** Fields BRAT reads from a theme's manifest.json */ +interface ThemeManifest { + name: string; } -export const checksumForString = (str: string): string => checksum(str).toString(); - /** * Installs or updates a theme * @@ -66,7 +59,7 @@ export const themeSave = async ( return false; } - const manifestInfo = (await JSON.parse(themeManifest)) as ThemeManifest; + const manifestInfo = JSON.parse(themeManifest) as ThemeManifest; const themeTargetFolderPath = normalizePath( themesRootPath(plugin) + manifestInfo.name, ); @@ -94,7 +87,8 @@ export const themeSave = async ( if (newInstall) { addBetaThemeToList(plugin, cssGithubRepository, themeCss); msg = `${manifestInfo.name} theme installed from ${cssGithubRepository}. `; - setTimeout(() => { + window.setTimeout(() => { + // @ts-expect-error customCss is not part of the public API plugin.app.customCss.setTheme(manifestInfo.name); }, 500); } else { @@ -103,8 +97,7 @@ export const themeSave = async ( void plugin.log(msg, false); toastMessage(plugin, msg, 20, () => { - // Use the rawBaseUrl for the theme repo link - window.open(`${parsed.rawBaseUrl}/${parsed.owner}/${parsed.repo}`); + window.open(parsed.webUrl); }); return true; }; @@ -120,7 +113,7 @@ export const themesCheckAndUpdates = async ( showInfo: boolean, ): Promise => { if (!(await isConnectedToInternet())) { - console.log("BRAT: No internet detected."); + console.debug("BRAT: No internet detected."); return; } let newNotice: Notice | undefined; @@ -185,8 +178,8 @@ export const themesRootPath = (plugin: BratPlugin): string => { * Fetch and checksum a theme CSS file */ async function grabChecksumOfThemeCssFile( - provider: import("src/providers/PluginProvider").PluginProvider, - parsed: import("src/providers/PluginProvider").ParsedRepo, + provider: PluginProvider, + parsed: ParsedRepo, betaVersion: boolean, ): Promise { const fileName = betaVersion ? "theme-beta.css" : "theme.css"; diff --git a/src/main.ts b/src/main.ts index b037eeb..f9881da 100644 --- a/src/main.ts +++ b/src/main.ts @@ -16,14 +16,13 @@ import { toastMessage } from "./utils/notifications"; export default class BratPlugin extends Plugin { APP_NAME = "BRAT"; - APP_ID = "obsidian42-brat"; settings: Settings = DEFAULT_SETTINGS; betaPlugins = new BetaPlugins(this); commands: PluginCommands = new PluginCommands(this); bratApi: BratAPI = new BratAPI(this); onload() { - console.log(`loading ${this.APP_NAME}`); + console.debug(`loading ${this.APP_NAME}`); addIcons(); this.addRibbonIcon("BratIcon", "BRAT", () => { @@ -33,8 +32,12 @@ export default class BratPlugin extends Plugin { this.loadSettings() .then(async () => { // Migrate tokens to SecretStorage (Obsidian 1.11.4+) - await migrateTokensToSecretStorage(this.app, this.settings, () => - this.saveSettings(), + await migrateTokensToSecretStorage( + this.app, + this.settings, + () => this.saveSettings(), + this.manifest.dir ?? + `${this.app.vault.configDir}/plugins/${this.manifest.id}`, ); this.app.workspace.onLayoutReady(() => { @@ -74,7 +77,7 @@ export default class BratPlugin extends Plugin { } onunload(): void { - console.log(`unloading ${this.APP_NAME}`); + console.debug(`unloading ${this.APP_NAME}`); } async loadSettings(): Promise { diff --git a/src/migrations.ts b/src/migrations.ts index ec26055..e0d1735 100644 --- a/src/migrations.ts +++ b/src/migrations.ts @@ -15,12 +15,11 @@ const MIGRATION_LOG_KEY = "brat-migrations"; */ async function hasMigrationRun( app: App, + logPath: string, migrationId: string, ): Promise { try { - const logData = await app.vault.adapter.read( - `${app.vault.configDir}/plugins/obsidian42-brat/${MIGRATION_LOG_KEY}.json`, - ); + const logData = await app.vault.adapter.read(logPath); const log = JSON.parse(logData) as MigrationLog; return log.appliedMigrations.includes(migrationId); } catch { @@ -33,10 +32,10 @@ async function hasMigrationRun( */ async function markMigrationComplete( app: App, + logPath: string, migrationId: string, ): Promise { try { - const logPath = `${app.vault.configDir}/plugins/obsidian42-brat/${MIGRATION_LOG_KEY}.json`; let log: MigrationLog = { appliedMigrations: [] }; try { @@ -69,10 +68,14 @@ export async function migrateTokensToSecretStorage( app: App, settings: Settings, saveSettings: () => Promise, + pluginDir: string, ): Promise { const MIGRATION_ID = "tokens-to-secretstorage-v1"; + // Kept in this plugin's own folder: the original BRAT uses the same file + // name in its folder, and its marker must not skip this plugin's migration. + const logPath = `${pluginDir}/${MIGRATION_LOG_KEY}.json`; - if (await hasMigrationRun(app, MIGRATION_ID)) { + if (await hasMigrationRun(app, logPath, MIGRATION_ID)) { return; } @@ -106,11 +109,11 @@ export async function migrateTokensToSecretStorage( ): string => { const existing = findExistingSecret(tokenValue); if (existing) { - console.log(`BRAT: Reusing existing secret "${existing}"`); + console.debug(`BRAT: Reusing existing secret "${existing}"`); return existing; } app.secretStorage.setSecret(secretId, tokenValue); - console.log(`BRAT: Created new secret "${secretId}"`); + console.debug(`BRAT: Created new secret "${secretId}"`); return secretId; }; @@ -143,10 +146,10 @@ export async function migrateTokensToSecretStorage( if (migrated > 0) { await saveSettings(); - console.log(`BRAT: Migrated ${migrated} token(s) to SecretStorage`); + console.debug(`BRAT: Migrated ${migrated} token(s) to SecretStorage`); } - await markMigrationComplete(app, MIGRATION_ID); + await markMigrationComplete(app, logPath, MIGRATION_ID); } catch (error) { console.error("BRAT: Failed to migrate tokens to SecretStorage:", error); } diff --git a/src/providers/GitHubProvider.ts b/src/providers/GitHubProvider.ts index 65c14bd..9f8481d 100644 --- a/src/providers/GitHubProvider.ts +++ b/src/providers/GitHubProvider.ts @@ -1,14 +1,13 @@ import { requestUrl, type RequestUrlParam, type RequestUrlResponse } from "obsidian"; -import { compare as semverCompare, coerce as semverCoerce } from "semver"; import type { ParsedRepo, PluginProvider, Release, - ReleaseAsset, ReleaseVersion, TokenInfo, } from "./PluginProvider"; import { ProviderRateLimitError, ProviderResponseError } from "./ProviderErrors"; +import { pickNewestRelease, type RawRelease, toRelease } from "./releases"; /** * Normalises all keys in an object to lowercase. @@ -27,22 +26,18 @@ function normalizeHeaders( export class GitHubProvider implements PluginProvider { parseUrl(url: string): ParsedRepo { - // Strip protocol, github.com prefix, .git suffix - let clean = url.replace(/https?:\/\//i, ""); - // Handle both "user/repo" and "github.com/user/repo" forms - if (clean.toLowerCase().startsWith("github.com/")) { - clean = clean.slice("github.com/".length); - } - if (clean.toLowerCase().endsWith(".git")) { - clean = clean.slice(0, -4); - } - if (clean.endsWith("/")) { - clean = clean.slice(0, -1); - } - - const parts = clean.split("/"); + // Accepts "user/repo", "github.com/user/repo" and full URLs such as + // "https://www.github.com/user/repo.git" or ".../user/repo/releases". + const path = url + .trim() + .replace(/^https?:\/\//i, "") + .replace(/^(?:www\.)?github\.com\//i, ""); + const parts = path.split("/").filter((p) => p !== ""); const owner = parts[0] ?? ""; - const repo = parts[1] ?? ""; + let repo = parts[1] ?? ""; + if (repo.toLowerCase().endsWith(".git")) { + repo = repo.slice(0, -4); + } return { host: "api.github.com", @@ -50,14 +45,11 @@ export class GitHubProvider implements PluginProvider { repo, apiBaseUrl: "https://api.github.com", rawBaseUrl: "https://raw.githubusercontent.com", + webUrl: `https://github.com/${owner}/${repo}`, isGitHub: true, }; } - formatRepoUrl(parsed: ParsedRepo): string { - return `${parsed.owner}/${parsed.repo}`; - } - async getRepoInfo( parsed: ParsedRepo, token?: string, @@ -67,7 +59,13 @@ export class GitHubProvider implements PluginProvider { url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`, headers: token ? { Authorization: `Token ${token}` } : {}, }); - return { exists: true, isPrivate: response.json.private ?? false }; + const json = response.json as unknown; + const isPrivate = + typeof json === "object" && + json !== null && + "private" in json && + Boolean(json.private); + return { exists: true, isPrivate }; } catch (err) { if (err instanceof ProviderResponseError && err.status === 404) { return { exists: false, isPrivate: false }; @@ -85,14 +83,14 @@ export class GitHubProvider implements PluginProvider { url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases?per_page=100`, headers: token ? { Authorization: `Token ${token}` } : {}, }); - const data = response.json as Array<{ - tag_name: string; - prerelease: boolean; - }>; - return data.map((r) => ({ - version: r.tag_name, - prerelease: r.prerelease, - })); + const data = response.json as unknown; + if (!Array.isArray(data)) return null; + return (data as Array<{ tag_name: string; prerelease: boolean }>).map( + (r) => ({ + version: r.tag_name, + prerelease: r.prerelease, + }), + ); } catch (err) { if (err instanceof ProviderRateLimitError) throw err; if (err instanceof ProviderResponseError) throw err; @@ -120,34 +118,17 @@ export class GitHubProvider implements PluginProvider { } const response = await this.apiRequest({ url: apiUrl, headers }); - if (response.status === 404) return null; + const json = response.json as unknown; - const releases: Release[] = - version && version !== "latest" - ? [this.normalizeRelease(response.json)] - : (response.json as any[]).map((r) => this.normalizeRelease(r)); - - const sorted = releases.sort((a, b) => { - try { - const aVer = semverCoerce(a.tag_name, { - includePrerelease: true, - loose: true, - }); - const bVer = semverCoerce(b.tag_name, { - includePrerelease: true, - loose: true, - }); - return aVer && bVer ? semverCompare(bVer.version, aVer.version) : 0; - } catch { - return ( - new Date(b.published_at).getTime() - - new Date(a.published_at).getTime() - ); - } - }); - - return ( - sorted.filter((r) => includePrereleases || !r.prerelease)[0] ?? null + if (version && version !== "latest") { + return typeof json === "object" && json !== null + ? toRelease(json as RawRelease) + : null; + } + if (!Array.isArray(json)) return null; + return pickNewestRelease( + (json as RawRelease[]).map(toRelease), + includePrereleases, ); } catch (err) { if (err instanceof ProviderRateLimitError) throw err; @@ -288,21 +269,6 @@ export class GitHubProvider implements PluginProvider { // ---- internal helpers ---- - private normalizeRelease(raw: any): Release { - return { - url: raw.url, - tag_name: raw.tag_name, - name: raw.name ?? raw.tag_name, - published_at: raw.published_at, - prerelease: raw.prerelease ?? false, - assets: (raw.assets ?? []).map((a: any) => ({ - name: a.name, - url: a.url, - browser_download_url: a.browser_download_url, - })), - }; - } - private async apiRequest( options: RequestUrlParam, ): Promise { @@ -314,7 +280,11 @@ export class GitHubProvider implements PluginProvider { try { return await requestUrl(options); } catch (error) { - const ghError = error as any; + const ghError = error as { + status?: number; + message?: string; + headers?: Record; + }; const status = ghError.status ?? 400; const headers = normalizeHeaders(ghError.headers ?? {}); diff --git a/src/providers/GiteaProvider.ts b/src/providers/GiteaProvider.ts index fc92512..8fba527 100644 --- a/src/providers/GiteaProvider.ts +++ b/src/providers/GiteaProvider.ts @@ -1,5 +1,4 @@ import { requestUrl, type RequestUrlParam, type RequestUrlResponse } from "obsidian"; -import { compare as semverCompare, coerce as semverCoerce } from "semver"; import type { ParsedRepo, PluginProvider, @@ -8,6 +7,39 @@ import type { TokenInfo, } from "./PluginProvider"; import { ProviderRateLimitError, ProviderResponseError } from "./ProviderErrors"; +import { pickNewestRelease, type RawRelease, toRelease } from "./releases"; + +/** Repository sub-pages that can follow `owner/repo` in a pasted browser URL. */ +const REPO_ROUTE_SEGMENTS: Record = { + releases: true, + src: true, + raw: true, + tree: true, + blob: true, + commits: true, + commit: true, + tags: true, + branches: true, + issues: true, + pulls: true, + wiki: true, + actions: true, + activity: true, + settings: true, +}; + +/** + * Page size requested from the releases endpoint. Gitea caps it with + * `[api] MAX_RESPONSE_ITEMS` (50 by default); pagination follows + * `X-Total-Count`, so a lower server cap only costs extra requests. + */ +const RELEASES_PAGE_SIZE = 50; +/** Hard stop for pagination (RELEASES_PAGE_SIZE × MAX_RELEASE_PAGES releases). */ +const MAX_RELEASE_PAGES = 20; + +interface GiteaRelease extends RawRelease { + draft?: boolean; +} /** * Provider for Gitea (and Forgejo) instances. @@ -16,55 +48,58 @@ import { ProviderRateLimitError, ProviderResponseError } from "./ProviderErrors" * GET /api/v1/repos/{owner}/{repo} * GET /api/v1/repos/{owner}/{repo}/releases * GET /api/v1/repos/{owner}/{repo}/releases/tags/{tag} - * GET /api/v1/repos/{owner}/{repo}/raw/{branch}/{file} + * GET /{owner}/{repo}/raw/{branch}/{file} */ export class GiteaProvider implements PluginProvider { - /** Default branch to use when fetching raw files */ - private defaultBranch = "HEAD"; - + /** + * Parses `https://host[:port][/base]/owner/repo[.git][/releases/...]`. + * + * Path segments before `owner/repo` are kept as the instance base path, so + * Gitea served under a sub-path (e.g. `https://example.com/git/`) works. + */ parseUrl(url: string): ParsedRepo { - // Strip protocol let clean = url.trim(); if (!/^https?:\/\//i.test(clean)) { clean = `https://${clean}`; } const parsedUrl = new URL(clean); - const host = parsedUrl.hostname; - const path = parsedUrl.pathname.replace(/^\/+/, "").replace(/\/+$/, ""); - const parts = path.split("/"); + const segments = parsedUrl.pathname.split("/").filter((s) => s !== ""); + + // Cut browser sub-pages such as /releases/tag/v1.0 or /src/branch/main + const routeIdx = segments.findIndex( + (s, i) => i >= 2 && REPO_ROUTE_SEGMENTS[s.toLowerCase()] === true, + ); + const repoPath = routeIdx === -1 ? segments : segments.slice(0, routeIdx); - // Handle: host/owner/repo or host/owner/repo.git let owner = ""; let repo = ""; - let pathIdx = 0; - - // Skip leading path segments that aren't owner/repo - if (parts.length >= 2) { - owner = parts[parts.length - 2]; - repo = parts[parts.length - 1]; + let basePath = ""; + if (repoPath.length >= 2) { + owner = repoPath[repoPath.length - 2]; + repo = repoPath[repoPath.length - 1]; + basePath = repoPath + .slice(0, -2) + .map((s) => `/${s}`) + .join(""); } - - // Remove .git suffix if (repo.toLowerCase().endsWith(".git")) { repo = repo.slice(0, -4); } - const protocol = parsedUrl.protocol; + // `host` keeps the port; `hostname` would drop it. + const origin = `${parsedUrl.protocol}//${parsedUrl.host}${basePath}`; return { - host, + host: parsedUrl.host, owner, repo, - apiBaseUrl: `${protocol}//${host}/api/v1`, - rawBaseUrl: `${protocol}//${host}`, + apiBaseUrl: `${origin}/api/v1`, + rawBaseUrl: origin, + webUrl: `${origin}/${owner}/${repo}`, isGitHub: false, }; } - formatRepoUrl(parsed: ParsedRepo): string { - return `${parsed.host}/${parsed.owner}/${parsed.repo}`; - } - async getRepoInfo( parsed: ParsedRepo, token?: string, @@ -72,9 +107,15 @@ export class GiteaProvider implements PluginProvider { try { const response = await this.apiRequest({ url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`, - headers: token ? { Authorization: `token ${token}` } : {}, + headers: this.authHeaders(token), }); - return { exists: true, isPrivate: response.json.private ?? false }; + const json = response.json as unknown; + const isPrivate = + typeof json === "object" && + json !== null && + "private" in json && + Boolean(json.private); + return { exists: true, isPrivate }; } catch (err) { if (err instanceof ProviderResponseError && err.status === 404) { return { exists: false, isPrivate: false }; @@ -87,24 +128,11 @@ export class GiteaProvider implements PluginProvider { parsed: ParsedRepo, token?: string, ): Promise { - try { - const response = await this.apiRequest({ - url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases?limit=100`, - headers: token ? { Authorization: `token ${token}` } : {}, - }); - const data = response.json as Array<{ - tag_name: string; - prerelease: boolean; - }>; - return data.map((r) => ({ - version: r.tag_name, - prerelease: r.prerelease ?? false, - })); - } catch (err) { - if (err instanceof ProviderRateLimitError) throw err; - if (err instanceof ProviderResponseError) throw err; - return null; - } + const releases = await this.fetchAllReleases(parsed, token); + return releases?.map((r) => ({ + version: r.tag_name, + prerelease: r.prerelease ?? false, + })) ?? null; } async getRelease( @@ -114,47 +142,22 @@ export class GiteaProvider implements PluginProvider { token?: string, ): Promise { try { - const apiUrl = - version && version !== "latest" - ? `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases/tags/${version}` - : `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases`; - - const headers: Record = {}; - if (token) { - headers.Authorization = `token ${token}`; + if (version && version !== "latest") { + const response = await this.apiRequest({ + url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases/tags/${encodeURIComponent(version)}`, + headers: this.authHeaders(token), + }); + const json = response.json as unknown; + return typeof json === "object" && json !== null + ? toRelease(json as RawRelease) + : null; } - const response = await this.apiRequest({ url: apiUrl, headers }); - if (response.status === 404) return null; - - const releases: Release[] = - version && version !== "latest" - ? [this.normalizeRelease(response.json)] - : (response.json as any[]).map((r) => this.normalizeRelease(r)); - - const sorted = releases.sort((a, b) => { - try { - const aVer = semverCoerce(a.tag_name, { - includePrerelease: true, - loose: true, - }); - const bVer = semverCoerce(b.tag_name, { - includePrerelease: true, - loose: true, - }); - return aVer && bVer - ? semverCompare(bVer.version, aVer.version) - : 0; - } catch { - return ( - new Date(b.published_at).getTime() - - new Date(a.published_at).getTime() - ); - } - }); - - return ( - sorted.filter((r) => includePrereleases || !r.prerelease)[0] ?? null + const releases = await this.fetchAllReleases(parsed, token); + if (!releases) return null; + return pickNewestRelease( + releases.map(toRelease), + includePrereleases, ); } catch (err) { if (err instanceof ProviderRateLimitError) throw err; @@ -169,24 +172,19 @@ export class GiteaProvider implements PluginProvider { async getAsset( release: Release, fileName: string, - isPrivate: boolean, + _isPrivate: boolean, token?: string, ): Promise { const asset = release.assets.find((a) => a.name === fileName); if (!asset) return null; - const headers: Record = { - Accept: "application/octet-stream", - }; - if (token) { - headers.Authorization = `token ${token}`; - } - - // For private repos, download via the API URL (which requires auth). - // For public repos, use the browser_download_url. - const downloadUrl = isPrivate ? asset.url : asset.browser_download_url; + // Gitea attachments only expose `browser_download_url`; for private + // repos the same URL accepts the API token in the Authorization header. try { - const response = await requestUrl({ url: downloadUrl, headers }); + const response = await requestUrl({ + url: asset.browser_download_url, + headers: this.authHeaders(token), + }); return response.status === 200 ? response.text : null; } catch { return null; @@ -196,21 +194,22 @@ export class GiteaProvider implements PluginProvider { async getRawFile( parsed: ParsedRepo, filePath: string, - branch?: string, + branch = "HEAD", token?: string, ): Promise { - const ref = branch ?? this.defaultBranch; - const url = `${parsed.rawBaseUrl}/${parsed.owner}/${parsed.repo}/raw/${ref}/${filePath}`; + const url = `${parsed.rawBaseUrl}/${parsed.owner}/${parsed.repo}/raw/${branch}/${filePath}`; try { - const headers: Record = {}; - if (token) headers.Authorization = `token ${token}`; - const response = await requestUrl({ url, headers }); + const response = await requestUrl({ url, headers: this.authHeaders(token) }); return response.status === 404 ? null : response.text; } catch { return null; } } + /** + * A Gitea token is checked against the repository it will be used for: + * repo-scoped tokens may not be allowed to read `/user`. + */ async validateToken( token: string, parsed?: ParsedRepo, @@ -218,63 +217,74 @@ export class GiteaProvider implements PluginProvider { if (!token) { return { valid: false, message: "No token provided" }; } + if (!parsed?.owner || !parsed.repo) { + return { + valid: false, + message: "Enter the repository address to validate a Gitea token", + }; + } try { - // Try accessing the repo (or a probe if no repo) to validate the token - if (parsed && parsed.owner && parsed.repo) { - await this.apiRequest({ - url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`, - headers: { Authorization: `token ${token}` }, - }); - return { valid: true, message: "Token is valid" }; - } - - // Probe: Gitea doesn't have a simple "validate token" endpoint, - // but we can try fetching the authenticated user - const response = await this.apiRequest({ - url: `${parsed?.apiBaseUrl ?? "https://localhost/api/v1"}/user`, - headers: { Authorization: `token ${token}` }, + await this.apiRequest({ + url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`, + headers: this.authHeaders(token), }); - if (response.status === 200) { - return { valid: true, message: "Token is valid" }; - } - return { valid: false, message: "Token validation failed" }; + return { valid: true, message: `Token can read ${parsed.owner}/${parsed.repo}` }; } catch (err) { if (err instanceof ProviderResponseError) { if (err.status === 401 || err.status === 403) { + return { valid: false, message: `Token rejected by ${parsed.host}` }; + } + if (err.status === 404) { return { valid: false, - message: `Token rejected: ${err.statusMessage}`, + message: "Repository not found, or the token cannot access it", }; } - // A 404 means the token is valid but the endpoint doesn't exist - if (err.status === 404) { - return { valid: true, message: "Token is valid (no specific repo access checked)" }; - } return { valid: false, - message: `API error: ${err.status} ${err.statusMessage}`, + message: `API error: ${err.status} ${err.message}`, }; } - return { valid: false, message: `Token validation failed: ${err}` }; + return { valid: false, message: `Token validation failed: ${String(err)}` }; } } // ---- internal helpers ---- - private normalizeRelease(raw: any): Release { - return { - url: raw.url, - tag_name: raw.tag_name, - name: raw.name ?? raw.tag_name, - published_at: raw.published_at ?? raw.created_at, - prerelease: raw.prerelease ?? false, - assets: (raw.assets ?? []).map((a: any) => ({ - name: a.name, - url: a.url, - browser_download_url: a.browser_download_url, - })), - }; + private authHeaders(token?: string): Record { + return token ? { Authorization: `token ${token}` } : {}; + } + + /** + * Fetches every published (non-draft) release, following pagination. + * Without `limit`, Gitea returns only its default page (10 items), which can + * hide the latest stable release behind newer prereleases. + */ + private async fetchAllReleases( + parsed: ParsedRepo, + token?: string, + ): Promise { + const all: GiteaRelease[] = []; + for (let page = 1; page <= MAX_RELEASE_PAGES; page++) { + const response = await this.apiRequest({ + url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases?draft=false&limit=${RELEASES_PAGE_SIZE}&page=${page}`, + headers: this.authHeaders(token), + }); + const data = response.json as unknown; + if (!Array.isArray(data)) return page === 1 ? null : all; + all.push(...(data as GiteaRelease[])); + + const total = Number.parseInt( + lowercaseKeys(response.headers)["x-total-count"] ?? "", + 10, + ); + if (data.length === 0) break; + if (Number.isNaN(total) ? data.length < RELEASES_PAGE_SIZE : all.length >= total) + break; + } + // Older servers ignore `draft=false`; drafts are never installable. + return all.filter((r) => !r.draft); } private async apiRequest( @@ -288,22 +298,19 @@ export class GiteaProvider implements PluginProvider { try { return await requestUrl(options); } catch (error) { - const gError = error as any; + const gError = error as { + status?: number; + message?: string; + headers?: Record; + }; const status = gError.status ?? 400; - const message = gError.message ?? "API error"; + const headers = lowercaseKeys(gError.headers ?? {}); // Gitea rate limits (if configured) use X-RateLimit-* headers - const headers: Record = {}; - if (gError.headers) { - for (const [k, v] of Object.entries(gError.headers)) { - headers[k.toLowerCase()] = String(v); - } - } - - const remaining = parseInt(headers["x-ratelimit-remaining"] ?? "", 10); - if (status === 403 && !isNaN(remaining) && remaining === 0) { - const limit = parseInt(headers["x-ratelimit-limit"] ?? "0", 10); - const reset = parseInt(headers["x-ratelimit-reset"] ?? "0", 10); + const remaining = Number.parseInt(headers["x-ratelimit-remaining"] ?? "", 10); + if (status === 403 && remaining === 0) { + const limit = Number.parseInt(headers["x-ratelimit-limit"] ?? "0", 10); + const reset = Number.parseInt(headers["x-ratelimit-reset"] ?? "0", 10); throw new ProviderRateLimitError( limit, remaining, @@ -313,7 +320,19 @@ export class GiteaProvider implements PluginProvider { ); } - throw new ProviderResponseError(message, status, headers); + throw new ProviderResponseError( + gError.message ?? "API error", + status, + headers, + ); } } -} \ No newline at end of file +} + +function lowercaseKeys(headers: Record): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(headers)) { + out[k.toLowerCase()] = String(v); + } + return out; +} diff --git a/src/providers/PluginProvider.ts b/src/providers/PluginProvider.ts index d3add1f..6c266b3 100644 --- a/src/providers/PluginProvider.ts +++ b/src/providers/PluginProvider.ts @@ -32,7 +32,7 @@ export interface TokenInfo { } export interface ParsedRepo { - /** The provider instance host, e.g. "api.github.com" or "git.mydomain.com" */ + /** The provider instance host (with port, if any), e.g. "api.github.com" or "git.mydomain.com:3000" */ host: string; /** Owner (user or org) */ owner: string; @@ -42,6 +42,8 @@ export interface ParsedRepo { apiBaseUrl: string; /** The raw file base URL, e.g. "https://raw.githubusercontent.com" */ rawBaseUrl: string; + /** Browser URL of the repository, e.g. "https://github.com/owner/repo" */ + webUrl: string; /** Whether this provider is GitHub (affects rate-limit / token validation) */ isGitHub: boolean; } @@ -88,7 +90,4 @@ export interface PluginProvider { /** Validate an access token */ validateToken(token: string, parsed?: ParsedRepo): Promise; - - /** Format a repo path for display / links */ - formatRepoUrl(parsed: ParsedRepo): string; } \ No newline at end of file diff --git a/src/providers/index.ts b/src/providers/index.ts index dee09b4..5218def 100644 --- a/src/providers/index.ts +++ b/src/providers/index.ts @@ -1,41 +1,40 @@ -import type { ParsedRepo, PluginProvider } from "./PluginProvider"; -import { GitHubProvider } from "./GitHubProvider"; import { GiteaProvider } from "./GiteaProvider"; +import { GitHubProvider } from "./GitHubProvider"; +import type { ParsedRepo, PluginProvider } from "./PluginProvider"; -let githubProvider: GitHubProvider | null = null; -let giteaProvider: GiteaProvider | null = null; +const githubProvider = new GitHubProvider(); +const giteaProvider = new GiteaProvider(); -function getGitHub(): GitHubProvider { - if (!githubProvider) githubProvider = new GitHubProvider(); - return githubProvider; -} +const BARE_GITHUB_REPO = /^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/; -function getGitea(): GiteaProvider { - if (!giteaProvider) giteaProvider = new GiteaProvider(); - return giteaProvider; +/** Hostname of an address, or "" when it is not a parsable URL. */ +function hostnameOf(address: string): string { + const withProtocol = /^https?:\/\//i.test(address) ? address : `https://${address}`; + try { + return new URL(withProtocol).hostname.toLowerCase(); + } catch { + return ""; + } } /** * Determine whether a repo address is GitHub or Gitea. * * Rules: - * 1. If the address matches `user/repo` (no host) → GitHub (existing behavior) - * 2. If the address contains `github.com` → GitHub - * 3. Everything else → Gitea (arbitrary hostname) + * 1. `user/repo` (no host) → GitHub (original BRAT format) + * 2. Host `github.com` / `www.github.com` → GitHub + * 3. Any other host → Gitea / Forgejo */ export function detectProvider(address: string): PluginProvider { const trimmed = address.trim(); + if (BARE_GITHUB_REPO.test(trimmed)) return githubProvider; + const host = hostnameOf(trimmed); + if (host === "github.com" || host === "www.github.com") return githubProvider; + return giteaProvider; +} - // Bare "user/repo" format or starts with "github.com" → GitHub - if (/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(trimmed)) { - return getGitHub(); - } - if (/github\.com/i.test(trimmed)) { - return getGitHub(); - } - - // Everything else is treated as a Gitea / self-hosted forge - return getGitea(); +export function isGitHubAddress(address: string): boolean { + return detectProvider(address) === githubProvider; } /** @@ -52,15 +51,18 @@ export function parseWithProvider(address: string): { } /** - * Convenience: return the Gitea provider (for when the provider is already known). + * Canonical form stored in settings: `user/repo` for GitHub (as in original + * BRAT), the repository URL (with port and sub-path) for Gitea. + * Returns null when the address doesn't name an owner and a repository. */ -export function getGiteaProvider(): GiteaProvider { - return getGitea(); +export function normalizeRepoAddress(address: string): string | null { + const trimmed = address.trim(); + if (trimmed === "") return null; + try { + const { parsed } = parseWithProvider(trimmed); + if (!parsed.owner || !parsed.repo) return null; + return parsed.isGitHub ? `${parsed.owner}/${parsed.repo}` : parsed.webUrl; + } catch { + return null; + } } - -/** - * Convenience: return the GitHub provider. - */ -export function getGitHubProvider(): GitHubProvider { - return getGitHub(); -} \ No newline at end of file diff --git a/src/providers/releases.ts b/src/providers/releases.ts new file mode 100644 index 0000000..df894a2 --- /dev/null +++ b/src/providers/releases.ts @@ -0,0 +1,69 @@ +import { coerce as semverCoerce, compare as semverCompare } from "semver"; +import type { Release } from "./PluginProvider"; + +/** Release payload shared by the GitHub and Gitea REST APIs (fields BRAT reads). */ +export interface RawRelease { + url?: string; + tag_name: string; + name?: string | null; + published_at?: string | null; + created_at?: string; + prerelease?: boolean; + assets?: Array<{ + name: string; + /** GitHub only: authenticated API download URL */ + url?: string; + browser_download_url: string; + }>; +} + +export function toRelease(raw: RawRelease): Release { + return { + url: raw.url ?? "", + tag_name: raw.tag_name, + name: raw.name ?? raw.tag_name, + published_at: raw.published_at ?? raw.created_at ?? "", + prerelease: raw.prerelease ?? false, + assets: (raw.assets ?? []).map((a) => ({ + name: a.name, + url: a.url ?? a.browser_download_url, + browser_download_url: a.browser_download_url, + })), + }; +} + +/** + * Orders releases newest first. + * + * Tags that coerce to semver are compared as versions and rank ahead of tags + * that don't (upstream BRAT fixes #105 and #114); the rest fall back to the + * publication date. + */ +function newestFirst(a: Release, b: Release): number { + const aVersion = semverCoerce(a.tag_name, { + includePrerelease: true, + loose: true, + }); + const bVersion = semverCoerce(b.tag_name, { + includePrerelease: true, + loose: true, + }); + + if (aVersion && bVersion) return semverCompare(bVersion.version, aVersion.version); + if (aVersion && !bVersion) return -1; + if (!aVersion && bVersion) return 1; + + return new Date(b.published_at).getTime() - new Date(a.published_at).getTime(); +} + +/** Returns the newest release, skipping prereleases unless requested. */ +export function pickNewestRelease( + releases: Release[], + includePrereleases: boolean, +): Release | null { + return ( + [...releases] + .sort(newestFirst) + .find((r) => includePrereleases || !r.prerelease) ?? null + ); +} diff --git a/src/settings.ts b/src/settings.ts index 6396343..1a3f75f 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -18,13 +18,12 @@ export interface ThemeInformation { } export interface PluginVersion { - repo: string; // path to the GitHub repository + repo: string; // `user/repo` (GitHub) or repository URL (Gitea) version: "latest" | string; // version of the plugin (semver or latest) /** @deprecated Tokens are now stored in SecretStorage (Obsidian 1.11.4+) */ token?: string; // optional private API key tokenName?: string; // name of secret in SecretStorage for per-repo token isIncompatible?: boolean; // if the plugin is incompatible - giteaUrl?: string; // Gitea instance base URL (only for non-GitHub repos) } export interface Settings { @@ -68,11 +67,10 @@ export const DEFAULT_SETTINGS: Settings = { * Adds a plugin for beta testing to the data.json file of this plugin * * @param plugin - the plugin object - * @param repositoryPath - path to the GitHub repository + * @param repositoryPath - `user/repo` (GitHub) or repository URL (Gitea) * @param specifyVersion - if the plugin needs to stay at the frozen version, we need to also record the version * @param isIncompatible - if the plugin is incompatible * @param secretName - optional: name of secret in SecretStorage for this repo - * @param giteaUrl - optional: Gitea instance URL for non-GitHub repos */ export function addBetaPluginToList( plugin: BratPlugin, @@ -80,7 +78,6 @@ export function addBetaPluginToList( specifyVersion = "latest", isIncompatible = false, secretName = "", - giteaUrl = "", ): void { let save = false; if (!plugin.settings.pluginList.contains(repositoryPath)) { @@ -99,7 +96,6 @@ export function addBetaPluginToList( token: undefined, // Don't store token in settings tokenName: secretName || existingFrozenPlugin.tokenName, isIncompatible: isIncompatible || undefined, - giteaUrl: giteaUrl || existingFrozenPlugin.giteaUrl, }); save = true; } else { @@ -109,7 +105,6 @@ export function addBetaPluginToList( token: undefined, // Don't store token in settings tokenName: secretName || undefined, isIncompatible: isIncompatible || undefined, - giteaUrl: giteaUrl || undefined, }); save = true; } diff --git a/src/ui/AddNewPluginModal.ts b/src/ui/AddNewPluginModal.ts index b796433..2d2f21c 100644 --- a/src/ui/AddNewPluginModal.ts +++ b/src/ui/AddNewPluginModal.ts @@ -6,7 +6,7 @@ import { SecretComponent, Setting, } from "obsidian"; -import { parseWithProvider } from "src/providers"; +import { normalizeRepoAddress, parseWithProvider } from "src/providers"; import type { ReleaseVersion } from "src/providers/PluginProvider"; import { ProviderRateLimitError, @@ -49,9 +49,6 @@ export default class AddNewPluginModal extends Modal { addPluginButton: ButtonComponent | null = null; cancelButton: ButtonComponent | null = null; - // Gitea-specific: stored per-plugin - giteaInstanceUrl: string; - constructor( plugin: BratPlugin, betaPlugins: BetaPlugins, @@ -70,12 +67,20 @@ export default class AddNewPluginModal extends Modal { this.openSettingsTabAfterwards = openSettingsTabAfterwards; this.updateVersion = updateVersion; this.enableAfterInstall = plugin.settings.enableAfterInstall; - this.giteaInstanceUrl = ""; } async submitForm(): Promise { if (this.address === "") return; - const scrubbedAddress = this.scrubAddress(this.address); + const scrubbedAddress = normalizeRepoAddress(this.address); + if (!scrubbedAddress) { + toastMessage( + this.plugin, + "Invalid address. Expected: user/repo (GitHub) or https://host/user/repo (Gitea).", + 10, + ); + this.resetButtons(); + return; + } const existingFrozenPlugin = this.plugin.settings.pluginSubListFrozenVersion.find( @@ -204,35 +209,18 @@ export default class AddNewPluginModal extends Modal { } /** - * Clean up a user-supplied address. For GitHub, strip protocol/domain. - * For Gitea, keep the full URL. + * Clean up a user-supplied address: `user/repo` for GitHub, the repository + * URL for Gitea. Incomplete input is returned trimmed, unchanged. */ private scrubAddress(address: string): string { - const trimmed = address.trim(); - // Bare "user/repo" → GitHub - if (/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(trimmed)) { - return trimmed; - } - // GitHub URL → strip to user/repo - if (/github\.com/i.test(trimmed)) { - return trimmed.replace(/https?:\/\/github\.com\//i, "").replace(/\.git$/i, "").replace(/\/$/, ""); - } - // Gitea / other → keep full URL, strip trailing .git - return trimmed.replace(/\.git$/i, "").replace(/\/$/, ""); + return normalizeRepoAddress(address) ?? address.trim(); } /** - * Check if an address looks like a valid repository URL (any provider) + * Check if an address names an owner and a repository (any provider) */ private isValidRepository(address: string): boolean { - const clean = address.trim().replace(/\.git$/i, ""); - // GitHub format: user/repo or github.com/user/repo - const githubPattern = - /^(?:https?:\/\/github\.com\/)?([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+)$/i; - // Gitea format: hostname/owner/repo - const giteaPattern = - /^https?:\/\/[a-zA-Z0-9.-]+\/[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/i; - return githubPattern.test(clean) || giteaPattern.test(clean); + return normalizeRepoAddress(address) !== null; } onOpen(): void { @@ -545,22 +533,9 @@ export default class AddNewPluginModal extends Modal { const scrubbedAddress = this.scrubAddress(this.address); try { - // Get token value - let tokenToUse = ""; - if (this.secretName) { - const tokenValue = this.plugin.app.secretStorage.getSecret( - this.secretName, - ); - if (tokenValue) tokenToUse = tokenValue; - } else if (this.plugin.settings.globalTokenName) { - const globalToken = this.plugin.app.secretStorage.getSecret( - this.plugin.settings.globalTokenName, - ); - if (globalToken) tokenToUse = globalToken; - } - // Use provider to fetch versions const { provider, parsed } = parseWithProvider(scrubbedAddress); + const tokenToUse = this.betaPlugins.resolveToken(parsed, this.secretName); const versions = await provider.listReleases(parsed, tokenToUse); if (versions && versions.length > 0) { @@ -622,7 +597,7 @@ export default class AddNewPluginModal extends Modal { toastMessage(this.plugin, error.message, 20); } else { validationStatusEl?.setText( - `Unexpected error: ${error}. Enable debug mode for details.`, + `Unexpected error: ${String(error)}. Enable debug mode for details.`, ); validationStatusEl?.addClass("validation-status-error"); this.disableVersionAndButton(); @@ -640,7 +615,7 @@ export default class AddNewPluginModal extends Modal { // @ts-expect-error this.plugin.app.setting.open(); // @ts-expect-error - this.plugin.app.setting.openTabById(this.plugin.APP_ID); + this.plugin.app.setting.openTabById(this.plugin.manifest.id); } } } \ No newline at end of file diff --git a/src/ui/AddNewTheme.ts b/src/ui/AddNewTheme.ts index 701da0a..ce5e669 100644 --- a/src/ui/AddNewTheme.ts +++ b/src/ui/AddNewTheme.ts @@ -1,5 +1,6 @@ import { ButtonComponent, Modal, Setting } from "obsidian"; import { themeSave } from "../features/themes"; +import { normalizeRepoAddress } from "../providers"; import type BratPlugin from "../main"; import { existBetaThemeinInList } from "../settings"; import { toastMessage } from "../utils/notifications"; @@ -22,7 +23,15 @@ export default class AddNewTheme extends Modal { async submitForm(): Promise { if (this.address === "") return; - const scrubbedAddress = this.address.replace("https://github.com/", ""); + const scrubbedAddress = normalizeRepoAddress(this.address); + if (!scrubbedAddress) { + toastMessage( + this.plugin, + "Invalid address. Expected: user/repo (GitHub) or https://host/user/repo (Gitea).", + 10, + ); + return; + } if (existBetaThemeinInList(this.plugin, scrubbedAddress)) { toastMessage( this.plugin, @@ -77,7 +86,6 @@ export default class AddNewTheme extends Modal { .setCta() .onClick((e: Event) => { e.preventDefault(); - console.log("Add theme button clicked"); if (this.address !== "") void this.submitForm(); }); }); @@ -113,7 +121,7 @@ export default class AddNewTheme extends Modal { // @ts-expect-error this.plugin.app.setting.openTab(); // @ts-expect-error - this.plugin.app.setting.openTabById(this.plugin.APP_ID); + this.plugin.app.setting.openTabById(this.plugin.manifest.id); } } } diff --git a/src/ui/PluginCommands.ts b/src/ui/PluginCommands.ts index 42e1e30..2be5618 100644 --- a/src/ui/PluginCommands.ts +++ b/src/ui/PluginCommands.ts @@ -6,6 +6,7 @@ import { } from "../features/communityUtils"; import { themesCheckAndUpdates } from "../features/themes"; import type BratPlugin from "../main"; +import { parseWithProvider } from "../providers"; import { toastMessage } from "../utils/notifications"; import AddNewTheme from "./AddNewTheme"; import type { SuggesterItem } from "./GenericFuzzySuggester"; @@ -166,7 +167,7 @@ export default class PluginCommands { gfs.setSuggesterData(pluginList); gfs.display((results) => { void this.plugin.log(`${results.display} plugin disabled`, false); - if (this.plugin.settings.debuggingMode) console.log(results.info); + if (this.plugin.settings.debuggingMode) console.debug(results.info); // @ts-expect-error void this.plugin.app.plugins.disablePluginAndSave( results.info as string, @@ -202,7 +203,7 @@ export default class PluginCommands { { id: "openGitHubZRepository", icon: "BratIcon", - name: "Plugins: Open the GitHub repository for a plugin", + name: "Plugins: Open the repository for a plugin", showInRibbon: true, callback: async () => { const communityPlugins = await grabCommmunityPluginList( @@ -226,7 +227,9 @@ export default class PluginCommands { gfs.setSuggesterData(bratList); gfs.display((results) => { if (results.info) - window.open(`https://github.com/${results.info as string}`); + window.open( + parseWithProvider(results.info as string).parsed.webUrl, + ); }); } }, diff --git a/src/ui/SettingsTab.ts b/src/ui/SettingsTab.ts index 76d1668..b5201b2 100644 --- a/src/ui/SettingsTab.ts +++ b/src/ui/SettingsTab.ts @@ -5,7 +5,7 @@ import { Setting, SettingGroup, } from "obsidian"; -import { parseWithProvider } from "src/providers"; +import { isGitHubAddress } from "src/providers"; import { TokenValidator } from "src/utils/TokenValidator"; import { themeDelete } from "../features/themes"; import type BratPlugin from "../main"; @@ -169,7 +169,7 @@ export class BratSettingsTab extends PluginSettingTab { ? this.plugin.app.secretStorage.getSecret(secretName) : ""; const isSecretMissing = Boolean(secretName && !secretValue); - const isGitea = !!bp?.giteaUrl; + const isGitea = !isGitHubAddress(p); const pluginDescription = document.createDocumentFragment(); const trackedVersionText = bp?.version @@ -431,11 +431,11 @@ export class BratSettingsTab extends PluginSettingTab { tokenSetting.setName("Personal access token").setDesc( createLink({ prependText: - "Increase rate limits for GitHub, or access private repos. Create one in ", + "GitHub only: increases rate limits and gives access to private repos. Create one in ", url: "https://github.com/settings/tokens/new?scopes=public_repo", text: "your GitHub settings", appendText: - ". For Gitea, create a token in your Gitea instance settings.", + ". It is never sent to other hosts: for Gitea/Forgejo, set a token on each plugin instead.", }), ); diff --git a/src/utils/BratAPI.ts b/src/utils/BratAPI.ts index 64f0d99..a56f802 100644 --- a/src/utils/BratAPI.ts +++ b/src/utils/BratAPI.ts @@ -1,6 +1,7 @@ import { themeDelete, themeSave, themesCheckAndUpdates } from "../features/themes"; -import { detectProvider } from "../providers"; import type BratPlugin from "../main"; +import { parseWithProvider } from "../providers"; +import { checksumForString } from "../settings"; // This module is for API access for use in debugging console @@ -15,7 +16,7 @@ export default class BratAPI { logDescription: string, ...outputs: (string | number | boolean)[] ): void => { - console.log(`BRAT: ${logDescription}`, ...outputs); + console.debug(`BRAT: ${logDescription}`, ...outputs); }; themes = { @@ -42,14 +43,10 @@ export default class BratAPI { betaVersion = false, ): Promise => { try { - const provider = detectProvider(repositoryPath); - const parsed = provider.parseUrl(repositoryPath); + const { provider, parsed } = parseWithProvider(repositoryPath); const fileName = betaVersion ? "theme-beta.css" : "theme.css"; const css = await provider.getRawFile(parsed, fileName, "HEAD"); - if (!css) return "0"; - let sum = 0; - for (let i = 0; i < css.length; i++) sum += css.charCodeAt(i); - return sum.toString(); + return css ? checksumForString(css) : "0"; } catch { return "0"; } diff --git a/src/utils/logging.ts b/src/utils/logging.ts index 12aa4aa..ce179ae 100644 --- a/src/utils/logging.ts +++ b/src/utils/logging.ts @@ -1,8 +1,43 @@ -import type { TFile } from "obsidian"; -import { moment, Platform } from "obsidian"; -import { getDailyNoteSettings } from "obsidian-daily-notes-interface"; +import { moment, Platform, TFile } from "obsidian"; import type BratPlugin from "../main"; +const DEFAULT_DAILY_NOTE_FORMAT = "YYYY-MM-DD"; + +interface DailyNotesPluginLike { + instance?: { + options?: { + format?: string; + }; + }; +} + +interface PeriodicNotesPluginLike { + settings?: { + daily?: { + enabled?: boolean; + format?: string; + }; + }; +} + +/** Daily note date format, from Periodic Notes if it handles dailies, else core Daily notes. */ +function getDailyNoteFormat(plugin: BratPlugin): string { + // @ts-expect-error app.plugins is not part of the public API + const periodicNotes = plugin.app.plugins.getPlugin( + "periodic-notes", + ) as PeriodicNotesPluginLike | null; + const periodicDailySettings = periodicNotes?.settings?.daily; + if (periodicDailySettings?.enabled) { + return periodicDailySettings.format || DEFAULT_DAILY_NOTE_FORMAT; + } + + // @ts-expect-error app.internalPlugins is not part of the public API + const dailyNotes = plugin.app.internalPlugins.getPluginById( + "daily-notes", + ) as DailyNotesPluginLike | null; + return dailyNotes?.instance?.options?.format || DEFAULT_DAILY_NOTE_FORMAT; +} + /** * Logs events to a log file * @@ -16,21 +51,22 @@ export async function logger( textToLog: string, verboseLoggingOn = false, ): Promise { - if (plugin.settings.debuggingMode) console.log(`BRAT: ${textToLog}`); + if (plugin.settings.debuggingMode) console.debug(`BRAT: ${textToLog}`); if (plugin.settings.loggingEnabled) { if (!plugin.settings.loggingVerboseEnabled && verboseLoggingOn) return; const fileName = `${plugin.settings.loggingPath}.md`; - const dateOutput = `[[${moment().format(getDailyNoteSettings().format).toString()}]] ${moment().format("HH:mm")}`; + const now = moment(); + const dateOutput = `[[${now.format(getDailyNoteFormat(plugin))}]] ${now.format("HH:mm")}`; const os = Platform.isDesktop ? (window.require("os") as { hostname: () => string }) : null; const machineName = Platform.isDesktop ? os?.hostname() : "MOBILE"; const output = `${dateOutput} ${machineName} ${textToLog.replace("\n", " ")}\n`; - let file = plugin.app.vault.getAbstractFileByPath(fileName) as TFile; - if (!file) { - file = await plugin.app.vault.create(fileName, output); + const file = plugin.app.vault.getAbstractFileByPath(fileName); + if (!(file instanceof TFile)) { + await plugin.app.vault.create(fileName, output); } else { await plugin.app.vault.append(file, output); } diff --git a/src/utils/notifications.ts b/src/utils/notifications.ts index f9e24e0..0028cbc 100644 --- a/src/utils/notifications.ts +++ b/src/utils/notifications.ts @@ -26,7 +26,7 @@ export function toastMessage( timeoutInSeconds * 1000, ); if (contextMenuCallback) - newNotice.noticeEl.oncontextmenu = () => { + newNotice.messageEl.oncontextmenu = () => { contextMenuCallback(); }; } \ No newline at end of file diff --git a/styles.css b/styles.css index b9a3684..3a7a555 100644 --- a/styles.css +++ b/styles.css @@ -111,12 +111,12 @@ /* Hide filtered plugin items */ .brat-plugin-item[hidden] { - display: none !important; + display: none; } /* Hide filtered theme items */ .brat-theme-item[hidden] { - display: none !important; + display: none; } /* Filter and button layout */