`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>
265 lines
9.0 KiB
JavaScript
265 lines
9.0 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { after, before, beforeEach, describe, it } from 'node:test';
|
|
import { ACCESS_LEVELS } from '../src/config/constants.js';
|
|
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
|
|
import {
|
|
createApiToken,
|
|
getLiveApiTokenByHash,
|
|
listSessions,
|
|
revokeApiToken,
|
|
} from '../src/database/repositories/web-session-repository.js';
|
|
import { authorize } from '../src/web/auth/guard.js';
|
|
import { redirectUri, requestOrigin, resolveAccessLevel } from '../src/web/auth/discord-oauth.js';
|
|
import {
|
|
assertSameOrigin,
|
|
authenticate,
|
|
closeSession,
|
|
hashToken,
|
|
openSession,
|
|
} from '../src/web/auth/session.js';
|
|
|
|
/** Minimal stand-ins for the Node request and response objects. */
|
|
const fakeRequest = (headers = {}, method = 'GET') => ({
|
|
method,
|
|
headers: { 'user-agent': 'node-test', ...headers },
|
|
socket: { remoteAddress: '127.0.0.1' },
|
|
});
|
|
|
|
function fakeResponse() {
|
|
const headers = {};
|
|
return {
|
|
headers,
|
|
setHeader: (name, value) => {
|
|
headers[name] = value;
|
|
},
|
|
getHeader: (name) => headers[name],
|
|
};
|
|
}
|
|
|
|
const cookieOf = (response) => {
|
|
const raw = [].concat(response.getHeader('Set-Cookie') ?? [])[0] ?? '';
|
|
return raw.split(';')[0];
|
|
};
|
|
|
|
describe('access guard', () => {
|
|
it('lets a public route through without an actor', () => {
|
|
assert.doesNotThrow(() => authorize(null, { public: true }));
|
|
});
|
|
|
|
it('refuses an anonymous caller with 401', () => {
|
|
assert.throws(() => authorize(null, { access: ACCESS_LEVELS.STAFF }), { status: 401 });
|
|
});
|
|
|
|
it('compares the actor level against the route requirement', () => {
|
|
const staff = { accessLevel: ACCESS_LEVELS.STAFF, source: 'discord' };
|
|
assert.doesNotThrow(() => authorize(staff, { access: ACCESS_LEVELS.STAFF }));
|
|
assert.throws(() => authorize(staff, { access: ACCESS_LEVELS.OWNER }), { status: 403 });
|
|
});
|
|
|
|
it('defaults to Owner when a route forgets to declare its level', () => {
|
|
assert.throws(() => authorize({ accessLevel: ACCESS_LEVELS.DEV, source: 'discord' }, {}), {
|
|
status: 403,
|
|
});
|
|
});
|
|
|
|
it('confines a bootstrap session to the configuration routes', () => {
|
|
const setup = { accessLevel: ACCESS_LEVELS.OWNER, source: 'setup' };
|
|
assert.doesNotThrow(() => authorize(setup, { access: ACCESS_LEVELS.OWNER, setup: true }));
|
|
assert.throws(() => authorize(setup, { access: ACCESS_LEVELS.STAFF }), { status: 403 });
|
|
});
|
|
});
|
|
|
|
describe('cross-site protection', () => {
|
|
it('never blocks a read', () => {
|
|
assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'GET'), { kind: 'session' }));
|
|
});
|
|
|
|
it('requires the dashboard header on a write', () => {
|
|
assert.throws(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'session' }), { status: 403 });
|
|
assert.doesNotThrow(() =>
|
|
assertSameOrigin(fakeRequest({ 'x-requested-with': 'fws-dashboard' }, 'POST'), { kind: 'session' }),
|
|
);
|
|
});
|
|
|
|
it('rejects a write coming from another origin', () => {
|
|
const request = fakeRequest(
|
|
{ 'x-requested-with': 'fws-dashboard', origin: 'https://evil.example', host: 'bot.example' },
|
|
'POST',
|
|
);
|
|
assert.throws(() => assertSameOrigin(request, { kind: 'session' }), { status: 403 });
|
|
});
|
|
|
|
it('accepts a write from the served host', () => {
|
|
const request = fakeRequest(
|
|
{ 'x-requested-with': 'fws-dashboard', origin: 'https://bot.example', host: 'bot.example' },
|
|
'POST',
|
|
);
|
|
assert.doesNotThrow(() => assertSameOrigin(request, { kind: 'session' }));
|
|
});
|
|
|
|
it('exempts machine tokens, which carry no cookie', () => {
|
|
assert.doesNotThrow(() => assertSameOrigin(fakeRequest({}, 'POST'), { kind: 'api-token' }));
|
|
});
|
|
});
|
|
|
|
describe('dashboard sessions', () => {
|
|
before(() => initDatabase(':memory:'));
|
|
after(() => closeDatabase());
|
|
beforeEach(() => getDatabase().exec('DELETE FROM web_sessions; DELETE FROM web_api_tokens;'));
|
|
|
|
const login = (level = ACCESS_LEVELS.DEV) => {
|
|
const response = fakeResponse();
|
|
const session = openSession(fakeRequest(), response, {
|
|
user: { id: '42', username: 'kim', displayName: 'Kim', avatar: null },
|
|
accessLevel: level,
|
|
});
|
|
return { session, cookie: cookieOf(response) };
|
|
};
|
|
|
|
it('stores only the hash of the cookie value', () => {
|
|
const { session, cookie } = login();
|
|
const token = decodeURIComponent(cookie.split('=')[1]);
|
|
|
|
assert.notEqual(session.token_hash, token);
|
|
assert.equal(session.token_hash, hashToken(token));
|
|
});
|
|
|
|
it('identifies the caller from its cookie', () => {
|
|
const { cookie } = login(ACCESS_LEVELS.STAFF);
|
|
const actor = authenticate(fakeRequest({ cookie }));
|
|
|
|
assert.equal(actor.kind, 'session');
|
|
assert.equal(actor.userId, '42');
|
|
assert.equal(actor.accessLevel, ACCESS_LEVELS.STAFF);
|
|
});
|
|
|
|
it('returns null for an unknown or absent cookie', () => {
|
|
assert.equal(authenticate(fakeRequest()), null);
|
|
assert.equal(authenticate(fakeRequest({ cookie: 'fws_session=inventé' })), null);
|
|
});
|
|
|
|
it('ignores an expired session', () => {
|
|
const { cookie } = login();
|
|
getDatabase().exec("UPDATE web_sessions SET expires_at = datetime('now', '-1 hour')");
|
|
assert.equal(authenticate(fakeRequest({ cookie })), null);
|
|
});
|
|
|
|
it('closes a session and clears the cookie', () => {
|
|
const { cookie } = login();
|
|
const response = fakeResponse();
|
|
closeSession(fakeRequest({ cookie }), response);
|
|
|
|
assert.equal(authenticate(fakeRequest({ cookie })), null);
|
|
assert.match([].concat(response.getHeader('Set-Cookie'))[0], /Max-Age=0/);
|
|
});
|
|
|
|
it('lists the live sessions', () => {
|
|
login();
|
|
login(ACCESS_LEVELS.OWNER);
|
|
assert.equal(listSessions().length, 2);
|
|
});
|
|
});
|
|
|
|
describe('api tokens', () => {
|
|
before(() => initDatabase(':memory:'));
|
|
after(() => closeDatabase());
|
|
beforeEach(() => getDatabase().exec('DELETE FROM web_api_tokens;'));
|
|
|
|
const issue = () => {
|
|
const token = 'fws_test-token-value';
|
|
const id = createApiToken({
|
|
name: 'ci',
|
|
tokenHash: hashToken(token),
|
|
prefix: token.slice(0, 12),
|
|
accessLevel: ACCESS_LEVELS.DEV,
|
|
});
|
|
return { id, token };
|
|
};
|
|
|
|
it('authenticates a bearer token', () => {
|
|
const { token } = issue();
|
|
const actor = authenticate(fakeRequest({ authorization: `Bearer ${token}` }));
|
|
|
|
assert.equal(actor.kind, 'api-token');
|
|
assert.equal(actor.accessLevel, ACCESS_LEVELS.DEV);
|
|
});
|
|
|
|
it('records the last usage', () => {
|
|
const { token } = issue();
|
|
authenticate(fakeRequest({ authorization: `Bearer ${token}` }));
|
|
assert.ok(getLiveApiTokenByHash(hashToken(token)).last_used_at);
|
|
});
|
|
|
|
it('refuses a revoked token', () => {
|
|
const { id, token } = issue();
|
|
revokeApiToken(id);
|
|
assert.equal(authenticate(fakeRequest({ authorization: `Bearer ${token}` })), null);
|
|
});
|
|
|
|
it('refuses an unknown token', () => {
|
|
assert.equal(authenticate(fakeRequest({ authorization: 'Bearer nope' })), null);
|
|
});
|
|
});
|
|
|
|
describe('oauth access level', () => {
|
|
const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' };
|
|
|
|
it('gives Owner to the guild owner whatever their roles', () => {
|
|
const level = resolveAccessLevel({ member: { roles: [] }, userId: '1', guildOwnerId: '1', roles });
|
|
assert.equal(level, ACCESS_LEVELS.OWNER);
|
|
});
|
|
|
|
it('reads the highest matching role', () => {
|
|
assert.equal(
|
|
resolveAccessLevel({ member: { roles: ['r-staff', 'r-dev'] }, userId: '2', guildOwnerId: '1', roles }),
|
|
ACCESS_LEVELS.DEV,
|
|
);
|
|
});
|
|
|
|
it('falls back to plain member', () => {
|
|
assert.equal(
|
|
resolveAccessLevel({ member: { roles: ['autre'] }, userId: '2', guildOwnerId: '1', roles }),
|
|
ACCESS_LEVELS.USER,
|
|
);
|
|
});
|
|
|
|
it('returns null when the visitor is not in the guild', () => {
|
|
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), '');
|
|
});
|
|
});
|