Skip to content

Commit 5e77e55

Browse files
feat(telemetry): add external RPC last-activity signals to sampled state writes (#47493)
## **Description** Stacked on [#47490](#47490) (`feat/telemetry-ms-since-last-ui-interaction`). Sampled State Persist traces already carry the activity snapshot (startup phase, UI counts, notification state, and elapsed time since the last UI event). This adds the last-activity side of that picture for external RPC callers, so an idle-looking write can be read against what callers outside the wallet were doing. Four signals are recorded by a middleware pushed on the EIP-1193 and CAIP provider engines, each throttled to once per second and restored from `storage.session` across service-worker restarts: - `msSinceLastDappRpc` (`state.write.ms_since_dapp_rpc`) for website connections - `msSinceLastConnectedDappRpc` (`state.write.ms_since_connected_dapp_rpc`) for website connections that already hold the CAIP-25 account permission - `msSinceLastSnapRpc` (`state.write.ms_since_snap_rpc`) for Snaps - `msSinceLastExternalExtensionRpc` (`state.write.ms_since_external_extension_rpc`) for other extensions Content scripts inject into every page, so the broad dapp signal also fires for unpermissioned sites that merely probe `window.ethereum`. The connected signal is recorded only when the requesting origin already has account access. That permission is checked on each request, so a connection granted mid-session starts counting from its next call. A failed permission lookup never drops the request. Snaps and other extensions never update the connected signal. No origins or method names are collected. ## **Changelog** CHANGELOG entry: null ## **Related issues** Fixes: ## **Manual testing steps** 1. Reproduce manual testing steps detailed in this PR: #46286 2. Open the [test dapp](https://metamask.github.io/test-dapp/) and connect MetaMask to it 3. Confirm `msSinceLastConnectedDappRpc`, `msSinceLastDappRpc`, and `msSinceLastSnapRpc` properties are now added to `state.write` metdata of [State Persist](https://metamask.sentry.io/explore/traces/?project=273496&query=transaction%3A%22State%20Persist%22&statsPeriod=30d) traces in Sentry. <img width="711" height="604" alt="Screenshot 2026-11-03 at 15 41 56" src="https://github.com/user-attachments/assets/d920afd4-8196-4f4f-bd00-87acdbdbc08e" /> <!-- ## **Screenshots/Recordings** ### **Before** ### **After** --> ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I've included tests if applicable - [x] I've documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [x] I've applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **Pre-merge reviewer checklist** - [ ] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [ ] I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots. Made with [Cursor](https://cursor.com) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Changes add side-effect-free telemetry on the RPC pipeline (timestamps only, no origins/methods) with explicit safeguards so permission lookup failures cannot drop requests. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 487920d. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 8b4d37e commit 5e77e55

7 files changed

Lines changed: 537 additions & 0 deletions
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import { SubjectType } from '@metamask/permission-controller';
2+
import { JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils';
3+
import {
4+
recordConnectedDappRpc,
5+
recordDappRpc,
6+
recordExternalExtensionRpc,
7+
recordSnapRpc,
8+
} from '../../../shared/lib/telemetry/last-activity';
9+
import createExternalRpcActivityMiddleware from './createExternalRpcActivityMiddleware';
10+
11+
jest.mock('../../../shared/lib/telemetry/last-activity', () => ({
12+
recordConnectedDappRpc: jest.fn(),
13+
recordDappRpc: jest.fn(),
14+
recordExternalExtensionRpc: jest.fn(),
15+
recordSnapRpc: jest.fn(),
16+
}));
17+
18+
const request: JsonRpcRequest = {
19+
id: 1,
20+
jsonrpc: '2.0',
21+
method: 'eth_chainId',
22+
};
23+
24+
const response: PendingJsonRpcResponse<null> = {
25+
id: 1,
26+
jsonrpc: '2.0',
27+
};
28+
29+
describe('createExternalRpcActivityMiddleware', () => {
30+
beforeEach(() => {
31+
jest.clearAllMocks();
32+
});
33+
34+
it('records a website request and calls next', () => {
35+
const next = jest.fn();
36+
37+
createExternalRpcActivityMiddleware(SubjectType.Website)(
38+
request,
39+
response,
40+
next,
41+
);
42+
43+
expect(recordDappRpc).toHaveBeenCalledTimes(1);
44+
expect(recordConnectedDappRpc).not.toHaveBeenCalled();
45+
expect(recordSnapRpc).not.toHaveBeenCalled();
46+
expect(recordExternalExtensionRpc).not.toHaveBeenCalled();
47+
expect(next).toHaveBeenCalledTimes(1);
48+
});
49+
50+
it('records a connected website request separately', () => {
51+
const next = jest.fn();
52+
const isConnected = jest.fn(() => true);
53+
54+
createExternalRpcActivityMiddleware(SubjectType.Website, { isConnected })(
55+
request,
56+
response,
57+
next,
58+
);
59+
60+
expect(recordDappRpc).toHaveBeenCalledTimes(1);
61+
expect(recordConnectedDappRpc).toHaveBeenCalledTimes(1);
62+
expect(isConnected).toHaveBeenCalledTimes(1);
63+
expect(next).toHaveBeenCalledTimes(1);
64+
});
65+
66+
it('does not record a connected website request when the origin has no account access', () => {
67+
const next = jest.fn();
68+
69+
createExternalRpcActivityMiddleware(SubjectType.Website, {
70+
isConnected: () => false,
71+
})(request, response, next);
72+
73+
expect(recordDappRpc).toHaveBeenCalledTimes(1);
74+
expect(recordConnectedDappRpc).not.toHaveBeenCalled();
75+
expect(next).toHaveBeenCalledTimes(1);
76+
});
77+
78+
it('still forwards the request when the connection check throws', () => {
79+
const next = jest.fn();
80+
81+
createExternalRpcActivityMiddleware(SubjectType.Website, {
82+
isConnected: () => {
83+
throw new Error('permission lookup failed');
84+
},
85+
})(request, response, next);
86+
87+
expect(recordDappRpc).toHaveBeenCalledTimes(1);
88+
expect(recordConnectedDappRpc).not.toHaveBeenCalled();
89+
expect(next).toHaveBeenCalledTimes(1);
90+
});
91+
92+
it('records a Snap request and calls next', () => {
93+
const next = jest.fn();
94+
95+
createExternalRpcActivityMiddleware(SubjectType.Snap)(
96+
request,
97+
response,
98+
next,
99+
);
100+
101+
expect(recordSnapRpc).toHaveBeenCalledTimes(1);
102+
expect(recordDappRpc).not.toHaveBeenCalled();
103+
expect(recordConnectedDappRpc).not.toHaveBeenCalled();
104+
expect(recordExternalExtensionRpc).not.toHaveBeenCalled();
105+
expect(next).toHaveBeenCalledTimes(1);
106+
});
107+
108+
it('records an external extension request and calls next', () => {
109+
const next = jest.fn();
110+
111+
createExternalRpcActivityMiddleware(SubjectType.Extension)(
112+
request,
113+
response,
114+
next,
115+
);
116+
117+
expect(recordExternalExtensionRpc).toHaveBeenCalledTimes(1);
118+
expect(recordDappRpc).not.toHaveBeenCalled();
119+
expect(recordConnectedDappRpc).not.toHaveBeenCalled();
120+
expect(recordSnapRpc).not.toHaveBeenCalled();
121+
expect(next).toHaveBeenCalledTimes(1);
122+
});
123+
124+
it('ignores an internal subject and still calls next', () => {
125+
const next = jest.fn();
126+
127+
createExternalRpcActivityMiddleware(SubjectType.Internal)(
128+
request,
129+
response,
130+
next,
131+
);
132+
133+
expect(recordDappRpc).not.toHaveBeenCalled();
134+
expect(recordConnectedDappRpc).not.toHaveBeenCalled();
135+
expect(recordSnapRpc).not.toHaveBeenCalled();
136+
expect(recordExternalExtensionRpc).not.toHaveBeenCalled();
137+
expect(next).toHaveBeenCalledTimes(1);
138+
});
139+
});
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { SubjectType } from '@metamask/permission-controller';
2+
import { Json, JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils';
3+
import {
4+
recordConnectedDappRpc,
5+
recordDappRpc,
6+
recordExternalExtensionRpc,
7+
recordSnapRpc,
8+
} from '../../../shared/lib/telemetry/last-activity';
9+
10+
const recordBySubjectType: Partial<Record<SubjectType, () => void>> = {
11+
[SubjectType.Website]: recordDappRpc,
12+
[SubjectType.Snap]: recordSnapRpc,
13+
[SubjectType.Extension]: recordExternalExtensionRpc,
14+
};
15+
16+
export type ExternalRpcActivityOptions = {
17+
/**
18+
* Whether this website origin already has account access.
19+
* Checked on each request so a connection granted mid-session starts counting.
20+
* Only consulted for {@link SubjectType.Website}.
21+
*/
22+
isConnected?: () => boolean;
23+
};
24+
25+
/**
26+
* Returns a middleware that records a JSON-RPC request for state-write
27+
* telemetry. The recorder depends on the connection's subject type.
28+
* `SubjectType.Internal` is ignored.
29+
*
30+
* Website requests also update the connected-dapp signal when `isConnected`
31+
* returns true.
32+
*
33+
* @param subjectType - The type of the sender subject.
34+
* @param options - Optional connection context.
35+
* @param options.isConnected - Whether the website origin already has account
36+
* access.
37+
* @returns The middleware function.
38+
*/
39+
export default function createExternalRpcActivityMiddleware(
40+
subjectType: SubjectType,
41+
{ isConnected }: ExternalRpcActivityOptions = {},
42+
) {
43+
const record = recordBySubjectType[subjectType];
44+
return function externalRpcActivityMiddleware(
45+
_req: JsonRpcRequest,
46+
_res: PendingJsonRpcResponse<Json>,
47+
next: () => void,
48+
) {
49+
record?.();
50+
if (subjectType === SubjectType.Website && isConnected) {
51+
try {
52+
if (isConnected()) {
53+
recordConnectedDappRpc();
54+
}
55+
} catch {
56+
// A permission lookup failure must not drop the request.
57+
}
58+
}
59+
next();
60+
};
61+
}

‎app/scripts/metamask-controller.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ import createMainFrameOriginMiddleware from './lib/createMainFrameOriginMiddlewa
222222
import createTabIdMiddleware from './lib/createTabIdMiddleware';
223223
import createFrameIdMiddleware from './lib/createFrameIdMiddleware';
224224
import createOnboardingMiddleware from './lib/createOnboardingMiddleware';
225+
import createExternalRpcActivityMiddleware from './lib/createExternalRpcActivityMiddleware';
225226
import { isStreamWritable, setupMultiplex } from './lib/stream-utils';
226227
import {
227228
createEventBuilder,
@@ -4274,6 +4275,17 @@ export default class MetamaskController extends EventEmitter {
42744275
}
42754276

42764277
engine.push(createLoggerMiddleware({ origin }));
4278+
if (subjectType !== SubjectType.Internal) {
4279+
engine.push(
4280+
createExternalRpcActivityMiddleware(subjectType, {
4281+
isConnected: () =>
4282+
this.permissionController.hasPermission(
4283+
origin,
4284+
Caip25EndowmentPermissionName,
4285+
),
4286+
}),
4287+
);
4288+
}
42774289
engine.push(this.permissionLogController.createMiddleware());
42784290

42794291
engine.push(createTracingMiddleware());
@@ -4708,6 +4720,17 @@ export default class MetamaskController extends EventEmitter {
47084720
}
47094721

47104722
engine.push(createLoggerMiddleware({ origin }));
4723+
if (subjectType !== SubjectType.Internal) {
4724+
engine.push(
4725+
createExternalRpcActivityMiddleware(subjectType, {
4726+
isConnected: () =>
4727+
this.permissionController.hasPermission(
4728+
origin,
4729+
Caip25EndowmentPermissionName,
4730+
),
4731+
}),
4732+
);
4733+
}
47114734

47124735
engine.push((req, _res, next, end) => {
47134736
const isSnap = isSnapId(origin);

0 commit comments

Comments
 (0)