auth

Main authentication module for my projects
git clone git://git.finwo.net/app/auth
Log | Files | Refs

commit 4998688953408308ee092cca290e37827f5038e5
parent f6c02605054acc8f99aa81699f505bbf2e610634
Author: finwo <finwo@pm.me>
Date:   Wed, 21 Oct 2026 01:48:44 +0200

Move sessions into system DB with host-scoped cookies

Diffstat:
Aserver/migrations/sqlite/realm/003_remove_sessions.sql | 1+
Aserver/migrations/sqlite/system/005_sessions.sql | 45+++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/controller/login/logout.js | 22+++++++++++-----------
Mserver/src/controller/login/password.js | 25+++++++++++++------------
Mserver/src/controller/login/resolve.js | 20++++++++++++++------
Mserver/src/controller/oidc.js | 11++++++-----
Mserver/src/controller/session/show.js | 31++++++++++++++++++++++---------
Aserver/src/lib/host-context.js | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/src/lib/oidc/context.js | 80++++++++++++++++++++++++++-----------------------------------------------------
Mserver/src/lib/session.js | 394++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mserver/test/http.test.js | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mserver/test/session.test.js | 261+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mserver/web/src/screen/admin.tsx | 20+++++++++-----------
Mserver/web/src/screen/login.tsx | 3+--
Mserver/web/src/util/api.ts | 28+++++++++++++++-------------
15 files changed, 859 insertions(+), 244 deletions(-)

