commit c9a2cee3a170a9ad80e713ada4ab29fe065c31bb
parent 4998688953408308ee092cca290e37827f5038e5
Author: finwo <finwo@pm.me>
Date: Wed, 21 Oct 2026 02:44:29 +0200
Add multi-account host sessions with forced account chooser
Diffstat:
11 files changed, 769 insertions(+), 68 deletions(-)
diff --git a/server/src/controller/login/password.js b/server/src/controller/login/password.js
@@ -3,7 +3,11 @@ import { resolveClientForHost, resolveHostContext } from '../../lib/host-context
import { HttpError } from '../../lib/http/http-error.js';
import { findManagedProviderForUser, resolveLogin } from '../../lib/login.js';
import { getClient } from '../../lib/oidc/clients.js';
-import { getAuthRequest, readAuthRequestId } from '../../lib/oidc/requests.js';
+import {
+ getAuthRequest,
+ readAuthRequestId,
+ selectAuthRequestAccount,
+} from '../../lib/oidc/requests.js';
import { verifyDummyPassword, verifyPassword } from '../../lib/password.js';
import { canUseClient } from '../../lib/policy.js';
import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../../lib/realm.js';
@@ -127,6 +131,13 @@ export default {
ip: requestIp(req),
});
setSessionCookie(res, req, token, session.ttl);
+ if (pendingClient && pending) {
+ await selectAuthRequestAccount(realmDb, pending.id, {
+ userId: user.id,
+ sessionId: session.id,
+ authTime: session.auth_time,
+ });
+ }
await updateLastLogin(systemDb, user.id);
return new app.HttpOk({
diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js
@@ -16,6 +16,7 @@ import {
import { getJwks, signToken, verifyToken } from '../lib/oidc/keys.js';
import {
clearAuthRequestCookie,
+ clearAuthRequestSelection,
completeAuthRequest,
createAuthRequest,
createAuthorizationCode,
@@ -36,6 +37,7 @@ import {
bindSessionRealm,
clearSessionCookie,
destroySession,
+ listSessionAccounts,
requestToken,
} from '../lib/session.js';
import {
@@ -239,6 +241,21 @@ async function authorize(context, client, req, res) {
return redirect(res, endpointUrls(context).login);
}
+ const accounts = await listSessionAccounts(systemDb, auth.group);
+ const selected = Boolean(
+ pending.user_id &&
+ pending.session_id &&
+ pending.session_id === auth.session.id &&
+ pending.user_id === auth.user.id
+ );
+ if ((pending.user_id || pending.session_id) && !selected) {
+ await clearAuthRequestSelection(db, pending.id);
+ }
+ if (!selected && accounts.length >= 2) {
+ setAuthRequestCookie(res, req, context.realm, pending.id);
+ return redirect(res, endpointUrls(context).login);
+ }
+
await bindSessionRealm(systemDb, auth.session.id, context.realm.id);
await completeAuthRequest(db, pending.id, {
userId: auth.user.id,
diff --git a/server/src/controller/session/select.js b/server/src/controller/session/select.js
@@ -0,0 +1,74 @@
+import { app } from '../../app.js';
+import { resolveClientForHost, resolveHostContext } from '../../lib/host-context.js';
+import { HttpError } from '../../lib/http/http-error.js';
+import {
+ getAuthRequest,
+ readAuthRequestId,
+ selectAuthRequestAccount,
+} from '../../lib/oidc/requests.js';
+import { getSystemDatabase, openRealmDatabase } from '../../lib/realm.js';
+import { requestToken, selectSessionAccount } from '../../lib/session.js';
+
+export default {
+ method: 'post',
+ path: '/api/v1/session/select',
+ name: 'session.select',
+ async handler(req) {
+ const body = req.body || {};
+ if (typeof body.public_id !== 'string') {
+ throw new HttpError(400, 'invalid_request', 'public_id is required');
+ }
+ if (body.client_id != null && typeof body.client_id !== 'string') {
+ throw new HttpError(400, 'invalid_request', 'client_id must be a string');
+ }
+
+ const hostContext = await resolveHostContext(req, {
+ publicUrl: app.config.server.public_url,
+ });
+ let realm = hostContext.realm || null;
+ let clientId = body.client_id || hostContext.clientId || null;
+ if (body.client_id && hostContext.mode !== 'client') {
+ const resolved = await resolveClientForHost(hostContext, body.client_id);
+ realm = resolved.realm;
+ clientId = resolved.clientId;
+ }
+
+ const selected = await selectSessionAccount(getSystemDatabase(), {
+ token: requestToken(req),
+ context: hostContext,
+ publicId: body.public_id,
+ });
+ if (!selected) {
+ throw new HttpError(401, 'not_authenticated', 'Not signed in');
+ }
+
+ let pendingAuthRequest = false;
+ if (realm) {
+ const realmDb = await openRealmDatabase(realm);
+ const pending = await getAuthRequest(realmDb, readAuthRequestId(req, realm));
+ if (
+ pending &&
+ !pending.completed_at &&
+ (!clientId || pending.client_id === clientId)
+ ) {
+ await selectAuthRequestAccount(realmDb, pending.id, {
+ userId: selected.user.id,
+ sessionId: selected.session.id,
+ authTime: selected.session.auth_time,
+ });
+ pendingAuthRequest = true;
+ }
+ }
+
+ return new app.HttpOk({
+ ok: true,
+ user: {
+ id: selected.user.id,
+ username: selected.user.username,
+ display_name: selected.user.display_name,
+ },
+ expires_at: selected.session.expires_at,
+ pending_auth_request: pendingAuthRequest,
+ });
+ },
+};
diff --git a/server/src/controller/session/show.js b/server/src/controller/session/show.js
@@ -3,7 +3,7 @@ import { resolveHostContext } from '../../lib/host-context.js';
import { HttpError } from '../../lib/http/http-error.js';
import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../../lib/realm.js';
import { isSystemAdmin } from '../../lib/policy.js';
-import { authenticateRequest } from '../../lib/session.js';
+import { authenticateRequest, listSessionAccounts } from '../../lib/session.js';
export default {
method: 'get',
@@ -50,6 +50,7 @@ export default {
roles: auth.roles,
is_system_admin: isSystemAdmin(auth.user),
expires_at: auth.session.expires_at,
+ accounts: await listSessionAccounts(getSystemDatabase(), auth.group),
});
},
};
diff --git a/server/src/lib/oidc/requests.js b/server/src/lib/oidc/requests.js
@@ -107,6 +107,30 @@ export async function getAuthRequest(db, id, now = Date.now()) {
return request;
}
+export async function selectAuthRequestAccount(
+ db,
+ id,
+ { userId, sessionId, authTime }
+) {
+ if (!id) return;
+ await db.run(
+ `UPDATE auth_requests
+ SET user_id = {userId}, session_id = {sessionId}, auth_time = {authTime}
+ WHERE id = {id} AND completed_at IS NULL`,
+ { id, userId, sessionId, authTime }
+ );
+}
+
+export async function clearAuthRequestSelection(db, id) {
+ if (!id) return;
+ await db.run(
+ `UPDATE auth_requests
+ SET user_id = NULL, session_id = NULL, auth_time = NULL
+ WHERE id = {id} AND completed_at IS NULL`,
+ { id }
+ );
+}
+
export async function completeAuthRequest(db, id, { userId, sessionId, authTime }, now = Date.now()) {
await db.run(
`UPDATE auth_requests
diff --git a/server/src/lib/session.js b/server/src/lib/session.js
@@ -150,6 +150,68 @@ export async function purgeExpiredSessions(systemDb, now = Date.now()) {
});
}
+async function insertSession(tx, {
+ groupId,
+ userId,
+ scope,
+ scopeHost,
+ ttl,
+ userAgent,
+ ip,
+ now,
+}) {
+ const id = crypto.randomUUID();
+ const publicId = crypto.randomUUID();
+ const expiresAt = now + ttl * 1000;
+ const authTime = Math.floor(now / 1000);
+
+ await tx.run(
+ `INSERT INTO sessions
+ (id, public_id, group_id, user_id, scope_type, scope_host, realm_id,
+ client_id, ttl, auth_time, created_at, expires_at, last_seen_at,
+ user_agent, ip)
+ VALUES
+ ({id}, {publicId}, {groupId}, {userId}, {scopeType}, {scopeHost}, {realmId},
+ {clientId}, {ttl}, {authTime}, {createdAt}, {expiresAt}, {lastSeenAt},
+ {userAgent}, {ip})`,
+ {
+ id,
+ publicId,
+ groupId,
+ userId,
+ scopeType: scope.scopeType,
+ scopeHost,
+ realmId: scope.realmId,
+ clientId: scope.clientId,
+ ttl,
+ authTime,
+ createdAt: now,
+ expiresAt,
+ lastSeenAt: now,
+ userAgent,
+ ip,
+ }
+ );
+
+ return {
+ id,
+ public_id: publicId,
+ group_id: groupId,
+ user_id: userId,
+ scope_type: scope.scopeType,
+ scope_host: scopeHost,
+ realm_id: scope.realmId,
+ client_id: scope.clientId,
+ ttl,
+ auth_time: authTime,
+ created_at: now,
+ expires_at: expiresAt,
+ last_seen_at: now,
+ user_agent: userAgent,
+ ip,
+ };
+}
+
export async function createHostSession(
systemDb,
{ context, token = null, userId, ttl, userAgent = null, ip = null },
@@ -159,8 +221,9 @@ export async function createHostSession(
return systemDb.transaction(async (tx) => {
let group = await findGroupByToken(tx, token);
+ if (group && group.host !== context.host) group = null;
- if (group && group.host === context.host) {
+ if (group) {
const existing = await tx.get(
`SELECT id, public_id, group_id, user_id, scope_type, scope_host, realm_id,
client_id, ttl, auth_time, created_at, expires_at, last_seen_at,
@@ -207,84 +270,68 @@ export async function createHostSession(
};
}
- await deleteGroup(tx, group.id);
- group = null;
+ if (existing) {
+ await tx.run('DELETE FROM sessions WHERE id = {id}', { id: existing.id });
+ }
+
+ const session = await insertSession(tx, {
+ groupId: group.id,
+ userId,
+ scope,
+ scopeHost: context.host,
+ ttl,
+ userAgent,
+ ip,
+ now,
+ });
+ await tx.run(
+ `UPDATE session_groups
+ SET active_session_id = {sessionId}, last_seen_at = {now}
+ WHERE id = {groupId}`,
+ { sessionId: session.id, now, groupId: group.id }
+ );
+
+ return {
+ token,
+ group: { ...group, active_session_id: session.id, last_seen_at: now },
+ session,
+ };
}
const nextToken = crypto.randomBytes(32).toString('base64url');
const groupId = hashToken(nextToken);
- const sessionId = crypto.randomUUID();
- const publicId = crypto.randomUUID();
const createdAt = now;
- const expiresAt = now + ttl * 1000;
- const authTime = Math.floor(now / 1000);
await tx.run(
`INSERT INTO session_groups
(id, host, active_session_id, created_at, last_seen_at)
VALUES
- ({id}, {host}, {activeSessionId}, {createdAt}, {lastSeenAt})`,
- {
- id: groupId,
- host: context.host,
- activeSessionId: sessionId,
- createdAt,
- lastSeenAt: now,
- }
- );
-
- await tx.run(
- `INSERT INTO sessions
- (id, public_id, group_id, user_id, scope_type, scope_host, realm_id,
- client_id, ttl, auth_time, created_at, expires_at, last_seen_at,
- user_agent, ip)
- VALUES
- ({id}, {publicId}, {groupId}, {userId}, {scopeType}, {scopeHost}, {realmId},
- {clientId}, {ttl}, {authTime}, {createdAt}, {expiresAt}, {lastSeenAt},
- {userAgent}, {ip})`,
- {
- id: sessionId,
- publicId,
- groupId,
- userId,
- scopeType: scope.scopeType,
- scopeHost: context.host,
- realmId: scope.realmId,
- clientId: scope.clientId,
- ttl,
- authTime,
- createdAt,
- expiresAt,
- lastSeenAt: now,
- userAgent,
- ip,
- }
+ ({id}, {host}, NULL, {createdAt}, {lastSeenAt})`,
+ { id: groupId, host: context.host, createdAt, lastSeenAt: now }
);
- const session = {
- id: sessionId,
- public_id: publicId,
- group_id: groupId,
- user_id: userId,
- scope_type: scope.scopeType,
- scope_host: context.host,
- realm_id: scope.realmId,
- client_id: scope.clientId,
+ const session = await insertSession(tx, {
+ groupId,
+ userId,
+ scope,
+ scopeHost: context.host,
ttl,
- auth_time: authTime,
- created_at: createdAt,
- expires_at: expiresAt,
- last_seen_at: now,
- user_agent: userAgent,
+ userAgent,
ip,
- };
+ now,
+ });
+
+ await tx.run(
+ 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}',
+ { sessionId: session.id, id: groupId }
+ );
return {
token: nextToken,
group: {
id: groupId,
host: context.host,
- active_session_id: sessionId,
+ active_session_id: session.id,
created_at: createdAt,
last_seen_at: now,
},
@@ -293,6 +340,82 @@ export async function createHostSession(
});
}
+export async function listSessionAccounts(systemDb, group, now = Date.now()) {
+ if (!group) return [];
+
+ const rows = await systemDb.all(
+ `SELECT s.id, s.public_id, s.user_id, s.created_at, s.expires_at,
+ u.username, u.display_name
+ FROM sessions s
+ JOIN users u ON u.id = s.user_id
+ WHERE s.group_id = {groupId}
+ AND s.expires_at > {now}
+ AND u.status = 'active'
+ ORDER BY s.created_at ASC`,
+ { groupId: group.id, now }
+ );
+
+ return rows.map((row) => ({
+ public_id: row.public_id,
+ active: row.id === group.active_session_id,
+ user: {
+ id: row.user_id,
+ username: row.username,
+ display_name: row.display_name,
+ },
+ created_at: row.created_at,
+ expires_at: row.expires_at,
+ }));
+}
+
+export async function selectSessionAccount(
+ systemDb,
+ { token, context, publicId },
+ now = Date.now()
+) {
+ if (!token || !publicId) return null;
+
+ return systemDb.transaction(async (tx) => {
+ const group = await findGroupByToken(tx, token);
+ if (!group || group.host !== context.host) return null;
+
+ const session = await tx.get(
+ `SELECT id, public_id, group_id, user_id, scope_type, scope_host, realm_id,
+ client_id, ttl, auth_time, created_at, expires_at, last_seen_at,
+ user_agent, ip
+ FROM sessions
+ WHERE group_id = {groupId} AND public_id = {publicId}`,
+ { groupId: group.id, publicId }
+ );
+ if (!session || session.expires_at <= now || !scopeMatches(session, context)) {
+ return null;
+ }
+
+ const user = await findUserById(tx, session.user_id);
+ if (!user || user.status !== 'active') return null;
+
+ const expiresAt = now + session.ttl * 1000;
+ await tx.run(
+ `UPDATE sessions
+ SET last_seen_at = {now}, expires_at = {expiresAt}
+ WHERE id = {id}`,
+ { now, expiresAt, id: session.id }
+ );
+ await tx.run(
+ `UPDATE session_groups
+ SET active_session_id = {sessionId}, last_seen_at = {now}
+ WHERE id = {id}`,
+ { sessionId: session.id, now, id: group.id }
+ );
+
+ return {
+ group: { ...group, active_session_id: session.id, last_seen_at: now },
+ session: { ...session, last_seen_at: now, expires_at: expiresAt },
+ user,
+ };
+ });
+}
+
export async function authenticateRequest({
systemDb,
realmDb = null,
@@ -335,8 +458,20 @@ export async function authenticateRequest({
const user = await findUserById(systemDb, session.user_id);
if (!user || user.status !== 'active') {
- await deleteGroup(systemDb, group.id);
- clearSessionCookie(res, req);
+ const groupDeleted = await systemDb.transaction(async (tx) => {
+ await tx.run('DELETE FROM sessions WHERE id = {id}', { id: session.id });
+ const next = await nextActiveSession(tx, group.id, now);
+ if (next) {
+ await tx.run(
+ 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}',
+ { sessionId: next.id, id: group.id }
+ );
+ return false;
+ }
+ await deleteGroup(tx, group.id);
+ return true;
+ });
+ if (groupDeleted) clearSessionCookie(res, req);
return null;
}
diff --git a/server/test/http.test.js b/server/test/http.test.js
@@ -355,6 +355,125 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(oldStyle.status, 401);
});
+ await t.test('a host group holds multiple accounts and can switch', async () => {
+ const aliceLogin = await acme({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' },
+ });
+ assert.equal(aliceLogin.status, 200);
+ const aliceCookie = mergeCookies('', aliceLogin);
+
+ const itLogin = await acme({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'it@acme.test', password: 'demo' },
+ cookie: aliceCookie,
+ });
+ assert.equal(itLogin.status, 200);
+ assert.equal(responseCookies(itLogin)[0], responseCookies(aliceLogin)[0]);
+ const cookie = mergeCookies(aliceCookie, itLogin);
+
+ const session = await acme({ path: '/api/v1/session', cookie });
+ assert.equal(session.status, 200);
+ assert.equal(session.json.user.username, 'acme-it');
+ assert.deepEqual(
+ session.json.accounts.map((account) => account.user.username),
+ ['alice', 'acme-it']
+ );
+ assert.equal(
+ session.json.accounts.find((account) => account.user.username === 'acme-it').active,
+ true
+ );
+
+ const aliceAccount = session.json.accounts.find(
+ (account) => account.user.username === 'alice'
+ );
+ const selected = await acme({
+ method: 'POST',
+ path: '/api/v1/session/select',
+ body: { public_id: aliceAccount.public_id, client_id: 'internal-app' },
+ cookie,
+ });
+ assert.equal(selected.status, 200);
+ assert.equal(selected.json.user.username, 'alice');
+ assert.equal(selected.json.pending_auth_request, false);
+
+ const switched = await acme({ path: '/api/v1/session', cookie });
+ assert.equal(switched.status, 200);
+ assert.equal(switched.json.user.username, 'alice');
+ });
+
+ await t.test('authorize asks which account to use when the group has multiple accounts', async () => {
+ const aliceLogin = await app({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' },
+ });
+ let jar = mergeCookies('', aliceLogin);
+ const itLogin = await app({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'it@acme.test', password: 'demo' },
+ cookie: jar,
+ });
+ jar = mergeCookies(jar, itLogin);
+
+ const { verifier, challenge } = pkce();
+ const redirectUri = `${origin('app.acme.localhost')}/callback`;
+ const authorizePath =
+ `/oidc/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=state-select&code_challenge=${challenge}&code_challenge_method=S256`;
+
+ const first = await app({ path: authorizePath, cookie: jar });
+ assert.equal(first.status, 302);
+ assert.equal(locationQuery(first).pathname, '/oidc/login');
+ jar = mergeCookies(jar, first);
+
+ const session = await app({ path: '/api/v1/session', cookie: jar });
+ const aliceAccount = session.json.accounts.find(
+ (account) => account.user.username === 'alice'
+ );
+ const selected = await app({
+ method: 'POST',
+ path: '/api/v1/session/select',
+ body: { public_id: aliceAccount.public_id, client_id: 'internal-app' },
+ cookie: jar,
+ });
+ assert.equal(selected.status, 200);
+ assert.equal(selected.json.pending_auth_request, true);
+ assert.equal(selected.json.user.username, 'alice');
+
+ const second = await app({ path: authorizePath, cookie: jar });
+ assert.equal(second.status, 302);
+ const redirected = locationQuery(second);
+ assert.equal(redirected.searchParams.get('state'), 'state-select');
+ const code = redirected.searchParams.get('code');
+ assert.ok(code);
+
+ const tokenResponse = await app({
+ method: 'POST',
+ path: '/oidc/token',
+ form: {
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: redirectUri,
+ client_id: 'internal-app',
+ code_verifier: verifier,
+ },
+ });
+ assert.equal(tokenResponse.status, 200);
+
+ const jwks = await app({ path: '/oidc/jwks' });
+ const keySet = createLocalJWKSet(jwks.json);
+ const { payload } = await jwtVerify(tokenResponse.json.id_token, keySet, {
+ issuer: `${publicUrl}/oidc/acme`,
+ audience: 'internal-app',
+ });
+ assert.equal(payload.preferred_username, 'alice');
+ });
+
await t.test('unknown hosts are rejected by auth and session APIs', async () => {
const unknown = (options = {}) =>
request(port, { host: `unknown.test:${port}`, ...options });
diff --git a/server/test/session.test.js b/server/test/session.test.js
@@ -19,6 +19,8 @@ import {
createHostSession,
destroySession,
getSessionByToken,
+ listSessionAccounts,
+ selectSessionAccount,
} from '../src/lib/session.js';
import { createUser, ensureMembership } from '../src/lib/users.js';
@@ -232,6 +234,52 @@ test('disabled users lose access and their session group is removed', async () =
}
});
+test('disabling the active account keeps other accounts in the group', async () => {
+ const { dir, realm, systemDb, userId } = await setup();
+ try {
+ const context = realmContext(realm);
+ const first = await createHostSession(systemDb, {
+ context,
+ userId,
+ ttl: SHORT_SESSION_TTL,
+ });
+ const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
+ const second = await createHostSession(systemDb, {
+ context,
+ token: first.token,
+ userId: otherId,
+ ttl: SHORT_SESSION_TTL,
+ });
+
+ await systemDb.run('UPDATE users SET status = {status} WHERE id = {id}', {
+ status: 'disabled',
+ id: otherId,
+ });
+
+ const res = mockResponse();
+ assert.equal(
+ await authenticateRequest({
+ systemDb,
+ realmDb: null,
+ req: mockRequest(`${SESSION_COOKIE}=${first.token}`),
+ res,
+ context,
+ }),
+ null
+ );
+
+ const found = await getSessionByToken(systemDb, first.token);
+ assert.equal(found.session.user_id, userId);
+
+ const accounts = await listSessionAccounts(systemDb, second.group);
+ assert.equal(accounts.length, 1);
+ assert.equal(accounts[0].user.id, userId);
+ } finally {
+ await closeRealms();
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});
+
test('a session is rejected on a different host scope', async () => {
const { dir, realm, realmDb, systemDb, userId } = await setup();
try {
@@ -263,7 +311,7 @@ test('a session is rejected on a different host scope', async () => {
}
});
-test('the same user reuses a group and a different user replaces it', async () => {
+test('the same user reuses a session and a different user adds an account', async () => {
const { dir, realm, systemDb, userId } = await setup();
try {
const context = realmContext(realm);
@@ -279,6 +327,7 @@ test('the same user reuses a group and a different user replaces it', async () =
ttl: SHORT_SESSION_TTL,
});
assert.equal(second.group.id, first.group.id);
+ assert.equal(second.token, first.token);
assert.equal(second.session.id, first.session.id);
const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
@@ -288,13 +337,68 @@ test('the same user reuses a group and a different user replaces it', async () =
userId: otherId,
ttl: SHORT_SESSION_TTL,
});
- assert.notEqual(third.group.id, first.group.id);
+ assert.equal(third.group.id, first.group.id);
+ assert.equal(third.token, first.token);
assert.equal(third.session.user_id, otherId);
const old = await systemDb.get('SELECT id FROM sessions WHERE id = {id}', {
id: first.session.id,
});
- assert.equal(old, undefined);
+ assert.equal(old.id, first.session.id);
+
+ const accounts = await listSessionAccounts(systemDb, third.group);
+ assert.deepEqual(
+ accounts.map((account) => account.user.username),
+ ['alice', 'bob']
+ );
+ assert.equal(accounts.find((account) => account.user.id === otherId).active, true);
+ } finally {
+ await closeRealms();
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});
+
+test('selecting an account updates the active session', async () => {
+ const { dir, realm, systemDb, userId } = await setup();
+ try {
+ const context = realmContext(realm);
+ const first = await createHostSession(systemDb, {
+ context,
+ userId,
+ ttl: SHORT_SESSION_TTL,
+ });
+ const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
+ const second = await createHostSession(systemDb, {
+ context,
+ token: first.token,
+ userId: otherId,
+ ttl: SHORT_SESSION_TTL,
+ });
+
+ const selected = await selectSessionAccount(systemDb, {
+ token: first.token,
+ context,
+ publicId: first.session.public_id,
+ });
+ assert.equal(selected.user.id, userId);
+ assert.equal(selected.session.id, first.session.id);
+
+ const found = await getSessionByToken(systemDb, first.token);
+ assert.equal(found.session.id, first.session.id);
+
+ const rejectedHost = await selectSessionAccount(systemDb, {
+ token: first.token,
+ context: clientContext(realm),
+ publicId: second.session.public_id,
+ });
+ assert.equal(rejectedHost, null);
+
+ const rejectedAccount = await selectSessionAccount(systemDb, {
+ token: first.token,
+ context,
+ publicId: 'missing',
+ });
+ assert.equal(rejectedAccount, null);
} finally {
await closeRealms();
await fs.rm(dir, { recursive: true, force: true });
@@ -324,6 +428,38 @@ test('logout deletes the active session and group', async () => {
}
});
+test('logout keeps the group when another account remains', async () => {
+ const { dir, realm, systemDb, userId } = await setup();
+ try {
+ const context = realmContext(realm);
+ const first = await createHostSession(systemDb, {
+ context,
+ userId,
+ ttl: SHORT_SESSION_TTL,
+ });
+ const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' });
+ const second = await createHostSession(systemDb, {
+ context,
+ token: first.token,
+ userId: otherId,
+ ttl: SHORT_SESSION_TTL,
+ });
+
+ const result = await destroySession(systemDb, first.token);
+ assert.equal(result.groupDeleted, false);
+
+ const found = await getSessionByToken(systemDb, first.token);
+ assert.equal(found.session.id, first.session.id);
+
+ const accounts = await listSessionAccounts(systemDb, second.group);
+ assert.equal(accounts.length, 1);
+ assert.equal(accounts[0].user.id, userId);
+ } finally {
+ await closeRealms();
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});
+
test('realm bindings are inserted once and updated on repeat', async () => {
const { dir, realm, systemDb, userId } = await setup();
try {
diff --git a/server/web/src/assets/global.css b/server/web/src/assets/global.css
@@ -115,6 +115,50 @@ body {
accent-color: var(--realm-primary);
}
+.auth-accounts {
+ display: grid;
+ gap: 0.5rem;
+ margin-top: 1rem;
+}
+
+.auth-account {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.125rem;
+ width: 100%;
+ padding: 0.75rem 0;
+ border: 0;
+ border-bottom: 1pt solid rgba(0, 0, 0, 0.16);
+ border-radius: 0;
+ background: none;
+ color: inherit;
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+}
+
+.auth-account:hover,
+.auth-account:focus-visible {
+ border-bottom-color: var(--realm-primary);
+}
+
+.auth-account:disabled {
+ opacity: 0.5;
+ cursor: default;
+}
+
+.auth-account-name {
+ font-size: 1rem;
+ line-height: 1.5;
+}
+
+.auth-account-username {
+ color: rgba(0, 0, 0, 0.6);
+ font-size: 0.875rem;
+ line-height: 1.5;
+}
+
.auth-error {
margin: 1rem 0 0;
color: #d93025;
@@ -175,10 +219,15 @@ body {
.auth-field label,
.auth-identifier,
- .auth-note {
+ .auth-note,
+ .auth-account-username {
color: rgba(255, 255, 255, 0.6);
}
+ .auth-account {
+ border-bottom-color: rgba(255, 255, 255, 0.16);
+ }
+
.auth-error {
color: #f28b82;
}
diff --git a/server/web/src/screen/login.tsx b/server/web/src/screen/login.tsx
@@ -1,14 +1,17 @@
import m from 'mithril';
import {
getClientDiscovery,
+ getSession,
resolveLogin,
+ selectSession,
signInPassword,
type ClientDiscovery,
type LoginResolution,
type PasswordLoginResult,
+ type SessionAccount,
} from '../util/api';
-type Step = 'identifier' | 'password' | 'oidc' | 'done';
+type Step = 'accounts' | 'identifier' | 'password' | 'oidc' | 'done';
interface TextFieldAttrs {
id: string;
@@ -47,6 +50,7 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
clientId: null as string | null,
discovery: null as ClientDiscovery | null,
step: 'identifier' as Step,
+ accounts: [] as SessionAccount[],
identifier: '',
password: '',
longSession: false,
@@ -69,12 +73,25 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
this.realmSlug = discovery.realm;
this.clientId = discovery.client_id;
document.title = discovery.display_name;
+ await this.loadAccounts();
} catch (e) {
this.error = e as Error;
}
m.redraw();
},
+ async loadAccounts(this: any) {
+ try {
+ const session = await getSession();
+ if (session.accounts.length >= 2) {
+ this.accounts = session.accounts;
+ this.step = 'accounts';
+ }
+ } catch {
+ this.accounts = [];
+ }
+ },
+
async submitIdentifier(this: any) {
this.pending = true;
this.error = null;
@@ -126,6 +143,41 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
}
},
+ async selectAccount(this: any, account: SessionAccount) {
+ this.pending = true;
+ this.error = null;
+ try {
+ const result = await selectSession(account.public_id, this.clientId);
+ if (result.pending_auth_request) {
+ const current = m.route.get() || '';
+ m.route.set(current.replace(/\/login$/, '/authorize'));
+ return;
+ }
+
+ if (this.clientId === 'admin') {
+ m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/admin` : '/admin');
+ return;
+ }
+
+ this.signedIn = result.user;
+ this.step = 'done';
+ } catch (e) {
+ this.error = e as Error;
+ }
+ this.pending = false;
+ m.redraw();
+ },
+
+ differentAccount(this: any) {
+ this.step = 'identifier';
+ this.identifier = '';
+ this.password = '';
+ this.longSession = false;
+ this.provider = null;
+ this.error = null;
+ m.redraw();
+ },
+
back(this: any) {
this.step = 'identifier';
this.password = '';
@@ -135,6 +187,12 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
m.redraw();
},
+ backToAccounts(this: any) {
+ this.step = 'accounts';
+ this.error = null;
+ m.redraw();
+ },
+
view(this: any) {
const branding = this.discovery?.branding || {};
const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A';
@@ -161,6 +219,7 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
) : null}
<h1>{title}</h1>
+ {this.step === 'accounts' ? this.renderAccounts() : null}
{this.step === 'identifier' ? this.renderIdentifier() : null}
{this.step === 'password' ? this.renderPassword() : null}
{this.step === 'oidc' ? this.renderProvider() : null}
@@ -170,6 +229,40 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
);
},
+ renderAccounts(this: any) {
+ return (
+ <div>
+ <p class="auth-note">Choose an account to continue.</p>
+ <div class="auth-accounts">
+ {this.accounts.map((account: SessionAccount) => {
+ const name = account.user.display_name || account.user.username;
+ const secondary =
+ account.user.display_name && account.user.display_name !== account.user.username
+ ? account.user.username
+ : null;
+ return (
+ <button
+ class="auth-account"
+ type="button"
+ disabled={this.pending}
+ onclick={() => this.selectAccount(account)}
+ >
+ <span class="auth-account-name">{name}</span>
+ {secondary ? <span class="auth-account-username">{secondary}</span> : null}
+ </button>
+ );
+ })}
+ </div>
+ {this.error ? <p class="auth-error">{this.error.message}</p> : null}
+ <div class="auth-actions">
+ <button class="auth-link" type="button" onclick={() => this.differentAccount()}>
+ Different account
+ </button>
+ </div>
+ </div>
+ );
+ },
+
renderIdentifier(this: any) {
return (
<form
@@ -191,6 +284,11 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
/>
{this.error ? <p class="auth-error">{this.error.message}</p> : null}
<div class="auth-actions">
+ {this.accounts.length >= 2 ? (
+ <button class="auth-link" type="button" onclick={() => this.backToAccounts()}>
+ Back to accounts
+ </button>
+ ) : null}
<button class="auth-button" type="submit" disabled={this.pending || !this.identifier.trim()}>
{this.pending ? 'Checking' : 'Next'}
</button>
diff --git a/server/web/src/util/api.ts b/server/web/src/util/api.ts
@@ -45,6 +45,18 @@ export interface SessionScope {
client_id: string | null;
}
+export interface SessionAccount {
+ public_id: string;
+ active: boolean;
+ user: {
+ id: string;
+ username: string;
+ display_name: string | null;
+ };
+ created_at: number;
+ expires_at: number;
+}
+
export interface SessionInfo {
scope: SessionScope;
realm: RealmInfo | null;
@@ -56,6 +68,18 @@ export interface SessionInfo {
roles: string[];
is_system_admin: boolean;
expires_at: number;
+ accounts: SessionAccount[];
+}
+
+export interface SelectSessionResult {
+ ok: boolean;
+ user: {
+ id: string;
+ username: string;
+ display_name: string | null;
+ };
+ expires_at: number;
+ pending_auth_request: boolean;
}
export interface ApiError extends Error {
@@ -132,6 +156,19 @@ export function getSession(): Promise<SessionInfo> {
return request<SessionInfo>('/api/v1/session');
}
+export function selectSession(
+ publicId: string,
+ clientId?: string | null
+): Promise<SelectSessionResult> {
+ return request<SelectSessionResult>('/api/v1/session/select', {
+ method: 'POST',
+ body: JSON.stringify({
+ public_id: publicId,
+ client_id: clientId || undefined,
+ }),
+ });
+}
+
export function signOut(): Promise<{ ok: boolean }> {
return request('/api/v1/logout', { method: 'POST' });
}