var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { Cid } from '../utils/cid.js';
import { GeneralJwsVerifier } from '../jose/jws/general/verifier.js';
import { Jws } from '../utils/jws.js';
import { PermissionsGrant } from '../interfaces/permissions-grant.js';
import { validateJsonSchema } from '../schema-validator.js';
import { DwnError, DwnErrorCode } from './dwn-error.js';
export class Authenticate {
    /**
     * Verifies all the signature(s) within the authorization property.
     * @throws {Error} if fails authentication
     */
    static authenticate(authorizationModel, didResolver) {
        return __awaiter(this, void 0, void 0, function* () {
            if (authorizationModel === undefined) {
                throw new DwnError(DwnErrorCode.AuthenticateJwsMissing, 'Missing JWS.');
            }
            yield GeneralJwsVerifier.verifySignatures(authorizationModel.signature, didResolver);
            if (authorizationModel.ownerSignature !== undefined) {
                yield GeneralJwsVerifier.verifySignatures(authorizationModel.ownerSignature, didResolver);
            }
            if (authorizationModel.authorDelegatedGrant !== undefined) {
                // verify the signature of the grantor of the delegated grant
                const authorDelegatedGrant = yield PermissionsGrant.parse(authorizationModel.authorDelegatedGrant);
                yield GeneralJwsVerifier.verifySignatures(authorDelegatedGrant.message.authorization.signature, didResolver);
            }
        });
    }
}
;
/**
 * Validates the structural integrity of the message signature given.
 * NOTE: signature is not verified.
 * @param payloadJsonSchemaKey The key to look up the JSON schema referenced in `compile-validators.js` and perform payload schema validation on.
 * @returns the parsed JSON payload object if validation succeeds.
 */
export function validateMessageSignatureIntegrity(messageSignature, messageDescriptor, payloadJsonSchemaKey = 'GenericSignaturePayload') {
    return __awaiter(this, void 0, void 0, function* () {
        if (messageSignature.signatures.length !== 1) {
            throw new DwnError(DwnErrorCode.AuthenticationMoreThanOneSignatureNotSupported, 'expected no more than 1 signature for authorization purpose');
        }
        // validate payload integrity
        const payloadJson = Jws.decodePlainObjectPayload(messageSignature);
        validateJsonSchema(payloadJsonSchemaKey, payloadJson);
        // `descriptorCid` validation - ensure that the provided descriptorCid matches the CID of the actual message
        const { descriptorCid } = payloadJson;
        const expectedDescriptorCid = yield Cid.computeCid(messageDescriptor);
        if (descriptorCid !== expectedDescriptorCid) {
            throw new DwnError(DwnErrorCode.AuthenticateDescriptorCidMismatch, `provided descriptorCid ${descriptorCid} does not match expected CID ${expectedDescriptorCid}`);
        }
        return payloadJson;
    });
}
/**
 * Verifies all the signature(s) within the authorization property.
 * @throws {Error} if fails authentication
 */
export function authenticate(authorizationModel, didResolver) {
    return __awaiter(this, void 0, void 0, function* () {
        if (authorizationModel === undefined) {
            throw new DwnError(DwnErrorCode.AuthenticateJwsMissing, 'Missing JWS.');
        }
        yield GeneralJwsVerifier.verifySignatures(authorizationModel.signature, didResolver);
        if (authorizationModel.ownerSignature !== undefined) {
            yield GeneralJwsVerifier.verifySignatures(authorizationModel.ownerSignature, didResolver);
        }
        if (authorizationModel.authorDelegatedGrant !== undefined) {
            // verify the signature of the grantor of the delegated grant
            const authorDelegatedGrant = yield PermissionsGrant.parse(authorizationModel.authorDelegatedGrant);
            yield GeneralJwsVerifier.verifySignatures(authorDelegatedGrant.message.authorization.signature, didResolver);
        }
    });
}
/**
 * Authorizes the incoming message.
 * @throws {Error} if fails authentication
 */
export function authorize(tenant, incomingMessage) {
    return __awaiter(this, void 0, void 0, function* () {
        // if author is the same as the target tenant, we can directly grant access
        if (incomingMessage.author === tenant) {
            return;
        }
        else {
            throw new DwnError(DwnErrorCode.AuthorizationUnknownAuthor, 'message failed authorization, permission grant check not yet implemented');
        }
    });
}
//# sourceMappingURL=auth.js.map