"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);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAuth2CredentialController = void 0;
const client_oauth2_1 = require("@n8n/client-oauth2");
const decorators_1 = require("@n8n/decorators");
const omit_1 = __importDefault(require("lodash/omit"));
const set_1 = __importDefault(require("lodash/set"));
const split_1 = __importDefault(require("lodash/split"));
const n8n_workflow_1 = require("n8n-workflow");
const oauth_service_1 = require("../../oauth/oauth.service");
const backend_common_1 = require("@n8n/backend-common");
const external_hooks_1 = require("../../external-hooks");
let OAuth2CredentialController = class OAuth2CredentialController {
    constructor(oauthService, logger, externalHooks) {
        this.oauthService = oauthService;
        this.logger = logger;
        this.externalHooks = externalHooks;
    }
    async getAuthUri(req) {
        const credential = await this.oauthService.getCredential(req);
        const uri = await this.oauthService.generateAOauth2AuthUri(credential, {
            cid: credential.id,
            origin: 'static-credential',
            userId: req.user.id,
        });
        return uri;
    }
    async handleCallback(req, res) {
        try {
            const { code, state: encodedState } = req.query;
            if (!code || !encodedState) {
                return this.oauthService.renderCallbackError(res, 'Insufficient parameters for OAuth2 callback.', `Received following query parameters: ${JSON.stringify(req.query)}`);
            }
            const [credential, decryptedDataOriginal, oauthCredentials, state] = await this.oauthService.resolveCredential(req);
            const oAuthOptions = this.convertCredentialToOptions(oauthCredentials);
            const isPkce = oauthCredentials.grantType === 'pkce';
            const isBodyAuth = oauthCredentials.authentication === 'body';
            const body = { ...(oAuthOptions.body ?? {}) };
            if (isPkce) {
                body.code_verifier = decryptedDataOriginal.codeVerifier;
            }
            if (isBodyAuth) {
                body.client_id = oAuthOptions.clientId;
                if (oAuthOptions.clientSecret) {
                    body.client_secret = oAuthOptions.clientSecret;
                }
                delete oAuthOptions.clientSecret;
            }
            let options = {};
            if (isPkce || isBodyAuth) {
                options = { body };
            }
            await this.externalHooks.run('oauth2.callback', [oAuthOptions]);
            const oAuthObj = new client_oauth2_1.ClientOAuth2(oAuthOptions);
            const queryParameters = req.originalUrl.split('?').splice(1, 1).join('');
            const oauthToken = await oAuthObj.code.getToken(`${oAuthOptions.redirectUri}?${queryParameters}`, options);
            if (Object.keys(req.query).length > 2) {
                (0, set_1.default)(oauthToken.data, 'callbackQueryString', (0, omit_1.default)(req.query, 'state', 'code'));
            }
            const { oauthTokenData: tokenData } = decryptedDataOriginal;
            const oauthTokenData = {
                ...(typeof tokenData === 'object' ? tokenData : {}),
                ...oauthToken.data,
            };
            if (!state.origin || state.origin === 'static-credential') {
                await this.oauthService.encryptAndSaveData(credential, { oauthTokenData }, ['csrfSecret']);
                this.logger.debug('OAuth2 callback successful for credential', {
                    credentialId: credential.id,
                });
                return res.render('oauth-callback');
            }
            if (state.origin === 'dynamic-credential') {
                if (!state.credentialResolverId || typeof state.credentialResolverId !== 'string') {
                    return this.oauthService.renderCallbackError(res, 'Credential resolver ID is required');
                }
                if (!state.authorizationHeader ||
                    typeof state.authorizationHeader !== 'string' ||
                    !state.authorizationHeader.startsWith('Bearer ')) {
                    return this.oauthService.renderCallbackError(res, 'Authorization header is required');
                }
                await this.oauthService.saveDynamicCredential(credential, { oauthTokenData }, state.authorizationHeader.split('Bearer ')[1], state.credentialResolverId, state.authMetadata ?? {});
                return res.render('oauth-callback');
            }
        }
        catch (e) {
            const error = (0, n8n_workflow_1.ensureError)(e);
            return this.oauthService.renderCallbackError(res, error.message, 'body' in error ? (0, n8n_workflow_1.jsonStringify)(error.body) : undefined);
        }
    }
    convertCredentialToOptions(credential) {
        const options = {
            clientId: credential.clientId,
            clientSecret: credential.clientSecret ?? '',
            accessTokenUri: credential.accessTokenUrl ?? '',
            authorizationUri: credential.authUrl ?? '',
            authentication: credential.authentication ?? 'header',
            redirectUri: `${this.oauthService.getBaseUrl(2)}/callback`,
            scopes: (0, split_1.default)(credential.scope ?? 'openid', ','),
            scopesSeparator: credential.scope?.includes(',') ? ',' : ' ',
            ignoreSSLIssues: credential.ignoreSSLIssues ?? false,
        };
        if (credential.additionalBodyProperties &&
            typeof credential.additionalBodyProperties === 'string') {
            const parsedBody = (0, n8n_workflow_1.jsonParse)(credential.additionalBodyProperties);
            if (parsedBody) {
                options.body = parsedBody;
            }
        }
        return options;
    }
};
exports.OAuth2CredentialController = OAuth2CredentialController;
__decorate([
    (0, decorators_1.Get)('/auth'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], OAuth2CredentialController.prototype, "getAuthUri", null);
__decorate([
    (0, decorators_1.Get)('/callback', { usesTemplates: true, skipAuth: oauth_service_1.skipAuthOnOAuthCallback }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], OAuth2CredentialController.prototype, "handleCallback", null);
exports.OAuth2CredentialController = OAuth2CredentialController = __decorate([
    (0, decorators_1.RestController)('/oauth2-credential'),
    __metadata("design:paramtypes", [oauth_service_1.OauthService,
        backend_common_1.Logger,
        external_hooks_1.ExternalHooks])
], OAuth2CredentialController);
//# sourceMappingURL=oauth2-credential.controller.js.map