2 Commits
Author SHA1 Message Date
olivier 8c92761136 chore: bump to v1.0.3
Tatortreiniger / tatort-reinigen (release) Has been cancelled
2026-10-25 20:39:39 -04:00
olivier d3f3fe926a 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
2026-10-25 20:39:33 -04:00
23 changed files with 516 additions and 462 deletions

No files matched your search

+6 -1
View File
@@ -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` | | **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` | | **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 ## Installation
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"id": "obsidian42-brat-gitea", "id": "obsidian42-brat-gitea",
"name": "BRAT (Gitea Fork)", "name": "BRAT (Gitea Fork)",
"version": "1.0.2", "version": "1.0.3",
"minAppVersion": "1.11.4", "minAppVersion": "1.11.4",
"description": "Easily install beta plugins from GitHub AND self-hosted Gitea/Forgejo instances.", "description": "Easily install beta plugins from GitHub AND self-hosted Gitea/Forgejo instances.",
"author": "TfTHacker (Gitea fork)", "author": "TfTHacker (Gitea fork)",
+1 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "obsidian42-brat-gitea", "name": "obsidian42-brat-gitea",
"version": "1.0.2", "version": "1.0.3",
"description": "BRAT fork with Gitea support — install beta plugins from GitHub or self-hosted Gitea/Forgejo.", "description": "BRAT fork with Gitea support — install beta plugins from GitHub or self-hosted Gitea/Forgejo.",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
@@ -32,7 +32,6 @@
"typescript": "5.9.2" "typescript": "5.9.2"
}, },
"dependencies": { "dependencies": {
"obsidian-daily-notes-interface": "^0.9.4",
"semver": "^7.7.2" "semver": "^7.7.2"
} }
} }
+61 -84
View File
@@ -6,6 +6,7 @@ import {
Platform, Platform,
requireApiVersion, requireApiVersion,
} from "obsidian"; } from "obsidian";
import { compare as compareVersions, coerce as semverCoerce } from "semver";
import { confirm } from "src/ui/ConfirmModal"; import { confirm } from "src/ui/ConfirmModal";
import { import {
ProviderRateLimitError, ProviderRateLimitError,
@@ -20,9 +21,6 @@ import { isConnectedToInternet } from "../utils/internetconnection";
import { toastMessage } from "../utils/notifications"; import { toastMessage } from "../utils/notifications";
import type { ReleaseFiles } from "./BetaPluginsTypes"; import type { ReleaseFiles } from "./BetaPluginsTypes";
const compareVersions = require("semver/functions/compare");
const semverCoerce = require("semver/functions/coerce");
interface PluginManifestEx extends PluginManifest { interface PluginManifestEx extends PluginManifest {
brat: { brat: {
isIncompatible?: boolean; isIncompatible?: boolean;
@@ -57,30 +55,17 @@ export default class BetaPlugins {
} }
/** /**
* Look up the Gitea instance URL stored per-plugin in settings (if any). * Token to send for a repository: its own secret if one is set, otherwise
* For plugins added before Gitea support, this could be empty. * the global token, which is a GitHub token and is never sent to other hosts.
*/ */
private getGiteaUrlForRepo(repoPath: string): string { resolveToken(parsed: ParsedRepo, secretName = ""): string {
const entry = this.plugin.settings.pluginSubListFrozenVersion.find( const { secretStorage } = this.plugin.app;
(p) => p.repo === repoPath, if (secretName.trim() !== "") {
); return secretStorage.getSecret(secretName) ?? "";
return entry?.giteaUrl ?? "";
} }
const { globalTokenName } = this.plugin.settings;
/** if (parsed.isGitHub && globalTokenName) {
* Retrieves the token value for a given plugin. return secretStorage.getSecret(globalTokenName) ?? "";
* 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)) || "";
}
if (this.plugin.settings.globalTokenName) {
return (
(await this.plugin.app.secretStorage.getSecret(
this.plugin.settings.globalTokenName,
)) || ""
);
} }
return ""; return "";
} }
@@ -124,7 +109,6 @@ export default class BetaPlugins {
reportIssues = false, reportIssues = false,
specifyVersion = "", specifyVersion = "",
privateApiKey = "", privateApiKey = "",
giteaUrl = "",
): Promise<PluginManifest | null> { ): Promise<PluginManifest | null> {
const noticeTimeout = 15; const noticeTimeout = 15;
@@ -193,8 +177,7 @@ export default class BetaPlugins {
return null; return null;
} }
// Version mismatch handling (same as original BRAT) // Improve robustness: if semver coercion fails, compare raw versions.
try {
const expectedVersion = semverCoerce(release.tag_name, { const expectedVersion = semverCoerce(release.tag_name, {
includePrerelease: true, includePrerelease: true,
loose: true, loose: true,
@@ -203,11 +186,12 @@ export default class BetaPlugins {
includePrerelease: true, includePrerelease: true,
loose: true, loose: true,
}); });
if ( const hasVersionMismatch =
expectedVersion && expectedVersion && manifestVersion
manifestVersion && ? compareVersions(expectedVersion.version, manifestVersion.version) !== 0
compareVersions(expectedVersion, manifestVersion) !== 0 : expectedVersion !== null && manifestJson.version !== release.tag_name;
) {
if (hasVersionMismatch && expectedVersion) {
if (reportIssues) if (reportIssues)
toastMessage( toastMessage(
this.plugin, this.plugin,
@@ -216,9 +200,6 @@ export default class BetaPlugins {
); );
manifestJson.version = expectedVersion.version; manifestJson.version = expectedVersion.version;
} }
} catch {
// Ignore comparison errors
}
return manifestJson; return manifestJson;
} catch (error) { } catch (error) {
@@ -257,7 +238,7 @@ export default class BetaPlugins {
if (reportIssues) if (reportIssues)
toastMessage( toastMessage(
this.plugin, this.plugin,
`${repositoryPath}\nUnspecified error: ${error}. Enable debug for more info.`, `${repositoryPath}\nUnspecified error: ${String(error)}. Enable debug for more info.`,
noticeTimeout, noticeTimeout,
); );
return null; return null;
@@ -272,7 +253,6 @@ export default class BetaPlugins {
getManifest: boolean, getManifest: boolean,
specifyVersion = "", specifyVersion = "",
tokenValue = "", tokenValue = "",
giteaUrl = "",
): Promise<ReleaseFiles> { ): Promise<ReleaseFiles> {
const { provider, parsed } = this.resolveProvider(repositoryPath); const { provider, parsed } = this.resolveProvider(repositoryPath);
@@ -287,11 +267,12 @@ export default class BetaPlugins {
); );
if (!release) { if (!release) {
return Promise.reject("No release found"); throw new Error("No release found");
} }
const reallyGetManifestOrNot = getManifest || specifyVersion !== ""; const reallyGetManifestOrNot = getManifest || specifyVersion !== "";
console.log({ reallyGetManifestOrNot, version: release.tag_name }); if (this.plugin.settings.debuggingMode)
console.debug({ reallyGetManifestOrNot, version: release.tag_name });
return { return {
mainJs: await provider.getAsset( mainJs: await provider.getAsset(
@@ -360,7 +341,7 @@ export default class BetaPlugins {
): Promise<boolean> { ): Promise<boolean> {
try { try {
if (this.plugin.settings.debuggingMode) { if (this.plugin.settings.debuggingMode) {
console.log( console.debug(
"BRAT: addPlugin", "BRAT: addPlugin",
repositoryPath, repositoryPath,
updatePluginFiles, updatePluginFiles,
@@ -373,29 +354,18 @@ export default class BetaPlugins {
); );
} }
// Resolve provider for this repo const { parsed } = this.resolveProvider(repositoryPath);
const { provider, parsed } = this.resolveProvider(repositoryPath);
// Retrieve token // Retrieve token
let tokenValue = ""; const tokenValue = this.resolveToken(parsed, secretName);
if (secretName && secretName.trim() !== "") { if (secretName.trim() !== "" && !tokenValue) {
tokenValue =
(await this.plugin.app.secretStorage.getSecret(secretName)) || "";
if (!tokenValue) {
toastMessage( toastMessage(
this.plugin, this.plugin,
`Secret not found for token name: ${secretName}. Please add it to SecretStorage or clear the token name for this plugin.`, `Secret not found for token name: ${secretName}. Please add it to SecretStorage or clear the token name for this plugin.`,
10, 10,
); );
} }
} else if (this.plugin.settings.globalTokenName) {
tokenValue =
(await this.plugin.app.secretStorage.getSecret(
this.plugin.settings.globalTokenName,
)) || "";
}
const giteaUrl = this.getGiteaUrlForRepo(repositoryPath);
const noticeTimeout = 10; const noticeTimeout = 10;
// Attempt to get manifest (check for beta/pre-release first) // Attempt to get manifest (check for beta/pre-release first)
@@ -405,7 +375,6 @@ export default class BetaPlugins {
true, true,
specifyVersion, specifyVersion,
tokenValue, tokenValue,
giteaUrl,
); );
const usingBetaManifest: boolean = !!primaryManifest; const usingBetaManifest: boolean = !!primaryManifest;
if (!usingBetaManifest) if (!usingBetaManifest)
@@ -415,7 +384,6 @@ export default class BetaPlugins {
true, true,
specifyVersion, specifyVersion,
tokenValue, tokenValue,
giteaUrl,
); );
if (primaryManifest === null) { if (primaryManifest === null) {
@@ -473,7 +441,6 @@ export default class BetaPlugins {
usingBetaManifest, usingBetaManifest,
specifyVersion, specifyVersion,
tokenValue, tokenValue,
giteaUrl,
); );
if (usingBetaManifest || rFiles.manifest === "") if (usingBetaManifest || rFiles.manifest === "")
@@ -544,8 +511,6 @@ export default class BetaPlugins {
specifyVersion, specifyVersion,
isIncompatible, isIncompatible,
secretName, secretName,
// Store Gitea URL if this is a Gitea repo
parsed.isGitHub ? "" : parsed.rawBaseUrl,
); );
if (enableAfterInstall) { if (enableAfterInstall) {
// @ts-expect-error // @ts-expect-error
@@ -583,13 +548,19 @@ export default class BetaPlugins {
const vaultAdapter = this.plugin.app.vault.adapter; const vaultAdapter = this.plugin.app.vault.adapter;
if (!(await vaultAdapter.exists(localManifestPath))) { if (!(await vaultAdapter.exists(localManifestPath))) {
// Plugin folder is empty/missing (deleted by sync, by hand, ...). // 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 // Reinstall it. updatePlugin() hard-codes enableAfterInstall=false
// for plain updates, which here would leave the plugin installed // for plain updates, which here would leave the plugin installed
// but disabled, so use the user's setting instead. // but disabled, so use the user's setting instead.
return await this.addPlugin( return await this.addPlugin(
repositoryPath, repositoryPath,
false, false,
usingBetaManifest, false,
false, false,
specifyVersion, specifyVersion,
false, false,
@@ -618,18 +589,21 @@ export default class BetaPlugins {
includePrerelease: true, includePrerelease: true,
loose: true, loose: true,
}); });
if ( const hasNewerRemote =
localVersion && localVersion && remoteVersion
remoteVersion && ? compareVersions(localVersion.version, remoteVersion.version) === -1
compareVersions(localVersion, remoteVersion) === -1 : localManifestJson.version !== primaryManifest.version;
) { if (hasNewerRemote) {
const releaseNotesUrl = `${parsed.webUrl}/releases/tag/${primaryManifest.version}`;
const releaseFiles = await getRelease(); const releaseFiles = await getRelease();
if (releaseFiles === null) return false; if (releaseFiles === null) return false;
if (seeIfUpdatedOnly) { if (seeIfUpdatedOnly) {
const msg = `Update available for ${primaryManifest.id}: ${localManifestJson.version} → ${primaryManifest.version}. `; const msg = `Update available for ${primaryManifest.id}: ${localManifestJson.version} → ${primaryManifest.version}. `;
await this.plugin.log(msg, true); await this.plugin.log(msg, true);
toastMessage(this.plugin, msg, 30); toastMessage(this.plugin, msg, 30, () => {
window.open(releaseNotesUrl);
});
return false; return false;
} }
@@ -642,9 +616,11 @@ export default class BetaPlugins {
const reloaded = await this.reloadPlugin(primaryManifest.id); const reloaded = await this.reloadPlugin(primaryManifest.id);
const msg = reloaded const msg = reloaded
? `${primaryManifest.id}\nUpdated: ${localManifestJson.version} → ${primaryManifest.version}. ` ? `${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); 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; return reloaded;
} }
@@ -667,36 +643,37 @@ 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> { async reloadPlugin(pluginName: string): Promise<boolean> {
// @ts-expect-error // @ts-expect-error
const { plugins } = this.plugin.app; const { plugins } = this.plugin.app;
let failure: string;
try { try {
await plugins.disablePlugin(pluginName); await plugins.disablePlugin(pluginName);
await plugins.enablePlugin(pluginName); if ((await plugins.enablePlugin(pluginName)) === true) return true;
return true; failure = "the plugin failed to load";
} catch (e) { } 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); console.error(`BRAT: Failed to reload plugin ${pluginName}`, e);
}
await this.plugin.log( await this.plugin.log(
`Failed to reload ${pluginName} after update: ${errorMessage}`, `Failed to reload ${pluginName} after update: ${failure}`,
true, true,
); );
try { try {
await plugins.enablePluginAndSave(pluginName); await plugins.enablePluginAndSave(pluginName);
return true;
} catch (e2) { } catch (e2) {
const fallbackMessage = e2 instanceof Error ? e2.message : String(e2); console.error(`BRAT: Could not keep ${pluginName} enabled`, 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; return false;
} }
}
}
async updatePlugin( async updatePlugin(
repositoryPath: string, repositoryPath: string,
@@ -725,7 +702,7 @@ export default class BetaPlugins {
onlyCheckDontUpdate = false, onlyCheckDontUpdate = false,
): Promise<void> { ): Promise<void> {
if (!(await isConnectedToInternet())) { if (!(await isConnectedToInternet())) {
console.log("BRAT: No internet detected."); console.debug("BRAT: No internet detected.");
return; return;
} }
let newNotice: Notice | undefined; let newNotice: Notice | undefined;
+2 -2
View File
@@ -37,7 +37,7 @@ export const grabCommmunityPluginList = async (
? null ? null
: (response.json as CommunityPlugin[]); : (response.json as CommunityPlugin[]);
} catch (error) { } catch (error) {
if (debugLogging) console.log("error in grabCommmunityPluginList", error); if (debugLogging) console.error("error in grabCommmunityPluginList", error);
return null; return null;
} }
}; };
@@ -55,7 +55,7 @@ export const grabCommmunityThemesList = async (
const response: RequestUrlResponse = await requestUrl({ url: themesUrl }); const response: RequestUrlResponse = await requestUrl({ url: themesUrl });
return response.status === 404 ? null : (response.json as CommunityTheme[]); return response.status === 404 ? null : (response.json as CommunityTheme[]);
} catch (error) { } catch (error) {
if (debugLogging) console.log("error in grabCommmunityThemesList", error); if (debugLogging) console.error("error in grabCommmunityThemesList", error);
return null; return null;
} }
}; };
+12 -19
View File
@@ -1,26 +1,19 @@
import { Notice, normalizePath } from "obsidian"; import { Notice, normalizePath } from "obsidian";
import type { ThemeManifest } from "obsidian-typings";
import { parseWithProvider } from "src/providers"; import { parseWithProvider } from "src/providers";
import type { ParsedRepo, PluginProvider } from "src/providers/PluginProvider";
import type BratPlugin from "../main"; import type BratPlugin from "../main";
import { import {
addBetaThemeToList, addBetaThemeToList,
checksumForString,
updateBetaThemeLastUpdateChecksum, updateBetaThemeLastUpdateChecksum,
} from "../settings"; } from "../settings";
import { isConnectedToInternet } from "../utils/internetconnection"; import { isConnectedToInternet } from "../utils/internetconnection";
import { toastMessage } from "../utils/notifications"; import { toastMessage } from "../utils/notifications";
/** /** Fields BRAT reads from a theme's manifest.json */
* Utility: simple string checksum for tracking theme changes interface ThemeManifest {
*/ name: string;
function checksum(str: string): number {
let sum = 0;
for (let i = 0; i < str.length; i++) {
sum += str.charCodeAt(i);
} }
return sum;
}
export const checksumForString = (str: string): string => checksum(str).toString();
/** /**
* Installs or updates a theme * Installs or updates a theme
@@ -66,7 +59,7 @@ export const themeSave = async (
return false; return false;
} }
const manifestInfo = (await JSON.parse(themeManifest)) as ThemeManifest; const manifestInfo = JSON.parse(themeManifest) as ThemeManifest;
const themeTargetFolderPath = normalizePath( const themeTargetFolderPath = normalizePath(
themesRootPath(plugin) + manifestInfo.name, themesRootPath(plugin) + manifestInfo.name,
); );
@@ -94,7 +87,8 @@ export const themeSave = async (
if (newInstall) { if (newInstall) {
addBetaThemeToList(plugin, cssGithubRepository, themeCss); addBetaThemeToList(plugin, cssGithubRepository, themeCss);
msg = `${manifestInfo.name} theme installed from ${cssGithubRepository}. `; 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); plugin.app.customCss.setTheme(manifestInfo.name);
}, 500); }, 500);
} else { } else {
@@ -103,8 +97,7 @@ export const themeSave = async (
void plugin.log(msg, false); void plugin.log(msg, false);
toastMessage(plugin, msg, 20, () => { toastMessage(plugin, msg, 20, () => {
// Use the rawBaseUrl for the theme repo link window.open(parsed.webUrl);
window.open(`${parsed.rawBaseUrl}/${parsed.owner}/${parsed.repo}`);
}); });
return true; return true;
}; };
@@ -120,7 +113,7 @@ export const themesCheckAndUpdates = async (
showInfo: boolean, showInfo: boolean,
): Promise<void> => { ): Promise<void> => {
if (!(await isConnectedToInternet())) { if (!(await isConnectedToInternet())) {
console.log("BRAT: No internet detected."); console.debug("BRAT: No internet detected.");
return; return;
} }
let newNotice: Notice | undefined; let newNotice: Notice | undefined;
@@ -185,8 +178,8 @@ export const themesRootPath = (plugin: BratPlugin): string => {
* Fetch and checksum a theme CSS file * Fetch and checksum a theme CSS file
*/ */
async function grabChecksumOfThemeCssFile( async function grabChecksumOfThemeCssFile(
provider: import("src/providers/PluginProvider").PluginProvider, provider: PluginProvider,
parsed: import("src/providers/PluginProvider").ParsedRepo, parsed: ParsedRepo,
betaVersion: boolean, betaVersion: boolean,
): Promise<string> { ): Promise<string> {
const fileName = betaVersion ? "theme-beta.css" : "theme.css"; const fileName = betaVersion ? "theme-beta.css" : "theme.css";
+8 -5
View File
@@ -16,14 +16,13 @@ import { toastMessage } from "./utils/notifications";
export default class BratPlugin extends Plugin { export default class BratPlugin extends Plugin {
APP_NAME = "BRAT"; APP_NAME = "BRAT";
APP_ID = "obsidian42-brat";
settings: Settings = DEFAULT_SETTINGS; settings: Settings = DEFAULT_SETTINGS;
betaPlugins = new BetaPlugins(this); betaPlugins = new BetaPlugins(this);
commands: PluginCommands = new PluginCommands(this); commands: PluginCommands = new PluginCommands(this);
bratApi: BratAPI = new BratAPI(this); bratApi: BratAPI = new BratAPI(this);
onload() { onload() {
console.log(`loading ${this.APP_NAME}`); console.debug(`loading ${this.APP_NAME}`);
addIcons(); addIcons();
this.addRibbonIcon("BratIcon", "BRAT", () => { this.addRibbonIcon("BratIcon", "BRAT", () => {
@@ -33,8 +32,12 @@ export default class BratPlugin extends Plugin {
this.loadSettings() this.loadSettings()
.then(async () => { .then(async () => {
// Migrate tokens to SecretStorage (Obsidian 1.11.4+) // Migrate tokens to SecretStorage (Obsidian 1.11.4+)
await migrateTokensToSecretStorage(this.app, this.settings, () => await migrateTokensToSecretStorage(
this.saveSettings(), this.app,
this.settings,
() => this.saveSettings(),
this.manifest.dir ??
`${this.app.vault.configDir}/plugins/${this.manifest.id}`,
); );
this.app.workspace.onLayoutReady(() => { this.app.workspace.onLayoutReady(() => {
@@ -74,7 +77,7 @@ export default class BratPlugin extends Plugin {
} }
onunload(): void { onunload(): void {
console.log(`unloading ${this.APP_NAME}`); console.debug(`unloading ${this.APP_NAME}`);
} }
async loadSettings(): Promise<void> { async loadSettings(): Promise<void> {
+12 -9
View File
@@ -15,12 +15,11 @@ const MIGRATION_LOG_KEY = "brat-migrations";
*/ */
async function hasMigrationRun( async function hasMigrationRun(
app: App, app: App,
logPath: string,
migrationId: string, migrationId: string,
): Promise<boolean> { ): Promise<boolean> {
try { try {
const logData = await app.vault.adapter.read( const logData = await app.vault.adapter.read(logPath);
`${app.vault.configDir}/plugins/obsidian42-brat/${MIGRATION_LOG_KEY}.json`,
);
const log = JSON.parse(logData) as MigrationLog; const log = JSON.parse(logData) as MigrationLog;
return log.appliedMigrations.includes(migrationId); return log.appliedMigrations.includes(migrationId);
} catch { } catch {
@@ -33,10 +32,10 @@ async function hasMigrationRun(
*/ */
async function markMigrationComplete( async function markMigrationComplete(
app: App, app: App,
logPath: string,
migrationId: string, migrationId: string,
): Promise<void> { ): Promise<void> {
try { try {
const logPath = `${app.vault.configDir}/plugins/obsidian42-brat/${MIGRATION_LOG_KEY}.json`;
let log: MigrationLog = { appliedMigrations: [] }; let log: MigrationLog = { appliedMigrations: [] };
try { try {
@@ -69,10 +68,14 @@ export async function migrateTokensToSecretStorage(
app: App, app: App,
settings: Settings, settings: Settings,
saveSettings: () => Promise<void>, saveSettings: () => Promise<void>,
pluginDir: string,
): Promise<void> { ): Promise<void> {
const MIGRATION_ID = "tokens-to-secretstorage-v1"; 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; return;
} }
@@ -106,11 +109,11 @@ export async function migrateTokensToSecretStorage(
): string => { ): string => {
const existing = findExistingSecret(tokenValue); const existing = findExistingSecret(tokenValue);
if (existing) { if (existing) {
console.log(`BRAT: Reusing existing secret "${existing}"`); console.debug(`BRAT: Reusing existing secret "${existing}"`);
return existing; return existing;
} }
app.secretStorage.setSecret(secretId, tokenValue); app.secretStorage.setSecret(secretId, tokenValue);
console.log(`BRAT: Created new secret "${secretId}"`); console.debug(`BRAT: Created new secret "${secretId}"`);
return secretId; return secretId;
}; };
@@ -143,10 +146,10 @@ export async function migrateTokensToSecretStorage(
if (migrated > 0) { if (migrated > 0) {
await saveSettings(); 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) { } catch (error) {
console.error("BRAT: Failed to migrate tokens to SecretStorage:", error); console.error("BRAT: Failed to migrate tokens to SecretStorage:", error);
} }
+40 -70
View File
@@ -1,14 +1,13 @@
import { requestUrl, type RequestUrlParam, type RequestUrlResponse } from "obsidian"; import { requestUrl, type RequestUrlParam, type RequestUrlResponse } from "obsidian";
import { compare as semverCompare, coerce as semverCoerce } from "semver";
import type { import type {
ParsedRepo, ParsedRepo,
PluginProvider, PluginProvider,
Release, Release,
ReleaseAsset,
ReleaseVersion, ReleaseVersion,
TokenInfo, TokenInfo,
} from "./PluginProvider"; } from "./PluginProvider";
import { ProviderRateLimitError, ProviderResponseError } from "./ProviderErrors"; import { ProviderRateLimitError, ProviderResponseError } from "./ProviderErrors";
import { pickNewestRelease, type RawRelease, toRelease } from "./releases";
/** /**
* Normalises all keys in an object to lowercase. * Normalises all keys in an object to lowercase.
@@ -27,22 +26,18 @@ function normalizeHeaders(
export class GitHubProvider implements PluginProvider { export class GitHubProvider implements PluginProvider {
parseUrl(url: string): ParsedRepo { parseUrl(url: string): ParsedRepo {
// Strip protocol, github.com prefix, .git suffix // Accepts "user/repo", "github.com/user/repo" and full URLs such as
let clean = url.replace(/https?:\/\//i, ""); // "https://www.github.com/user/repo.git" or ".../user/repo/releases".
// Handle both "user/repo" and "github.com/user/repo" forms const path = url
if (clean.toLowerCase().startsWith("github.com/")) { .trim()
clean = clean.slice("github.com/".length); .replace(/^https?:\/\//i, "")
} .replace(/^(?:www\.)?github\.com\//i, "");
if (clean.toLowerCase().endsWith(".git")) { const parts = path.split("/").filter((p) => p !== "");
clean = clean.slice(0, -4);
}
if (clean.endsWith("/")) {
clean = clean.slice(0, -1);
}
const parts = clean.split("/");
const owner = parts[0] ?? ""; const owner = parts[0] ?? "";
const repo = parts[1] ?? ""; let repo = parts[1] ?? "";
if (repo.toLowerCase().endsWith(".git")) {
repo = repo.slice(0, -4);
}
return { return {
host: "api.github.com", host: "api.github.com",
@@ -50,14 +45,11 @@ export class GitHubProvider implements PluginProvider {
repo, repo,
apiBaseUrl: "https://api.github.com", apiBaseUrl: "https://api.github.com",
rawBaseUrl: "https://raw.githubusercontent.com", rawBaseUrl: "https://raw.githubusercontent.com",
webUrl: `https://github.com/${owner}/${repo}`,
isGitHub: true, isGitHub: true,
}; };
} }
formatRepoUrl(parsed: ParsedRepo): string {
return `${parsed.owner}/${parsed.repo}`;
}
async getRepoInfo( async getRepoInfo(
parsed: ParsedRepo, parsed: ParsedRepo,
token?: string, token?: string,
@@ -67,7 +59,13 @@ export class GitHubProvider implements PluginProvider {
url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`, url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`,
headers: token ? { Authorization: `Token ${token}` } : {}, 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) { } catch (err) {
if (err instanceof ProviderResponseError && err.status === 404) { if (err instanceof ProviderResponseError && err.status === 404) {
return { exists: false, isPrivate: false }; 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`, url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases?per_page=100`,
headers: token ? { Authorization: `Token ${token}` } : {}, headers: token ? { Authorization: `Token ${token}` } : {},
}); });
const data = response.json as Array<{ const data = response.json as unknown;
tag_name: string; if (!Array.isArray(data)) return null;
prerelease: boolean; return (data as Array<{ tag_name: string; prerelease: boolean }>).map(
}>; (r) => ({
return data.map((r) => ({
version: r.tag_name, version: r.tag_name,
prerelease: r.prerelease, prerelease: r.prerelease,
})); }),
);
} catch (err) { } catch (err) {
if (err instanceof ProviderRateLimitError) throw err; if (err instanceof ProviderRateLimitError) throw err;
if (err instanceof ProviderResponseError) 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 }); const response = await this.apiRequest({ url: apiUrl, headers });
if (response.status === 404) return null; const json = response.json as unknown;
const releases: Release[] = if (version && version !== "latest") {
version && version !== "latest" return typeof json === "object" && json !== null
? [this.normalizeRelease(response.json)] ? toRelease(json as RawRelease)
: (response.json as any[]).map((r) => this.normalizeRelease(r)); : null;
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()
);
} }
}); if (!Array.isArray(json)) return null;
return pickNewestRelease(
return ( (json as RawRelease[]).map(toRelease),
sorted.filter((r) => includePrereleases || !r.prerelease)[0] ?? null includePrereleases,
); );
} catch (err) { } catch (err) {
if (err instanceof ProviderRateLimitError) throw err; if (err instanceof ProviderRateLimitError) throw err;
@@ -288,21 +269,6 @@ export class GitHubProvider implements PluginProvider {
// ---- internal helpers ---- // ---- 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( private async apiRequest(
options: RequestUrlParam, options: RequestUrlParam,
): Promise<RequestUrlResponse> { ): Promise<RequestUrlResponse> {
@@ -314,7 +280,11 @@ export class GitHubProvider implements PluginProvider {
try { try {
return await requestUrl(options); return await requestUrl(options);
} catch (error) { } catch (error) {
const ghError = error as any; const ghError = error as {
status?: number;
message?: string;
headers?: Record<string, string>;
};
const status = ghError.status ?? 400; const status = ghError.status ?? 400;
const headers = normalizeHeaders(ghError.headers ?? {}); const headers = normalizeHeaders(ghError.headers ?? {});
+171 -152
View File
@@ -1,5 +1,4 @@
import { requestUrl, type RequestUrlParam, type RequestUrlResponse } from "obsidian"; import { requestUrl, type RequestUrlParam, type RequestUrlResponse } from "obsidian";
import { compare as semverCompare, coerce as semverCoerce } from "semver";
import type { import type {
ParsedRepo, ParsedRepo,
PluginProvider, PluginProvider,
@@ -8,6 +7,39 @@ import type {
TokenInfo, TokenInfo,
} from "./PluginProvider"; } from "./PluginProvider";
import { ProviderRateLimitError, ProviderResponseError } from "./ProviderErrors"; 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<string, true> = {
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. * 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}
* GET /api/v1/repos/{owner}/{repo}/releases * GET /api/v1/repos/{owner}/{repo}/releases
* GET /api/v1/repos/{owner}/{repo}/releases/tags/{tag} * 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 { 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 { parseUrl(url: string): ParsedRepo {
// Strip protocol
let clean = url.trim(); let clean = url.trim();
if (!/^https?:\/\//i.test(clean)) { if (!/^https?:\/\//i.test(clean)) {
clean = `https://${clean}`; clean = `https://${clean}`;
} }
const parsedUrl = new URL(clean); const parsedUrl = new URL(clean);
const host = parsedUrl.hostname; const segments = parsedUrl.pathname.split("/").filter((s) => s !== "");
const path = parsedUrl.pathname.replace(/^\/+/, "").replace(/\/+$/, "");
const parts = path.split("/"); // 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 owner = "";
let repo = ""; let repo = "";
let pathIdx = 0; let basePath = "";
if (repoPath.length >= 2) {
// Skip leading path segments that aren't owner/repo owner = repoPath[repoPath.length - 2];
if (parts.length >= 2) { repo = repoPath[repoPath.length - 1];
owner = parts[parts.length - 2]; basePath = repoPath
repo = parts[parts.length - 1]; .slice(0, -2)
.map((s) => `/${s}`)
.join("");
} }
// Remove .git suffix
if (repo.toLowerCase().endsWith(".git")) { if (repo.toLowerCase().endsWith(".git")) {
repo = repo.slice(0, -4); 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 { return {
host, host: parsedUrl.host,
owner, owner,
repo, repo,
apiBaseUrl: `${protocol}//${host}/api/v1`, apiBaseUrl: `${origin}/api/v1`,
rawBaseUrl: `${protocol}//${host}`, rawBaseUrl: origin,
webUrl: `${origin}/${owner}/${repo}`,
isGitHub: false, isGitHub: false,
}; };
} }
formatRepoUrl(parsed: ParsedRepo): string {
return `${parsed.host}/${parsed.owner}/${parsed.repo}`;
}
async getRepoInfo( async getRepoInfo(
parsed: ParsedRepo, parsed: ParsedRepo,
token?: string, token?: string,
@@ -72,9 +107,15 @@ export class GiteaProvider implements PluginProvider {
try { try {
const response = await this.apiRequest({ const response = await this.apiRequest({
url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`, 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) { } catch (err) {
if (err instanceof ProviderResponseError && err.status === 404) { if (err instanceof ProviderResponseError && err.status === 404) {
return { exists: false, isPrivate: false }; return { exists: false, isPrivate: false };
@@ -87,24 +128,11 @@ export class GiteaProvider implements PluginProvider {
parsed: ParsedRepo, parsed: ParsedRepo,
token?: string, token?: string,
): Promise<ReleaseVersion[] | null> { ): Promise<ReleaseVersion[] | null> {
try { const releases = await this.fetchAllReleases(parsed, token);
const response = await this.apiRequest({ return releases?.map((r) => ({
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, version: r.tag_name,
prerelease: r.prerelease ?? false, prerelease: r.prerelease ?? false,
})); })) ?? null;
} catch (err) {
if (err instanceof ProviderRateLimitError) throw err;
if (err instanceof ProviderResponseError) throw err;
return null;
}
} }
async getRelease( async getRelease(
@@ -114,47 +142,22 @@ export class GiteaProvider implements PluginProvider {
token?: string, token?: string,
): Promise<Release | null> { ): Promise<Release | null> {
try { try {
const apiUrl = if (version && version !== "latest") {
version && version !== "latest" const response = await this.apiRequest({
? `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases/tags/${version}` url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases/tags/${encodeURIComponent(version)}`,
: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}/releases`; headers: this.authHeaders(token),
});
const headers: Record<string, string> = {}; const json = response.json as unknown;
if (token) { return typeof json === "object" && json !== null
headers.Authorization = `token ${token}`; ? toRelease(json as RawRelease)
: null;
} }
const response = await this.apiRequest({ url: apiUrl, headers }); const releases = await this.fetchAllReleases(parsed, token);
if (response.status === 404) return null; if (!releases) return null;
return pickNewestRelease(
const releases: Release[] = releases.map(toRelease),
version && version !== "latest" includePrereleases,
? [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
); );
} catch (err) { } catch (err) {
if (err instanceof ProviderRateLimitError) throw err; if (err instanceof ProviderRateLimitError) throw err;
@@ -169,24 +172,19 @@ export class GiteaProvider implements PluginProvider {
async getAsset( async getAsset(
release: Release, release: Release,
fileName: string, fileName: string,
isPrivate: boolean, _isPrivate: boolean,
token?: string, token?: string,
): Promise<string | null> { ): Promise<string | null> {
const asset = release.assets.find((a) => a.name === fileName); const asset = release.assets.find((a) => a.name === fileName);
if (!asset) return null; if (!asset) return null;
const headers: Record<string, string> = { // Gitea attachments only expose `browser_download_url`; for private
Accept: "application/octet-stream", // repos the same URL accepts the API token in the Authorization header.
};
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;
try { 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; return response.status === 200 ? response.text : null;
} catch { } catch {
return null; return null;
@@ -196,21 +194,22 @@ export class GiteaProvider implements PluginProvider {
async getRawFile( async getRawFile(
parsed: ParsedRepo, parsed: ParsedRepo,
filePath: string, filePath: string,
branch?: string, branch = "HEAD",
token?: string, token?: string,
): Promise<string | null> { ): Promise<string | null> {
const ref = branch ?? this.defaultBranch; const url = `${parsed.rawBaseUrl}/${parsed.owner}/${parsed.repo}/raw/${branch}/${filePath}`;
const url = `${parsed.rawBaseUrl}/${parsed.owner}/${parsed.repo}/raw/${ref}/${filePath}`;
try { try {
const headers: Record<string, string> = {}; const response = await requestUrl({ url, headers: this.authHeaders(token) });
if (token) headers.Authorization = `token ${token}`;
const response = await requestUrl({ url, headers });
return response.status === 404 ? null : response.text; return response.status === 404 ? null : response.text;
} catch { } catch {
return null; 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( async validateToken(
token: string, token: string,
parsed?: ParsedRepo, parsed?: ParsedRepo,
@@ -218,63 +217,74 @@ export class GiteaProvider implements PluginProvider {
if (!token) { if (!token) {
return { valid: false, message: "No token provided" }; 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 {
// Try accessing the repo (or a probe if no repo) to validate the token
if (parsed && parsed.owner && parsed.repo) {
await this.apiRequest({ await this.apiRequest({
url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`, url: `${parsed.apiBaseUrl}/repos/${parsed.owner}/${parsed.repo}`,
headers: { Authorization: `token ${token}` }, headers: this.authHeaders(token),
}); });
return { valid: true, message: "Token is valid" }; return { valid: true, message: `Token can read ${parsed.owner}/${parsed.repo}` };
}
// 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}` },
});
if (response.status === 200) {
return { valid: true, message: "Token is valid" };
}
return { valid: false, message: "Token validation failed" };
} catch (err) { } catch (err) {
if (err instanceof ProviderResponseError) { if (err instanceof ProviderResponseError) {
if (err.status === 401 || err.status === 403) { if (err.status === 401 || err.status === 403) {
return { return { valid: false, message: `Token rejected by ${parsed.host}` };
valid: false,
message: `Token rejected: ${err.statusMessage}`,
};
} }
// A 404 means the token is valid but the endpoint doesn't exist
if (err.status === 404) { if (err.status === 404) {
return { valid: true, message: "Token is valid (no specific repo access checked)" }; return {
valid: false,
message: "Repository not found, or the token cannot access it",
};
} }
return { return {
valid: false, 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 ---- // ---- internal helpers ----
private normalizeRelease(raw: any): Release { private authHeaders(token?: string): Record<string, string> {
return { return token ? { Authorization: `token ${token}` } : {};
url: raw.url, }
tag_name: raw.tag_name,
name: raw.name ?? raw.tag_name, /**
published_at: raw.published_at ?? raw.created_at, * Fetches every published (non-draft) release, following pagination.
prerelease: raw.prerelease ?? false, * Without `limit`, Gitea returns only its default page (10 items), which can
assets: (raw.assets ?? []).map((a: any) => ({ * hide the latest stable release behind newer prereleases.
name: a.name, */
url: a.url, private async fetchAllReleases(
browser_download_url: a.browser_download_url, parsed: ParsedRepo,
})), token?: string,
}; ): Promise<GiteaRelease[] | null> {
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( private async apiRequest(
@@ -288,22 +298,19 @@ export class GiteaProvider implements PluginProvider {
try { try {
return await requestUrl(options); return await requestUrl(options);
} catch (error) { } catch (error) {
const gError = error as any; const gError = error as {
status?: number;
message?: string;
headers?: Record<string, string>;
};
const status = gError.status ?? 400; 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 // Gitea rate limits (if configured) use X-RateLimit-* headers
const headers: Record<string, string> = {}; const remaining = Number.parseInt(headers["x-ratelimit-remaining"] ?? "", 10);
if (gError.headers) { if (status === 403 && remaining === 0) {
for (const [k, v] of Object.entries(gError.headers)) { const limit = Number.parseInt(headers["x-ratelimit-limit"] ?? "0", 10);
headers[k.toLowerCase()] = String(v); const reset = Number.parseInt(headers["x-ratelimit-reset"] ?? "0", 10);
}
}
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);
throw new ProviderRateLimitError( throw new ProviderRateLimitError(
limit, limit,
remaining, 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,
);
} }
} }
} }
function lowercaseKeys(headers: Record<string, string>): Record<string, string> {
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(headers)) {
out[k.toLowerCase()] = String(v);
}
return out;
}
+3 -4
View File
@@ -32,7 +32,7 @@ export interface TokenInfo {
} }
export interface ParsedRepo { 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; host: string;
/** Owner (user or org) */ /** Owner (user or org) */
owner: string; owner: string;
@@ -42,6 +42,8 @@ export interface ParsedRepo {
apiBaseUrl: string; apiBaseUrl: string;
/** The raw file base URL, e.g. "https://raw.githubusercontent.com" */ /** The raw file base URL, e.g. "https://raw.githubusercontent.com" */
rawBaseUrl: string; 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) */ /** Whether this provider is GitHub (affects rate-limit / token validation) */
isGitHub: boolean; isGitHub: boolean;
} }
@@ -88,7 +90,4 @@ export interface PluginProvider {
/** Validate an access token */ /** Validate an access token */
validateToken(token: string, parsed?: ParsedRepo): Promise<TokenInfo>; validateToken(token: string, parsed?: ParsedRepo): Promise<TokenInfo>;
/** Format a repo path for display / links */
formatRepoUrl(parsed: ParsedRepo): string;
} }
+34 -32
View File
@@ -1,41 +1,40 @@
import type { ParsedRepo, PluginProvider } from "./PluginProvider";
import { GitHubProvider } from "./GitHubProvider";
import { GiteaProvider } from "./GiteaProvider"; import { GiteaProvider } from "./GiteaProvider";
import { GitHubProvider } from "./GitHubProvider";
import type { ParsedRepo, PluginProvider } from "./PluginProvider";
let githubProvider: GitHubProvider | null = null; const githubProvider = new GitHubProvider();
let giteaProvider: GiteaProvider | null = null; const giteaProvider = new GiteaProvider();
function getGitHub(): GitHubProvider { const BARE_GITHUB_REPO = /^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/;
if (!githubProvider) githubProvider = new GitHubProvider();
return githubProvider; /** 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 "";
} }
function getGitea(): GiteaProvider {
if (!giteaProvider) giteaProvider = new GiteaProvider();
return giteaProvider;
} }
/** /**
* Determine whether a repo address is GitHub or Gitea. * Determine whether a repo address is GitHub or Gitea.
* *
* Rules: * Rules:
* 1. If the address matches `user/repo` (no host) → GitHub (existing behavior) * 1. `user/repo` (no host) → GitHub (original BRAT format)
* 2. If the address contains `github.com` → GitHub * 2. Host `github.com` / `www.github.com` → GitHub
* 3. Everything else → Gitea (arbitrary hostname) * 3. Any other host → Gitea / Forgejo
*/ */
export function detectProvider(address: string): PluginProvider { export function detectProvider(address: string): PluginProvider {
const trimmed = address.trim(); const trimmed = address.trim();
if (BARE_GITHUB_REPO.test(trimmed)) return githubProvider;
// Bare "user/repo" format or starts with "github.com" → GitHub const host = hostnameOf(trimmed);
if (/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(trimmed)) { if (host === "github.com" || host === "www.github.com") return githubProvider;
return getGitHub(); return giteaProvider;
}
if (/github\.com/i.test(trimmed)) {
return getGitHub();
} }
// Everything else is treated as a Gitea / self-hosted forge export function isGitHubAddress(address: string): boolean {
return getGitea(); 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 { export function normalizeRepoAddress(address: string): string | null {
return getGitea(); 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();
} }
+69
View File
@@ -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
);
}
+2 -7
View File
@@ -18,13 +18,12 @@ export interface ThemeInformation {
} }
export interface PluginVersion { 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) version: "latest" | string; // version of the plugin (semver or latest)
/** @deprecated Tokens are now stored in SecretStorage (Obsidian 1.11.4+) */ /** @deprecated Tokens are now stored in SecretStorage (Obsidian 1.11.4+) */
token?: string; // optional private API key token?: string; // optional private API key
tokenName?: string; // name of secret in SecretStorage for per-repo token tokenName?: string; // name of secret in SecretStorage for per-repo token
isIncompatible?: boolean; // if the plugin is incompatible isIncompatible?: boolean; // if the plugin is incompatible
giteaUrl?: string; // Gitea instance base URL (only for non-GitHub repos)
} }
export interface Settings { 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 * Adds a plugin for beta testing to the data.json file of this plugin
* *
* @param plugin - the plugin object * @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 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 isIncompatible - if the plugin is incompatible
* @param secretName - optional: name of secret in SecretStorage for this repo * @param secretName - optional: name of secret in SecretStorage for this repo
* @param giteaUrl - optional: Gitea instance URL for non-GitHub repos
*/ */
export function addBetaPluginToList( export function addBetaPluginToList(
plugin: BratPlugin, plugin: BratPlugin,
@@ -80,7 +78,6 @@ export function addBetaPluginToList(
specifyVersion = "latest", specifyVersion = "latest",
isIncompatible = false, isIncompatible = false,
secretName = "", secretName = "",
giteaUrl = "",
): void { ): void {
let save = false; let save = false;
if (!plugin.settings.pluginList.contains(repositoryPath)) { if (!plugin.settings.pluginList.contains(repositoryPath)) {
@@ -99,7 +96,6 @@ export function addBetaPluginToList(
token: undefined, // Don't store token in settings token: undefined, // Don't store token in settings
tokenName: secretName || existingFrozenPlugin.tokenName, tokenName: secretName || existingFrozenPlugin.tokenName,
isIncompatible: isIncompatible || undefined, isIncompatible: isIncompatible || undefined,
giteaUrl: giteaUrl || existingFrozenPlugin.giteaUrl,
}); });
save = true; save = true;
} else { } else {
@@ -109,7 +105,6 @@ export function addBetaPluginToList(
token: undefined, // Don't store token in settings token: undefined, // Don't store token in settings
tokenName: secretName || undefined, tokenName: secretName || undefined,
isIncompatible: isIncompatible || undefined, isIncompatible: isIncompatible || undefined,
giteaUrl: giteaUrl || undefined,
}); });
save = true; save = true;
} }
+19 -44
View File
@@ -6,7 +6,7 @@ import {
SecretComponent, SecretComponent,
Setting, Setting,
} from "obsidian"; } from "obsidian";
import { parseWithProvider } from "src/providers"; import { normalizeRepoAddress, parseWithProvider } from "src/providers";
import type { ReleaseVersion } from "src/providers/PluginProvider"; import type { ReleaseVersion } from "src/providers/PluginProvider";
import { import {
ProviderRateLimitError, ProviderRateLimitError,
@@ -49,9 +49,6 @@ export default class AddNewPluginModal extends Modal {
addPluginButton: ButtonComponent | null = null; addPluginButton: ButtonComponent | null = null;
cancelButton: ButtonComponent | null = null; cancelButton: ButtonComponent | null = null;
// Gitea-specific: stored per-plugin
giteaInstanceUrl: string;
constructor( constructor(
plugin: BratPlugin, plugin: BratPlugin,
betaPlugins: BetaPlugins, betaPlugins: BetaPlugins,
@@ -70,12 +67,20 @@ export default class AddNewPluginModal extends Modal {
this.openSettingsTabAfterwards = openSettingsTabAfterwards; this.openSettingsTabAfterwards = openSettingsTabAfterwards;
this.updateVersion = updateVersion; this.updateVersion = updateVersion;
this.enableAfterInstall = plugin.settings.enableAfterInstall; this.enableAfterInstall = plugin.settings.enableAfterInstall;
this.giteaInstanceUrl = "";
} }
async submitForm(): Promise<void> { async submitForm(): Promise<void> {
if (this.address === "") return; 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 = const existingFrozenPlugin =
this.plugin.settings.pluginSubListFrozenVersion.find( 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. * Clean up a user-supplied address: `user/repo` for GitHub, the repository
* For Gitea, keep the full URL. * URL for Gitea. Incomplete input is returned trimmed, unchanged.
*/ */
private scrubAddress(address: string): string { private scrubAddress(address: string): string {
const trimmed = address.trim(); return normalizeRepoAddress(address) ?? 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(/\/$/, "");
} }
/** /**
* 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 { private isValidRepository(address: string): boolean {
const clean = address.trim().replace(/\.git$/i, ""); return normalizeRepoAddress(address) !== null;
// 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);
} }
onOpen(): void { onOpen(): void {
@@ -545,22 +533,9 @@ export default class AddNewPluginModal extends Modal {
const scrubbedAddress = this.scrubAddress(this.address); const scrubbedAddress = this.scrubAddress(this.address);
try { 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 // Use provider to fetch versions
const { provider, parsed } = parseWithProvider(scrubbedAddress); const { provider, parsed } = parseWithProvider(scrubbedAddress);
const tokenToUse = this.betaPlugins.resolveToken(parsed, this.secretName);
const versions = await provider.listReleases(parsed, tokenToUse); const versions = await provider.listReleases(parsed, tokenToUse);
if (versions && versions.length > 0) { if (versions && versions.length > 0) {
@@ -622,7 +597,7 @@ export default class AddNewPluginModal extends Modal {
toastMessage(this.plugin, error.message, 20); toastMessage(this.plugin, error.message, 20);
} else { } else {
validationStatusEl?.setText( validationStatusEl?.setText(
`Unexpected error: ${error}. Enable debug mode for details.`, `Unexpected error: ${String(error)}. Enable debug mode for details.`,
); );
validationStatusEl?.addClass("validation-status-error"); validationStatusEl?.addClass("validation-status-error");
this.disableVersionAndButton(); this.disableVersionAndButton();
@@ -640,7 +615,7 @@ export default class AddNewPluginModal extends Modal {
// @ts-expect-error // @ts-expect-error
this.plugin.app.setting.open(); this.plugin.app.setting.open();
// @ts-expect-error // @ts-expect-error
this.plugin.app.setting.openTabById(this.plugin.APP_ID); this.plugin.app.setting.openTabById(this.plugin.manifest.id);
} }
} }
} }
+11 -3
View File
@@ -1,5 +1,6 @@
import { ButtonComponent, Modal, Setting } from "obsidian"; import { ButtonComponent, Modal, Setting } from "obsidian";
import { themeSave } from "../features/themes"; import { themeSave } from "../features/themes";
import { normalizeRepoAddress } from "../providers";
import type BratPlugin from "../main"; import type BratPlugin from "../main";
import { existBetaThemeinInList } from "../settings"; import { existBetaThemeinInList } from "../settings";
import { toastMessage } from "../utils/notifications"; import { toastMessage } from "../utils/notifications";
@@ -22,7 +23,15 @@ export default class AddNewTheme extends Modal {
async submitForm(): Promise<void> { async submitForm(): Promise<void> {
if (this.address === "") return; 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)) { if (existBetaThemeinInList(this.plugin, scrubbedAddress)) {
toastMessage( toastMessage(
this.plugin, this.plugin,
@@ -77,7 +86,6 @@ export default class AddNewTheme extends Modal {
.setCta() .setCta()
.onClick((e: Event) => { .onClick((e: Event) => {
e.preventDefault(); e.preventDefault();
console.log("Add theme button clicked");
if (this.address !== "") void this.submitForm(); if (this.address !== "") void this.submitForm();
}); });
}); });
@@ -113,7 +121,7 @@ export default class AddNewTheme extends Modal {
// @ts-expect-error // @ts-expect-error
this.plugin.app.setting.openTab(); this.plugin.app.setting.openTab();
// @ts-expect-error // @ts-expect-error
this.plugin.app.setting.openTabById(this.plugin.APP_ID); this.plugin.app.setting.openTabById(this.plugin.manifest.id);
} }
} }
} }
+6 -3
View File
@@ -6,6 +6,7 @@ import {
} from "../features/communityUtils"; } from "../features/communityUtils";
import { themesCheckAndUpdates } from "../features/themes"; import { themesCheckAndUpdates } from "../features/themes";
import type BratPlugin from "../main"; import type BratPlugin from "../main";
import { parseWithProvider } from "../providers";
import { toastMessage } from "../utils/notifications"; import { toastMessage } from "../utils/notifications";
import AddNewTheme from "./AddNewTheme"; import AddNewTheme from "./AddNewTheme";
import type { SuggesterItem } from "./GenericFuzzySuggester"; import type { SuggesterItem } from "./GenericFuzzySuggester";
@@ -166,7 +167,7 @@ export default class PluginCommands {
gfs.setSuggesterData(pluginList); gfs.setSuggesterData(pluginList);
gfs.display((results) => { gfs.display((results) => {
void this.plugin.log(`${results.display} plugin disabled`, false); 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 // @ts-expect-error
void this.plugin.app.plugins.disablePluginAndSave( void this.plugin.app.plugins.disablePluginAndSave(
results.info as string, results.info as string,
@@ -202,7 +203,7 @@ export default class PluginCommands {
{ {
id: "openGitHubZRepository", id: "openGitHubZRepository",
icon: "BratIcon", icon: "BratIcon",
name: "Plugins: Open the GitHub repository for a plugin", name: "Plugins: Open the repository for a plugin",
showInRibbon: true, showInRibbon: true,
callback: async () => { callback: async () => {
const communityPlugins = await grabCommmunityPluginList( const communityPlugins = await grabCommmunityPluginList(
@@ -226,7 +227,9 @@ export default class PluginCommands {
gfs.setSuggesterData(bratList); gfs.setSuggesterData(bratList);
gfs.display((results) => { gfs.display((results) => {
if (results.info) if (results.info)
window.open(`https://github.com/${results.info as string}`); window.open(
parseWithProvider(results.info as string).parsed.webUrl,
);
}); });
} }
}, },
+4 -4
View File
@@ -5,7 +5,7 @@ import {
Setting, Setting,
SettingGroup, SettingGroup,
} from "obsidian"; } from "obsidian";
import { parseWithProvider } from "src/providers"; import { isGitHubAddress } from "src/providers";
import { TokenValidator } from "src/utils/TokenValidator"; import { TokenValidator } from "src/utils/TokenValidator";
import { themeDelete } from "../features/themes"; import { themeDelete } from "../features/themes";
import type BratPlugin from "../main"; import type BratPlugin from "../main";
@@ -169,7 +169,7 @@ export class BratSettingsTab extends PluginSettingTab {
? this.plugin.app.secretStorage.getSecret(secretName) ? this.plugin.app.secretStorage.getSecret(secretName)
: ""; : "";
const isSecretMissing = Boolean(secretName && !secretValue); const isSecretMissing = Boolean(secretName && !secretValue);
const isGitea = !!bp?.giteaUrl; const isGitea = !isGitHubAddress(p);
const pluginDescription = document.createDocumentFragment(); const pluginDescription = document.createDocumentFragment();
const trackedVersionText = bp?.version const trackedVersionText = bp?.version
@@ -431,11 +431,11 @@ export class BratSettingsTab extends PluginSettingTab {
tokenSetting.setName("Personal access token").setDesc( tokenSetting.setName("Personal access token").setDesc(
createLink({ createLink({
prependText: 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", url: "https://github.com/settings/tokens/new?scopes=public_repo",
text: "your GitHub settings", text: "your GitHub settings",
appendText: 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.",
}), }),
); );
+5 -8
View File
@@ -1,6 +1,7 @@
import { themeDelete, themeSave, themesCheckAndUpdates } from "../features/themes"; import { themeDelete, themeSave, themesCheckAndUpdates } from "../features/themes";
import { detectProvider } from "../providers";
import type BratPlugin from "../main"; import type BratPlugin from "../main";
import { parseWithProvider } from "../providers";
import { checksumForString } from "../settings";
// This module is for API access for use in debugging console // This module is for API access for use in debugging console
@@ -15,7 +16,7 @@ export default class BratAPI {
logDescription: string, logDescription: string,
...outputs: (string | number | boolean)[] ...outputs: (string | number | boolean)[]
): void => { ): void => {
console.log(`BRAT: ${logDescription}`, ...outputs); console.debug(`BRAT: ${logDescription}`, ...outputs);
}; };
themes = { themes = {
@@ -42,14 +43,10 @@ export default class BratAPI {
betaVersion = false, betaVersion = false,
): Promise<string> => { ): Promise<string> => {
try { try {
const provider = detectProvider(repositoryPath); const { provider, parsed } = parseWithProvider(repositoryPath);
const parsed = provider.parseUrl(repositoryPath);
const fileName = betaVersion ? "theme-beta.css" : "theme.css"; const fileName = betaVersion ? "theme-beta.css" : "theme.css";
const css = await provider.getRawFile(parsed, fileName, "HEAD"); const css = await provider.getRawFile(parsed, fileName, "HEAD");
if (!css) return "0"; return css ? checksumForString(css) : "0";
let sum = 0;
for (let i = 0; i < css.length; i++) sum += css.charCodeAt(i);
return sum.toString();
} catch { } catch {
return "0"; return "0";
} }
+44 -8
View File
@@ -1,8 +1,43 @@
import type { TFile } from "obsidian"; import { moment, Platform, TFile } from "obsidian";
import { moment, Platform } from "obsidian";
import { getDailyNoteSettings } from "obsidian-daily-notes-interface";
import type BratPlugin from "../main"; 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 * Logs events to a log file
* *
@@ -16,21 +51,22 @@ export async function logger(
textToLog: string, textToLog: string,
verboseLoggingOn = false, verboseLoggingOn = false,
): Promise<void> { ): Promise<void> {
if (plugin.settings.debuggingMode) console.log(`BRAT: ${textToLog}`); if (plugin.settings.debuggingMode) console.debug(`BRAT: ${textToLog}`);
if (plugin.settings.loggingEnabled) { if (plugin.settings.loggingEnabled) {
if (!plugin.settings.loggingVerboseEnabled && verboseLoggingOn) return; if (!plugin.settings.loggingVerboseEnabled && verboseLoggingOn) return;
const fileName = `${plugin.settings.loggingPath}.md`; 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 const os = Platform.isDesktop
? (window.require("os") as { hostname: () => string }) ? (window.require("os") as { hostname: () => string })
: null; : null;
const machineName = Platform.isDesktop ? os?.hostname() : "MOBILE"; const machineName = Platform.isDesktop ? os?.hostname() : "MOBILE";
const output = `${dateOutput} ${machineName} ${textToLog.replace("\n", " ")}\n`; const output = `${dateOutput} ${machineName} ${textToLog.replace("\n", " ")}\n`;
let file = plugin.app.vault.getAbstractFileByPath(fileName) as TFile; const file = plugin.app.vault.getAbstractFileByPath(fileName);
if (!file) { if (!(file instanceof TFile)) {
file = await plugin.app.vault.create(fileName, output); await plugin.app.vault.create(fileName, output);
} else { } else {
await plugin.app.vault.append(file, output); await plugin.app.vault.append(file, output);
} }
+1 -1
View File
@@ -26,7 +26,7 @@ export function toastMessage(
timeoutInSeconds * 1000, timeoutInSeconds * 1000,
); );
if (contextMenuCallback) if (contextMenuCallback)
newNotice.noticeEl.oncontextmenu = () => { newNotice.messageEl.oncontextmenu = () => {
contextMenuCallback(); contextMenuCallback();
}; };
} }
+2 -2
View File
@@ -111,12 +111,12 @@
/* Hide filtered plugin items */ /* Hide filtered plugin items */
.brat-plugin-item[hidden] { .brat-plugin-item[hidden] {
display: none !important; display: none;
} }
/* Hide filtered theme items */ /* Hide filtered theme items */
.brat-theme-item[hidden] { .brat-theme-item[hidden] {
display: none !important; display: none;
} }
/* Filter and button layout */ /* Filter and button layout */
+2 -1
View File
@@ -1,3 +1,4 @@
{ {
"1.0.0": "1.11.4" "1.0.0": "1.11.4",
"1.0.3": "1.11.4"
} }