Skip to content

Build your personal knowledge base with Trilium Notes

refactor(import): extract generic OAuth from the OneNote desktop sign-in

Elian Doranfecad17bc595
diff --git a/apps/desktop/src/services/loopback_oauth.ts b/apps/desktop/src/services/loopback_oauth.ts
new file mode 100644
index 0000000000..a59af44ba7
--- /dev/null
+++ b/apps/desktop/src/services/loopback_oauth.ts
@@ -0,0 +1,105 @@
+import oauth, { type OAuthProviderConfig, type TokenResponse } from "@triliumnext/server/src/services/oauth/oauth.js";
+import electron from "electron";
+import http from "node:http";
+
+/**
+ * Generic desktop OAuth authorization-code-with-PKCE flow over a loopback redirect.
+ *
+ * Provider-agnostic: given any {@link OAuthProviderConfig} it runs the whole sign-in in the main
+ * process and returns the raw token response, leaving provider-specific follow-up (account lookup,
+ * token storage) to the caller. The first consumer is the OneNote importer (see ./onenote.ts).
+ *
+ * Why this lives in the main process at all: the renderer talks to Express over the `trilium-app://`
+ * custom protocol, so a request-derived redirect URI is unreachable (`http://app/...`) and the OAuth
+ * callback would land in a different session than the one the renderer polls. Running the flow here,
+ * with a throwaway loopback server as the redirect target, avoids both problems.
+ *
+ * The provider's app registration must list `http://localhost` as a redirect URI ("Mobile and desktop
+ * applications" platform); providers match loopback redirects on host only, so the dynamic port is fine.
+ */
+
+/** 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 async function authorizeViaLoopback(config: OAuthProviderConfig): Promise<TokenResponse> {
+ const { verifier, challenge } = oauth.generatePkce();
+ const state = oauth.generateState();
+
+ const loopback = await startLoopbackServer(state);
+ const redirectUri = `http://localhost:${loopback.port}/`;
+ try {
+ electron.shell.openExternal(oauth.buildAuthorizationUrl(config, { redirectUri, state, challenge }));
+
+ const code = await loopback.waitForCode;
+ return await oauth.exchangeCodeForToken(config, { code, verifier, redirectUri });
+ } 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 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>Sign-in</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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] ?? c);
+}
diff --git a/apps/desktop/src/services/onenote.ts b/apps/desktop/src/services/onenote.ts
index aa39b70c16..3229e0f53b 100644
--- a/apps/desktop/src/services/onenote.ts
+++ b/apps/desktop/src/services/onenote.ts
@@ -2,134 +2,36 @@ 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 { ONENOTE_OAUTH } from "@triliumnext/server/src/services/import/onenote/oauth.js";
import electron from "electron";
-import http from "node:http";
+
+import { authorizeViaLoopback } from "./loopback_oauth.js";
/**
- * 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.
+ * Main-process handler for the OneNote importer's Microsoft sign-in on the desktop build.
*
- * 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.
+ * Just the OneNote-specific glue: it runs the provider-agnostic loopback OAuth flow with the OneNote
+ * config, then resolves the signed-in account and stores the token in the process-wide desktop session
+ * store that the dispatched API requests read from (see apps/server/.../onenote_import.ts). The renderer
+ * invokes this and waits for the result.
*/
-
-/** 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();
+ const tokens = await authorizeViaLoopback(ONENOTE_OAUTH);
+ 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 };
} catch (e) {
- const message = coreUtils.safeExtractMessageAndStackFromError(e);
- getLog().error(`OneNote desktop sign-in failed: ${message}`);
+ getLog().error(`OneNote desktop sign-in failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c] ?? c);
-}
diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.ts
index 4c3591de60..ec4f72b21c 100644
--- a/apps/server/src/routes/api/onenote_import.ts
+++ b/apps/server/src/routes/api/onenote_import.ts
@@ -18,17 +18,17 @@ 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";
+import { ONENOTE_OAUTH } from "../../services/import/onenote/oauth.js";
+import oauth from "../../services/oauth/oauth.js";
function getAuthUrl(req: Request) {
- const clientId = oauth.getClientId();
const { verifier, challenge } = oauth.generatePkce();
const state = oauth.generateState();
const redirectUri = getRedirectUri(req);
req.session.oneNoteImport = { verifier, state, redirectUri };
- return { authUrl: oauth.buildAuthorizationUrl({ clientId, redirectUri, state, challenge }) };
+ return { authUrl: oauth.buildAuthorizationUrl(ONENOTE_OAUTH, { redirectUri, state, challenge }) };
}
async function callback(req: Request, res: Response) {
@@ -45,8 +45,7 @@ async function callback(req: Request, res: Response) {
return sendHtml(res, "Sign-in could not be completed (invalid or expired state). Please close this window and try again.");
}
- const clientId = oauth.getClientId();
- const tokens = await oauth.exchangeCodeForToken({ clientId, code, verifier: pending.verifier, redirectUri: pending.redirectUri });
+ const tokens = await oauth.exchangeCodeForToken(ONENOTE_OAUTH, { code, verifier: pending.verifier, redirectUri: pending.redirectUri });
const account = await graph.getAccount(tokens.access_token);
req.session.oneNoteImport = {
@@ -122,7 +121,7 @@ async function getValidAccessToken(req: Request): Promise<string | null> {
}
if (session.refreshToken) {
- const tokens = await oauth.refreshAccessToken({ clientId: oauth.getClientId(), refreshToken: session.refreshToken });
+ const tokens = await oauth.refreshAccessToken(ONENOTE_OAUTH, { refreshToken: session.refreshToken });
await store.write({
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token ?? session.refreshToken,
diff --git a/apps/server/src/services/import/onenote/oauth.ts b/apps/server/src/services/import/onenote/oauth.ts
index f2ad641f44..a0976fdcc8 100644
--- a/apps/server/src/services/import/onenote/oauth.ts
+++ b/apps/server/src/services/import/onenote/oauth.ts
@@ -1,113 +1,27 @@
/**
- * OAuth 2.0 authorization-code-with-PKCE flow against Microsoft Entra ID, used to obtain a
- * delegated Microsoft Graph access token for the OneNote importer.
+ * OneNote importer OAuth provider config: delegated Microsoft Graph access via Microsoft Entra ID.
*
- * This is intentionally separate from the user-login OAuth in `open_id.ts`: that one authenticates
- * the Trilium user (OIDC), whereas this one authorizes the app to call the Graph API on the user's
- * behalf and therefore needs to keep (and refresh) the resulting access/refresh tokens.
+ * This is the single place the OneNote provider's OAuth specifics live; the actual flow runs through
+ * the generic client in services/oauth/oauth.ts. It is intentionally separate from the user-login OAuth
+ * in open_id.ts: that one authenticates the Trilium user (OIDC), whereas this one authorizes the app to
+ * call the Graph API on the user's behalf (and to refresh the resulting tokens).
*
* It is a PUBLIC client (no client secret), so PKCE is mandatory. The backing app registration is of
* type "Mobile and desktop applications" in the Microsoft Entra admin center, allows personal +
- * work/school accounts, and grants delegated Graph permissions (Notes.Read, User.Read,
- * offline_access). Its client id is a public identifier (see getClientId), so it is hardcoded.
+ * work/school accounts, and grants delegated Graph permissions (Notes.Read, User.Read, offline_access).
+ * The client id is a public identifier — the flow is protected by PKCE, not by hiding this value — so
+ * it is hardcoded, the same way other open-source apps (e.g. Obsidian's OneNote importer) ship theirs.
*/
-import { createHash, randomBytes } from "node:crypto";
+import type { OAuthProviderConfig } from "../../oauth/oauth.js";
/** `/common` lets both personal Microsoft accounts and work/school accounts sign in. */
const AUTHORITY = "https://login.microsoftonline.com/common/oauth2/v2.0";
-const AUTHORIZE_ENDPOINT = `${AUTHORITY}/authorize`;
-const TOKEN_ENDPOINT = `${AUTHORITY}/token`;
-/** offline_access is requested so we receive a refresh token that survives long imports. */
-const SCOPES = "offline_access User.Read Notes.Read";
-
-export interface TokenResponse {
- access_token: string;
- refresh_token?: string;
- expires_in: number;
- token_type: string;
- scope?: string;
-}
-
-export interface Pkce {
- verifier: string;
- challenge: string;
-}
-
-/**
- * The public client id of the registered Microsoft Entra app. A public-client (PKCE) client id is not
- * a secret — the flow is protected by PKCE, not by hiding this value — so it is hardcoded, the same
- * way other open-source apps (e.g. Obsidian's OneNote importer) ship theirs.
- */
-export function getClientId(): string {
- return "47e34695-b922-4c23-8519-303fa39284c8";
-}
-
-export function generatePkce(): Pkce {
- const verifier = randomBytes(32).toString("base64url");
- const challenge = createHash("sha256").update(verifier).digest("base64url");
- return { verifier, challenge };
-}
-
-export function generateState(): string {
- return randomBytes(16).toString("hex");
-}
-
-export function buildAuthorizationUrl({ clientId, redirectUri, state, challenge }: { clientId: string; redirectUri: string; state: string; challenge: string }): string {
- const params = new URLSearchParams({
- client_id: clientId,
- response_type: "code",
- redirect_uri: redirectUri,
- response_mode: "query",
- scope: SCOPES,
- state,
- code_challenge: challenge,
- code_challenge_method: "S256"
- });
- return `${AUTHORIZE_ENDPOINT}?${params.toString()}`;
-}
-
-export async function exchangeCodeForToken({ clientId, code, verifier, redirectUri }: { clientId: string; code: string; verifier: string; redirectUri: string }): Promise<TokenResponse> {
- return postToken({
- client_id: clientId,
- grant_type: "authorization_code",
- code,
- code_verifier: verifier,
- redirect_uri: redirectUri,
- scope: SCOPES
- });
-}
-
-export async function refreshAccessToken({ clientId, refreshToken }: { clientId: string; refreshToken: string }): Promise<TokenResponse> {
- return postToken({
- client_id: clientId,
- grant_type: "refresh_token",
- refresh_token: refreshToken,
- scope: SCOPES
- });
-}
-
-async function postToken(body: Record<string, string>): Promise<TokenResponse> {
- const response = await fetch(TOKEN_ENDPOINT, {
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body: new URLSearchParams(body).toString()
- });
-
- const json = await response.json();
- if (!response.ok || !json.access_token) {
- const detail = json.error_description || json.error || `HTTP ${response.status}`;
- throw new Error(`OneNote token request failed: ${detail}`);
- }
- return json as TokenResponse;
-}
-
-export default {
- getClientId,
- generatePkce,
- generateState,
- buildAuthorizationUrl,
- exchangeCodeForToken,
- refreshAccessToken
+export const ONENOTE_OAUTH: OAuthProviderConfig = {
+ authorizeEndpoint: `${AUTHORITY}/authorize`,
+ tokenEndpoint: `${AUTHORITY}/token`,
+ clientId: "47e34695-b922-4c23-8519-303fa39284c8",
+ // offline_access is requested so we receive a refresh token that survives long imports.
+ scopes: "offline_access User.Read Notes.Read"
};
diff --git a/apps/server/src/services/oauth/oauth.ts b/apps/server/src/services/oauth/oauth.ts
new file mode 100644
index 0000000000..971688e8f5
--- /dev/null
+++ b/apps/server/src/services/oauth/oauth.ts
@@ -0,0 +1,105 @@
+/**
+ * Generic OAuth 2.0 authorization-code-with-PKCE client for public (no-secret) clients.
+ *
+ * Provider-agnostic: every call is parameterised by an {@link OAuthProviderConfig} (endpoints, client
+ * id, scopes), so the same machinery serves any provider. The first consumer is the OneNote importer's
+ * delegated Microsoft Graph access (see services/import/onenote/oauth.ts for its config), driven on the
+ * web by the API route and on desktop by a loopback redirect (see apps/desktop/.../loopback_oauth.ts).
+ *
+ * PKCE is mandatory because there is no client secret to authenticate the token request — the flow is
+ * protected by the verifier/challenge pair, not by a shared secret. A public-client id is therefore not
+ * sensitive and may be shipped in the open.
+ */
+
+import { createHash, randomBytes } from "node:crypto";
+
+export interface OAuthProviderConfig {
+ /** The provider's authorization endpoint (where the user is sent to sign in). */
+ authorizeEndpoint: string;
+ /** The provider's token endpoint (where the code is exchanged and tokens are refreshed). */
+ tokenEndpoint: string;
+ /** The public client id of the registered application. */
+ clientId: string;
+ /** Space-separated scope list requested for the access token. */
+ scopes: string;
+}
+
+export interface TokenResponse {
+ access_token: string;
+ refresh_token?: string;
+ expires_in: number;
+ token_type: string;
+ scope?: string;
+}
+
+export interface Pkce {
+ verifier: string;
+ challenge: string;
+}
+
+export function generatePkce(): Pkce {
+ const verifier = randomBytes(32).toString("base64url");
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
+ return { verifier, challenge };
+}
+
+export function generateState(): string {
+ return randomBytes(16).toString("hex");
+}
+
+export function buildAuthorizationUrl(config: OAuthProviderConfig, { redirectUri, state, challenge }: { redirectUri: string; state: string; challenge: string }): string {
+ const params = new URLSearchParams({
+ client_id: config.clientId,
+ response_type: "code",
+ redirect_uri: redirectUri,
+ response_mode: "query",
+ scope: config.scopes,
+ state,
+ code_challenge: challenge,
+ code_challenge_method: "S256"
+ });
+ return `${config.authorizeEndpoint}?${params.toString()}`;
+}
+
+export async function exchangeCodeForToken(config: OAuthProviderConfig, { code, verifier, redirectUri }: { code: string; verifier: string; redirectUri: string }): Promise<TokenResponse> {
+ return postToken(config, {
+ client_id: config.clientId,
+ grant_type: "authorization_code",
+ code,
+ code_verifier: verifier,
+ redirect_uri: redirectUri,
+ scope: config.scopes
+ });
+}
+
+export async function refreshAccessToken(config: OAuthProviderConfig, { refreshToken }: { refreshToken: string }): Promise<TokenResponse> {
+ return postToken(config, {
+ client_id: config.clientId,
+ grant_type: "refresh_token",
+ refresh_token: refreshToken,
+ scope: config.scopes
+ });
+}
+
+async function postToken(config: OAuthProviderConfig, body: Record<string, string>): Promise<TokenResponse> {
+ const response = await fetch(config.tokenEndpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams(body).toString()
+ });
+
+ const json = await response.json();
+ if (!response.ok || !json.access_token) {
+ const detail = json.error_description || json.error || `HTTP ${response.status}`;
+ throw new Error(`OAuth token request failed: ${detail}`);
+ }
+ return json as TokenResponse;
+}
+
+export default {
+ generatePkce,
+ generateState,
+ buildAuthorizationUrl,
+ exchangeCodeForToken,
+ refreshAccessToken
+};