"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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePrivateKey = generatePrivateKey;
exports.generatePublicKey = generatePublicKey;
exports.getPublicKey = getPublicKey;
exports.getPrivateKey = getPrivateKey;
const debug = __importStar(require("../debug"));
const secp256k1_1 = require("@noble/curves/secp256k1");
const utils_1 = require("@noble/hashes/utils");
const ns_1 = __importDefault(require("../ns"));
const solid_logic_1 = require("solid-logic");
const $rdf = __importStar(require("rdflib"));
const accessData_1 = require("../utils/keyHelpers/accessData");
const acl_1 = require("../utils/keyHelpers/acl");
function generatePrivateKey() {
    return (0, utils_1.bytesToHex)(secp256k1_1.schnorr.utils.randomPrivateKey());
}
function generatePublicKey(privateKey) {
    return (0, utils_1.bytesToHex)(secp256k1_1.schnorr.getPublicKey(privateKey));
}
/**
 * getPublicKey
 * used for displaying messages in chat, therefore does not
 * create a new key if not found
 * @param webId
 * @returns string | undefined
 */
async function getPublicKey(webId) {
    await solid_logic_1.store.fetcher.load(webId);
    const publicKeyDoc = await (0, accessData_1.pubKeyUrl)(webId);
    try {
        await solid_logic_1.store.fetcher.load(publicKeyDoc); // url.href)
        const key = solid_logic_1.store.any(webId, ns_1.default.solid('publicKey'));
        return key?.value; // as NamedNode
    }
    catch (err) {
        return undefined;
    }
}
async function getPrivateKey(webId) {
    await solid_logic_1.store.fetcher.load(webId);
    // find keys url's
    const publicKeyDoc = await (0, accessData_1.pubKeyUrl)(webId);
    const privateKeyDoc = await (0, accessData_1.privKeyUrl)(webId);
    // find key pair
    const publicKey = await (0, accessData_1.getExistingPublicKey)(webId, publicKeyDoc);
    let privateKey = await (0, accessData_1.getExistingPrivateKey)(webId, privateKeyDoc);
    // is publicKey valid ?
    let validPublicKey = true;
    if (privateKey && (publicKey !== generatePublicKey(privateKey))) {
        if (confirm('This is strange the publicKey is not valid for\n' + webId?.uri +
            '\'shall we repair keeping the private key ?'))
            validPublicKey = false;
    }
    // create key pair or repair publicKey
    if (!privateKey || !publicKey || !validPublicKey) {
        let del = [];
        let add = [];
        if (!privateKey) {
            // add = []
            privateKey = generatePrivateKey();
            add = [$rdf.st(webId, ns_1.default.solid('privateKey'), $rdf.literal(privateKey), solid_logic_1.store.sym(privateKeyDoc))];
            await saveKey(privateKeyDoc, [], add, webId.uri);
        }
        if (!publicKey || !validPublicKey) {
            del = [];
            // delete invalid public key
            if (publicKey) {
                del = [$rdf.st(webId, ns_1.default.solid('publicKey'), $rdf.lit(publicKey), solid_logic_1.store.sym(publicKeyDoc))];
                debug.log('delete invalid publicKey ' + del);
            }
            // update new valid key
            const newPublicKey = generatePublicKey(privateKey);
            add = [$rdf.st(webId, ns_1.default.solid('publicKey'), $rdf.literal(newPublicKey), solid_logic_1.store.sym(publicKeyDoc))];
            await saveKey(publicKeyDoc, del, add);
        }
        const keyContainer = privateKeyDoc.substring(0, privateKeyDoc.lastIndexOf('/') + 1);
        await (0, acl_1.setAcl)(keyContainer, (0, acl_1.keyContainerAclBody)(webId.uri)); // includes DELETE and PUT
    }
    return privateKey;
}
const deleteKeyAcl = async (keyDoc) => {
    await solid_logic_1.store.fetcher.load(keyDoc);
    const keyAclDoc = solid_logic_1.store.any(solid_logic_1.store.sym(keyDoc), solid_logic_1.store.sym('http://www.iana.org/assignments/link-relations/acl'));
    if (keyAclDoc) {
        // delete READ only keyAclDoc. This is possible if the webId is an owner
        try {
            const response = await solid_logic_1.store.fetcher.webOperation('DELETE', keyAclDoc.value); // this may fail if webId is not an owner
            debug.log('delete keyAcl' + keyAclDoc.value + ' ' + response.status); // should test 404 and 2xx
        }
        catch (err) {
            if (err.response.status !== 404) {
                throw new Error(err);
            }
            debug.log('delete keyAcl' + keyAclDoc.value + ' ' + err.response.status); // should test 404 and 2xx
        }
    }
};
/**
 * delete acl if keydoc exists
 * create/edit keyDoc
 * set keyDoc acl
 */
async function saveKey(keyDoc, del, add, me = '') {
    await deleteKeyAcl(keyDoc);
    // save key
    await solid_logic_1.store.updater.updateMany(del, add); // or a promise store.updater.update ?
    // create READ only ACL
    const aclBody = (0, acl_1.keyAclBody)(keyDoc, me);
    await (0, acl_1.setAcl)(keyDoc, aclBody);
}
//# sourceMappingURL=keys.js.map