@metamask/permission-controller 11.0.1 → 11.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/dist/Caveat.cjs +48 -0
  3. package/dist/Caveat.cjs.map +1 -0
  4. package/dist/{types/Caveat.d.ts → Caveat.d.cts} +3 -3
  5. package/dist/Caveat.d.cts.map +1 -0
  6. package/dist/Caveat.d.mts +210 -0
  7. package/dist/Caveat.d.mts.map +1 -0
  8. package/dist/Caveat.mjs +42 -11
  9. package/dist/Caveat.mjs.map +1 -1
  10. package/dist/Permission.cjs +65 -0
  11. package/dist/Permission.cjs.map +1 -0
  12. package/dist/{types/Permission.d.ts → Permission.d.cts} +7 -7
  13. package/dist/Permission.d.cts.map +1 -0
  14. package/dist/Permission.d.mts +417 -0
  15. package/dist/Permission.d.mts.map +1 -0
  16. package/dist/Permission.mjs +58 -13
  17. package/dist/Permission.mjs.map +1 -1
  18. package/dist/PermissionController.cjs +1481 -0
  19. package/dist/{chunk-COGJLF22.mjs.map → PermissionController.cjs.map} +1 -1
  20. package/dist/{types/PermissionController.d.ts → PermissionController.d.cts} +10 -10
  21. package/dist/PermissionController.d.cts.map +1 -0
  22. package/dist/PermissionController.d.mts +986 -0
  23. package/dist/PermissionController.d.mts.map +1 -0
  24. package/dist/PermissionController.mjs +1479 -13
  25. package/dist/PermissionController.mjs.map +1 -1
  26. package/dist/SubjectMetadataController.cjs +152 -0
  27. package/dist/SubjectMetadataController.cjs.map +1 -0
  28. package/dist/{types/SubjectMetadataController.d.ts → SubjectMetadataController.d.cts} +5 -5
  29. package/dist/SubjectMetadataController.d.cts.map +1 -0
  30. package/dist/SubjectMetadataController.d.mts +107 -0
  31. package/dist/SubjectMetadataController.d.mts.map +1 -0
  32. package/dist/SubjectMetadataController.mjs +146 -8
  33. package/dist/SubjectMetadataController.mjs.map +1 -1
  34. package/dist/errors.cjs +217 -0
  35. package/dist/errors.cjs.map +1 -0
  36. package/dist/{types/errors.d.ts → errors.d.cts} +6 -6
  37. package/dist/errors.d.cts.map +1 -0
  38. package/dist/errors.d.mts +185 -0
  39. package/dist/errors.d.mts.map +1 -0
  40. package/dist/errors.mjs +187 -57
  41. package/dist/errors.mjs.map +1 -1
  42. package/dist/index.cjs +38 -0
  43. package/dist/index.cjs.map +1 -0
  44. package/dist/index.d.cts +9 -0
  45. package/dist/index.d.cts.map +1 -0
  46. package/dist/index.d.mts +9 -0
  47. package/dist/index.d.mts.map +1 -0
  48. package/dist/index.mjs +7 -97
  49. package/dist/index.mjs.map +1 -1
  50. package/dist/permission-middleware.cjs +55 -0
  51. package/dist/permission-middleware.cjs.map +1 -0
  52. package/dist/{types/permission-middleware.d.ts → permission-middleware.d.cts} +4 -4
  53. package/dist/permission-middleware.d.cts.map +1 -0
  54. package/dist/permission-middleware.d.mts +33 -0
  55. package/dist/permission-middleware.d.mts.map +1 -0
  56. package/dist/permission-middleware.mjs +50 -8
  57. package/dist/permission-middleware.mjs.map +1 -1
  58. package/dist/rpc-methods/getPermissions.cjs +27 -0
  59. package/dist/rpc-methods/getPermissions.cjs.map +1 -0
  60. package/dist/rpc-methods/getPermissions.d.cts +9 -0
  61. package/dist/rpc-methods/getPermissions.d.cts.map +1 -0
  62. package/dist/rpc-methods/getPermissions.d.mts +9 -0
  63. package/dist/rpc-methods/getPermissions.d.mts.map +1 -0
  64. package/dist/rpc-methods/getPermissions.mjs +22 -7
  65. package/dist/rpc-methods/getPermissions.mjs.map +1 -1
  66. package/dist/rpc-methods/index.cjs +12 -0
  67. package/dist/rpc-methods/index.cjs.map +1 -0
  68. package/dist/rpc-methods/index.d.cts +6 -0
  69. package/dist/rpc-methods/index.d.cts.map +1 -0
  70. package/dist/rpc-methods/index.d.mts +6 -0
  71. package/dist/rpc-methods/index.d.mts.map +1 -0
  72. package/dist/rpc-methods/index.mjs +8 -12
  73. package/dist/rpc-methods/index.mjs.map +1 -1
  74. package/dist/rpc-methods/requestPermissions.cjs +36 -0
  75. package/dist/rpc-methods/requestPermissions.cjs.map +1 -0
  76. package/dist/{types/rpc-methods/requestPermissions.d.ts → rpc-methods/requestPermissions.d.cts} +3 -3
  77. package/dist/rpc-methods/requestPermissions.d.cts.map +1 -0
  78. package/dist/rpc-methods/requestPermissions.d.mts +17 -0
  79. package/dist/rpc-methods/requestPermissions.d.mts.map +1 -0
  80. package/dist/rpc-methods/requestPermissions.mjs +31 -8
  81. package/dist/rpc-methods/requestPermissions.mjs.map +1 -1
  82. package/dist/rpc-methods/revokePermissions.cjs +41 -0
  83. package/dist/rpc-methods/revokePermissions.cjs.map +1 -0
  84. package/dist/{types/rpc-methods/revokePermissions.d.ts → rpc-methods/revokePermissions.d.cts} +4 -4
  85. package/dist/rpc-methods/revokePermissions.d.cts.map +1 -0
  86. package/dist/rpc-methods/revokePermissions.d.mts +11 -0
  87. package/dist/rpc-methods/revokePermissions.d.mts.map +1 -0
  88. package/dist/rpc-methods/revokePermissions.mjs +36 -8
  89. package/dist/rpc-methods/revokePermissions.mjs.map +1 -1
  90. package/dist/utils.cjs +44 -0
  91. package/dist/utils.cjs.map +1 -0
  92. package/dist/{types/utils.d.ts → utils.d.cts} +5 -5
  93. package/dist/utils.d.cts.map +1 -0
  94. package/dist/utils.d.mts +57 -0
  95. package/dist/utils.d.mts.map +1 -0
  96. package/dist/utils.mjs +39 -9
  97. package/dist/utils.mjs.map +1 -1
  98. package/package.json +16 -11
  99. package/dist/Caveat.js +0 -12
  100. package/dist/Caveat.js.map +0 -1
  101. package/dist/Permission.js +0 -14
  102. package/dist/Permission.js.map +0 -1
  103. package/dist/PermissionController.js +0 -15
  104. package/dist/PermissionController.js.map +0 -1
  105. package/dist/SubjectMetadataController.js +0 -10
  106. package/dist/SubjectMetadataController.js.map +0 -1
  107. package/dist/chunk-2L4QPE5A.mjs +0 -25
  108. package/dist/chunk-2L4QPE5A.mjs.map +0 -1
  109. package/dist/chunk-3WWJKO7P.mjs +0 -37
  110. package/dist/chunk-3WWJKO7P.mjs.map +0 -1
  111. package/dist/chunk-3YOPLPVY.js +0 -37
  112. package/dist/chunk-3YOPLPVY.js.map +0 -1
  113. package/dist/chunk-42QSJHWO.mjs +0 -155
  114. package/dist/chunk-42QSJHWO.mjs.map +0 -1
  115. package/dist/chunk-4FMYQC3Y.mjs +0 -29
  116. package/dist/chunk-4FMYQC3Y.mjs.map +0 -1
  117. package/dist/chunk-4NAVRO44.mjs +0 -35
  118. package/dist/chunk-4NAVRO44.mjs.map +0 -1
  119. package/dist/chunk-5RFW5THA.mjs +0 -17
  120. package/dist/chunk-5RFW5THA.mjs.map +0 -1
  121. package/dist/chunk-6PXDVUYM.js +0 -29
  122. package/dist/chunk-6PXDVUYM.js.map +0 -1
  123. package/dist/chunk-74H4CVH7.mjs +0 -34
  124. package/dist/chunk-74H4CVH7.mjs.map +0 -1
  125. package/dist/chunk-7A3VYLCK.js +0 -30
  126. package/dist/chunk-7A3VYLCK.js.map +0 -1
  127. package/dist/chunk-B6PDRQ7N.js +0 -1679
  128. package/dist/chunk-B6PDRQ7N.js.map +0 -1
  129. package/dist/chunk-COGJLF22.mjs +0 -1679
  130. package/dist/chunk-F5TBMVWC.js +0 -46
  131. package/dist/chunk-F5TBMVWC.js.map +0 -1
  132. package/dist/chunk-FYADAA2G.js +0 -220
  133. package/dist/chunk-FYADAA2G.js.map +0 -1
  134. package/dist/chunk-G4BWJ7EA.mjs +0 -220
  135. package/dist/chunk-G4BWJ7EA.mjs.map +0 -1
  136. package/dist/chunk-HYMS7IGB.mjs +0 -31
  137. package/dist/chunk-HYMS7IGB.mjs.map +0 -1
  138. package/dist/chunk-I62TTXZ6.mjs +0 -46
  139. package/dist/chunk-I62TTXZ6.mjs.map +0 -1
  140. package/dist/chunk-OCLNDUYO.mjs +0 -30
  141. package/dist/chunk-OCLNDUYO.mjs.map +0 -1
  142. package/dist/chunk-VBIZGGQL.js +0 -17
  143. package/dist/chunk-VBIZGGQL.js.map +0 -1
  144. package/dist/chunk-VQPP5PWS.js +0 -35
  145. package/dist/chunk-VQPP5PWS.js.map +0 -1
  146. package/dist/chunk-VSDHL2GQ.js +0 -155
  147. package/dist/chunk-VSDHL2GQ.js.map +0 -1
  148. package/dist/chunk-X4ZAW4QR.js +0 -34
  149. package/dist/chunk-X4ZAW4QR.js.map +0 -1
  150. package/dist/chunk-Z2XKIXLS.js +0 -25
  151. package/dist/chunk-Z2XKIXLS.js.map +0 -1
  152. package/dist/chunk-ZH4MLSXX.js +0 -31
  153. package/dist/chunk-ZH4MLSXX.js.map +0 -1
  154. package/dist/errors.js +0 -58
  155. package/dist/errors.js.map +0 -1
  156. package/dist/index.js +0 -98
  157. package/dist/index.js.map +0 -1
  158. package/dist/permission-middleware.js +0 -9
  159. package/dist/permission-middleware.js.map +0 -1
  160. package/dist/rpc-methods/getPermissions.js +0 -9
  161. package/dist/rpc-methods/getPermissions.js.map +0 -1
  162. package/dist/rpc-methods/index.js +0 -13
  163. package/dist/rpc-methods/index.js.map +0 -1
  164. package/dist/rpc-methods/requestPermissions.js +0 -10
  165. package/dist/rpc-methods/requestPermissions.js.map +0 -1
  166. package/dist/rpc-methods/revokePermissions.js +0 -10
  167. package/dist/rpc-methods/revokePermissions.js.map +0 -1
  168. package/dist/tsconfig.build.tsbuildinfo +0 -1
  169. package/dist/types/Caveat.d.ts.map +0 -1
  170. package/dist/types/Permission.d.ts.map +0 -1
  171. package/dist/types/PermissionController.d.ts.map +0 -1
  172. package/dist/types/SubjectMetadataController.d.ts.map +0 -1
  173. package/dist/types/errors.d.ts.map +0 -1
  174. package/dist/types/index.d.ts +0 -9
  175. package/dist/types/index.d.ts.map +0 -1
  176. package/dist/types/permission-middleware.d.ts.map +0 -1
  177. package/dist/types/rpc-methods/getPermissions.d.ts +0 -9
  178. package/dist/types/rpc-methods/getPermissions.d.ts.map +0 -1
  179. package/dist/types/rpc-methods/index.d.ts +0 -6
  180. package/dist/types/rpc-methods/index.d.ts.map +0 -1
  181. package/dist/types/rpc-methods/requestPermissions.d.ts.map +0 -1
  182. package/dist/types/rpc-methods/revokePermissions.d.ts.map +0 -1
  183. package/dist/types/utils.d.ts.map +0 -1
  184. package/dist/utils.js +0 -10
  185. package/dist/utils.js.map +0 -1
