@metamask/snaps-rpc-methods
Version:
MetaMask Snaps JSON-RPC method implementations
85 lines • 3.12 kB
JavaScript
import { PermissionType, SubjectType } from "@metamask/permission-controller";
import { rpcErrors } from "@metamask/rpc-errors";
import { MessengerScopesStruct, SnapCaveatType } from "@metamask/snaps-utils";
import { assertStruct, hasProperty, isObject } from "@metamask/utils";
import { createGenericPermissionValidator } from "./caveats/index.mjs";
import { SnapEndowments } from "./enum.mjs";
const permissionName = SnapEndowments.Messenger;
/**
* `endowment:messenger` returns nothing; it is intended to be used as a
* flag by the Snaps Platform to detect whether a Snap has the capability to
* use the messenger API.
*
* @param _builderOptions - Optional specification builder options.
* @returns The specification for the messenger endowment.
*/
const specificationBuilder = (_builderOptions) => {
return {
permissionType: PermissionType.Endowment,
targetName: permissionName,
allowedCaveats: [SnapCaveatType.MessengerScopes],
endowmentGetter: (_getterOptions) => null,
validator: createGenericPermissionValidator([
{ type: SnapCaveatType.MessengerScopes },
]),
subjectTypes: [SubjectType.Snap],
};
};
export const messengerEndowmentBuilder = Object.freeze({
targetName: permissionName,
specificationBuilder,
});
/**
* Map a raw value from the `initialPermissions` to a caveat specification.
* Note that this function does not do any validation, that's handled by the
* PermissionsController when the permission is requested.
*
* @param value - The raw value from the `initialPermissions`.
* @returns The caveat specification.
*/
export function getMessengerCaveatMapper(value) {
if (!value || !isObject(value) || Object.keys(value).length === 0) {
return { caveats: null };
}
return {
caveats: [
{
type: SnapCaveatType.MessengerScopes,
value,
},
],
};
}
/**
* Getter function to get the {@link MessengerActions} caveat value from a
* permission.
*
* @param permission - The permission to get the caveat value from.
* @returns The caveat value.
*/
export function getMessengerCaveatActions(permission) {
const caveat = permission?.caveats?.find((permCaveat) => permCaveat.type === SnapCaveatType.MessengerScopes);
return caveat?.value.actions ? caveat.value.actions : null;
}
/**
* Validates the type of the caveat value.
*
* @param caveat - The caveat to validate.
* @throws If the caveat value is invalid.
*/
function validateCaveat(caveat) {
if (!hasProperty(caveat, 'value') || !isObject(caveat)) {
throw rpcErrors.invalidParams({
message: 'Expected an object.',
});
}
const { value } = caveat;
assertStruct(value, MessengerScopesStruct, 'Invalid messenger scopes specified', rpcErrors.invalidParams);
}
export const messengerCaveatSpecifications = {
[SnapCaveatType.MessengerScopes]: Object.freeze({
type: SnapCaveatType.MessengerScopes,
validator: (caveat) => validateCaveat(caveat),
}),
};
//# sourceMappingURL=messenger.mjs.map