Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): show the device's location with MapLibre's locate button

Elian Doran8b10c77c86ae
diff --git a/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md b/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md
index cc35f689dc..3e8dd46834 100644
--- a/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md
+++ b/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md
@@ -16,7 +16,7 @@ In packaged Electron the renderer loads the **entire** UI from `trilium-app://ap
| **SSE / LLM chat stream buffers** until the request ends (no incremental tokens) | The handler never called `res.flushHeaders()`, or the streaming bridge shim is missing/broken. Non-streaming handlers resolve via the buffered `res.on("end")` path; only `flushHeaders()` commits a `ReadableStream` body. | `installStreamingBridge` (`protocol.ts:284`) maps `res.flushHeaders()` → `commit()`, which resolves the Fetch `Response` with a `ReadableStream` and forwards later `res.write(chunk)` into the controller. The handler must call `flushHeaders()` to opt in. The bridge also shims `res.flush` to a no-op to avoid an Express prototype-swap crash (in the same bridge). |
| API call from an **iframe** returns **403** / is cancelled | The frame-origin guard rejected the request: a non-`mainFrame` request whose frame chain contains a non-app (foreign) frame is denied **before** the protocol handler runs. | `installFrameOriginGuard` (`protocol.ts:120`) registers a `webRequest.onBeforeRequest` filter; the pure policy is `isRequestorChainTrusted(resourceType, frameUrls)` (`protocol.ts:143`) — `mainFrame` always allowed; otherwise every committed frame must be the app shell or `devtools:`. A second, weaker check `isDispatchOriginAllowed` (`protocol.ts:173`) 403s any request that *positively* attests a foreign `Origin` (only navigation-style requests carry one). |
| **`<webview>` won't attach** / log shows `Blocked <webview> attach requesting [...]` | The attach requested a banned capability (`preload`, `nodeIntegration`, `nodeIntegrationInSubFrames`, `webSecurity:false`, `allowRunningInsecureContent`) or the wrong/empty session partition. | `hardenWebviewPreferences` (`web_contents_security.ts:79`), called from the `will-attach-webview` hook (`:50`), returns the violation list; a non-empty list `preventDefault()`s the attach. The partition **must** exactly equal `WEBVIEW_SESSION_PARTITION` (`"persist:webview"`) — an unset/empty/different partition is a violation (`:111-115`). The legit Web View note always declares it. |
-| **Permission denied** (camera, mic, geolocation, clipboard-read, notifications from a remote embed, …) | Not in `PERMISSION_ALLOWLIST` for that session kind, or the request origin isn't the app shell. Unset handlers would GRANT everything, so deny-by-default is enforced explicitly. | `PERMISSION_ALLOWLIST` (`web_contents_security.ts:150`): `app` = `clipboard-sanitized-write`, `fullscreen`, `notifications`; `guest` = `fullscreen` only. `isPermissionAllowedForOrigin` (`:176`) additionally requires the request to come from `trilium-app://app` (except `fullscreen`, allowed for any origin). Installed on both the default and `WEBVIEW_SESSION_PARTITION` sessions (`:63-66`). |
+| **Permission denied** (camera, mic, clipboard-read, notifications or geolocation from a remote embed, …) | Not in `PERMISSION_ALLOWLIST` for that session kind, or the request origin isn't the app shell. Unset handlers would GRANT everything, so deny-by-default is enforced explicitly. | `PERMISSION_ALLOWLIST` (`web_contents_security.ts:150`): `app` = `clipboard-sanitized-write`, `fileSystem`, `fullscreen`, `geolocation`, `local-fonts`, `notifications`; `guest` = `fullscreen` only. `isPermissionAllowedForOrigin` (`:176`) additionally requires the request to come from `trilium-app://app` (except `fullscreen`, allowed for any origin). Installed on both the default and `WEBVIEW_SESSION_PARTITION` sessions (`:63-66`). |
| `window.open` / `target=_blank` does nothing, or a note link opens in the OS browser | By design: only the app shell's root URL (`isNavigationAllowed`, query string and hash allowed) is allowed — that is the client's own "open in new window", and Chromium creates it in the opener's renderer process; every other window-open is denied, and for app windows the URL is re-validated through the same scheme allowlist and routed to the OS browser. | `installWindowOpenPolicy` (`web_contents_security.ts`) returns `allow` + `outlivesOpener` + the `extraWindowOptions()` that `setupWindowing()` supplies; otherwise it reuses `validateOpenExternalUrl` from `shell.ts`, so a note-content link can't bypass the Follina/`smb:` allowlist. `<webview>` guests are denied outright (no external dispatch, not even for the app URL). |
| A window opened from the client is **blank**, or has no `window.electronApi` | The `window.open` child was built without a preload — children inherit only the security-related `webPreferences` (`sandbox`, `nodeIntegration`, …), never `preload` — or its initial navigation was blocked by the guard. | `getExtraWindowOptions()` (`window.ts`) must include `webPreferences.preload`; `setupWindowing()` passes it as `extraWindowOptions`. `did-create-window` on the opener runs `adoptExtraWindow()` (menu bar, spellcheck, focus tracking). The `--new-window` command line still uses main-process `createExtraWindow()`, which has no opener. |
| A link/drag navigates an **app window away from Trilium** and gets blocked | The navigation guard only allows the app shell root. | `isNavigationAllowed(targetUrl)` (`web_contents_security.ts:199`): allowed only for `trilium-app:` + the app host at root path (`/`, `/?`, or empty). `<webview>` guests are exempt (they're embedded browsers). The old `localhost` carve-out was removed as dangerous. |
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.css b/apps/client/src/widgets/collections/geomap/MapToolbar.css
index af42428efb..3242570b1e 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.css
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.css
@@ -5,3 +5,11 @@
width: 32px;
}
+/* MapLibre's locate button is added to the corner this group stands in (see useGeolocateControl in
+ MapToolbar.tsx), so it is lifted to stand above the group: the foot is the room kept from the
+ edge, the group's height and as much air again. Named by four classes to outweigh the corner
+ margins index.css gives every control. */
+.geo-map-container .maplibregl-ctrl-bottom-right .maplibregl-ctrl.maplibregl-ctrl-group {
+ margin-bottom: var(--geo-map-foot);
+}
+
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx
index e53cc77261..2ab1fb89f3 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx
@@ -5,7 +5,7 @@
* allowed being refused rather than merely doing nothing, and the screen being given and taken
* back.
*/
-import type { Map as MapLibreGLMap } from "maplibre-gl";
+import { GeolocateControl, type Map as MapLibreGLMap } from "maplibre-gl";
import { render } from "preact";
import { act } from "preact/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -39,8 +39,15 @@ function fakeMap({ zoom = 5, minZoom = 2, maxZoom = 22, pitch = 0 } = {}) {
pitch = value;
fire("pitch");
};
+ /** The controls the map holds, which a map being removed lets go of on its own. */
+ const controls = new Set<unknown>();
return {
+ addControl: vi.fn((control: unknown, _position?: string) => { controls.add(control); }),
+ removeControl: vi.fn((control: unknown) => { controls.delete(control); }),
+ hasControl: (control: unknown) => controls.has(control),
+ /** The map being torn down, as `map.remove()` does before any cleanup around it runs. */
+ remove: () => controls.clear(),
getZoom: () => zoom,
getMinZoom: () => minZoom,
getMaxZoom: () => maxZoom,
@@ -162,6 +169,30 @@ describe("geo map MapToolbar", () => {
expect(buttons(container)).toHaveLength(0);
});
+ it("stands MapLibre's locate button on the map, set to follow the device, and takes it off again", () => {
+ const map = fakeMap();
+ const container = renderToolbar(map);
+
+ expect(map.addControl).toHaveBeenCalledTimes(1);
+ const [ control, position ] = map.addControl.mock.calls[0];
+ expect(control).toBeInstanceOf(GeolocateControl);
+ // A toggle that follows the device rather than a button that flies there once.
+ expect((control as GeolocateControl).options.trackUserLocation).toBe(true);
+ // The corner this group stands in, lifted above it (see MapToolbar.css).
+ expect(position).toBe("bottom-right");
+
+ act(() => { render(null, container); });
+ expect(map.removeControl).toHaveBeenCalledWith(control);
+
+ // A map torn down first has let go of the control already, and is not asked to again —
+ // MapLibre throws for a control it no longer holds.
+ const torn = fakeMap();
+ const second = renderToolbar(torn);
+ torn.remove();
+ act(() => { render(null, second); });
+ expect(torn.removeControl).not.toHaveBeenCalled();
+ });
+
it("zooms the map in either direction", () => {
const map = fakeMap();
const container = renderToolbar(map);
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
index 77ebc2cfed..e02361e791 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
@@ -1,6 +1,6 @@
import "./MapToolbar.css";
-import type { Map as MapLibreGLMap } from "maplibre-gl";
+import { GeolocateControl, type Map as MapLibreGLMap } from "maplibre-gl";
import { useContext, useEffect, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
@@ -49,6 +49,7 @@ export default function MapToolbar() {
// The map itself rather than the whole view: what is around it is the note's own chrome, and
// everything the bar above the map offers is on the map's right-click menu as well.
const [ isFullscreen, toggleFullscreen ] = useFullscreen(map?.getContainer());
+ useGeolocateControl(map);
if (!map) return null;
@@ -113,3 +114,30 @@ function useMapZoom(map: MapLibreGLMap | null) {
return zoom;
}
+
+/**
+ * Stands MapLibre's own locate button on the map, in the corner above this group (see
+ * MapToolbar.css for the lift).
+ *
+ * With `trackUserLocation` the button is a toggle: the first press asks the browser for the device's
+ * position, frames it and follows it as it changes; dragging the map keeps the dot but frees the
+ * camera; a second press turns the watch off and takes the dot away. The control draws the dot and
+ * its accuracy circle itself, as DOM markers over the canvas, so nothing here survives a style
+ * switch only by being carried across (see `keepAdditions` in map.tsx).
+ */
+function useGeolocateControl(map: MapLibreGLMap | null) {
+ useEffect(() => {
+ if (!map) return;
+
+ const control = new GeolocateControl({ trackUserLocation: true });
+ map.addControl(control, "bottom-right");
+
+ return () => {
+ // A map being removed lets go of its controls first, and MapLibre's `removeControl`
+ // throws for one the map no longer holds (see the scale control in map.tsx).
+ if (map.hasControl(control)) {
+ map.removeControl(control);
+ }
+ };
+ }, [ map ]);
+}
diff --git a/apps/desktop/src/services/web_contents_security.spec.ts b/apps/desktop/src/services/web_contents_security.spec.ts
index e971597084..572a7537e3 100644
--- a/apps/desktop/src/services/web_contents_security.spec.ts
+++ b/apps/desktop/src/services/web_contents_security.spec.ts
@@ -314,8 +314,12 @@ describe("isPermissionAllowed", () => {
expect(isPermissionAllowed("guest", "fileSystem")).toBe(false);
expect(isPermissionAllowed("guest", "local-fonts")).toBe(false);
+ // The geo map's locate button asks where the device is; a remote page does not get to.
+ expect(isPermissionAllowed("app", "geolocation")).toBe(true);
+ expect(isPermissionAllowed("guest", "geolocation")).toBe(false);
+
// Everything else is denied everywhere.
- for (const permission of ["media", "geolocation", "midi", "hid", "serial", "usb", "pointerLock", "clipboard-read", "openExternal"]) {
+ for (const permission of ["media", "midi", "hid", "serial", "usb", "pointerLock", "clipboard-read", "openExternal"]) {
expect(isPermissionAllowed("app", permission)).toBe(false);
expect(isPermissionAllowed("guest", permission)).toBe(false);
}
@@ -328,11 +332,14 @@ describe("isPermissionAllowedForOrigin", () => {
expect(isPermissionAllowedForOrigin("app", "notifications", "trilium-app://app")).toBe(true);
expect(isPermissionAllowedForOrigin("app", "clipboard-sanitized-write", "trilium-app://app/some/path")).toBe(true);
expect(isPermissionAllowedForOrigin("app", "fileSystem", "trilium-app://app")).toBe(true);
+ expect(isPermissionAllowedForOrigin("app", "geolocation", "trilium-app://app")).toBe(true);
// A remote <iframe> sharing the default session does not.
expect(isPermissionAllowedForOrigin("app", "notifications", "https://www.youtube-nocookie.com/embed/x")).toBe(false);
expect(isPermissionAllowedForOrigin("app", "clipboard-sanitized-write", "https://evil.example")).toBe(false);
expect(isPermissionAllowedForOrigin("app", "fileSystem", "https://evil.example")).toBe(false);
+ // Where the device is stays the app's to ask; an embed does not learn it.
+ expect(isPermissionAllowedForOrigin("app", "geolocation", "https://evil.example")).toBe(false);
// The installed font list is a fingerprinting surface, so an embed does not get to read it.
expect(isPermissionAllowedForOrigin("app", "local-fonts", "https://evil.example")).toBe(false);
// Another host under our own scheme is not the app shell.
@@ -349,7 +356,7 @@ describe("isPermissionAllowedForOrigin", () => {
});
it("never grants a permission outside the session allowlist, even from the app shell", () => {
- expect(isPermissionAllowedForOrigin("app", "geolocation", "trilium-app://app")).toBe(false);
+ expect(isPermissionAllowedForOrigin("app", "media", "trilium-app://app")).toBe(false);
expect(isPermissionAllowedForOrigin("app", "clipboard-read", "trilium-app://app")).toBe(false);
expect(isPermissionAllowedForOrigin("guest", "notifications", "trilium-app://app")).toBe(false);
});
@@ -431,7 +438,9 @@ describe("permission handlers", () => {
expect(appCheck({}, "clipboard-sanitized-write", "trilium-app://app")).toBe(true);
expect(appCheck({}, "clipboard-sanitized-write", "https://www.youtube-nocookie.com")).toBe(false);
- expect(appCheck({}, "geolocation", "trilium-app://app")).toBe(false);
+ // MapLibre's locate button asks this before enabling itself (`navigator.permissions.query`).
+ expect(appCheck({}, "geolocation", "trilium-app://app")).toBe(true);
+ expect(appCheck({}, "geolocation", "https://evil.example")).toBe(false);
// Fullscreen is origin-independent.
expect(guestCheck({}, "fullscreen", "https://www.youtube-nocookie.com")).toBe(true);
expect(guestCheck({}, "clipboard-sanitized-write", "https://www.youtube-nocookie.com")).toBe(false);
diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.ts
index 628f4e333b..13322094c3 100644
--- a/apps/desktop/src/services/web_contents_security.ts
+++ b/apps/desktop/src/services/web_contents_security.ts
@@ -136,9 +136,8 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences
/**
* Permission allowlists per session kind. Unset handlers make Electron GRANT
- * every request, so anything not listed here (camera, microphone, geolocation,
- * notifications, MIDI, HID, serial, USB, pointer lock, clipboard read, …) is
- * denied.
+ * every request, so anything not listed here (camera, microphone, MIDI, HID,
+ * serial, USB, pointer lock, clipboard read, …) is denied.
*
* - `app`: the default session — the Trilium renderer itself. It legitimately
* writes to the clipboard (copy note content/links), toggles fullscreen
@@ -159,6 +158,11 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences
* this device (see `listSystemFonts`); Chromium routes it through the
* *check* handler rather than the request handler, so granting it here is
* what keeps the picker from falling back to the stock list.
+ * `geolocation` lets the geo map's locate button ask where this device is
+ * (see `useGeolocateControl` in the client). Chromium prompts for nothing
+ * of its own in Electron, so this grant is the only gate; the origin check
+ * below keeps it from remote embeds, and MapLibre probes the *check*
+ * handler before it enables the button at all.
* - `guest`: the `<webview>` partition hosting arbitrary remote pages from
* Web View notes. Fullscreen only (embedded video players) — a remote page
* must not show OS notifications that appear to come from Trilium.
@@ -169,7 +173,7 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences
* the default session. Fullscreen is the exception — granted for any origin.
*/
const PERMISSION_ALLOWLIST = {
- app: new Set(["clipboard-sanitized-write", "fileSystem", "fullscreen", "local-fonts", "notifications"]),
+ app: new Set(["clipboard-sanitized-write", "fileSystem", "fullscreen", "geolocation", "local-fonts", "notifications"]),
guest: new Set(["fullscreen"])
} as const;
diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml
index d382a7bc3d..81d37e2b71 100644
--- a/apps/mobile/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml
@@ -41,4 +41,13 @@
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
+ <!-- The geo map's locate button. Capacitor's WebChromeClient asks the user for these when the
+ page first calls the Geolocation API; without them the WebView answers with a denial. -->
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <!-- The location permissions above imply these features as required, which would hide the app
+ from GPS-less devices on Google Play. Locating is optional, so they are not. -->
+ <uses-feature android:name="android.hardware.location" android:required="false" />
+ <uses-feature android:name="android.hardware.location.gps" android:required="false" />
+ <uses-feature android:name="android.hardware.location.network" android:required="false" />
</manifest>
diff --git a/apps/mobile/ios/App/App/Info.plist b/apps/mobile/ios/App/App/Info.plist
index 5a23d25440..ba27f6b684 100644
--- a/apps/mobile/ios/App/App/Info.plist
+++ b/apps/mobile/ios/App/App/Info.plist
@@ -51,6 +51,10 @@
<array>
<string>localhost</string>
</array>
+ <!-- Shown in the system prompt when the geo map's locate button first asks for a
+ position. iOS refuses the Geolocation API outright when this key is missing. -->
+ <key>NSLocationWhenInUseUsageDescription</key>
+ <string>Trilium shows where you are on a geo map.</string>
<!-- App Transport Security: Trilium users self-host the sync server,
often on LAN IPs, *.local, or personal domains without HTTPS.
iOS blocks plain http:// by default — allow it so users can