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
This commit is contained in:
olivier committed 2026-10-25 20:39:33 -04:00
1 parent 91247d31e2
commit d3f3fe926a
21 files changed
+548 -495

No files matched your search

+87 -110
View File
@@ -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<string> {
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<PluginManifest | null> {
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<ReleaseFiles> {
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<boolean> {
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<boolean> {
// @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<void> {
if (!(await isConnectedToInternet())) {
console.log("BRAT: No internet detected.");
console.debug("BRAT: No internet detected.");
return;
}
let newNotice: Notice | undefined;