"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2026 Jonas Lochmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenValidationException = exports.MissingSignSecretException = void 0;
exports.createIdentityToken = createIdentityToken;
exports.verifyIdentitifyToken = verifyIdentitifyToken;
const jose_1 = require("jose");
const config_1 = require("../config");
const validator_1 = require("../api/validator");
async function createIdentityToken({ purpose, familyId, userId, mail }) {
    const jwt = await new jose_1.SignJWT({ purpose, familyId, userId, mail })
        .setExpirationTime('7d')
        .setProtectedHeader({ alg: 'HS512' })
        .sign(getSignSecret());
    return Buffer.from(jwt, 'ascii')
        .toString('base64')
        .split(/(.{32})/)
        .filter((item) => item.length > 0)
        .join('\n');
}
async function verifyIdentitifyToken(token, dryRun) {
    try {
        const { payload } = await (0, jose_1.jwtVerify)(Buffer.from(token, 'base64').toString('ascii'), getSignSecret(), {
            algorithms: ['HS512'],
            clockTolerance: dryRun ? 0 : '4w',
        });
        if (!(0, validator_1.isIdentityTokenPayload)(payload))
            throw new BadPayloadException();
        return payload;
    }
    catch (ex) {
        if (ex instanceof TokenValidationException)
            throw ex;
        else if (ex instanceof Error)
            throw new TokenValidationException(ex.message);
        else
            throw ex;
    }
}
function getSignSecret() {
    if (config_1.config.signSecret === '')
        throw new MissingSignSecretException();
    return Buffer.from(config_1.config.signSecret, 'utf8');
}
class MissingSignSecretException extends Error {
}
exports.MissingSignSecretException = MissingSignSecretException;
class TokenValidationException extends Error {
}
exports.TokenValidationException = TokenValidationException;
class BadPayloadException extends TokenValidationException {
    constructor() { super('bad payload'); }
}
//# sourceMappingURL=identity-token.js.map