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
fix(notes): reject unknown note types when changing a note's type
Elian Doran869ffad5cfd9
diff --git a/apps/server/spec/etapi/patch-note.spec.ts b/apps/server/spec/etapi/patch-note.spec.tsindex 4e726916ae..0b47bacd67 100644--- a/apps/server/spec/etapi/patch-note.spec.ts+++ b/apps/server/spec/etapi/patch-note.spec.ts@@ -45,7 +45,7 @@ describe("etapi/patch-note", () => {it("patches type, mime and creation dates", async () => {const changes = {"title": "Wassup",- "type": "html",+ "type": "text","mime": "text/html","dateCreated": "2023-08-21 23:38:51.123+0200","utcDateCreated": "2023-08-21 23:38:51.123Z"@@ -80,6 +80,16 @@ describe("etapi/patch-note", () => {expect(response.body.code).toStrictEqual("PROPERTY_VALIDATION_ERROR");});+ it("refuses a type outside the note type set", async () => {+ const response = await supertest(app)+ .patch(`/etapi/notes/${createdNoteId}`)+ .auth("etapi", token, { "type": "basic"})+ .send({ type: "EVILTYPE", mime: "application/x-anything" })+ .expect(400);+ expect(response.body.code).toStrictEqual("PROPERTY_VALIDATION_ERROR");+ await expectNoteToMatch({ type: "text", mime: "text/html" });+ });+it("rejects turning a note into an image with a non-image MIME", async () => {const response = await supertest(app).patch(`/etapi/notes/${createdNoteId}`)diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex eb98be05bf..ab7c95e0af 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -21,7 +21,7 @@"_help_LLzSMXACKhUs": "<p>If you are running the Trilium server under a <a href=\"#root/_help_vcjrb3VVYPZI\">reverse proxy</a>, it's important to configure it as a trusted proxy so that the application can correctly identify the real IP address of the clients. Trilium uses that address for <a href=\"#root/_help_0hzsNCP31IAB\">brute-force protection</a>, for the failed sign-in entries in its logs and to detect whether the connection was made over HTTPS.</p><p>Without this setting, every request appears to come from the reverse proxy, so all clients share a single limit of failed sign-in attempts.</p><h2>Configuring the trusted proxy</h2><p>To trust the reverse proxy, modify <a class=\"reference-link\" href=\"#root/_help_Gzjqa934BdH4\">Configuration (config.ini or environment variables)</a> and set <code>trustedReverseProxy</code> to the address the reverse proxy connects to Trilium from:</p><pre><code class=\"language-text-x-trilium-auto\">[Network]\ntrustedReverseProxy=loopback</code></pre><p>The value is a comma-separated list of IP addresses, subnets in CIDR notation or one of the following names:</p><figure class=\"table\"><table><thead><tr><th>Name</th><th>Addresses</th></tr></thead><tbody><tr><td><code>loopback</code></td><td><code>127.0.0.1/8</code>, <code>::1/128</code></td></tr><tr><td><code>linklocal</code></td><td><code>169.254.0.0/16</code>, <code>fe80::/10</code></td></tr><tr><td><code>uniquelocal</code></td><td><code>10.0.0.0/8</code>, <code>172.16.0.0/12</code>, <code>192.168.0.0/16</code>, <code>fc00::/7</code></td></tr></tbody></table></figure><p>Trilium then reads the client's address from the <code>X-Forwarded-For</code> header, taking the right-most entry that does not belong to a trusted address. Entries a client adds to the header are to the left of the ones the proxy appends, so they are ignored.</p><p>Common setups:</p><ul><li><strong>The reverse proxy runs on the same machine</strong>: use <code>loopback</code>.</li><li><strong>Trilium runs in Docker, with the reverse proxy on the host or in another container</strong>: use the subnet of the Docker network (for example <code>172.18.0.0/16</code>), or <code>uniquelocal</code> to cover every Docker network. With the environment variable: <code>TRILIUM_NETWORK_TRUSTEDREVERSEPROXY=172.18.0.0/16</code>.</li><li><strong>The reverse proxy runs on another machine</strong>: use its IP address.</li></ul><p>Only list addresses that the reverse proxy connects from. Any client connecting from a trusted address can claim to be another client through the <code>X-Forwarded-For</code> header. This matters for broad values such as <code>uniquelocal</code>: if devices on your local network can also reach Trilium directly, use the proxy's exact address instead.</p><aside class=\"admonition warning\"><p>Avoid setting <code>trustedReverseProxy=true</code>. It makes Trilium use the left-most entry of <code>X-Forwarded-For</code>, which is the value the client sent, unless the proxy discards the incoming header. Proxies usually append to it instead (such as Nginx's <code>$proxy_add_x_forwarded_for</code>), so a client can send a different address with every request and bypass the limit on failed sign-in attempts.</p></aside><p>For more information, consult <a href=\"https://expressjs.com/en/guide/behind-proxies.html\">Express behind proxies</a>.</p>","_help_5ERVJb9s4FRD": "<p>The goal of this article is to configure Traefik proxy and HTTPS. See <a href=\"https://github.com/TriliumNext/Trilium/issues/7768#issuecomment-3539165814\">#7768</a> for reference.</p><h2>Breaking change in Traefik 3.6.4</h2><p>Traefik 3.6.4 introduced a <a href=\"https://doc.traefik.io/traefik/migrate/v3/#encoded-characters-in-request-path\">breaking change</a> regarding how percent-encoded characters are handled in URLs. Trilium puts the title of an image or attachment in its URL path, so one whose title contains <code>#</code> or <code>/</code> is requested at a path such as <code>/api/images/…/diagram%231.png</code>. Traefik rejects these paths with HTTP 400, and the image does not load. Search is not affected, because it sends its text in a query parameter.</p><p>The easiest solution is to update to Traefik 3.6.7 or later which reverts this configuration change. Alternatively, the configuration can be changed according to the section below.</p><details class=\"trilium-collapsible\"><summary>Configuration change</summary><p>To solve this, the Traefik <a href=\"https://doc.traefik.io/traefik/getting-started/configuration-overview/#the-install-configuration\"><strong>static</strong> configuration</a> must be modified in order to allow those characters:</p><pre><code class=\"language-text-x-yaml\">entryPoints:\n web:\n http:\n encodedCharacters:\n allowEncodedSlash: true\n allowEncodedHash: true</code></pre><aside class=\"admonition tip\"><p>If images still fail to load, you might need to enable more encoded character groups. For more information, see <a href=\"https://github.com/TriliumNext/Trilium/issues/7968\">the relevant GitHub issue</a>; feel free to report your findings.</p></aside></details><h3>Build the docker-compose file</h3><p>Setting up Traefik as reverse proxy requires setting the following labels:</p><pre><code class=\"language-text-x-yaml\"> labels:\n - traefik.enable=true\n - traefik.http.routers.trilium.entrypoints=https\n - traefik.http.routers.trilium.rule=Host(`trilium.mydomain.tld`)\n - traefik.http.routers.trilium.tls=true\n - traefik.http.routers.trilium.service=trilium\n - traefik.http.services.trilium.loadbalancer.server.port=8080\n # scheme must be HTTP instead of the usual HTTPS because Trilium listens on HTTP internally\n - traefik.http.services.trilium.loadbalancer.server.scheme=http\n - traefik.docker.network=proxy\n # forward HTTP to HTTPS\n - traefik.http.routers.trilium.middlewares=trilium-headers@docker\n - traefik.http.middlewares.trilium-headers.headers.customrequestheaders.X-Forwarded-Proto=https</code></pre><h3>Setup needed environment variables</h3><p>After setting up a reverse proxy, make sure to configure the <a class=\"reference-link\" href=\"#root/_help_LLzSMXACKhUs\">Trusted proxy</a>.</p><h3>Example <code>docker-compose.yaml</code></h3><pre><code class=\"language-text-x-yaml\">services:\n trilium:\n image: triliumnext/trilium\n container_name: trilium\n networks:\n - traefik-proxy\n environment:\n - TRILIUM_NETWORK_TRUSTEDREVERSEPROXY=my-traefik-host-ip # e.g., 172.18.0.0/16\n volumes:\n - /path/to/data:/home/node/trilium-data\n - /etc/timezone:/etc/timezone:ro\n - /etc/localtime:/etc/localtime:ro\n labels:\n - traefik.enable=true\n - traefik.http.routers.trilium.entrypoints=https\n - traefik.http.routers.trilium.rule=Host(`trilium.mydomain.tld`)\n - traefik.http.routers.trilium.tls=true\n - traefik.http.routers.trilium.service=trilium\n - traefik.http.services.trilium.loadbalancer.server.port=8080\n # scheme must be HTTP instead of the usual HTTPS because of how trilium works\n - traefik.http.services.trilium.loadbalancer.server.scheme=http\n - traefik.docker.network=traefik-proxy\n # Tell Trilium the original request was HTTPS\n - traefik.http.routers.trilium.middlewares=trilium-headers@docker\n - traefik.http.middlewares.trilium-headers.headers.customrequestheaders.X-Forwarded-Proto=https\n\nnetworks:\n traefik-proxy:\n external: true</code></pre>","_help_l2VkvOwUNfZj": "<p>Configuring TLS is essential for <a href=\"#root/_help_WOcw2SLH6tbX\">server installation</a> in Trilium. This guide details the steps to set up TLS within Trilium itself.</p><aside class=\"admonition tip\"><p>While Trilium supports HTTPS on its own, it's generally a good idea to use a <a href=\"#root/_help_vcjrb3VVYPZI\">reverse proxy</a> instead with TLS termination. You can follow a <a href=\"https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-20-04\">guide like this</a> for such setups.</p></aside><h2>Obtaining a TLS Certificate</h2><p>You have two options for obtaining a TLS certificate:</p><ul><li><strong>Recommended</strong>: Obtain a TLS certificate signed by a root certificate authority. For personal use, <a href=\"https://letsencrypt.org\">Let's Encrypt</a> is an excellent choice. It is free, automated, and straightforward. Certbot can facilitate automatic TLS setup.</li><li>Generate a self-signed certificate. This option is not recommended due to the additional complexity of importing the certificate into all machines connecting to the server.</li></ul><h2>Modifying <code>config.ini</code></h2><p>Once you have your certificate, modify the <code>config.ini</code> file in the <a href=\"#root/_help_tAassRL4RSQL\">data directory</a> to configure Trilium to use it:</p><pre><code class=\"language-text-x-trilium-auto\">[Network]\nport=8080\n# Set to true for TLS/SSL/HTTPS (secure), false for HTTP (insecure).\nhttps=true\n# Path to the certificate (run \"bash bin/generate-cert.sh\" to generate a self-signed certificate).\n# Relevant only if https=true\ncertPath=/[username]/.acme.sh/[hostname]/fullchain.cer\nkeyPath=/[username]/.acme.sh/[hostname]/example.com.key</code></pre><p>You can also review the <a href=\"#root/_help_Gzjqa934BdH4\">configuration</a> file to provide all <code>config.ini</code> values as environment variables instead. For example, you can configure TLS using environment variables:</p><pre><code class=\"language-text-x-trilium-auto\">export TRILIUM_NETWORK_HTTPS=true\nexport TRILIUM_NETWORK_CERTPATH=/path/to/cert.pem\nexport TRILIUM_NETWORK_KEYPATH=/path/to/key.pem</code></pre><p>The above example shows how this is set up in an environment where the certificate was generated using Let's Encrypt's ACME utility. Your paths may differ. For Docker installations, ensure these paths are within a volume or another directory accessible by the Docker container, such as <code>/home/node/trilium-data/[DIR IN DATA DIRECTORY]</code>.</p><p>After configuring <code>config.ini</code>, restart Trilium and access the hostname using \"https\".</p><h2>Self-Signed Certificate</h2><p>If you opt to use a self-signed certificate for your server instance, note that the desktop instance will not trust it by default.</p><p>To bypass this, disable certificate validation by setting the following environment variable (for Linux):</p><pre><code class=\"language-text-x-trilium-auto\">export NODE_TLS_REJECT_UNAUTHORIZED=0\ntrilium</code></pre><p>Trilium provides scripts to start in this mode, such as <code>trilium-no-cert-check.bat</code> for Windows.</p><p><strong>Warning</strong>: Disabling TLS certificate validation is insecure. Proceed only if you fully understand the implications.</p>",- "_help_0hzsNCP31IAB": "<h2>Disabling authentication</h2><p>If you are running Trilium on <code>localhost</code> only or if authentication is handled by another component, you can disable Trilium’s authentication by adding the following to <code>config.ini</code>:</p><pre><code class=\"language-text-x-trilium-auto\">[General]\nnoAuthentication=true</code></pre><p>Disabling authentication will bypass even the <a class=\"reference-link\" href=\"#root/_help_7DAiwaf8Z7Rz\">Multi-Factor Authentication</a> since v0.94.1.</p><h2>Brute-force protection</h2><p>Trilium limits each IP address to 10 failed sign-in attempts in 15 minutes. Once an address reaches the limit, Trilium rejects every further attempt from it, including correct ones, until the 15 minutes have passed. The sign-in page then shows <em>Too many login attempts</em>; other clients receive HTTP status 429.</p><p>The limit applies to every way of signing in with the password:</p><ul><li>The sign-in page.</li><li>Setting up <a class=\"reference-link\" href=\"#root/_help_cbkrhQjrkKrh\">Synchronization</a> from a desktop or mobile app.</li><li>Connecting the <a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a> or the Android sender app.</li><li>Requesting a token through <a class=\"reference-link\" href=\"#root/_help_pgxEVkzLl1OP\">ETAPI (REST API)</a>.</li></ul><p>All of these count toward the same limit, and a wrong password, a wrong one-time password and a wrong recovery code each count as one failed attempt. Successful sign-ins are not counted.</p><p>The limit is per IP address, not per account, so an attacker cannot lock you out by failing to sign in from their own address. The count is kept in memory: restarting the server clears it.</p><aside class=\"admonition important\"><p>Behind a reverse proxy, Trilium sees every request as coming from the proxy unless it is configured as a <a class=\"reference-link\" href=\"#root/_help_LLzSMXACKhUs\">Trusted proxy</a>. All clients then share a single limit, so a few wrong attempts from anyone block everyone.</p></aside><h3>Blocking repeated failures with fail2ban</h3><p>A failed attempt on the sign-in page is answered with HTTP status 401 and recorded in the <a class=\"reference-link\" href=\"#root/_help_bnyigUA2UK7s\">Backend (server) logs</a> as:</p><pre><code class=\"language-text-x-trilium-auto\">WARNING: Wrong password from 203.0.113.7, rejecting.</code></pre><p>When <a class=\"reference-link\" href=\"#root/_help_7DAiwaf8Z7Rz\">Multi-Factor Authentication</a> is enabled, a wrong one-time password or recovery code is logged as <code>Wrong totp</code> instead. Tools such as fail2ban can match either the log line or the 401 responses to <code>POST /login</code> in the reverse proxy's access log to block an address for longer than 15 minutes.</p><h2>Understanding how the session works</h2><p>Once logged into Trilium, the application will store this information about the login into a cookie on the browser, but also as a session on the server.</p><p>If “Remember me” is checked, then the login will expire in 21 days. This period can be adjusted by modifying the <code>Session.cookieMaxAge</code> value in <code>config.ini</code>. For example, to have the session expire in one day:</p><pre><code class=\"language-text-x-trilium-auto\">[Session]\ncookieMaxAge=86400</code></pre><p>When “Remember me” is unchecked, the behavior is different. At client/browser level the authentication does not have any expiration date, but it will be automatically cleared as soon as the user closes the browser. Nevertheless, the server will also dismiss this authentication in around 24 hours from the <em>last interaction with the application</em>.</p><h2>Viewing active sessions</h2><p>The login sessions are now stored in the same <a class=\"reference-link\" href=\"#root/_help_wX4HbRucYSDD\">Database</a> as the user data. In order to view which sessions are active, open the <a class=\"reference-link\" href=\"#root/_help_YKWqdJhzi2VY\">SQL Console</a> and run the following query:</p><pre><code class=\"language-text-x-trilium-auto\">SELECT * FROM sessions</code></pre><p>Expired sessions are periodically cleaned by the server, generally an hourly interval.</p><h2>See also</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_7DAiwaf8Z7Rz\">Multi-Factor Authentication</a></li><li><a class=\"reference-link\" href=\"#root/_help_LLzSMXACKhUs\">Trusted proxy</a></li></ul>",+ "_help_0hzsNCP31IAB": "<h2>Disabling authentication</h2><p>If you are running Trilium on <code>localhost</code> only or if authentication is handled by another component, you can disable Trilium’s authentication by adding the following to <code>config.ini</code>:</p><pre><code class=\"language-text-x-trilium-auto\">[General]\nnoAuthentication=true</code></pre><p>Disabling authentication will bypass even the <a class=\"reference-link\" href=\"#root/_help_7DAiwaf8Z7Rz\">Multi-Factor Authentication</a> since v0.94.1.</p><h2>Brute-force protection</h2><p>Trilium limits each IP address to 10 failed sign-in attempts in 15 minutes. Once an address reaches the limit, Trilium rejects every further attempt from it, including correct ones, until the 15 minutes have passed. The sign-in page then shows <em>Too many login attempts</em>; other clients receive HTTP status 429.</p><p>The limit applies to every way of signing in with the password:</p><ul><li>The sign-in page.</li><li>Setting up <a class=\"reference-link\" href=\"#root/_help_cbkrhQjrkKrh\">Synchronization</a> from a desktop or mobile app.</li><li>Connecting the <a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a> or the Android sender app.</li><li>Requesting a token through <a class=\"reference-link\" href=\"#root/_help_pgxEVkzLl1OP\">ETAPI (REST API)</a>.</li></ul><p>All of these count toward the same limit, and a wrong password, a wrong one-time password and a wrong recovery code each count as one failed attempt. Successful sign-ins are not counted.</p><p>The limit is per IP address, not per account, so an attacker cannot lock you out by failing to sign in from their own address. The count is kept in memory: restarting the server clears it.</p><aside class=\"admonition important\"><p>Behind a reverse proxy, Trilium sees every request as coming from the proxy unless it is configured as a <a class=\"reference-link\" href=\"#root/_help_LLzSMXACKhUs\">Trusted proxy</a>. All clients then share a single limit, so a few wrong attempts from anyone block everyone.</p></aside><h3>Blocking repeated failures with fail2ban</h3><p>A failed attempt on the sign-in page is answered with HTTP status 401 and recorded in the <a class=\"reference-link\" href=\"#root/_help_bnyigUA2UK7s\">Backend (server) logs</a> as:</p><pre><code class=\"language-text-x-trilium-auto\">WARNING: Wrong password from 203.0.113.7, rejecting.</code></pre><p>When <a class=\"reference-link\" href=\"#root/_help_7DAiwaf8Z7Rz\">Multi-Factor Authentication</a> is enabled, a wrong one-time password or recovery code is logged as <code>Wrong totp</code> instead. Tools such as fail2ban can match either the log line or the 401 responses to <code>POST /login</code> in the reverse proxy's access log to block an address for longer than 15 minutes.</p><h2>Understanding how the session works</h2><p>Once logged into Trilium, the application will store this information about the login into a cookie on the browser, but also as a session on the server.</p><p>If “Remember me” is checked, then the login will expire in 21 days. This period can be adjusted by modifying the <code>Session.cookieMaxAge</code> value in <code>config.ini</code>. For example, to have the session expire in one day:</p><pre><code class=\"language-text-x-trilium-auto\">[Session]\ncookieMaxAge=86400</code></pre><p>When “Remember me” is unchecked, the behavior is different. At client/browser level the authentication does not have any expiration date, but it will be automatically cleared as soon as the user closes the browser. Nevertheless, the server will also dismiss this authentication in around 24 hours from the <em>last interaction with the application</em>.</p><p>Changing or resetting the password logs out every session, including the one that made the change, so you have to log in again with the new password. This also applies when the password is changed on another instance and reaches the server through synchronization. If you suspect that someone has obtained your session cookie, changing the password cuts off their access.</p><h2>Viewing active sessions</h2><p>The login sessions are now stored in the same <a class=\"reference-link\" href=\"#root/_help_wX4HbRucYSDD\">Database</a> as the user data. In order to view which sessions are active, open the <a class=\"reference-link\" href=\"#root/_help_YKWqdJhzi2VY\">SQL Console</a> and run the following query:</p><pre><code class=\"language-text-x-trilium-auto\">SELECT * FROM sessions</code></pre><p>Expired sessions are periodically cleaned by the server, generally an hourly interval.</p><h2>See also</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_7DAiwaf8Z7Rz\">Multi-Factor Authentication</a></li><li><a class=\"reference-link\" href=\"#root/_help_LLzSMXACKhUs\">Trusted proxy</a></li></ul>","_help_lwAX5SvbrK2g": "<aside class=\"admonition important\"><p>If you forget your password:</p><ul><li>Protected notes are irretrievable without the password.</li><li>Unprotected notes can be recovered.</li></ul></aside><p>There are two options, both involving access to the device that is running your server.</p><h3>By disabling authentication</h3><ol><li>See <a class=\"reference-link\" href=\"#root/_help_0hzsNCP31IAB\">Authentication</a> on how to disable the authentication.</li><li>Restart the server.</li><li>Go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → Password → Reset password.</li><li>Re-enable authentication by following step (1) in reverse.</li><li>Restart the server.</li><li>Log in with the new password.</li></ol><h3>By altering the database</h3><ol><li><p>Access the <a href=\"#root/_help_wX4HbRucYSDD\">database</a> file in the <a href=\"#root/_help_tAassRL4RSQL\">data directory</a>. Open the <code>document.db</code> file with an SQLite client (e.g., <a href=\"https://sqlitebrowser.org/\">DB Browser</a>).</p></li><li><p>Execute the following queries:</p><pre><code class=\"language-text-x-trilium-auto\">UPDATE options SET value = '77/twC5O00cuQgNC63VK32qOKKYwj21ev3jZDXoytVU=' WHERE name = 'passwordVerificationSalt';\nUPDATE options SET value = '710BMasZCAgibzIc07X4P9Q4TeBd4ONnqJOho+pWcBM=' WHERE name = 'passwordDerivedKeySalt';\nUPDATE options SET value = 'Eb8af1/T57b89lCRuS97tPEl4CwxsAWAU7YNJ77oY+s=' WHERE name = 'passwordVerificationHash';\nUPDATE options SET value = 'QpC8XoiYYeqHPtHKRtbNxfTHsk+pEBqVBODYp0FkPBa22tlBBKBMigdLu5GNX8Uu' WHERE name = 'encryptedDataKey';</code></pre></li><li><p>After executing the changes, commit/write the changes. <strong>This sets the password to</strong> <code>**password**</code><strong>, allowing you to log in again.</strong></p></li><li><p>Go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Password</em> → <em>Change password</em> and replace the unsafe password.</p></li></ol><h2>Handling protected notes</h2><p>When the password is reset, the protected notes are permanently lost due to the fact that they are encrypted with your password so there is no way for Trilium to recover them.</p><p>For pre-existing protected notes (now unrecoverable), consider deleting them or exporting the unprotected notes. Then, delete <code>document.db</code> and start fresh.</p>","_help_7DAiwaf8Z7Rz": "<p>Multi-factor authentication (MFA) is a security process that requires users to provide two or more verification factors to gain access to a system, application, or account. This adds an extra layer of protection beyond just using a password.</p><p>By requiring more than one verification method, MFA helps reduce the risk of unauthorized access, even if someone has obtained your password. It’s highly recommended for securing sensitive information stored in your notes.</p><h2>Relationship to OpenID Connect (OIDC)</h2><p>Multi-factor authentication makes your Trilium login safer by requiring an additional proof of identity apart from your password. <a class=\"reference-link\" href=\"#root/_help_x1lQNKQBqLcA\">Signing in with OpenID Connect</a> is a different concept which delegates your authentication to an external provider (e.g. your Google provider, or a self-hosted one such as Authelia). These authentication providers might provide their own security features such as TOTP or passkeys.</p><h2>Time-based one-time password (TOTP)</h2><p>TOTP (Time-Based One-Time Password) is a security feature that generates a unique, temporary code on your device, like a smartphone, which changes every 30 seconds. You use this code, along with your password, to log into your account, making it much harder for anyone else to access them.</p><ol><li>Go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Password & Auth.</em></li><li>Make sure <em>Sign-in with</em> has <em>Local password</em> selected.</li><li>In the <em>Two-factor authentication</em> section, press <em>Set up.</em></li><li>Scan the QR code or manually enter the code in your authenticator app.</li><li>Enter the verification code from your authenticator app to confirm that the setup was successful and press <em>Verify & continue</em>.</li><li>Save the recovery codes, then tick the confirmation and press <em>Finish setup</em>.</li><li>Re-login will be required after TOTP setup is finished (after refreshing the page).</li></ol><h2>Signing in</h2><p>Once TOTP is enabled, the sign-in page asks for the code from your authenticator app in <em>One-time password or recovery code</em>, below the password.</p><p>Trilium accepts the code for the current 30-second period as well as the periods just before and after it, so a clock that is slightly off on either side still works. Since v0.106.0, each code is accepted only once: after a successful sign-in, that code and any older one are rejected, even while they are still valid.</p><p>A wrong one-time password counts toward the same limit of failed attempts as a wrong password. See <em>Brute-force protection</em> in <a class=\"reference-link\" href=\"#root/_help_0hzsNCP31IAB\">Authentication</a>.</p><h2>Connecting a device to the server</h2><p>Once TOTP is enabled, connecting a new desktop or mobile app to the server through <a class=\"reference-link\" href=\"#root/_help_cbkrhQjrkKrh\">Synchronization</a> also asks for the second factor. On the <em>Connect to an existing server</em> screen, enter a one-time password or a recovery code in <em>One-time password or recovery code</em>, below the server's password. Without it, the server refuses to set up the sync.</p><p>The second factor is only asked for when a device is first connected. A device that is already set up keeps syncing without it.</p><aside class=\"admonition note\"><p>Versions prior to v0.107.0 do not ask for the second factor when setting up the sync. Update the desktop and mobile apps along with the server, since older apps have no field to send it.</p></aside><h2>Obtaining an ETAPI token with a password</h2><p>Once TOTP is enabled, obtaining a token for the <a class=\"reference-link\" href=\"#root/_help_pgxEVkzLl1OP\">ETAPI (REST API)</a> through the <code>/auth/login</code> call also requires the second factor: send the one-time password or a recovery code as <code>totpToken</code>, next to <code>password</code>. Each code is accepted only once.</p><p>For scripts and tools that run unattended, create a token in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>ETAPI</em> instead. Such a token works regardless of TOTP.</p><aside class=\"admonition warning\"><p>Versions prior to v0.107.0 issue an ETAPI token for the password alone, even with TOTP enabled.</p></aside><h2>Recovery codes</h2><p>Recovery codes can be used in place of the TOTP if you lose access to your authenticator. Trilium provides 8 different recovery codes, each recovery code can be used once.</p><p>To use a recovery code, simply login with your password and use the recovery code as the security token.</p><p>The initial set of recovery codes is generated when setting up your TOTP for the first time. They can be regenerated at any time by going to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Password & Auth</em> and pressing the <em>Regenerate recovery codes</em> button. This will generate a new set of recovery codes while at the same time disabling the previous ones.</p>","_help_x1lQNKQBqLcA": "<p>OpenID is a standardized way to let you log into websites using an account from another service, like Google or Authelia, to verify your identity.</p><p>When OpenID is activated, the password-based authentication in Trilium is replaced with a button that connects using your provider. This means that the configuration of <a class=\"reference-link\" href=\"#root/_help_7DAiwaf8Z7Rz\">Multi-factor authentication with TOTP</a> no longer takes effect, since your provider has to handle any multi-factor authentication.</p><h2>Setup</h2><p>Setting up authentication with OpenID connect is a two-step process:</p><ol><li>First the Trilium server must be configured with information about your authentication provider such as the URL, client ID and secret.</li><li>Second, the user must connect from options to create a link between the account on the provider and the one Trilium has.</li></ol><h3>Configuring the authentication provider</h3><ol><li><p>First, make sure the authentication provider (e.g. Google, Authelia) is configured properly. See <a class=\"reference-link\" href=\"#root/_help_IgkTHSaFfq6A\">Setting up with various providers</a> for concrete examples.</p><ol><li>The redirect URL of Trilium is <code>https://<your-trilium-domain>/callback</code>.</li><li>You should obtain the base URL, client ID and client secret.</li></ol></li><li><p>Set the following information using <a class=\"reference-link\" href=\"#root/_help_Gzjqa934BdH4\">Configuration (config.ini or environment variables)</a>:</p><figure class=\"table\"><table><thead><tr><th>Configuration</th><th><code>config.ini</code> in <code>[MultiFactorAuthentication]</code> section</th><th>Environment variable</th><th>Description</th></tr></thead><tbody><tr><td>Base URL*</td><td><code>oauthBaseUrl</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHBASEURL</code></td><td>The URL of your Trilium instance (e.g. <code>https://example.com</code>).</td></tr><tr><td>Client ID*</td><td><code>oauthClientId</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTID</code></td><td>The client ID from your provider configuration.</td></tr><tr><td>Client Secret*</td><td><code>oauthClientSecret</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTSECRET</code></td><td>The client secret from your provider configuration.</td></tr><tr><td>Client auth method</td><td><code>oauthClientAuthMethod</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHCLIENTAUTHMETHOD</code></td><td>Token-endpoint auth method: <code>client_secret_basic</code> or <code>client_secret_post</code>. Empty auto-detects. Only needed if sign-in fails with a <code>WWW-Authenticate</code> or <code>invalid_client</code> error.</td></tr><tr><td>ID token algorithm</td><td><code>oauthIdTokenSigningAlg</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHIDTOKENSIGNINGALG</code></td><td><span style=\"color:rgb(32,32,32);\">The algorithm your provider signs ID tokens with, e.g.</span> <code>RS256</code><span style=\"color:rgb(32,32,32);\">,</span> <code>EdDSA</code><span style=\"color:rgb(32,32,32);\">,</span> <code>ES256</code><span style=\"color:rgb(32,32,32);\">. Empty auto-detects from the provider. Only needed if sign-in fails with an</span> <code>unexpected JWT alg</code> <span style=\"color:rgb(32,32,32);\">error.</span></td></tr></tbody></table></figure><p>Asterisk (*) marks a required field</p></li><li><p>The default OAuth issuer is Google. To use other services such as Authentik or Auth0, you can configure the settings via <code>oauthIssuerBaseUrl</code>, <code>oauthIssuerName</code>, and <code>oauthIssuerIcon</code> in the <code>config.ini</code> file. Alternatively, these values can be set using environment variables:</p><figure class=\"table\"><table><thead><tr><th>Configuration</th><th><code>config.ini</code> in <code>[MultiFactorAuthentication]</code> section</th><th>Environment variable</th><th>Description</th></tr></thead><tbody><tr><td>Issuer base URL</td><td><code>oauthIssuerBaseUrl</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERBASEURL</code></td><td>Either the issuer itself (<code>https://auth.example.com</code>) or a full discovery URL (<code>https://auth.example.com/.well-known/openid-configuration</code>). <br> <br>A URL containing <code>/.well-known/</code> is used as-is<span style=\"color:rgb(32,32,32);\">, which is convenient when your provider hands you a discovery URL to copy. A trailing slash may be included or omitted; Trilium matches whichever spelling the provider advertises.</span> <br> <br>Use the full form when your provider advertises an issuer that differs from the path serving its discovery document, such as Authentik in \"global\" issuer mode.</td></tr><tr><td>Issuer name</td><td><code>oauthIssuerName</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERNAME</code></td><td>The name of your authentication provider, used for reference on the login screen and in settings. Default is “Google”.</td></tr><tr><td>Issuer icon</td><td><code>oauthIssuerIcon</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHISSUERICON</code></td><td>Optionally, the URL to a logo of the provider. By default it will try to obtain the favicon from the website, so it's optional.</td></tr></tbody></table></figure><p>All the fields here are optional, since the default OAuth issuer is Google.</p></li><li><p>Optionally, tune the following advanced settings. All are optional and have sensible defaults:</p><figure class=\"table\"><table><thead><tr><th>Configuration</th><th><code>config.ini</code> in <code>[MultiFactorAuthentication]</code> section</th><th>Environment variable</th><th>Description</th></tr></thead><tbody><tr><td>HTTP timeout</td><td><code>oauthHttpTimeout</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHHTTPTIMEOUT</code></td><td>Timeout in milliseconds for the provider HTTP requests (discovery, token exchange, userinfo). Defaults to <code>30000</code> (30s). Raise this if your provider cold-starts slowly and you are occasionally asked to sign in twice. Minimum accepted value is <code>500</code>.</td></tr><tr><td>Scopes</td><td><code>oauthScope</code></td><td><code>TRILIUM_MULTIFACTORAUTHENTICATION_OAUTHSCOPE</code></td><td>Space-separated list of OIDC scopes requested at login. Defaults to <code>openid profile email</code>. <code>openid</code> is required and is prepended automatically if you omit it.</td></tr></tbody></table></figure><p>The OIDC session lifetime is automatically bound to Trilium's own session cookie lifetime (the <code>cookieMaxAge</code> setting in the <code>[Session]</code> section, 21 days by default), so a single sign-in stays valid for as long as your Trilium session does rather than expiring early on the OIDC library's shorter internal defaults.</p></li><li><p>Restart the server so that the changes are applied.</p></li></ol><aside class=\"admonition note\"><p>Legacy environment variables are also supported: <code>TRILIUM_OAUTH_BASE_URL</code>, <code>TRILIUM_OAUTH_CLIENT_ID</code>, <code>TRILIUM_OAUTH_CLIENT_SECRET</code>, and for customizing the provider: <code>TRILIUM_OAUTH_ISSUER_BASE_URL</code>, <code>TRILIUM_OAUTH_ISSUER_NAME</code>, <code>TRILIUM_OAUTH_ISSUER_ICON</code>, <code>TRILIUM_OAUTH_HTTP_TIMEOUT</code>, <code>TRILIUM_OAUTH_SCOPE</code>, <code>TRILIUM_OAUTH_CLIENT_AUTH_METHOD</code>, <code>TRILIUM_OAUTH_ID_TOKEN_SIGNING_ALG</code>.</p></aside><h2>Connecting to the authentication provider</h2><p>Once the server has been configured at the previous step, the next step is to create a link between your account on the authentication provider and the Trilium instance. This makes sure that only you can access the Trilium instance, and not just any other valid account.</p><p>To do so:</p><ol><li>Go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Password & Auth.</em></li><li>In the <em>Sign-in with</em> field, choose <em>OpenID Connect provider.</em></li><li>In the <em>OpenID Connect</em> section, look for the <em>Connect account</em> (<span class=\"tn-icon bx bx-log-in\"></span>) button.</li><li>This will redirect you to your authentication provider, where you can sign in or confirm the action if needed.</li><li>Once you are authenticated you will be redirected back to the Trilium application.</li></ol><h2>Logging out</h2><p>When logging out of Trilium, a request is made to the authentication provider to log out from there as well. This feature depends on the authentication provider, so it may not be honored (Google and Authelia are known cases in which they don't respect the logout feature).</p><h2>Switching providers</h2><p>When switching providers (e.g. going from Google to Authelia), it's important to take the following steps:</p><ol><li>Go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Password & Auth</em>.</li><li>In the <em>OpenID Connect</em> section, press the <em>Disconnect</em> (<span class=\"tn-icon bx bx-trash\"></span>) button.</li><li>Wait for the section to indicate that you are disconnected.</li><li>Change the configuration pointing to the new provider.</li><li>Restart your server.</li><li>Repeat the normal steps to connect to the authentication provider.</li></ol><p>Failing to disconnect before switching providers might temporarily lock you in, as you will not be able to login (credentials won't match). Should this happen:</p><ol><li>Modify the server configuration again to your old provider.</li><li>Restart the server and follow the disconnect instructions above.</li><li>Modify the server configuration again to your new provider.</li><li>Restart again the server.</li></ol><h2>Deactivating OpenID Connect temporarily</h2><p>To disable the OpenID Connect authentication and instead rely on the local password temporarily, you must:</p><ol><li>Modify the <code>config.ini</code> or environment variables (depending on how you set up the provider information) and temporarily deactivate the multi-factor authentication section by renaming <code>[MultiFactorAuthentication]</code> to something else (e.g. <code>[MultiFactorAuthentication.bak]</code>.</li><li>Restart the server for the changes to take effect.</li></ol><h2>Troubleshooting</h2><h3>Setup fails with a <code>WWW-Authenticate</code> or <code>invalid_client</code> error</h3><p>Your provider disagrees with Trilium about how client credentials should be sent to the token endpoint. Set <code>oauthClientAuthMethod</code> to <code>client_secret_post</code> (or <code>client_secret_basic</code> if it's already set to post) and restart. Providers vary: some reject <code>client_secret_post</code> outright because the method is fixed when the client is registered (e.g. Authelia), so if one value doesn't work, try the other.</p><h3>Setup fails with <code>invalid user</code></h3><p>If you are running behind a <a href=\"#root/_help_vcjrb3VVYPZI\">reverse proxy</a>, a buffer overflow can also cause this issue. Here is a sample fix for <a class=\"reference-link\" href=\"#root/_help_ud6MShXL4WpO\">Nginx</a>: </p><pre><code class=\"language-text-x-trilium-auto\">proxy_buffer_size 128k;\nproxy_buffers 4 256k;\nproxy_busy_buffers_size 256k;</code></pre><h3>Setup fails with an <code>unexpected JWT alg</code> error</h3><p>Depending on your version the message reads <code>unexpected JWT \"alg\" header parameter</code> or <code>unexpected JWT alg received, expected RS256, got: EdDSA</code>. Both mean the same thing: your provider signs ID tokens with an algorithm other than RS256. Pocket ID (Ed25519) and Kanidm (ES256) do this.</p><p>From v0.104.2 Trilium detects the algorithm from your provider automatically, and the log records the outcome (<code>OAuth: the issuer does not sign ID tokens with RS256; expecting ES256</code>). If detection can't reach the provider it falls back to RS256, so check that the issuer URL is correct and reachable first. Should it still fail, set <code>oauthIdTokenSigningAlg</code> explicitly to the algorithm your provider uses.</p><h3>Setup fails with <code>OAUTH_RESPONSE_IS_NOT_CONFORM</code></h3><p>Make sure the base URL is correct and that the identity provider actually supports OpenID Connect. Some providers such as GitHub offer only OAuth 2.0.</p>",diff --git a/apps/server/src/etapi/notes.ts b/apps/server/src/etapi/notes.tsindex a926b96d9e..887d165af7 100644--- a/apps/server/src/etapi/notes.ts+++ b/apps/server/src/etapi/notes.ts@@ -84,7 +84,7 @@ function register(router: Router) {const ALLOWED_PROPERTIES_FOR_PATCH = {title: [v.notNull, v.isString],- type: [v.notNull, v.isString],+ type: [v.notNull, v.isNoteType],mime: [v.notNull, v.isString],dateCreated: [v.notNull, v.isString, v.isLocalDateTime],utcDateCreated: [v.notNull, v.isString, v.isUtcDateTime],diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.tsindex 1422d23cc3..b0f9945f03 100644--- a/packages/trilium-core/src/routes/api/notes.spec.ts+++ b/packages/trilium-core/src/routes/api/notes.spec.ts@@ -621,6 +621,19 @@ describe("Notes API (core)", () => {expect(note.body.type).toBe("code");expect(note.body.mime).toBe("text/x-python");});++ it("rejects a type outside the note type set and leaves the note unchanged", async () => {+ const { noteId } = await createTextNote(api, { title: "Bad type" });+ for (const type of ["EVILTYPE", "html", undefined, 42]) {+ const res = await api.put(`/api/notes/${noteId}/type`, {+ body: { type, mime: "application/x-anything" }+ });+ expect(res.status).toBe(400);+ }++ expect(becca.getNoteOrThrow(noteId).type).toBe("text");+ expect(becca.getNoteOrThrow(noteId).mime).toBe("text/html");+ });});describe("structural operations", () => {diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.tsindex 37e5f8b1ad..f9d5e6ab2e 100644--- a/packages/trilium-core/src/routes/api/notes.ts+++ b/packages/trilium-core/src/routes/api/notes.ts@@ -1,4 +1,4 @@-import type { AttributeRow, CreateChildrenResponse, DeleteNotesPreview, MetadataResponse } from "@triliumnext/commons";+import { type AttributeRow, type CreateChildrenResponse, type DeleteNotesPreview, isNoteType, type MetadataResponse } from "@triliumnext/commons";import { t } from "i18next";import type { Request } from "../../http_interface";@@ -367,6 +367,10 @@ function setNoteTypeMime(req: Request<{ noteId: string }>) {const { noteId } = req.params;const { type, mime } = req.body;+ if (!isNoteType(type)) {+ throw new ValidationError(`'${type}' is not a valid note type`);+ }+const note = becca.getNoteOrThrow(noteId);note.type = type;note.mime = mime;