Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
import type { OptionNames, UserFont, UserTheme } from "@triliumnext/commons";
import type { Request } from "../../http_interface";
import attributeService from "../../services/attributes.js";
import config from "../../services/config.js";
import { changeLanguage } from "../../services/i18n.js";
import { getLog } from "../../services/log.js";
import optionService from "../../services/options.js";
import searchService from "../../services/search/services/search.js";
import { getSql } from "../../services/sql/index.js";
import syncOptions from "../../services/sync_options.js";
import { ValidationError } from "../../errors.js";
// options allowed to be updated directly in the Options dialog
const ALLOWED_OPTIONS = new Set<OptionNames>([
"eraseEntitiesAfterTimeInSeconds",
"eraseEntitiesAfterTimeScale",
"protectedSessionTimeout",
"protectedSessionTimeoutTimeScale",
"revisionSnapshotTimeInterval",
"revisionSnapshotTimeIntervalTimeScale",
"revisionSnapshotNumberLimit",
"revisionIgnoreNamedSnapshots",
"zoomFactor",
"theme",
"codeBlockTheme",
"codeBlockThemeMatchesApp",
"codeBlockThemeLight",
"codeBlockThemeDark",
"codeBlockWordWrap",
"codeBlockTabWidth",
"codeNoteTheme",
"codeNoteThemeMatchesApp",
"codeNoteThemeLight",
"codeNoteThemeDark",
"codeNoteTabWidth",
"codeNoteIndentWithTabs",
"pdfSignatures",
"syncServerHost",
"syncServerTimeout",
"syncServerTimeoutTimeScale",
"syncProxy",
"hoistedNoteId",
"mainFontSize",
"mainFontFamily",
"treeFontSize",
"treeFontFamily",
"detailFontSize",
"detailFontFamily",
"monospaceFontSize",
"monospaceFontFamily",
"monospaceLigaturesEnabled",
"openNoteContexts",
"vimKeymapEnabled",
"codeLineWrapEnabled",
"codeLineNumbersEnabled",
"transcriptCleanupEnabled",
"transcriptionEnabled",
"transcriptionModel",
"transcriptionSpeakersEnabled",
"transcriptionKeepRecordings",
"codeNotesMimeTypes",
"codeNotesMimeTypesSortAlphabetically",
"contentManagerSortOrder",
"contentManagerViewMode",
"spellCheckEnabled",
"spellCheckLanguageCode",
"imageMaxWidthHeight",
"imageJpegQuality",
"imageResize",
"imageJpegHandling",
"imagePngHandling",
"imageConversionQuality",
"leftPaneWidth",
"leftPaneVisible",
"rightPaneWidth",
"rightPaneCollapsedItems",
"rightPaneSelectedTab",
"rightPaneNoteMapType",
"rightPaneVisible",
"presentationSidebarVisible",
"nativeTitleBarVisible",
"headingStyle",
"autoCollapseNoteTree",
"treeScrollFollowNavigation",
"treeDensity",
"autoReadonlySizeText",
"customDateTimeFormat",
"autoReadonlySizeCode",
"overrideThemeFonts",
"dailyBackupEnabled",
"weeklyBackupEnabled",
"monthlyBackupEnabled",
"customDbBackupDir",
"backupEnableCompression",
"backupEnableEncryption",
"motionEnabled",
"shadowsEnabled",
"smoothScrollEnabled",
"hardwareAccelerationEnabled",
"backdropEffectsEnabled",
"maxContentWidth",
"centerContent",
"compressImages",
"downloadImagesAutomatically",
"highlightsList",
"checkForUpdates",
"disableTray",
"closeToTray",
"launchOnStartup",
"hideOnAutoStart",
"eraseUnusedAttachmentsAfterSeconds",
"eraseUnusedAttachmentsAfterTimeScale",
"customSearchEngineName",
"customSearchEngineUrl",
"editedNotesOpenInRibbon",
"locale",
"formattingLocale",
"defaultContentLanguage",
"firstDayOfWeek",
"firstWeekOfYear",
"minDaysInFirstWeek",
"languages",
"textNoteEditorType",
"textNoteEditorMultilineToolbar",
"textNoteDoubleQuoteStyle",
"textNoteSingleQuoteStyle",
"textNotePunctuationReplacementsEnabled",
"textNoteMathReplacementsEnabled",
"textNoteSymbolReplacementsEnabled",
"textNoteCustomReplacements",
"textNoteEmojiCompletionEnabled",
"textNoteCompletionEnabled",
"textNoteSlashCommandsEnabled",
"mathFieldEnabled",
"textNoteContentHintsEnabled",
"textNoteAutoLinkPreviewsEnabled",
"textNoteStickyTableHeadersEnabled",
"textNoteHtmlSupportEnabled",
"clipboardImageEmbedEnabled",
"layoutOrientation",
"backgroundEffects",
"allowedHtmlTags",
"cleanupToolOptions",
"imageCompressionToolOptions",
"searchEnableFuzzyMatching",
"searchAutocompleteFuzzy",
"searchResultsPageSize",
"canvasThinStroke",
"redirectBareDomain",
"showLoginInShareTheme",
"splitEditorOrientation",
"seenCallToActions",
"experimentalFeatures",
"mfaMethod",
// LLM options
"aiEnabled",
"llmProviders",
"llmWebSearchProvider",
"llmPermissionMode",
"aiAssistantModel",
"mcpEnabled",
// OCR options
"ocrAutoProcessImages",
"ocrMinConfidence"
]);
// Options that contain secrets (API keys, tokens, etc.).
// These can be written by the client but are never sent back in GET responses.
const WRITE_ONLY_OPTIONS = new Set<string>([
"openaiApiKey",
"anthropicApiKey"
]);
function getOptions() {
const optionMap = optionService.getOptionMap();
const resultMap: Record<string, string> = {};
for (const optionName in optionMap) {
if (isReadable(optionName)) {
resultMap[optionName] = optionMap[optionName as OptionNames];
}
}
resultMap["isPasswordSet"] = optionMap["passwordVerificationHash"] ? "true" : "false";
// Expose boolean flags for write-only (secret) options so the client
// knows whether a value has been configured without revealing the value.
for (const secretOption of WRITE_ONLY_OPTIONS) {
resultMap[`is${secretOption.charAt(0).toUpperCase()}${secretOption.slice(1)}Set`] =
optionMap[secretOption] ? "true" : "false";
}
// Expose scripting config (read-only, from config.ini / env vars)
resultMap["backendScriptingEnabled"] = config.Security.backendScriptingEnabled ? "true" : "false";
resultMap["sqlConsoleEnabled"] = config.Security.sqlConsoleEnabled ? "true" : "false";
// Desktop LAN-access override (read-only; toggled via the Electron security bridge)
resultMap["allowLanAccess"] = config.Security.allowLanAccess ? "true" : "false";
// Expose the sync address actually in use (read-only), which config.ini / env vars can override
// so that a development copy of a live document does not push to the live sync server.
const syncServerHost = syncOptions.isSyncSetup() ? syncOptions.getSyncServerHost() : null;
resultMap["effectiveSyncServerHost"] = syncServerHost ? stripSyncCredentials(syncServerHost) : "";
resultMap["syncServerHostOverridden"] = config.Sync.syncServerHost ? "true" : "false";
// Detect if the user has any backend scripts with #run labels (backendStartup, hourly, daily).
// Filter by MIME type since #run can also appear on frontend scripts.
const hasUserBackendScripts = attributeService.getNotesWithLabel("run")
.some((note) => note.mime === "application/javascript;env=backend");
resultMap["hasUserBackendScripts"] = hasUserBackendScripts ? "true" : "false";
// if database is read-only, disable editing in UI by setting 0 here
if (config.General.readOnly) {
resultMap["autoReadonlySizeText"] = "0";
resultMap["autoReadonlySizeCode"] = "0";
resultMap["databaseReadonly"] = "true";
}
return resultMap;
}
async function updateOption(req: Request<{ name: string; value: string }>) {
const { name, value } = req.params;
if (!update(name, value)) {
throw new ValidationError("not allowed option to change");
}
if (name === "locale") {
await changeLanguage(value);
}
}
async function updateOptions(req: Request) {
// The route is registered with asyncApiRoute (no automatic transaction wrapping) because the
// synchronous sql.transactional() cannot await promises — the transaction would commit at the
// first await and changeLanguage() would run outside it. Wrap the option-setting loop manually
// so a failure mid-batch still rolls back earlier options in the same request.
getSql().transactional(() => {
for (const optionName in req.body) {
if (!update(optionName, req.body[optionName])) {
// this should be improved
// it should return 400 instead of current 500, but at least it now rollbacks transaction
throw new Error(`Option '${optionName}' is not allowed to be changed`);
}
}
});
if ("locale" in req.body) {
await changeLanguage(req.body["locale"]);
}
}
function update(name: string, value: string) {
if (!isAllowed(name)) {
return false;
}
if (name !== "openNoteContexts") {
const logValue = (WRITE_ONLY_OPTIONS as Set<string>).has(name)
? "[redacted]"
: value;
getLog().info(`Updating option '${name}' to '${logValue}'`);
}
optionService.setOption(name as OptionNames, value);
return true;
}
function getUserThemes() {
const notes = searchService.searchNotes("#appTheme", { ignoreHoistedNote: true });
const ret: UserTheme[] = [];
for (const note of notes) {
const title = note.getTitleOrProtected();
let value = note.getOwnedLabelValue("appTheme");
if (!value) {
value = title.toLowerCase().replace(/[^a-z0-9]/gi, "-");
}
ret.push({
val: value,
title,
noteId: note.noteId,
icon: note.getIcon(),
appThemeBase: (note.getLabelValue("appThemeBase") ?? undefined) as "next" | "next-light" | "next-dark" | undefined
});
}
return ret;
}
function getUserFonts() {
const notes = searchService.searchNotes("#customFont", { ignoreHoistedNote: true });
const ret: UserFont[] = [];
for (const note of notes) {
// A font whose bytes cannot be read — a protected note outside a protected session — has
// nothing to offer the picker.
if (!note.isContentAvailable()) {
continue;
}
ret.push({
noteId: note.noteId,
title: note.getTitleOrProtected(),
blobId: note.blobId ?? ""
});
}
return ret;
}
/** Check if an option can be read by the client (GET responses). */
function isReadable(name: string) {
return (ALLOWED_OPTIONS as Set<string>).has(name)
|| name.startsWith("keyboardShortcuts")
|| name.endsWith("Collapsed")
|| name.startsWith("hideArchivedNotes");
}
/** Removes any `user:password@` from a sync address, so it can be shown in the UI. */
function stripSyncCredentials(host: string) {
return host.replace(/^((?:[a-z][a-z\d+.-]*:)?\/\/)?[^/?#]*@/i, "$1");
}
/** Check if an option can be written by the client (PUT requests). */
function isAllowed(name: string) {
return isReadable(name)
|| (WRITE_ONLY_OPTIONS as Set<string>).has(name);
}
export default {
getOptions,
updateOption,
updateOptions,
getUserThemes,
getUserFonts
};