@metamask-previews/permission-log-controller 3.0.0-preview-cf09c0a → 3.0.0-preview-09a2ffd5

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 (44) hide show
  1. package/dist/PermissionLogController.js +8 -0
  2. package/dist/PermissionLogController.js.map +1 -0
  3. package/dist/PermissionLogController.mjs +6 -256
  4. package/dist/PermissionLogController.mjs.map +1 -1
  5. package/dist/chunk-6OHY6RYL.mjs +51 -0
  6. package/dist/chunk-6OHY6RYL.mjs.map +1 -0
  7. package/dist/chunk-F4V6DVN7.js +309 -0
  8. package/dist/chunk-F4V6DVN7.js.map +1 -0
  9. package/dist/chunk-IBGGF3GZ.mjs +309 -0
  10. package/dist/chunk-IBGGF3GZ.mjs.map +1 -0
  11. package/dist/chunk-MF2HNE3K.js +51 -0
  12. package/dist/chunk-MF2HNE3K.js.map +1 -0
  13. package/dist/enums.js +15 -0
  14. package/dist/enums.js.map +1 -0
  15. package/dist/enums.mjs +14 -23
  16. package/dist/enums.mjs.map +1 -1
  17. package/dist/index.js +8 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/index.mjs +7 -1
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/tsconfig.build.tsbuildinfo +1 -0
  22. package/dist/{PermissionLogController.d.mts → types/PermissionLogController.d.ts} +5 -5
  23. package/dist/types/PermissionLogController.d.ts.map +1 -0
  24. package/dist/{enums.d.cts → types/enums.d.ts} +1 -1
  25. package/dist/types/enums.d.ts.map +1 -0
  26. package/dist/types/index.d.ts +2 -0
  27. package/dist/types/index.d.ts.map +1 -0
  28. package/package.json +7 -12
  29. package/dist/PermissionLogController.cjs +0 -262
  30. package/dist/PermissionLogController.cjs.map +0 -1
  31. package/dist/PermissionLogController.d.cts +0 -78
  32. package/dist/PermissionLogController.d.cts.map +0 -1
  33. package/dist/PermissionLogController.d.mts.map +0 -1
  34. package/dist/enums.cjs +0 -27
  35. package/dist/enums.cjs.map +0 -1
  36. package/dist/enums.d.cts.map +0 -1
  37. package/dist/enums.d.mts +0 -14
  38. package/dist/enums.d.mts.map +0 -1
  39. package/dist/index.cjs +0 -18
  40. package/dist/index.cjs.map +0 -1
  41. package/dist/index.d.cts +0 -2
  42. package/dist/index.d.cts.map +0 -1
  43. package/dist/index.d.mts +0 -2
  44. package/dist/index.d.mts.map +0 -1
