fix(polar): lift invalid_grant to reauth and harden the credentials surface

classifyPolarError now lifts a 400 carrying invalid_grant on the token
endpoint from persistent to reauth_required, mirroring Oura via the shared
isOAuthInvalidGrant helper. A stale or replayed authorization code at connect
time now surfaces the reconnect prompt instead of silently parking after 24 h.

The BYO-credentials DELETE now audit-logs and parks the integration ledger at
disconnected for parity with the dedicated disconnect route, and the PUT
audit-logs the credential write. Refresh the connect-route comment that still
described Polar as env-only OAuth; it has resolved BYO-first since v1.17.1.

Add the invalid_grant classification test plus the previously-missing
callback (happy path, CSRF mismatch, cross-user, off-spec token), connect, and
credentials route tests.
This commit is contained in:
Marc-André Bombeck committed 2026-06-15 00:09:22 +02:00
1 parent 574b860eb4
commit 87e570abfe
7 files changed
+348 -5

No files matched your search

@@ -0,0 +1,84 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const { storeMock, clearMock, auditMock, markDisconnectedMock } = vi.hoisted(
() => ({
storeMock: vi.fn(),
clearMock: vi.fn(),
auditMock: vi.fn(),
markDisconnectedMock: vi.fn(),
}),
);
vi.mock("@/lib/api-handler", () => ({
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
}));
vi.mock("@/lib/db", () => ({
prisma: { user: { findUnique: vi.fn(), update: vi.fn() } },
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: auditMock }));
vi.mock("@/lib/integrations/status", () => ({
markDisconnected: markDisconnectedMock,
}));
vi.mock("@/lib/polar/credentials", () => ({
storePolarClientCredentials: storeMock,
clearPolarClientCredentials: clearMock,
}));
vi.mock("@/lib/api-response", () => ({
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
apiError: (error: string, status: number) => ({ data: null, error, status }),
safeJson: vi.fn(async (req: { _body: unknown }) => ({
data: req._body,
error: null,
})),
}));
import { PUT, DELETE } from "../route";
import { prisma } from "@/lib/db";
type RouteResult = { data: unknown; error: string | null; status: number };
const userUpdate = prisma.user.update as ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
});
describe("PUT /api/polar/credentials", () => {
it("stores credentials and audit-logs the mutation", async () => {
const req = { _body: { clientId: "cid", clientSecret: "csecret" } };
const put = PUT as unknown as (r: typeof req) => Promise<RouteResult>;
const res = await put(req);
expect(res.status).toBe(200);
expect(storeMock).toHaveBeenCalledWith("u1", "cid", "csecret");
expect(auditMock).toHaveBeenCalledWith("polar.credentials.update", {
userId: "u1",
});
});
it("rejects an invalid body with a 422", async () => {
const req = { _body: { clientId: "" } };
const put = PUT as unknown as (r: typeof req) => Promise<RouteResult>;
const res = await put(req);
expect(res.status).toBe(422);
expect(storeMock).not.toHaveBeenCalled();
});
});
describe("DELETE /api/polar/credentials", () => {
it("clears creds + token and parks the ledger at disconnected", async () => {
const del = DELETE as unknown as () => Promise<RouteResult>;
const res = await del();
expect(res.status).toBe(200);
// The active token + member id are nulled.
expect(userUpdate).toHaveBeenCalledWith({
where: { id: "u1" },
data: { polarAccessTokenEncrypted: null, polarUserIdEncrypted: null },
});
expect(clearMock).toHaveBeenCalledWith("u1");
expect(auditMock).toHaveBeenCalledWith("polar.credentials.delete", {
userId: "u1",
});
expect(markDisconnectedMock).toHaveBeenCalledWith("u1", "polar");
});
});
+10
View File
@@ -1,7 +1,9 @@
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { auditLog } from "@/lib/auth/audit";
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { markDisconnected } from "@/lib/integrations/status";
import {
storePolarClientCredentials,
clearPolarClientCredentials,
@@ -57,12 +59,18 @@ export const PUT = apiHandler(async (request: NextRequest) => {
result.data.clientId,
result.data.clientSecret,
);
await auditLog("polar.credentials.update", { userId: user.id });
return apiSuccess({ updated: true });
});
/**
* Delete Polar credentials and the active connection.
*
* Removing the BYO client id/secret also drops the live grant: a token minted
* under the user's own AccessLink app would be orphaned once the keys are gone.
* Parks the integration ledger at `disconnected` for parity with the dedicated
* disconnect route so the status snapshot does not linger at a stale state.
*/
export const DELETE = apiHandler(async () => {
const { user } = await requireAuth();
@@ -76,6 +84,8 @@ export const DELETE = apiHandler(async () => {
},
});
await clearPolarClientCredentials(user.id);
await auditLog("polar.credentials.delete", { userId: user.id });
await markDisconnected(user.id, "polar");
return apiSuccess({ deleted: true });
});