diff --git a/server/migrations/sqlite/realm/003_remove_sessions.sql b/server/migrations/sqlite/realm/003_remove_sessions.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS sessions; diff --git a/server/migrations/sqlite/system/005_sessions.sql b/server/migrations/sqlite/system/005_sessions.sql @@ -0,0 +1,45 @@ +CREATE TABLE session_groups ( + id TEXT PRIMARY KEY, + host TEXT NOT NULL, + active_session_id TEXT, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL +); + +CREATE INDEX session_groups_host ON session_groups(host); + +CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + public_id TEXT NOT NULL UNIQUE, + group_id TEXT NOT NULL REFERENCES session_groups(id) ON DELETE CASCADE, + user_id TEXT NOT NULL, + scope_type TEXT NOT NULL CHECK (scope_type IN ('global', 'realm', 'client')), + scope_host TEXT NOT NULL, + realm_id TEXT REFERENCES realms(id) ON DELETE CASCADE, + client_id TEXT, + ttl INTEGER NOT NULL, + auth_time INTEGER NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + user_agent TEXT, + ip TEXT, + UNIQUE (group_id, user_id) +); + +CREATE INDEX sessions_group ON sessions(group_id); +CREATE INDEX sessions_user ON sessions(user_id); +CREATE INDEX sessions_expires ON sessions(expires_at); +CREATE INDEX sessions_scope ON sessions(scope_type, scope_host); + +CREATE TABLE session_realms ( + session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + realm_id TEXT NOT NULL REFERENCES realms(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + revoked_at INTEGER, + revoked_by TEXT, + PRIMARY KEY (session_id, realm_id) +); + +CREATE INDEX session_realms_realm ON session_realms(realm_id); diff --git a/server/src/controller/login/logout.js b/server/src/controller/login/logout.js @@ -1,22 +1,22 @@ import { app } from '../../app.js'; -import { openRealmDatabase, resolveRealm } from '../../lib/realm.js'; -import { clearSessionCookie, destroySession, requestToken } from '../../lib/session.js'; +import { resolveHostContext } from '../../lib/host-context.js'; +import { getSystemDatabase } from '../../lib/realm.js'; +import { + clearSessionCookie, + destroySession, + requestToken, +} from '../../lib/session.js'; export default { method: 'post', path: '/api/v1/logout', name: 'login.logout', async handler(req, res) { - const body = req.body || {}; - const realm = await resolveRealm({ - host: req.headers.host, - slug: body.realm || undefined, - }); - const realmDb = await openRealmDatabase(realm); - const token = requestToken(req, realm); + await resolveHostContext(req, { publicUrl: app.config.server.public_url }); - await destroySession(realmDb, token); - clearSessionCookie(res, req, realm); + const systemDb = getSystemDatabase(); + const result = await destroySession(systemDb, requestToken(req)); + if (result.groupDeleted) clearSessionCookie(res, req); return new app.HttpOk({ ok: true }); }, diff --git a/server/src/controller/login/password.js b/server/src/controller/login/password.js @@ -1,17 +1,19 @@ import { app } from '../../app.js'; +import { resolveClientForHost, resolveHostContext } from '../../lib/host-context.js'; 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 { verifyDummyPassword, verifyPassword } from '../../lib/password.js'; import { canUseClient } from '../../lib/policy.js'; -import { getSystemDatabase, openRealmDatabase, realmMetadata, resolveRealm } from '../../lib/realm.js'; +import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../../lib/realm.js'; import { LONG_SESSION_TTL, SHORT_SESSION_TTL, - createSession, + createHostSession, purgeExpiredSessions, requestIp, + requestToken, setSessionCookie, } from '../../lib/session.js'; import { @@ -40,21 +42,18 @@ export default { if (typeof body.client_id !== 'string') { throw new HttpError(400, 'invalid_request', 'client_id is required'); } - if (body.realm != null && typeof body.realm !== 'string') { - throw new HttpError(400, 'invalid_request', 'realm must be a string'); - } if (body.long_session != null && typeof body.long_session !== 'boolean') { throw new HttpError(400, 'invalid_request', 'long_session must be a boolean'); } - const realm = await resolveRealm({ - host: req.headers.host, - slug: body.realm || undefined, + const hostContext = await resolveHostContext(req, { + publicUrl: app.config.server.public_url, }); + const { realm, clientId } = await resolveClientForHost(hostContext, body.client_id); const metadata = await realmMetadata(realm); const realmDb = await openRealmDatabase(realm); const systemDb = getSystemDatabase(); - const client = await getClient(realmDb, body.client_id); + const client = await getClient(realmDb, clientId); if (!client || !client.enabled) { throw new HttpError(404, 'unknown_client', 'Unknown client'); } @@ -118,14 +117,16 @@ export default { const longSession = body.long_session === true && metadata.allow_session_duration_choice; const ttl = longSession ? LONG_SESSION_TTL : SHORT_SESSION_TTL; - await purgeExpiredSessions(realmDb); - const { token, session } = await createSession(realmDb, { + await purgeExpiredSessions(systemDb); + const { token, session } = await createHostSession(systemDb, { + context: hostContext, + token: requestToken(req), userId: user.id, ttl, userAgent: req.headers['user-agent'] || null, ip: requestIp(req), }); - setSessionCookie(res, req, realm, token, ttl); + setSessionCookie(res, req, token, session.ttl); await updateLastLogin(systemDb, user.id); return new app.HttpOk({ diff --git a/server/src/controller/login/resolve.js b/server/src/controller/login/resolve.js @@ -1,7 +1,9 @@ import { app } from '../../app.js'; +import { resolveClientForHost, resolveHostContext } from '../../lib/host-context.js'; import { resolveLogin } from '../../lib/login.js'; +import { getClient } from '../../lib/oidc/clients.js'; import { HttpError } from '../../lib/http/http-error.js'; -import { realmMetadata, resolveRealm } from '../../lib/realm.js'; +import { openRealmDatabase, realmMetadata } from '../../lib/realm.js'; export default { method: 'post', @@ -12,14 +14,20 @@ export default { if (typeof body.identifier !== 'string') { throw new HttpError(400, 'invalid_request', 'identifier is required'); } - if (body.realm != null && typeof body.realm !== 'string') { - throw new HttpError(400, 'invalid_request', 'realm must be a string'); + if (typeof body.client_id !== 'string') { + throw new HttpError(400, 'invalid_request', 'client_id is required'); } - const realm = await resolveRealm({ - host: req.headers.host, - slug: body.realm || undefined, + const hostContext = await resolveHostContext(req, { + publicUrl: app.config.server.public_url, }); + const { realm, clientId } = await resolveClientForHost(hostContext, body.client_id); + const realmDb = await openRealmDatabase(realm); + const client = await getClient(realmDb, clientId); + if (!client || !client.enabled) { + throw new HttpError(404, 'unknown_client', 'Unknown client'); + } + const metadata = await realmMetadata(realm); const result = await resolveLogin({ identifier: body.identifier }); diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js @@ -33,6 +33,7 @@ import { } from '../lib/realm.js'; import { authenticateRequest, + bindSessionRealm, clearSessionCookie, destroySession, requestToken, @@ -193,7 +194,7 @@ async function authorize(context, client, req, res) { realmDb: db, req, res, - realm: context.realm, + context, }); const allowed = auth @@ -238,11 +239,11 @@ async function authorize(context, client, req, res) { return redirect(res, endpointUrls(context).login); } - const authTime = Math.floor(auth.session.created_at / 1000); + await bindSessionRealm(systemDb, auth.session.id, context.realm.id); await completeAuthRequest(db, pending.id, { userId: auth.user.id, sessionId: auth.session.id, - authTime, + authTime: auth.session.auth_time, }); const request = await getAuthRequest(db, pending.id); @@ -446,8 +447,8 @@ async function logout(context, client, req, res) { } } - await destroySession(db, requestToken(req, context.realm)); - clearSessionCookie(res, req, context.realm); + const result = await destroySession(getSystemDatabase(), requestToken(req)); + if (result.groupDeleted) clearSessionCookie(res, req); clearAuthRequestCookie(res, req, context.realm); if (postLogoutUri) { diff --git a/server/src/controller/session/show.js b/server/src/controller/session/show.js @@ -1,6 +1,7 @@ import { app } from '../../app.js'; +import { resolveHostContext } from '../../lib/host-context.js'; import { HttpError } from '../../lib/http/http-error.js'; -import { getSystemDatabase, openRealmDatabase, realmMetadata, resolveRealm } from '../../lib/realm.js'; +import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../../lib/realm.js'; import { isSystemAdmin } from '../../lib/policy.js'; import { authenticateRequest } from '../../lib/session.js'; @@ -9,26 +10,37 @@ export default { path: '/api/v1/session', name: 'session.show', async handler(req, res) { - const url = new URL(req.url, 'http://localhost'); - const realm = await resolveRealm({ - host: req.headers.host, - slug: url.searchParams.get('realm') || undefined, + const hostContext = await resolveHostContext(req, { + publicUrl: app.config.server.public_url, }); - const metadata = await realmMetadata(realm); - const realmDb = await openRealmDatabase(realm); + const realmDb = hostContext.realm ? await openRealmDatabase(hostContext.realm) : null; + const metadata = hostContext.realm ? await realmMetadata(hostContext.realm) : null; const auth = await authenticateRequest({ systemDb: getSystemDatabase(), realmDb, req, res, - realm, + context: hostContext, }); - if (!auth || (!isSystemAdmin(auth.user) && (!auth.membership || auth.membership.status !== 'active'))) { + if (!auth) { + throw new HttpError(401, 'not_authenticated', 'Not signed in'); + } + if ( + hostContext.mode !== 'canonical' && + !isSystemAdmin(auth.user) && + (!auth.membership || auth.membership.status !== 'active') + ) { throw new HttpError(401, 'not_authenticated', 'Not signed in'); } return new app.HttpOk({ + scope: { + type: auth.session.scope_type, + host: auth.session.scope_host, + realm_id: auth.session.realm_id, + client_id: auth.session.client_id, + }, realm: metadata, user: { id: auth.user.id, @@ -36,6 +48,7 @@ export default { display_name: auth.user.display_name, }, roles: auth.roles, + is_system_admin: isSystemAdmin(auth.user), expires_at: auth.session.expires_at, }); }, diff --git a/server/src/lib/host-context.js b/server/src/lib/host-context.js @@ -0,0 +1,68 @@ +import { HttpError } from './http/http-error.js'; +import { isVirtualClient } from './oidc/clients.js'; +import { findClientRealm, findOidcClientHost, findRealmHost, normalizeHost } from './realm.js'; + +export async function resolveHostContext(req, { publicUrl } = {}) { + const host = normalizeHost(req.headers.host); + + const clientHost = await findOidcClientHost(host); + if (clientHost) { + return { + mode: 'client', + host, + realm: { + id: clientHost.realm_id, + slug: clientHost.slug, + db_file: clientHost.db_file, + owner_user_id: clientHost.owner_user_id, + }, + clientId: clientHost.client_id, + }; + } + + const realmHost = await findRealmHost(host); + if (realmHost) { + return { mode: 'realm', host, realm: realmHost }; + } + + if (publicUrl) { + const canonicalHost = normalizeHost(new URL(publicUrl).host); + if (host === canonicalHost) return { mode: 'canonical', host }; + } + + throw new HttpError(404, 'not_found', 'Not found'); +} + +export async function resolveClientForHost(context, clientId) { + const value = String(clientId || '').trim(); + if (!value) throw new HttpError(400, 'invalid_request', 'client_id is required'); + + if (context.mode === 'client') { + if (value !== context.clientId) { + throw new HttpError(404, 'unknown_client', 'Unknown client'); + } + return { realm: context.realm, clientId: context.clientId }; + } + + if (context.mode === 'realm' && isVirtualClient(value)) { + return { realm: context.realm, clientId: value }; + } + + const mapping = await findClientRealm(value); + if (!mapping || !mapping.realm_id) { + throw new HttpError(404, 'unknown_client', 'Unknown client'); + } + if (context.mode === 'realm' && mapping.realm_id !== context.realm.id) { + throw new HttpError(404, 'unknown_client', 'Unknown client'); + } + + return { + realm: { + id: mapping.realm_id, + slug: mapping.slug, + db_file: mapping.db_file, + owner_user_id: mapping.owner_user_id, + }, + clientId: value, + }; +} diff --git a/server/src/lib/oidc/context.js b/server/src/lib/oidc/context.js @@ -1,17 +1,12 @@ import { HttpError } from '../http/http-error.js'; +import { resolveClientForHost, resolveHostContext } from '../host-context.js'; import { isVirtualClient } from './clients.js'; -import { - findClientRealm, - findOidcClientHost, - findRealmHost, - normalizeHost, -} from '../realm.js'; export function requestOrigin(req) { - const proto = String(req.headers['x-forwarded-proto'] || '') + const forwarded = String(req.headers['x-forwarded-proto'] || '') .split(',')[0] - .trim() - .toLowerCase() || (req.socket?.encrypted ? 'https' : 'http'); + .trim(); + const proto = forwarded || (req.socket?.encrypted ? 'https' : 'http'); return `${proto}://${req.headers.host}`; } @@ -31,69 +26,46 @@ function pathSegments(req) { export async function resolveOidcContext(req, { publicUrl } = {}) { const segments = pathSegments(req); const origin = requestOrigin(req); + const hostContext = await resolveHostContext(req, { publicUrl }); - const clientHost = await findOidcClientHost(req.headers.host); - if (clientHost) { + if (hostContext.mode === 'client') { if (segments.length !== 1) throw new HttpError(404, 'not_found', 'Not found'); return { mode: 'client', + host: hostContext.host, origin, - realm: { - id: clientHost.realm_id, - slug: clientHost.slug, - db_file: clientHost.db_file, - owner_user_id: clientHost.owner_user_id, - }, - clientId: clientHost.client_id, + realm: hostContext.realm, + clientId: hostContext.clientId, action: segments[0], }; } - const realmHost = await findRealmHost(req.headers.host); - if (realmHost) { - if (segments.length !== 2) throw new HttpError(404, 'not_found', 'Not found'); - const clientId = segments[0]; - if (!isVirtualClient(clientId)) { - const mapping = await findClientRealm(clientId); - if (!mapping || mapping.realm_id !== realmHost.id) { - throw new HttpError(404, 'unknown_client', 'Unknown client'); - } - } + if (segments.length !== 2) throw new HttpError(404, 'not_found', 'Not found'); + const clientId = segments[0]; + const action = segments[1]; + + if (hostContext.mode === 'realm') { + const resolved = isVirtualClient(clientId) + ? { realm: hostContext.realm, clientId } + : await resolveClientForHost(hostContext, clientId); return { mode: 'realm', + host: hostContext.host, origin, - realm: realmHost, - clientId, - action: segments[1], + realm: resolved.realm, + clientId: resolved.clientId, + action, }; } - if (segments.length !== 2) throw new HttpError(404, 'not_found', 'Not found'); - - if (publicUrl) { - const canonicalHost = normalizeHost(new URL(publicUrl).host); - if (normalizeHost(req.headers.host) !== canonicalHost) { - throw new HttpError(404, 'not_found', 'Not found'); - } - } - - const clientId = segments[0]; - const mapping = await findClientRealm(clientId); - if (!mapping || !mapping.realm_id) { - throw new HttpError(404, 'unknown_client', 'Unknown client'); - } - + const resolved = await resolveClientForHost(hostContext, clientId); return { mode: 'canonical', + host: hostContext.host, origin, - realm: { - id: mapping.realm_id, - slug: mapping.slug, - db_file: mapping.db_file, - owner_user_id: mapping.owner_user_id, - }, - clientId, - action: segments[1], + realm: resolved.realm, + clientId: resolved.clientId, + action, }; } diff --git a/server/src/lib/session.js b/server/src/lib/session.js @@ -4,12 +4,9 @@ import { findUserById, getMembership, getUserRoles } from './users.js'; export const SHORT_SESSION_TTL = 12 * 60 * 60; export const LONG_SESSION_TTL = 7 * 24 * 60 * 60; +export const SESSION_COOKIE = 'auth_session'; const TOUCH_INTERVAL_MS = 60 * 1000; -export function sessionCookieName(realm) { - return `auth_session_${realm.slug}`; -} - function isSecureRequest(req) { if (req.socket?.encrypted) return true; const proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim().toLowerCase(); @@ -26,11 +23,11 @@ function appendSetCookie(res, value) { res.setHeader('Set-Cookie', [...values, value]); } -export function setSessionCookie(res, req, realm, token, ttl) { +export function setSessionCookie(res, req, token, ttl) { appendSetCookie( res, stringifySetCookie({ - name: sessionCookieName(realm), + name: SESSION_COOKIE, value: token, httpOnly: true, sameSite: 'lax', @@ -41,11 +38,11 @@ export function setSessionCookie(res, req, realm, token, ttl) { ); } -export function clearSessionCookie(res, req, realm) { +export function clearSessionCookie(res, req) { appendSetCookie( res, stringifySetCookie({ - name: sessionCookieName(realm), + name: SESSION_COOKIE, value: '', httpOnly: true, sameSite: 'lax', @@ -56,9 +53,9 @@ export function clearSessionCookie(res, req, realm) { ); } -export function requestToken(req, realm) { +export function requestToken(req) { const cookies = parseCookie(req.headers.cookie || ''); - return cookies[sessionCookieName(realm)] || null; + return cookies[SESSION_COOKIE] || null; } export function requestIp(req) { @@ -72,100 +69,353 @@ function hashToken(token) { return crypto.createHash('sha256').update(token).digest('hex'); } -export async function purgeExpiredSessions(db, now = Date.now()) { - await db.run('DELETE FROM sessions WHERE expires_at <= {now}', { now }); -} - -export async function createSession(db, { userId, ttl, userAgent = null, ip = null }, now = Date.now()) { - const token = crypto.randomBytes(32).toString('base64url'); - const session = { - id: hashToken(token), - user_id: userId, - ttl, - created_at: now, - expires_at: now + ttl * 1000, - last_seen_at: now, - user_agent: userAgent, - ip, +function scopeForContext(context) { + if (context.mode === 'canonical') { + return { scopeType: 'global', realmId: null, clientId: null }; + } + if (context.mode === 'realm') { + return { scopeType: 'realm', realmId: context.realm.id, clientId: null }; + } + return { + scopeType: 'client', + realmId: context.realm.id, + clientId: context.clientId, }; +} - await db.run( - `INSERT INTO sessions - (id, user_id, ttl, created_at, expires_at, last_seen_at, user_agent, ip) - VALUES - ({id}, {userId}, {ttl}, {createdAt}, {expiresAt}, {lastSeenAt}, {userAgent}, {ip})`, - { - id: session.id, - userId: session.user_id, - ttl: session.ttl, - createdAt: session.created_at, - expiresAt: session.expires_at, - lastSeenAt: session.last_seen_at, - userAgent: session.user_agent, - ip: session.ip, - } +function scopeMatches(session, context) { + if (session.scope_host !== context.host) return false; + if (context.mode === 'canonical') return session.scope_type === 'global'; + if (context.mode === 'realm') { + return session.scope_type === 'realm' && session.realm_id === context.realm.id; + } + return ( + session.scope_type === 'client' && + session.realm_id === context.realm.id && + session.client_id === context.clientId ); - - return { token, session }; } -export async function getSessionByToken(db, token, now = Date.now()) { +async function findGroupByToken(systemDb, token) { if (!token) return null; - const session = await db.get( - `SELECT id, user_id, ttl, created_at, expires_at, last_seen_at, user_agent, ip - FROM sessions + return systemDb.get( + `SELECT id, host, active_session_id, created_at, last_seen_at + FROM session_groups WHERE id = {id}`, { id: hashToken(token) } ); - if (!session) return null; - if (session.expires_at <= now) { - await db.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); - return null; - } - return session; } -export async function destroySession(db, token) { - if (!token) return; - await db.run('DELETE FROM sessions WHERE id = {id}', { id: hashToken(token) }); +async function findActiveSession(systemDb, group) { + if (!group?.active_session_id) return null; + return systemDb.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 id = {id} AND group_id = {groupId}`, + { id: group.active_session_id, groupId: group.id } + ); +} + +export async function getSessionByToken(systemDb, token, now = Date.now()) { + const group = await findGroupByToken(systemDb, token); + if (!group) return null; + const session = await findActiveSession(systemDb, group); + if (!session || session.expires_at <= now) return null; + return { group, session }; +} + +async function deleteGroup(systemDb, groupId) { + await systemDb.run('DELETE FROM session_groups WHERE id = {id}', { id: groupId }); +} + +async function nextActiveSession(systemDb, groupId, now) { + return systemDb.get( + `SELECT id + FROM sessions + WHERE group_id = {groupId} AND expires_at > {now} + ORDER BY created_at DESC + LIMIT 1`, + { groupId, now } + ); +} + +export async function purgeExpiredSessions(systemDb, now = Date.now()) { + await systemDb.transaction(async (tx) => { + await tx.run('DELETE FROM sessions WHERE expires_at <= {now}', { now }); + await tx.run( + 'DELETE FROM session_groups WHERE id NOT IN (SELECT group_id FROM sessions)' + ); + }); +} + +export async function createHostSession( + systemDb, + { context, token = null, userId, ttl, userAgent = null, ip = null }, + now = Date.now() +) { + const scope = scopeForContext(context); + + return systemDb.transaction(async (tx) => { + let group = await findGroupByToken(tx, token); + + if (group && group.host === context.host) { + 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, + user_agent, ip + FROM sessions + WHERE group_id = {groupId} AND user_id = {userId}`, + { groupId: group.id, userId } + ); + + if ( + existing && + existing.expires_at > now && + existing.scope_type === scope.scopeType && + existing.scope_host === context.host && + existing.realm_id === scope.realmId && + existing.client_id === scope.clientId + ) { + const sessionTtl = Math.max(existing.ttl, ttl); + const expiresAt = Math.max(existing.expires_at, now + sessionTtl * 1000); + await tx.run( + `UPDATE sessions + SET ttl = {ttl}, expires_at = {expiresAt}, last_seen_at = {now}, + user_agent = {userAgent}, ip = {ip} + WHERE id = {id}`, + { ttl: sessionTtl, expiresAt, now, userAgent, ip, id: existing.id } + ); + await tx.run( + `UPDATE session_groups + SET active_session_id = {sessionId}, last_seen_at = {now} + WHERE id = {groupId}`, + { sessionId: existing.id, now, groupId: group.id } + ); + return { + token, + group: { ...group, active_session_id: existing.id, last_seen_at: now }, + session: { + ...existing, + ttl: sessionTtl, + expires_at: expiresAt, + last_seen_at: now, + user_agent: userAgent, + ip, + }, + }; + } + + await deleteGroup(tx, group.id); + group = null; + } + + 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, + } + ); + + 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, + ttl, + auth_time: authTime, + created_at: createdAt, + expires_at: expiresAt, + last_seen_at: now, + user_agent: userAgent, + ip, + }; + + return { + token: nextToken, + group: { + id: groupId, + host: context.host, + active_session_id: sessionId, + created_at: createdAt, + last_seen_at: now, + }, + session, + }; + }); } export async function authenticateRequest({ systemDb, - realmDb, + realmDb = null, req, res, - realm, + context, now = Date.now(), }) { - const token = requestToken(req, realm); + const token = requestToken(req); if (!token) return null; - const session = await getSessionByToken(realmDb, token, now); - if (!session) return null; + const group = await findGroupByToken(systemDb, token); + if (!group || group.host !== context.host) { + clearSessionCookie(res, req); + return null; + } + + const session = await findActiveSession(systemDb, group); + if (!session || session.expires_at <= now) { + if (session) { + await systemDb.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); + } + const next = await nextActiveSession(systemDb, group.id, now); + if (next) { + await systemDb.run( + 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', + { sessionId: next.id, id: group.id } + ); + } else { + await deleteGroup(systemDb, group.id); + clearSessionCookie(res, req); + } + return null; + } + + if (!scopeMatches(session, context)) { + clearSessionCookie(res, req); + return null; + } const user = await findUserById(systemDb, session.user_id); if (!user || user.status !== 'active') { - await destroySession(realmDb, token); - clearSessionCookie(res, req, realm); + await deleteGroup(systemDb, group.id); + clearSessionCookie(res, req); return null; } - const membership = await getMembership(realmDb, user.id); + const membership = realmDb ? await getMembership(realmDb, user.id) : null; + const roles = realmDb ? await getUserRoles(realmDb, user.id) : []; if (now - session.last_seen_at >= TOUCH_INTERVAL_MS) { const expiresAt = now + session.ttl * 1000; - await realmDb.run( - `UPDATE sessions - SET last_seen_at = {now}, expires_at = {expiresAt} - WHERE id = {id}`, - { now, expiresAt, id: session.id } - ); + await systemDb.transaction(async (tx) => { + 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 last_seen_at = {now} WHERE id = {id}', + { now, id: group.id } + ); + }); session.last_seen_at = now; session.expires_at = expiresAt; - setSessionCookie(res, req, realm, token, session.ttl); + setSessionCookie(res, req, token, session.ttl); } - const roles = await getUserRoles(realmDb, user.id); - return { session, user, membership, roles }; + return { group, session, user, membership, roles }; +} + +export async function destroySession(systemDb, token) { + if (!token) return { groupDeleted: true }; + + return systemDb.transaction(async (tx) => { + const group = await findGroupByToken(tx, token); + if (!group) return { groupDeleted: true }; + + const session = await findActiveSession(tx, group); + if (session) { + await tx.run('DELETE FROM sessions WHERE id = {id}', { id: session.id }); + } + + const next = await nextActiveSession(tx, group.id, Date.now()); + if (next) { + await tx.run( + 'UPDATE session_groups SET active_session_id = {sessionId} WHERE id = {id}', + { sessionId: next.id, id: group.id } + ); + return { groupDeleted: false }; + } + + await deleteGroup(tx, group.id); + return { groupDeleted: true }; + }); +} + +export async function bindSessionRealm(systemDb, sessionId, realmId, now = Date.now()) { + const existing = await systemDb.get( + `SELECT session_id, realm_id, revoked_at + FROM session_realms + WHERE session_id = {sessionId} AND realm_id = {realmId}`, + { sessionId, realmId } + ); + + if (existing) { + if (!existing.revoked_at) { + await systemDb.run( + `UPDATE session_realms + SET last_seen_at = {now} + WHERE session_id = {sessionId} AND realm_id = {realmId}`, + { now, sessionId, realmId } + ); + } + return; + } + + await systemDb.run( + `INSERT INTO session_realms + (session_id, realm_id, created_at, last_seen_at, revoked_at, revoked_by) + VALUES + ({sessionId}, {realmId}, {now}, {now}, NULL, NULL)`, + { sessionId, realmId, now } + ); } diff --git a/server/test/http.test.js b/server/test/http.test.js @@ -7,6 +7,7 @@ import http from 'node:http'; import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; import { fileURLToPath } from 'node:url'; import { createLocalJWKSet, jwtVerify } from 'jose'; @@ -268,7 +269,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { const password = await acme({ method: 'POST', path: '/api/v1/login/resolve', - body: { identifier: 'alice@acme.test' }, + body: { client_id: 'internal-app', identifier: 'alice@acme.test' }, }); assert.equal(password.status, 200); assert.equal(password.json.next, 'password'); @@ -276,7 +277,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { const upstream = await acme({ method: 'POST', path: '/api/v1/login/resolve', - body: { identifier: 'someone@sso.acme.test' }, + body: { client_id: 'internal-app', identifier: 'someone@sso.acme.test' }, }); assert.equal(upstream.status, 200); assert.equal(upstream.json.next, 'oidc'); @@ -292,11 +293,81 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(response.status, 200); assert.equal(response.json.user.username, 'alice'); assert.equal(maxAge(response), 12 * 60 * 60); + assert.ok(responseCookies(response)[0].startsWith('auth_session=')); const cookie = mergeCookies('', response); const session = await acme({ path: '/api/v1/session', cookie }); assert.equal(session.status, 200); assert.equal(session.json.user.username, 'alice'); + assert.equal(session.json.scope.type, 'realm'); + assert.equal(session.json.scope.host, 'acme.localhost'); + assert.equal(session.json.realm.slug, 'acme'); + }); + + await t.test('canonical and client hosts create their own session scopes', async () => { + const canonical = await identity({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + assert.equal(canonical.status, 200); + const canonicalCookie = mergeCookies('', canonical); + const canonicalSession = await identity({ + path: '/api/v1/session', + cookie: canonicalCookie, + }); + assert.equal(canonicalSession.status, 200); + assert.equal(canonicalSession.json.scope.type, 'global'); + assert.equal(canonicalSession.json.scope.host, 'identity.test'); + assert.equal(canonicalSession.json.realm, null); + + const client = await app({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + assert.equal(client.status, 200); + const clientSession = await app({ + path: '/api/v1/session', + cookie: mergeCookies('', client), + }); + assert.equal(clientSession.status, 200); + assert.equal(clientSession.json.scope.type, 'client'); + assert.equal(clientSession.json.scope.host, 'app.acme.localhost'); + assert.equal(clientSession.json.scope.client_id, 'internal-app'); + assert.equal(clientSession.json.realm.slug, 'acme'); + }); + + await t.test('sessions are scoped to their host and old cookies are rejected', async () => { + const login = await acme({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + const cookie = mergeCookies('', login); + const token = cookie.slice('auth_session='.length); + + const wrongHost = await globex({ path: '/api/v1/session', cookie }); + assert.equal(wrongHost.status, 401); + + const oldCookie = `auth_session_acme=${token}`; + const oldStyle = await acme({ path: '/api/v1/session', cookie: oldCookie }); + assert.equal(oldStyle.status, 401); + }); + + await t.test('unknown hosts are rejected by auth and session APIs', async () => { + const unknown = (options = {}) => + request(port, { host: `unknown.test:${port}`, ...options }); + + const login = await unknown({ + method: 'POST', + path: '/api/v1/login/password', + body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' }, + }); + assert.equal(login.status, 404); + + const session = await unknown({ path: '/api/v1/session' }); + assert.equal(session.status, 404); }); await t.test('long sessions are only issued when requested', async () => { @@ -472,7 +543,6 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { method: 'POST', path: '/api/v1/login/password', body: { - realm: 'acme', client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo', @@ -502,6 +572,22 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { }, }); assert.equal(tokenResponse.status, 200); + + const database = new DatabaseSync(env.AUTH_DATABASE_PATH, { readOnly: true }); + try { + const binding = database + .prepare( + `SELECT COUNT(*) AS count + FROM session_realms sr + JOIN sessions s ON s.id = sr.session_id + JOIN realms r ON r.id = sr.realm_id + WHERE r.slug = 'acme' AND s.scope_type = 'global'` + ) + .get(); + assert.equal(binding.count, 1); + } finally { + database.close(); + } }); await t.test('public clients allow non-members through authorize', async () => { @@ -625,7 +711,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => { assert.equal(tokenResponse.status, 200); }); - await t.test('logout removes only the current realm session', async () => { + await t.test('logout removes only the current host session', async () => { const acmeLogin = await acme({ method: 'POST', path: '/api/v1/login/password', diff --git a/server/test/session.test.js b/server/test/session.test.js @@ -12,15 +12,28 @@ import { openRealmDatabase, } from '../src/lib/realm.js'; import { + SESSION_COOKIE, SHORT_SESSION_TTL, authenticateRequest, - createSession, + bindSessionRealm, + createHostSession, destroySession, getSessionByToken, - sessionCookieName, } from '../src/lib/session.js'; import { createUser, ensureMembership } from '../src/lib/users.js'; +function realmContext(realm, host = 'acme.localhost') { + return { mode: 'realm', host, realm }; +} + +function clientContext(realm, host = 'app.acme.localhost', clientId = 'internal-app') { + return { mode: 'client', host, realm, clientId }; +} + +function canonicalContext(host = 'identity.test') { + return { mode: 'canonical', host }; +} + async function setup() { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'auth-session-')); const cfg = { @@ -59,10 +72,12 @@ function mockResponse() { }; } -test('sessions store only the token hash and authenticate the user', async () => { +test('sessions store only the group token hash and authenticate the user', async () => { const { dir, realm, realmDb, systemDb, userId } = await setup(); try { - const { token } = await createSession(realmDb, { + const context = realmContext(realm); + const { token, group, session } = await createHostSession(systemDb, { + context, userId, ttl: SHORT_SESSION_TTL, userAgent: 'test', @@ -70,13 +85,21 @@ test('sessions store only the token hash and authenticate the user', async () => }); const id = crypto.createHash('sha256').update(token).digest('hex'); - const session = await getSessionByToken(realmDb, token); - assert.equal(session.id, id); - assert.notEqual(session.id, token); + assert.equal(group.id, id); + assert.notEqual(session.public_id, token); + + const found = await getSessionByToken(systemDb, token); + assert.equal(found.session.id, session.id); - const req = mockRequest(`${sessionCookieName(realm)}=${token}`); + const req = mockRequest(`${SESSION_COOKIE}=${token}`); const res = mockResponse(); - const auth = await authenticateRequest({ systemDb, realmDb, req, res, realm }); + const auth = await authenticateRequest({ + systemDb, + realmDb, + req, + res, + context, + }); assert.equal(auth.user.id, userId); assert.equal(auth.membership.status, 'active'); } finally { @@ -85,15 +108,43 @@ test('sessions store only the token hash and authenticate the user', async () => } }); +test('host scopes are stored from the request context', async () => { + const { dir, realm, systemDb, userId } = await setup(); + try { + const global = await createHostSession(systemDb, { + context: canonicalContext(), + userId, + ttl: SHORT_SESSION_TTL, + }); + assert.equal(global.session.scope_type, 'global'); + assert.equal(global.session.scope_host, 'identity.test'); + assert.equal(global.session.realm_id, null); + + const client = await createHostSession(systemDb, { + context: clientContext(realm), + userId, + ttl: SHORT_SESSION_TTL, + }); + assert.equal(client.session.scope_type, 'client'); + assert.equal(client.session.scope_host, 'app.acme.localhost'); + assert.equal(client.session.realm_id, realm.id); + assert.equal(client.session.client_id, 'internal-app'); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +}); + test('sliding sessions extend expiry and reissue the cookie', async () => { const { dir, realm, realmDb, systemDb, userId } = await setup(); try { - const { token, session } = await createSession( - realmDb, - { userId, ttl: SHORT_SESSION_TTL }, + const context = realmContext(realm); + const { token, session } = await createHostSession( + systemDb, + { context, userId, ttl: SHORT_SESSION_TTL }, 1000 ); - const req = mockRequest(`${sessionCookieName(realm)}=${token}`); + const req = mockRequest(`${SESSION_COOKIE}=${token}`); const res = mockResponse(); await authenticateRequest({ @@ -101,13 +152,14 @@ test('sliding sessions extend expiry and reissue the cookie', async () => { realmDb, req, res, - realm, + context, now: 1000 + 61_000, }); - const updated = await realmDb.get('SELECT expires_at, last_seen_at FROM sessions WHERE id = {id}', { - id: session.id, - }); + const updated = await systemDb.get( + 'SELECT expires_at, last_seen_at FROM sessions WHERE id = {id}', + { id: session.id } + ); assert.equal(updated.expires_at, 1000 + 61_000 + SHORT_SESSION_TTL * 1000); assert.ok(res.getHeader('set-cookie')); } finally { @@ -116,12 +168,28 @@ test('sliding sessions extend expiry and reissue the cookie', async () => { } }); -test('expired sessions are rejected and removed', async () => { - const { dir, realmDb, userId } = await setup(); +test('expired sessions are rejected and their group is removed', async () => { + const { dir, realm, realmDb, systemDb, userId } = await setup(); try { - const { token, session } = await createSession(realmDb, { userId, ttl: 1 }, 1000); - assert.equal(await getSessionByToken(realmDb, token, 3000), null); - const row = await realmDb.get('SELECT id FROM sessions WHERE id = {id}', { id: session.id }); + const context = realmContext(realm); + const { token, group } = await createHostSession( + systemDb, + { context, userId, ttl: 1 }, + 1000 + ); + + assert.equal(await getSessionByToken(systemDb, token, 3000), null); + await authenticateRequest({ + systemDb, + realmDb, + req: mockRequest(`${SESSION_COOKIE}=${token}`), + res: mockResponse(), + context, + now: 3000, + }); + const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { + id: group.id, + }); assert.equal(row, undefined); } finally { await closeRealms(); @@ -129,50 +197,153 @@ test('expired sessions are rejected and removed', async () => { } }); -test('disabled users lose access and suspended memberships are returned', async () => { +test('disabled users lose access and their session group is removed', async () => { const { dir, realm, realmDb, systemDb, userId } = await setup(); try { - const { token } = await createSession(realmDb, { userId, ttl: SHORT_SESSION_TTL }); - const req = mockRequest(`${sessionCookieName(realm)}=${token}`); + const context = realmContext(realm); + const { token, group } = await createHostSession(systemDb, { + context, + userId, + ttl: SHORT_SESSION_TTL, + }); await systemDb.run('UPDATE users SET status = {status} WHERE id = {id}', { status: 'disabled', id: userId, }); assert.equal( - await authenticateRequest({ systemDb, realmDb, req, res: mockResponse(), realm }), + await authenticateRequest({ + systemDb, + realmDb, + req: mockRequest(`${SESSION_COOKIE}=${token}`), + res: mockResponse(), + context, + }), null ); - await systemDb.run('UPDATE users SET status = {status} WHERE id = {id}', { - status: 'active', - id: userId, + const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { + id: group.id, }); - await realmDb.run('UPDATE realm_memberships SET status = {status} WHERE user_id = {id}', { - status: 'suspended', - id: userId, + assert.equal(row, undefined); + } 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 { + const context = realmContext(realm); + const { token, group } = await createHostSession(systemDb, { + context, + userId, + ttl: SHORT_SESSION_TTL, }); - const fresh = await createSession(realmDb, { userId, ttl: SHORT_SESSION_TTL }); - const auth = await authenticateRequest({ - systemDb, - realmDb, - req: mockRequest(`${sessionCookieName(realm)}=${fresh.token}`), - res: mockResponse(), - realm, + + assert.equal( + await authenticateRequest({ + systemDb, + realmDb, + req: mockRequest(`${SESSION_COOKIE}=${token}`), + res: mockResponse(), + context: clientContext(realm), + }), + null + ); + + const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { + id: group.id, }); - assert.equal(auth.membership.status, 'suspended'); + assert.equal(row.id, group.id); } finally { await closeRealms(); await fs.rm(dir, { recursive: true, force: true }); } }); -test('logout deletes the session', async () => { - const { dir, realmDb, userId } = await setup(); +test('the same user reuses a group and a different user replaces it', async () => { + const { dir, realm, systemDb, userId } = await setup(); try { - const { token } = await createSession(realmDb, { userId, ttl: SHORT_SESSION_TTL }); - await destroySession(realmDb, token); - assert.equal(await getSessionByToken(realmDb, token), null); + const context = realmContext(realm); + const first = await createHostSession(systemDb, { + context, + userId, + ttl: SHORT_SESSION_TTL, + }); + const second = await createHostSession(systemDb, { + context, + token: first.token, + userId, + ttl: SHORT_SESSION_TTL, + }); + assert.equal(second.group.id, first.group.id); + assert.equal(second.session.id, first.session.id); + + const otherId = await createUser(systemDb, { username: 'bob', displayName: 'Bob' }); + const third = await createHostSession(systemDb, { + context, + token: first.token, + userId: otherId, + ttl: SHORT_SESSION_TTL, + }); + assert.notEqual(third.group.id, first.group.id); + 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); + } finally { + await closeRealms(); + await fs.rm(dir, { recursive: true, force: true }); + } +}); + +test('logout deletes the active session and group', async () => { + const { dir, realm, systemDb, userId } = await setup(); + try { + const { token, group } = await createHostSession(systemDb, { + context: realmContext(realm), + userId, + ttl: SHORT_SESSION_TTL, + }); + + const result = await destroySession(systemDb, token); + assert.equal(result.groupDeleted, true); + assert.equal(await getSessionByToken(systemDb, token), null); + + const row = await systemDb.get('SELECT id FROM session_groups WHERE id = {id}', { + id: group.id, + }); + assert.equal(row, undefined); + } 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 { + const { session } = await createHostSession(systemDb, { + context: canonicalContext(), + userId, + ttl: SHORT_SESSION_TTL, + }); + + await bindSessionRealm(systemDb, session.id, realm.id, 1000); + await bindSessionRealm(systemDb, session.id, realm.id, 2000); + + const rows = await systemDb.all( + `SELECT session_id, realm_id, last_seen_at + FROM session_realms + WHERE session_id = {sessionId}`, + { sessionId: session.id } + ); + assert.equal(rows.length, 1); + assert.equal(rows[0].last_seen_at, 2000); } finally { await closeRealms(); await fs.rm(dir, { recursive: true, force: true }); diff --git a/server/web/src/screen/admin.tsx b/server/web/src/screen/admin.tsx @@ -1,25 +1,23 @@ import m from 'mithril'; import { getSession, signOut, type ApiError, type SessionInfo } from '../util/api'; -export const Admin: m.Component<{ realm?: string }> = { - realmSlug: null as string | null, +export const Admin: m.Component = { session: null as SessionInfo | null, error: null as Error | null, pending: false, - oninit(this: any, vnode: any) { - this.realmSlug = vnode.attrs.realm ?? null; + oninit(this: any) { this.load(); }, async load(this: any) { try { - this.session = await getSession(this.realmSlug); - document.title = this.session.realm.display_name; + this.session = await getSession(); + document.title = this.session.realm?.display_name || 'Identity'; } catch (e) { const error = e as ApiError; if (error.status === 401) { - m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/login` : '/login'); + m.route.set('/oidc/admin/login'); return; } this.error = error; @@ -31,8 +29,8 @@ export const Admin: m.Component<{ realm?: string }> = { this.pending = true; this.error = null; try { - await signOut(this.realmSlug); - m.route.set(this.realmSlug ? `/realms/${this.realmSlug}/login` : '/login'); + await signOut(); + m.route.set('/oidc/admin/login'); } catch (e) { this.error = e as Error; this.pending = false; @@ -42,7 +40,7 @@ export const Admin: m.Component<{ realm?: string }> = { view(this: any) { const session = this.session; - const branding = session?.realm.branding || {}; + const branding = session?.realm?.branding || {}; const primary = typeof branding.primary_color === 'string' ? branding.primary_color : '#25A'; const style = { '--realm-primary': primary } as any; @@ -60,7 +58,7 @@ export const Admin: m.Component<{ realm?: string }> = { return ( <div class="auth-page" style={style}> <div class="auth-card"> - <h1>{session.realm.display_name}</h1> + <h1>{session.realm?.display_name || 'Identity'}</h1> <p class="auth-identifier"> Signed in as {session.user.display_name || session.user.username} </p> diff --git a/server/web/src/screen/login.tsx b/server/web/src/screen/login.tsx @@ -79,7 +79,7 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { this.pending = true; this.error = null; try { - const result = await resolveLogin(this.realmSlug, this.clientId, this.identifier); + const result = await resolveLogin(this.clientId, this.identifier); if (result.next === 'oidc' && result.provider) { this.provider = result.provider; this.step = 'oidc'; @@ -98,7 +98,6 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = { this.error = null; try { const result = await signInPassword( - this.realmSlug, this.clientId, this.identifier, this.password, diff --git a/server/web/src/util/api.ts b/server/web/src/util/api.ts @@ -38,14 +38,23 @@ export interface PasswordLoginResult { pending_auth_request: boolean; } +export interface SessionScope { + type: 'global' | 'realm' | 'client'; + host: string; + realm_id: string | null; + client_id: string | null; +} + export interface SessionInfo { - realm: RealmInfo; + scope: SessionScope; + realm: RealmInfo | null; user: { id: string; username: string; display_name: string | null; }; roles: string[]; + is_system_admin: boolean; expires_at: number; } @@ -93,18 +102,16 @@ export function getClientDiscovery(clientId?: string | null): Promise<ClientDisc } export function resolveLogin( - realm: string | null, clientId: string, identifier: string ): Promise<LoginResolution> { return request<LoginResolution>('/api/v1/login/resolve', { method: 'POST', - body: JSON.stringify({ realm: realm || undefined, client_id: clientId, identifier }), + body: JSON.stringify({ client_id: clientId, identifier }), }); } export function signInPassword( - realm: string | null, clientId: string, identifier: string, password: string, @@ -113,7 +120,6 @@ export function signInPassword( return request<PasswordLoginResult>('/api/v1/login/password', { method: 'POST', body: JSON.stringify({ - realm: realm || undefined, client_id: clientId, identifier, password, @@ -122,14 +128,10 @@ export function signInPassword( }); } -export function getSession(realm?: string | null): Promise<SessionInfo> { - const query = realm ? `?realm=${encodeURIComponent(realm)}` : ''; - return request<SessionInfo>(`/api/v1/session${query}`); +export function getSession(): Promise<SessionInfo> { + return request<SessionInfo>('/api/v1/session'); } -export function signOut(realm?: string | null): Promise<{ ok: boolean }> { - return request('/api/v1/logout', { - method: 'POST', - body: JSON.stringify({ realm: realm || undefined }), - }); +export function signOut(): Promise<{ ok: boolean }> { + return request('/api/v1/logout', { method: 'POST' }); }