Resolve OAuth callback URLs on the server for integration cards

The v1.38.0 notice that warns when the configured OAuth callback origin
differs from the origin the browser is on never rendered in the published
image, and the copyable callback address in the redirect guide showed a
bare path. `integrationCallbackUrl()` read `process.env.NEXT_PUBLIC_APP_URL`
inside a "use client" module. Next.js inlines NEXT_PUBLIC_* into client
bundles at build time, and the GHCR image is built without that variable
(only the version, build-sha and built-at args reach the build), so the
base compiled to an empty string, `new URL("/api/<provider>/callback")`
threw, and the notice returned null on every card for every self-hoster.

The value now comes from the server at request time. A new map
(`src/lib/integrations/callback-urls.ts`) calls each provider's own
redirect-URI function (the four private `getRedirectUri()` helpers are
exported under provider-specific names; Polar, Oura and Strava already
exported theirs), so the page shows exactly what the handshake registers,
explicit `*_REDIRECT_URI` override included. The settings route resolves
the map and passes it as a prop through `IntegrationsSection` and
`ConnectionsPanel` to every card. Fitbit and Google Health validate their
URI and throw on a bad configuration; that surfaces as `null`, the notice
skips the comparison and the guide falls back to the fixed path.

Tests: a map test proving the explicit override wins and the derived form
is used otherwise, a component test rendering the notice from a passed
value (mismatch renders, match does not), and a structural guard that
fails when any "use client" file under src/components/settings/integrations
reads NEXT_PUBLIC_APP_URL.
This commit is contained in:
Marc-André Bombeck committed 2026-09-01 21:00:12 +02:00
1 parent 97b1603cb9
commit 05d3736d75
25 files changed
+516 -57

No files matched your search

