feat: move sso and ldap logins into plugins (C2)

This commit is contained in:
LukeGus committed 2026-09-24 18:23:20 -05:00
1 parent 5c18435105
commit 925da4a661
223 files changed
+25778 -6820

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
import type { Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { providers } from "./tables.js";
import { createProviderStore } from "./providers.js";
import { createSsoLogin, METHOD_ID } from "./login.js";
import { PUBLIC_PATHS, registerSsoRoutes } from "./routes.js";
export async function activate(ctx: PluginContext) {
const table = await ctx.db.define(providers);
const store = createProviderStore(ctx, table);
const login = createSsoLogin(ctx, store);
// One button per enabled provider.
ctx.auth.registerLoginMethod({
id: METHOD_ID,
labelKey: "loginWithSso",
icon: "key-round",
kind: "redirect",
external: true,
describe: async () =>
(await store.listInstances()).map((instance) => ({
...instance,
enabled: true,
})),
start: login.start,
callback: login.callback,
});
registerSsoRoutes(
ctx.http.router<Router>({ public: PUBLIC_PATHS }),
ctx,
store,
login,
);
}
export async function deactivate() {
// Everything above was registered through ctx and is disposed by core.
}
+482
View File
@@ -0,0 +1,482 @@
/**
* The OIDC, GitHub and Google sign-in. start builds the provider's authorize
* URL; callback turns the provider's answer into a verified identity. Core
* finds or provisions the user and issues the session.
*/
import crypto from "node:crypto";
import {
LoginMethodError,
type PluginContext,
type PluginLoginRequest,
type PluginVerifiedIdentity,
} from "@termix/plugin-sdk/backend";
import {
OIDCTokenFormatError,
buildFetchOptions,
extractOidcGroupsFromSources,
generatePkceCodeChallenge,
generatePkceCodeVerifier,
getDesktopCallbackUrl,
getNestedValue,
parseOidcRoleMap,
resolveOidcMappedRoles,
verifyOIDCToken,
} from "./oidc-protocol.js";
import {
ENV_INSTANCE_ID,
ENV_PROVIDER_ID,
type ProviderStore,
} from "./providers.js";
import type { OidcConfig, ResolvedProvider } from "./types.js";
export const METHOD_ID = "oidc";
export const CALLBACK_PATH = "/plugin-api/sso/callback";
/** The redirect URI identity providers were set up with before 2.9. */
export const LEGACY_CALLBACK_PATH = "/users/oidc/callback";
const STATE_TTL_MS = 10 * 60 * 1000;
const STATE_PREFIX = "state:";
/** An error raised after the return address is known redirects there. */
export class RedirectLoginError extends LoginMethodError {
constructor(
message: string,
readonly returnTo: string,
status = 400,
code?: string,
) {
super(message, status, code);
this.name = "RedirectLoginError";
}
}
interface PendingState {
nonce: string;
backendCallback: string;
frontendOrigin: string;
rememberMe: boolean;
providerId: number | null;
codeVerifier: string;
createdAt: number;
}
function nonEmpty(value: unknown): value is string {
return typeof value === "string" && value.trim().length > 0;
}
function header(request: PluginLoginRequest, name: string): string {
const value = request.headers[name];
return typeof (Array.isArray(value) ? value[0] : value) === "string"
? String(Array.isArray(value) ? value[0] : value)
: "";
}
export function redirectUriFor(
baseUrl: string,
provider: Pick<ResolvedProvider, "legacyCallback">,
): string {
return `${baseUrl}${provider.legacyCallback ? LEGACY_CALLBACK_PATH : CALLBACK_PATH}`;
}
export type SsoLogin = ReturnType<typeof createSsoLogin>;
export function createSsoLogin(ctx: PluginContext, store: ProviderStore) {
async function saveState(state: string, pending: PendingState) {
// Drop anything abandoned so the store does not grow.
const now = Date.now();
for (const key of await ctx.kv.list()) {
if (!key.startsWith(STATE_PREFIX)) continue;
const entry = (await ctx.kv.get(key)) as PendingState | undefined;
if (!entry || now - entry.createdAt > STATE_TTL_MS) {
await ctx.kv.delete(key);
}
}
await ctx.kv.set(`${STATE_PREFIX}${state}`, pending);
}
async function takeState(state: string): Promise<PendingState | null> {
const key = `${STATE_PREFIX}${state}`;
const entry = (await ctx.kv.get(key)) as PendingState | undefined;
if (!entry) return null;
await ctx.kv.delete(key);
return Date.now() - entry.createdAt > STATE_TTL_MS ? null : entry;
}
function frontendOriginFor(
request: PluginLoginRequest,
baseUrl: string,
): string {
const { desktopCallbackPort, appCallbackUrl } = request.query;
if (desktopCallbackPort !== undefined && desktopCallbackPort !== "") {
const url = getDesktopCallbackUrl(desktopCallbackPort);
if (!url) {
throw new LoginMethodError("Invalid desktop callback port", 400);
}
return url;
}
if (typeof appCallbackUrl === "string" && appCallbackUrl) {
let callbackUrl: URL;
try {
callbackUrl = new URL(appCallbackUrl);
} catch {
throw new LoginMethodError("Invalid app callback URL", 400);
}
if (callbackUrl.protocol !== "termix-mobile:") {
throw new LoginMethodError("Unsupported app callback URL", 400);
}
return callbackUrl.toString();
}
const referer = header(request, "referer");
if (referer) {
try {
const refererUrl = new URL(referer);
return `${refererUrl.protocol}//${refererUrl.host}`;
} catch {
// fall through to the request's own origin
}
}
return new URL(baseUrl).origin;
}
async function start(
request: PluginLoginRequest,
instanceId: string | null,
): Promise<{ redirectUrl: string }> {
const requested =
instanceId ??
(typeof request.query.providerId === "string"
? request.query.providerId
: null);
const rowId =
requested && requested !== ENV_INSTANCE_ID
? Number.parseInt(requested, 10)
: null;
if (rowId !== null && !Number.isInteger(rowId)) {
throw new LoginMethodError("OIDC not configured", 404);
}
const provider = await store.resolve(rowId);
if (!provider) throw new LoginMethodError("OIDC not configured", 404);
const baseUrl = ctx.http.baseUrl(request);
const backendCallback = redirectUriFor(baseUrl, provider);
const frontendOrigin = frontendOriginFor(request, baseUrl);
const state = crypto.randomUUID();
const nonce = crypto.randomUUID();
const codeVerifier = generatePkceCodeVerifier();
await saveState(state, {
nonce,
backendCallback,
frontendOrigin,
rememberMe: String(request.query.rememberMe) === "true",
providerId: provider.rowId,
codeVerifier,
createdAt: Date.now(),
});
const authUrl = new URL(provider.config.authorization_url);
authUrl.searchParams.set("client_id", provider.config.client_id);
authUrl.searchParams.set("redirect_uri", backendCallback);
authUrl.searchParams.set("response_type", "code");
authUrl.searchParams.set("scope", provider.config.scopes);
authUrl.searchParams.set("state", state);
authUrl.searchParams.set("nonce", nonce);
authUrl.searchParams.set(
"code_challenge",
generatePkceCodeChallenge(codeVerifier),
);
authUrl.searchParams.set("code_challenge_method", "S256");
return { redirectUrl: authUrl.toString() };
}
async function exchangeCode(
config: OidcConfig,
code: string,
pending: PendingState,
withVerifier: boolean,
): Promise<Record<string, unknown>> {
const response = await fetch(config.token_url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: config.client_id,
client_secret: config.client_secret,
code,
redirect_uri: pending.backendCallback,
...(withVerifier ? { code_verifier: pending.codeVerifier } : {}),
}),
...buildFetchOptions(config.ca_cert),
} as RequestInit);
if (!response.ok) {
ctx.log.error(
"Token exchange failed",
new Error(`HTTP ${response.status}: ${await response.text()}`),
);
throw new LoginMethodError("Failed to exchange authorization code", 400);
}
return (await response.json()) as Record<string, unknown>;
}
function providerKey(provider: ResolvedProvider): string {
return provider.rowId === null ? ENV_PROVIDER_ID : String(provider.rowId);
}
async function githubIdentity(
provider: ResolvedProvider,
code: string,
pending: PendingState,
): Promise<PluginVerifiedIdentity> {
const tokenData = await exchangeCode(provider.config, code, pending, false);
const fetchOptions = buildFetchOptions(provider.config.ca_cert);
const headers = {
Authorization: `Bearer ${tokenData.access_token}`,
Accept: "application/json",
"User-Agent": "Termix",
};
const userInfoResponse = await fetch("https://api.github.com/user", {
headers,
...fetchOptions,
} as RequestInit);
if (!userInfoResponse.ok) {
throw new LoginMethodError("Failed to get GitHub user information", 400);
}
const userInfo = (await userInfoResponse.json()) as Record<string, unknown>;
const emailResponse = await fetch("https://api.github.com/user/emails", {
headers,
});
if (emailResponse.ok) {
const emails = (await emailResponse.json()) as Array<{
email: string;
primary: boolean;
verified: boolean;
}>;
const primary = emails.find((e) => e.primary && e.verified);
if (primary) userInfo.email = primary.email;
}
const subject = String(userInfo.id ?? userInfo.login);
const legacyIdentifier = `github:${provider.rowId}:${subject}`;
return {
kind: "external",
provider: providerKey(provider),
subject,
email: (userInfo.email as string | undefined) ?? null,
name: ((userInfo.name || userInfo.login) as string) || legacyIdentifier,
allowedUsers: provider.config.allowed_users ?? null,
legacy: { identifier: legacyIdentifier, providerRowId: provider.rowId },
returnTo: pending.frontendOrigin,
rememberMe: pending.rememberMe,
};
}
async function fetchUserInfo(
config: OidcConfig,
accessToken: unknown,
userInfo: Record<string, unknown> | null,
claimSources: Record<string, unknown>[],
): Promise<Record<string, unknown> | null> {
const fetchOptions = buildFetchOptions(config.ca_cert);
const issuer = config.issuer_url.endsWith("/")
? config.issuer_url.slice(0, -1)
: config.issuer_url;
const base = issuer.replace(/\/application\/o\/[^/]+$/, "");
const urls: string[] = [];
try {
const discovery = await fetch(
`${issuer}/.well-known/openid-configuration`,
fetchOptions as RequestInit,
);
if (discovery.ok) {
const document = (await discovery.json()) as Record<string, unknown>;
if (typeof document.userinfo_endpoint === "string") {
urls.push(document.userinfo_endpoint);
}
}
} catch (error) {
ctx.log.warn(`OIDC discovery failed: ${String(error)}`);
}
if (config.userinfo_url) urls.unshift(config.userinfo_url);
urls.push(
`${base}/userinfo/`,
`${base}/userinfo`,
`${issuer}/userinfo/`,
`${issuer}/userinfo`,
`${base}/oauth2/userinfo/`,
`${base}/oauth2/userinfo`,
`${issuer}/oauth2/userinfo/`,
`${issuer}/oauth2/userinfo`,
);
if (!accessToken) return userInfo;
for (const url of urls) {
try {
const response = await fetch(url, {
headers: { Authorization: `Bearer ${accessToken}` },
...fetchOptions,
} as RequestInit);
if (response.ok) {
const fetched = (await response.json()) as Record<string, unknown>;
claimSources.push(fetched);
return { ...userInfo, ...fetched };
}
ctx.log.warn(`Userinfo endpoint ${url} answered ${response.status}`);
} catch (error) {
ctx.log.warn(`Userinfo endpoint ${url} failed: ${String(error)}`);
}
}
return userInfo;
}
async function oidcIdentity(
provider: ResolvedProvider,
code: string,
pending: PendingState,
): Promise<PluginVerifiedIdentity> {
const { config } = provider;
const tokenData = await exchangeCode(config, code, pending, true);
let userInfo: Record<string, unknown> | null = null;
const claimSources: Record<string, unknown>[] = [];
if (typeof tokenData.id_token === "string") {
try {
userInfo = await verifyOIDCToken(
tokenData.id_token,
config.issuer_url,
config.client_id,
config.ca_cert,
);
if (userInfo.nonce !== pending.nonce) {
ctx.log.warn("OIDC ID token nonce mismatch");
throw new LoginMethodError("Invalid OIDC token nonce", 401);
}
claimSources.push(userInfo);
} catch (error) {
// A token that is not a JWS carries no claims we could trust; fall
// through to userinfo. Signature and claim failures still reject.
if (!(error instanceof OIDCTokenFormatError)) throw error;
userInfo = null;
ctx.log.warn(
`OIDC ID token cannot be verified, using userinfo: ${error.message}`,
);
}
}
userInfo = await fetchUserInfo(
config,
tokenData.access_token,
userInfo,
claimSources,
);
if (!userInfo) {
throw new LoginMethodError("Failed to get user information", 400);
}
const identifier = (getNestedValue(userInfo, config.identifier_path) ||
userInfo[config.identifier_path] ||
userInfo.sub ||
userInfo.email ||
userInfo.preferred_username) as string;
const name = (getNestedValue(userInfo, config.name_path) ||
userInfo[config.name_path] ||
userInfo.name ||
userInfo.given_name ||
identifier) as string;
if (!identifier) {
throw new LoginMethodError(
`User identifier not found at path: ${config.identifier_path}. Available fields: ${Object.keys(userInfo).join(", ")}`,
400,
);
}
const groups = extractOidcGroupsFromSources(
claimSources,
config.group_claim,
);
const isAdmin = config.admin_group
? groups.includes(config.admin_group)
: undefined;
let roles: { desired: string[]; managed: string[] } | undefined;
const roleMap = parseOidcRoleMap(
config.role_map ?? process.env.OIDC_ROLE_MAP,
);
if (roleMap.size > 0) {
const { desired, managed } = resolveOidcMappedRoles(groups, roleMap);
roles = { desired: [...desired], managed: [...managed] };
}
return {
kind: "external",
provider: providerKey(provider),
subject: String(identifier),
email: (userInfo.email as string | undefined) ?? null,
name,
groups,
isAdmin,
allowedUsers: config.allowed_users ?? null,
roles,
logoutClaims: {
providerId: provider.rowId,
sub: typeof userInfo.sub === "string" ? userInfo.sub : null,
sid: typeof userInfo.sid === "string" ? userInfo.sid : null,
},
legacy: { identifier: String(identifier), providerRowId: provider.rowId },
returnTo: pending.frontendOrigin,
rememberMe: pending.rememberMe,
};
}
/**
* The provider's callback. Throws RedirectLoginError once the return
* address is known, and a plain LoginMethodError (answered as JSON) before.
*/
async function callback(
request: PluginLoginRequest,
): Promise<PluginVerifiedIdentity> {
const source = { ...request.query, ...(request.body ?? {}) };
const { code, state } = source as Record<string, unknown>;
if (!nonEmpty(code) || !nonEmpty(state)) {
throw new LoginMethodError("Code and state are required", 400);
}
const pending = await takeState(state);
if (!pending) throw new LoginMethodError("Invalid state parameter", 400);
try {
const provider = await store.resolve(pending.providerId);
if (!provider) throw new LoginMethodError("OIDC not configured", 500);
// GitHub does not issue OIDC id_tokens; it has its own token exchange.
return provider.type === "github"
? await githubIdentity(provider, code, pending)
: await oidcIdentity(provider, code, pending);
} catch (error) {
if (error instanceof LoginMethodError) {
throw new RedirectLoginError(
error.message,
pending.frontendOrigin,
error.status,
error.code,
);
}
ctx.log.error(
"OIDC callback failed",
error instanceof Error ? error : new Error(String(error)),
);
throw new RedirectLoginError(
"OIDC authentication failed",
pending.frontendOrigin,
500,
);
}
}
return { start, callback };
}
+463
View File
@@ -0,0 +1,463 @@
/**
* OpenID Connect protocol helpers: token verification, groups and the role
* map, back-channel logout tokens and the provider defaults. Nothing here
* touches storage.
*/
import crypto from "node:crypto";
import { Agent } from "undici";
import type { OidcConfig } from "./types.js";
const BACKCHANNEL_LOGOUT_EVENT =
"http://schemas.openid.net/event/backchannel-logout";
/**
* Raised when a token cannot be verified because it is not a compact JWS,
* as opposed to a signature or claim check that actually failed.
*/
export class OIDCTokenFormatError extends Error {
constructor(message: string) {
super(message);
this.name = "OIDCTokenFormatError";
}
}
export function normalizeIssuer(url: string): string {
return url
.trim()
.replace(/\/+$/, "")
.replace(/\/\.well-known\/openid-configuration$/, "");
}
export function buildFetchOptions(caCert?: string): Record<string, unknown> {
if (!caCert || !caCert.trim()) return {};
return { dispatcher: new Agent({ connect: { ca: caCert } }) };
}
/**
* Renders why a fetch failed in a form an administrator can act on.
*
* undici reports every transport failure as the same "fetch failed" message
* and puts the reason that actually matters -- ENOTFOUND, ECONNREFUSED,
* UNABLE_TO_VERIFY_LEAF_SIGNATURE, a timeout -- on the cause. Reporting only
* the outer message says nothing at all.
*/
export function describeFetchFailure(error: unknown): string {
if (!(error instanceof Error)) return String(error);
const cause = (error as { cause?: unknown }).cause;
if (cause instanceof Error) {
const code = (cause as { code?: unknown }).code;
return code
? `${error.message}: ${cause.message} (${code})`
: `${error.message}: ${cause.message}`;
}
return cause ? `${error.message}: ${String(cause)}` : error.message;
}
export function getOidcConfigFromEnv(): OidcConfig | null {
const client_id = process.env.OIDC_CLIENT_ID;
const client_secret = process.env.OIDC_CLIENT_SECRET;
const issuer_url = process.env.OIDC_ISSUER_URL;
const authorization_url = process.env.OIDC_AUTHORIZATION_URL;
const token_url = process.env.OIDC_TOKEN_URL;
if (
!client_id ||
!client_secret ||
!issuer_url ||
!authorization_url ||
!token_url
) {
return null;
}
return {
client_id,
client_secret,
issuer_url,
authorization_url,
token_url,
userinfo_url: process.env.OIDC_USERINFO_URL || "",
identifier_path: process.env.OIDC_IDENTIFIER_PATH || "sub",
name_path: process.env.OIDC_NAME_PATH || "name",
scopes: process.env.OIDC_SCOPES || "openid email profile",
allowed_users: process.env.OIDC_ALLOWED_USERS || "",
admin_group: process.env.OIDC_ADMIN_GROUP || "",
group_claim: process.env.OIDC_GROUP_CLAIM || "",
role_map: process.env.OIDC_ROLE_MAP || "",
};
}
export function isOIDCEnvOverrideEnabled(): boolean {
return process.env.OIDC_ENV_OVERRIDE?.toLowerCase() === "true";
}
/**
* Normalizes a group name for comparison. Providers are inconsistent about
* whether they emit bare names (`devops-interns`) or full paths
* (`/devops-interns`, Keycloak's "Full group path" option), so leading slashes
* are stripped and case is ignored.
*/
function normalizeGroupName(group: string): string {
return group.trim().replace(/^\/+/, "").toLowerCase();
}
/**
* Parses `OIDC_ROLE_MAP` into a group -> role-name lookup.
*
* Format is a comma- or newline-separated list of `group:role` pairs, e.g.
* `devops-interns:devops-intern,devops-seniors:devops-senior`. Group keys are
* normalized via {@link normalizeGroupName}; role names are passed through
* verbatim because they must match `roles.name` exactly.
*
* Malformed entries are skipped rather than throwing - a typo in one pair must
* not lock every user out of login.
*/
export function parseOidcRoleMap(raw?: string | null): Map<string, string> {
const map = new Map<string, string>();
if (!raw || !raw.trim()) return map;
for (const entry of raw.split(/[\n,]/)) {
const trimmed = entry.trim();
if (!trimmed) continue;
// rsplit on the last ":" so group names containing a colon still work.
const separator = trimmed.lastIndexOf(":");
if (separator <= 0 || separator === trimmed.length - 1) continue;
const group = normalizeGroupName(trimmed.slice(0, separator));
const roleName = trimmed.slice(separator + 1).trim();
if (!group || !roleName) continue;
map.set(group, roleName);
}
return map;
}
/**
* Resolves which mapped roles a user should hold, given their provider groups.
*
* Returns both the `desired` roles (mapped groups the user is actually in) and
* the full set of `managed` roles (every role named in the map). Callers must
* only ever add/remove roles within `managed` - roles assigned by hand in
* Termix, and the `admin`/`user` roles maintained by the admin-group sync, are
* deliberately left alone.
*/
export function resolveOidcMappedRoles(
groups: string[],
roleMap: Map<string, string>,
): { desired: Set<string>; managed: Set<string> } {
const managed = new Set(roleMap.values());
const desired = new Set<string>();
for (const group of groups) {
const roleName = roleMap.get(normalizeGroupName(group));
if (roleName) desired.add(roleName);
}
return { desired, managed };
}
/**
* Extracts the list of group/role names from an OIDC userInfo payload.
*
* When `groupClaim` is set, that claim is read first (useful for providers like
* Zitadel that nest roles under a custom path such as
* `urn:zitadel:iam:org:project:roles`). Otherwise the common `groups`, `roles`
* and `group` claims are tried. Values may be an array, a comma-separated
* string, or an object whose keys are the group names.
*/
export function extractOidcGroups(
userInfo: Record<string, unknown>,
groupClaim?: string,
): string[] {
let raw: unknown;
if (groupClaim && groupClaim.trim()) {
raw = userInfo[groupClaim.trim()];
}
if (raw === undefined || raw === null) {
raw = userInfo.groups ?? userInfo.roles ?? userInfo.group;
}
if (Array.isArray(raw)) {
return raw.map(String);
}
if (typeof raw === "string") {
return raw
.split(",")
.map((s) => s.trim())
.filter(Boolean);
}
if (raw && typeof raw === "object") {
return Object.keys(raw as Record<string, unknown>);
}
return [];
}
/**
* OIDC providers may return group claims in the ID token, userinfo response,
* or both. Keep every verified source authoritative instead of letting a
* sparse userinfo payload overwrite claims from the ID token.
*/
export function extractOidcGroupsFromSources(
sources: Record<string, unknown>[],
groupClaim?: string,
): string[] {
return [
...new Set(
sources.flatMap((source) => extractOidcGroups(source, groupClaim)),
),
];
}
export async function verifyOIDCToken(
idToken: string,
issuerUrl: string,
clientId: string,
caCert?: string,
): Promise<Record<string, unknown>> {
const segments = idToken.split(".");
if (segments.length !== 3) {
throw new OIDCTokenFormatError(
segments.length === 5
? "Token is a JWE (encrypted). Termix cannot verify encrypted tokens; disable token encryption for this client in your OIDC provider."
: `Token is not a compact JWS: expected 3 segments, got ${segments.length}.`,
);
}
const fetchOptions = buildFetchOptions(caCert);
const configuredIssuerUrl = issuerUrl.trim().replace(/\/+$/, "");
const normalizedIssuerUrl = normalizeIssuer(issuerUrl);
const possibleIssuers = [
normalizedIssuerUrl,
normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
...(configuredIssuerUrl === normalizedIssuerUrl ? [issuerUrl] : []),
];
const jwksUrls = [
`${normalizedIssuerUrl}/.well-known/jwks.json`,
`${normalizedIssuerUrl}/jwks/`,
`${normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, "")}/.well-known/jwks.json`,
];
// Every attempt records why it failed. Without this the only thing an
// administrator ever sees is "Failed to fetch JWKS from any URL", which
// does not distinguish an issuer URL typo from a proxy, a private CA, or
// a provider outage.
const attempts: string[] = [];
const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
try {
const discoveryResponse = await fetch(discoveryUrl, fetchOptions);
if (!discoveryResponse.ok) {
attempts.push(`${discoveryUrl}: HTTP ${discoveryResponse.status}`);
} else {
const discovery = (await discoveryResponse.json()) as Record<
string,
unknown
>;
if (typeof discovery.jwks_uri === "string" && discovery.jwks_uri) {
jwksUrls.unshift(discovery.jwks_uri);
} else {
attempts.push(`${discoveryUrl}: no jwks_uri in the discovery document`);
}
}
} catch (discoveryError) {
attempts.push(`${discoveryUrl}: ${describeFetchFailure(discoveryError)}`);
}
let jwks: Record<string, unknown> | null = null;
for (const url of jwksUrls) {
try {
const response = await fetch(url, fetchOptions);
if (!response.ok) {
attempts.push(`${url}: HTTP ${response.status}`);
continue;
}
const jwksData = (await response.json()) as Record<string, unknown>;
if (jwksData && Array.isArray(jwksData.keys)) {
jwks = jwksData;
break;
}
attempts.push(`${url}: response contains no "keys" array`);
} catch (error) {
attempts.push(`${url}: ${describeFetchFailure(error)}`);
}
}
if (!jwks) {
throw new Error(
`Failed to fetch JWKS from any URL. Attempts:\n ${attempts.join("\n ")}`,
);
}
if (!jwks.keys || !Array.isArray(jwks.keys)) {
throw new Error(
`Invalid JWKS response structure. Expected 'keys' array, got: ${JSON.stringify(jwks)}`,
);
}
const { decodeProtectedHeader, importJWK, jwtVerify } = await import("jose");
const header = decodeProtectedHeader(idToken);
const keyId = header.kid;
const publicKey = jwks.keys.find(
(key: Record<string, unknown>) => key.kid === keyId,
);
if (!publicKey) {
throw new Error(
`No matching public key found for key ID: ${keyId}. Available keys: ${jwks.keys.map((k: Record<string, unknown>) => k.kid).join(", ")}`,
);
}
const algorithm =
typeof publicKey.alg === "string" ? publicKey.alg : header.alg;
const key = await importJWK(publicKey, algorithm);
const { payload } = await jwtVerify(idToken, key, {
issuer: possibleIssuers,
audience: clientId,
});
return payload;
}
const GOOGLE_DEFAULTS = {
issuer_url: "https://accounts.google.com",
authorization_url: "https://accounts.google.com/o/oauth2/v2/auth",
token_url: "https://oauth2.googleapis.com/token",
userinfo_url: "https://openidconnect.googleapis.com/v1/userinfo",
identifier_path: "sub",
name_path: "name",
scopes: "openid email profile",
};
const GITHUB_DEFAULTS = {
issuer_url: "https://token.actions.githubusercontent.com",
authorization_url: "https://github.com/login/oauth/authorize",
token_url: "https://github.com/login/oauth/access_token",
userinfo_url: "https://api.github.com/user",
identifier_path: "id",
name_path: "name",
scopes: "read:user user:email",
};
export function applyProviderDefaults(
config: OidcConfig,
providerType: string,
): OidcConfig {
const defaults =
providerType === "google"
? GOOGLE_DEFAULTS
: providerType === "github"
? GITHUB_DEFAULTS
: null;
if (!defaults) return config;
return {
...config,
issuer_url: config.issuer_url || defaults.issuer_url,
authorization_url: config.authorization_url || defaults.authorization_url,
token_url: config.token_url || defaults.token_url,
userinfo_url: config.userinfo_url || defaults.userinfo_url,
identifier_path: config.identifier_path || defaults.identifier_path,
name_path: config.name_path || defaults.name_path,
scopes: config.scopes || defaults.scopes,
};
}
export type LogoutTokenClaims = {
sub: string | null;
sid: string | null;
jti: string;
};
export function validateLogoutTokenClaims(
payload: Record<string, unknown>,
): LogoutTokenClaims {
if ("nonce" in payload) {
throw new Error("logout_token must not contain a nonce claim");
}
const event = (payload.events as Record<string, unknown> | undefined)?.[
BACKCHANNEL_LOGOUT_EVENT
];
if (!event || typeof event !== "object" || Array.isArray(event)) {
throw new Error("logout_token missing back-channel logout event");
}
if (!Number.isInteger(payload.iat)) {
throw new Error("logout_token missing iat claim");
}
const jti = typeof payload.jti === "string" ? payload.jti.trim() : "";
if (!jti) {
throw new Error("logout_token missing jti claim");
}
const sub = typeof payload.sub === "string" ? payload.sub : null;
const sid = typeof payload.sid === "string" ? payload.sid : null;
if (!sub && !sid) {
throw new Error("logout_token must contain sub and/or sid");
}
return { sub, sid, jti };
}
export async function validateLogoutToken(
logoutToken: string,
config: OidcConfig,
): Promise<LogoutTokenClaims> {
const payload = await verifyOIDCToken(
logoutToken,
config.issuer_url,
config.client_id,
config.ca_cert,
);
return validateLogoutTokenClaims(payload);
}
export function isValidOidcIssuer(value: unknown): boolean {
if (typeof value !== "string") return false;
try {
const url = new URL(value);
return (
["http:", "https:"].includes(url.protocol) &&
!/\/userinfo\/?$/i.test(url.pathname)
);
} catch {
return false;
}
}
export function getNestedValue(
obj: Record<string, unknown>,
path: string,
): unknown {
if (!path || !obj) return null;
return path
.split(".")
.reduce<unknown>(
(current, key) => (current as Record<string, unknown>)?.[key],
obj,
);
}
// RFC 7636 PKCE: 43-128 char unreserved-character string.
export function generatePkceCodeVerifier(): string {
return crypto.randomBytes(64).toString("base64url");
}
export function generatePkceCodeChallenge(verifier: string): string {
return crypto.createHash("sha256").update(verifier).digest("base64url");
}
/** The desktop app's loopback listener for a callback port it sent. */
export function getDesktopCallbackUrl(value: unknown): string | null {
if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
const port = Number(value);
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
return `http://localhost:${port}/oidc-callback`;
}
+278
View File
@@ -0,0 +1,278 @@
import { and, asc, desc, eq } from "drizzle-orm";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { applyProviderDefaults, normalizeIssuer } from "./oidc-protocol.js";
import {
SSO_PROVIDER_TYPES,
type OidcConfig,
type ProviderRow,
type ResolvedProvider,
type SsoProviderType,
} from "./types.js";
/* eslint-disable @typescript-eslint/no-explicit-any */
// ctx.db.define hands the table back untyped and the drizzle handle is the
// server's own, so both are typed at this module's edge.
type Table = any;
type Drizzle = any;
/* eslint-enable @typescript-eslint/no-explicit-any */
/** Identities from the env-configured provider use this provider id. */
export const ENV_PROVIDER_ID = "legacy-oidc";
/** The login instance id of the env-configured provider. */
export const ENV_INSTANCE_ID = "0";
const SECRET_FIELDS = ["client_secret"] as const;
const LEGACY_PREFIXES = ["encoded:", "encrypted:"];
export function isSsoType(type: unknown): type is SsoProviderType {
return SSO_PROVIDER_TYPES.includes(type as SsoProviderType);
}
export function getOidcConfigFromEnv(): OidcConfig | null {
const client_id = process.env.OIDC_CLIENT_ID;
const client_secret = process.env.OIDC_CLIENT_SECRET;
const issuer_url = process.env.OIDC_ISSUER_URL;
const authorization_url = process.env.OIDC_AUTHORIZATION_URL;
const token_url = process.env.OIDC_TOKEN_URL;
if (
!client_id ||
!client_secret ||
!issuer_url ||
!authorization_url ||
!token_url
) {
return null;
}
return {
client_id,
client_secret,
issuer_url,
authorization_url,
token_url,
userinfo_url: process.env.OIDC_USERINFO_URL || "",
identifier_path: process.env.OIDC_IDENTIFIER_PATH || "sub",
name_path: process.env.OIDC_NAME_PATH || "name",
scopes: process.env.OIDC_SCOPES || "openid email profile",
allowed_users: process.env.OIDC_ALLOWED_USERS || "",
admin_group: process.env.OIDC_ADMIN_GROUP || "",
group_claim: process.env.OIDC_GROUP_CLAIM || "",
role_map: process.env.OIDC_ROLE_MAP || "",
};
}
export function isEnvOverrideEnabled(): boolean {
return process.env.OIDC_ENV_OVERRIDE?.toLowerCase() === "true";
}
function envProvider(config: OidcConfig): ResolvedProvider {
// Env providers were set up against the 2.8 callback and cannot be edited.
return { config, type: "oidc", rowId: null, legacyCallback: true };
}
export type ProviderStore = ReturnType<typeof createProviderStore>;
export function createProviderStore(ctx: PluginContext, table: Table) {
const client = () => ctx.db.client<Drizzle>();
/** Opens a stored secret: sealed, or the 2.8 base64 forms. */
async function openSecret(value: string): Promise<string> {
const prefix = LEGACY_PREFIXES.find((p) => value.startsWith(p));
if (prefix) {
try {
return Buffer.from(value.slice(prefix.length), "base64").toString(
"utf8",
);
} catch {
return "";
}
}
const opened = await ctx.secrets.unseal(value);
// A value seal() never wrote was stored in the clear by hand.
return opened ?? value;
}
async function parseConfig(raw: string): Promise<Record<string, unknown>> {
let config: Record<string, unknown>;
try {
config = JSON.parse(raw);
} catch {
return {};
}
for (const field of SECRET_FIELDS) {
const value = config[field];
if (typeof value === "string" && value) {
config[field] = await openSecret(value);
}
}
return config;
}
async function sealConfig(config: Record<string, unknown>): Promise<string> {
const out = { ...config };
for (const field of SECRET_FIELDS) {
const value = out[field];
if (typeof value === "string" && value) {
out[field] = await ctx.secrets.seal(value);
}
}
return JSON.stringify(out);
}
async function listRows(): Promise<ProviderRow[]> {
const drizzle = await client();
const rows = (await drizzle
.select()
.from(table)
.orderBy(asc(table.displayOrder), asc(table.id))) as ProviderRow[];
return rows.filter((row) => isSsoType(row.type));
}
async function findRow(id: number): Promise<ProviderRow | null> {
const drizzle = await client();
const rows = (await drizzle
.select()
.from(table)
.where(eq(table.id, id))
.limit(1)) as ProviderRow[];
const row = rows[0];
return row && isSsoType(row.type) ? row : null;
}
async function resolveRow(row: ProviderRow): Promise<ResolvedProvider> {
const type = row.type as SsoProviderType;
const config = applyProviderDefaults(
(await parseConfig(row.config)) as unknown as OidcConfig,
type,
);
return {
config,
type,
rowId: row.id,
legacyCallback: !!row.legacyCallback,
};
}
return {
parseConfig,
sealConfig,
listRows,
findRow,
/** Login instances: env override, rows, or the env provider alone. */
async listInstances(): Promise<
Array<{ id: string; label: string; type: SsoProviderType }>
> {
const env = getOidcConfigFromEnv();
const envInstance = {
id: ENV_INSTANCE_ID,
label: "SSO",
type: "oidc" as const,
};
if (env && isEnvOverrideEnabled()) return [envInstance];
const rows = (await listRows()).filter((row) => row.enabled);
const instances = rows.map((row) => ({
id: String(row.id),
label: row.name,
type: row.type as SsoProviderType,
}));
if (instances.length === 0 && env) instances.push(envInstance);
return instances;
},
/**
* The provider for a login. With no id, the env provider or the first
* enabled row, as 2.8 did.
*/
async resolve(rowId: number | null): Promise<ResolvedProvider | null> {
const env = getOidcConfigFromEnv();
if (env && isEnvOverrideEnabled()) return envProvider(env);
if (rowId != null) {
const row = await findRow(rowId);
return row?.enabled ? resolveRow(row) : null;
}
if (env) return envProvider(env);
const first = (await listRows()).find((row) => row.enabled);
return first ? resolveRow(first) : null;
},
/** The provider a back-channel logout token's issuer belongs to. */
async resolveByIssuer(issuer: string): Promise<ResolvedProvider | null> {
const target = normalizeIssuer(issuer);
const env = getOidcConfigFromEnv();
const envMatches =
!!env?.issuer_url && normalizeIssuer(env.issuer_url) === target;
if (envMatches && isEnvOverrideEnabled()) return envProvider(env!);
for (const row of await listRows()) {
if (!row.enabled) continue;
const resolved = await resolveRow(row);
if (
resolved.config.issuer_url &&
normalizeIssuer(resolved.config.issuer_url) === target
) {
return resolved;
}
}
return envMatches ? envProvider(env!) : null;
},
async create(input: {
name: string;
type: SsoProviderType;
enabled: boolean;
displayOrder: number;
config: Record<string, unknown>;
}): Promise<ProviderRow> {
const drizzle = await client();
const now = new Date().toISOString();
await drizzle.insert(table).values({
name: input.name,
type: input.type,
enabled: input.enabled,
displayOrder: input.displayOrder,
config: await sealConfig(input.config),
legacyCallback: false,
createdAt: now,
updatedAt: now,
});
await ctx.db.persist();
// No returning() on every engine: find the row by what was written.
const rows = (await drizzle
.select()
.from(table)
.where(and(eq(table.name, input.name), eq(table.createdAt, now)))
.orderBy(desc(table.id))
.limit(1)) as ProviderRow[];
return rows[0];
},
async update(
id: number,
values: Partial<{
name: string;
enabled: boolean;
displayOrder: number;
config: Record<string, unknown>;
legacyCallback: boolean;
}>,
): Promise<ProviderRow | null> {
const drizzle = await client();
const { config, ...rest } = values;
await drizzle
.update(table)
.set({
...rest,
...(config ? { config: await sealConfig(config) } : {}),
updatedAt: new Date().toISOString(),
})
.where(eq(table.id, id));
await ctx.db.persist();
return findRow(id);
},
async remove(id: number): Promise<void> {
const drizzle = await client();
await drizzle.delete(table).where(eq(table.id, id));
await ctx.db.persist();
},
};
}
+502
View File
@@ -0,0 +1,502 @@
import type { Request, Response, Router } from "express";
import {
LoginMethodError,
type PluginContext,
} from "@termix/plugin-sdk/backend";
import {
applyProviderDefaults,
isValidOidcIssuer,
validateLogoutToken,
} from "./oidc-protocol.js";
import { isSsoType, type ProviderStore } from "./providers.js";
import { METHOD_ID, redirectUriFor, type SsoLogin } from "./login.js";
import type { OidcConfig, ProviderRow, SsoProviderType } from "./types.js";
export const PUBLIC_PATHS = [
"/start",
"/callback",
"/backchannel-logout",
"/config",
];
const LOGOUT_JTI_TTL_MS = 5 * 60 * 1000;
const REQUIRED_OIDC_FIELDS = [
"client_id",
"client_secret",
"issuer_url",
"authorization_url",
"token_url",
] as const;
function fail(
ctx: PluginContext,
res: Response,
message: string,
error: unknown,
) {
ctx.log.error(
message,
error instanceof Error ? error : new Error(String(error)),
);
res.status(500).json({ error: message });
}
export function registerSsoRoutes(
router: Router,
ctx: PluginContext,
store: ProviderStore,
login: SsoLogin,
): void {
// Replayed logout tokens are answered but not acted on twice.
const seenLogoutJti = new Map<string, number>();
async function present(req: Request, row: ProviderRow) {
const config = await store.parseConfig(row.config);
const { client_secret: secret, ...rest } = config;
return {
id: row.id,
name: row.name,
type: row.type,
enabled: !!row.enabled,
displayOrder: row.displayOrder,
legacyCallback: !!row.legacyCallback,
config: rest,
hasClientSecret: typeof secret === "string" && secret.length > 0,
redirectUri: redirectUriFor(ctx.http.baseUrl(req), {
legacyCallback: !!row.legacyCallback,
}),
};
}
/** Checks a full provider config; returns the error to show, if any. */
function validate(type: SsoProviderType, config: Partial<OidcConfig>) {
if (type === "oidc") {
const missing = REQUIRED_OIDC_FIELDS.filter((field) => !config[field]);
if (missing.length > 0) {
return `Missing required OIDC fields: ${missing.join(", ")}`;
}
} else if (!config.client_id || !config.client_secret) {
return "Client ID and Client Secret are required";
}
if (config.issuer_url && !isValidOidcIssuer(config.issuer_url)) {
return "Issuer URL must be an HTTP(S) issuer and not a userinfo endpoint";
}
return null;
}
/**
* @openapi
* /plugin-api/sso/start:
* get:
* summary: Start an SSO login in the browser
* description: Public. Sends the browser straight to the provider, so a link can start a login. The provider is picked by the provider query parameter, or the default one.
* tags:
* - SSO
* parameters:
* - in: query
* name: provider
* schema:
* type: string
* responses:
* 302:
* description: Redirect to the identity provider.
* 404:
* description: SSO is not configured.
*/
router.get("/start", async (req: Request, res: Response) => {
try {
const instance =
typeof req.query.provider === "string" ? req.query.provider : null;
const { redirectUrl } = await login.start(req as never, instance);
res.redirect(redirectUrl);
} catch (error) {
if (error instanceof LoginMethodError) {
res.status(error.status).json({ error: error.message });
return;
}
fail(ctx, res, "Failed to start SSO login", error);
}
});
/**
* @openapi
* /plugin-api/sso/callback:
* get:
* summary: SSO callback
* description: Public. The redirect URI to register with an identity provider. Exchanges the code and redirects back to the app with a session, a second-factor step or an error.
* tags:
* - SSO
* responses:
* 302:
* description: Back to the app.
* post:
* summary: SSO callback (form post)
* description: Same as the GET form, for providers that post their answer.
* tags:
* - SSO
* responses:
* 302:
* description: Back to the app.
*/
const callback = (req: Request, res: Response) =>
ctx.auth.completeRedirectLogin(METHOD_ID, req, res);
router.get("/callback", callback);
router.post("/callback", callback);
/**
* @openapi
* /plugin-api/sso/backchannel-logout:
* post:
* summary: OIDC back-channel logout
* description: Public. Where an identity provider sends a signed logout token. Ends the Termix sessions that came from the matching provider login.
* tags:
* - SSO
* requestBody:
* required: true
* content:
* application/x-www-form-urlencoded:
* schema:
* type: object
* properties:
* logout_token:
* type: string
* responses:
* 200:
* description: Logout processed.
* 400:
* description: Missing, invalid or unknown logout token.
*/
router.post("/backchannel-logout", async (req: Request, res: Response) => {
res.setHeader("Cache-Control", "no-store");
const logoutToken = (req.body as Record<string, unknown> | undefined)
?.logout_token;
if (typeof logoutToken !== "string" || !logoutToken) {
res.status(400).json({ error: "missing logout_token" });
return;
}
let issuer: string | null = null;
try {
const parts = logoutToken.split(".");
if (parts.length === 3) {
const claims = JSON.parse(Buffer.from(parts[1], "base64").toString());
issuer = typeof claims.iss === "string" ? claims.iss : null;
}
} catch {
issuer = null;
}
if (!issuer) {
res.status(400).json({ error: "invalid logout_token" });
return;
}
try {
const provider = await store.resolveByIssuer(issuer);
if (!provider) {
ctx.log.warn(`Back-channel logout for unknown issuer ${issuer}`);
res.status(400).json({ error: "unknown issuer" });
return;
}
const claims = await validateLogoutToken(logoutToken, provider.config);
const now = Date.now();
for (const [key, expiry] of seenLogoutJti) {
if (expiry <= now) seenLogoutJti.delete(key);
}
if (seenLogoutJti.has(claims.jti)) {
res.status(200).json({ ok: true });
return;
}
try {
await ctx.auth.revokeSessions({
providerId: provider.rowId,
sub: claims.sub,
sid: claims.sid,
});
} catch (error) {
fail(ctx, res, "logout processing failed", error);
return;
}
seenLogoutJti.set(claims.jti, now + LOGOUT_JTI_TTL_MS);
res.status(200).json({ ok: true });
} catch (error) {
ctx.log.warn(`Back-channel logout failed: ${String(error)}`);
res.status(400).json({ error: "invalid logout_token" });
}
});
/**
* @openapi
* /plugin-api/sso/config:
* get:
* summary: Default provider's public configuration
* description: Public, for 2.8 clients. The client id, issuer, authorization URL and scopes of the default provider, or null.
* tags:
* - SSO
* responses:
* 200:
* description: Public configuration, or null.
*/
router.get("/config", async (_req: Request, res: Response) => {
try {
const provider = await store.resolve(null);
if (!provider) {
res.json(null);
return;
}
const { config } = provider;
res.json({
client_id: config.client_id,
issuer_url: config.issuer_url,
authorization_url: config.authorization_url,
scopes: config.scopes,
});
} catch (error) {
fail(ctx, res, "Failed to get OIDC config", error);
}
});
// Everything below manages providers.
const manage = ctx.rbac.require("manage") as never;
/**
* @openapi
* /plugin-api/sso/providers:
* get:
* summary: List SSO providers
* description: Every OIDC, GitHub and Google provider with its redirect URI. Secrets are never sent, only whether one is set. Needs sso.manage.
* tags:
* - SSO
* responses:
* 200:
* description: Providers.
* 403:
* description: Missing permission.
*/
router.get("/providers", manage, async (req: Request, res: Response) => {
try {
const rows = await store.listRows();
res.json({
providers: await Promise.all(rows.map((row) => present(req, row))),
newRedirectUri: redirectUriFor(ctx.http.baseUrl(req), {
legacyCallback: false,
}),
});
} catch (error) {
fail(ctx, res, "Failed to list SSO providers", error);
}
});
/**
* @openapi
* /plugin-api/sso/providers:
* post:
* summary: Add an SSO provider
* description: Adds an OIDC, GitHub or Google provider. GitHub and Google fill in their own endpoints. Needs sso.manage.
* tags:
* - SSO
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* type:
* type: string
* enum: [oidc, github, google]
* enabled:
* type: boolean
* config:
* type: object
* responses:
* 201:
* description: Provider added.
* 400:
* description: Missing or invalid fields.
* 403:
* description: Missing permission.
*/
router.post("/providers", manage, async (req: Request, res: Response) => {
try {
const {
name,
type,
enabled = true,
displayOrder = 0,
config = {},
} = req.body ?? {};
if (typeof name !== "string" || !name.trim()) {
res.status(400).json({ error: "Provider name is required" });
return;
}
if (!isSsoType(type)) {
res.status(400).json({ error: "Invalid provider type" });
return;
}
const full = applyProviderDefaults(config as OidcConfig, type);
const invalid = validate(type, full);
if (invalid) {
res.status(400).json({ error: invalid });
return;
}
const row = await store.create({
name: name.trim(),
type,
enabled: !!enabled,
displayOrder: Number(displayOrder) || 0,
config: { ...(config as Record<string, unknown>) },
});
await ctx.audit.record({
action: "sso_provider_create",
resourceType: "sso_provider",
resourceId: String(row.id),
resourceName: row.name,
success: true,
});
res.status(201).json(await present(req, row));
} catch (error) {
fail(ctx, res, "Failed to create SSO provider", error);
}
});
/**
* @openapi
* /plugin-api/sso/providers/{id}:
* put:
* summary: Update an SSO provider
* description: Changes a provider. Config fields are merged over the stored ones; an empty client secret keeps the stored secret. legacyCallback false moves it to the new redirect URI. Needs sso.manage.
* tags:
* - SSO
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Provider updated.
* 400:
* description: Invalid fields.
* 403:
* description: Missing permission.
* 404:
* description: Provider not found.
*/
router.put("/providers/:id", manage, async (req: Request, res: Response) => {
try {
const id = Number.parseInt(String(req.params.id), 10);
const row = Number.isInteger(id) ? await store.findRow(id) : null;
if (!row) {
res.status(404).json({ error: "Provider not found" });
return;
}
const { name, enabled, displayOrder, config, legacyCallback } =
req.body ?? {};
const values: Parameters<ProviderStore["update"]>[1] = {};
if (name !== undefined) {
if (typeof name !== "string" || !name.trim()) {
res.status(400).json({ error: "Provider name is required" });
return;
}
values.name = name.trim();
}
if (enabled !== undefined) values.enabled = !!enabled;
if (displayOrder !== undefined) {
values.displayOrder = Number(displayOrder) || 0;
}
if (legacyCallback !== undefined) {
values.legacyCallback = !!legacyCallback;
}
if (config && typeof config === "object") {
const incoming = { ...(config as Record<string, unknown>) };
if (!incoming.client_secret) delete incoming.client_secret;
const merged = {
...(await store.parseConfig(row.config)),
...incoming,
};
const invalid = validate(
row.type as SsoProviderType,
applyProviderDefaults(merged as unknown as OidcConfig, row.type),
);
if (invalid) {
res.status(400).json({ error: invalid });
return;
}
values.config = merged;
}
const updated = await store.update(id, values);
await ctx.audit.record({
action: "sso_provider_update",
resourceType: "sso_provider",
resourceId: String(id),
resourceName: updated?.name ?? row.name,
success: true,
});
res.json(await present(req, updated ?? row));
} catch (error) {
fail(ctx, res, "Failed to update SSO provider", error);
}
});
/**
* @openapi
* /plugin-api/sso/providers/{id}:
* delete:
* summary: Delete an SSO provider
* description: Refused while users still sign in with it. Needs sso.manage.
* tags:
* - SSO
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Provider deleted.
* 403:
* description: Missing permission.
* 404:
* description: Provider not found.
* 409:
* description: Users are still linked to it.
*/
router.delete(
"/providers/:id",
manage,
async (req: Request, res: Response) => {
try {
const id = Number.parseInt(String(req.params.id), 10);
const row = Number.isInteger(id) ? await store.findRow(id) : null;
if (!row) {
res.status(404).json({ error: "Provider not found" });
return;
}
if ((await ctx.auth.countLinkedUsers(String(id))) > 0) {
res.status(409).json({
error:
"Users still sign in with this provider. Disable it instead, or remove those users first.",
});
return;
}
await store.remove(id);
await ctx.audit.record({
action: "sso_provider_delete",
resourceType: "sso_provider",
resourceId: String(id),
resourceName: row.name,
success: true,
});
res.json({ message: "SSO provider deleted" });
} catch (error) {
fail(ctx, res, "Failed to delete SSO provider", error);
}
},
);
}
+32
View File
@@ -0,0 +1,32 @@
import {
adoptLegacyTable,
boolean,
defineTable,
id,
integer,
text,
timestamp,
} from "@termix/plugin-sdk/db";
/**
* Adopted from core's sso_providers, so the column names are the legacy ones
* and the rename carries every provider across. LDAP rows are moved out to
* the ldap plugin by core's boot migration; until then they are ignored here.
*/
export const providers = adoptLegacyTable(
"sso_providers",
defineTable("providers", {
id: id(),
name: text().notNull(),
type: text().notNull(),
enabled: boolean().notNull().default(true),
displayOrder: integer().notNull().default(0),
config: text().notNull(),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
// Providers from before 2.9 keep sending the old redirect URI.
legacyCallback: boolean().notNull().default(false),
}),
);
export const tables = [providers];
+46
View File
@@ -0,0 +1,46 @@
export type SsoProviderType = "oidc" | "github" | "google";
export const SSO_PROVIDER_TYPES: readonly SsoProviderType[] = [
"oidc",
"github",
"google",
];
export interface OidcConfig {
client_id: string;
client_secret: string;
issuer_url: string;
authorization_url: string;
token_url: string;
userinfo_url: string;
identifier_path: string;
name_path: string;
scopes: string;
allowed_users: string;
admin_group: string;
group_claim?: string;
role_map?: string;
ca_cert?: string;
}
/** A provider ready to sign someone in: secrets opened, defaults applied. */
export interface ResolvedProvider {
config: OidcConfig;
type: SsoProviderType;
/** The row id, or null for the provider configured through OIDC_* env vars. */
rowId: number | null;
/** Sends the 2.8 redirect URI, /users/oidc/callback, which core forwards. */
legacyCallback: boolean;
}
export interface ProviderRow {
id: number;
name: string;
type: string;
enabled: boolean;
displayOrder: number;
config: string;
legacyCallback: boolean;
createdAt: string;
updatedAt: string;
}