Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): harden OneNote device-flow sign-in and the import circuit breaker

Elian Doran0392a8427f2b
diff --git a/apps/client/src/widgets/dialogs/import/onenote.tsx b/apps/client/src/widgets/dialogs/import/onenote.tsx
index 697fd9361c..eca3010713 100644
--- a/apps/client/src/widgets/dialogs/import/onenote.tsx
+++ b/apps/client/src/widgets/dialogs/import/onenote.tsx
@@ -26,11 +26,15 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
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 pollRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Bumped whenever polling stops; an in-flight poll compares against it to know it has been
+ // superseded (cancelled, or the sign-in already completed) and must not reschedule.
+ const pollGenRef = useRef(0);
const stopPolling = useCallback(() => {
+ pollGenRef.current++;
if (pollRef.current) {
- clearInterval(pollRef.current);
+ clearTimeout(pollRef.current);
pollRef.current = null;
}
}, []);
@@ -88,27 +92,49 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
const login = await onenoteImport.deviceLogin();
setDeviceLogin(login);
setPhase("connecting");
+
+ // Self-scheduling poll (not setInterval): the next poll is queued only after the current one
+ // resolves, so slow responses never overlap — overlapping polls could race and one clearing
+ // its pending state could wipe another's completed sign-in.
stopPolling();
- pollRef.current = setInterval(async () => {
+ const generation = pollGenRef.current;
+ let intervalMs = (login.intervalSeconds || 5) * 1000;
+
+ const poll = async () => {
+ let result: Awaited<ReturnType<typeof onenoteImport.devicePoll>> | null = null;
try {
- const result = await onenoteImport.devicePoll();
- if (result.status === "connected") {
- stopPolling();
- setDeviceLogin(null);
- setAccount(result.account);
- await loadNotebooks();
- setPhase("ready");
- } else if (result.status === "failed") {
- stopPolling();
- setDeviceLogin(null);
- toast.showError(result.error);
- setPhase("disconnected");
- }
+ result = await onenoteImport.devicePoll();
} catch (e) {
// A transient poll failure shouldn't surface a toast on every tick; keep polling.
console.error("Failed to poll OneNote sign-in:", e);
}
- }, (login.intervalSeconds || 5) * 1000);
+
+ // Bail if this poll loop was superseded (cancelled, or a prior poll already finished).
+ if (pollGenRef.current !== generation) {
+ return;
+ }
+ if (result?.status === "connected") {
+ stopPolling();
+ setDeviceLogin(null);
+ setAccount(result.account);
+ await loadNotebooks();
+ setPhase("ready");
+ return;
+ }
+ if (result?.status === "failed") {
+ stopPolling();
+ setDeviceLogin(null);
+ toast.showError(result.error);
+ setPhase("disconnected");
+ return;
+ }
+ // RFC 8628: on slow_down the provider is asking us to poll less often.
+ if (result?.status === "pending" && result.slowDown) {
+ intervalMs += 5000;
+ }
+ pollRef.current = setTimeout(() => void poll(), intervalMs);
+ };
+ pollRef.current = setTimeout(() => void poll(), intervalMs);
} catch (e) {
toast.showError(e instanceof Error ? e.message : String(e));
setPhase("disconnected");
diff --git a/apps/server/src/routes/api/onenote_import.spec.ts b/apps/server/src/routes/api/onenote_import.spec.ts
index cff33171ea..63f31807a4 100644
--- a/apps/server/src/routes/api/onenote_import.spec.ts
+++ b/apps/server/src/routes/api/onenote_import.spec.ts
@@ -119,6 +119,43 @@ describe("devicePoll", () => {
expect(stored?.deviceCode).toBeUndefined();
});
+ it("keeps the connection when the profile lookup fails after tokens are issued", async () => {
+ // The device code is consumed on success, so the tokens cannot be re-fetched by polling again;
+ // a transient getAccount failure must not throw the just-established connection away.
+ oauthMock.pollDeviceToken.mockResolvedValue({
+ status: "success",
+ tokens: { token_type: "Bearer", access_token: "access-token", refresh_token: "refresh-token", expires_in: 3600 }
+ });
+ graphMock.getAccount.mockRejectedValue(new Error("Graph timed out"));
+ const req = fakeRequest({ deviceCode: "device-secret", deviceCodeExpiresAt: Date.now() + 900_000 });
+
+ const result = await onenoteImportRoute.devicePoll(req);
+
+ expect(result).toEqual({ status: "connected", account: { name: "", email: "" } });
+ // Tokens are persisted despite the profile failure, so the import can proceed.
+ expect(req.session.oneNoteImport?.accessToken).toBe("access-token");
+ expect(req.session.oneNoteImport?.deviceCode).toBeUndefined();
+ });
+
+ it("passes slowDown through so the client can widen its polling interval", async () => {
+ oauthMock.pollDeviceToken.mockResolvedValue({ status: "pending", slowDown: true });
+ const req = fakeRequest({ deviceCode: "device-secret", deviceCodeExpiresAt: Date.now() + 900_000 });
+
+ expect(await onenoteImportRoute.devicePoll(req)).toEqual({ status: "pending", slowDown: true });
+ });
+
+ it("reports the existing connection instead of re-polling a consumed device code", async () => {
+ // Models an overlapping poll: a prior poll already stored the tokens. This one must not poll the
+ // now-dead device code (which would fail and wipe the good session).
+ const req = fakeRequest({ accessToken: "access-token", account: { name: "Ada", email: "[email protected]" }, deviceCode: "device-secret" });
+
+ const result = await onenoteImportRoute.devicePoll(req);
+
+ expect(result).toEqual({ status: "connected", account: { name: "Ada", email: "[email protected]" } });
+ expect(oauthMock.pollDeviceToken).not.toHaveBeenCalled();
+ expect(req.session.oneNoteImport?.accessToken).toBe("access-token");
+ });
+
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 });
diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.ts
index 49e413c0c2..18bb953acd 100644
--- a/apps/server/src/routes/api/onenote_import.ts
+++ b/apps/server/src/routes/api/onenote_import.ts
@@ -19,7 +19,7 @@
*/
import type { OneNoteDeviceLogin, OneNoteDevicePollResult, OneNoteSectionSelection } from "@triliumnext/commons";
-import { becca, ValidationError } from "@triliumnext/core";
+import { becca, getLog, ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import { isInternalElectronRequest } from "../../services/electron_request.js";
@@ -28,7 +28,7 @@ import graph, { type AccessTokenProvider } from "../../services/import/onenote/g
import importer from "../../services/import/onenote/importer.js";
import { ONENOTE_OAUTH } from "../../services/import/onenote/oauth.js";
import { createGraphTokenProvider } from "../../services/import/onenote/token_provider.js";
-import oauth from "../../services/oauth/oauth.js";
+import oauth, { type DevicePollResult } from "../../services/oauth/oauth.js";
async function deviceLogin(req: Request): Promise<OneNoteDeviceLogin> {
const device = await oauth.requestDeviceCode(ONENOTE_OAUTH);
@@ -52,6 +52,12 @@ async function deviceLogin(req: Request): Promise<OneNoteDeviceLogin> {
async function devicePoll(req: Request): Promise<OneNoteDevicePollResult | [number, string]> {
const pending = req.session.oneNoteImport;
+
+ // A concurrent/earlier poll may have already completed the sign-in. Report that instead of polling
+ // the now-consumed device code again (which would fail and could wipe the good tokens).
+ if (pending?.accessToken) {
+ return { status: "connected", account: pending.account ?? EMPTY_ACCOUNT };
+ }
if (!pending?.deviceCode) {
return [400, "No sign-in is in progress."];
}
@@ -66,30 +72,47 @@ async function devicePoll(req: Request): Promise<OneNoteDevicePollResult | [numb
return { status: "failed", error: "The sign-in code expired before the sign-in was completed. Please try again." };
}
+ let result: DevicePollResult;
try {
- const result = await oauth.pollDeviceToken(ONENOTE_OAUTH, pending.deviceCode);
- if (result.status === "pending") {
- return { status: "pending" };
- }
-
- const account = await graph.getAccount(() => Promise.resolve(result.tokens.access_token));
- req.session.oneNoteImport = {
- accessToken: result.tokens.access_token,
- refreshToken: result.tokens.refresh_token,
- expiresAt: Date.now() + result.tokens.expires_in * 1000,
- account
- };
- await saveSession(req);
-
- return { status: "connected", account };
+ result = await oauth.pollDeviceToken(ONENOTE_OAUTH, pending.deviceCode);
} catch (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.
+ // pollDeviceToken throws only on a known terminal outcome (declined, code expired): the device
+ // code is dead, so the pending state is too and the client offers a fresh sign-in. Transient
+ // failures come back as `pending`, never here, so a network blip won't cancel a valid sign-in.
await clearPending();
return { status: "failed", error: e instanceof Error ? e.message : String(e) };
}
+
+ if (result.status === "pending") {
+ return { status: "pending", slowDown: result.slowDown };
+ }
+
+ // Success consumes the device code, so the tokens can't be re-fetched by polling again — persist
+ // them immediately, before the (fallible, non-essential) profile lookup, so a transient failure
+ // there can't discard a completed sign-in.
+ req.session.oneNoteImport = {
+ accessToken: result.tokens.access_token,
+ refreshToken: result.tokens.refresh_token,
+ expiresAt: Date.now() + result.tokens.expires_in * 1000
+ };
+ await saveSession(req);
+
+ let account = EMPTY_ACCOUNT;
+ try {
+ account = await graph.getAccount(() => Promise.resolve(result.tokens.access_token));
+ req.session.oneNoteImport = { ...req.session.oneNoteImport, account };
+ await saveSession(req);
+ } catch (e) {
+ // The connection stands (tokens are stored); only the display name is missing. Leave it blank
+ // rather than failing the whole sign-in over a cosmetic profile fetch.
+ getLog().info(`OneNote sign-in connected but the profile lookup failed: ${e instanceof Error ? e.message : String(e)}`);
+ }
+
+ return { status: "connected", account };
}
+const EMPTY_ACCOUNT = { name: "", email: "" };
+
function getStatus(req: Request) {
const session = tokenStore(req).read();
return { connected: !!session?.accessToken, account: session?.account ?? null };
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.ts
index 213ed02b4d..509954dead 100644
--- a/apps/server/src/services/import/onenote/importer.spec.ts
+++ b/apps/server/src/services/import/onenote/importer.spec.ts
@@ -17,6 +17,19 @@ vi.mock("./graph.js", () => ({
}
}));
+// Delegates to the real converter, but lets a test force a content-processing failure for pages whose
+// HTML carries the sentinel — the way to exercise "fetched fine, but processing threw".
+vi.mock("./converter.js", async (importActual) => {
+ const actual = await importActual<typeof import("./converter.js")>();
+ const convertPageHtml = (html: string) => {
+ if (html.includes("PROCESSING_BOOM")) {
+ throw new Error("content conversion failed");
+ }
+ return actual.convertPageHtml(html);
+ };
+ return { ...actual, default: { ...actual.default, convertPageHtml } };
+});
+
const graphMock = vi.mocked(graph);
describe("resolveSubpageParents", () => {
@@ -214,4 +227,37 @@ describe("importSelection (real DB)", () => {
expect(graphMock.getPageContent).toHaveBeenCalledTimes(6);
expect(parent.getChildNotes()).toHaveLength(0);
});
+
+ it("does not trip the breaker when pages fetch but fail local processing", async () => {
+ // All eight pages fetch successfully (Graph is healthy) but every one fails to convert. These
+ // are isolated bad pages, not a systemic outage, so the import must finish with placeholders
+ // rather than aborting the way a run of fetch failures does.
+ graphMock.listPages.mockResolvedValue(
+ Array.from({ length: 8 }, (_, i) => ({ id: `1-pf${i}`, title: `PF Page ${i}`, level: 0 }))
+ );
+ graphMock.getPageContent.mockClear();
+ graphMock.getPageContent.mockResolvedValue({ html: "<p>PROCESSING_BOOM</p>", inkml: "" });
+
+ const parent = cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "processing failure parent",
+ content: "",
+ type: "text",
+ mime: "text/html"
+ }).note);
+
+ await cls.init(() => importSelection({
+ getAccessToken: () => Promise.resolve("token"),
+ parentNoteId: parent.noteId,
+ sections: [{ id: "sec-5", title: "PF Section", groupPath: [], notebookId: "nb-5", notebookTitle: "PF Notebook" }],
+ taskId: "task-processing-failure"
+ }));
+
+ // Every page was fetched (no early abort) and imported as a placeholder.
+ expect(graphMock.getPageContent).toHaveBeenCalledTimes(8);
+ const pages = new Map(Object.values(becca.notes).filter((note) => /^PF Page \d+$/.test(note.title)).map((note) => [note.noteId, note]));
+ expect(pages.size).toBe(8);
+ expect([...pages.values()].every((note) => note.hasOwnedLabel("oneNoteImportFailed"))).toBe(true);
+ expect([...pages.values()][0]?.getContent()).toContain("could not be imported");
+ });
});
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index ab386e59e4..1f0087dfde 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -109,11 +109,15 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
for (const { section, pages } of sectionPages) {
const fetchedPages: FetchedPage[] = [];
for (const page of pages) {
+ // The Graph fetch and the local processing (HTML/InkML conversion, resource discovery)
+ // are guarded separately. Only a failed *fetch* counts toward the circuit breaker: a run
+ // of fetch failures means a systemic problem (expired auth, Graph outage) worth aborting
+ // for, whereas a page that fetches but fails to convert is an isolated bad page that must
+ // become a placeholder without dragging the whole import down.
+ let rawHtml: string;
+ let inkml: string;
try {
- const { html: rawHtml, inkml } = await graph.getPageContent(getAccessToken, page.id);
- const html = converter.convertPageHtml(rawHtml);
- const { resources, failedResourceCount } = await downloadPageResources(getAccessToken, page.title, html);
- fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, failedResourceCount, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
+ ({ html: rawHtml, inkml } = await graph.getPageContent(getAccessToken, page.id));
consecutivePageFailures = 0;
} catch (e: unknown) {
consecutivePageFailures++;
@@ -122,7 +126,19 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
if (consecutivePageFailures > MAX_CONSECUTIVE_PAGE_FAILURES) {
throw new Error(`Aborting the OneNote import: ${consecutivePageFailures} pages in a row failed to fetch, which points to a systemic problem rather than individual broken pages. Last error: ${message}`);
}
- fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html: "", rawHtml: "", rawInkml: "", inkSvg: null, resources: [], failedResourceCount: 0, fetchError: message, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
+ fetchedPages.push(buildPlaceholderPage(page, message));
+ taskContext.increaseProgressCount();
+ continue;
+ }
+
+ try {
+ const html = converter.convertPageHtml(rawHtml);
+ const { resources, failedResourceCount } = await downloadPageResources(getAccessToken, page.title, html);
+ fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, failedResourceCount, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
+ } catch (e: unknown) {
+ const message = e instanceof Error ? e.message : String(e);
+ getLog().error(`OneNote import: fetched page '${page.title}' (${page.id}) but could not process its content; a placeholder note will be imported instead: ${message}`);
+ fetchedPages.push(buildPlaceholderPage(page, message));
}
taskContext.increaseProgressCount();
}
@@ -149,6 +165,12 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
}
}
+/** A content-less stand-in for a page that could not be fetched or processed; imported so the tree and
+ * cross-page links stay intact and the failure is reported (see {@link FetchedPage.fetchError}). */
+function buildPlaceholderPage(page: OneNotePage, error: string): FetchedPage {
+ return { id: page.id, title: page.title, level: page.level, pageId: page.pageId, html: "", rawHtml: "", rawInkml: "", inkSvg: null, resources: [], failedResourceCount: 0, fetchError: error, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime };
+}
+
function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean, shrinkImages: boolean, startedAtMs: number): string {
const parentNote = becca.getNoteOrThrow(parentNoteId);
const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();
diff --git a/apps/server/src/services/oauth/oauth.spec.ts b/apps/server/src/services/oauth/oauth.spec.ts
index 6da32e202b..756f4c71ae 100644
--- a/apps/server/src/services/oauth/oauth.spec.ts
+++ b/apps/server/src/services/oauth/oauth.spec.ts
@@ -93,16 +93,20 @@ describe("pollDeviceToken", () => {
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" });
- }
+ fetchMock.mockResolvedValue(jsonResponse(400, { error: "authorization_pending" }));
+ 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" }));
+ it("reports pending with slowDown so the caller widens its polling interval", async () => {
+ fetchMock.mockResolvedValue(jsonResponse(400, { error: "slow_down" }));
+ await expect(pollDeviceToken(CONFIG, "device-secret")).resolves.toEqual({ status: "pending", slowDown: true });
+ });
- await expect(pollDeviceToken(CONFIG, "device-secret")).rejects.toThrow(/declined/);
+ it("throws a friendly error when the user declined (authorization_declined or access_denied)", async () => {
+ for (const error of ["authorization_declined", "access_denied"]) {
+ fetchMock.mockResolvedValue(jsonResponse(400, { error }));
+ await expect(pollDeviceToken(CONFIG, "device-secret")).rejects.toThrow(/declined/);
+ }
});
it("throws a friendly error when the code expired before the user signed in", async () => {
@@ -111,9 +115,19 @@ describe("pollDeviceToken", () => {
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." }));
+ it("keeps polling (does not abandon the sign-in) on a transient network failure", async () => {
+ fetchMock.mockRejectedValue(new Error("ECONNRESET"));
+
+ await expect(pollDeviceToken(CONFIG, "device-secret")).resolves.toEqual({ status: "pending" });
+ });
+
+ it("keeps polling on an unrecognised or 5xx error rather than treating it as terminal", async () => {
+ // A server-side hiccup at the token endpoint must not kill an otherwise valid sign-in; only the
+ // known terminal outcomes (declined, expired) end it.
+ fetchMock.mockResolvedValue(jsonResponse(500, { error: "temporarily_unavailable" }));
+ await expect(pollDeviceToken(CONFIG, "device-secret")).resolves.toEqual({ status: "pending" });
- await expect(pollDeviceToken(CONFIG, "device-secret")).rejects.toThrow("Device code flow is disabled for this tenant.");
+ fetchMock.mockResolvedValue(new Response("<html>502 Bad Gateway</html>", { status: 502 }));
+ await expect(pollDeviceToken(CONFIG, "device-secret")).resolves.toEqual({ status: "pending" });
});
});
diff --git a/apps/server/src/services/oauth/oauth.ts b/apps/server/src/services/oauth/oauth.ts
index 83783229db..5893c9af87 100644
--- a/apps/server/src/services/oauth/oauth.ts
+++ b/apps/server/src/services/oauth/oauth.ts
@@ -51,7 +51,10 @@ export interface DeviceCodeResponse {
message?: string;
}
-export type DevicePollResult = { status: "pending" } | { status: "success"; tokens: TokenResponse };
+export type DevicePollResult =
+ /** Not finished yet — poll again. `slowDown` asks the caller to widen its polling interval. */
+ | { status: "pending"; slowDown?: boolean }
+ | { status: "success"; tokens: TokenResponse };
export interface Pkce {
verifier: string;
@@ -121,31 +124,47 @@ export async function requestDeviceCode(config: OAuthProviderConfig): Promise<De
/**
* 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).
+ * has not finished signing in (the caller schedules the next poll) and the tokens once they have.
+ *
+ * Only a *known terminal* OAuth outcome throws (the user declined, or the code expired) — these mean
+ * the device code is dead and the sign-in must restart. Everything else the caller can't recover from
+ * a single failed poll — a network blip, a 5xx from the token endpoint, an unrecognised error — is
+ * reported as `pending` so a transient hiccup does not abandon an otherwise valid sign-in; the device
+ * code's own expiry bounds how long polling can continue.
*/
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
- });
+ let response: Response;
+ let json: Partial<TokenResponse> & OAuthErrorFields;
+ try {
+ ({ response, json } = await postForm<TokenResponse>(config.tokenEndpoint, {
+ client_id: config.clientId,
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
+ device_code: deviceCode
+ }));
+ } catch {
+ // Couldn't reach the token endpoint at all: transient, keep polling.
+ return { status: "pending" };
+ }
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") {
+ // `slow_down` means "keep polling, but less often" — ask the caller to widen its interval (RFC 8628).
+ if (json.error === "slow_down") {
+ return { status: "pending", slowDown: true };
+ }
+ if (json.error === "authorization_pending") {
return { status: "pending" };
}
- if (json.error === "authorization_declined") {
+ if (json.error === "authorization_declined" || json.error === "access_denied") {
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)}`);
+ // Anything else (5xx, a transient proxy error, an unrecognised code) is not a proven terminal
+ // outcome, so keep polling rather than discarding the sign-in on one bad response.
+ return { status: "pending" };
}
async function postToken(config: OAuthProviderConfig, body: Record<string, string>): Promise<TokenResponse> {
diff --git a/packages/commons/src/lib/onenote.ts b/packages/commons/src/lib/onenote.ts
index f8b7c1ae18..5934f5b9ca 100644
--- a/packages/commons/src/lib/onenote.ts
+++ b/packages/commons/src/lib/onenote.ts
@@ -17,7 +17,8 @@ export interface OneNoteDeviceLogin {
/** One round of polling a pending device-flow sign-in. `failed` is terminal — start a new sign-in. */
export type OneNoteDevicePollResult =
- | { status: "pending" }
+ /** Not finished yet — poll again; `slowDown` asks the client to widen its polling interval. */
+ | { status: "pending"; slowDown?: boolean }
| { status: "connected"; account: { name: string; email: string } }
| { status: "failed"; error: string };