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(server): use OAuth device flow for OneNote sign-in so self-hosted servers work
Elian Doran32d5353265a6
diff --git a/apps/client/src/services/onenote_import.ts b/apps/client/src/services/onenote_import.tsindex a3b14f08fc..6e4ffbfe71 100644--- a/apps/client/src/services/onenote_import.ts+++ b/apps/client/src/services/onenote_import.ts@@ -3,13 +3,13 @@// without this side-effect import the progress/finished toasts would never appear.import "./import.js";-import type { OneNoteFolderRef, OneNoteNotebook, OneNoteSection, OneNoteSectionGroup, OneNoteSectionSelection } from "@triliumnext/commons";+import type { OneNoteDeviceLogin, OneNoteDevicePollResult, OneNoteFolderRef, OneNoteNotebook, OneNoteSection, OneNoteSectionGroup, OneNoteSectionSelection } from "@triliumnext/commons";import server from "./server.js";// The notebook/section/selection types are shared with the server; re-export them so existing callers// (the import dialog, tests) keep importing them from this service.-export type { OneNoteFolderRef, OneNoteNotebook, OneNoteSection, OneNoteSectionGroup, OneNoteSectionSelection };+export type { OneNoteDeviceLogin, OneNoteDevicePollResult, OneNoteFolderRef, OneNoteNotebook, OneNoteSection, OneNoteSectionGroup, OneNoteSectionSelection };export interface OneNoteAccount {name: string;@@ -21,8 +21,17 @@ export interface OneNoteStatus {account: OneNoteAccount | null;}-function getAuthUrl() {- return server.get<{ authUrl: string }>("onenote-import/auth-url");+// Starts a device-flow sign-in (RFC 8628): the server obtains a short user code from Microsoft, the+// dialog shows it, and the user enters it at the verification URI in any browser. There is no OAuth+// redirect back to the server, so this works no matter what domain the server is reachable on.+function deviceLogin() {+ return server.post<OneNoteDeviceLogin>("onenote-import/device-login");+}++// One round of asking the server whether the pending device sign-in has completed; called on the+// interval returned by deviceLogin until the result is `connected` or `failed`.+function devicePoll() {+ return server.post<OneNoteDevicePollResult>("onenote-import/device-poll");}function getStatus() {@@ -45,7 +54,8 @@ function runImport(payload: { parentNoteId: string; sections: OneNoteSectionSele}export default {- getAuthUrl,+ deviceLogin,+ devicePoll,getStatus,disconnect,getNotebooks,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 67f90bfe24..a5cadce4eb 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -263,6 +263,9 @@"section_heading": "Microsoft OneNote","checking": "Checking your OneNote connection…","connecting": "Waiting for sign-in to complete…",+ "device_instructions": "Open the Microsoft sign-in page and enter this code:",+ "device_open_page": "Open the sign-in page",+ "device_cancel": "Cancel sign-in","connected_as": "Connected as {{name}}","disconnect": "Disconnect","load_failed": "Could not load your OneNote notebooks.",diff --git a/apps/client/src/widgets/dialogs/import/import_dialog.css b/apps/client/src/widgets/dialogs/import/import_dialog.cssindex 3ffbdf50d6..c4ce2d7736 100644--- a/apps/client/src/widgets/dialogs/import/import_dialog.css+++ b/apps/client/src/widgets/dialogs/import/import_dialog.css@@ -62,6 +62,32 @@gap: 0.5em;}+ .onenote-device-signin {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 0.75em;+ }++ /* The code the user has to carry over to Microsoft's sign-in page: large, monospaced and+ selectable so it is easy to read across windows or copy. */+ .onenote-device-code {+ font-family: var(--monospace-font-family, monospace);+ font-size: 1.6em;+ letter-spacing: 0.15em;+ user-select: all;+ padding: 0.25em 0.6em;+ border: 1px solid var(--main-border-color);+ border-radius: 6px;+ background: var(--accented-background-color);+ }++ .onenote-device-actions {+ display: flex;+ align-items: center;+ gap: 0.5em;+ }+.onenote-notebooks {display: flex;flex-direction: column;diff --git a/apps/client/src/widgets/dialogs/import/onenote.tsx b/apps/client/src/widgets/dialogs/import/onenote.tsxindex b1c58fe231..697fd9361c 100644--- a/apps/client/src/widgets/dialogs/import/onenote.tsx+++ b/apps/client/src/widgets/dialogs/import/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 OneNoteContainer, type OneNoteNotebook, orderedChildren } from "../../../services/onenote_import.js";+import onenoteImport, { buildSectionSelections, type OneNoteAccount, type OneNoteContainer, type OneNoteDeviceLogin, 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";@@ -24,6 +24,8 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPaconst [debug, setDebug] = useState(false);const [compressImages] = useTriliumOptionBool("compressImages");const [shrinkImages, setShrinkImages] = useState(compressImages);+ // Set while a web (device-flow) sign-in is pending; null on desktop, whose sign-in needs no code.+ const [deviceLogin, setDeviceLogin] = useState<OneNoteDeviceLogin | null>(null);const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);const stopPolling = useCallback(() => {@@ -80,31 +82,45 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPareturn;}- const { authUrl } = await onenoteImport.getAuthUrl();- window.open(authUrl, "_blank", "noopener,noreferrer");-+ // Web uses the device flow: a self-hosted server's domain cannot be registered as an OAuth+ // redirect URI, so instead of a callback the user enters a short code at Microsoft's+ // sign-in page while we poll the server until the sign-in completes.+ const login = await onenoteImport.deviceLogin();+ setDeviceLogin(login);setPhase("connecting");stopPolling();pollRef.current = setInterval(async () => {try {- const status = await onenoteImport.getStatus();- if (status.connected) {+ const result = await onenoteImport.devicePoll();+ if (result.status === "connected") {stopPolling();- setAccount(status.account);+ setDeviceLogin(null);+ setAccount(result.account);await loadNotebooks();setPhase("ready");+ } else if (result.status === "failed") {+ stopPolling();+ setDeviceLogin(null);+ toast.showError(result.error);+ setPhase("disconnected");}} catch (e) {// A transient poll failure shouldn't surface a toast on every tick; keep polling.- console.error("Failed to poll OneNote status:", e);+ console.error("Failed to poll OneNote sign-in:", e);}- }, 2000);+ }, (login.intervalSeconds || 5) * 1000);} catch (e) {toast.showError(e instanceof Error ? e.message : String(e));setPhase("disconnected");}}, [loadNotebooks, stopPolling]);+ const cancelSignIn = useCallback(() => {+ stopPolling();+ setDeviceLogin(null);+ setPhase("disconnected");+ }, [stopPolling]);+const disconnect = useCallback(async () => {stopPolling();await onenoteImport.disconnect();@@ -179,9 +195,26 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa<Card heading={t("onenote_import.section_heading")}><CardSection className="onenote-panel"><p>{t("onenote_import.connect_description")}</p>- {phase === "connecting"- ? <p className="onenote-status"><LoadingSpinner /> {t("onenote_import.connecting")}</p>- : <Button text={t("onenote_import.connect")} kind="primary" icon="bxl-microsoft" onClick={connect} />}+ {phase === "connecting" && deviceLogin+ ? (+ <div className="onenote-device-signin">+ <p>{t("onenote_import.device_instructions")}</p>+ <div className="onenote-device-code">{deviceLogin.userCode}</div>+ <div className="onenote-device-actions">+ <Button+ text={t("onenote_import.device_open_page")}+ kind="primary"+ icon="bx-link-external"+ onClick={() => window.open(deviceLogin.verificationUri, "_blank", "noopener,noreferrer")}+ />+ <Button text={t("onenote_import.device_cancel")} kind="lowProfile" onClick={cancelSignIn} />+ </div>+ <p className="onenote-status"><LoadingSpinner /> {t("onenote_import.connecting")}</p>+ </div>+ )+ : phase === "connecting"+ ? <p className="onenote-status"><LoadingSpinner /> {t("onenote_import.connecting")}</p>+ : <Button text={t("onenote_import.connect")} kind="primary" icon="bxl-microsoft" onClick={connect} />}</CardSection></Card>);diff --git a/apps/server/src/express.d.ts b/apps/server/src/express.d.tsindex ec71865b67..6ba2c919df 100644--- a/apps/server/src/express.d.ts+++ b/apps/server/src/express.d.ts@@ -54,14 +54,15 @@ export declare module "express-session" {*/ssoConnectionFailed?: string;/**- * Transient state for the OneNote importer's delegated-Graph OAuth flow. During sign-in it- * holds the PKCE verifier + state + redirect URI; after a successful callback it holds the- * access/refresh tokens and the connected account. Session-scoped only — never synced.+ * Transient state for the OneNote importer's delegated-Graph OAuth device flow. During+ * sign-in it holds the pending device code (the secret the tokens are polled out with — never+ * sent to the browser); once the sign-in completes it holds the access/refresh tokens and the+ * connected account. Session-scoped only — never synced.*/oneNoteImport?: {- verifier?: string;- state?: string;- redirectUri?: string;+ deviceCode?: string;+ /** Epoch millis at which the pending device code expires. */+ deviceCodeExpiresAt?: number;accessToken?: string;refreshToken?: string;expiresAt?: number;diff --git a/apps/server/src/routes/api/onenote_import.spec.ts b/apps/server/src/routes/api/onenote_import.spec.tsnew file mode 100644index 0000000000..cff33171ea--- /dev/null+++ b/apps/server/src/routes/api/onenote_import.spec.ts@@ -0,0 +1,141 @@+import type { Request } from "express";+import { beforeEach, describe, expect, it, vi } from "vitest";++import graph from "../../services/import/onenote/graph.js";+import oauth from "../../services/oauth/oauth.js";+import onenoteImportRoute from "./onenote_import.js";++vi.mock("../../services/oauth/oauth.js", () => ({+ default: {+ requestDeviceCode: vi.fn(),+ pollDeviceToken: vi.fn(),+ refreshAccessToken: vi.fn()+ }+}));++vi.mock("../../services/import/onenote/graph.js", () => ({+ default: {+ getAccount: vi.fn(),+ listNotebooks: vi.fn()+ }+}));++const oauthMock = vi.mocked(oauth);+const graphMock = vi.mocked(graph);++/** A minimal express-session-shaped request: web (non-Electron), with a working save callback. */+function fakeRequest(oneNoteImport?: Request["session"]["oneNoteImport"]): Request {+ const session = {+ oneNoteImport,+ save: (cb: (err?: Error) => void) => cb()+ };+ return { session } as unknown as Request;+}++beforeEach(() => {+ oauthMock.requestDeviceCode.mockReset();+ oauthMock.pollDeviceToken.mockReset();+ graphMock.getAccount.mockReset();+});++describe("deviceLogin", () => {+ it("returns the user-facing codes and keeps the device code secret in the session", async () => {+ oauthMock.requestDeviceCode.mockResolvedValue({+ device_code: "device-secret",+ user_code: "ABCD-1234",+ verification_uri: "https://microsoft.com/devicelogin",+ expires_in: 900,+ interval: 5+ });+ const req = fakeRequest();++ const result = await onenoteImportRoute.deviceLogin(req);++ // The device code is the credential Microsoft polls tokens out with — it must never reach the+ // browser, only the session.+ expect(JSON.stringify(result)).not.toContain("device-secret");+ expect(result).toEqual({+ userCode: "ABCD-1234",+ verificationUri: "https://microsoft.com/devicelogin",+ expiresInSeconds: 900,+ intervalSeconds: 5+ });+ expect(req.session.oneNoteImport?.deviceCode).toBe("device-secret");+ });++ it("discards any previous connection when a new sign-in starts", async () => {+ oauthMock.requestDeviceCode.mockResolvedValue({+ device_code: "device-secret",+ user_code: "ABCD-1234",+ verification_uri: "https://microsoft.com/devicelogin",+ expires_in: 900,+ interval: 5+ });+ const req = fakeRequest({ accessToken: "old-token", account: { name: "Old", email: "[email protected]" } });++ await onenoteImportRoute.deviceLogin(req);++ expect(req.session.oneNoteImport?.accessToken).toBeUndefined();+ expect(req.session.oneNoteImport?.account).toBeUndefined();+ });+});++describe("devicePoll", () => {+ it("rejects a poll with no sign-in in progress", async () => {+ const result = await onenoteImportRoute.devicePoll(fakeRequest());++ expect(result).toEqual([400, expect.stringContaining("No sign-in")]);+ expect(oauthMock.pollDeviceToken).not.toHaveBeenCalled();+ });++ it("reports pending while the user has not finished signing in", async () => {+ oauthMock.pollDeviceToken.mockResolvedValue({ status: "pending" });+ const req = fakeRequest({ deviceCode: "device-secret", deviceCodeExpiresAt: Date.now() + 900_000 });++ const result = await onenoteImportRoute.devicePoll(req);++ expect(result).toEqual({ status: "pending" });+ // The pending state must survive so the next poll can still complete the sign-in.+ expect(req.session.oneNoteImport?.deviceCode).toBe("device-secret");+ });++ it("stores the tokens and account once the sign-in completes", async () => {+ oauthMock.pollDeviceToken.mockResolvedValue({+ status: "success",+ tokens: { token_type: "Bearer", access_token: "access-token", refresh_token: "refresh-token", expires_in: 3600 }+ });+ graphMock.getAccount.mockResolvedValue({ name: "Ada", email: "[email protected]" });+ const req = fakeRequest({ deviceCode: "device-secret", deviceCodeExpiresAt: Date.now() + 900_000 });++ const result = await onenoteImportRoute.devicePoll(req);++ expect(result).toEqual({ status: "connected", account: { name: "Ada", email: "[email protected]" } });+ const stored = req.session.oneNoteImport;+ expect(stored?.accessToken).toBe("access-token");+ expect(stored?.refreshToken).toBe("refresh-token");+ expect(stored?.expiresAt).toBeGreaterThan(Date.now());+ expect(stored?.account).toEqual({ name: "Ada", email: "[email protected]" });+ // The consumed device code must not linger next to the real tokens.+ expect(stored?.deviceCode).toBeUndefined();+ });++ it("fails and clears the pending sign-in on a terminal error (declined, disabled tenant, ...)", async () => {+ oauthMock.pollDeviceToken.mockRejectedValue(new Error("The sign-in was declined."));+ const req = fakeRequest({ deviceCode: "device-secret", deviceCodeExpiresAt: Date.now() + 900_000 });++ const result = await onenoteImportRoute.devicePoll(req);++ expect(result).toEqual({ status: "failed", error: "The sign-in was declined." });+ expect(req.session.oneNoteImport).toBeUndefined();+ });++ it("fails locally once the code has expired, without polling the provider", async () => {+ const req = fakeRequest({ deviceCode: "device-secret", deviceCodeExpiresAt: Date.now() - 1000 });++ const result = await onenoteImportRoute.devicePoll(req);++ expect(result).toEqual({ status: "failed", error: expect.stringContaining("expired") });+ expect(req.session.oneNoteImport).toBeUndefined();+ expect(oauthMock.pollDeviceToken).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.tsindex 32b7e6a286..650c76145e 100644--- a/apps/server/src/routes/api/onenote_import.ts+++ b/apps/server/src/routes/api/onenote_import.ts@@ -1,19 +1,26 @@/**- * REST endpoints for the OneNote importer. Implements the OAuth authorization-code-with-PKCE flow- * (delegated Microsoft Graph access) and the actual import. Tokens live in the user's session only —- * they are never written to the synced options store.+ * REST endpoints for the OneNote importer. Implements the OAuth device authorization grant (delegated+ * Microsoft Graph access) and the actual import. Tokens live in the user's session only — they are+ * never written to the synced options store.+ *+ * The device flow (RFC 8628) is used because a self-hosted server's domain cannot be pre-registered as+ * a redirect URI on the shared app registration, so an authorization-code callback can never come back+ * to it. With the device flow there is no redirect at all: the user enters a short code at Microsoft's+ * sign-in page in any browser while the client polls until the tokens arrive. (The desktop build does+ * not use these sign-in endpoints — it runs an authorization-code flow over a loopback redirect in the+ * Electron main process, which Microsoft matches host-only, and only stores the result here.)** Flow:- * 1. GET /api/onenote-import/auth-url -> { authUrl } (client opens it in a browser)- * 2. GET /api/onenote-import/callback -> browser lands here after sign-in; tokens are stored- * 3. GET /api/onenote-import/status -> { connected, account } (client polls)- * 4. GET /api/onenote-import/notebooks -> { notebooks }- * 5. POST /api/onenote-import/import -> { noteId }+ * 1. POST /api/onenote-import/device-login -> { userCode, verificationUri, ... } (shown to the user)+ * 2. POST /api/onenote-import/device-poll -> { status: pending | connected | failed } (client polls)+ * 3. GET /api/onenote-import/status -> { connected, account }+ * 4. GET /api/onenote-import/notebooks -> { notebooks }+ * 5. POST /api/onenote-import/import -> { noteId }*/-import type { OneNoteSectionSelection } from "@triliumnext/commons";+import type { OneNoteDeviceLogin, OneNoteDevicePollResult, OneNoteSectionSelection } from "@triliumnext/commons";import { becca, ValidationError } from "@triliumnext/core";-import type { Request, Response } from "express";+import type { Request } from "express";import { isInternalElectronRequest } from "../../services/electron_request.js";import { getDesktopSession, type OneNoteTokenSession, setDesktopSession } from "../../services/import/onenote/desktop_session.js";@@ -22,44 +29,63 @@ import importer from "../../services/import/onenote/importer.js";import { ONENOTE_OAUTH } from "../../services/import/onenote/oauth.js";import oauth from "../../services/oauth/oauth.js";-function getAuthUrl(req: Request) {- const { verifier, challenge } = oauth.generatePkce();- const state = oauth.generateState();- const redirectUri = getRedirectUri(req);+async function deviceLogin(req: Request): Promise<OneNoteDeviceLogin> {+ const device = await oauth.requestDeviceCode(ONENOTE_OAUTH);- req.session.oneNoteImport = { verifier, state, redirectUri };+ // Starting a new sign-in discards any previous connection or half-finished attempt. Only the+ // device code (the credential the tokens are polled out with) stays server-side; the browser gets+ // exclusively the user-facing pieces.+ req.session.oneNoteImport = {+ deviceCode: device.device_code,+ deviceCodeExpiresAt: Date.now() + device.expires_in * 1000+ };+ await saveSession(req);- return { authUrl: oauth.buildAuthorizationUrl(ONENOTE_OAUTH, { redirectUri, state, challenge }) };+ return {+ userCode: device.user_code,+ verificationUri: device.verification_uri,+ expiresInSeconds: device.expires_in,+ intervalSeconds: device.interval+ };}-async function callback(req: Request, res: Response) {- res.triliumResponseHandled = true;+async function devicePoll(req: Request): Promise<OneNoteDevicePollResult | [number, string]> {+ const pending = req.session.oneNoteImport;+ if (!pending?.deviceCode) {+ return [400, "No sign-in is in progress."];+ }- try {- const { code, state, error } = req.query as { code?: string; state?: string; error?: string };- const pending = req.session.oneNoteImport;+ const clearPending = async () => {+ delete req.session.oneNoteImport;+ await saveSession(req);+ };- if (error) {- return sendHtml(res, `Sign-in failed: ${error}. You can close this window and try again.`);- }- if (!code || !pending?.verifier || !pending.state || !pending.redirectUri || pending.state !== state) {- return sendHtml(res, "Sign-in could not be completed (invalid or expired state). Please close this window and try again.");- }+ if (pending.deviceCodeExpiresAt && Date.now() > pending.deviceCodeExpiresAt) {+ await clearPending();+ return { status: "failed", error: "The sign-in code expired before the sign-in was completed. Please try again." };+ }- const tokens = await oauth.exchangeCodeForToken(ONENOTE_OAUTH, { code, verifier: pending.verifier, redirectUri: pending.redirectUri });- const account = await graph.getAccount(tokens.access_token);+ try {+ const result = await oauth.pollDeviceToken(ONENOTE_OAUTH, pending.deviceCode);+ if (result.status === "pending") {+ return { status: "pending" };+ }+ const account = await graph.getAccount(result.tokens.access_token);req.session.oneNoteImport = {- accessToken: tokens.access_token,- refreshToken: tokens.refresh_token,- expiresAt: Date.now() + tokens.expires_in * 1000,+ accessToken: result.tokens.access_token,+ refreshToken: result.tokens.refresh_token,+ expiresAt: Date.now() + result.tokens.expires_in * 1000,account};await saveSession(req);- return sendHtml(res, `Connected as ${account.name}. You can close this window and return to Trilium.`);+ return { status: "connected", account };} catch (e) {- return sendHtml(res, `Sign-in failed: ${e instanceof Error ? e.message : String(e)}`);+ // Terminal outcome (declined, expired, tenant policy, ...): the device code is dead, so the+ // pending state is too. The client offers a fresh sign-in rather than continuing to poll.+ await clearPending();+ return { status: "failed", error: e instanceof Error ? e.message : String(e) };}}@@ -104,10 +130,6 @@ async function runImport(req: Request) {return {};}-function getRedirectUri(req: Request): string {- return `${req.protocol}://${req.get("host")}/api/onenote-import/callback`;-}-/** Returns a usable access token, transparently refreshing it when expired, or null if disconnected. */async function getValidAccessToken(req: Request): Promise<string | null> {const store = tokenStore(req);@@ -175,21 +197,9 @@ function saveSession(req: Request): Promise<void> {return new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve())));}-function sendHtml(res: Response, message: string) {- res.status(200).setHeader("Content-Type", "text/html").send(- `<!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);-}-export default {- getAuthUrl,- callback,+ deviceLogin,+ devicePoll,getStatus,disconnect,getNotebooks,diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 24e55816d2..c55babba2a 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -186,10 +186,8 @@ function register(app: express.Application) {// one-time token or a signed signature. The body is not logged.asyncApiRoute(PST, "/api/link-embed/metadata", linkEmbedRoute.getMetadata);- apiRoute(GET, "/api/onenote-import/auth-url", onenoteImportRoute.getAuthUrl);- // Plain GET (no CSRF/auth headers): this is a top-level browser redirect back from Microsoft.- // The OAuth `state` validated against the session is what guards it.- asyncRoute(GET, "/api/onenote-import/callback", [], onenoteImportRoute.callback);+ asyncApiRoute(PST, "/api/onenote-import/device-login", onenoteImportRoute.deviceLogin);+ asyncApiRoute(PST, "/api/onenote-import/device-poll", onenoteImportRoute.devicePoll);apiRoute(GET, "/api/onenote-import/status", onenoteImportRoute.getStatus);asyncApiRoute(PST, "/api/onenote-import/disconnect", onenoteImportRoute.disconnect);asyncApiRoute(GET, "/api/onenote-import/notebooks", onenoteImportRoute.getNotebooks);diff --git a/apps/server/src/services/import/onenote/desktop_session.ts b/apps/server/src/services/import/onenote/desktop_session.tsindex 66b5d8e7b1..15eb1e918d 100644--- a/apps/server/src/services/import/onenote/desktop_session.ts+++ b/apps/server/src/services/import/onenote/desktop_session.ts@@ -1,12 +1,12 @@/*** 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.+ * On the server/web build the token lives in the user's express-session (see onenote_import.ts): the+ * device-flow sign-in is driven entirely by the same browser session that later runs the import, so+ * the session is the natural scope. The desktop build has no such session: it runs an+ * authorization-code flow whose OAuth callback arrives over a throwaway loopback HTTP server in the+ * main process, outside any Express session — the renderer talks to Express over the `trilium-app://`+ * custom protocol — so a session cookie cannot carry the sign-in result.** 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)diff --git a/apps/server/src/services/import/onenote/oauth.ts b/apps/server/src/services/import/onenote/oauth.tsindex a0976fdcc8..2e426dacfe 100644--- a/apps/server/src/services/import/onenote/oauth.ts+++ b/apps/server/src/services/import/onenote/oauth.ts@@ -21,6 +21,7 @@ const AUTHORITY = "https://login.microsoftonline.com/common/oauth2/v2.0";export const ONENOTE_OAUTH: OAuthProviderConfig = {authorizeEndpoint: `${AUTHORITY}/authorize`,tokenEndpoint: `${AUTHORITY}/token`,+ deviceCodeEndpoint: `${AUTHORITY}/devicecode`,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.spec.ts b/apps/server/src/services/oauth/oauth.spec.tsnew file mode 100644index 0000000000..6da32e202b--- /dev/null+++ b/apps/server/src/services/oauth/oauth.spec.ts@@ -0,0 +1,119 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { type OAuthProviderConfig, pollDeviceToken, requestDeviceCode } from "./oauth.js";++const CONFIG: OAuthProviderConfig = {+ authorizeEndpoint: "https://login.example.com/authorize",+ tokenEndpoint: "https://login.example.com/token",+ deviceCodeEndpoint: "https://login.example.com/devicecode",+ clientId: "client-123",+ scopes: "offline_access User.Read Notes.Read"+};++const fetchMock = vi.fn<typeof fetch>();+vi.stubGlobal("fetch", fetchMock);++function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), { status });+}++/** The urlencoded body the mocked fetch received on its `call`-th invocation. */+function sentBody(call = 0): URLSearchParams {+ return new URLSearchParams(String(fetchMock.mock.calls[call]?.[1]?.body));+}++afterEach(() => {+ fetchMock.mockReset();+});++describe("requestDeviceCode", () => {+ it("posts the client id and scopes to the device code endpoint and returns the codes", async () => {+ fetchMock.mockResolvedValue(jsonResponse(200, {+ device_code: "device-secret",+ user_code: "ABCD-1234",+ verification_uri: "https://microsoft.com/devicelogin",+ expires_in: 900,+ interval: 5,+ message: "Go sign in."+ }));++ const result = await requestDeviceCode(CONFIG);++ expect(fetchMock).toHaveBeenCalledWith(CONFIG.deviceCodeEndpoint, expect.objectContaining({ method: "POST" }));+ const body = sentBody();+ expect(body.get("client_id")).toBe("client-123");+ expect(body.get("scope")).toBe("offline_access User.Read Notes.Read");++ expect(result).toEqual({+ device_code: "device-secret",+ user_code: "ABCD-1234",+ verification_uri: "https://microsoft.com/devicelogin",+ expires_in: 900,+ interval: 5,+ message: "Go sign in."+ });+ });++ it("surfaces the provider's error description on failure", async () => {+ fetchMock.mockResolvedValue(jsonResponse(400, { error: "invalid_client", error_description: "Client not enabled for device flow." }));++ await expect(requestDeviceCode(CONFIG)).rejects.toThrow("Client not enabled for device flow.");+ });++ it("falls back to the HTTP status when the response is not JSON (e.g. a proxy error page)", async () => {+ fetchMock.mockResolvedValue(new Response("<html>502</html>", { status: 502 }));++ await expect(requestDeviceCode(CONFIG)).rejects.toThrow("HTTP 502");+ });+});++describe("pollDeviceToken", () => {+ it("exchanges the device code for tokens once the user has signed in", async () => {+ fetchMock.mockResolvedValue(jsonResponse(200, {+ token_type: "Bearer",+ access_token: "access-token",+ refresh_token: "refresh-token",+ expires_in: 3599+ }));++ const result = await pollDeviceToken(CONFIG, "device-secret");++ expect(fetchMock).toHaveBeenCalledWith(CONFIG.tokenEndpoint, expect.objectContaining({ method: "POST" }));+ const body = sentBody();+ expect(body.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:device_code");+ expect(body.get("device_code")).toBe("device-secret");+ expect(body.get("client_id")).toBe("client-123");++ expect(result).toEqual({+ status: "success",+ tokens: expect.objectContaining({ access_token: "access-token", refresh_token: "refresh-token", expires_in: 3599 })+ });+ });++ it("reports pending while the user has not finished signing in", async () => {+ // `authorization_pending` is the normal keep-polling response; `slow_down` also means "not yet"+ // (just poll less eagerly), so both map to pending rather than an error.+ for (const error of ["authorization_pending", "slow_down"]) {+ fetchMock.mockResolvedValue(jsonResponse(400, { error }));+ await expect(pollDeviceToken(CONFIG, "device-secret")).resolves.toEqual({ status: "pending" });+ }+ });++ it("throws a friendly error when the user declined the sign-in", async () => {+ fetchMock.mockResolvedValue(jsonResponse(400, { error: "authorization_declined" }));++ await expect(pollDeviceToken(CONFIG, "device-secret")).rejects.toThrow(/declined/);+ });++ it("throws a friendly error when the code expired before the user signed in", async () => {+ fetchMock.mockResolvedValue(jsonResponse(400, { error: "expired_token" }));++ await expect(pollDeviceToken(CONFIG, "device-secret")).rejects.toThrow(/expired/);+ });++ it("surfaces unexpected token errors with the provider's description", async () => {+ fetchMock.mockResolvedValue(jsonResponse(400, { error: "invalid_grant", error_description: "Device code flow is disabled for this tenant." }));++ await expect(pollDeviceToken(CONFIG, "device-secret")).rejects.toThrow("Device code flow is disabled for this tenant.");+ });+});diff --git a/apps/server/src/services/oauth/oauth.ts b/apps/server/src/services/oauth/oauth.tsindex f6e1dd8eb3..83783229db 100644--- a/apps/server/src/services/oauth/oauth.ts+++ b/apps/server/src/services/oauth/oauth.ts@@ -1,10 +1,12 @@/**- * Generic OAuth 2.0 authorization-code-with-PKCE client for public (no-secret) clients.+ * Generic OAuth 2.0 client for public (no-secret) clients: authorization code with PKCE, plus the+ * device authorization grant (RFC 8628) for deployments where no redirect URI can be registered.** 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).+ * web by the API route (device flow — a self-hosted server's domain cannot be pre-registered as a+ * redirect URI) 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@@ -18,6 +20,8 @@ export interface OAuthProviderConfig {authorizeEndpoint: string;/** The provider's token endpoint (where the code is exchanged and tokens are refreshed). */tokenEndpoint: string;+ /** The provider's device authorization endpoint (where device codes are requested). */+ deviceCodeEndpoint: string;/** The public client id of the registered application. */clientId: string;/** Space-separated scope list requested for the access token. */@@ -32,6 +36,23 @@ export interface TokenResponse {scope?: string;}+/** Response of the device authorization endpoint (RFC 8628 §3.2). */+export interface DeviceCodeResponse {+ /** The long secret the client polls the token endpoint with. Never shown to (or sent to) the user. */+ device_code: string;+ /** The short code the user types at the verification URI. */+ user_code: string;+ verification_uri: string;+ /** Seconds until the device/user code pair expires. */+ expires_in: number;+ /** Minimum seconds the client must wait between token polls. */+ interval: number;+ /** Human-readable sign-in instructions from the provider. */+ message?: string;+}++export type DevicePollResult = { status: "pending" } | { status: "success"; tokens: TokenResponse };+export interface Pkce {verifier: string;challenge: string;@@ -81,27 +102,88 @@ export async function refreshAccessToken(config: OAuthProviderConfig, { refreshT});}+/**+ * Starts a device authorization grant (RFC 8628): asks the provider for a user code + device code+ * pair. The user then signs in at `verification_uri` in any browser while the application polls+ * {@link pollDeviceToken}. No redirect URI is involved, which is the whole point — it works no matter+ * what host the application is served from.+ */+export async function requestDeviceCode(config: OAuthProviderConfig): Promise<DeviceCodeResponse> {+ const { response, json } = await postForm<DeviceCodeResponse>(config.deviceCodeEndpoint, {+ client_id: config.clientId,+ scope: config.scopes+ });+ if (!response.ok || !json.device_code || !json.user_code) {+ throw new Error(`OAuth device code request failed: ${errorDetail(response, json)}`);+ }+ return json as DeviceCodeResponse;+}++/**+ * One poll of the token endpoint for a pending device authorization. Returns `pending` while the user+ * has not finished signing in (the caller schedules the next poll) and the tokens once they have;+ * throws on terminal outcomes (declined, code expired, provider errors).+ */+export async function pollDeviceToken(config: OAuthProviderConfig, deviceCode: string): Promise<DevicePollResult> {+ const { response, json } = await postForm<TokenResponse>(config.tokenEndpoint, {+ client_id: config.clientId,+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",+ device_code: deviceCode+ });++ if (response.ok && json.access_token) {+ return { status: "success", tokens: json as TokenResponse };+ }+ // `slow_down` also means "not finished yet", just polled too eagerly; the poll cadence is driven by+ // the client at the provider's requested interval, so treating it as pending is enough.+ if (json.error === "authorization_pending" || json.error === "slow_down") {+ return { status: "pending" };+ }+ if (json.error === "authorization_declined") {+ throw new Error("The sign-in was declined.");+ }+ if (json.error === "expired_token") {+ throw new Error("The sign-in code expired before the sign-in was completed. Please try again.");+ }+ throw new Error(`OAuth token request failed: ${errorDetail(response, json)}`);+}+async function postToken(config: OAuthProviderConfig, body: Record<string, string>): Promise<TokenResponse> {- const response = await fetch(config.tokenEndpoint, {+ const { response, json } = await postForm<TokenResponse>(config.tokenEndpoint, body);+ if (!response.ok || !json.access_token) {+ throw new Error(`OAuth token request failed: ${errorDetail(response, json)}`);+ }+ return json as TokenResponse;+}++interface OAuthErrorFields {+ error?: string;+ error_description?: string;+}++/**+ * POSTs a urlencoded form and parses the JSON response without throwing on HTTP errors, so callers can+ * inspect the OAuth `error` code (the device flow signals "keep polling" via an error response). The+ * endpoint may also return non-JSON (e.g. a reverse proxy's HTML 502 page); that surfaces as the HTTP+ * status rather than an opaque JSON SyntaxError.+ */+async function postForm<T>(url: string, body: Record<string, string>): Promise<{ response: Response; json: Partial<T> & OAuthErrorFields }> {+ const response = await fetch(url, {method: "POST",headers: { "Content-Type": "application/x-www-form-urlencoded" },body: new URLSearchParams(body).toString()});- // The token endpoint may return a non-JSON error (e.g. a reverse proxy's HTML 502/500 page); parse- // the text ourselves so that surfaces as the HTTP status rather than an opaque JSON SyntaxError.const text = await response.text();- let json: Partial<TokenResponse> & { error?: string; error_description?: string };try {- json = JSON.parse(text);+ return { response, json: JSON.parse(text) };} catch {- throw new Error(`OAuth token request failed: HTTP ${response.status}`);+ return { 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;+}++function errorDetail(response: Response, json: OAuthErrorFields): string {+ return json.error_description || json.error || `HTTP ${response.status}`;}export default {@@ -109,5 +191,7 @@ export default {generateState,buildAuthorizationUrl,exchangeCodeForToken,- refreshAccessToken+ refreshAccessToken,+ requestDeviceCode,+ pollDeviceToken};diff --git a/packages/commons/src/lib/onenote.ts b/packages/commons/src/lib/onenote.tsindex 5bcf870f87..f8b7c1ae18 100644--- a/packages/commons/src/lib/onenote.ts+++ b/packages/commons/src/lib/onenote.ts@@ -4,6 +4,23 @@* rather than relying on two hand-kept copies staying in sync.*/+/** What the client shows the user to complete a device-flow sign-in (RFC 8628). */+export interface OneNoteDeviceLogin {+ /** The short code the user enters at {@link verificationUri}. */+ userCode: string;+ verificationUri: string;+ /** Seconds until the code expires and the sign-in must be restarted. */+ expiresInSeconds: number;+ /** Seconds the client should wait between sign-in polls. */+ intervalSeconds: number;+}++/** One round of polling a pending device-flow sign-in. `failed` is terminal — start a new sign-in. */+export type OneNoteDevicePollResult =+ | { status: "pending" }+ | { status: "connected"; account: { name: string; email: string } }+ | { status: "failed"; error: string };+export interface OneNoteSection {id: string;title: string;