Previously each authclient only supported GET /api/session/validate - the "just gate requests behind a valid session" case. A service that runs its own login/register/admin-user-management screens proxied to AuthGuard (GameStream's pattern, now also used by InfiniteVideo and OutdoorGames) needs much more: register, login, logout, me, totp_enable/verify/disable, password-reset request/confirm, and managed-user list/create/update/delete. The Go client already had this full surface from GameStream's original migration; Python and Node only had validate(), so both gained the same method set as Go, mirroring its behavior and JSON wire shapes exactly (register/login/logout return the raw Set-Cookie values to forward, totp_required surfaces on a 401 from login, etc). Also adds a SetupStatus/ setup_status/setupStatus method (GET /api/setup-status) so a service's own first-launch flow can tell whether AuthGuard already has an account before showing its own account-creation form, and adds totp_enabled to the Go client's PublicUser (AuthGuard has reported it for a while; the client just hadn't picked it up). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
285 lines
11 KiB
JavaScript
285 lines
11 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { APIError, AuthClient, InvalidSessionError } from '../src/authclient.js';
|
|
|
|
function fakeFetch(responses) {
|
|
let call = 0;
|
|
return async () => {
|
|
const res = responses[Math.min(call, responses.length - 1)];
|
|
call += 1;
|
|
const bodyText = res.body === undefined ? '' : JSON.stringify(res.body);
|
|
return {
|
|
status: res.status,
|
|
ok: res.status >= 200 && res.status < 300,
|
|
json: async () => res.body,
|
|
text: async () => bodyText,
|
|
headers: { getSetCookie: () => res.cookies ?? [] },
|
|
};
|
|
};
|
|
}
|
|
|
|
// Records every (url, init) pair a fakeFetch call received, for assertions
|
|
// on method/headers/body without a full fetch mock library.
|
|
function recordingFetch(responses) {
|
|
const calls = [];
|
|
const inner = fakeFetch(responses);
|
|
const wrapped = async (url, init) => {
|
|
calls.push({ url, init });
|
|
return inner(url, init);
|
|
};
|
|
wrapped.calls = calls;
|
|
return wrapped;
|
|
}
|
|
|
|
test('validate resolves the user on a valid session', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
|
|
});
|
|
const user = await client.validate('good-token');
|
|
assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' });
|
|
});
|
|
|
|
test('validate throws InvalidSessionError on an empty token', async () => {
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: {} }]) });
|
|
await assert.rejects(() => client.validate(''), InvalidSessionError);
|
|
await assert.rejects(() => client.validate(' '), InvalidSessionError);
|
|
});
|
|
|
|
test('validate throws InvalidSessionError when AuthGuard reports invalid', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
|
|
});
|
|
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
|
|
});
|
|
|
|
test('tokenFromRequest prefers the Authorization header over the cookie', () => {
|
|
const client = new AuthClient('https://auth.example.com');
|
|
const req = {
|
|
headers: {
|
|
authorization: 'Bearer header-token',
|
|
cookie: 'auth_session=cookie-token; other=1',
|
|
},
|
|
};
|
|
assert.equal(client.tokenFromRequest(req), 'header-token');
|
|
});
|
|
|
|
test('tokenFromRequest falls back to the auth_session cookie', () => {
|
|
const client = new AuthClient('https://auth.example.com');
|
|
const req = { headers: { cookie: 'other=1; auth_session=cookie-token' } };
|
|
assert.equal(client.tokenFromRequest(req), 'cookie-token');
|
|
});
|
|
|
|
test('middleware attaches authUser on success and 401s on failure', async () => {
|
|
const okClient = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
|
|
});
|
|
const req = { headers: { authorization: 'Bearer t' } };
|
|
let nextCalled = false;
|
|
await okClient.middleware()(req, { status: () => ({ json: () => {} }) }, () => {
|
|
nextCalled = true;
|
|
});
|
|
assert.equal(nextCalled, true);
|
|
assert.deepEqual(req.authUser, { id: 1, username: 'a', role: 'user' });
|
|
|
|
const badClient = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
|
|
});
|
|
let statusCode = null;
|
|
let jsonBody = null;
|
|
const res = {
|
|
status(code) {
|
|
statusCode = code;
|
|
return { json: (body) => (jsonBody = body) };
|
|
},
|
|
};
|
|
await badClient.middleware()({ headers: {} }, res, () => {
|
|
throw new Error('next should not be called');
|
|
});
|
|
assert.equal(statusCode, 401);
|
|
assert.deepEqual(jsonBody, { error: 'authentication required' });
|
|
});
|
|
|
|
// --- register/login/.../setupStatus: the additional surface a service that
|
|
// runs its own login/admin screens proxied to AuthGuard needs, beyond the
|
|
// original validate()-only surface. ---
|
|
|
|
test('setupStatus reflects AuthGuard setup_required', async () => {
|
|
for (const setupRequired of [true, false]) {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([{ status: 200, body: { setup_required: setupRequired } }]),
|
|
});
|
|
assert.equal(await client.setupStatus(), setupRequired);
|
|
}
|
|
});
|
|
|
|
test('register returns the user and forwards Set-Cookie values', async () => {
|
|
const fetchImpl = recordingFetch([
|
|
{
|
|
status: 201,
|
|
body: { user: { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', totp_enabled: false } },
|
|
cookies: ['auth_session=abc; HttpOnly'],
|
|
},
|
|
]);
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
const result = await client.register('root', 'root@example.com', 'correct horse battery staple');
|
|
assert.deepEqual(result.user, {
|
|
id: 1,
|
|
username: 'root',
|
|
email: 'root@example.com',
|
|
role: 'superadmin',
|
|
totpEnabled: false,
|
|
});
|
|
assert.deepEqual(result.cookies, ['auth_session=abc; HttpOnly']);
|
|
const sent = JSON.parse(fetchImpl.calls[0].init.body);
|
|
assert.deepEqual(sent, { username: 'root', email: 'root@example.com', password: 'correct horse battery staple' });
|
|
});
|
|
|
|
test('login success reports totpEnabled from AuthGuard', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([
|
|
{
|
|
status: 200,
|
|
body: { user: { id: 2, username: 'alice', email: 'alice@example.com', role: 'user', totp_enabled: true } },
|
|
cookies: ['auth_session=xyz'],
|
|
},
|
|
]),
|
|
});
|
|
const result = await client.login('alice', 'correct horse battery staple', '123456');
|
|
assert.equal(result.user.username, 'alice');
|
|
assert.equal(result.user.totpEnabled, true);
|
|
assert.deepEqual(result.cookies, ['auth_session=xyz']);
|
|
});
|
|
|
|
test('login raises APIError with totpRequired on a 401 asking for a code', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([
|
|
{ status: 401, body: { error: 'two-factor authentication code required', totp_required: true } },
|
|
]),
|
|
});
|
|
await assert.rejects(
|
|
() => client.login('alice', 'correct horse battery staple'),
|
|
(err) => err instanceof APIError && err.statusCode === 401 && err.totpRequired === true,
|
|
);
|
|
});
|
|
|
|
test('login raises APIError without totpRequired on invalid credentials', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([{ status: 401, body: { error: 'invalid username/email or password' } }]),
|
|
});
|
|
await assert.rejects(
|
|
() => client.login('alice', 'wrong password'),
|
|
(err) => err instanceof APIError && err.totpRequired === false && err.detailMessage === 'invalid username/email or password',
|
|
);
|
|
});
|
|
|
|
test('logout returns the clearing cookies', async () => {
|
|
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true }, cookies: ['auth_session=; Max-Age=0'] }]);
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
const cookies = await client.logout('a-token');
|
|
assert.deepEqual(cookies, ['auth_session=; Max-Age=0']);
|
|
assert.equal(fetchImpl.calls[0].init.headers.Authorization, 'Bearer a-token');
|
|
});
|
|
|
|
test('me resolves the public user', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([
|
|
{ status: 200, body: { user: { id: 3, username: 'bob', email: 'bob@example.com', role: 'admin', totp_enabled: false } } },
|
|
]),
|
|
});
|
|
const user = await client.me('a-token');
|
|
assert.equal(user.id, 3);
|
|
assert.equal(user.role, 'admin');
|
|
});
|
|
|
|
test('totpEnable returns the provisioned secret', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([{ status: 200, body: { secret: 'SECRET', otpauth_url: 'otpauth://...', enabled: false } }]),
|
|
});
|
|
const result = await client.totpEnable('a-token');
|
|
assert.equal(result.secret, 'SECRET');
|
|
assert.equal(result.enabled, false);
|
|
});
|
|
|
|
test('totpVerify and totpDisable send the code as {token}', async () => {
|
|
let fetchImpl = recordingFetch([{ status: 200, body: { enabled: true } }]);
|
|
let client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
await client.totpVerify('a-token', '123456');
|
|
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '123456' });
|
|
|
|
fetchImpl = recordingFetch([{ status: 200, body: { enabled: false } }]);
|
|
client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
await client.totpDisable('a-token', '654321');
|
|
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '654321' });
|
|
});
|
|
|
|
test('requestPasswordReset with no identifier sends an empty body (targets the superadmin)', async () => {
|
|
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
await client.requestPasswordReset();
|
|
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), {});
|
|
});
|
|
|
|
test('confirmPasswordReset sends the code and new password', async () => {
|
|
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
await client.confirmPasswordReset('ABCD1234', 'a brand new passphrase');
|
|
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { code: 'ABCD1234', password: 'a brand new passphrase' });
|
|
});
|
|
|
|
test('listManagedUsers maps every row', async () => {
|
|
const client = new AuthClient('https://auth.example.com', {
|
|
fetchImpl: fakeFetch([
|
|
{
|
|
status: 200,
|
|
body: {
|
|
users: [
|
|
{ id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', created_at: '2026-01-01T00:00:00Z' },
|
|
{ id: 2, username: 'bob', email: 'bob@example.com', role: 'user', created_at: '2026-01-02T00:00:00Z' },
|
|
],
|
|
},
|
|
},
|
|
]),
|
|
});
|
|
const users = await client.listManagedUsers('a-token');
|
|
assert.equal(users.length, 2);
|
|
assert.deepEqual(users[0], {
|
|
id: 1,
|
|
username: 'root',
|
|
email: 'root@example.com',
|
|
role: 'superadmin',
|
|
createdAt: '2026-01-01T00:00:00Z',
|
|
});
|
|
});
|
|
|
|
test('createManagedUser sends only the given fields', async () => {
|
|
const fetchImpl = recordingFetch([
|
|
{ status: 201, body: { user: { id: 4, username: 'carol', email: 'carol@example.com', role: 'user', created_at: '' } } },
|
|
]);
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
const created = await client.createManagedUser('a-token', {
|
|
username: 'carol',
|
|
email: 'carol@example.com',
|
|
password: 'correct horse battery staple',
|
|
});
|
|
assert.equal(created.username, 'carol');
|
|
const sent = JSON.parse(fetchImpl.calls[0].init.body);
|
|
assert.equal('role' in sent, false);
|
|
});
|
|
|
|
test('updateManagedUser PUTs to /api/admin/users/{id}', async () => {
|
|
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
await client.updateManagedUser('a-token', 5, { email: 'new@example.com' });
|
|
assert.equal(fetchImpl.calls[0].init.method, 'PUT');
|
|
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/5');
|
|
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { email: 'new@example.com' });
|
|
});
|
|
|
|
test('deleteManagedUser DELETEs /api/admin/users/{id}', async () => {
|
|
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
|
|
const client = new AuthClient('https://auth.example.com', { fetchImpl });
|
|
await client.deleteManagedUser('a-token', 6);
|
|
assert.equal(fetchImpl.calls[0].init.method, 'DELETE');
|
|
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6');
|
|
});
|