"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SsoInstanceSettingsLoader = void 0;
const api_types_1 = require("@n8n/api-types");
const backend_common_1 = require("@n8n/backend-common");
const config_1 = require("@n8n/config");
const db_1 = require("@n8n/db");
const di_1 = require("@n8n/di");
const n8n_core_1 = require("n8n-core");
const n8n_workflow_1 = require("n8n-workflow");
const zod_1 = require("zod");
const constants_1 = require("../../modules/provisioning.ee/constants");
const constants_2 = require("../../modules/sso-oidc/constants");
const constants_3 = require("../../modules/sso-saml/constants");
const sso_helpers_1 = require("../../sso.ee/sso-helpers");
const PROVISIONING_MODES = ['disabled', 'instance_role', 'instance_and_project_roles'];
const provisioningSchema = zod_1.z
    .object({
    ssoUserRoleProvisioning: zod_1.z.enum(PROVISIONING_MODES, {
        errorMap: () => ({
            message: `N8N_SSO_USER_ROLE_PROVISIONING must be one of: ${PROVISIONING_MODES.join(', ')}`,
        }),
    }),
})
    .transform((input) => ({
    scopesProvisionInstanceRole: input.ssoUserRoleProvisioning === 'instance_role' ||
        input.ssoUserRoleProvisioning === 'instance_and_project_roles',
    scopesProvisionProjectRoles: input.ssoUserRoleProvisioning === 'instance_and_project_roles',
}));
const samlEnvSchema = zod_1.z
    .object({
    samlMetadata: zod_1.z.string(),
    samlMetadataUrl: zod_1.z.string(),
    samlLoginEnabled: zod_1.z.boolean(),
})
    .refine((data) => data.samlMetadata || data.samlMetadataUrl, {
    message: 'At least one of N8N_SSO_SAML_METADATA or N8N_SSO_SAML_METADATA_URL is required when configuring SAML via environment variables',
})
    .transform(({ samlMetadata, samlMetadataUrl, samlLoginEnabled }) => ({
    ...(samlMetadata ? { metadata: samlMetadata } : {}),
    ...(samlMetadataUrl ? { metadataUrl: samlMetadataUrl } : {}),
    loginEnabled: samlLoginEnabled,
}));
const oidcEnvSchema = zod_1.z
    .object({
    oidcClientId: zod_1.z
        .string()
        .min(1, 'N8N_SSO_OIDC_CLIENT_ID is required when configuring OIDC via environment variables'),
    oidcClientSecret: zod_1.z
        .string()
        .min(1, 'N8N_SSO_OIDC_CLIENT_SECRET is required when configuring OIDC via environment variables'),
    oidcDiscoveryEndpoint: zod_1.z.string().url('N8N_SSO_OIDC_DISCOVERY_ENDPOINT must be a valid URL'),
    oidcLoginEnabled: zod_1.z.boolean(),
    oidcPrompt: zod_1.z.enum(api_types_1.OIDC_PROMPT_VALUES, {
        errorMap: () => ({
            message: `N8N_SSO_OIDC_PROMPT must be one of: ${api_types_1.OIDC_PROMPT_VALUES.join(', ')}`,
        }),
    }),
    oidcAcrValues: zod_1.z.string(),
})
    .transform((input) => ({
    clientId: input.oidcClientId,
    clientSecret: input.oidcClientSecret,
    discoveryEndpoint: input.oidcDiscoveryEndpoint,
    loginEnabled: input.oidcLoginEnabled,
    prompt: input.oidcPrompt,
    authenticationContextClassReference: input.oidcAcrValues
        ? input.oidcAcrValues
            .split(',')
            .map((v) => v.trim())
            .filter(Boolean)
        : [],
}));
let SsoInstanceSettingsLoader = class SsoInstanceSettingsLoader {
    constructor(config, settingsRepository, cipher, logger) {
        this.config = config;
        this.settingsRepository = settingsRepository;
        this.cipher = cipher;
        this.logger = logger;
        this.logger = this.logger.scoped('instance-settings-loader');
    }
    async run() {
        if (!this.config.ssoManagedByEnv) {
            this.logger.debug('ssoManagedByEnv is disabled — skipping SSO config');
            return 'skipped';
        }
        const { samlLoginEnabled, oidcLoginEnabled } = this.config;
        if (samlLoginEnabled && oidcLoginEnabled) {
            throw new n8n_workflow_1.OperationalError('N8N_SSO_SAML_LOGIN_ENABLED and N8N_SSO_OIDC_LOGIN_ENABLED cannot both be true. Only one SSO protocol can be enabled at a time.');
        }
        if (samlLoginEnabled || oidcLoginEnabled) {
            await this.writeProvisioning();
        }
        await this.applySamlConfig();
        await this.applyOidcConfig();
        await this.syncAuthMethod();
        return 'created';
    }
    async applySamlConfig() {
        if (!this.config.samlLoginEnabled) {
            await this.writeSamlLoginDisabled();
            return;
        }
        this.logger.info('SAML login is enabled — applying SAML SSO env vars');
        const parsed = samlEnvSchema.safeParse(this.config);
        if (!parsed.success) {
            throw new n8n_workflow_1.OperationalError(parsed.error.issues[0].message);
        }
        await this.writeSamlPreferences(parsed.data);
    }
    async applyOidcConfig() {
        if (!this.config.oidcLoginEnabled) {
            await this.writeOidcLoginDisabled();
            return;
        }
        this.logger.info('OIDC login is enabled — applying OIDC SSO env vars');
        const parsed = oidcEnvSchema.safeParse(this.config);
        if (!parsed.success) {
            throw new n8n_workflow_1.OperationalError(parsed.error.issues[0].message);
        }
        await this.writeOidcPreferences(parsed.data);
    }
    async syncAuthMethod() {
        const { samlLoginEnabled, oidcLoginEnabled } = this.config;
        if (samlLoginEnabled) {
            await (0, sso_helpers_1.setCurrentAuthenticationMethod)('saml');
            return;
        }
        if (oidcLoginEnabled) {
            await (0, sso_helpers_1.setCurrentAuthenticationMethod)('oidc');
            return;
        }
        const current = (0, sso_helpers_1.getCurrentAuthenticationMethod)();
        if (current === 'saml' || current === 'oidc') {
            await (0, sso_helpers_1.setCurrentAuthenticationMethod)('email');
        }
    }
    async writeSamlPreferences(preferences) {
        await this.settingsRepository.save({
            key: constants_3.SAML_PREFERENCES_DB_KEY,
            value: JSON.stringify(preferences),
            loadOnStartup: true,
        });
    }
    async writeSamlLoginDisabled() {
        await this.settingsRepository.save({
            key: constants_3.SAML_PREFERENCES_DB_KEY,
            value: JSON.stringify({ loginEnabled: false }),
            loadOnStartup: true,
        });
    }
    async writeOidcPreferences(preferences) {
        await this.settingsRepository.upsert({
            key: constants_2.OIDC_PREFERENCES_DB_KEY,
            value: JSON.stringify({
                ...preferences,
                clientSecret: this.cipher.encrypt(preferences.clientSecret),
            }),
            loadOnStartup: true,
        }, { conflictPaths: ['key'] });
    }
    async writeOidcLoginDisabled() {
        await this.settingsRepository.upsert({
            key: constants_2.OIDC_PREFERENCES_DB_KEY,
            value: JSON.stringify({ loginEnabled: false }),
            loadOnStartup: true,
        }, { conflictPaths: ['key'] });
    }
    async writeProvisioning() {
        const parsed = provisioningSchema.safeParse(this.config);
        if (!parsed.success) {
            throw new n8n_workflow_1.OperationalError(parsed.error.issues[0].message);
        }
        await this.settingsRepository.upsert({
            key: constants_1.PROVISIONING_PREFERENCES_DB_KEY,
            value: JSON.stringify(parsed.data),
            loadOnStartup: true,
        }, { conflictPaths: ['key'] });
    }
};
exports.SsoInstanceSettingsLoader = SsoInstanceSettingsLoader;
exports.SsoInstanceSettingsLoader = SsoInstanceSettingsLoader = __decorate([
    (0, di_1.Service)(),
    __metadata("design:paramtypes", [config_1.InstanceSettingsLoaderConfig,
        db_1.SettingsRepository,
        n8n_core_1.Cipher,
        backend_common_1.Logger])
], SsoInstanceSettingsLoader);
//# sourceMappingURL=sso.instance-settings-loader.js.map