"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signAndContextify = exports.buildSignedRequestOptions = exports.computeBody = exports.buildGlobalHeaders = void 0;
const tslib_1 = require("tslib");
const peertube_crypto_1 = require("../../../helpers/peertube-crypto");
const constants_1 = require("../../../initializers/constants");
const actor_1 = require("../../../models/actor/actor");
const application_1 = require("../../../models/application/application");
const context_1 = require("../context");
function computeBody(payload) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        let body = payload.body;
        if (payload.signatureActorId) {
            const actorSignature = yield actor_1.ActorModel.load(payload.signatureActorId);
            if (!actorSignature)
                throw new Error('Unknown signature actor id.');
            body = yield signAndContextify(actorSignature, payload.body, payload.contextType);
        }
        return body;
    });
}
exports.computeBody = computeBody;
function buildSignedRequestOptions(payload) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        let actor;
        if (payload.signatureActorId) {
            actor = yield actor_1.ActorModel.load(payload.signatureActorId);
            if (!actor)
                throw new Error('Unknown signature actor id.');
        }
        else {
            actor = yield (0, application_1.getServerActor)();
        }
        const keyId = actor.url;
        return {
            algorithm: constants_1.HTTP_SIGNATURE.ALGORITHM,
            authorizationHeaderName: constants_1.HTTP_SIGNATURE.HEADER_NAME,
            keyId,
            key: actor.privateKey,
            headers: constants_1.HTTP_SIGNATURE.HEADERS_TO_SIGN
        };
    });
}
exports.buildSignedRequestOptions = buildSignedRequestOptions;
function buildGlobalHeaders(body) {
    return {
        'digest': (0, peertube_crypto_1.buildDigest)(body),
        'content-type': 'application/activity+json',
        'accept': constants_1.ACTIVITY_PUB.ACCEPT_HEADER
    };
}
exports.buildGlobalHeaders = buildGlobalHeaders;
function signAndContextify(byActor, data, contextType) {
    const activity = contextType
        ? (0, context_1.activityPubContextify)(data, contextType)
        : data;
    return (0, peertube_crypto_1.signJsonLDObject)(byActor, activity);
}
exports.signAndContextify = signAndContextify;
//# sourceMappingURL=http.js.map