+3 -3
View File
@@ -75,7 +75,7 @@ export interface FitbitCredentials {
* - must land on the fixed `/api/fitbit/callback` path,
* - when derived from `NEXT_PUBLIC_APP_URL`, must stay same-origin with it.
*/
function getRedirectUri(): string {
export function getFitbitRedirectUri(): string {
const explicit = process.env.FITBIT_REDIRECT_URI;
const appUrl = process.env.NEXT_PUBLIC_APP_URL;
const raw =
@@ -188,7 +188,7 @@ export function getAuthorizationUrl(
const params = new URLSearchParams({
response_type: "code",
client_id: creds.clientId,
redirect_uri: getRedirectUri(),
redirect_uri: getFitbitRedirectUri(),
scope: FITBIT_OAUTH_SCOPE,
code_challenge: codeChallenge,
code_challenge_method: "S256",
@@ -287,7 +287,7 @@ export async function exchangeCode(
grant_type: "authorization_code",
code,
client_id: creds.clientId,
redirect_uri: getRedirectUri(),
redirect_uri: getFitbitRedirectUri(),
code_verifier: codeVerifier,
}),
creds,
+3 -3
View File
@@ -146,7 +146,7 @@ export interface GoogleHealthCredentials {
* - must land on the fixed `/api/google-health/callback` path,
* - when derived from `NEXT_PUBLIC_APP_URL`, must stay same-origin with it.
*/
function getRedirectUri(): string {
export function getGoogleHealthRedirectUri(): string {
const explicit = process.env.GOOGLE_HEALTH_REDIRECT_URI;
const appUrl = process.env.NEXT_PUBLIC_APP_URL;
const raw =
@@ -276,7 +276,7 @@ export function getAuthorizationUrl(
const params = new URLSearchParams({
response_type: "code",
client_id: creds.clientId,
redirect_uri: getRedirectUri(),
redirect_uri: getGoogleHealthRedirectUri(),
scope: getGoogleHealthScopeString(),
access_type: "offline",
prompt: "consent",
@@ -371,7 +371,7 @@ export async function exchangeCode(
grant_type: "authorization_code",
code,
client_id: creds.clientId,
redirect_uri: getRedirectUri(),
redirect_uri: getGoogleHealthRedirectUri(),
code_verifier: codeVerifier,
}),
creds,
@@ -0,0 +1,113 @@
/**
* `getIntegrationCallbackUrls()` must hand the Settings → Integrations cards
* the exact `redirect_uri` each provider's client registers: the explicit
* `<PROVIDER>_REDIRECT_URI` when the operator set one, the
* `${NEXT_PUBLIC_APP_URL}/api/<provider>/callback` form otherwise. The map
* goes through the provider functions themselves rather than restating the
* rule, so this test pins that the wiring reaches every provider and that a
* provider whose validation throws surfaces as `null` instead of taking the
* page down.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
INTEGRATION_CALLBACK_PROVIDERS,
getIntegrationCallbackUrls,
} from "../callback-urls";
const OVERRIDE_VARS: Record<
(typeof INTEGRATION_CALLBACK_PROVIDERS)[number],
string
> = {
withings: "WITHINGS_REDIRECT_URI",
whoop: "WHOOP_REDIRECT_URI",
fitbit: "FITBIT_REDIRECT_URI",
"google-health": "GOOGLE_HEALTH_REDIRECT_URI",
polar: "POLAR_REDIRECT_URI",
oura: "OURA_REDIRECT_URI",
strava: "STRAVA_REDIRECT_URI",
};
const TOUCHED = ["NEXT_PUBLIC_APP_URL", ...Object.values(OVERRIDE_VARS)];
let saved: Record<string, string | undefined>;
beforeEach(() => {
saved = Object.fromEntries(TOUCHED.map((k) => [k, process.env[k]]));
for (const k of TOUCHED) delete process.env[k];
});
afterEach(() => {
for (const k of TOUCHED) {
if (saved[k] === undefined) delete process.env[k];
else process.env[k] = saved[k];
}
});
describe("getIntegrationCallbackUrls", () => {
it("derives ${NEXT_PUBLIC_APP_URL}/api/<provider>/callback when nothing overrides it", () => {
process.env.NEXT_PUBLIC_APP_URL = "https://health.example";
const urls = getIntegrationCallbackUrls();
for (const provider of INTEGRATION_CALLBACK_PROVIDERS) {
expect(urls[provider], provider).toBe(
`https://health.example/api/${provider}/callback`,
);
}
});
it("lets the explicit <PROVIDER>_REDIRECT_URI win over the derived form", () => {
// Withings / WHOOP / Polar / Oura / Strava accept any explicit value.
process.env.NEXT_PUBLIC_APP_URL = "https://health.example";
for (const provider of [
"withings",
"whoop",
"polar",
"oura",
"strava",
] as const) {
process.env[OVERRIDE_VARS[provider]] =
`https://edge.example/api/${provider}/callback`;
}
const urls = getIntegrationCallbackUrls();
for (const provider of [
"withings",
"whoop",
"polar",
"oura",
"strava",
] as const) {
expect(urls[provider], provider).toBe(
`https://edge.example/api/${provider}/callback`,
);
}
// No override for these two, so they still derive.
expect(urls.fitbit).toBe("https://health.example/api/fitbit/callback");
expect(urls["google-health"]).toBe(
"https://health.example/api/google-health/callback",
);
});
it("uses the explicit Fitbit / Google Health override when the app URL is unset", () => {
// Those two pin an explicit override to the app origin when both are set;
// with only the override present it is taken verbatim.
process.env.FITBIT_REDIRECT_URI =
"https://edge.example/api/fitbit/callback";
process.env.GOOGLE_HEALTH_REDIRECT_URI =
"https://edge.example/api/google-health/callback";
const urls = getIntegrationCallbackUrls();
expect(urls.fitbit).toBe("https://edge.example/api/fitbit/callback");
expect(urls["google-health"]).toBe(
"https://edge.example/api/google-health/callback",
);
});
it("reports null for a provider whose redirect URI fails validation, leaving the rest intact", () => {
// Fitbit refuses a plain-http, non-loopback origin; the others do not
// validate and keep deriving.
process.env.NEXT_PUBLIC_APP_URL = "http://health.example";
const urls = getIntegrationCallbackUrls();
expect(urls.fitbit).toBeNull();
expect(urls["google-health"]).toBeNull();
expect(urls.withings).toBe("http://health.example/api/withings/callback");
expect(urls.whoop).toBe("http://health.example/api/whoop/callback");
});
});
+78
View File
@@ -0,0 +1,78 @@
/**
* The OAuth callback URL each BYO-key provider registers, resolved on the
* server at request time.
*
* Settings → Integrations shows two things built from this value: the
* copyable callback address in the redirect guide, and the notice that warns
* when the configured callback origin differs from the origin the browser is
* on. Both used to read `process.env.NEXT_PUBLIC_APP_URL` inside a
* `"use client"` module. Next.js inlines `NEXT_PUBLIC_*` into client bundles
* at build time, and the published image is built without that variable, so
* every self-hoster's bundle carried an empty base: the guide showed a bare
* path and the notice never rendered. Resolving here, in server code, reads
* the runtime env the operator actually set.
*
* Each entry is the exact value the provider's client sends as `redirect_uri`
* on the wire, through the same function, so what the page shows and what the
* handshake registers cannot drift apart. Fitbit and Google Health validate
* their URI and throw on a malformed configuration; here that surfaces as
* `null` (nothing would be registered), and the cards fall back to the fixed
* path for the guide and skip the origin comparison.
*/
import { getFitbitRedirectUri } from "@/lib/fitbit/client";
import { getGoogleHealthRedirectUri } from "@/lib/google-health/client";
import { getOuraRedirectUri } from "@/lib/oura/client";
import { getPolarRedirectUri } from "@/lib/polar/client";
import { getStravaRedirectUri } from "@/lib/strava/client";
import { getWhoopRedirectUri } from "@/lib/whoop/client";
import { getWithingsRedirectUri } from "@/lib/withings/client";
export const INTEGRATION_CALLBACK_PROVIDERS = [
"withings",
"whoop",
"fitbit",
"google-health",
"polar",
"oura",
"strava",
] as const;
export type IntegrationCallbackProvider =
(typeof INTEGRATION_CALLBACK_PROVIDERS)[number];
/** `null` when the provider cannot produce a redirect URI from the current env. */
export type IntegrationCallbackUrls = Record<
IntegrationCallbackProvider,
string | null
>;
const RESOLVERS: Record<IntegrationCallbackProvider, () => string> = {
withings: getWithingsRedirectUri,
whoop: getWhoopRedirectUri,
fitbit: getFitbitRedirectUri,
"google-health": getGoogleHealthRedirectUri,
polar: getPolarRedirectUri,
oura: getOuraRedirectUri,
strava: getStravaRedirectUri,
};
function resolve(provider: IntegrationCallbackProvider): string | null {
try {
return RESOLVERS[provider]();
} catch {
return null;
}
}
export function getIntegrationCallbackUrls(): IntegrationCallbackUrls {
return {
withings: resolve("withings"),
whoop: resolve("whoop"),
fitbit: resolve("fitbit"),
"google-health": resolve("google-health"),
polar: resolve("polar"),
oura: resolve("oura"),
strava: resolve("strava"),
};
}
+3 -3
View File
@@ -32,7 +32,7 @@ export interface WhoopCredentials {
clientSecret: string;
}
function getRedirectUri(): string {
export function getWhoopRedirectUri(): string {
// `||`, not `??`: the compose whitelist materialises the var as an empty
// string when unset, which must still fall through to the derived URI.
return (
@@ -61,7 +61,7 @@ export function getAuthorizationUrl(
const params = new URLSearchParams({
response_type: "code",
client_id: creds.clientId,
redirect_uri: getRedirectUri(),
redirect_uri: getWhoopRedirectUri(),
scope: WHOOP_OAUTH_SCOPE,
state,
});
@@ -119,7 +119,7 @@ export async function exchangeCode(
code,
client_id: creds.clientId,
client_secret: creds.clientSecret,
redirect_uri: getRedirectUri(),
redirect_uri: getWhoopRedirectUri(),
}),
"exchangeCode",
);
+3 -3
View File
@@ -20,7 +20,7 @@ export interface WithingsCredentials {
clientSecret: string;
}
function getRedirectUri(): string {
export function getWithingsRedirectUri(): string {
return (
process.env.WITHINGS_REDIRECT_URI ??
`${process.env.NEXT_PUBLIC_APP_URL}/api/withings/callback`
@@ -79,7 +79,7 @@ export function getAuthorizationUrl(
const params = new URLSearchParams({
response_type: "code",
client_id: creds.clientId,
redirect_uri: getRedirectUri(),
redirect_uri: getWithingsRedirectUri(),
scope: WITHINGS_OAUTH_SCOPE,
state,
});
@@ -105,7 +105,7 @@ export async function exchangeCode(
grant_type: "authorization_code",
client_id: creds.clientId,
client_secret: creds.clientSecret,
redirect_uri: getRedirectUri(),
redirect_uri: getWithingsRedirectUri(),
code,
});