refactor(integrations): start and end every OAuth connection through the kit

Minting the state, building the consent URL and dropping a grant each had a
copy per provider route. The routes keep their auth, rate limits and
redirects and hand the rest to one implementation, which the managed-profile
routes reuse.
This commit is contained in:
Marc-André Bombeck committed 2026-10-21 19:49:06 +02:00
1 parent b60fa0123b
commit 65e0cba0bf
14 files changed
+483 -344

No files matched your search

+17 -41
View File
@@ -1,17 +1,12 @@
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { prisma } from "@/lib/db";
import { annotate, getEvent } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { getAuthorizationUrl } from "@/lib/withings/client";
import { getUserWithingsCredentials } from "@/lib/withings/credentials";
import {
WITHINGS_OAUTH_STATE_COOKIE,
WITHINGS_OAUTH_STATE_TTL_MS,
mintWithingsOAuthStateNonce,
} from "@/lib/withings/oauth-state";
setConnectStateCookie,
startOAuthConnect,
} from "@/lib/integrations/oauth-kit/connect-start";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { NextRequest, NextResponse } from "next/server";
import { relativeRedirect } from "@/lib/http/relative-redirect";
import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
/**
* Redirects the user to Withings OAuth authorization page.
@@ -62,41 +57,22 @@ export const GET = apiHandler(async (req: NextRequest) => {
);
}
const creds = await getUserWithingsCredentials(user.id);
if (!creds) {
annotate({ action: { name: "withings.connect.no_credentials" } });
return relativeRedirect(
"/settings/integrations?withings=error&reason=nocreds",
);
}
const nonce = mintWithingsOAuthStateNonce();
try {
await prisma.withingsOAuthState.create({
data: {
nonce,
userId: user.id,
expiresAt: new Date(Date.now() + WITHINGS_OAUTH_STATE_TTL_MS),
},
});
} catch (err) {
getEvent()?.setError(err);
const started = await startOAuthConnect("withings", user.id);
if (!started.ok) {
if (started.reason === "nocreds") {
annotate({ action: { name: "withings.connect.no_credentials" } });
return relativeRedirect(
"/settings/integrations?withings=error&reason=nocreds",
);
}
annotate({ action: { name: "withings.connect.create_failed" } });
return relativeRedirect(
"/settings/integrations?withings=error&reason=connect",
);
}
const url = getAuthorizationUrl(nonce, creds);
const response = NextResponse.redirect(url);
response.cookies.set(WITHINGS_OAUTH_STATE_COOKIE, nonce, {
httpOnly: true,
secure: shouldEmitSecureCookie(),
sameSite: "lax",
maxAge: Math.floor(WITHINGS_OAUTH_STATE_TTL_MS / 1000),
path: "/",
});
return response;
return setConnectStateCookie(
NextResponse.redirect(started.authorizationUrl),
started.cookie,
);
});
+2 -41
View File
@@ -1,15 +1,7 @@
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { auditLog } from "@/lib/auth/audit";
import { disconnectOAuth } from "@/lib/integrations/oauth-kit/disconnect";
import { apiSuccess, apiError } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { decrypt } from "@/lib/crypto";
import { unsubscribeWebhook } from "@/lib/withings/client";
import {
WITHINGS_NOTIFY_APPLIS,
getWithingsWebhookCallbackUrl,
} from "@/lib/withings/sync";
import { markDisconnected } from "@/lib/integrations/status";
/**
* Disconnect Withings integration for the current user.
@@ -18,40 +10,9 @@ export const POST = apiHandler(async () => {
const { user } = await requireAuth();
annotate({ action: { name: "withings.disconnect" } });
const connection = await prisma.withingsConnection.findUnique({
where: { userId: user.id },
});
if (!connection) {
if ((await disconnectOAuth("withings", user.id)) === "not_connected") {
return apiError("No Withings connection", 404);
}
// Best-effort unsubscribe across every appli category we subscribed
// to in setupWebhook. A token-expired failure on one category should
// not stop us from cleaning up the others.
try {
const accessToken = decrypt(connection.accessToken);
const callbackUrl = getWithingsWebhookCallbackUrl();
for (const appli of WITHINGS_NOTIFY_APPLIS) {
try {
await unsubscribeWebhook(accessToken, callbackUrl, appli);
} catch {
// Ignore — token might be expired or the appli was never subscribed.
}
}
} catch {
// Ignore — token might be undecryptable.
}
await prisma.withingsConnection.delete({
where: { userId: user.id },
});
await auditLog("withings.disconnect", {
userId: user.id,
});
await markDisconnected(user.id, "withings");
return apiSuccess({ disconnected: true });
});