@@ -1,46 +0,0 @@
1
- import {
2
- internalError
3
- } from "./chunk-G4BWJ7EA.mjs";
4
-
5
- // src/permission-middleware.ts
6
- import { createAsyncMiddleware } from "@metamask/json-rpc-engine";
7
- function getPermissionMiddlewareFactory({
8
- executeRestrictedMethod,
9
- getRestrictedMethod,
10
- isUnrestrictedMethod
11
- }) {
12
- return function createPermissionMiddleware(subject) {
13
- const { origin } = subject;
14
- if (typeof origin !== "string" || !origin) {
15
- throw new Error('The subject "origin" must be a non-empty string.');
16
- }
17
- const permissionsMiddleware = async (req, res, next) => {
18
- const { method, params } = req;
19
- if (isUnrestrictedMethod(method)) {
20
- return next();
21
- }
22
- const methodImplementation = getRestrictedMethod(method, origin);
23
- const result = await executeRestrictedMethod(
24
- methodImplementation,
25
- subject,
26
- method,
27
- params
28
- );
29
- if (result === void 0) {
30
- res.error = internalError(
31
- `Request for method "${req.method}" returned undefined result.`,
32
- { request: req }
33
- );
34
- return void 0;
35
- }
36
- res.result = result;
37
- return void 0;
38
- };
39
- return createAsyncMiddleware(permissionsMiddleware);
40
- };
41
- }
42
-
43
- export {
44
- getPermissionMiddlewareFactory
45
- };
46
- //# sourceMappingURL=chunk-I62TTXZ6.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/permission-middleware.ts"],"sourcesContent":["import { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n JsonRpcEngine,\n JsonRpcMiddleware,\n AsyncJsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type {\n Json,\n PendingJsonRpcResponse,\n JsonRpcRequest,\n} from '@metamask/utils';\n\nimport type {\n GenericPermissionController,\n PermissionSubjectMetadata,\n RestrictedMethodParameters,\n} from '.';\nimport { internalError } from './errors';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { PermissionController } from './PermissionController';\n\ntype PermissionMiddlewareFactoryOptions = {\n executeRestrictedMethod: GenericPermissionController['_executeRestrictedMethod'];\n getRestrictedMethod: GenericPermissionController['getRestrictedMethod'];\n isUnrestrictedMethod: (method: string) => boolean;\n};\n\n/**\n * Creates a permission middleware function factory. Intended for internal use\n * in the {@link PermissionController}. Like any {@link JsonRpcEngine}\n * middleware, each middleware will only receive requests from a particular\n * subject / origin. However, each middleware also requires access to some\n * `PermissionController` internals, which is why this \"factory factory\" exists.\n *\n * The middlewares returned by the factory will pass through requests for\n * unrestricted methods, and attempt to execute restricted methods. If a method\n * is neither restricted nor unrestricted, a \"method not found\" error will be\n * returned.\n * If a method is restricted, the middleware will first attempt to retrieve the\n * subject's permission for that method. If the permission is found, the method\n * will be executed. Otherwise, an \"unauthorized\" error will be returned.\n *\n * @param options - Options bag.\n * @param options.executeRestrictedMethod - {@link PermissionController._executeRestrictedMethod}.\n * @param options.getRestrictedMethod - {@link PermissionController.getRestrictedMethod}.\n * @param options.isUnrestrictedMethod - A function that checks whether a\n * particular method is unrestricted.\n * @returns A permission middleware factory function.\n */\nexport function getPermissionMiddlewareFactory({\n executeRestrictedMethod,\n getRestrictedMethod,\n isUnrestrictedMethod,\n}: PermissionMiddlewareFactoryOptions) {\n return function createPermissionMiddleware(\n subject: PermissionSubjectMetadata,\n ): JsonRpcMiddleware<RestrictedMethodParameters, Json> {\n const { origin } = subject;\n if (typeof origin !== 'string' || !origin) {\n throw new Error('The subject \"origin\" must be a non-empty string.');\n }\n\n const permissionsMiddleware = async (\n req: JsonRpcRequest<RestrictedMethodParameters>,\n res: PendingJsonRpcResponse<Json>,\n next: AsyncJsonRpcEngineNextCallback,\n ): Promise<void> => {\n const { method, params } = req;\n\n // Skip registered unrestricted methods.\n if (isUnrestrictedMethod(method)) {\n return next();\n }\n\n // This will throw if no restricted method implementation is found.\n const methodImplementation = getRestrictedMethod(method, origin);\n\n // This will throw if the permission does not exist.\n const result = await executeRestrictedMethod(\n methodImplementation,\n subject,\n method,\n params,\n );\n\n if (result === undefined) {\n res.error = internalError(\n `Request for method \"${req.method}\" returned undefined result.`,\n { request: req },\n );\n return undefined;\n }\n\n res.result = result;\n return undefined;\n };\n\n return createAsyncMiddleware(permissionsMiddleware);\n };\n}\n"],"mappings":";;;;;AAAA,SAAS,6BAA6B;AAkD/B,SAAS,+BAA+B;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AACF,GAAuC;AACrC,SAAO,SAAS,2BACd,SACqD;AACrD,UAAM,EAAE,OAAO,IAAI;AACnB,QAAI,OAAO,WAAW,YAAY,CAAC,QAAQ;AACzC,YAAM,IAAI,MAAM,kDAAkD;AAAA,IACpE;AAEA,UAAM,wBAAwB,OAC5B,KACA,KACA,SACkB;AAClB,YAAM,EAAE,QAAQ,OAAO,IAAI;AAG3B,UAAI,qBAAqB,MAAM,GAAG;AAChC,eAAO,KAAK;AAAA,MACd;AAGA,YAAM,uBAAuB,oBAAoB,QAAQ,MAAM;AAG/D,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAEA,UAAI,WAAW,QAAW;AACxB,YAAI,QAAQ;AAAA,UACV,uBAAuB,IAAI,MAAM;AAAA,UACjC,EAAE,SAAS,IAAI;AAAA,QACjB;AACA,eAAO;AAAA,MACT;AAEA,UAAI,SAAS;AACb,aAAO;AAAA,IACT;AAEA,WAAO,sBAAsB,qBAAqB;AAAA,EACpD;AACF;","names":[]}
@@ -1,30 +0,0 @@
1
- import {
2
- invalidParams
3
- } from "./chunk-G4BWJ7EA.mjs";
4
-
5
- // src/rpc-methods/requestPermissions.ts
6
- import { isPlainObject } from "@metamask/controller-utils";
7
- var requestPermissionsHandler = {
8
- methodNames: ["wallet_requestPermissions" /* RequestPermissions */],
9
- implementation: requestPermissionsImplementation,
10
- hookNames: {
11
- requestPermissionsForOrigin: true
12
- }
13
- };
14
- async function requestPermissionsImplementation(req, res, _next, end, { requestPermissionsForOrigin }) {
15
- const { params } = req;
16
- if (!Array.isArray(params) || !isPlainObject(params[0])) {
17
- return end(invalidParams({ data: { request: req } }));
18
- }
19
- const [requestedPermissions] = params;
20
- const [grantedPermissions] = await requestPermissionsForOrigin(
21
- requestedPermissions
22
- );
23
- res.result = Object.values(grantedPermissions);
24
- return end();
25
- }
26
-
27
- export {
28
- requestPermissionsHandler
29
- };
30
- //# sourceMappingURL=chunk-OCLNDUYO.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc-methods/requestPermissions.ts"],"sourcesContent":["import { isPlainObject } from '@metamask/controller-utils';\nimport type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils';\n\nimport { invalidParams } from '../errors';\nimport type { PermissionConstraint, RequestedPermissions } from '../Permission';\nimport type { PermittedHandlerExport } from '../utils';\nimport { MethodNames } from '../utils';\n\nexport const requestPermissionsHandler: PermittedHandlerExport<\n RequestPermissionsHooks,\n [RequestedPermissions],\n PermissionConstraint[]\n> = {\n methodNames: [MethodNames.RequestPermissions],\n implementation: requestPermissionsImplementation,\n hookNames: {\n requestPermissionsForOrigin: true,\n },\n};\n\ntype RequestPermissions = (\n requestedPermissions: RequestedPermissions,\n) => Promise<\n [Record<string, PermissionConstraint>, { id: string; origin: string }]\n>;\n\nexport type RequestPermissionsHooks = {\n requestPermissionsForOrigin: RequestPermissions;\n};\n\n/**\n * Request Permissions implementation to be used in JsonRpcEngine middleware.\n *\n * @param req - The JsonRpcEngine request\n * @param res - The JsonRpcEngine result object\n * @param _next - JsonRpcEngine next() callback - unused\n * @param end - JsonRpcEngine end() callback\n * @param options - Method hooks passed to the method implementation\n * @param options.requestPermissionsForOrigin - The specific method hook needed for this method implementation\n * @returns A promise that resolves to nothing\n */\nasync function requestPermissionsImplementation(\n req: JsonRpcRequest<[RequestedPermissions]>,\n res: PendingJsonRpcResponse<PermissionConstraint[]>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { requestPermissionsForOrigin }: RequestPermissionsHooks,\n): Promise<void> {\n const { params } = req;\n\n if (!Array.isArray(params) || !isPlainObject(params[0])) {\n return end(invalidParams({ data: { request: req } }));\n }\n\n const [requestedPermissions] = params;\n const [grantedPermissions] = await requestPermissionsForOrigin(\n requestedPermissions,\n );\n\n // `wallet_requestPermission` is specified to return an array.\n res.result = Object.values(grantedPermissions);\n return end();\n}\n"],"mappings":";;;;;AAAA,SAAS,qBAAqB;AASvB,IAAM,4BAIT;AAAA,EACF,aAAa,qDAA+B;AAAA,EAC5C,gBAAgB;AAAA,EAChB,WAAW;AAAA,IACT,6BAA6B;AAAA,EAC/B;AACF;AAuBA,eAAe,iCACb,KACA,KACA,OACA,KACA,EAAE,4BAA4B,GACf;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,MAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,CAAC,cAAc,OAAO,CAAC,CAAC,GAAG;AACvD,WAAO,IAAI,cAAc,EAAE,MAAM,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;AAAA,EACtD;AAEA,QAAM,CAAC,oBAAoB,IAAI;AAC/B,QAAM,CAAC,kBAAkB,IAAI,MAAM;AAAA,IACjC;AAAA,EACF;AAGA,MAAI,SAAS,OAAO,OAAO,kBAAkB;AAC7C,SAAO,IAAI;AACb;","names":[]}
@@ -1,17 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/rpc-methods/getPermissions.ts
2
- var getPermissionsHandler = {
3
- methodNames: ["wallet_getPermissions" /* GetPermissions */],
4
- implementation: getPermissionsImplementation,
5
- hookNames: {
6
- getPermissionsForOrigin: true
7
- }
8
- };
9
- async function getPermissionsImplementation(_req, res, _next, end, { getPermissionsForOrigin }) {
10
- res.result = Object.values(getPermissionsForOrigin() || {});
11
- return end();
12
- }
13
-
14
-
15
-
16
- exports.getPermissionsHandler = getPermissionsHandler;
17
- //# sourceMappingURL=chunk-VBIZGGQL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc-methods/getPermissions.ts"],"names":[],"mappings":";AAQO,IAAM,wBAIT;AAAA,EACF,aAAa,6CAA2B;AAAA,EACxC,gBAAgB;AAAA,EAChB,WAAW;AAAA,IACT,yBAAyB;AAAA,EAC3B;AACF;AAkBA,eAAe,6BACb,MACA,KACA,OACA,KACA,EAAE,wBAAwB,GACX;AACf,MAAI,SAAS,OAAO,OAAO,wBAAwB,KAAK,CAAC,CAAC;AAC1D,SAAO,IAAI;AACb","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { PermissionConstraint } from '../Permission';\nimport type { SubjectPermissions } from '../PermissionController';\nimport type { PermittedHandlerExport } from '../utils';\nimport { MethodNames } from '../utils';\n\nexport const getPermissionsHandler: PermittedHandlerExport<\n GetPermissionsHooks,\n [],\n PermissionConstraint[]\n> = {\n methodNames: [MethodNames.GetPermissions],\n implementation: getPermissionsImplementation,\n hookNames: {\n getPermissionsForOrigin: true,\n },\n};\n\nexport type GetPermissionsHooks = {\n // This must be bound to the requesting origin.\n getPermissionsForOrigin: () => SubjectPermissions<PermissionConstraint>;\n};\n\n/**\n * Get Permissions implementation to be used in JsonRpcEngine middleware.\n *\n * @param _req - The JsonRpcEngine request - unused\n * @param res - The JsonRpcEngine result object\n * @param _next - JsonRpcEngine next() callback - unused\n * @param end - JsonRpcEngine end() callback\n * @param options - Method hooks passed to the method implementation\n * @param options.getPermissionsForOrigin - The specific method hook needed for this method implementation\n * @returns A promise that resolves to nothing\n */\nasync function getPermissionsImplementation(\n _req: unknown,\n res: PendingJsonRpcResponse<PermissionConstraint[]>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { getPermissionsForOrigin }: GetPermissionsHooks,\n): Promise<void> {\n res.result = Object.values(getPermissionsForOrigin() || {});\n return end();\n}\n"]}
@@ -1,35 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/utils.ts
2
- var MethodNames = /* @__PURE__ */ ((MethodNames2) => {
3
- MethodNames2["RequestPermissions"] = "wallet_requestPermissions";
4
- MethodNames2["GetPermissions"] = "wallet_getPermissions";
5
- MethodNames2["RevokePermissions"] = "wallet_revokePermissions";
6
- return MethodNames2;
7
- })(MethodNames || {});
8
- function collectUniqueAndPairedCaveats(leftPermission, rightPermission) {
9
- const leftCaveats = leftPermission?.caveats?.slice() ?? [];
10
- const rightCaveats = rightPermission.caveats?.slice() ?? [];
11
- const leftUniqueCaveats = [];
12
- const caveatPairs = [];
13
- leftCaveats.forEach((leftCaveat) => {
14
- const rightCaveatIndex = rightCaveats.findIndex(
15
- (rightCaveat) => rightCaveat.type === leftCaveat.type
16
- );
17
- if (rightCaveatIndex === -1) {
18
- leftUniqueCaveats.push(leftCaveat);
19
- } else {
20
- caveatPairs.push([leftCaveat, rightCaveats[rightCaveatIndex]]);
21
- rightCaveats.splice(rightCaveatIndex, 1);
22
- }
23
- });
24
- return {
25
- caveatPairs,
26
- leftUniqueCaveats,
27
- rightUniqueCaveats: [...rightCaveats]
28
- };
29
- }
30
-
31
-
32
-
33
-
34
- exports.MethodNames = MethodNames; exports.collectUniqueAndPairedCaveats = collectUniqueAndPairedCaveats;
35
- //# sourceMappingURL=chunk-VQPP5PWS.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils.ts"],"names":["MethodNames"],"mappings":";AAsBO,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,wBAAqB;AACrB,EAAAA,aAAA,oBAAiB;AACjB,EAAAA,aAAA,uBAAoB;AAHV,SAAAA;AAAA,GAAA;AAsEL,SAAS,8BACd,gBACA,iBACA;AACA,QAAM,cAAc,gBAAgB,SAAS,MAAM,KAAK,CAAC;AACzD,QAAM,eAAe,gBAAgB,SAAS,MAAM,KAAK,CAAC;AAC1D,QAAM,oBAAwC,CAAC;AAC/C,QAAM,cAAsD,CAAC;AAE7D,cAAY,QAAQ,CAAC,eAAe;AAClC,UAAM,mBAAmB,aAAa;AAAA,MACpC,CAAC,gBAAgB,YAAY,SAAS,WAAW;AAAA,IACnD;AAEA,QAAI,qBAAqB,IAAI;AAC3B,wBAAkB,KAAK,UAAU;AAAA,IACnC,OAAO;AACL,kBAAY,KAAK,CAAC,YAAY,aAAa,gBAAgB,CAAC,CAAC;AAC7D,mBAAa,OAAO,kBAAkB,CAAC;AAAA,IACzC;AAAA,EACF,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,oBAAoB,CAAC,GAAG,YAAY;AAAA,EACtC;AACF","sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n CaveatConstraint,\n CaveatSpecificationConstraint,\n CaveatSpecificationMap,\n} from './Caveat';\nimport type {\n PermissionConstraint,\n PermissionSpecificationConstraint,\n PermissionSpecificationMap,\n} from './Permission';\n\nexport enum MethodNames {\n RequestPermissions = 'wallet_requestPermissions',\n GetPermissions = 'wallet_getPermissions',\n RevokePermissions = 'wallet_revokePermissions',\n}\n\n/**\n * Utility type for extracting a union of all individual caveat or permission\n * specification types from a {@link CaveatSpecificationMap} or\n * {@link PermissionSpecificationMap}.\n *\n * @template SpecificationsMap - The caveat or permission specifications map\n * whose specification type union to extract.\n */\nexport type ExtractSpecifications<\n SpecificationsMap extends\n | CaveatSpecificationMap<CaveatSpecificationConstraint>\n | PermissionSpecificationMap<PermissionSpecificationConstraint>,\n> = SpecificationsMap[keyof SpecificationsMap];\n\n/**\n * A middleware function for handling a permitted method.\n */\nexport type HandlerMiddlewareFunction<\n Hooks,\n Params extends JsonRpcParams,\n Result extends Json,\n> = (\n req: JsonRpcRequest<Params>,\n res: PendingJsonRpcResponse<Result>,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: Hooks,\n) => void | Promise<void>;\n\n/**\n * We use a mapped object type in order to create a type that requires the\n * presence of the names of all hooks for the given handler.\n * This can then be used to select only the necessary hooks whenever a method\n * is called for purposes of POLA.\n */\nexport type HookNames<HookMap> = {\n [Property in keyof HookMap]: true;\n};\n\n/**\n * A handler for a permitted method.\n */\nexport type PermittedHandlerExport<\n Hooks,\n Params extends JsonRpcParams,\n Result extends Json,\n> = {\n implementation: HandlerMiddlewareFunction<Hooks, Params, Result>;\n hookNames: HookNames<Hooks>;\n methodNames: string[];\n};\n\n/**\n * Given two permission objects, computes 3 sets:\n * - The set of caveat pairs that are common to both permissions.\n * - The set of caveats that are unique to the existing permission.\n * - The set of caveats that are unique to the requested permission.\n *\n * Assumes that the caveat arrays of both permissions are valid.\n *\n * @param leftPermission - The left-hand permission.\n * @param rightPermission - The right-hand permission.\n * @returns The sets of caveat pairs and unique caveats.\n */\nexport function collectUniqueAndPairedCaveats(\n leftPermission: Partial<PermissionConstraint> | undefined,\n rightPermission: Partial<PermissionConstraint>,\n) {\n const leftCaveats = leftPermission?.caveats?.slice() ?? [];\n const rightCaveats = rightPermission.caveats?.slice() ?? [];\n const leftUniqueCaveats: CaveatConstraint[] = [];\n const caveatPairs: [CaveatConstraint, CaveatConstraint][] = [];\n\n leftCaveats.forEach((leftCaveat) => {\n const rightCaveatIndex = rightCaveats.findIndex(\n (rightCaveat) => rightCaveat.type === leftCaveat.type,\n );\n\n if (rightCaveatIndex === -1) {\n leftUniqueCaveats.push(leftCaveat);\n } else {\n caveatPairs.push([leftCaveat, rightCaveats[rightCaveatIndex]]);\n rightCaveats.splice(rightCaveatIndex, 1);\n }\n });\n\n return {\n caveatPairs,\n leftUniqueCaveats,\n rightUniqueCaveats: [...rightCaveats],\n };\n}\n"]}
@@ -1,155 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/SubjectMetadataController.ts
2
- var _basecontroller = require('@metamask/base-controller');
3
- var controllerName = "SubjectMetadataController";
4
- var SubjectType = /* @__PURE__ */ ((SubjectType2) => {
5
- SubjectType2["Extension"] = "extension";
6
- SubjectType2["Internal"] = "internal";
7
- SubjectType2["Unknown"] = "unknown";
8
- SubjectType2["Website"] = "website";
9
- SubjectType2["Snap"] = "snap";
10
- return SubjectType2;
11
- })(SubjectType || {});
12
- var stateMetadata = {
13
- subjectMetadata: { persist: true, anonymous: false }
14
- };
15
- var defaultState = {
16
- subjectMetadata: {}
17
- };
18
- var SubjectMetadataController = class _SubjectMetadataController extends _basecontroller.BaseController {
19
- constructor({
20
- messenger,
21
- subjectCacheLimit,
22
- state = {}
23
- }) {
24
- if (!Number.isInteger(subjectCacheLimit) || subjectCacheLimit < 1) {
25
- throw new Error(
26
- `subjectCacheLimit must be a positive integer. Received: "${subjectCacheLimit}"`
27
- );
28
- }
29
- const hasPermissions = (origin) => {
30
- return messenger.call("PermissionController:hasPermissions", origin);
31
- };
32
- super({
33
- name: controllerName,
34
- metadata: stateMetadata,
35
- messenger,
36
- state: {
37
- ..._SubjectMetadataController.getTrimmedState(state, hasPermissions)
38
- }
39
- });
40
- this.subjectHasPermissions = hasPermissions;
41
- this.subjectCacheLimit = subjectCacheLimit;
42
- this.subjectsWithoutPermissionsEncounteredSinceStartup = /* @__PURE__ */ new Set();
43
- this.messagingSystem.registerActionHandler(
44
- // ESLint is confused by the string literal type.
45
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
46
- `${this.name}:getSubjectMetadata`,
47
- this.getSubjectMetadata.bind(this)
48
- );
49
- this.messagingSystem.registerActionHandler(
50
- // ESLint is confused by the string literal type.
51
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
52
- `${this.name}:addSubjectMetadata`,
53
- this.addSubjectMetadata.bind(this)
54
- );
55
- }
56
- /**
57
- * Clears the state of this controller. Also resets the cache of subjects
58
- * encountered since startup, so as to not prematurely reach the cache limit.
59
- */
60
- clearState() {
61
- this.subjectsWithoutPermissionsEncounteredSinceStartup.clear();
62
- this.update((_draftState) => {
63
- return { ...defaultState };
64
- });
65
- }
66
- /**
67
- * Stores domain metadata for the given origin (subject). Deletes metadata for
68
- * subjects without permissions in a FIFO manner once more than
69
- * {@link SubjectMetadataController.subjectCacheLimit} distinct origins have
70
- * been added since boot.
71
- *
72
- * In order to prevent a degraded user experience,
73
- * metadata is never deleted for subjects with permissions, since metadata
74
- * cannot yet be requested on demand.
75
- *
76
- * @param metadata - The subject metadata to store.
77
- */
78
- addSubjectMetadata(metadata) {
79
- const { origin } = metadata;
80
- const newMetadata = {
81
- ...metadata,
82
- extensionId: metadata.extensionId || null,
83
- iconUrl: metadata.iconUrl || null,
84
- name: metadata.name || null,
85
- subjectType: metadata.subjectType || null
86
- };
87
- let originToForget = null;
88
- if (this.subjectsWithoutPermissionsEncounteredSinceStartup.size >= this.subjectCacheLimit) {
89
- const cachedOrigin = this.subjectsWithoutPermissionsEncounteredSinceStartup.values().next().value;
90
- this.subjectsWithoutPermissionsEncounteredSinceStartup.delete(
91
- cachedOrigin
92
- );
93
- if (!this.subjectHasPermissions(cachedOrigin)) {
94
- originToForget = cachedOrigin;
95
- }
96
- }
97
- this.subjectsWithoutPermissionsEncounteredSinceStartup.add(origin);
98
- this.update((draftState) => {
99
- draftState.subjectMetadata[origin] = newMetadata;
100
- if (typeof originToForget === "string") {
101
- delete draftState.subjectMetadata[originToForget];
102
- }
103
- });
104
- }
105
- /**
106
- * Gets the subject metadata for the given origin, if any.
107
- *
108
- * @param origin - The origin for which to get the subject metadata.
109
- * @returns The subject metadata, if any, or `undefined` otherwise.
110
- */
111
- getSubjectMetadata(origin) {
112
- return this.state.subjectMetadata[origin];
113
- }
114
- /**
115
- * Deletes all subjects without permissions from the controller's state.
116
- */
117
- trimMetadataState() {
118
- this.update((draftState) => {
119
- return _SubjectMetadataController.getTrimmedState(
120
- draftState,
121
- this.subjectHasPermissions
122
- );
123
- });
124
- }
125
- /**
126
- * Returns a new state object that only includes subjects with permissions.
127
- * This method is static because we want to call it in the constructor, before
128
- * the controller's state is initialized.
129
- *
130
- * @param state - The state object to trim.
131
- * @param hasPermissions - A function that returns a boolean indicating
132
- * whether a particular subject (identified by its origin) has any
133
- * permissions.
134
- * @returns The new state object. If the specified `state` object has no
135
- * subject metadata, the returned object will be equivalent to the default
136
- * state of this controller.
137
- */
138
- static getTrimmedState(state, hasPermissions) {
139
- const { subjectMetadata = {} } = state;
140
- return {
141
- subjectMetadata: Object.keys(subjectMetadata).reduce((newSubjectMetadata, origin) => {
142
- if (hasPermissions(origin)) {
143
- newSubjectMetadata[origin] = subjectMetadata[origin];
144
- }
145
- return newSubjectMetadata;
146
- }, {})
147
- };
148
- }
149
- };
150
-
151
-
152
-
153
-
154
- exports.SubjectType = SubjectType; exports.SubjectMetadataController = SubjectMetadataController;
155
- //# sourceMappingURL=chunk-VSDHL2GQ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/SubjectMetadataController.ts"],"names":["SubjectType"],"mappings":";AAKA,SAAS,sBAAsB;AAS/B,IAAM,iBAAiB;AAQhB,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,cAAW;AACX,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,UAAO;AALG,SAAAA;AAAA,GAAA;AA2BZ,IAAM,gBAAgB;AAAA,EACpB,iBAAiB,EAAE,SAAS,MAAM,WAAW,MAAM;AACrD;AAEA,IAAM,eAA+C;AAAA,EACnD,iBAAiB,CAAC;AACpB;AAiDO,IAAM,4BAAN,MAAM,mCAAkC,eAI7C;AAAA,EAOA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA,QAAQ,CAAC;AAAA,EACX,GAAqC;AACnC,QAAI,CAAC,OAAO,UAAU,iBAAiB,KAAK,oBAAoB,GAAG;AACjE,YAAM,IAAI;AAAA,QACR,4DAA4D,iBAAiB;AAAA,MAC/E;AAAA,IACF;AAEA,UAAM,iBAAiB,CAAC,WAAmB;AACzC,aAAO,UAAU,KAAK,uCAAuC,MAAM;AAAA,IACrE;AAEA,UAAM;AAAA,MACJ,MAAM;AAAA,MACN,UAAU;AAAA,MACV;AAAA,MACA,OAAO;AAAA,QACL,GAAG,2BAA0B,gBAAgB,OAAO,cAAc;AAAA,MACpE;AAAA,IACF,CAAC;AAED,SAAK,wBAAwB;AAC7B,SAAK,oBAAoB;AACzB,SAAK,oDAAoD,oBAAI,IAAI;AAEjE,SAAK,gBAAgB;AAAA;AAAA;AAAA,MAGnB,GAAG,KAAK,IAAI;AAAA,MACZ,KAAK,mBAAmB,KAAK,IAAI;AAAA,IACnC;AAEA,SAAK,gBAAgB;AAAA;AAAA;AAAA,MAGnB,GAAG,KAAK,IAAI;AAAA,MACZ,KAAK,mBAAmB,KAAK,IAAI;AAAA,IACnC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAmB;AACjB,SAAK,kDAAkD,MAAM;AAC7D,SAAK,OAAO,CAAC,gBAAgB;AAC3B,aAAO,EAAE,GAAG,aAAa;AAAA,IAC3B,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,mBAAmB,UAAsC;AACvD,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,cAA+B;AAAA,MACnC,GAAG;AAAA,MACH,aAAa,SAAS,eAAe;AAAA,MACrC,SAAS,SAAS,WAAW;AAAA,MAC7B,MAAM,SAAS,QAAQ;AAAA,MACvB,aAAa,SAAS,eAAe;AAAA,IACvC;AAEA,QAAI,iBAAgC;AAGpC,QACE,KAAK,kDAAkD,QACvD,KAAK,mBACL;AACA,YAAM,eACJ,KAAK,kDACF,OAAO,EACP,KAAK,EAAE;AAEZ,WAAK,kDAAkD;AAAA,QACrD;AAAA,MACF;AAEA,UAAI,CAAC,KAAK,sBAAsB,YAAY,GAAG;AAC7C,yBAAiB;AAAA,MACnB;AAAA,IACF;AAEA,SAAK,kDAAkD,IAAI,MAAM;AAEjE,SAAK,OAAO,CAAC,eAAe;AAC1B,iBAAW,gBAAgB,MAAM,IAAI;AACrC,UAAI,OAAO,mBAAmB,UAAU;AACtC,eAAO,WAAW,gBAAgB,cAAc;AAAA,MAClD;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,mBAAmB,QAAoD;AACrE,WAAO,KAAK,MAAM,gBAAgB,MAAM;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA,EAKA,oBAA0B;AACxB,SAAK,OAAO,CAAC,eAAe;AAE1B,aAAO,2BAA0B;AAAA,QAC/B;AAAA,QACA,KAAK;AAAA,MACP;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,OAAe,gBACb,OACA,gBACgC;AAChC,UAAM,EAAE,kBAAkB,CAAC,EAAE,IAAI;AAEjC,WAAO;AAAA,MACL,iBAAiB,OAAO,KAAK,eAAe,EAAE,OAE5C,CAAC,oBAAoB,WAAW;AAChC,YAAI,eAAe,MAAM,GAAG;AAC1B,6BAAmB,MAAM,IAAI,gBAAgB,MAAM;AAAA,QACrD;AACA,eAAO;AAAA,MACT,GAAG,CAAC,CAAC;AAAA,IACP;AAAA,EACF;AACF","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n GenericPermissionController,\n HasPermissions,\n PermissionSubjectMetadata,\n} from './PermissionController';\n\nconst controllerName = 'SubjectMetadataController';\n\ntype SubjectOrigin = string;\n\n/**\n * The different kinds of subjects that MetaMask may interact with, including\n * third parties and itself (e.g., when the background communicated with the UI).\n */\nexport enum SubjectType {\n Extension = 'extension',\n Internal = 'internal',\n Unknown = 'unknown',\n Website = 'website',\n Snap = 'snap',\n}\n\nexport type SubjectMetadata = PermissionSubjectMetadata & {\n [key: string]: Json;\n name: string | null;\n subjectType: SubjectType | null;\n extensionId: string | null;\n iconUrl: string | null;\n};\n\ntype SubjectMetadataToAdd = PermissionSubjectMetadata & {\n name?: string | null;\n subjectType?: SubjectType | null;\n extensionId?: string | null;\n iconUrl?: string | null;\n} & Record<string, Json>;\n\nexport type SubjectMetadataControllerState = {\n subjectMetadata: Record<SubjectOrigin, SubjectMetadata>;\n};\n\nconst stateMetadata = {\n subjectMetadata: { persist: true, anonymous: false },\n};\n\nconst defaultState: SubjectMetadataControllerState = {\n subjectMetadata: {},\n};\n\nexport type GetSubjectMetadataState = ControllerGetStateAction<\n typeof controllerName,\n SubjectMetadataControllerState\n>;\n\nexport type GetSubjectMetadata = {\n type: `${typeof controllerName}:getSubjectMetadata`;\n handler: (origin: SubjectOrigin) => SubjectMetadata | undefined;\n};\n\nexport type AddSubjectMetadata = {\n type: `${typeof controllerName}:addSubjectMetadata`;\n handler: (metadata: SubjectMetadataToAdd) => void;\n};\n\nexport type SubjectMetadataControllerActions =\n | GetSubjectMetadataState\n | GetSubjectMetadata\n | AddSubjectMetadata;\n\nexport type SubjectMetadataStateChange = ControllerStateChangeEvent<\n typeof controllerName,\n SubjectMetadataControllerState\n>;\n\nexport type SubjectMetadataControllerEvents = SubjectMetadataStateChange;\n\ntype AllowedActions = HasPermissions;\n\nexport type SubjectMetadataControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SubjectMetadataControllerActions | AllowedActions,\n SubjectMetadataControllerEvents,\n AllowedActions['type'],\n never\n>;\n\ntype SubjectMetadataControllerOptions = {\n messenger: SubjectMetadataControllerMessenger;\n subjectCacheLimit: number;\n state?: Partial<SubjectMetadataControllerState>;\n};\n\n/**\n * A controller for storing metadata associated with permission subjects. More\n * or less, a cache.\n */\nexport class SubjectMetadataController extends BaseController<\n typeof controllerName,\n SubjectMetadataControllerState,\n SubjectMetadataControllerMessenger\n> {\n private readonly subjectCacheLimit: number;\n\n private readonly subjectsWithoutPermissionsEncounteredSinceStartup: Set<string>;\n\n private readonly subjectHasPermissions: GenericPermissionController['hasPermissions'];\n\n constructor({\n messenger,\n subjectCacheLimit,\n state = {},\n }: SubjectMetadataControllerOptions) {\n if (!Number.isInteger(subjectCacheLimit) || subjectCacheLimit < 1) {\n throw new Error(\n `subjectCacheLimit must be a positive integer. Received: \"${subjectCacheLimit}\"`,\n );\n }\n\n const hasPermissions = (origin: string) => {\n return messenger.call('PermissionController:hasPermissions', origin);\n };\n\n super({\n name: controllerName,\n metadata: stateMetadata,\n messenger,\n state: {\n ...SubjectMetadataController.getTrimmedState(state, hasPermissions),\n },\n });\n\n this.subjectHasPermissions = hasPermissions;\n this.subjectCacheLimit = subjectCacheLimit;\n this.subjectsWithoutPermissionsEncounteredSinceStartup = new Set();\n\n this.messagingSystem.registerActionHandler(\n // ESLint is confused by the string literal type.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:getSubjectMetadata`,\n this.getSubjectMetadata.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n // ESLint is confused by the string literal type.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `${this.name}:addSubjectMetadata`,\n this.addSubjectMetadata.bind(this),\n );\n }\n\n /**\n * Clears the state of this controller. Also resets the cache of subjects\n * encountered since startup, so as to not prematurely reach the cache limit.\n */\n clearState(): void {\n this.subjectsWithoutPermissionsEncounteredSinceStartup.clear();\n this.update((_draftState) => {\n return { ...defaultState };\n });\n }\n\n /**\n * Stores domain metadata for the given origin (subject). Deletes metadata for\n * subjects without permissions in a FIFO manner once more than\n * {@link SubjectMetadataController.subjectCacheLimit} distinct origins have\n * been added since boot.\n *\n * In order to prevent a degraded user experience,\n * metadata is never deleted for subjects with permissions, since metadata\n * cannot yet be requested on demand.\n *\n * @param metadata - The subject metadata to store.\n */\n addSubjectMetadata(metadata: SubjectMetadataToAdd): void {\n const { origin } = metadata;\n const newMetadata: SubjectMetadata = {\n ...metadata,\n extensionId: metadata.extensionId || null,\n iconUrl: metadata.iconUrl || null,\n name: metadata.name || null,\n subjectType: metadata.subjectType || null,\n };\n\n let originToForget: string | null = null;\n // We only delete the oldest encountered subject from the cache, again to\n // ensure that the user's experience isn't degraded by missing icons etc.\n if (\n this.subjectsWithoutPermissionsEncounteredSinceStartup.size >=\n this.subjectCacheLimit\n ) {\n const cachedOrigin =\n this.subjectsWithoutPermissionsEncounteredSinceStartup\n .values()\n .next().value;\n\n this.subjectsWithoutPermissionsEncounteredSinceStartup.delete(\n cachedOrigin,\n );\n\n if (!this.subjectHasPermissions(cachedOrigin)) {\n originToForget = cachedOrigin;\n }\n }\n\n this.subjectsWithoutPermissionsEncounteredSinceStartup.add(origin);\n\n this.update((draftState) => {\n draftState.subjectMetadata[origin] = newMetadata;\n if (typeof originToForget === 'string') {\n delete draftState.subjectMetadata[originToForget];\n }\n });\n }\n\n /**\n * Gets the subject metadata for the given origin, if any.\n *\n * @param origin - The origin for which to get the subject metadata.\n * @returns The subject metadata, if any, or `undefined` otherwise.\n */\n getSubjectMetadata(origin: SubjectOrigin): SubjectMetadata | undefined {\n return this.state.subjectMetadata[origin];\n }\n\n /**\n * Deletes all subjects without permissions from the controller's state.\n */\n trimMetadataState(): void {\n this.update((draftState) => {\n // @ts-expect-error ts(2589)\n return SubjectMetadataController.getTrimmedState(\n draftState,\n this.subjectHasPermissions,\n );\n });\n }\n\n /**\n * Returns a new state object that only includes subjects with permissions.\n * This method is static because we want to call it in the constructor, before\n * the controller's state is initialized.\n *\n * @param state - The state object to trim.\n * @param hasPermissions - A function that returns a boolean indicating\n * whether a particular subject (identified by its origin) has any\n * permissions.\n * @returns The new state object. If the specified `state` object has no\n * subject metadata, the returned object will be equivalent to the default\n * state of this controller.\n */\n private static getTrimmedState(\n state: Partial<SubjectMetadataControllerState>,\n hasPermissions: SubjectMetadataController['subjectHasPermissions'],\n ): SubjectMetadataControllerState {\n const { subjectMetadata = {} } = state;\n\n return {\n subjectMetadata: Object.keys(subjectMetadata).reduce<\n Record<SubjectOrigin, SubjectMetadata>\n >((newSubjectMetadata, origin) => {\n if (hasPermissions(origin)) {\n newSubjectMetadata[origin] = subjectMetadata[origin];\n }\n return newSubjectMetadata;\n }, {}),\n };\n }\n}\n"]}
@@ -1,34 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
- var _chunkFYADAA2Gjs = require('./chunk-FYADAA2G.js');
4
-
5
- // src/rpc-methods/revokePermissions.ts
6
-
7
-
8
- var _utils = require('@metamask/utils');
9
- var revokePermissionsHandler = {
10
- methodNames: ["wallet_revokePermissions" /* RevokePermissions */],
11
- implementation: revokePermissionsImplementation,
12
- hookNames: {
13
- revokePermissionsForOrigin: true
14
- }
15
- };
16
- async function revokePermissionsImplementation(req, res, _next, end, { revokePermissionsForOrigin }) {
17
- const { params } = req;
18
- const param = params?.[0];
19
- if (!param) {
20
- return end(_chunkFYADAA2Gjs.invalidParams.call(void 0, { data: { request: req } }));
21
- }
22
- const permissionKeys = Object.keys(param);
23
- if (!_utils.isNonEmptyArray.call(void 0, permissionKeys)) {
24
- return end(_chunkFYADAA2Gjs.invalidParams.call(void 0, { data: { request: req } }));
25
- }
26
- revokePermissionsForOrigin(permissionKeys);
27
- res.result = null;
28
- return end();
29
- }
30
-
31
-
32
-
33
- exports.revokePermissionsHandler = revokePermissionsHandler;
34
- //# sourceMappingURL=chunk-X4ZAW4QR.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc-methods/revokePermissions.ts"],"names":[],"mappings":";;;;;AACA;AAAA,EACE;AAAA,OAKK;AAOA,IAAM,2BAIT;AAAA,EACF,aAAa,mDAA8B;AAAA,EAC3C,gBAAgB;AAAA,EAChB,WAAW;AAAA,IACT,4BAA4B;AAAA,EAC9B;AACF;AA0BA,eAAe,gCACb,KACA,KACA,OACA,KACA,EAAE,2BAA2B,GACd;AACf,QAAM,EAAE,OAAO,IAAI;AAEnB,QAAM,QAAQ,SAAS,CAAC;AAExB,MAAI,CAAC,OAAO;AACV,WAAO,IAAI,cAAc,EAAE,MAAM,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;AAAA,EACtD;AAIA,QAAM,iBAAiB,OAAO,KAAK,KAAK;AAExC,MAAI,CAAC,gBAAgB,cAAc,GAAG;AACpC,WAAO,IAAI,cAAc,EAAE,MAAM,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;AAAA,EACtD;AAEA,6BAA2B,cAAc;AAEzC,MAAI,SAAS;AAEb,SAAO,IAAI;AACb","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport {\n isNonEmptyArray,\n type Json,\n type JsonRpcRequest,\n type NonEmptyArray,\n type PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport { invalidParams } from '../errors';\nimport type { PermissionConstraint } from '../Permission';\nimport type { PermittedHandlerExport } from '../utils';\nimport { MethodNames } from '../utils';\n\nexport const revokePermissionsHandler: PermittedHandlerExport<\n RevokePermissionsHooks,\n RevokePermissionArgs,\n null\n> = {\n methodNames: [MethodNames.RevokePermissions],\n implementation: revokePermissionsImplementation,\n hookNames: {\n revokePermissionsForOrigin: true,\n },\n};\n\nexport type RevokePermissionArgs = Record<\n PermissionConstraint['parentCapability'],\n Json\n>;\n\ntype RevokePermissions = (\n permissions: NonEmptyArray<PermissionConstraint['parentCapability']>,\n) => void;\n\nexport type RevokePermissionsHooks = {\n revokePermissionsForOrigin: RevokePermissions;\n};\n\n/**\n * Revoke Permissions implementation to be used in JsonRpcEngine middleware.\n *\n * @param req - The JsonRpcEngine request\n * @param res - The JsonRpcEngine result object\n * @param _next - JsonRpcEngine next() callback - unused\n * @param end - JsonRpcEngine end() callback\n * @param options - Method hooks passed to the method implementation\n * @param options.revokePermissionsForOrigin - A hook that revokes given permission keys for an origin\n * @returns A promise that resolves to nothing\n */\nasync function revokePermissionsImplementation(\n req: JsonRpcRequest<RevokePermissionArgs>,\n res: PendingJsonRpcResponse<null>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { revokePermissionsForOrigin }: RevokePermissionsHooks,\n): Promise<void> {\n const { params } = req;\n\n const param = params?.[0];\n\n if (!param) {\n return end(invalidParams({ data: { request: req } }));\n }\n\n // For now, this API revokes the entire permission key\n // even if caveats are specified.\n const permissionKeys = Object.keys(param);\n\n if (!isNonEmptyArray(permissionKeys)) {\n return end(invalidParams({ data: { request: req } }));\n }\n\n revokePermissionsForOrigin(permissionKeys);\n\n res.result = null;\n\n return end();\n}\n"]}
@@ -1,25 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
- var __accessCheck = (obj, member, msg) => {
7
- if (!member.has(obj))
8
- throw TypeError("Cannot " + msg);
9
- };
10
- var __privateAdd = (obj, member, value) => {
11
- if (member.has(obj))
12
- throw TypeError("Cannot add the same private member more than once");
13
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
14
- };
15
- var __privateMethod = (obj, member, method) => {
16
- __accessCheck(obj, member, "access private method");
17
- return method;
18
- };
19
-
20
-
21
-
22
-
23
-
24
- exports.__export = __export; exports.__privateAdd = __privateAdd; exports.__privateMethod = __privateMethod;
25
- //# sourceMappingURL=chunk-Z2XKIXLS.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,31 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/Permission.ts
2
- var _nanoid = require('nanoid');
3
- function constructPermission(options) {
4
- const { caveats = null, invoker, target } = options;
5
- return {
6
- id: _nanoid.nanoid.call(void 0, ),
7
- parentCapability: target,
8
- invoker,
9
- caveats,
10
- date: (/* @__PURE__ */ new Date()).getTime()
11
- };
12
- }
13
- function findCaveat(permission, caveatType) {
14
- return permission.caveats?.find((caveat) => caveat.type === caveatType);
15
- }
16
- var PermissionType = /* @__PURE__ */ ((PermissionType2) => {
17
- PermissionType2["RestrictedMethod"] = "RestrictedMethod";
18
- PermissionType2["Endowment"] = "Endowment";
19
- return PermissionType2;
20
- })(PermissionType || {});
21
- function hasSpecificationType(specification, expectedType) {
22
- return specification.permissionType === expectedType;
23
- }
24
-
25
-
26
-
27
-
28
-
29
-
30
- exports.constructPermission = constructPermission; exports.findCaveat = findCaveat; exports.PermissionType = PermissionType; exports.hasSpecificationType = hasSpecificationType;
31
- //# sourceMappingURL=chunk-ZH4MLSXX.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/Permission.ts"],"names":["PermissionType"],"mappings":";AAMA,SAAS,cAAc;AA2JhB,SAAS,oBAEd,SAAgE;AAChE,QAAM,EAAE,UAAU,MAAM,SAAS,OAAO,IAAI;AAE5C,SAAO;AAAA,IACL,IAAI,OAAO;AAAA,IACX,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA,OAAM,oBAAI,KAAK,GAAE,QAAQ;AAAA,EAC3B;AACF;AASO,SAAS,WACd,YACA,YAC8B;AAC9B,SAAO,WAAW,SAAS,KAAK,CAAC,WAAW,OAAO,SAAS,UAAU;AACxE;AAmKO,IAAK,iBAAL,kBAAKA,oBAAL;AAKL,EAAAA,gBAAA,sBAAmB;AAMnB,EAAAA,gBAAA,eAAY;AAXF,SAAAA;AAAA,GAAA;AA2NL,SAAS,qBAId,eACA,cAGA;AACA,SAAO,cAAc,mBAAmB;AAC1C","sourcesContent":["import type {\n ActionConstraint,\n EventConstraint,\n} from '@metamask/base-controller';\nimport type { NonEmptyArray } from '@metamask/controller-utils';\nimport type { Json } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport type { CaveatConstraint, Caveat } from './Caveat';\nimport type {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n PermissionController,\n PermissionsRequest,\n SideEffectMessenger,\n} from './PermissionController';\nimport type { SubjectType } from './SubjectMetadataController';\n\n/**\n * The origin of a subject.\n * Effectively the GUID of an entity that can have permissions.\n */\nexport type OriginString = string;\n\n/**\n * The name of a permission target.\n */\ntype TargetName = string;\n\n/**\n * A `ZCAP-LD`-like permission object. A permission is associated with a\n * particular `invoker`, which is the holder of the permission. Possessing the\n * permission grants access to a particular restricted resource, identified by\n * the `parentCapability`. The use of the restricted resource may be further\n * restricted by any `caveats` associated with the permission.\n *\n * See the README for details.\n */\nexport type PermissionConstraint = {\n /**\n * The context(s) in which this capability is meaningful.\n *\n * It is required by the standard, but we make it optional since there is only\n * one context in our usage (i.e. the user's MetaMask instance).\n */\n readonly '@context'?: NonEmptyArray<string>;\n\n /**\n * The caveats of the permission.\n *\n * @see {@link Caveat} For more information.\n */\n readonly caveats: null | NonEmptyArray<CaveatConstraint>;\n\n /**\n * The creation date of the permission, in UNIX epoch time.\n */\n readonly date: number;\n\n /**\n * The GUID of the permission object.\n */\n readonly id: string;\n\n /**\n * The origin string of the subject that has the permission.\n */\n readonly invoker: OriginString;\n\n /**\n * A pointer to the resource that possession of the capability grants\n * access to, for example a JSON-RPC method or endowment.\n */\n readonly parentCapability: string;\n};\n\n/**\n * A `ZCAP-LD`-like permission object. A permission is associated with a\n * particular `invoker`, which is the holder of the permission. Possessing the\n * permission grants access to a particular restricted resource, identified by\n * the `parentCapability`. The use of the restricted resource may be further\n * restricted by any `caveats` associated with the permission.\n *\n * See the README for details.\n *\n * @template Name - The name of the permission that the target corresponds to.\n * @template AllowedCaveat - A union of the allowed {@link Caveat} types\n * for the permission.\n */\nexport type ValidPermission<\n Name extends TargetName,\n AllowedCaveat extends CaveatConstraint,\n> = PermissionConstraint & {\n /**\n * The caveats of the permission.\n *\n * @see {@link Caveat} For more information.\n */\n readonly caveats: AllowedCaveat extends never\n ? null\n : NonEmptyArray<AllowedCaveat> | null;\n\n /**\n * A pointer to the resource that possession of the capability grants\n * access to, for example a JSON-RPC method or endowment.\n */\n readonly parentCapability: Name;\n};\n\n/**\n * Internal utility for extracting the members types of an array. The type\n * evalutes to `never` if the specified type is the empty tuple or neither\n * an array nor a tuple.\n *\n * @template ArrayType - The array type whose members to extract.\n */\ntype ExtractArrayMembers<ArrayType> = ArrayType extends []\n ? never\n : ArrayType extends unknown[] | readonly unknown[]\n ? ArrayType[number]\n : never;\n\n/**\n * A utility type for extracting the allowed caveat types for a particular\n * permission from a permission specification type.\n *\n * @template PermissionSpecification - The permission specification type to\n * extract valid caveat types from.\n */\nexport type ExtractAllowedCaveatTypes<\n PermissionSpecification extends PermissionSpecificationConstraint,\n> = ExtractArrayMembers<PermissionSpecification['allowedCaveats']>;\n\n/**\n * The options object of {@link constructPermission}.\n *\n * @template TargetPermission - The {@link Permission} that will be constructed.\n */\nexport type PermissionOptions<TargetPermission extends PermissionConstraint> = {\n target: TargetPermission['parentCapability'];\n /**\n * The origin string of the subject that has the permission.\n */\n invoker: OriginString;\n\n /**\n * The caveats of the permission.\n * See {@link Caveat}.\n */\n caveats?: NonEmptyArray<CaveatConstraint>;\n};\n\n/**\n * The default permission factory function. Naively constructs a permission from\n * the inputs. Sets a default, random `id` if none is provided.\n *\n * @see {@link Permission} For more details.\n * @template TargetPermission- - The {@link Permission} that will be constructed.\n * @param options - The options for the permission.\n * @returns The new permission object.\n */\nexport function constructPermission<\n TargetPermission extends PermissionConstraint,\n>(options: PermissionOptions<TargetPermission>): TargetPermission {\n const { caveats = null, invoker, target } = options;\n\n return {\n id: nanoid(),\n parentCapability: target,\n invoker,\n caveats,\n date: new Date().getTime(),\n } as TargetPermission;\n}\n\n/**\n * Gets the caveat of the specified type belonging to the specified permission.\n *\n * @param permission - The permission whose caveat to retrieve.\n * @param caveatType - The type of the caveat to retrieve.\n * @returns The caveat, or undefined if no such caveat exists.\n */\nexport function findCaveat(\n permission: PermissionConstraint,\n caveatType: string,\n): CaveatConstraint | undefined {\n return permission.caveats?.find((caveat) => caveat.type === caveatType);\n}\n\n/**\n * A requested permission object. Just an object with any of the properties\n * of a {@link PermissionConstraint} object.\n */\ntype RequestedPermission = Partial<PermissionConstraint>;\n\n/**\n * A record of target names and their {@link RequestedPermission} objects.\n */\nexport type RequestedPermissions = Record<TargetName, RequestedPermission>;\n\n/**\n * The restricted method context object. Essentially a way to pass internal\n * arguments to restricted methods and caveat functions, most importantly the\n * requesting origin.\n */\ntype RestrictedMethodContext = Readonly<{\n origin: OriginString;\n [key: string]: unknown;\n}>;\n\nexport type RestrictedMethodParameters = Json[] | Record<string, Json>;\n\n/**\n * The arguments passed to a restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n */\nexport type RestrictedMethodOptions<\n Params extends RestrictedMethodParameters | null,\n> = {\n method: TargetName;\n params?: Params;\n context: RestrictedMethodContext;\n};\n\n/**\n * A synchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type SyncRestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> = (args: RestrictedMethodOptions<Params>) => Result;\n\n/**\n * An asynchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type AsyncRestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> = (args: RestrictedMethodOptions<Params>) => Promise<Result>;\n\n/**\n * A synchronous or asynchronous restricted method implementation.\n *\n * @template Params - The JSON-RPC parameters of the restricted method.\n * @template Result - The JSON-RPC result of the restricted method.\n */\nexport type RestrictedMethod<\n Params extends RestrictedMethodParameters,\n Result extends Json,\n> =\n | SyncRestrictedMethod<Params, Result>\n | AsyncRestrictedMethod<Params, Result>;\n\nexport type ValidRestrictedMethod<\n MethodImplementation extends RestrictedMethod<\n RestrictedMethodParameters,\n Json\n >,\n> = MethodImplementation extends (args: infer Options) => Json | Promise<Json>\n ? Options extends RestrictedMethodOptions<RestrictedMethodParameters>\n ? MethodImplementation\n : never\n : never;\n\n/**\n * {@link EndowmentGetter} parameter object.\n */\nexport type EndowmentGetterParams = {\n /**\n * The origin of the requesting subject.\n */\n origin: string;\n\n /**\n * Any additional data associated with the request.\n */\n requestData?: unknown;\n\n [key: string]: unknown;\n};\n\n/**\n * A synchronous or asynchronous function that gets the endowments for a\n * particular endowment permission. The getter receives the origin of the\n * requesting subject and, optionally, additional request metadata.\n */\nexport type EndowmentGetter<Endowments extends Json> = (\n options: EndowmentGetterParams,\n) => Endowments | Promise<Endowments>;\n\nexport type PermissionFactory<\n TargetPermission extends PermissionConstraint,\n RequestData extends Record<string, unknown>,\n> = (\n options: PermissionOptions<TargetPermission>,\n requestData?: RequestData,\n) => TargetPermission;\n\nexport type PermissionValidatorConstraint = (\n permission: PermissionConstraint,\n origin?: OriginString,\n target?: string,\n) => void;\n\n/**\n * The parameters passed to the side-effect function.\n */\nexport type SideEffectParams<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = {\n requestData: PermissionsRequest;\n messagingSystem: SideEffectMessenger<Actions, Events>;\n};\n\n/**\n * A function that will execute actions as a permission side-effect.\n */\nexport type SideEffectHandler<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = (params: SideEffectParams<Actions, Events>) => Promise<unknown>;\n\n/**\n * The permissions side effects.\n */\nexport type PermissionSideEffect<\n Actions extends ActionConstraint,\n Events extends EventConstraint,\n> = {\n /**\n * A method triggered when the permission is accepted by the user\n */\n onPermitted: SideEffectHandler<Actions, Events>;\n /**\n * A method triggered if a `onPermitted` method rejected.\n */\n onFailure?: SideEffectHandler<Actions, Events>;\n};\n\n/**\n * The different possible types of permissions.\n */\nexport enum PermissionType {\n /**\n * A restricted JSON-RPC method. A subject must have the requisite permission\n * to call a restricted JSON-RPC method.\n */\n RestrictedMethod = 'RestrictedMethod',\n\n /**\n * An \"endowment\" granted to subjects that possess the requisite permission,\n * such as a global environment variable exposing a restricted API, etc.\n */\n Endowment = 'Endowment',\n}\n\n/**\n * The base constraint for permission specification objects. Every\n * {@link Permission} supported by a {@link PermissionController} must have an\n * associated specification, which is the source of truth for all permission-\n * related types. A permission specification includes the list of permitted\n * caveats, and any factory and validation functions specified by the consumer.\n * A concrete permission specification may specify further fields as necessary.\n *\n * See the README for more details.\n */\ntype PermissionSpecificationBase<Type extends PermissionType> = {\n /**\n * The type of the specified permission.\n */\n permissionType: Type;\n\n /**\n * The name of the target resource of the permission.\n */\n targetName: string;\n\n /**\n * An array of the caveat types that may be added to instances of this\n * permission.\n */\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n\n /**\n * The factory function used to get permission objects. Permissions returned\n * by this function are presumed to valid, and they will not be passed to the\n * validator function associated with this specification (if any). In other\n * words, the factory function should validate the permissions it creates.\n *\n * If no factory is specified, the {@link Permission} constructor will be\n * used, and the validator function (if specified) will be called on newly\n * constructed permissions.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n factory?: PermissionFactory<any, Record<string, unknown>>;\n\n /**\n * The validator function used to validate permissions of the associated type\n * whenever they are mutated. The only way a permission can be legally mutated\n * is when its caveats are modified by the permission controller.\n *\n * The validator should throw an appropriate JSON-RPC error if validation fails.\n */\n validator?: PermissionValidatorConstraint;\n\n /**\n * The side-effect triggered by the {@link PermissionController} once the user approved it.\n * The side-effect can only be an action allowed to be called inside the {@link PermissionController}.\n *\n * If the side-effect action fails, the permission that triggered it is revoked.\n */\n sideEffect?: PermissionSideEffect<ActionConstraint, EventConstraint>;\n\n /**\n * The Permission may be available to only a subset of the subject types. If so, specify the subject types as an array.\n * If a subject with a type not in this array tries to request the permission, the call will fail.\n *\n * Leaving this as undefined uses default behaviour where the permission is available to request for all subject types.\n */\n subjectTypes?: readonly SubjectType[];\n};\n\n/**\n * The constraint for restricted method permission specification objects.\n * Permissions that correspond to JSON-RPC methods are specified using objects\n * that conform to this type.\n *\n * See the README for more details.\n */\nexport type RestrictedMethodSpecificationConstraint =\n PermissionSpecificationBase<PermissionType.RestrictedMethod> & {\n /**\n * The implementation of the restricted method that the permission\n * corresponds to.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n methodImplementation: RestrictedMethod<any, Json>;\n };\n\n/**\n * The constraint for endowment permission specification objects. Permissions\n * that endow callers with some restricted resource are specified using objects\n * that conform to this type.\n *\n * See the README for more details.\n */\nexport type EndowmentSpecificationConstraint =\n PermissionSpecificationBase<PermissionType.Endowment> & {\n /**\n * The {@link EndowmentGetter} function for the permission. This function\n * will be called by the {@link PermissionController} whenever the\n * permission is invoked, after which the host can apply the endowments to\n * the requesting subject in the intended manner.\n */\n endowmentGetter: EndowmentGetter<Json>;\n };\n\n/**\n * The constraint for permission specification objects. Every {@link Permission}\n * supported by a {@link PermissionController} must have an associated\n * specification, which is the source of truth for all permission-related types.\n * All specifications must adhere to the {@link PermissionSpecificationBase}\n * interface, but specifications may have different fields depending on the\n * {@link PermissionType}.\n *\n * See the README for more details.\n */\nexport type PermissionSpecificationConstraint =\n | EndowmentSpecificationConstraint\n | RestrictedMethodSpecificationConstraint;\n\n/**\n * Options for {@link PermissionSpecificationBuilder} functions.\n */\ntype PermissionSpecificationBuilderOptions<\n FactoryHooks extends Record<string, unknown>,\n MethodHooks extends Record<string, unknown>,\n ValidatorHooks extends Record<string, unknown>,\n> = {\n targetName?: string;\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n factoryHooks?: FactoryHooks;\n methodHooks?: MethodHooks;\n validatorHooks?: ValidatorHooks;\n};\n\n/**\n * A function that builds a permission specification. Modules that specify\n * permissions for external consumption should make this their primary /\n * default export so that host applications can use them to generate concrete\n * specifications tailored to their requirements.\n */\nexport type PermissionSpecificationBuilder<\n Type extends PermissionType,\n Options extends PermissionSpecificationBuilderOptions<\n Record<string, unknown>,\n Record<string, unknown>,\n Record<string, unknown>\n >,\n Specification extends PermissionSpecificationConstraint & {\n permissionType: Type;\n },\n> = (options: Options) => Specification;\n\n/**\n * A restricted method permission export object, containing the\n * {@link PermissionSpecificationBuilder} function and \"hook name\" objects.\n */\nexport type PermissionSpecificationBuilderExportConstraint = {\n targetName: string;\n specificationBuilder: PermissionSpecificationBuilder<\n PermissionType,\n PermissionSpecificationBuilderOptions<\n Record<string, unknown>,\n Record<string, unknown>,\n Record<string, unknown>\n >,\n PermissionSpecificationConstraint\n >;\n factoryHookNames?: Record<string, true>;\n methodHookNames?: Record<string, true>;\n validatorHookNames?: Record<string, true>;\n};\n\ntype ValidRestrictedMethodSpecification<\n Specification extends RestrictedMethodSpecificationConstraint,\n> = Specification['methodImplementation'] extends ValidRestrictedMethod<\n Specification['methodImplementation']\n>\n ? Specification\n : never;\n\n/**\n * Constraint for {@link PermissionSpecificationConstraint} objects that\n * evaluates to `never` if the specification contains any invalid fields.\n *\n * @template Specification - The permission specification to validate.\n */\nexport type ValidPermissionSpecification<\n Specification extends PermissionSpecificationConstraint,\n> = Specification['targetName'] extends TargetName\n ? Specification['permissionType'] extends PermissionType.Endowment\n ? Specification\n : Specification['permissionType'] extends PermissionType.RestrictedMethod\n ? ValidRestrictedMethodSpecification<\n Extract<Specification, RestrictedMethodSpecificationConstraint>\n >\n : never\n : never;\n\n/**\n * Checks that the specification has the expected permission type.\n *\n * @param specification - The specification to check.\n * @param expectedType - The expected permission type.\n * @template Specification - The specification to check.\n * @template Type - The expected permission type.\n * @returns Whether or not the specification is of the expected type.\n */\nexport function hasSpecificationType<\n Specification extends PermissionSpecificationConstraint,\n Type extends PermissionType,\n>(\n specification: Specification,\n expectedType: Type,\n): specification is Specification & {\n permissionType: Type;\n} {\n return specification.permissionType === expectedType;\n}\n\n/**\n * The specifications for all permissions supported by a particular\n * {@link PermissionController}.\n *\n * @template Specifications - The union of all {@link PermissionSpecificationConstraint} types.\n */\nexport type PermissionSpecificationMap<\n Specification extends PermissionSpecificationConstraint,\n> = {\n [Name in Specification['targetName']]: Specification extends {\n targetName: Name;\n }\n ? Specification\n : never;\n};\n\n/**\n * Extracts a specific {@link PermissionSpecificationConstraint} from a union of\n * permission specifications.\n *\n * @template Specification - The specification union type to extract from.\n * @template Name - The `targetName` of the specification to extract.\n */\nexport type ExtractPermissionSpecification<\n Specification extends PermissionSpecificationConstraint,\n Name extends Specification['targetName'],\n> = Specification extends {\n targetName: Name;\n}\n ? Specification\n : never;\n"]}
package/dist/errors.js DELETED
@@ -1,58 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
- var _chunkFYADAA2Gjs = require('./chunk-FYADAA2G.js');
29
- require('./chunk-Z2XKIXLS.js');
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
- exports.CaveatAlreadyExistsError = _chunkFYADAA2Gjs.CaveatAlreadyExistsError; exports.CaveatDoesNotExistError = _chunkFYADAA2Gjs.CaveatDoesNotExistError; exports.CaveatInvalidJsonError = _chunkFYADAA2Gjs.CaveatInvalidJsonError; exports.CaveatMergeTypeMismatchError = _chunkFYADAA2Gjs.CaveatMergeTypeMismatchError; exports.CaveatMergerDoesNotExistError = _chunkFYADAA2Gjs.CaveatMergerDoesNotExistError; exports.CaveatMissingValueError = _chunkFYADAA2Gjs.CaveatMissingValueError; exports.CaveatSpecificationMismatchError = _chunkFYADAA2Gjs.CaveatSpecificationMismatchError; exports.DuplicateCaveatError = _chunkFYADAA2Gjs.DuplicateCaveatError; exports.EndowmentPermissionDoesNotExistError = _chunkFYADAA2Gjs.EndowmentPermissionDoesNotExistError; exports.ForbiddenCaveatError = _chunkFYADAA2Gjs.ForbiddenCaveatError; exports.InvalidApprovedPermissionError = _chunkFYADAA2Gjs.InvalidApprovedPermissionError; exports.InvalidCaveatError = _chunkFYADAA2Gjs.InvalidCaveatError; exports.InvalidCaveatFieldsError = _chunkFYADAA2Gjs.InvalidCaveatFieldsError; exports.InvalidCaveatTypeError = _chunkFYADAA2Gjs.InvalidCaveatTypeError; exports.InvalidCaveatsPropertyError = _chunkFYADAA2Gjs.InvalidCaveatsPropertyError; exports.InvalidMergedPermissionsError = _chunkFYADAA2Gjs.InvalidMergedPermissionsError; exports.InvalidSubjectIdentifierError = _chunkFYADAA2Gjs.InvalidSubjectIdentifierError; exports.PermissionDoesNotExistError = _chunkFYADAA2Gjs.PermissionDoesNotExistError; exports.PermissionsRequestNotFoundError = _chunkFYADAA2Gjs.PermissionsRequestNotFoundError; exports.UnrecognizedCaveatTypeError = _chunkFYADAA2Gjs.UnrecognizedCaveatTypeError; exports.UnrecognizedSubjectError = _chunkFYADAA2Gjs.UnrecognizedSubjectError; exports.internalError = _chunkFYADAA2Gjs.internalError; exports.invalidParams = _chunkFYADAA2Gjs.invalidParams; exports.methodNotFound = _chunkFYADAA2Gjs.methodNotFound; exports.unauthorized = _chunkFYADAA2Gjs.unauthorized; exports.userRejectedRequest = _chunkFYADAA2Gjs.userRejectedRequest;
58
- //# sourceMappingURL=errors.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}