"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.signingCertificate = exports.bundle = exports.isVerifiableTransparencyLogEntry = exports.isCAVerificationOptions = exports.isBundleWithCertificateChain = exports.isBundleWithVerificationMaterial = exports.bundleFromJSON = void 0;
/*
Copyright 2023 The Sigstore Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const protobuf_specs_1 = require("@sigstore/protobuf-specs");
const util_1 = require("../../util");
const cert_1 = require("../../x509/cert");
const validate_1 = require("./validate");
__exportStar(require("@sigstore/protobuf-specs"), exports);
__exportStar(require("./serialized"), exports);
__exportStar(require("./validate"), exports);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const bundleFromJSON = (obj) => {
    const bundle = protobuf_specs_1.Bundle.fromJSON(obj);
    (0, validate_1.assertValidBundle)(bundle);
    return bundle;
};
exports.bundleFromJSON = bundleFromJSON;
const BUNDLE_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1';
// Type guard for narrowing a Bundle to a BundleWithVerificationMaterial
function isBundleWithVerificationMaterial(bundle) {
    return bundle.verificationMaterial !== undefined;
}
exports.isBundleWithVerificationMaterial = isBundleWithVerificationMaterial;
// Type guard for narrowing a Bundle to a BundleWithCertificateChain
function isBundleWithCertificateChain(bundle) {
    return (isBundleWithVerificationMaterial(bundle) &&
        bundle.verificationMaterial.content !== undefined &&
        bundle.verificationMaterial.content.$case === 'x509CertificateChain');
}
exports.isBundleWithCertificateChain = isBundleWithCertificateChain;
function isCAVerificationOptions(options) {
    return (options.ctlogOptions !== undefined &&
        (options.signers === undefined ||
            options.signers.$case === 'certificateIdentities'));
}
exports.isCAVerificationOptions = isCAVerificationOptions;
function isVerifiableTransparencyLogEntry(entry) {
    return (entry.logId !== undefined &&
        entry.inclusionPromise !== undefined &&
        entry.kindVersion !== undefined);
}
exports.isVerifiableTransparencyLogEntry = isVerifiableTransparencyLogEntry;
exports.bundle = {
    toDSSEBundle: (envelope, signature, rekorEntry) => ({
        mediaType: BUNDLE_MEDIA_TYPE,
        content: {
            $case: 'dsseEnvelope',
            dsseEnvelope: envelope,
        },
        verificationMaterial: toVerificationMaterial(signature, rekorEntry),
    }),
    toMessageSignatureBundle: (digest, signature, rekorEntry) => ({
        mediaType: BUNDLE_MEDIA_TYPE,
        content: {
            $case: 'messageSignature',
            messageSignature: {
                messageDigest: {
                    algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256,
                    digest: digest,
                },
                signature: signature.signature,
            },
        },
        verificationMaterial: toVerificationMaterial(signature, rekorEntry),
    }),
};
function toTransparencyLogEntry(entry) {
    const set = Buffer.from(entry.verification.signedEntryTimestamp, 'base64');
    const logID = Buffer.from(entry.logID, 'hex');
    // Parse entry body so we can extract the kind and version.
    const bodyJSON = util_1.encoding.base64Decode(entry.body);
    const entryBody = JSON.parse(bodyJSON);
    return {
        inclusionPromise: {
            signedEntryTimestamp: set,
        },
        logIndex: entry.logIndex.toString(),
        logId: {
            keyId: logID,
        },
        integratedTime: entry.integratedTime.toString(),
        kindVersion: {
            kind: entryBody.kind,
            version: entryBody.apiVersion,
        },
        inclusionProof: undefined,
        canonicalizedBody: Buffer.from(entry.body, 'base64'),
    };
}
function toVerificationMaterial(signature, entry) {
    return {
        content: signature.certificates
            ? toVerificationMaterialx509CertificateChain(signature.certificates)
            : toVerificationMaterialPublicKey(signature.key.id || ''),
        tlogEntries: [toTransparencyLogEntry(entry)],
        timestampVerificationData: undefined,
    };
}
function toVerificationMaterialx509CertificateChain(certificates) {
    return {
        $case: 'x509CertificateChain',
        x509CertificateChain: {
            certificates: certificates.map((c) => ({
                rawBytes: util_1.pem.toDER(c),
            })),
        },
    };
}
function toVerificationMaterialPublicKey(hint) {
    return { $case: 'publicKey', publicKey: { hint } };
}
function signingCertificate(bundle) {
    if (!isBundleWithCertificateChain(bundle)) {
        return undefined;
    }
    const signingCert = bundle.verificationMaterial.content.x509CertificateChain.certificates[0];
    return cert_1.x509Certificate.parse(signingCert.rawBytes);
}
exports.signingCertificate = signingCertificate;
