fix(web): derive the OAuth2 redirect from the address actually used
`WEB_PUBLIC_URL` was the only source of the `redirect_uri`, so a hosting panel or a proxy publishing the dashboard on another port produced a link Discord refuses, with nothing on screen pointing at the port mismatch. The browser's own origin is what Discord compares against, so the redirect now comes from the request, honouring `X-Forwarded-Host` and `X-Forwarded-Proto` when a proxy sits in front. `WEB_PUBLIC_URL` stays as the fallback for links built outside a request, and the sign-in page prints the exact value to declare in the portal. The `Secure` cookie flag follows the same rule: announcing HTTPS in the configuration while serving plain HTTP made the browser drop the session. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
7 files changed
+140
-28
No files matched your search
@@ -99,7 +99,7 @@ const readManaged = () =>
|
||||
export function registerSettingsRoutes(router) {
|
||||
router.get(
|
||||
'/api/settings',
|
||||
({ actor }) => ({
|
||||
({ request, actor }) => ({
|
||||
schema: MANAGED_SETTINGS,
|
||||
values: readManaged(),
|
||||
runtime: {
|
||||
@@ -144,7 +144,7 @@ export function registerSettingsRoutes(router) {
|
||||
publicUrl: env.web.publicUrl,
|
||||
sessionTtlHours: env.web.sessionTtlHours,
|
||||
oauthConfigured: isOauthConfigured(),
|
||||
redirectUri: redirectUri(),
|
||||
redirectUri: redirectUri(request),
|
||||
allowCommandDeploys: env.web.allowCommandDeploys,
|
||||
allowRestart: env.web.allowRestart,
|
||||
rateLimitPerMinute: env.web.rateLimitPerMinute,
|
||||
|
||||
@@ -13,18 +13,46 @@ const DISCORD_API = 'https://discord.com/api/v10';
|
||||
*/
|
||||
const SCOPES = ['identify', 'guilds.members.read'];
|
||||
|
||||
export const redirectUri = () => `${env.web.publicUrl}/auth/callback`;
|
||||
/**
|
||||
* Origin the visitor actually reached the dashboard on.
|
||||
*
|
||||
* It is the address in their browser bar that has to match the redirect
|
||||
* declared in the Developer Portal, and a hosting panel or a proxy commonly
|
||||
* publishes the site on a different port than `WEB_PUBLIC_URL` claims.
|
||||
* Trusting the request rather than the configuration avoids a sign-in that
|
||||
* fails on a port mismatch nobody thinks to look at.
|
||||
*/
|
||||
export function requestOrigin(request) {
|
||||
const header = (name) =>
|
||||
String(request?.headers?.[name] ?? '')
|
||||
.split(',')[0]
|
||||
.trim();
|
||||
|
||||
/** True when the OAuth2 login can actually run. */
|
||||
export function isOauthConfigured() {
|
||||
return Boolean(env.discord.clientId && env.web.oauthClientSecret && env.web.publicUrl);
|
||||
const host = header('x-forwarded-host') || header('host');
|
||||
if (!host) return env.web.publicUrl;
|
||||
|
||||
const protocol = header('x-forwarded-proto') || (request.socket?.encrypted ? 'https' : 'http');
|
||||
return `${protocol}://${host}`;
|
||||
}
|
||||
|
||||
export function authorizeUrl(state) {
|
||||
export const redirectUri = (request) => {
|
||||
const origin = requestOrigin(request) || env.web.publicUrl;
|
||||
return origin ? `${origin}/auth/callback` : '';
|
||||
};
|
||||
|
||||
/**
|
||||
* True when the OAuth2 login can run. `WEB_PUBLIC_URL` is not required: the
|
||||
* redirect is derived from the request when one is available.
|
||||
*/
|
||||
export function isOauthConfigured() {
|
||||
return Boolean(env.discord.clientId && env.web.oauthClientSecret);
|
||||
}
|
||||
|
||||
export function authorizeUrl(state, request) {
|
||||
const params = new URLSearchParams({
|
||||
client_id: env.discord.clientId,
|
||||
response_type: 'code',
|
||||
redirect_uri: redirectUri(),
|
||||
redirect_uri: redirectUri(request),
|
||||
scope: SCOPES.join(' '),
|
||||
state,
|
||||
prompt: 'none',
|
||||
@@ -45,13 +73,14 @@ async function discordFetch(endpoint, options = {}) {
|
||||
return response.status === 204 ? null : response.json();
|
||||
}
|
||||
|
||||
export async function exchangeCode(code) {
|
||||
/** Discord checks that this `redirect_uri` is the one used to obtain the code. */
|
||||
export async function exchangeCode(code, request) {
|
||||
const body = new URLSearchParams({
|
||||
client_id: env.discord.clientId,
|
||||
client_secret: env.web.oauthClientSecret,
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: redirectUri(),
|
||||
redirect_uri: redirectUri(request),
|
||||
});
|
||||
|
||||
return discordFetch('/oauth2/token', {
|
||||
|
||||
+16
-7
@@ -12,6 +12,7 @@ import {
|
||||
fetchGuildMember,
|
||||
fetchUser,
|
||||
isOauthConfigured,
|
||||
redirectUri,
|
||||
resolveAccessLevel,
|
||||
revokeToken,
|
||||
} from './discord-oauth.js';
|
||||
@@ -23,26 +24,31 @@ const log = createLogger('web:auth');
|
||||
export function registerAuthRoutes(router) {
|
||||
router.get(
|
||||
'/api/auth/config',
|
||||
({ context }) => ({
|
||||
({ request, context }) => ({
|
||||
oauthConfigured: isOauthConfigured(),
|
||||
setupAvailable: hasSetupToken(),
|
||||
setupOnly: context.setupOnly,
|
||||
guildConfigured: Boolean(env.discord.guildId),
|
||||
loginUrl: '/auth/login',
|
||||
// Shown on the sign-in page: it is the value to declare in the portal.
|
||||
redirectUri: redirectUri(request),
|
||||
}),
|
||||
{ public: true },
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/auth/login',
|
||||
({ response }) => {
|
||||
({ request, response }) => {
|
||||
if (!isOauthConfigured()) {
|
||||
redirect(response, '/#/login?error=oauth-not-configured');
|
||||
return;
|
||||
}
|
||||
const state = signState(randomBytes(16).toString('base64url'));
|
||||
appendCookie(response, serializeCookie(STATE_COOKIE, state, { maxAge: 600, secure: secureCookies() }));
|
||||
redirect(response, authorizeUrl(state));
|
||||
appendCookie(
|
||||
response,
|
||||
serializeCookie(STATE_COOKIE, state, { maxAge: 600, secure: secureCookies(request) }),
|
||||
);
|
||||
redirect(response, authorizeUrl(state, request));
|
||||
},
|
||||
{ public: true },
|
||||
);
|
||||
@@ -56,7 +62,10 @@ export function registerAuthRoutes(router) {
|
||||
|
||||
const state = query.get('state');
|
||||
const expected = parseCookies(request.headers.cookie)[STATE_COOKIE];
|
||||
appendCookie(response, serializeCookie(STATE_COOKIE, '', { maxAge: 0, secure: secureCookies() }));
|
||||
appendCookie(
|
||||
response,
|
||||
serializeCookie(STATE_COOKIE, '', { maxAge: 0, secure: secureCookies(request) }),
|
||||
);
|
||||
if (!state || state !== expected || !verifyState(state)) return failure('state-mismatch');
|
||||
|
||||
const code = query.get('code');
|
||||
@@ -64,9 +73,9 @@ export function registerAuthRoutes(router) {
|
||||
|
||||
let grant;
|
||||
try {
|
||||
grant = await exchangeCode(code);
|
||||
grant = await exchangeCode(code, request);
|
||||
} catch (error) {
|
||||
log.warn('OAuth2 code exchange failed', error);
|
||||
log.warn('OAuth2 code exchange failed', { error, redirectUri: redirectUri(request) });
|
||||
return failure('exchange-failed');
|
||||
}
|
||||
|
||||
|
||||
+30
-5
@@ -30,7 +30,19 @@ const pepper = (() => {
|
||||
|
||||
const hash = (value) => createHmac('sha256', pepper).update(value).digest('hex');
|
||||
|
||||
export const secureCookies = () => env.web.publicUrl.startsWith('https://');
|
||||
/**
|
||||
* A `Secure` cookie is dropped by the browser over plain HTTP, so the flag has
|
||||
* to follow the scheme the visitor actually used rather than what the
|
||||
* configuration announces.
|
||||
*/
|
||||
export const secureCookies = (request) => {
|
||||
const forwarded = String(request?.headers?.['x-forwarded-proto'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim();
|
||||
if (forwarded) return forwarded === 'https';
|
||||
if (request?.socket?.encrypted) return true;
|
||||
return env.web.publicUrl.startsWith('https://');
|
||||
};
|
||||
|
||||
export function issueToken() {
|
||||
return randomBytes(32).toString('base64url');
|
||||
@@ -74,7 +86,7 @@ export function openSession(request, response, { user = {}, accessLevel, source
|
||||
|
||||
appendCookie(
|
||||
response,
|
||||
serializeCookie(SESSION_COOKIE, token, { maxAge: ttlSeconds, secure: secureCookies() }),
|
||||
serializeCookie(SESSION_COOKIE, token, { maxAge: ttlSeconds, secure: secureCookies(request) }),
|
||||
);
|
||||
log.info('Dashboard session opened', { userId: session.user_id, source, accessLevel });
|
||||
return session;
|
||||
@@ -84,7 +96,7 @@ export function closeSession(request, response) {
|
||||
const token = parseCookies(request.headers.cookie)[SESSION_COOKIE];
|
||||
const session = token ? getLiveSessionByHash(hash(token)) : null;
|
||||
if (session) deleteSession(session.id);
|
||||
appendCookie(response, serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: secureCookies() }));
|
||||
appendCookie(response, serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: secureCookies(request) }));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -146,8 +158,21 @@ export function assertSameOrigin(request, actor) {
|
||||
|
||||
const origin = request.headers.origin;
|
||||
if (!origin) return;
|
||||
const host = request.headers.host;
|
||||
const allowed = new Set([env.web.publicUrl, `http://${host}`, `https://${host}`]);
|
||||
|
||||
// The host the visitor used is what the browser puts in `Origin`; behind a
|
||||
// proxy that is the forwarded one, not the socket's.
|
||||
const hosts = [request.headers['x-forwarded-host'], request.headers.host]
|
||||
.map((value) =>
|
||||
String(value ?? '')
|
||||
.split(',')[0]
|
||||
.trim(),
|
||||
)
|
||||
.filter(Boolean);
|
||||
const allowed = new Set([
|
||||
env.web.publicUrl,
|
||||
...hosts.flatMap((host) => [`http://${host}`, `https://${host}`]),
|
||||
]);
|
||||
|
||||
if (!allowed.has(origin.replace(/\/+$/, ''))) {
|
||||
throw forbidden('Requête rejetée : origine inattendue');
|
||||
}
|
||||
|
||||
@@ -6,10 +6,10 @@ import { button, field, input, notice, toast } from '../core/ui.js';
|
||||
|
||||
const ERRORS = {
|
||||
'oauth-not-configured':
|
||||
'La connexion Discord n’est pas configurée. Renseigne `DISCORD_CLIENT_SECRET` et `WEB_PUBLIC_URL`, puis redémarre le bot.',
|
||||
'La connexion Discord n’est pas configurée. Renseigne `DISCORD_CLIENT_SECRET`, puis redémarre le bot.',
|
||||
'state-mismatch': 'La session de connexion a expiré. Réessaie.',
|
||||
'exchange-failed':
|
||||
'Discord a refusé l’échange du code. Vérifie l’URL de redirection déclarée dans le portail.',
|
||||
'Discord a refusé l’échange du code : la redirection déclarée dans le portail ne correspond pas à celle ci-dessous.',
|
||||
'not-a-member': 'Ton compte Discord n’est pas membre du serveur FWS.',
|
||||
'insufficient-level': 'Ton compte n’a pas le rôle Staff, Dev ou Owner sur le serveur.',
|
||||
'missing-code': 'Discord n’a pas renvoyé de code d’autorisation.',
|
||||
@@ -54,6 +54,19 @@ export function render(host, { state }) {
|
||||
'warning',
|
||||
),
|
||||
|
||||
// The redirect is derived from the address in use, so it is the exact
|
||||
// value to paste in the portal — port included.
|
||||
config.redirectUri &&
|
||||
h(
|
||||
'details',
|
||||
{ class: 'muted', style: { textAlign: 'left', width: '100%' } },
|
||||
h('summary', { text: 'Redirection OAuth2 à déclarer dans le Developer Portal' }),
|
||||
h('pre', {}, h('code', { text: config.redirectUri })),
|
||||
h('p', {
|
||||
text: 'Developer Portal → ton application → OAuth2 → Redirects. Elle doit être identique au caractère près, port compris.',
|
||||
}),
|
||||
),
|
||||
|
||||
config.setupAvailable &&
|
||||
h(
|
||||
'div',
|
||||
|
||||
@@ -98,7 +98,8 @@ export const SECTIONS = Object.freeze([
|
||||
'Le tableau de bord réutilise la connexion Discord des membres. Il faut donc déclarer une URL de redirection OAuth2 dans le Developer Portal.',
|
||||
steps: [
|
||||
'Developer Portal → **OAuth2** → copie le **Client Secret** dans `DISCORD_CLIENT_SECRET`.',
|
||||
'Toujours dans **OAuth2 → Redirects**, ajoute exactement `{WEB_PUBLIC_URL}/auth/callback`.',
|
||||
'Toujours dans **OAuth2 → Redirects**, ajoute exactement l’URL affichée dans **Paramètres → Tableau de bord** : c’est l’adresse par laquelle tu ouvres le site, suivie de `/auth/callback`.',
|
||||
'Si le site répond sur un port différent de celui annoncé par ton hébergeur, c’est bien le port que tu utilises dans le navigateur qu’il faut déclarer.',
|
||||
'Génère `WEB_SESSION_SECRET` avec le bouton ci-dessous.',
|
||||
'Laisse `WEB_HOST` sur `127.0.0.1` et place un reverse proxy HTTPS devant, sauf en développement local.',
|
||||
],
|
||||
@@ -457,7 +458,7 @@ export const VARIABLES = Object.freeze([
|
||||
key: 'WEB_PUBLIC_URL',
|
||||
section: 'web',
|
||||
label: 'URL publique',
|
||||
help: 'URL par laquelle les membres accèdent au site. La redirection OAuth2 à déclarer est cette URL suivie de `/auth/callback`.',
|
||||
help: 'URL de partage du site, utilisée dans les liens. La redirection OAuth2 est déduite de l’adresse réellement utilisée par le navigateur : ce champ n’est qu’un repli.',
|
||||
type: 'url',
|
||||
placeholder: 'https://bot.exemple.org',
|
||||
restartRequired: true,
|
||||
@@ -701,7 +702,7 @@ export function crossCheck(values) {
|
||||
if (read('WEB_ENABLED') === 'true') {
|
||||
if (!read('WEB_PUBLIC_URL')) {
|
||||
warnings.push(
|
||||
'Le tableau de bord est activé mais `WEB_PUBLIC_URL` est vide : la connexion Discord échouera.',
|
||||
'Le tableau de bord est activé sans `WEB_PUBLIC_URL` : la connexion Discord fonctionnera, mais les liens partagés vers le site seront incomplets.',
|
||||
);
|
||||
}
|
||||
if (!read('DISCORD_CLIENT_SECRET')) {
|
||||
|
||||
+36
-1
@@ -9,7 +9,7 @@ import {
|
||||
revokeApiToken,
|
||||
} from '../src/database/repositories/web-session-repository.js';
|
||||
import { authorize } from '../src/web/auth/guard.js';
|
||||
import { resolveAccessLevel } from '../src/web/auth/discord-oauth.js';
|
||||
import { redirectUri, requestOrigin, resolveAccessLevel } from '../src/web/auth/discord-oauth.js';
|
||||
import {
|
||||
assertSameOrigin,
|
||||
authenticate,
|
||||
@@ -227,3 +227,38 @@ describe('oauth access level', () => {
|
||||
assert.equal(resolveAccessLevel({ member: null, userId: '2', guildOwnerId: '1', roles }), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('oauth redirect', () => {
|
||||
it('follows the address the visitor actually used', () => {
|
||||
// A hosting panel can publish the site on another port than the one
|
||||
// announced by `WEB_PUBLIC_URL`; the browser's address is what Discord
|
||||
// compares against.
|
||||
const request = fakeRequest({ host: 'bot.example:25571' });
|
||||
assert.equal(requestOrigin(request), 'http://bot.example:25571');
|
||||
assert.equal(redirectUri(request), 'http://bot.example:25571/auth/callback');
|
||||
});
|
||||
|
||||
it('honours a reverse proxy', () => {
|
||||
const request = fakeRequest({
|
||||
host: '127.0.0.1:3080',
|
||||
'x-forwarded-host': 'bot.example',
|
||||
'x-forwarded-proto': 'https',
|
||||
});
|
||||
assert.equal(redirectUri(request), 'https://bot.example/auth/callback');
|
||||
});
|
||||
|
||||
it('keeps only the left-most forwarded value', () => {
|
||||
const request = fakeRequest({
|
||||
host: 'interne:3080',
|
||||
'x-forwarded-host': 'bot.example, interne',
|
||||
'x-forwarded-proto': 'https, http',
|
||||
});
|
||||
assert.equal(requestOrigin(request), 'https://bot.example');
|
||||
});
|
||||
|
||||
it('falls back to the configured URL when there is no request', () => {
|
||||
// `WEB_PUBLIC_URL` is unset in the tests, so nothing can be built.
|
||||
assert.equal(requestOrigin(undefined), '');
|
||||
assert.equal(redirectUri(undefined), '');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user