@@ -0,0 +1,8 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkF4V6DVN7js = require('./chunk-F4V6DVN7.js');
4
+ require('./chunk-MF2HNE3K.js');
5
+
6
+
7
+ exports.PermissionLogController = _chunkF4V6DVN7js.PermissionLogController;
8
+ //# sourceMappingURL=PermissionLogController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,258 +1,8 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _PermissionLogController_instances, _PermissionLogController_restrictedMethods, _PermissionLogController_getAccountToTimeMap, _PermissionLogController_logRequest, _PermissionLogController_logResponse, _PermissionLogController_logPermissionsHistory, _PermissionLogController_commitNewHistory, _PermissionLogController_getRequestedMethods, _PermissionLogController_getAccountsFromPermission;
13
- import { BaseController } from "@metamask/base-controller";
14
- import { hasProperty } from "@metamask/utils";
15
- import { LOG_IGNORE_METHODS, LOG_LIMIT, LOG_METHOD_TYPES, WALLET_PREFIX, CAVEAT_TYPES } from "./enums.mjs";
16
- const defaultState = {
17
- permissionHistory: {},
18
- permissionActivityLog: [],
19
- };
20
- const name = 'PermissionLogController';
21
- /**
22
- * Controller with middleware for logging requests and responses to restricted
23
- * and permissions-related methods.
24
- */
25
- export class PermissionLogController extends BaseController {
26
- constructor({ messenger, restrictedMethods, state, }) {
27
- super({
28
- messenger,
29
- name,
30
- metadata: {
31
- permissionHistory: {
32
- persist: true,
33
- anonymous: false,
34
- },
35
- permissionActivityLog: {
36
- persist: true,
37
- anonymous: false,
38
- },
39
- },
40
- state: { ...defaultState, ...state },
41
- });
42
- _PermissionLogController_instances.add(this);
43
- _PermissionLogController_restrictedMethods.set(this, void 0);
44
- __classPrivateFieldSet(this, _PermissionLogController_restrictedMethods, restrictedMethods, "f");
45
- }
46
- /**
47
- * Updates the exposed account history for the given origin.
48
- * Sets the 'last seen' time to Date.now() for the given accounts.
49
- * Does **not** update the 'lastApproved' time for the permission itself.
50
- * Returns if the accounts array is empty.
51
- *
52
- * @param origin - The origin that the accounts are exposed to.
53
- * @param accounts - The accounts.
54
- */
55
- updateAccountsHistory(origin, accounts) {
56
- if (accounts.length === 0) {
57
- return;
58
- }
59
- const newEntries = {
60
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
61
- // eslint-disable-next-line @typescript-eslint/naming-convention
62
- eth_accounts: {
63
- accounts: __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_getAccountToTimeMap).call(this, accounts, Date.now()),
64
- },
65
- };
66
- __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_commitNewHistory).call(this, origin, newEntries);
67
- }
68
- /**
69
- * Create a permissions log middleware. Records permissions activity and history:
70
- *
71
- * Activity: requests and responses for restricted and most wallet_ methods.
72
- *
73
- * History: for each origin, the last time a permission was granted, including
74
- * which accounts were exposed, if any.
75
- *
76
- * @returns The permissions log middleware.
77
- */
78
- createMiddleware() {
79
- return (req, res, next) => {
80
- const { origin, method } = req;
81
- const isInternal = method.startsWith(WALLET_PREFIX);
82
- const isEthRequestAccounts = method === 'eth_requestAccounts';
83
- // Determine if the method should be logged
84
- if ((!LOG_IGNORE_METHODS.includes(method) &&
85
- (isInternal || __classPrivateFieldGet(this, _PermissionLogController_restrictedMethods, "f").has(method))) ||
86
- isEthRequestAccounts) {
87
- const activityEntry = __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_logRequest).call(this, req, isInternal);
88
- const requestedMethods = __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_getRequestedMethods).call(this, req);
89
- // Call next with a return handler for capturing the response
90
- next((cb) => {
91
- const time = Date.now();
92
- __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_logResponse).call(this, activityEntry, res, time);
93
- if (requestedMethods && !res.error && res.result && origin) {
94
- __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_logPermissionsHistory).call(this, requestedMethods, origin, res.result, time, isEthRequestAccounts);
95
- }
96
- cb();
97
- });
98
- return;
99
- }
100
- next();
101
- };
102
- }
103
- }
104
- _PermissionLogController_restrictedMethods = new WeakMap(), _PermissionLogController_instances = new WeakSet(), _PermissionLogController_getAccountToTimeMap = function _PermissionLogController_getAccountToTimeMap(accounts, time) {
105
- return accounts.reduce((acc, account) => ({
106
- ...acc,
107
- [account]: time,
108
- }), {});
109
- }, _PermissionLogController_logRequest = function _PermissionLogController_logRequest(request, isInternal) {
110
- const activityEntry = {
111
- id: request.id,
112
- method: request.method,
113
- methodType: isInternal
114
- ? LOG_METHOD_TYPES.internal
115
- : LOG_METHOD_TYPES.restricted,
116
- origin: request.origin,
117
- requestTime: Date.now(),
118
- responseTime: null,
119
- success: null,
120
- };
121
- this.update((state) => {
122
- const newLogs = [...state.permissionActivityLog, activityEntry];
123
- state.permissionActivityLog =
124
- // remove oldest log if exceeding size limit
125
- newLogs.length > LOG_LIMIT ? newLogs.slice(1) : newLogs;
126
- });
127
- return activityEntry;
128
- }, _PermissionLogController_logResponse = function _PermissionLogController_logResponse(entry, response, time) {
129
- if (!entry || !response) {
130
- return;
131
- }
132
- // The JSON-RPC 2.0 specification defines "success" by the presence of
133
- // either the "result" or "error" property. The specification forbids
134
- // both properties from being present simultaneously, and our JSON-RPC
135
- // stack is spec-compliant at the time of writing.
136
- this.update((state) => {
137
- state.permissionActivityLog = state.permissionActivityLog.map((log) => {
138
- // Update the log entry that matches the given entry id
139
- if (log.id === entry.id) {
140
- return {
141
- ...log,
142
- success: hasProperty(response, 'result'),
143
- responseTime: time,
144
- };
145
- }
146
- return log;
147
- });
148
- });
149
- }, _PermissionLogController_logPermissionsHistory = function _PermissionLogController_logPermissionsHistory(requestedMethods, origin, result, time, isEthRequestAccounts) {
150
- let newEntries;
151
- if (isEthRequestAccounts) {
152
- // Type assertion: We are assuming that the response data contains
153
- // a set of accounts if the RPC method is "eth_requestAccounts".
154
- const accounts = result;
155
- newEntries = {
156
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
157
- // eslint-disable-next-line @typescript-eslint/naming-convention
158
- eth_accounts: {
159
- accounts: __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_getAccountToTimeMap).call(this, accounts, time),
160
- lastApproved: time,
161
- },
162
- };
163
- }
164
- else {
165
- // Records new "lastApproved" times for the granted permissions, if any.
166
- // Special handling for eth_accounts, in order to record the time the
167
- // accounts were last seen or approved by the origin.
168
- // Type assertion: We are assuming that the response data contains
169
- // a set of permissions if the RPC method is "eth_requestPermissions".
170
- const permissions = result;
171
- newEntries = permissions.reduce((acc, permission) => {
172
- const method = permission.parentCapability;
173
- if (!requestedMethods.includes(method)) {
174
- return acc;
175
- }
176
- if (method === 'eth_accounts') {
177
- const accounts = __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_getAccountsFromPermission).call(this, permission);
178
- return {
179
- ...acc,
180
- [method]: {
181
- lastApproved: time,
182
- accounts: __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_getAccountToTimeMap).call(this, accounts, time),
183
- },
184
- };
185
- }
186
- return {
187
- ...acc,
188
- [method]: {
189
- lastApproved: time,
190
- },
191
- };
192
- }, {});
193
- }
194
- if (Object.keys(newEntries).length > 0) {
195
- __classPrivateFieldGet(this, _PermissionLogController_instances, "m", _PermissionLogController_commitNewHistory).call(this, origin, newEntries);
196
- }
197
- }, _PermissionLogController_commitNewHistory = function _PermissionLogController_commitNewHistory(origin, newEntries) {
198
- const { permissionHistory } = this.state;
199
- // a simple merge updates most permissions
200
- const oldOriginHistory = permissionHistory[origin] ?? {};
201
- const newOriginHistory = {
202
- ...oldOriginHistory,
203
- ...newEntries,
204
- };
205
- // eth_accounts requires special handling, because of information
206
- // we store about the accounts
207
- const existingEthAccountsEntry = oldOriginHistory.eth_accounts;
208
- const newEthAccountsEntry = newEntries.eth_accounts;
209
- if (existingEthAccountsEntry && newEthAccountsEntry) {
210
- // we may intend to update just the accounts, not the permission
211
- // itself
212
- const lastApproved = newEthAccountsEntry.lastApproved ??
213
- existingEthAccountsEntry.lastApproved;
214
- // merge old and new eth_accounts history entries
215
- newOriginHistory.eth_accounts = {
216
- lastApproved,
217
- accounts: {
218
- ...existingEthAccountsEntry.accounts,
219
- ...newEthAccountsEntry.accounts,
220
- },
221
- };
222
- }
223
- this.update((state) => {
224
- state.permissionHistory = {
225
- ...permissionHistory,
226
- [origin]: newOriginHistory,
227
- };
228
- });
229
- }, _PermissionLogController_getRequestedMethods = function _PermissionLogController_getRequestedMethods(request) {
230
- const { method, params } = request;
231
- if (method === 'eth_requestAccounts') {
232
- return ['eth_accounts'];
233
- }
234
- else if (method === `${WALLET_PREFIX}requestPermissions` &&
235
- params &&
236
- Array.isArray(params) &&
237
- params[0] &&
238
- typeof params[0] === 'object' &&
239
- !Array.isArray(params[0])) {
240
- return Object.keys(params[0]);
241
- }
242
- return null;
243
- }, _PermissionLogController_getAccountsFromPermission = function _PermissionLogController_getAccountsFromPermission(permission) {
244
- if (permission.parentCapability !== 'eth_accounts' || !permission.caveats) {
245
- return [];
246
- }
247
- const accounts = new Set();
248
- for (const caveat of permission.caveats) {
249
- if (caveat.type === CAVEAT_TYPES.restrictReturnedAccounts &&
250
- Array.isArray(caveat.value)) {
251
- for (const value of caveat.value) {
252
- accounts.add(value);
253
- }
254
- }
255
- }
256
- return [...accounts];
1
+ import {
2
+ PermissionLogController
3
+ } from "./chunk-IBGGF3GZ.mjs";
4
+ import "./chunk-6OHY6RYL.mjs";
5
+ export {
6
+ PermissionLogController
257
7
  };
258
8
  //# sourceMappingURL=PermissionLogController.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"PermissionLogController.mjs","sourceRoot":"","sources":["../src/PermissionLogController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EAEf,kCAAkC;AAEnC,OAAO,EAKL,WAAW,EACZ,wBAAwB;AAEzB,OAAO,EACL,kBAAkB,EAClB,SAAS,EACT,gBAAgB,EAChB,aAAa,EACb,YAAY,EACb,oBAAgB;AA6DjB,MAAM,YAAY,GAAiC;IACjD,iBAAiB,EAAE,EAAE;IACrB,qBAAqB,EAAE,EAAE;CAC1B,CAAC;AAEF,MAAM,IAAI,GAAG,yBAAyB,CAAC;AAEvC;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,cAI5C;IAGC,YAAY,EACV,SAAS,EACT,iBAAiB,EACjB,KAAK,GAC0B;QAC/B,KAAK,CAAC;YACJ,SAAS;YACT,IAAI;YACJ,QAAQ,EAAE;gBACR,iBAAiB,EAAE;oBACjB,OAAO,EAAE,IAAI;oBACb,SAAS,EAAE,KAAK;iBACjB;gBACD,qBAAqB,EAAE;oBACrB,OAAO,EAAE,IAAI;oBACb,SAAS,EAAE,KAAK;iBACjB;aACF;YACD,KAAK,EAAE,E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QACzE,OAAO,EAAE,CAAC;KACX;IAED,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;IACnC,KAAK,MAAM,MAAM,IAAI,UAAU,CAAC,OAAO,EAAE;QACvC,IACE,MAAM,CAAC,IAAI,KAAK,YAAY,CAAC,wBAAwB;YACrD,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAC3B;YACA,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,KAAK,EAAE;gBAChC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;aACrB;SACF;KACF;IAED,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import {\n BaseController,\n type RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport {\n type Json,\n type JsonRpcRequest,\n type JsonRpcParams,\n type PendingJsonRpcResponse,\n hasProperty,\n} from '@metamask/utils';\n\nimport {\n LOG_IGNORE_METHODS,\n LOG_LIMIT,\n LOG_METHOD_TYPES,\n WALLET_PREFIX,\n CAVEAT_TYPES,\n} from './enums';\n\nexport type JsonRpcRequestWithOrigin<\n Params extends JsonRpcParams = JsonRpcParams,\n> = JsonRpcRequest<Params> & {\n origin?: string;\n};\n\nexport type Caveat = {\n type: string;\n value: string[];\n};\n\nexport type Permission = {\n parentCapability: string;\n caveats?: Caveat[];\n};\n\nexport type PermissionActivityLog = {\n id: string | number | null;\n method: string;\n methodType: LOG_METHOD_TYPES;\n origin?: string;\n requestTime: number;\n responseTime: number | null;\n success: boolean | null;\n};\n\nexport type PermissionLog = {\n accounts?: Record<string, number>;\n lastApproved?: number;\n};\nexport type PermissionEntry = Record<string, PermissionLog>;\n\nexport type PermissionHistory = Record<string, PermissionEntry>;\n\n/**\n *\n * Permission log controller state\n * @property permissionHistory - permission history\n * @property permissionActivityLog - permission activity logs\n */\nexport type PermissionLogControllerState = {\n permissionHistory: PermissionHistory;\n permissionActivityLog: PermissionActivityLog[];\n};\n\nexport type PermissionLogControllerOptions = {\n restrictedMethods: Set<string>;\n state?: Partial<PermissionLogControllerState>;\n messenger: PermissionLogControllerMessenger;\n};\n\nexport type PermissionLogControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n never,\n never,\n never,\n never\n>;\n\nconst defaultState: PermissionLogControllerState = {\n permissionHistory: {},\n permissionActivityLog: [],\n};\n\nconst name = 'PermissionLogController';\n\n/**\n * Controller with middleware for logging requests and responses to restricted\n * and permissions-related methods.\n */\nexport class PermissionLogController extends BaseController<\n typeof name,\n PermissionLogControllerState,\n PermissionLogControllerMessenger\n> {\n #restrictedMethods: Set<string>;\n\n constructor({\n messenger,\n restrictedMethods,\n state,\n }: PermissionLogControllerOptions) {\n super({\n messenger,\n name,\n metadata: {\n permissionHistory: {\n persist: true,\n anonymous: false,\n },\n permissionActivityLog: {\n persist: true,\n anonymous: false,\n },\n },\n state: { ...defaultState, ...state },\n });\n this.#restrictedMethods = restrictedMethods;\n }\n\n /**\n * Updates the exposed account history for the given origin.\n * Sets the 'last seen' time to Date.now() for the given accounts.\n * Does **not** update the 'lastApproved' time for the permission itself.\n * Returns if the accounts array is empty.\n *\n * @param origin - The origin that the accounts are exposed to.\n * @param accounts - The accounts.\n */\n updateAccountsHistory(origin: string, accounts: string[]) {\n if (accounts.length === 0) {\n return;\n }\n const newEntries = {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n eth_accounts: {\n accounts: this.#getAccountToTimeMap(accounts, Date.now()),\n },\n };\n this.#commitNewHistory(origin, newEntries);\n }\n\n /**\n * Create a permissions log middleware. Records permissions activity and history:\n *\n * Activity: requests and responses for restricted and most wallet_ methods.\n *\n * History: for each origin, the last time a permission was granted, including\n * which accounts were exposed, if any.\n *\n * @returns The permissions log middleware.\n */\n createMiddleware(): JsonRpcMiddleware<JsonRpcParams, Json> {\n return (req: JsonRpcRequestWithOrigin, res, next) => {\n const { origin, method } = req;\n const isInternal = method.startsWith(WALLET_PREFIX);\n const isEthRequestAccounts = method === 'eth_requestAccounts';\n\n // Determine if the method should be logged\n if (\n (!LOG_IGNORE_METHODS.includes(method) &&\n (isInternal || this.#restrictedMethods.has(method))) ||\n isEthRequestAccounts\n ) {\n const activityEntry = this.#logRequest(req, isInternal);\n\n const requestedMethods = this.#getRequestedMethods(req);\n\n // Call next with a return handler for capturing the response\n next((cb) => {\n const time = Date.now();\n this.#logResponse(activityEntry, res, time);\n\n if (requestedMethods && !res.error && res.result && origin) {\n this.#logPermissionsHistory(\n requestedMethods,\n origin,\n res.result,\n time,\n isEthRequestAccounts,\n );\n }\n cb();\n });\n return;\n }\n\n next();\n };\n }\n\n /**\n * Get a map from account addresses to the given time.\n *\n * @param accounts - An array of addresses.\n * @param time - A time, e.g. Date.now().\n * @returns A string:number map of addresses to time.\n */\n #getAccountToTimeMap(\n accounts: string[],\n time: number,\n ): Record<string, number> {\n return accounts.reduce(\n (acc, account) => ({\n ...acc,\n [account]: time,\n }),\n {},\n );\n }\n\n /**\n * Creates and commits an activity log entry, without response data.\n *\n * @param request - The request object.\n * @param isInternal - Whether the request is internal.\n * @returns new added activity entry\n */\n #logRequest(\n request: JsonRpcRequestWithOrigin,\n isInternal: boolean,\n ): PermissionActivityLog {\n const activityEntry: PermissionActivityLog = {\n id: request.id,\n method: request.method,\n methodType: isInternal\n ? LOG_METHOD_TYPES.internal\n : LOG_METHOD_TYPES.restricted,\n origin: request.origin,\n requestTime: Date.now(),\n responseTime: null,\n success: null,\n };\n this.update((state) => {\n const newLogs = [...state.permissionActivityLog, activityEntry];\n state.permissionActivityLog =\n // remove oldest log if exceeding size limit\n newLogs.length > LOG_LIMIT ? newLogs.slice(1) : newLogs;\n });\n return activityEntry;\n }\n\n /**\n * Adds response data to an existing activity log entry.\n * Entry assumed already committed (i.e., in the log).\n *\n * @param entry - The entry to add a response to.\n * @param response - The response object.\n * @param time - Output from Date.now()\n */\n #logResponse(\n entry: PermissionActivityLog,\n response: PendingJsonRpcResponse<Json>,\n time: number,\n ) {\n if (!entry || !response) {\n return;\n }\n\n // The JSON-RPC 2.0 specification defines \"success\" by the presence of\n // either the \"result\" or \"error\" property. The specification forbids\n // both properties from being present simultaneously, and our JSON-RPC\n // stack is spec-compliant at the time of writing.\n this.update((state) => {\n state.permissionActivityLog = state.permissionActivityLog.map((log) => {\n // Update the log entry that matches the given entry id\n if (log.id === entry.id) {\n return {\n ...log,\n success: hasProperty(response, 'result'),\n responseTime: time,\n };\n }\n return log;\n });\n });\n }\n\n /**\n * Create new permissions history log entries, if any, and commit them.\n *\n * @param requestedMethods - The method names corresponding to the requested permissions.\n * @param origin - The origin of the permissions request.\n * @param result - The permissions request response.result.\n * @param time - The time of the request, i.e. Date.now().\n * @param isEthRequestAccounts - Whether the permissions request was 'eth_requestAccounts'.\n */\n #logPermissionsHistory(\n requestedMethods: string[],\n origin: string,\n result: Json,\n time: number,\n isEthRequestAccounts: boolean,\n ) {\n let newEntries: PermissionEntry;\n\n if (isEthRequestAccounts) {\n // Type assertion: We are assuming that the response data contains\n // a set of accounts if the RPC method is \"eth_requestAccounts\".\n const accounts = result as string[];\n newEntries = {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n eth_accounts: {\n accounts: this.#getAccountToTimeMap(accounts, time),\n lastApproved: time,\n },\n };\n } else {\n // Records new \"lastApproved\" times for the granted permissions, if any.\n // Special handling for eth_accounts, in order to record the time the\n // accounts were last seen or approved by the origin.\n // Type assertion: We are assuming that the response data contains\n // a set of permissions if the RPC method is \"eth_requestPermissions\".\n const permissions = result as Permission[];\n newEntries = permissions.reduce((acc: PermissionEntry, permission) => {\n const method = permission.parentCapability;\n\n if (!requestedMethods.includes(method)) {\n return acc;\n }\n\n if (method === 'eth_accounts') {\n const accounts = this.#getAccountsFromPermission(permission);\n return {\n ...acc,\n [method]: {\n lastApproved: time,\n accounts: this.#getAccountToTimeMap(accounts, time),\n },\n };\n }\n\n return {\n ...acc,\n [method]: {\n lastApproved: time,\n },\n };\n }, {});\n }\n\n if (Object.keys(newEntries).length > 0) {\n this.#commitNewHistory(origin, newEntries);\n }\n }\n\n /**\n * Commit new entries to the permissions history log.\n * Merges the history for the given origin, overwriting existing entries\n * with the same key (permission name).\n *\n * @param origin - The requesting origin.\n * @param newEntries - The new entries to commit.\n */\n #commitNewHistory(origin: string, newEntries: PermissionEntry) {\n const { permissionHistory } = this.state;\n\n // a simple merge updates most permissions\n const oldOriginHistory = permissionHistory[origin] ?? {};\n const newOriginHistory = {\n ...oldOriginHistory,\n ...newEntries,\n };\n\n // eth_accounts requires special handling, because of information\n // we store about the accounts\n const existingEthAccountsEntry = oldOriginHistory.eth_accounts;\n const newEthAccountsEntry = newEntries.eth_accounts;\n\n if (existingEthAccountsEntry && newEthAccountsEntry) {\n // we may intend to update just the accounts, not the permission\n // itself\n const lastApproved =\n newEthAccountsEntry.lastApproved ??\n existingEthAccountsEntry.lastApproved;\n\n // merge old and new eth_accounts history entries\n newOriginHistory.eth_accounts = {\n lastApproved,\n accounts: {\n ...existingEthAccountsEntry.accounts,\n ...newEthAccountsEntry.accounts,\n },\n };\n }\n\n this.update((state) => {\n state.permissionHistory = {\n ...permissionHistory,\n [origin]: newOriginHistory,\n };\n });\n }\n\n /**\n * Get all requested methods from a permissions request.\n *\n * @param request - The request object.\n * @returns The names of the requested permissions.\n */\n #getRequestedMethods(request: JsonRpcRequestWithOrigin): string[] | null {\n const { method, params } = request;\n if (method === 'eth_requestAccounts') {\n return ['eth_accounts'];\n } else if (\n method === `${WALLET_PREFIX}requestPermissions` &&\n params &&\n Array.isArray(params) &&\n params[0] &&\n typeof params[0] === 'object' &&\n !Array.isArray(params[0])\n ) {\n return Object.keys(params[0]);\n }\n return null;\n }\n\n /**\n * Get the permitted accounts from an eth_accounts permissions object.\n * Returns an empty array if the permission is not eth_accounts.\n *\n * @param permission - The permissions object.\n * @param permission.parentCapability - The permissions parentCapability.\n * @param permission.caveats - The permissions caveats.\n * @returns The permitted accounts.\n */\n #getAccountsFromPermission(permission: Permission): string[] {\n if (permission.parentCapability !== 'eth_accounts' || !permission.caveats) {\n return [];\n }\n\n const accounts = new Set<string>();\n for (const caveat of permission.caveats) {\n if (\n caveat.type === CAVEAT_TYPES.restrictReturnedAccounts &&\n Array.isArray(caveat.value)\n ) {\n for (const value of caveat.value) {\n accounts.add(value);\n }\n }\n }\n\n return [...accounts];\n }\n}\n"]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,51 @@
1
+ var __accessCheck = (obj, member, msg) => {
2
+ if (!member.has(obj))
3
+ throw TypeError("Cannot " + msg);
4
+ };
5
+ var __privateGet = (obj, member, getter) => {
6
+ __accessCheck(obj, member, "read from private field");
7
+ return getter ? getter.call(obj) : member.get(obj);
8
+ };
9
+ var __privateAdd = (obj, member, value) => {
10
+ if (member.has(obj))
11
+ throw TypeError("Cannot add the same private member more than once");
12
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
+ };
14
+ var __privateSet = (obj, member, value, setter) => {
15
+ __accessCheck(obj, member, "write to private field");
16
+ setter ? setter.call(obj, value) : member.set(obj, value);
17
+ return value;
18
+ };
19
+ var __privateMethod = (obj, member, method) => {
20
+ __accessCheck(obj, member, "access private method");
21
+ return method;
22
+ };
23
+
24
+ // src/enums.ts
25
+ var WALLET_PREFIX = "wallet_";
26
+ var CAVEAT_TYPES = Object.freeze({
27
+ restrictReturnedAccounts: "restrictReturnedAccounts"
28
+ });
29
+ var LOG_IGNORE_METHODS = [
30
+ "wallet_registerOnboarding",
31
+ "wallet_watchAsset"
32
+ ];
33
+ var LOG_METHOD_TYPES = /* @__PURE__ */ ((LOG_METHOD_TYPES2) => {
34
+ LOG_METHOD_TYPES2["restricted"] = "restricted";
35
+ LOG_METHOD_TYPES2["internal"] = "internal";
36
+ return LOG_METHOD_TYPES2;
37
+ })(LOG_METHOD_TYPES || {});
38
+ var LOG_LIMIT = 100;
39
+
40
+ export {
41
+ __privateGet,
42
+ __privateAdd,
43
+ __privateSet,
44
+ __privateMethod,
45
+ WALLET_PREFIX,
46
+ CAVEAT_TYPES,
47
+ LOG_IGNORE_METHODS,
48
+ LOG_METHOD_TYPES,
49
+ LOG_LIMIT
50
+ };
51
+ //# sourceMappingURL=chunk-6OHY6RYL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/enums.ts"],"sourcesContent":["export const WALLET_PREFIX = 'wallet_';\n\nexport const CAVEAT_TYPES = Object.freeze({\n restrictReturnedAccounts: 'restrictReturnedAccounts' as const,\n});\n\nexport const LOG_IGNORE_METHODS = [\n 'wallet_registerOnboarding',\n 'wallet_watchAsset',\n];\n\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport enum LOG_METHOD_TYPES {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n restricted = 'restricted',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n internal = 'internal',\n}\n\n/**\n * The permission activity log size limit.\n */\nexport const LOG_LIMIT = 100;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAO,IAAM,gBAAgB;AAEtB,IAAM,eAAe,OAAO,OAAO;AAAA,EACxC,0BAA0B;AAC5B,CAAC;AAEM,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AACF;AAIO,IAAK,mBAAL,kBAAKA,sBAAL;AAGL,EAAAA,kBAAA,gBAAa;AAGb,EAAAA,kBAAA,cAAW;AAND,SAAAA;AAAA,GAAA;AAYL,IAAM,YAAY;","names":["LOG_METHOD_TYPES"]}