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 { removeUndefinedProperties } from '../utils/object.js';
import { Time } from '../utils/time.js';
import { validateMessageSignatureIntegrity } from '../core/auth.js';
import { DwnError, DwnErrorCode } from '../core/dwn-error.js';
import { DwnInterfaceName, DwnMethodName, Message } from '../core/message.js';
import { normalizeProtocolUrl, normalizeSchemaUrl } from '../utils/url.js';
export class PermissionsGrant extends Message {
    static parse(message) {
        return __awaiter(this, void 0, void 0, function* () {
            yield validateMessageSignatureIntegrity(message.authorization.signature, message.descriptor);
            PermissionsGrant.validateScope(message);
            Time.validateTimestamp(message.descriptor.messageTimestamp);
            Time.validateTimestamp(message.descriptor.dateExpires);
            return new PermissionsGrant(message);
        });
    }
    static create(options) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const scope = Object.assign({}, options.scope);
            scope.protocol = scope.protocol !== undefined ? normalizeProtocolUrl(scope.protocol) : undefined;
            scope.schema = scope.schema !== undefined ? normalizeSchemaUrl(scope.schema) : undefined;
            const descriptor = {
                interface: DwnInterfaceName.Permissions,
                method: DwnMethodName.Grant,
                messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp(),
                dateExpires: options.dateExpires,
                description: options.description,
                grantedTo: options.grantedTo,
                grantedBy: options.grantedBy,
                grantedFor: options.grantedFor,
                delegated: options.delegated,
                permissionsRequestId: options.permissionsRequestId,
                scope: scope,
                conditions: options.conditions,
            };
            // delete all descriptor properties that are `undefined` else the code will encounter the following IPLD issue when attempting to generate CID:
            // Error: `undefined` is not supported by the IPLD Data Model and cannot be encoded
            removeUndefinedProperties(descriptor);
            const authorization = yield Message.createAuthorization(descriptor, options.signer);
            const message = { descriptor, authorization };
            Message.validateJsonSchema(message);
            PermissionsGrant.validateScope(message);
            return new PermissionsGrant(message);
        });
    }
    /**
     * A convenience method for casting a PermissionsGrantMessage to a DelegatedGrantMessage if the `delegated` property is `true`.
     * @throws {DwnError} if the `delegated` property is not `true`.
     */
    asDelegatedGrant() {
        return PermissionsGrant.asDelegatedGrant(this.message);
    }
    /**
     * A convenience method for casting a PermissionsGrantMessage to a DelegatedGrantMessage if the `delegated` property is `true`.
     * @throws {DwnError} if the `delegated` property is not `true`.
     */
    static asDelegatedGrant(message) {
        if (!message.descriptor.delegated) {
            throw new DwnError(DwnErrorCode.PermissionsGrantNotADelegatedGrant, `PermissionsGrant given is not a delegated grant. Descriptor: ${message.descriptor}`);
        }
        return message;
    }
    /**
     * generates a PermissionsGrant using the provided PermissionsRequest
     * @param permissionsRequest
     * @param signer - the private key and additional signature material of the grantor
     * @param overrides - overrides that will be used instead of the properties in `permissionsRequest`
     */
    static createFromPermissionsRequest(permissionsRequest, signer, overrides) {
        var _a, _b, _c, _d, _e, _f;
        return __awaiter(this, void 0, void 0, function* () {
            const descriptor = permissionsRequest.message.descriptor;
            return PermissionsGrant.create({
                dateExpires: overrides.dateExpires,
                description: (_a = overrides.description) !== null && _a !== void 0 ? _a : descriptor.description,
                grantedBy: (_b = overrides.grantedBy) !== null && _b !== void 0 ? _b : descriptor.grantedBy,
                grantedTo: (_c = overrides.grantedTo) !== null && _c !== void 0 ? _c : descriptor.grantedTo,
                grantedFor: (_d = overrides.grantedFor) !== null && _d !== void 0 ? _d : descriptor.grantedFor,
                permissionsRequestId: yield Message.getCid(permissionsRequest.message),
                scope: (_e = overrides.scope) !== null && _e !== void 0 ? _e : descriptor.scope,
                conditions: (_f = overrides.conditions) !== null && _f !== void 0 ? _f : descriptor.conditions,
                signer,
            });
        });
    }
    /**
     * Current implementation only allows the DWN owner to store grants they created.
     */
    authorize() {
        const { grantedBy, grantedFor } = this.message.descriptor;
        if (this.author !== grantedBy) {
            throw new DwnError(DwnErrorCode.PermissionsGrantGrantedByMismatch, 'Message author must match grantedBy property');
        }
        else if (grantedBy !== grantedFor) {
            // Without delegation, only the DWN owner may grant access to their own DWN.
            throw new DwnError(DwnErrorCode.PermissionsGrantUnauthorizedGrant, `${grantedBy} is not authorized to give access to the DWN belonging to ${grantedFor}`);
        }
    }
    /**
     * Validates scope structure for properties beyond `interface` and `method`.
     * Currently only grants for RecordsRead and RecordsWrite have such properties and need validation beyond JSON Schema.
     */
    static validateScope(permissionsGrantMessage) {
        const recordsScope = permissionsGrantMessage.descriptor.scope;
        // `schema` scopes may not have protocol-related fields
        if (recordsScope.schema !== undefined) {
            if (recordsScope.protocol !== undefined || recordsScope.contextId !== undefined || recordsScope.protocolPath) {
                throw new DwnError(DwnErrorCode.PermissionsGrantScopeSchemaProhibitedFields, 'PermissionsGrants for RecordsRead and RecordsWrite that have `schema` present may not also have protocol-related properties present');
            }
        }
        if (recordsScope.protocol !== undefined) {
            // `contextId` and `protocolPath` are mutually exclusive
            if (recordsScope.contextId !== undefined && recordsScope.protocolPath !== undefined) {
                throw new DwnError(DwnErrorCode.PermissionsGrantScopeContextIdAndProtocolPath, 'PermissionsGrants for RecordsRead and RecordsWrite may not have both `contextId` and `protocolPath` present');
            }
        }
    }
}
//# sourceMappingURL=permissions-grant.js.map