Files
crosscode-platform/apps/accounts/backend/src/oidc/sessions.ts
T

46 lines
2.3 KiB
TypeScript

/**
* The Accounts session (oidc-provider's own cookie) for the account pages and admin, and signing
* someone out everywhere: every session of theirs ends, and each product that session signed in to
* is told by OIDC Back-Channel Logout (docs/ACCOUNTS-1.0-PLAN.md §3).
*/
import type { Request, Response } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import type { Account } from '../generated/prisma/client.js';
export type SignedIn = { account: Account; amr: string[]; acr: string | null; sessionId: string };
export async function currentSession(ctx: Ctx, provider: Provider, req: Request, res: Response): Promise<SignedIn | null> {
const k = provider.createContext(req, res);
const session = await provider.Session.get(k);
if (!session?.accountId) return null;
const account = await ctx.db.account.findUnique({ where: { id: session.accountId } });
if (!account || account.status !== 'active') return null;
return { account, amr: (session.amr as string[] | undefined) ?? [], acr: (session.acr as string | undefined) ?? null, sessionId: session.jti };
}
type StoredSession = { authorizations?: Record<string, { sid?: string; grantId?: string }> };
/** Ends every session of the account and tells the products. Returns how many products were told. */
export async function signOutEverywhere(ctx: Ctx, provider: Provider, accountId: string): Promise<number> {
const rows = await ctx.db.oidcPayload.findMany({ where: { model: 'Session', accountId } });
let told = 0;
for (const row of rows) {
const auths = (row.payload as StoredSession).authorizations ?? {};
for (const [clientId, auth] of Object.entries(auths)) {
if (auth.grantId) await ctx.db.oidcPayload.deleteMany({ where: { grantId: auth.grantId } });
try {
const client = await provider.Client.find(clientId);
if (client?.backchannelLogoutUri) {
await (client as unknown as { backchannelLogout(sub: string, sid: string): Promise<void> }).backchannelLogout(accountId, auth.sid ?? '');
told++;
}
} catch (e) {
console.warn(`[sessions] back-channel logout to ${clientId} failed:`, (e as Error).message, (e as { cause?: Error }).cause?.message ?? '');
}
}
await ctx.db.oidcPayload.deleteMany({ where: { id: row.id } });
}
return told;
}