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
feat(import): support OneNote OAuth sign-in on desktop via loopback redirect
Elian Doran67634d19fd0f
diff --git a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx b/apps/client/src/widgets/dialogs/import_providers/onenote.tsxindex 2323a2dfdc..97c7f0a4a0 100644--- a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx+++ b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx@@ -1,7 +1,7 @@import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";-import onenoteImport, { buildSectionSelections, type OneNoteAccount, type OneNoteNotebook, type OneNoteSectionGroup } from "../../../services/onenote_import.js";+import onenoteImport, { buildSectionSelections, type OneNoteAccount, type OneNoteContainer, type OneNoteNotebook, orderedChildren } from "../../../services/onenote_import.js";import toast from "../../../services/toast.js";import { isElectron, randomString } from "../../../services/utils.js";import Button from "../../react/Button.js";@@ -51,13 +51,28 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {const connect = useCallback(async () => {try {- const { authUrl } = await onenoteImport.getAuthUrl();- if (isElectron()) {- window.electronApi?.shell.openExternal(authUrl);- } else {- window.open(authUrl, "_blank", "noopener,noreferrer");+ // Desktop runs the whole OAuth flow in the main process via a loopback redirect (the+ // browser-callback-into-session approach can't bridge Electron's split sessions), so the+ // sign-in resolves directly rather than being polled for.+ if (isElectron() && window.electronApi) {+ setPhase("connecting");+ const result = await window.electronApi.onenote.login();+ if (!result.connected) {+ if (result.error) {+ toast.showError(result.error);+ }+ setPhase("disconnected");+ return;+ }+ setAccount(result.account ?? null);+ await loadNotebooks();+ setPhase("ready");+ return;}+ const { authUrl } = await onenoteImport.getAuthUrl();+ window.open(authUrl, "_blank", "noopener,noreferrer");+setPhase("connecting");stopPolling();pollRef.current = setInterval(async () => {@@ -140,6 +155,10 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {: (<><p>{t("onenote_import.select_sections")}</p>+ <p className="onenote-order-hint">+ <span className="bx bx-info-circle" />+ {t("onenote_import.order_hint")}+ </p><div className="onenote-notebooks">{notebooks.map((notebook) => (<div className="onenote-notebook" key={notebook.id}>@@ -171,29 +190,31 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {}/** Renders a notebook's (or section group's) sections as checkboxes and recurses into nested section- * groups, so the OneNote folder structure is mirrored in the picker. */+ * groups. Sections and groups are interleaved in creation-date order so the picker mirrors the OneNote+ * left rail (which the API can't reproduce exactly — see the order caveat above the list). */function SectionTree({ container, selectedIds, onToggle }: {- container: OneNoteNotebook | OneNoteSectionGroup;+ container: OneNoteContainer;selectedIds: Set<string>;onToggle: (id: string, checked: boolean) => void;}) {return (<>- {container.sections.map((section) => (- <FormCheckbox- key={section.id}- name={`onenote-section-${section.id}`}- label={section.title}- currentValue={selectedIds.has(section.id)}- onChange={(checked) => onToggle(section.id, checked)}- />- ))}- {container.sectionGroups.map((group) => (- <div className="onenote-section-group" key={group.id}>- <span className="onenote-section-group-title">{group.title}</span>- <SectionTree container={group} selectedIds={selectedIds} onToggle={onToggle} />- </div>- ))}+ {orderedChildren(container).map((child) => (child.type === "section"+ ? (+ <FormCheckbox+ key={child.section.id}+ name={`onenote-section-${child.section.id}`}+ label={child.section.title}+ currentValue={selectedIds.has(child.section.id)}+ onChange={(checked) => onToggle(child.section.id, checked)}+ />+ )+ : (+ <div className="onenote-section-group" key={child.group.id}>+ <span className="onenote-section-group-title">{child.group.title}</span>+ <SectionTree container={child.group} selectedIds={selectedIds} onToggle={onToggle} />+ </div>+ )))}</>);}diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex f0ba88cbf7..7b6f2d1201 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -193,6 +193,7 @@ vi.mock("./services/auto_launch", () => ({wasLaunchedHidden: () => h.wasLaunchedHidden()}));vi.mock("./services/shell", () => ({ setupShellHandlers: vi.fn() }));+vi.mock("./services/onenote", () => ({ setupOneNoteHandlers: vi.fn() }));vi.mock("./services/security_settings", () => ({getSecuritySettings: () => h.securitySettings,registerSecurityIpcHandlers: vi.fn()diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 6e76fb3388..2738d26dbb 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -27,6 +27,7 @@ import DesktopPlatformProvider from "./platform_provider";import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";import { applyLaunchOnStartup, setupAutoLaunch, wasLaunchedHidden } from "./services/auto_launch";import { setupCustomDictionary } from "./services/custom_dictionary";+import { setupOneNoteHandlers } from "./services/onenote";import { setupPrintingHandlers } from "./services/printing";import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";import { setupShellHandlers } from "./services/shell";@@ -125,6 +126,7 @@ export async function main() {setupAutoLaunch();setupCustomDictionary();setupShellHandlers();+ setupOneNoteHandlers();setupPrintingHandlers();registerSecurityIpcHandlers();setupStartupMetricsIpc();diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex 9543dc71dc..367809eb81 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -604,4 +604,13 @@ describe("preload script", () => {expect(ipcRendererInvoked).toContainEqual({ channel: "security-set-lan-access", args: [true] });});});++ describe("onenote", () => {+ const onenote = () => getGroup("onenote");++ it("login invokes the corresponding IPC channel", async () => {+ await onenote().login();+ expect(ipcRendererInvoked).toContainEqual({ channel: "onenote-login", args: [] });+ });+ });});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex cdab8da3c0..6c928f4f52 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -1,4 +1,4 @@-import type { ElectronApi, ElectronContextMenuParams, RendererStartupMetric } from "@triliumnext/commons";+import type { ElectronApi, ElectronContextMenuParams, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";import { contextBridge, ipcRenderer, webFrame } from "electron";contextBridge.exposeInMainWorld("electronApi", {@@ -261,5 +261,11 @@ contextBridge.exposeInMainWorld("electronApi", {setLanAccessEnabled(enabled: boolean): Promise<boolean> {return ipcRenderer.invoke("security-set-lan-access", enabled);}+ },++ onenote: {+ login(): Promise<OneNoteLoginResult> {+ return ipcRenderer.invoke("onenote-login");+ }}} satisfies ElectronApi);diff --git a/apps/desktop/src/services/onenote.ts b/apps/desktop/src/services/onenote.tsnew file mode 100644index 0000000000..aa39b70c16--- /dev/null+++ b/apps/desktop/src/services/onenote.ts@@ -0,0 +1,135 @@+import type { OneNoteLoginResult } from "@triliumnext/commons";+import { getLog, utils as coreUtils } from "@triliumnext/core";+import { setDesktopSession } from "@triliumnext/server/src/services/import/onenote/desktop_session.js";+import graph from "@triliumnext/server/src/services/import/onenote/graph.js";+import oauth from "@triliumnext/server/src/services/import/onenote/oauth.js";+import electron from "electron";+import http from "node:http";++/**+ * Main-process driver for the OneNote importer's Microsoft sign-in on the desktop build.+ *+ * The server/web flow can't be reused here: it derives the OAuth redirect URI from the incoming+ * request, which on desktop is the `trilium-app://` custom protocol (yielding an unreachable+ * `http://app/...`), and it stashes the token in the request's express-session — a session the OAuth+ * callback, arriving in a separate browser, can never reach.+ *+ * Instead we run the whole authorization-code-with-PKCE flow here: spin up a throwaway loopback HTTP+ * server, point the redirect at it, open the system browser, capture the `code`, exchange it for a+ * token, and hand the token to the process-wide desktop session store that the dispatched API+ * requests read from (see apps/server/.../onenote_import.ts). The renderer just invokes this and+ * waits for the result.+ *+ * The app registration must list `http://localhost` as a redirect URI ("Mobile and desktop+ * applications" platform); Microsoft matches loopback redirects on host only, so any port is accepted.+ */++/** How long to wait for the user to complete sign-in before giving up and tearing the server down. */+const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;++export function setupOneNoteHandlers() {+ electron.ipcMain.handle("onenote-login", async (): Promise<OneNoteLoginResult> => {+ try {+ return await login();+ } catch (e) {+ const message = coreUtils.safeExtractMessageAndStackFromError(e);+ getLog().error(`OneNote desktop sign-in failed: ${message}`);+ return { connected: false, error: e instanceof Error ? e.message : String(e) };+ }+ });+}++async function login(): Promise<OneNoteLoginResult> {+ const clientId = oauth.getClientId();+ const { verifier, challenge } = oauth.generatePkce();+ const state = oauth.generateState();++ const loopback = await startLoopbackServer(state);+ const redirectUri = `http://localhost:${loopback.port}/`;+ try {+ const authUrl = oauth.buildAuthorizationUrl({ clientId, redirectUri, state, challenge });+ electron.shell.openExternal(authUrl);++ const code = await loopback.waitForCode;+ const tokens = await oauth.exchangeCodeForToken({ clientId, code, verifier, redirectUri });+ const account = await graph.getAccount(tokens.access_token);++ setDesktopSession({+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token,+ expiresAt: Date.now() + tokens.expires_in * 1000,+ account+ });++ return { connected: true, account };+ } finally {+ loopback.close();+ }+}++interface Loopback {+ port: number;+ /** Resolves with the OAuth `code` once the browser is redirected back; rejects on error/timeout. */+ waitForCode: Promise<string>;+ close(): void;+}++function startLoopbackServer(expectedState: string): Promise<Loopback> {+ return new Promise<Loopback>((resolveServer, rejectServer) => {+ let resolveCode!: (code: string) => void;+ let rejectCode!: (err: Error) => void;+ const waitForCode = new Promise<string>((resolve, reject) => {+ resolveCode = resolve;+ rejectCode = reject;+ });++ const server = http.createServer((req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const code = url.searchParams.get("code");+ const error = url.searchParams.get("error");+ const returnedState = url.searchParams.get("state");++ // Browsers fetch /favicon.ico and similar alongside the redirect; only the request that+ // actually carries the OAuth result should settle (and respond to) the flow.+ if (!code && !error) {+ res.writeHead(404).end();+ return;+ }++ if (error) {+ respond(res, `Sign-in failed: ${error}. You can close this window and try again.`);+ rejectCode(new Error(`Sign-in failed: ${error}`));+ } else if (!code || returnedState !== expectedState) {+ respond(res, "Sign-in could not be completed (invalid or expired state). Please close this window and try again.");+ rejectCode(new Error("Sign-in could not be completed (invalid or expired state)."));+ } else {+ respond(res, "Connected. You can close this window and return to Trilium.");+ resolveCode(code);+ }+ });++ const timeout = setTimeout(() => rejectCode(new Error("Timed out waiting for OneNote sign-in.")), SIGN_IN_TIMEOUT_MS);+ const guardedWaitForCode = waitForCode.finally(() => clearTimeout(timeout));++ server.on("error", rejectServer);+ // Listen on the same loopback name used in the redirect URI so the browser resolves to exactly+ // the address we bound, and let the OS pick a free port.+ server.listen(0, "localhost", () => {+ const address = server.address();+ const port = typeof address === "object" && address ? address.port : 0;+ resolveServer({ port, waitForCode: guardedWaitForCode, close: () => server.close() });+ });+ });+}++function respond(res: http.ServerResponse, message: string) {+ res.writeHead(200, { "Content-Type": "text/html" }).end(+ `<!doctype html><html><head><meta charset="utf-8"><title>OneNote import</title></head>` ++ `<body style="font-family: sans-serif; padding: 2rem; text-align: center;">` ++ `<p>${escapeHtml(message)}</p><script>setTimeout(() => window.close(), 1500);</script></body></html>`+ );+}++function escapeHtml(text: string): string {+ return text.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] ?? c);+}diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.tsindex 36f666be3a..4c3591de60 100644--- a/apps/server/src/routes/api/onenote_import.ts+++ b/apps/server/src/routes/api/onenote_import.ts@@ -14,6 +14,8 @@import { becca, ValidationError } from "@triliumnext/core";import type { Request, Response } from "express";+import { isInternalElectronRequest } from "../../services/electron_request.js";+import { getDesktopSession, type OneNoteTokenSession, setDesktopSession } from "../../services/import/onenote/desktop_session.js";import graph from "../../services/import/onenote/graph.js";import importer, { type SectionSelection } from "../../services/import/onenote/importer.js";import oauth from "../../services/import/onenote/oauth.js";@@ -62,12 +64,12 @@ async function callback(req: Request, res: Response) {}function getStatus(req: Request) {- const session = req.session.oneNoteImport;+ const session = tokenStore(req).read();return { connected: !!session?.accessToken, account: session?.account ?? null };}-function disconnect(req: Request) {- delete req.session.oneNoteImport;+async function disconnect(req: Request) {+ await tokenStore(req).clear();return {};}@@ -108,7 +110,8 @@ function getRedirectUri(req: Request): string {/** Returns a usable access token, transparently refreshing it when expired, or null if disconnected. */async function getValidAccessToken(req: Request): Promise<string | null> {- const session = req.session.oneNoteImport;+ const store = tokenStore(req);+ const session = store.read();if (!session?.accessToken) {return null;}@@ -120,15 +123,52 @@ async function getValidAccessToken(req: Request): Promise<string | null> {if (session.refreshToken) {const tokens = await oauth.refreshAccessToken({ clientId: oauth.getClientId(), refreshToken: session.refreshToken });- session.accessToken = tokens.access_token;- session.refreshToken = tokens.refresh_token ?? session.refreshToken;- session.expiresAt = Date.now() + tokens.expires_in * 1000;- await saveSession(req);+ await store.write({+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token ?? session.refreshToken,+ expiresAt: Date.now() + tokens.expires_in * 1000+ });+ return tokens.access_token;}return session.accessToken;}+interface TokenStore {+ read(): OneNoteTokenSession | undefined;+ /** Merges `data` into the stored token, preserving fields (e.g. the account) not being updated. */+ write(data: OneNoteTokenSession): Promise<void>;+ clear(): Promise<void>;+}++/**+ * Picks where the connected Graph token lives. Desktop renderer requests arrive over the+ * `trilium-app://` protocol dispatch (tagged as internal-electron) and use the process-wide+ * {@link getDesktopSession} singleton, because their OAuth callback was handled out-of-band by the+ * main process and never touched this session. Every other request keeps the token in its own+ * express-session, the same browser that completed the callback.+ */+function tokenStore(req: Request): TokenStore {+ if (isInternalElectronRequest(req)) {+ return {+ read: () => getDesktopSession() ?? undefined,+ write: async (data) => setDesktopSession({ ...getDesktopSession(), ...data }),+ clear: async () => setDesktopSession(null)+ };+ }+ return {+ read: () => req.session.oneNoteImport,+ write: async (data) => {+ req.session.oneNoteImport = { ...req.session.oneNoteImport, ...data };+ await saveSession(req);+ },+ clear: async () => {+ delete req.session.oneNoteImport;+ await saveSession(req);+ }+ };+}+function saveSession(req: Request): Promise<void> {return new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve())));}diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex c25944057e..40b65766be 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -188,7 +188,7 @@ function register(app: express.Application) {// The OAuth `state` validated against the session is what guards it.asyncRoute(GET, "/api/onenote-import/callback", [], onenoteImportRoute.callback);apiRoute(GET, "/api/onenote-import/status", onenoteImportRoute.getStatus);- apiRoute(PST, "/api/onenote-import/disconnect", onenoteImportRoute.disconnect);+ asyncApiRoute(PST, "/api/onenote-import/disconnect", onenoteImportRoute.disconnect);asyncApiRoute(GET, "/api/onenote-import/notebooks", onenoteImportRoute.getNotebooks);asyncApiRoute(PST, "/api/onenote-import/import", onenoteImportRoute.runImport);diff --git a/apps/server/src/services/import/onenote/desktop_session.ts b/apps/server/src/services/import/onenote/desktop_session.tsnew file mode 100644index 0000000000..66b5d8e7b1--- /dev/null+++ b/apps/server/src/services/import/onenote/desktop_session.ts@@ -0,0 +1,34 @@+/**+ * Process-wide store for the OneNote importer's delegated-Graph token on the desktop build.+ *+ * On the server/web build the token lives in the user's express-session (see onenote_import.ts),+ * because the OAuth callback and the page that polls for it share one browser — and therefore one+ * session cookie. The desktop build has no such shared session: the renderer talks to Express over the+ * `trilium-app://` custom protocol (one session context) while the OAuth callback arrives over a+ * throwaway loopback HTTP server in the main process (a different one). A session cookie cannot bridge+ * the two.+ *+ * Desktop is single-user and single-process, so a module-level singleton is the correct scope: the+ * main process writes the token here after a successful sign-in (see apps/desktop/src/services/onenote.ts)+ * and the dispatched API requests read it back from the same module instance.+ */++import type { GraphAccount } from "./graph.js";++export interface OneNoteTokenSession {+ accessToken?: string;+ refreshToken?: string;+ /** Epoch millis at which the access token expires. */+ expiresAt?: number;+ account?: GraphAccount;+}++let desktopSession: OneNoteTokenSession | null = null;++export function getDesktopSession(): OneNoteTokenSession | null {+ return desktopSession;+}++export function setDesktopSession(data: OneNoteTokenSession | null): void {+ desktopSession = data;+}diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 7e11809735..6a992375bb 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -491,6 +491,26 @@ export interface ElectronSecurityApi {setLanAccessEnabled(enabled: boolean): Promise<boolean>;}+/** Outcome of a {@link ElectronOneNoteApi.login} attempt. */+export interface OneNoteLoginResult {+ /** True if sign-in completed and a Microsoft Graph token was stored. */+ connected: boolean;+ /** The connected Microsoft account, present when `connected` is true. */+ account?: { name: string; email: string };+ /** A human-readable failure reason when `connected` is false (absent on user cancellation). */+ error?: string;+}++/** Desktop-only OneNote importer sign-in, driven from the main process via a loopback OAuth redirect. */+export interface ElectronOneNoteApi {+ /**+ * Runs the Microsoft delegated-Graph OAuth flow: opens the system browser, captures the redirect+ * on a throwaway loopback server, exchanges the code, and stores the token process-side. Resolves+ * once the desktop session is connected (or with `connected: false` on failure/timeout).+ */+ login(): Promise<OneNoteLoginResult>;+}+/*** The complete surface exposed to the renderer as `window.electronApi` via* `contextBridge`. The renderer must access Electron-only functionality through@@ -523,4 +543,6 @@ export interface ElectronApi {ws: ElectronWsApi;/** Security settings (backend scripting, SQL console) stored outside the DB. */security: ElectronSecurityApi;+ /** OneNote importer sign-in via a loopback OAuth redirect (desktop only). */+ onenote: ElectronOneNoteApi;}