mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-07-15 21:03:47 +00:00
d1a8dcf3c6
* chore(deps-dev): bump the dev-minor-updates group across 1 directory with 12 updates (#910) Bumps the dev-minor-updates group with 12 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@radix-ui/react-select](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/select) | `2.2.6` | `2.3.1` | | [@radix-ui/react-slider](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/slider) | `1.3.6` | `1.4.1` | | [@radix-ui/react-slot](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/slot) | `1.2.5` | `1.3.0` | | [@radix-ui/react-switch](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/switch) | `1.2.6` | `1.3.1` | | [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.33.4` | `3.34.0` | | [electron](https://github.com/electron/electron) | `42.2.0` | `42.4.1` | | [electron-builder](https://github.com/electron-userland/electron-builder/tree/HEAD/packages/electron-builder) | `26.8.1` | `26.15.3` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.16.0` | `1.20.0` | | [radix-ui](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/radix-ui) | `1.4.3` | `1.6.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.76.1` | `7.79.0` | | [sharp](https://github.com/lovell/sharp) | `0.34.5` | `0.35.1` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.60.0` | `8.61.1` | Updates `@radix-ui/react-select` from 2.2.6 to 2.3.1 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/select/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/select) Updates `@radix-ui/react-slider` from 1.3.6 to 1.4.1 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/slider/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/slider) Updates `@radix-ui/react-slot` from 1.2.5 to 1.3.0 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/slot/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/slot) Updates `@radix-ui/react-switch` from 1.2.6 to 1.3.1 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/switch/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/switch) Updates `cytoscape` from 3.33.4 to 3.34.0 - [Release notes](https://github.com/cytoscape/cytoscape.js/releases) - [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.33.4...v3.34.0) Updates `electron` from 42.2.0 to 42.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v42.2.0...v42.4.1) Updates `electron-builder` from 26.8.1 to 26.15.3 - [Release notes](https://github.com/electron-userland/electron-builder/releases) - [Changelog](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-builder/CHANGELOG.md) - [Commits](https://github.com/electron-userland/electron-builder/commits/electron-builder@26.15.3/packages/electron-builder) Updates `lucide-react` from 1.16.0 to 1.20.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.20.0/packages/lucide-react) Updates `radix-ui` from 1.4.3 to 1.6.0 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/radix-ui/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/radix-ui) Updates `react-hook-form` from 7.76.1 to 7.79.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.76.1...v7.79.0) Updates `sharp` from 0.34.5 to 0.35.1 - [Release notes](https://github.com/lovell/sharp/releases) - [Commits](https://github.com/lovell/sharp/compare/v0.34.5...v0.35.1) Updates `typescript-eslint` from 8.60.0 to 8.61.1 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.61.1/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@radix-ui/react-select" dependency-version: 2.3.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@radix-ui/react-slider" dependency-version: 1.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@radix-ui/react-slot" dependency-version: 1.3.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@radix-ui/react-switch" dependency-version: 1.3.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: cytoscape dependency-version: 3.34.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 42.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron-builder dependency-version: 26.15.3 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.18.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: radix-ui dependency-version: 1.6.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.79.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: sharp dependency-version: 0.35.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.61.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump node in /docker in the docker-major-updates group (#914) Bumps the docker-major-updates group in /docker with 1 update: node. Updates `node` from 24-slim to 26-slim --- updated-dependencies: - dependency-name: node dependency-version: 26-slim dependency-type: direct:production dependency-group: docker-major-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * ci(deps): bump the github-actions group with 2 updates (#915) Bumps the github-actions group with 2 updates: [actions/checkout](https://github.com/actions/checkout) and [actions/setup-node](https://github.com/actions/setup-node). Updates `actions/checkout` from 5 to 6 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v5...v6) Updates `actions/setup-node` from 4 to 6 - [Release notes](https://github.com/actions/setup-node/releases) - [Commits](https://github.com/actions/setup-node/compare/v4...v6) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/setup-node dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-minor-updates group across 1 directory with 5 updates (#916) Bumps the prod-minor-updates group with 5 updates in the / directory: | Package | From | To | | --- | --- | --- | | [axios](https://github.com/axios/axios) | `1.17.0` | `1.18.0` | | [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) | `12.10.0` | `12.11.1` | | [body-parser](https://github.com/expressjs/body-parser) | `2.2.2` | `2.3.0` | | [multer](https://github.com/expressjs/multer) | `2.1.1` | `2.2.0` | | [undici](https://github.com/nodejs/undici) | `8.4.0` | `8.5.0` | Updates `axios` from 1.17.0 to 1.18.0 - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.17.0...v1.18.0) Updates `better-sqlite3` from 12.10.0 to 12.11.1 - [Release notes](https://github.com/WiseLibs/better-sqlite3/releases) - [Commits](https://github.com/WiseLibs/better-sqlite3/compare/v12.10.0...v12.11.1) Updates `body-parser` from 2.2.2 to 2.3.0 - [Release notes](https://github.com/expressjs/body-parser/releases) - [Changelog](https://github.com/expressjs/body-parser/blob/master/HISTORY.md) - [Commits](https://github.com/expressjs/body-parser/compare/v2.2.2...v2.3.0) Updates `multer` from 2.1.1 to 2.2.0 - [Release notes](https://github.com/expressjs/multer/releases) - [Changelog](https://github.com/expressjs/multer/blob/main/CHANGELOG.md) - [Commits](https://github.com/expressjs/multer/compare/v2.1.1...v2.2.0) Updates `undici` from 8.4.0 to 8.5.0 - [Release notes](https://github.com/nodejs/undici/releases) - [Commits](https://github.com/nodejs/undici/compare/v8.4.0...v8.5.0) --- updated-dependencies: - dependency-name: axios dependency-version: 1.18.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: better-sqlite3 dependency-version: 12.11.1 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: body-parser dependency-version: 2.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: multer dependency-version: 2.2.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: undici dependency-version: 8.5.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat: add unlink button for dual auth * fix: general bug fixes * fix: general qol/small feature additions * fix: 100mb max upload size * fix: terminal syntax not handling carriage returns or shell prompt lines properly * feat: continued general improvements * fix: terminal outputting success right after folder path * chore: update release notes * feat: continued fixes and improvements * chore: lint, format, and bump version to 2.4.1 * chore: sync Crowdin translations for 2.4.1 * fix: rebase dev branch onto main before Crowdin download * fix: use merge instead of rebase to sync main before Crowdin --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
420 lines
12 KiB
TypeScript
420 lines
12 KiB
TypeScript
import { authLogger } from "../../utils/logger.js";
|
|
import type { SSOProviderType } from "../../../types/index.js";
|
|
import { db } from "../db/index.js";
|
|
import { ssoProviders } from "../db/schema.js";
|
|
import { eq } from "drizzle-orm";
|
|
import { DataCrypto } from "../../utils/data-crypto.js";
|
|
import { Agent } from "undici";
|
|
|
|
export type 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;
|
|
ca_cert?: string;
|
|
};
|
|
|
|
export function buildFetchOptions(caCert?: string): Record<string, unknown> {
|
|
if (!caCert || !caCert.trim()) return {};
|
|
return { dispatcher: new Agent({ connect: { ca: caCert } }) };
|
|
}
|
|
|
|
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 || "",
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 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 [];
|
|
}
|
|
|
|
export function isOIDCUserAllowed(
|
|
allowedUsers: string,
|
|
identifier: string,
|
|
email?: string,
|
|
): boolean {
|
|
if (!allowedUsers || !allowedUsers.trim()) return true;
|
|
const patterns = allowedUsers
|
|
.split(/[\n,]/)
|
|
.map((p) => p.trim())
|
|
.filter(Boolean);
|
|
if (patterns.length === 0) return true;
|
|
|
|
const values = [
|
|
identifier,
|
|
...(email && email !== identifier ? [email] : []),
|
|
];
|
|
for (const pattern of patterns) {
|
|
if (pattern === "*") return true;
|
|
if (pattern.includes("*")) {
|
|
const escaped = pattern
|
|
.toLowerCase()
|
|
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
.replace(/\*/g, ".*");
|
|
const regex = new RegExp(`^${escaped}$`);
|
|
if (values.some((v) => v && regex.test(v.toLowerCase()))) return true;
|
|
continue;
|
|
}
|
|
for (const value of values) {
|
|
if (!value) continue;
|
|
if (pattern.toLowerCase().startsWith("@")) {
|
|
if (value.toLowerCase().endsWith(pattern.toLowerCase())) return true;
|
|
} else {
|
|
if (value.toLowerCase() === pattern.toLowerCase()) return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
export async function verifyOIDCToken(
|
|
idToken: string,
|
|
issuerUrl: string,
|
|
clientId: string,
|
|
caCert?: string,
|
|
): Promise<Record<string, unknown>> {
|
|
const fetchOptions = buildFetchOptions(caCert);
|
|
const normalizedIssuerUrl = issuerUrl.endsWith("/")
|
|
? issuerUrl.slice(0, -1)
|
|
: issuerUrl;
|
|
const possibleIssuers = [
|
|
issuerUrl,
|
|
normalizedIssuerUrl,
|
|
issuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
|
|
normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
|
|
];
|
|
|
|
const jwksUrls = [
|
|
`${normalizedIssuerUrl}/.well-known/jwks.json`,
|
|
`${normalizedIssuerUrl}/jwks/`,
|
|
`${normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, "")}/.well-known/jwks.json`,
|
|
];
|
|
|
|
try {
|
|
const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
|
|
const discoveryResponse = await fetch(discoveryUrl, fetchOptions);
|
|
if (discoveryResponse.ok) {
|
|
const discovery = (await discoveryResponse.json()) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
if (discovery.jwks_uri) {
|
|
jwksUrls.unshift(discovery.jwks_uri as string);
|
|
}
|
|
}
|
|
} catch (discoveryError) {
|
|
authLogger.error(`OIDC discovery failed: ${discoveryError}`);
|
|
}
|
|
|
|
let jwks: Record<string, unknown> | null = null;
|
|
|
|
for (const url of jwksUrls) {
|
|
try {
|
|
const response = await fetch(url, fetchOptions);
|
|
if (response.ok) {
|
|
const jwksData = (await response.json()) as Record<string, unknown>;
|
|
if (jwksData && jwksData.keys && Array.isArray(jwksData.keys)) {
|
|
jwks = jwksData;
|
|
break;
|
|
} else {
|
|
authLogger.error(
|
|
`Invalid JWKS structure from ${url}: ${JSON.stringify(jwksData)}`,
|
|
);
|
|
}
|
|
} else {
|
|
// expected - non-ok response, try next URL
|
|
}
|
|
} catch {
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (!jwks) {
|
|
throw new Error("Failed to fetch JWKS from any URL");
|
|
}
|
|
|
|
if (!jwks.keys || !Array.isArray(jwks.keys)) {
|
|
throw new Error(
|
|
`Invalid JWKS response structure. Expected 'keys' array, got: ${JSON.stringify(jwks)}`,
|
|
);
|
|
}
|
|
|
|
const header = JSON.parse(
|
|
Buffer.from(idToken.split(".")[0], "base64").toString(),
|
|
);
|
|
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 { importJWK, jwtVerify } = await import("jose");
|
|
const key = await importJWK(publicKey);
|
|
|
|
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",
|
|
};
|
|
|
|
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,
|
|
};
|
|
}
|
|
|
|
function decryptConfigSecret(
|
|
config: Record<string, unknown>,
|
|
): Record<string, unknown> {
|
|
const out = { ...config };
|
|
for (const field of ["client_secret", "bindPassword"] as const) {
|
|
const val = out[field] as string | undefined;
|
|
if (val?.startsWith("encoded:")) {
|
|
try {
|
|
out[field] = Buffer.from(val.substring(8), "base64").toString("utf8");
|
|
} catch {
|
|
// leave as-is
|
|
}
|
|
} else if (val?.startsWith("encrypted:")) {
|
|
// encrypted: prefix means it was encrypted with DataCrypto; without a
|
|
// userId/dataKey here we cannot decrypt it. The caller should use the
|
|
// full admin decrypt path when possible. Fall back to stripping prefix.
|
|
try {
|
|
out[field] = Buffer.from(val.substring(10), "base64").toString("utf8");
|
|
} catch {
|
|
// leave as-is
|
|
}
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export async function loadProviderConfig(
|
|
providerId: number | null | undefined,
|
|
adminUserId?: string,
|
|
): Promise<{
|
|
config: OIDCConfig;
|
|
providerType: SSOProviderType;
|
|
providerDbId: number | null;
|
|
} | null> {
|
|
if (providerId != null) {
|
|
try {
|
|
const rows = await db
|
|
.select()
|
|
.from(ssoProviders)
|
|
.where(eq(ssoProviders.id, providerId))
|
|
.limit(1);
|
|
if (rows.length > 0) {
|
|
const row = rows[0];
|
|
let parsed: Record<string, unknown>;
|
|
try {
|
|
parsed = JSON.parse(row.config);
|
|
} catch {
|
|
parsed = {};
|
|
}
|
|
if (adminUserId) {
|
|
try {
|
|
const adminDataKey = DataCrypto.getUserDataKey(adminUserId);
|
|
if (adminDataKey) {
|
|
parsed = DataCrypto.decryptRecord(
|
|
"settings",
|
|
parsed,
|
|
adminUserId,
|
|
adminDataKey,
|
|
);
|
|
}
|
|
} catch {
|
|
parsed = decryptConfigSecret(parsed);
|
|
}
|
|
} else {
|
|
parsed = decryptConfigSecret(parsed);
|
|
}
|
|
const providerType = row.type as SSOProviderType;
|
|
const config = applyProviderDefaults(
|
|
parsed as unknown as OIDCConfig,
|
|
providerType,
|
|
);
|
|
return {
|
|
config,
|
|
providerType,
|
|
providerDbId: row.id,
|
|
};
|
|
}
|
|
} catch (err) {
|
|
authLogger.error("Failed to load SSO provider config by id", err, {
|
|
providerId,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Fallback: env vars
|
|
const envConfig = getOIDCConfigFromEnv();
|
|
if (envConfig) {
|
|
return { config: envConfig, providerType: "oidc", providerDbId: null };
|
|
}
|
|
|
|
// Fallback: first enabled OIDC-type provider in ssoProviders table
|
|
try {
|
|
const rows = await db
|
|
.select()
|
|
.from(ssoProviders)
|
|
.where(eq(ssoProviders.enabled, true))
|
|
.orderBy();
|
|
const oidcRow = rows.find(
|
|
(r) => r.type === "oidc" || r.type === "github" || r.type === "google",
|
|
);
|
|
if (oidcRow) {
|
|
let parsed: Record<string, unknown>;
|
|
try {
|
|
parsed = JSON.parse(oidcRow.config);
|
|
} catch {
|
|
parsed = {};
|
|
}
|
|
parsed = decryptConfigSecret(parsed);
|
|
const oidcProviderType = oidcRow.type as SSOProviderType;
|
|
return {
|
|
config: applyProviderDefaults(
|
|
parsed as unknown as OIDCConfig,
|
|
oidcProviderType,
|
|
),
|
|
providerType: oidcProviderType,
|
|
providerDbId: oidcRow.id,
|
|
};
|
|
}
|
|
} catch {
|
|
// fall through to legacy
|
|
}
|
|
|
|
// Fallback: legacy settings blob
|
|
try {
|
|
const legacyRow = db.$client
|
|
.prepare("SELECT value FROM settings WHERE key = 'oidc_config'")
|
|
.get() as { value: string } | undefined;
|
|
if (legacyRow) {
|
|
let config = JSON.parse(legacyRow.value) as Record<string, unknown>;
|
|
config = decryptConfigSecret(config);
|
|
return {
|
|
config: config as unknown as OIDCConfig,
|
|
providerType: "oidc",
|
|
providerDbId: null,
|
|
};
|
|
}
|
|
} catch {
|
|
// no legacy config
|
|
}
|
|
|
|
return null;
|
|
}
|