From d75e3ac4be0ea3bf0e5a5133e0882b2c1288f08d Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Wed, 18 Nov 2026 13:43:47 +0000 Subject: [PATCH 1/3] feat: add a session event buffer with one cursor and mm events mark Adds one buffer per browser session for console and network records (filled by mm logs and mm network sources in follow-ups). Records share one monotonic seq, so a single 'mm events mark' bookmarks both kinds. Reads are paged with cursor/since/limit and report hasMore, gap (records after the cursor were dropped) and a summary whose startedAt changes on relaunch. Adds URL/text redaction helpers applied before a record enters the buffer. The buffer starts with the session at launch; 'mm events' is browser only and read-only. --- CHANGELOG.md | 1 + README.md | 3 + SKILL.md | 16 +- src/cli/mm.test.ts | 51 ++++ src/cli/mm.ts | 47 ++++ src/events/event-buffer.test.ts | 264 ++++++++++++++++++ src/events/event-buffer.ts | 216 +++++++++++++++ src/events/redact.test.ts | 374 ++++++++++++++++++++++++++ src/events/redact.ts | 430 ++++++++++++++++++++++++++++++ src/events/session-events.test.ts | 127 +++++++++ src/events/session-events.ts | 122 +++++++++ src/tools/events.test.ts | 97 +++++++ src/tools/events.ts | 44 +++ src/tools/launch.test.ts | 75 ++++++ src/tools/launch.ts | 41 +++ src/tools/mock-network.ts | 2 +- src/tools/platform-gating.test.ts | 1 + src/tools/registry.test.ts | 8 +- src/tools/registry.ts | 7 +- src/tools/types/events.ts | 60 +++++ src/tools/types/index.ts | 1 + src/tools/types/tool-inputs.ts | 5 + src/tools/types/tool-outputs.ts | 14 + src/validation/schemas.test.ts | 22 ++ src/validation/schemas.ts | 26 ++ 25 files changed, 2050 insertions(+), 4 deletions(-) create mode 100644 src/events/event-buffer.test.ts create mode 100644 src/events/event-buffer.ts create mode 100644 src/events/redact.test.ts create mode 100644 src/events/redact.ts create mode 100644 src/events/session-events.test.ts create mode 100644 src/events/session-events.ts create mode 100644 src/tools/events.test.ts create mode 100644 src/tools/events.ts create mode 100644 src/tools/types/events.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index af58a1b8..d152d090 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- feat: record console and network events in a per-session buffer with one shared cursor, so `mm events mark` bookmarks both kinds and reads report `hasMore`, `gap` and a page summary ([#109](https://github.com/MetaMask/client-mcp-core/pull/109)) - feat: deliver console and network CDP events from every browser page and the Extension service worker to event subscribers, re-attaching after page, session and MV3 worker restarts ([#107](https://github.com/MetaMask/client-mcp-core/pull/107)) - feat: `mm` sees and acts inside iframes on the browser, including cross-origin ones such as the candlestick chart. A page snapshot (`describe_screen`, `accessibility_snapshot` without `rootSelector`, observations) lists the content of up to 5 visible iframes after the page, with refs namespaced by frame (`f1e1`, `f2e1`, ...) and a `path` ending in `iframe:`; these refs act inside their iframe. Each iframe element also gets a ref, usable as `frame`. `describe_screen`, `click`, `type`, `hover`, `wait_for`, `get_text`, `inspect` and `screenshot` take `frame` (`--frame <iframe>`) to work inside one iframe, the way Playwright's `frameLocator` does. `mm screenshot` adds `--selector` ([#99](https://github.com/MetaMask/client-mcp-core/pull/99)) diff --git a/README.md b/README.md index 82356077..c60d3fff 100644 --- a/README.md +++ b/README.md @@ -435,6 +435,7 @@ The daemon routes `POST /tool/:name` requests through the registry, applies Zod | `run_steps` | Executes a batch of tool invocations sequentially. Supports `stopOnError` to halt on first failure, a top-level `observe` level for the single observation collected after the batch (default `diff`; without one, the last executed step's `observe` is used), and `batchTimeoutMs` (1 000–30 000 ms) to set an overall deadline (checked between steps; remaining steps are skipped, partial results are returned). The daemon queue and the CLI wait for the deadline plus the slowest step's own timeout, so a step in progress is never cut off by `MM_QUEUE_TIMEOUT`; without `batchTimeoutMs` the call keeps the daemon queue default (30 s, or 180 s when the host sets it). Accepts tool aliases like `navigate_home` / `navigate-home`. Returns per-step results with timing. | | **Advanced** | | | `mock_network` | Adds, clears, lists, and inspects targeted Playwright network mocks on the active browser context. Unmatched same-origin requests are continued unchanged. A rule with `record` and no `response` records the real request and forwards it unchanged. Rules can opt in to record request bodies and headers (redacted). | +| `events` | Bookmarks or clears the session event buffer that `mm logs` and `mm network` read: `mark` returns the current cursor (one cursor for both) and `summary.startedAt`; `clear` empties it without resetting the cursor. The buffer starts with a browser session and keeps the newest 1000 console and 2000 network records. Browser only. | | `cdp` | Sends a raw Chrome DevTools Protocol command, dispatched through the active platform driver. **Browser:** targets the active page (`target: "page"`, default) or the Extension service worker (`target: "sw"`) on a persistent CDP session shared across calls, so enabled domains and listeners survive; `fresh: true` uses a one-shot session. Full Runtime/DOM/Network/Page surface; destructive methods (`Browser.close`, `Target.closeTarget`, etc.) are blocked. **Mobile (iOS/Android):** targets the app's React Native Hermes JS runtime via Metro's inspector proxy (delegates to `@metamask/device-mcp`, needs a DEBUG build with Metro running); only the JS-engine subset exists (`Runtime`, `Debugger`, `Log`, `HeapProfiler` — no DOM/Page/Network) and `Runtime.terminateExecution` / `Inspector.detached` are blocked. Optional `metroPort` / `appId` are mobile-only (ignored on browser). Categorized as `cdp`: no observation is collected and refs are not refreshed, so run `describe_screen` after a call that changes state. See [Browser vs Mobile CDP](#browser-vs-mobile-hermes-cdp). | | **Hermes (mobile only)** | | | `hermes_targets` | Lists and diagnoses the debuggable Hermes targets Metro exposes (iOS and Android), reporting which target would be chosen or why selection is ambiguous. Use to confirm Metro is running and the app is registered. Pass `all` to bypass the appId filter and discover the real appId. Mobile only — there is no browser equivalent. | @@ -685,6 +686,8 @@ mm describe-screen | `mm mock-network clear` | Clears route mocks and recorded requests. | | `mm mock-network list` | Lists active route mocks. | | `mm mock-network requests [--limit <n>] [--url <glob-or-text>] [--bodies]` | Shows recorded matched and missed requests. `--url` keeps only matching URLs. `--bodies` adds the recorded (redacted) request bodies and headers. | +| `mm events mark` | Returns the current cursor of the session event buffer and `summary.startedAt`. Take it at the start of a flow and pass it to `mm logs` / `mm network` at the end. Browser only. | +| `mm events clear [--kind console\|network]` | Empties the session event buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. | | `mm cdp <method> [params-json] [--timeout <ms>] [--target page\|sw\|hermes\|android-webview] [--fresh] [--metro-port <p>] [--app-id <id>]` | Sends a raw Chrome DevTools Protocol command against the active session. Escape hatch for when structured tools are insufficient. Works on both browser and mobile — the target runtime and blocked methods differ by platform (see below). Browser targets are the active page (`page`, default) and the Extension service worker (`sw`); `--fresh` uses a one-shot session. On mobile the session keeps the `--metro-port` given to `mm launch`, so later calls use it; a per-call `--metro-port` is only an override. | ```bash diff --git a/SKILL.md b/SKILL.md index eedba42e..e1845ffb 100644 --- a/SKILL.md +++ b/SKILL.md @@ -42,7 +42,7 @@ The default depends on the tool's category: | Category | Examples | Default `observe` | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | | **Mutating** | click, type, navigate, reload, launch, cleanup, build, clipboard, mock_network, scroll_to_element, device_swipe, long_press, tap_coordinates, dismiss_keyboard, dismiss_alert, open_app, close_app, press_button, device_context, device_clipboard | `diff` | -| **Read-only** | get_state, get_text, inspect, get_context, set_context, get_alert_text, screen_recording, device_logs, generate_locators, hermes_targets | `none` | +| **Read-only** | get_state, get_text, inspect, get_context, set_context, events, get_alert_text, screen_recording, device_logs, generate_locators, hermes_targets | `none` | | **Discovery** | describe_screen, list_testids, accessibility_snapshot, screenshot (data is already in `result`) | `none` | | **CDP** | cdp | `none` | | **Batch** | run_steps | `diff` | @@ -747,6 +747,20 @@ mm hermes-targets mm hermes-targets --all ``` +### Session events (browser only) + +From `mm launch` on, the daemon records events from every page and the Extension's background service worker into one buffer per session. `mm logs` and `mm network` read it. All kinds share one cursor (`seq`), so one `mark` covers both. Traffic during `mm launch` itself (for example self-onboarding) is not recorded. Mobile sessions return `MM_TOOL_NOT_SUPPORTED_ON_PLATFORM`. + +#### `mm events mark` + +Returns `{ cursor, summary }`. Take it at the start of a flow. + +#### `mm events clear [--kind console|network]` + +Empties the buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. + +`summary` is `{ startedAt, seq, counts: { console, network }, dropped: { console, network } }`. `startedAt` (epoch ms) changes when the session is relaunched; `seq` then starts at 1 again. The buffer keeps the newest 1000 console and 2000 network records; older ones are dropped and counted. + ### Mobile device actions (iOS/Android only) These commands require a mobile session (`mm launch --platform ios|android`). On a browser diff --git a/src/cli/mm.test.ts b/src/cli/mm.test.ts index 9182ceef..d9bcfe99 100644 --- a/src/cli/mm.test.ts +++ b/src/cli/mm.test.ts @@ -1057,6 +1057,7 @@ describe('printHelp', () => { expect(output).toContain('--observe <level>'); expect(output).toContain('--pretty'); expect(output).toContain('MM_PRETTY'); + expect(output).toContain('mm events mark'); }); }); @@ -3119,6 +3120,56 @@ describe('routeCommand', () => { expectFailure(expect.stringContaining('Usage: mm mock-network add'), 2); }); + it('routes events mark', async () => { + await routeCommand('events', ['mark'], 3000); + expect(globalThis.fetch).toHaveBeenCalledWith( + 'http://127.0.0.1:3000/tool/events', + expect.objectContaining({ body: JSON.stringify({ action: 'mark' }) }), + ); + }); + + it('routes events clear with and without --kind', async () => { + await routeCommand('events', ['clear'], 3000); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/events', + expect.objectContaining({ body: JSON.stringify({ action: 'clear' }) }), + ); + await routeCommand('events', ['clear', '--kind', 'network'], 3000); + expect(globalThis.fetch).toHaveBeenLastCalledWith( + 'http://127.0.0.1:3000/tool/events', + expect.objectContaining({ + body: JSON.stringify({ action: 'clear', kind: 'network' }), + }), + ); + }); + + it('exits when events clear --kind has no value', async () => { + await expect( + routeCommand('events', ['clear', '--kind'], 3000), + ).rejects.toThrowError('process.exit'); + expectFailure(expect.stringContaining('Usage: mm events'), 2); + }); + + it.each<[string, string[]]>([ + ['mark with a flag', ['mark', '--kind', 'console']], + ['mark with a stray value', ['mark', 'extra']], + ['clear with a stray value', ['clear', 'extra']], + ['clear with an unknown flag', ['clear', '--error']], + ['clear with a flag after --kind', ['clear', '--kind', 'console', '--x']], + ])('exits when events %s', async (_name, args) => { + await expect(routeCommand('events', args, 3000)).rejects.toThrowError( + 'process.exit', + ); + expectFailure(expect.stringContaining('Usage: mm events'), 2); + }); + + it('exits when events has an unknown action', async () => { + await expect(routeCommand('events', [], 3000)).rejects.toThrowError( + 'process.exit', + ); + expectFailure(expect.stringContaining('Usage: mm events'), 2); + }); + it('exits when mock-network has an unknown action', async () => { await expect( routeCommand('mock-network', ['unknown'], 3000), diff --git a/src/cli/mm.ts b/src/cli/mm.ts index 4cb590d2..2a66ac49 100644 --- a/src/cli/mm.ts +++ b/src/cli/mm.ts @@ -1011,6 +1011,10 @@ export async function routeCommand( await routeMockNetworkCommand(args, daemon); break; } + case 'events': { + await routeEventsCommand(args, daemon); + break; + } case 'cdp': { const cdpMethod = args[0]; if (!cdpMethod) { @@ -1322,6 +1326,43 @@ export async function routeMockNetworkCommand( failUsage('Usage: mm mock-network <add|clear|list|requests> [options]'); } +const EVENTS_USAGE = 'Usage: mm events <mark | clear [--kind console|network]>'; + +/** + * Routes `mm events` subcommands to the daemon. + * + * @param args - CLI arguments after `events`. + * @param daemon - The daemon endpoint (a port or the daemon state). + */ +export async function routeEventsCommand( + args: string[], + daemon: DaemonEndpoint, +): Promise<void> { + const [action, ...rest] = args; + if (action !== 'mark' && action !== 'clear') { + failUsage(EVENTS_USAGE); + } + let kind: string | undefined; + if (rest.length > 0) { + // Only `clear --kind <console|network>` takes arguments; anything else + // (an unknown flag, a stray value, `mark --kind`) is a usage error. + if ( + action !== 'clear' || + rest.length !== 2 || + rest[0] !== '--kind' || + !rest[1] || + rest[1].startsWith('--') + ) { + failUsage(EVENTS_USAGE); + } + [, kind] = rest; + } + await sendRequest(daemon, 'POST', '/tool/events', { + action, + ...(kind === undefined ? {} : { kind }), + }); +} + /** * Checks whether a failed request is safe to send again: only a refused * connection (`ECONNREFUSED`), because the daemon never accepted the request. @@ -2214,6 +2255,12 @@ Advanced: mm cdp <method> [params-json] [--timeout <ms>] [--target page|sw|hermes|android-webview] [--fresh] [--url-filter <substr>] [--metro-port <p>] [--app-id <id>] mm hermes-targets [--all] [--metro-port <p>] [--app-id <id>] (mobile only) +Session events (browser only; recorded from launch on, not during it): + mm events mark Current cursor and summary.startedAt. Take one at the + start of a flow; pass the cursor to logs/network. + mm events clear [--kind console|network] + Empty the buffer; the cursor keeps counting. + Mobile (iOS/Android only): mm device-swipe <up|down|left|right> [--startX <n>] [--startY <n>] [--distance <n>] mm long-press <ref> [--selector <css>] [--testid <id>] [--duration <ms>] diff --git a/src/events/event-buffer.test.ts b/src/events/event-buffer.test.ts new file mode 100644 index 00000000..a23070c5 --- /dev/null +++ b/src/events/event-buffer.test.ts @@ -0,0 +1,264 @@ +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_EVENT_CAPACITY, EventBuffer } from './event-buffer.js'; +import type { EventRecordBase } from '../tools/types/events.js'; + +type TestRecord = EventRecordBase & { name: string; status?: number }; + +const TARGET = { kind: 'page' as const, id: 'T1', url: 'https://a.example/' }; + +/** + * Appends a test record. + * + * @param buffer - The buffer. + * @param kind - The record kind. + * @param name - A label. + * @param t - The record time. + * @returns The stored record. + */ +function add( + buffer: EventBuffer, + kind: 'console' | 'network', + name: string, + t = 1000, +): TestRecord { + return buffer.append<TestRecord>(kind, { t, target: TARGET, name }); +} + +describe('EventBuffer', () => { + it('shares one seq across kinds, starting at 1', () => { + const buffer = new EventBuffer(); + expect(buffer.seq).toBe(0); + expect(add(buffer, 'console', 'a').seq).toBe(1); + expect(add(buffer, 'network', 'b').seq).toBe(2); + expect(add(buffer, 'console', 'c').seq).toBe(3); + expect(buffer.summary()).toStrictEqual({ + startedAt: buffer.startedAt, + seq: 3, + counts: { console: 2, network: 1 }, + dropped: { console: 0, network: 0 }, + }); + }); + + it('uses the default capacities', () => { + expect(DEFAULT_EVENT_CAPACITY).toStrictEqual({ + console: 1000, + network: 2000, + }); + }); + + it('drops the oldest record of a full kind, counts it, and reports a gap', () => { + const buffer = new EventBuffer({ capacity: { console: 2 } }); + add(buffer, 'console', 'c1'); // seq 1 + add(buffer, 'network', 'n1'); // seq 2 + add(buffer, 'console', 'c2'); // seq 3 + add(buffer, 'console', 'c3'); // seq 4, drops c1 + + expect(buffer.summary().dropped).toStrictEqual({ console: 1, network: 0 }); + expect(buffer.summary().counts).toStrictEqual({ console: 2, network: 1 }); + + const fromStart = buffer.read<TestRecord>({ + kind: 'console', + cursor: 0, + limit: 10, + }); + expect(fromStart.gap).toBe(true); + expect(fromStart.records.map((record) => record.name)).toStrictEqual([ + 'c2', + 'c3', + ]); + + // The dropped record is at or before the cursor: no gap. + const afterDrop = buffer.read<TestRecord>({ + kind: 'console', + cursor: 1, + limit: 10, + }); + expect(afterDrop.gap).toBe(false); + + // Other kinds are not affected. + expect( + buffer.read<TestRecord>({ kind: 'network', cursor: 0, limit: 10 }).gap, + ).toBe(false); + }); + + it('reports a gap for a since read only when a dropped record is at or after since', () => { + const buffer = new EventBuffer({ capacity: { network: 1 } }); + add(buffer, 'network', 'old', 100); + add(buffer, 'network', 'new', 300); + + expect( + buffer.read<TestRecord>({ kind: 'network', since: 200, limit: 10 }).gap, + ).toBe(false); + expect( + buffer.read<TestRecord>({ kind: 'network', since: 100, limit: 10 }).gap, + ).toBe(true); + }); + + it('pages with limit and cursor without duplicates or holes', () => { + const buffer = new EventBuffer(); + for (let index = 1; index <= 7; index++) { + add(buffer, index % 2 === 0 ? 'console' : 'network', `r${index}`); + } + // network: r1 r3 r5 r7 (seq 1 3 5 7) + const names: string[] = []; + let cursor = 0; + let pages = 0; + for (;;) { + const page = buffer.read<TestRecord>({ + kind: 'network', + cursor, + limit: 2, + }); + names.push(...page.records.map((record) => record.name)); + pages += 1; + expect(page.cursor).toBeGreaterThanOrEqual(cursor); + ({ cursor } = page); + if (!page.hasMore) { + break; + } + } + expect(names).toStrictEqual(['r1', 'r3', 'r5', 'r7']); + expect(pages).toBe(2); + // The last page moves the cursor to the newest seq of any kind. + expect(cursor).toBe(7); + + const first = buffer.read<TestRecord>({ kind: 'network', limit: 2 }); + expect(first.hasMore).toBe(true); + expect(first.cursor).toBe(3); + }); + + it('returns hasMore false when the page holds exactly the rest', () => { + const buffer = new EventBuffer(); + add(buffer, 'console', 'a'); + add(buffer, 'console', 'b'); + const page = buffer.read<TestRecord>({ kind: 'console', limit: 2 }); + expect(page.hasMore).toBe(false); + expect(page.cursor).toBe(2); + }); + + it('pages with since', () => { + const buffer = new EventBuffer(); + add(buffer, 'console', 'early', 100); + add(buffer, 'console', 'late1', 500); + add(buffer, 'console', 'late2', 600); + const page = buffer.read<TestRecord>({ + kind: 'console', + since: 500, + limit: 1, + }); + expect(page.records.map((record) => record.name)).toStrictEqual(['late1']); + expect(page.hasMore).toBe(true); + const next = buffer.read<TestRecord>({ + kind: 'console', + since: 500, + cursor: page.cursor, + limit: 1, + }); + expect(next.records.map((record) => record.name)).toStrictEqual(['late2']); + expect(next.hasMore).toBe(false); + }); + + it('applies the filter before the limit', () => { + const buffer = new EventBuffer(); + add(buffer, 'console', 'skip'); + add(buffer, 'console', 'keep1'); + add(buffer, 'console', 'skip'); + add(buffer, 'console', 'keep2'); + const page = buffer.read<TestRecord>({ + kind: 'console', + limit: 1, + filter: (record) => record.name.startsWith('keep'), + }); + expect(page.records.map((record) => record.name)).toStrictEqual(['keep1']); + expect(page.hasMore).toBe(true); + expect(page.cursor).toBe(2); + }); + + it('does not return a record updated in place after it was read', () => { + const buffer = new EventBuffer(); + const request = add(buffer, 'network', 'req'); + const page = buffer.read<TestRecord>({ kind: 'network', limit: 10 }); + expect(page.records[0]?.status).toBeUndefined(); + + request.status = 200; + const again = buffer.read<TestRecord>({ + kind: 'network', + cursor: page.cursor, + limit: 10, + }); + expect(again.records).toStrictEqual([]); + // The returned copy is not changed by the update. + expect(page.records[0]?.status).toBeUndefined(); + expect( + buffer.read<TestRecord>({ kind: 'network', limit: 10 }).records[0] + ?.status, + ).toBe(200); + }); + + it('reads from the oldest record and reports a gap for a cursor from an earlier session', () => { + const buffer = new EventBuffer(); + add(buffer, 'console', 'a'); + add(buffer, 'console', 'b'); + const page = buffer.read<TestRecord>({ + kind: 'console', + cursor: 50, + limit: 10, + }); + expect(page.records.map((record) => record.name)).toStrictEqual(['a', 'b']); + expect(page.gap).toBe(true); + expect(page.cursor).toBe(2); + + const firstPage = buffer.read<TestRecord>({ + kind: 'console', + cursor: 50, + limit: 1, + }); + expect(firstPage.records.map((record) => record.name)).toStrictEqual(['a']); + expect(firstPage.hasMore).toBe(true); + expect(firstPage.gap).toBe(true); + expect(firstPage.cursor).toBe(1); + }); + + it('clamps a limit below one to one record', () => { + const buffer = new EventBuffer(); + add(buffer, 'console', 'a'); + add(buffer, 'console', 'b'); + for (const limit of [0, -3, Number.NaN, 1.9]) { + const page = buffer.read<TestRecord>({ kind: 'console', limit }); + expect(page.records).toHaveLength(1); + expect(page.hasMore).toBe(true); + } + }); + + it('clear keeps seq, so old cursors stay valid, and is not a gap', () => { + const buffer = new EventBuffer(); + add(buffer, 'console', 'a'); + add(buffer, 'network', 'b'); + expect(buffer.clear('console')).toStrictEqual(['console']); + expect(buffer.summary().counts).toStrictEqual({ console: 0, network: 1 }); + expect(add(buffer, 'console', 'c').seq).toBe(3); + + const page = buffer.read<TestRecord>({ + kind: 'console', + cursor: 0, + limit: 10, + }); + expect(page.gap).toBe(false); + expect(page.records.map((record) => record.name)).toStrictEqual(['c']); + + expect(buffer.clear()).toStrictEqual(['console', 'network']); + expect(buffer.summary()).toMatchObject({ + seq: 3, + counts: { console: 0, network: 0 }, + }); + }); + + it('gives each new buffer a new startedAt', () => { + const first = new EventBuffer({ now: 5000 }); + const second = new EventBuffer({ now: 5000 }); + expect(second.startedAt).toBeGreaterThan(first.startedAt); + const third = new EventBuffer(); + expect(third.startedAt).toBeGreaterThan(second.startedAt); + }); +}); diff --git a/src/events/event-buffer.ts b/src/events/event-buffer.ts new file mode 100644 index 00000000..2a0d0619 --- /dev/null +++ b/src/events/event-buffer.ts @@ -0,0 +1,216 @@ +import type { + EventKind, + EventPage, + EventRecordBase, + EventSummary, +} from '../tools/types/events.js'; + +/** Records kept per kind by default. */ +export const DEFAULT_EVENT_CAPACITY: Readonly<Record<EventKind, number>> = { + console: 1000, + network: 2000, +}; + +export const EVENT_KINDS: readonly EventKind[] = ['console', 'network']; + +/** Options for {@link EventBuffer.read}. */ +export type EventReadOptions<RecordType> = { + kind: EventKind; + /** Only records with a `seq` above this (from `mark` or an earlier read). */ + cursor?: number; + /** Only records with `t` at or after this, epoch ms. */ + since?: number; + /** Maximum records to return. */ + limit: number; + /** Only records this returns true for. */ + filter?: (record: RecordType) => boolean; +}; + +type KindState = { + records: EventRecordBase[]; + capacity: number; + dropped: number; + /** `seq` of the newest dropped record, 0 when none. */ + lastDroppedSeq: number; + /** Largest `t` of a dropped record, 0 when none. */ + lastDroppedT: number; +}; + +let lastStartedAt = 0; + +/** + * Returns a start time later than every earlier one, so two sessions never + * share a `startedAt`, even when started in the same millisecond. + * + * @param now - The current time, epoch ms. + * @returns The start time. + */ +function nextStartedAt(now: number): number { + lastStartedAt = Math.max(now, lastStartedAt + 1); + return lastStartedAt; +} + +/** + * The event buffer of one session: one bounded list per record kind, and + * one `seq` shared by all kinds, so one cursor covers every kind. + * + * A record keeps the `seq` it got when it was appended, also when its + * source updates it in place later (a network request that finishes), so a + * read after a cursor never returns it again. + */ +export class EventBuffer { + readonly startedAt: number; + + readonly #kinds: Record<EventKind, KindState>; + + #seq = 0; + + /** + * @param options - Buffer options. + * @param options.capacity - Records kept per kind; the oldest record of a + * full kind is dropped and counted. + * @param options.now - The current time, epoch ms (for tests). + */ + constructor( + options: { + capacity?: Partial<Record<EventKind, number>>; + now?: number; + } = {}, + ) { + this.startedAt = nextStartedAt(options.now ?? Date.now()); + const state = (kind: EventKind): KindState => ({ + records: [], + capacity: options.capacity?.[kind] ?? DEFAULT_EVENT_CAPACITY[kind], + dropped: 0, + lastDroppedSeq: 0, + lastDroppedT: 0, + }); + this.#kinds = { console: state('console'), network: state('network') }; + } + + /** + * @returns The newest `seq` given out (0 before the first record). + */ + get seq(): number { + return this.#seq; + } + + /** + * Appends a record and gives it the next `seq`. The returned object is the + * stored record: a source may update its fields in place later. + * + * @param kind - The record kind. + * @param record - The record without its `seq`. + * @returns The stored record. + */ + append<RecordType extends EventRecordBase>( + kind: EventKind, + record: Omit<RecordType, 'seq'>, + ): RecordType { + this.#seq += 1; + const stored = { seq: this.#seq, ...record } as RecordType; + const state = this.#kinds[kind]; + state.records.push(stored); + while (state.records.length > state.capacity) { + const dropped = state.records.shift() as EventRecordBase; + state.dropped += 1; + state.lastDroppedSeq = dropped.seq; + state.lastDroppedT = Math.max(state.lastDroppedT, dropped.t); + } + return stored; + } + + /** + * Reads records of one kind, oldest first. + * + * The returned `cursor` continues the read without duplicates or holes: + * the `seq` of the last returned record when `hasMore`, else the newest + * `seq` of the buffer (records of other kinds and records the filter + * skipped are behind it). `gap` is true when a record after `cursor` (and + * at or after `since`) was dropped because the buffer was full. When + * `cursor` and `since` are both given, `gap` is approximate: a record + * dropped after `cursor` but before `since` is not distinguished. + * + * A `cursor` above the newest `seq` (from an earlier session: `seq` starts + * at 1 per session) is stale. The read then starts from the oldest record + * and reports `gap: true`, so a client that only compares cursors notices + * the records are not the ones it asked for. + * + * `limit` is clamped to at least 1. + * + * @param options - What to read. + * @returns The page. + */ + read<RecordType extends EventRecordBase>( + options: EventReadOptions<RecordType>, + ): EventPage<RecordType> { + const { kind, since, limit, filter } = options; + const requestedCursor = options.cursor ?? 0; + const staleCursor = requestedCursor > this.#seq; + const cursor = staleCursor ? 0 : requestedCursor; + const maxRecords = + Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : 1; + const state = this.#kinds[kind]; + const records: RecordType[] = []; + let hasMore = false; + for (const record of state.records as RecordType[]) { + if ( + record.seq <= cursor || + (since !== undefined && record.t < since) || + (filter !== undefined && !filter(record)) + ) { + continue; + } + if (records.length === maxRecords) { + hasMore = true; + break; + } + records.push({ ...record }); + } + const last = records.at(-1); + return { + records, + cursor: + hasMore && last !== undefined ? last.seq : Math.max(cursor, this.#seq), + hasMore, + gap: + staleCursor || + (state.lastDroppedSeq > cursor && + (since === undefined || state.lastDroppedT >= since)), + summary: this.summary(), + }; + } + + /** + * Empties the buffer of one kind, or of every kind. `seq` keeps counting, + * so older cursors stay valid. Cleared records are not a gap. + * + * @param kind - The kind to clear; every kind when undefined. + * @returns The kinds cleared. + */ + clear(kind?: EventKind): EventKind[] { + const kinds = kind === undefined ? [...EVENT_KINDS] : [kind]; + for (const each of kinds) { + this.#kinds[each].records.length = 0; + } + return kinds; + } + + /** + * @returns The buffer state. + */ + summary(): EventSummary { + return { + startedAt: this.startedAt, + seq: this.#seq, + counts: { + console: this.#kinds.console.records.length, + network: this.#kinds.network.records.length, + }, + dropped: { + console: this.#kinds.console.dropped, + network: this.#kinds.network.dropped, + }, + }; + } +} diff --git a/src/events/redact.test.ts b/src/events/redact.test.ts new file mode 100644 index 00000000..1c6351a8 --- /dev/null +++ b/src/events/redact.test.ts @@ -0,0 +1,374 @@ +import { describe, expect, it } from 'vitest'; + +import { + isSecretUrlSegment, + isSensitiveQueryParam, + MAX_RECORDED_TEXT_LENGTH, + MAX_RECORDED_URL_LENGTH, + REDACTED_VALUE, + redactText, + redactUrl, + redactUrlsInText, + truncateText, +} from './redact.js'; + +const INFURA_KEY = '0123456789abcdef0123456789abcdef'; +const ADDRESS = '0x5aeda56215b167893e80b4fe645ba6d5bab767de'; +const TX_HASH = + '0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b'; +const UUID = '3f2504e0-4f89-11d3-9a0c-0305e82c3301'; + +describe('redactUrl', () => { + it.each([ + [ + 'Infura key in the path', + `https://mainnet.infura.io/v3/${INFURA_KEY}`, + `https://mainnet.infura.io/v3/${REDACTED_VALUE}`, + ], + [ + 'key in a host label', + `https://${INFURA_KEY}.rpc.example.com/`, + `https://${REDACTED_VALUE}.rpc.example.com/`, + ], + [ + 'apiKey query value', + 'https://api.example.com/v1/x?apiKey=supersecret&chainId=1', + `https://api.example.com/v1/x?apiKey=${REDACTED_VALUE}&chainId=1`, + ], + [ + 'snake and dash query names', + 'https://a.example/?api_key=1&x-api-key=2&project-id=3&token=4&sig=5&jwt=6&session=7&key=8', + `https://a.example/?api_key=${REDACTED_VALUE}&x-api-key=${REDACTED_VALUE}&project-id=${REDACTED_VALUE}&token=${REDACTED_VALUE}&sig=${REDACTED_VALUE}&jwt=${REDACTED_VALUE}&session=${REDACTED_VALUE}&key=${REDACTED_VALUE}`, + ], + [ + 'encoded query name', + 'https://a.example/?api%5Fkey=1&%E0%A4%A=2', + `https://a.example/?api%5Fkey=${REDACTED_VALUE}&%E0%A4%A=2`, + ], + [ + 'credentials', + 'https://user:pass@rpc.example.com/path', + `https://${REDACTED_VALUE}@rpc.example.com/path`, + ], + [ + 'username only credential', + 'https://user@rpc.example.com/path', + `https://${REDACTED_VALUE}@rpc.example.com/path`, + ], + [ + 'AWS signed URL', + 'https://bucket.s3.amazonaws.com/x?X-Amz-Signature=abc&X-Amz-Credential=akid%2Fdate', + `https://bucket.s3.amazonaws.com/x?X-Amz-Signature=${REDACTED_VALUE}&X-Amz-Credential=${REDACTED_VALUE}`, + ], + [ + 'GCS signed URL', + 'https://storage.example.com/x?X-Goog-Signature=abc&X-Goog-Credential=akid', + `https://storage.example.com/x?X-Goog-Signature=${REDACTED_VALUE}&X-Goog-Credential=${REDACTED_VALUE}`, + ], + [ + 'bare JWT fragment', + 'https://x.io/p#eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig', + `https://x.io/p#${REDACTED_VALUE}`, + ], + [ + 'JWT value under a non-sensitive name', + 'https://x.io/p?data=eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig', + `https://x.io/p?data=${REDACTED_VALUE}`, + ], + [ + '0x address kept', + `https://api.example.com/accounts/${ADDRESS}/balances`, + `https://api.example.com/accounts/${ADDRESS}/balances`, + ], + [ + 'tx hash kept', + `https://api.example.com/tx/${TX_HASH}`, + `https://api.example.com/tx/${TX_HASH}`, + ], + [ + 'UUID kept', + `https://api.example.com/quotes/${UUID}`, + `https://api.example.com/quotes/${UUID}`, + ], + [ + 'UUID after a version word kept', + `https://api.example.com/v2/${UUID}`, + `https://api.example.com/v2/${UUID}`, + ], + [ + 'UUID under an orders path kept', + `https://api.example.com/v1/orders/${UUID}`, + `https://api.example.com/v1/orders/${UUID}`, + ], + [ + 'UUID as the only path segment redacted (Blast gateway key)', + `https://eth-mainnet.blastapi.io/${UUID}`, + `https://eth-mainnet.blastapi.io/${REDACTED_VALUE}`, + ], + [ + 'fragment tokens', + 'https://x.io/cb#access_token=ya29.a0AfH6&id_token=eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig', + `https://x.io/cb#access_token=${REDACTED_VALUE}&id_token=${REDACTED_VALUE}`, + ], + [ + 'JWT in the path', + 'https://x.io/verify/eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig', + `https://x.io/verify/${REDACTED_VALUE}`, + ], + [ + 'project ID and token query names', + 'https://rpc.example.com/?infuraProjectId=1&api_token=2&access_key=3&code=4&keyword=5&chainId=6', + `https://rpc.example.com/?infuraProjectId=${REDACTED_VALUE}&api_token=${REDACTED_VALUE}&access_key=${REDACTED_VALUE}&code=${REDACTED_VALUE}&keyword=5&chainId=6`, + ], + [ + 'Alchemy key after a version word', + 'https://eth-mainnet.g.alchemy.com/v2/AbCdEfGhIjKlMnOpQrStUvWxYzAbCdEf', + `https://eth-mainnet.g.alchemy.com/v2/${REDACTED_VALUE}`, + ], + [ + 'Bitcoin transaction ID after an identifier word kept', + 'https://api.example.com/tx/9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b', + 'https://api.example.com/tx/9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b', + ], + [ + 'Bitcoin address after an identifier word kept', + 'https://api.example.com/accounts/1BoatSLRHtKNngkdXEeobR76b53LETtpyT', + 'https://api.example.com/accounts/1BoatSLRHtKNngkdXEeobR76b53LETtpyT', + ], + [ + 'hash and flag query kept', + 'https://a.example/p?flag&x=1#frag', + 'https://a.example/p?flag&x=1#frag', + ], + [ + 'chrome-extension URL', + `chrome-extension://abcdefghijklmnopabcdefghijklmnop/home.html?token=1`, + `chrome-extension://abcdefghijklmnopabcdefghijklmnop/home.html?token=${REDACTED_VALUE}`, + ], + [ + 'URL without a host', + `data:text/plain,${INFURA_KEY}`, + `data:text/plain,${INFURA_KEY}`, + ], + ])('%s', (_name, input, expected) => { + expect(redactUrl(input)).toBe(expected); + }); + + it('keeps an unparsable URL, cut to the URL limit', () => { + expect(redactUrl('not a url')).toBe('not a url'); + const long = 'x'.repeat(MAX_RECORDED_URL_LENGTH + 10); + expect(redactUrl(long)).toBe(`${'x'.repeat(MAX_RECORDED_URL_LENGTH)}…`); + }); + + it('cuts a long URL', () => { + const url = `https://a.example/${'a/'.repeat(MAX_RECORDED_URL_LENGTH)}`; + expect(redactUrl(url)).toHaveLength(MAX_RECORDED_URL_LENGTH + 1); + }); +}); + +describe('isSecretUrlSegment', () => { + it.each([ + [INFURA_KEY, true], + ['abcdefghijklmnopqrstuvwxyz', false], + ['123456789012345678901234', false], + ['short1a', false], + [ADDRESS, false], + [UUID, false], + ['has.dot.abcdef0123456789abcdef', false], + ])('%s → %s', (segment, expected) => { + expect(isSecretUrlSegment(segment)).toBe(expected); + }); +}); + +describe('isSensitiveQueryParam', () => { + it('matches body field names and query names, ignoring case, - and _', () => { + expect(isSensitiveQueryParam('writeKey')).toBe(true); + expect(isSensitiveQueryParam('ACCESS_TOKEN')).toBe(true); + expect(isSensitiveQueryParam('projectId')).toBe(true); + expect(isSensitiveQueryParam('chainId')).toBe(false); + expect(isSensitiveQueryParam('token_symbol')).toBe(false); + }); + + it('matches signed-URL credential names', () => { + for (const name of [ + 'X-Amz-Signature', + 'X-Amz-Credential', + 'X-Goog-Signature', + 'X-Goog-Credential', + ]) { + expect(isSensitiveQueryParam(name)).toBe(true); + } + }); + + it('matches short secret names', () => { + for (const name of [ + 'passwd', + 'pwd', + 'pass', + 'bearer', + 'seed', + 'pk', + 'mnemonicPhrase', + ]) { + expect(isSensitiveQueryParam(name)).toBe(true); + } + expect(isSensitiveQueryParam('password')).toBe(true); + expect(isSensitiveQueryParam('PASSWD')).toBe(true); + }); + + it('keeps non-secret names that end in key or token', () => { + for (const name of [ + 'publicKey', + 'pubKey', + 'sortKey', + 'cacheKey', + 'primaryKey', + 'sourceToken', + 'destinationToken', + 'fromToken', + 'toToken', + 'buyToken', + 'sellToken', + 'tokenAddress', + 'nativeToken', + ]) { + expect(isSensitiveQueryParam(name)).toBe(false); + } + }); + + it('does not match innocent prefix lookalikes', () => { + for (const name of [ + 'author', + 'authors', + 'authority', + 'signer', + 'significant', + ]) { + expect(isSensitiveQueryParam(name)).toBe(false); + } + expect(isSensitiveQueryParam('authorization')).toBe(true); + expect(isSensitiveQueryParam('signature')).toBe(true); + }); +}); + +describe('redactUrlsInText / redactText', () => { + it('redacts URLs inside text', () => { + expect( + redactUrlsInText( + `fetch failed: https://mainnet.infura.io/v3/${INFURA_KEY} (status 401)`, + ), + ).toBe( + `fetch failed: https://mainnet.infura.io/v3/${REDACTED_VALUE} (status 401)`, + ); + expect(redactUrlsInText('wss://x.example/?token=abc"')).toBe( + `wss://x.example/?token=${REDACTED_VALUE}"`, + ); + }); + + it('keeps a URL without secrets as written', () => { + expect(redactUrlsInText('see https://A.Example')).toBe( + 'see https://A.Example', + ); + expect(redactUrlsInText('see https://a.example/p')).toBe( + 'see https://a.example/p', + ); + }); + + it('redacts credentials in a URL inside text', () => { + expect( + redactUrlsInText('basic https://user:s3cret@rpc.example.com/ end'), + ).toBe(`basic https://${REDACTED_VALUE}@rpc.example.com/ end`); + }); + + it('redacts a URL followed by sentence punctuation and keeps the punctuation', () => { + const infura = `https://mainnet.infura.io/v3/${INFURA_KEY}`; + expect(redactUrlsInText(`Failed to fetch ${infura}.`)).toBe( + `Failed to fetch https://mainnet.infura.io/v3/${REDACTED_VALUE}.`, + ); + expect(redactUrlsInText(`fetch ${infura}, retrying`)).toBe( + `fetch https://mainnet.infura.io/v3/${REDACTED_VALUE}, retrying`, + ); + expect(redactUrlsInText(`fetch ${infura}: 401`)).toBe( + `fetch https://mainnet.infura.io/v3/${REDACTED_VALUE}: 401`, + ); + expect(redactUrlsInText(`[${infura}]`)).toBe( + `[https://mainnet.infura.io/v3/${REDACTED_VALUE}]`, + ); + expect(redactUrlsInText(`url=${infura};`)).toBe( + `url=https://mainnet.infura.io/v3/${REDACTED_VALUE};`, + ); + expect( + redactUrlsInText('https://h.io/v2/AbCdEfGhIjKlMnOpQrStUvWxYzAbCdEf.'), + ).toBe(`https://h.io/v2/${REDACTED_VALUE}.`); + expect(redactUrlsInText(`(${infura})`)).toBe( + `(https://mainnet.infura.io/v3/${REDACTED_VALUE})`, + ); + }); + + it('redacts JWTs and Bearer tokens anywhere in a text', () => { + const jwt = 'eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig'; + expect(redactText(`Authorization: Bearer ${jwt}`)).toBe( + `Authorization: Bearer ${REDACTED_VALUE}`, + ); + expect(redactText(`token=${jwt} in text`)).toBe( + `token=${REDACTED_VALUE} in text`, + ); + expect(redactText(`payload ${jwt} end`)).toBe( + `payload ${REDACTED_VALUE} end`, + ); + expect(redactText('Bearer abc123def456')).toBe(`Bearer ${REDACTED_VALUE}`); + expect(redactText('bearer abc123def456')).toBe(`bearer ${REDACTED_VALUE}`); + }); + + it('redacts credentials in non-HTTP URLs inside text', () => { + expect( + redactText('connect ftp://user:s3cret@files.example.com/x now'), + ).toBe(`connect ftp://${REDACTED_VALUE}@files.example.com/x now`); + expect(redactText('postgres://admin:hunter2@db.example.com:5432/app')).toBe( + `postgres://${REDACTED_VALUE}@db.example.com:5432/app`, + ); + expect( + redactText( + 'mongodb+srv://user:pass@cluster.example.net/db?retryWrites=true', + ), + ).toBe( + `mongodb+srv://${REDACTED_VALUE}@cluster.example.net/db?retryWrites=true`, + ); + }); + + it('keeps a path that contains a colon and an at sign', () => { + expect(redactText('see https://x.io/a:b@c')).toBe('see https://x.io/a:b@c'); + }); + + it('leaves text without secrets byte-identical', () => { + const text = 'plain {"a":1} — “quotes” and https://example.com/a:b@c'; + expect(redactText(text)).toBe(text); + }); + + it('keeps a closing brace or star after a URL', () => { + const url = `https://x.io/p?token=${INFURA_KEY}`; + expect(redactUrlsInText(`{url: ${url}}, next`)).toBe( + `{url: https://x.io/p?token=${REDACTED_VALUE}}, next`, + ); + expect(redactUrlsInText(`${url}*`)).toBe( + `https://x.io/p?token=${REDACTED_VALUE}*`, + ); + }); + + it('redacts a long run of punctuation in linear time', () => { + // A regex-based trailing-punctuation check took seconds on this input. + const text = `https://x.io/${'.'.repeat(100_000)}x`; + const started = performance.now(); + expect(redactText(text)).toBe( + `${text.slice(0, MAX_RECORDED_TEXT_LENGTH)}…`, + ); + expect(performance.now() - started).toBeLessThan(500); + }); + + it('cuts long text', () => { + const text = 'e'.repeat(MAX_RECORDED_TEXT_LENGTH + 5); + expect(redactText(text)).toBe(`${'e'.repeat(MAX_RECORDED_TEXT_LENGTH)}…`); + expect(truncateText('abc', 2)).toBe('ab…'); + expect(truncateText('abc')).toBe('abc'); + }); +}); diff --git a/src/events/redact.ts b/src/events/redact.ts new file mode 100644 index 00000000..08980588 --- /dev/null +++ b/src/events/redact.ts @@ -0,0 +1,430 @@ +/** + * Redaction for session event records (`mm logs`, `mm network`). Applied + * before a record enters the buffer, so secrets never reach the output. + */ + +import { isSensitiveBodyField, REDACTED_VALUE } from '../tools/mock-network.js'; + +export { REDACTED_VALUE }; + +export const MAX_RECORDED_URL_LENGTH = 2048; + +export const MAX_RECORDED_TEXT_LENGTH = 2000; + +// Query and fragment parameter names whose values are secrets, in addition to +// the mock-network body field names and the patterns below. +const SENSITIVE_QUERY_PARAMS = new Set([ + 'key', + 'token', + 'auth', + 'authtoken', + 'sig', + 'signature', + 'jwt', + 'session', + 'sessionid', + 'sessiontoken', + 'projectid', + 'code', + 'passwd', + 'pwd', + 'pass', + 'bearer', + 'seed', + 'pk', +]); + +// Names that end in `key` or `token` but are not secrets: a sort key, the +// source and destination tokens of a swap, a public key. They are checked +// before the suffix patterns, so a name on this list is never redacted. +const NON_SECRET_QUERY_NAMES = new Set([ + 'publickey', + 'pubkey', + 'sortkey', + 'cachekey', + 'primarykey', + 'sourcetoken', + 'destinationtoken', + 'fromtoken', + 'totoken', + 'buytoken', + 'selltoken', + 'tokenaddress', + 'nativetoken', +]); + +// Parameter names that carry a secret as a suffix or prefix, after +// lowercasing and removing `-` and `_`: `infuraProjectId`, `api_token`, +// `access_key`, `x-api-key`, `sig`, `signature`, `authToken`, `oauth`. +const SENSITIVE_QUERY_NAME_PATTERNS = [ + /token$/u, + /key$/u, + /secret$/u, + /projectid$/u, + // `sig`, `sign`, `signature`, and `x-amz-signature` / `x-goog-signature` + // through the suffix rule. `signer` and `significant` are not secrets. + /^sig(?:n|nature)?$/u, + /signature$/u, + // `auth`, `authToken`, `authentication`, `authorization`, but not the + // innocent `author`, `authors` and `authority`. + /^auth(?!or(?:s|ity)?$)/u, + // `x-amz-credential` / `x-goog-credential`. + /credential$/u, + // `mnemonic`, `mnemonicPhrase`, `mnemonic_words`. + /mnemonic/u, +]; + +// A JWT: three base64url parts, the first starting with `eyJ` (`{"`). +const JWT_PATTERN = /^eyJ[\w-]+\.[\w-]+\.[\w-]*$/u; + +// A JWT anywhere in a text. A shorter first part is allowed than in a URL +// path, because a text can be a log line around a token. +const JWT_IN_TEXT_PATTERN = /\beyJ[\w-]{4,}\.[\w-]{4,}\.[\w-]*/gu; + +// The credential after `Bearer`, case-insensitive, anywhere in a text. A +// value shorter than 8 token characters is prose (`the bearer of good news`), +// not a token. +const BEARER_TOKEN_IN_TEXT_PATTERN = /\b(Bearer\s+)[A-Za-z0-9._~+/-]{8,}=*/giu; + +// `scheme://user:password@` anywhere in a text, for schemes the URL pattern +// does not know (`ftp:`, `postgres:`, `redis:`, `mongodb+srv:`, …). The match +// is parsed as a URL so only a real userinfo is redacted, not a path that +// happens to contain `:` and `@`. +const ANY_SCHEME_URL_IN_TEXT_PATTERN = + /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>`)\]}*]+/giu; + +// Path segments that identify an object (an account, a transaction), whose +// next segment can be a hash-like ID rather than a key. +const IDENTIFIER_PATH_WORDS = new Set([ + 'account', + 'accounts', + 'address', + 'addresses', + 'tx', + 'txs', + 'transaction', + 'transactions', +]); + +// Path segments that hold an API key in the next segment (`/v3/<key>`). +const RPC_KEY_PATH_WORDS = new Set(['v1', 'v2', 'v3', 'v4']); + +const UUID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu; + +// A 64-character hex ID without `0x`, such as a Bitcoin transaction ID. +const HEX_ID_PATTERN = /^[0-9a-f]{64}$/iu; + +// A base58 string of the length of a Bitcoin address or transaction ID. +const BASE58_ID_PATTERN = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/u; + +const URL_IN_TEXT_PATTERN = /\b(?:https?|wss?):\/\/[^\s"'<>`)\]}*]+/giu; + +// Punctuation that can end a sentence right after a URL, which the URL +// pattern otherwise swallows. `)}]`, `}` and `*` are already excluded from +// the pattern, so a URL wrapped in `{`/`(`/`[` keeps its wrapper. +const TRAILING_URL_PUNCTUATION_CHARS = new Set([ + '.', + ',', + ';', + ':', + '!', + '?', + '}', + '*', +]); + +/** + * Checks whether a URL segment looks like an API key: at least 24 + * characters of letters, digits, `-` or `_`, with both letters and digits. + * Hex values with `0x` (addresses, hashes) and UUIDs are kept; JWTs are + * always redacted, even when shorter than 24 characters. + * + * @param segment - A path segment or host label. + * @returns True if the segment must be redacted. + */ +export function isSecretUrlSegment(segment: string): boolean { + return ( + (segment.length >= 24 && + /^[A-Za-z0-9_-]+$/u.test(segment) && + /[0-9]/u.test(segment) && + /[A-Za-z]/u.test(segment) && + !/^0x[0-9a-f]+$/iu.test(segment) && + !UUID_PATTERN.test(segment)) || + JWT_PATTERN.test(segment) + ); +} + +/** + * Checks whether a query or fragment parameter holds a secret. + * + * @param name - The decoded parameter name. + * @returns True if the value must be redacted. + */ +export function isSensitiveQueryParam(name: string): boolean { + const normalized = name.toLowerCase().replace(/[-_]/gu, ''); + if (NON_SECRET_QUERY_NAMES.has(normalized)) { + return false; + } + return ( + isSensitiveBodyField(name) || + SENSITIVE_QUERY_PARAMS.has(normalized) || + SENSITIVE_QUERY_NAME_PATTERNS.some((pattern) => pattern.test(normalized)) + ); +} + +/** + * Cuts a text to a maximum length and marks the cut. + * + * @param text - The text. + * @param maxLength - The maximum length. + * @returns The text, at most `maxLength` characters plus the marker. + */ +export function truncateText( + text: string, + maxLength = MAX_RECORDED_TEXT_LENGTH, +): string { + return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text; +} + +/** + * Redacts secrets in a URL: credentials, key-like host labels and path + * segments (for example an Infura project ID) and sensitive query values. + * The result is cut to {@link MAX_RECORDED_URL_LENGTH} characters. + * + * @param rawUrl - The URL. + * @returns The URL safe to record. + */ +export function redactUrl(rawUrl: string): string { + let url: URL; + try { + url = new URL(rawUrl); + } catch { + return truncateText(rawUrl, MAX_RECORDED_URL_LENGTH); + } + if (url.host === '') { + // `chrome-extension:` and other non-hierarchical URLs: nothing to redact + // in a host; keep the path rules. + return truncateText( + `${url.protocol}${redactPath(url.pathname)}${redactParameters( + url.search, + '?', + )}${redactParameters(url.hash, '#')}`, + MAX_RECORDED_URL_LENGTH, + ); + } + + const host = url.host + .split('.') + .map((label) => (isSecretUrlSegment(label) ? REDACTED_VALUE : label)) + .join('.'); + // `user:pass@host` carries a credential: keep the fact that there was one, + // so a redacted URL is recognisably redacted, without the credential. + const credentials = + url.username !== '' || url.password !== '' ? `${REDACTED_VALUE}@` : ''; + return truncateText( + `${url.protocol}//${credentials}${host}${redactPath( + url.pathname, + )}${redactParameters(url.search, '?')}${redactParameters(url.hash, '#')}`, + MAX_RECORDED_URL_LENGTH, + ); +} + +/** + * Redacts key-like segments of a URL path. A UUID that is the whole path is + * a credential, as in `https://eth-mainnet.blastapi.io/<uuid>`; a UUID under + * a real path is an identifier and is kept. Segments after an identifier word + * also keep hash-like IDs (a transaction hash, a Bitcoin address); segments + * after an RPC version word are redacted as API keys when they are opaque. + * + * @param pathname - The URL path. + * @returns The path with secret segments replaced. + */ +function redactPath(pathname: string): string { + const segments = pathname.split('/'); + const nonEmpty = segments.filter((segment) => segment !== ''); + // The only-segment rule keeps `/v1/orders/<uuid>` and `/v2/<uuid>` as + // identifiers while redacting a bare key path such as the Blast one. + const onlySegment = nonEmpty.length === 1 ? nonEmpty[0] : undefined; + let previous = ''; + return segments + .map((segment) => { + const afterIdentifier = IDENTIFIER_PATH_WORDS.has(previous); + const afterRpcVersion = RPC_KEY_PATH_WORDS.has(previous); + previous = segment.toLowerCase(); + if (segment === onlySegment && UUID_PATTERN.test(segment)) { + return REDACTED_VALUE; + } + if ( + afterIdentifier && + (HEX_ID_PATTERN.test(segment) || BASE58_ID_PATTERN.test(segment)) + ) { + return segment; + } + if (afterRpcVersion && isOpaquePathKey(segment)) { + return REDACTED_VALUE; + } + return isSecretUrlSegment(segment) ? REDACTED_VALUE : segment; + }) + .join('/'); +} + +/** + * Checks whether a path segment after an RPC version word is an API key: at + * least 28 letters, digits, `-` or `_`, not a hex value with `0x` or a UUID. + * + * Trade-off: the check does not require digits, because real keys can be + * 32 random letters only (a digit-less Alchemy key would leak otherwise). + * A long human-readable word in that position is redacted as collateral; + * version words are followed by a key in every RPC provider URL seen, so + * that is the safe side. + * + * @param segment - The path segment. + * @returns True if the segment must be redacted. + */ +function isOpaquePathKey(segment: string): boolean { + return ( + segment.length >= 28 && + /^[A-Za-z0-9_-]+$/u.test(segment) && + !/^0x[0-9a-f]+$/iu.test(segment) && + !UUID_PATTERN.test(segment) + ); +} + +/** + * Redacts the values of sensitive parameters in a query string or fragment. + * + * @param parameters - The query string or fragment, with its `?` or `#`, or + * empty. + * @param prefix - The `?` or `#` that starts the parameters. + * @returns The parameters with secret values replaced. + */ +function redactParameters(parameters: string, prefix: '?' | '#'): string { + if (!parameters) { + return ''; + } + const pairs = parameters.slice(1).split('&').map(redactPair); + return `${prefix}${pairs.join('&')}`; +} + +/** + * Redacts one `name=value` parameter when its name is sensitive or its value + * is a JWT. A bare part (no `=`) is redacted when it looks like a key, as in + * `#<jwt>`. + * + * @param pair - The encoded parameter. + * @returns The parameter with its value replaced, or the input. + */ +function redactPair(pair: string): string { + const separator = pair.indexOf('='); + if (separator < 0) { + return isSecretUrlSegment(decodeQueryName(pair)) ? REDACTED_VALUE : pair; + } + const name = decodeQueryName(pair.slice(0, separator)); + const value = decodeQueryName(pair.slice(separator + 1)); + return isSensitiveQueryParam(name) || JWT_PATTERN.test(value) + ? `${pair.slice(0, separator)}=${REDACTED_VALUE}` + : pair; +} + +/** + * Decodes a query parameter name without throwing. + * + * @param name - The encoded name. + * @returns The decoded name, or the input when it is not valid encoding. + */ +function decodeQueryName(name: string): string { + try { + return decodeURIComponent(name.replace(/\+/gu, ' ')); + } catch { + return name; + } +} + +/** + * Counts the trailing sentence punctuation of a URL match. A backward loop + * keeps the work linear: a regex such as `[.,;:!?]+$` can retry at every + * position of a long run of punctuation. + * + * @param match - The URL as matched in the text. + * @returns The number of trailing punctuation characters. + */ +function trailingUrlPunctuationLength(match: string): number { + let start = match.length; + while ( + start > 0 && + TRAILING_URL_PUNCTUATION_CHARS.has(match.charAt(start - 1)) + ) { + start -= 1; + } + return match.length - start; +} + +/** + * Redacts the credentials of a `scheme://user:password@` URL in a text for + * the schemes the URL pattern does not know (`ftp:`, `postgres:`, …). The URL + * is parsed, so a path that contains `:` and `@` is not mistaken for a + * credential. + * + * @param text - The text. + * @returns The text with URL credentials redacted. + */ +function redactCredentialUrlsInText(text: string): string { + return text.replace(ANY_SCHEME_URL_IN_TEXT_PATTERN, (match) => { + let url: URL; + try { + url = new URL(match); + } catch { + return match; + } + if (url.username === '' && url.password === '') { + return match; + } + return `${url.protocol}//${REDACTED_VALUE}@${url.host}${url.pathname}${url.search}${url.hash}`; + }); +} + +/** + * Redacts JWTs and `Bearer` tokens anywhere in a text. Text without a match + * is returned unchanged. + * + * @param text - The text. + * @returns The text with tokens redacted. + */ +function redactTokensInText(text: string): string { + return text + .replace(BEARER_TOKEN_IN_TEXT_PATTERN, `$1${REDACTED_VALUE}`) + .replace(JWT_IN_TEXT_PATTERN, REDACTED_VALUE); +} + +/** + * Redacts every URL found in a text. A URL without secrets is kept as it + * appears, so normalizing it does not change the text. Trailing sentence + * punctuation is not part of the URL and is put back after redacting. + * + * @param text - The text. + * @returns The text with redacted URLs. + */ +export function redactUrlsInText(text: string): string { + return text.replace(URL_IN_TEXT_PATTERN, (match) => { + const length = trailingUrlPunctuationLength(match); + const suffix = length === 0 ? '' : match.slice(-length); + const url = length === 0 ? match : match.slice(0, -length); + const redacted = redactUrl(url); + return redacted.includes(REDACTED_VALUE) ? `${redacted}${suffix}` : match; + }); +} + +/** + * Redacts URLs and their credentials, JWTs and `Bearer` tokens in a text and + * cuts it to {@link MAX_RECORDED_TEXT_LENGTH} characters. + * + * @param text - The text, for example a console message. + * @returns The text safe to record. + */ +export function redactText(text: string): string { + const withoutUrls = redactUrlsInText(text); + return truncateText( + redactTokensInText(redactCredentialUrlsInText(withoutUrls)), + ); +} diff --git a/src/events/session-events.test.ts b/src/events/session-events.test.ts new file mode 100644 index 00000000..5f828d5b --- /dev/null +++ b/src/events/session-events.test.ts @@ -0,0 +1,127 @@ +import type { BrowserContext } from '@playwright/test'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { SessionEventSource } from './session-events.js'; +import { getSessionEvents, SessionEvents } from './session-events.js'; +import { getCdpManager } from '../platform/cdp-manager.js'; + +vi.mock('../platform/cdp-manager.js', () => ({ + getCdpManager: vi.fn(), +})); + +const getCdpManagerMock = vi.mocked(getCdpManager); + +/** + * Creates a source whose start resolves with a fake subscription. + * + * @returns The source and its unsubscribe mock. + */ +function createSource(): { + source: SessionEventSource & { start: ReturnType<typeof vi.fn> }; + unsubscribe: ReturnType<typeof vi.fn>; +} { + const unsubscribe = vi.fn().mockResolvedValue(undefined); + const source = { + start: vi.fn().mockResolvedValue({ unsubscribe }), + }; + return { source, unsubscribe }; +} + +describe('SessionEvents', () => { + beforeEach(() => { + getCdpManagerMock.mockReset(); + }); + + it('starts every source once per CDP manager', async () => { + const manager = { id: 1 }; + getCdpManagerMock.mockReturnValue(manager as never); + const { source } = createSource(); + const events = new SessionEvents({} as BrowserContext, [source]); + + await Promise.all([events.ensureStarted(), events.ensureStarted()]); + await events.ensureStarted(); + + expect(source.start).toHaveBeenCalledTimes(1); + expect(source.start).toHaveBeenCalledWith(manager, events); + }); + + it('restarts the sources on a new CDP manager, ending the old subscriptions', async () => { + getCdpManagerMock.mockReturnValueOnce({ id: 1 } as never); + const { source, unsubscribe } = createSource(); + const events = new SessionEvents({} as BrowserContext, [source]); + await events.ensureStarted(); + + const second = { id: 2 }; + getCdpManagerMock.mockReturnValue(second as never); + await events.ensureStarted(); + + expect(unsubscribe).toHaveBeenCalledTimes(1); + expect(source.start).toHaveBeenCalledTimes(2); + expect(source.start).toHaveBeenLastCalledWith(second, events); + }); + + it('unsubscribes subscriptions that finish after their manager was replaced', async () => { + const unsubscribeFirst = vi.fn().mockResolvedValue(undefined); + const unsubscribeSecond = vi.fn().mockResolvedValue(undefined); + let resolveFirstStart: (subscription: { + unsubscribe: () => Promise<void>; + }) => void = () => undefined; + const source = { + start: vi + .fn() + .mockImplementationOnce( + async () => + new Promise((resolve) => { + resolveFirstStart = resolve; + }), + ) + .mockResolvedValue({ unsubscribe: unsubscribeSecond }), + }; + const events = new SessionEvents({} as BrowserContext, [source]); + + getCdpManagerMock.mockReturnValue({ id: 1 } as never); + const firstRun = events.ensureStarted(); + + // The manager is replaced before the first source finishes starting. + getCdpManagerMock.mockReturnValue({ id: 2 } as never); + await events.ensureStarted(); + expect(source.start).toHaveBeenCalledTimes(2); + + resolveFirstStart({ unsubscribe: unsubscribeFirst }); + await firstRun; + + expect(unsubscribeFirst).toHaveBeenCalledTimes(1); + expect(unsubscribeSecond).not.toHaveBeenCalled(); + + // The manager-2 subscription is the one kept: no restart. + await events.ensureStarted(); + expect(source.start).toHaveBeenCalledTimes(2); + }); + + it('keeps the other sources when one fails to start', async () => { + getCdpManagerMock.mockReturnValueOnce({ id: 1 } as never); + const failing = { start: vi.fn().mockRejectedValue(new Error('boom')) }; + const { source, unsubscribe } = createSource(); + const events = new SessionEvents({} as BrowserContext, [failing, source]); + + expect(await events.ensureStarted()).toBeUndefined(); + + getCdpManagerMock.mockReturnValue({ id: 2 } as never); + await events.ensureStarted(); + expect(unsubscribe).toHaveBeenCalledTimes(1); + expect(failing.start).toHaveBeenCalledTimes(2); + }); +}); + +describe('getSessionEvents', () => { + it('returns one instance per browser context, with its own buffer', () => { + const first = {} as BrowserContext; + const second = {} as BrowserContext; + const events = getSessionEvents(first); + + expect(getSessionEvents(first)).toBe(events); + const other = getSessionEvents(second); + expect(other).not.toBe(events); + expect(other.buffer.startedAt).toBeGreaterThan(events.buffer.startedAt); + }); +}); diff --git a/src/events/session-events.ts b/src/events/session-events.ts new file mode 100644 index 00000000..05031670 --- /dev/null +++ b/src/events/session-events.ts @@ -0,0 +1,122 @@ +import type { BrowserContext } from '@playwright/test'; + +import { EventBuffer } from './event-buffer.js'; +import type { CdpManager, CdpSubscription } from '../platform/cdp-manager.js'; +import { getCdpManager } from '../platform/cdp-manager.js'; +import { debugWarn } from '../utils'; + +/** + * A producer of event records: it listens to CDP events of every page and + * the Extension service worker and writes records into the session buffer. + */ +export type SessionEventSource = { + /** + * Starts listening. Called once per CDP manager of the session. + * + * @param manager - The session's CDP manager. + * @param events - The session's events: its buffer and browser context. + * @returns The subscription to end when the session stops. + */ + start(manager: CdpManager, events: SessionEvents): Promise<CdpSubscription>; +}; + +/** + * The event buffer and event sources of one browser session. + */ +export class SessionEvents { + readonly buffer = new EventBuffer(); + + readonly context: BrowserContext; + + readonly #sources: SessionEventSource[]; + + #manager: CdpManager | undefined; + + #starting: Promise<void> | undefined; + + #subscriptions: CdpSubscription[] = []; + + /** + * @param context - The browser context of the session. + * @param sources - The sources that fill the buffer. + */ + constructor(context: BrowserContext, sources: SessionEventSource[]) { + this.context = context; + this.#sources = sources; + } + + /** + * Starts every source, once per CDP manager. Safe to call often: a call + * while the sources run does nothing. When the context's CDP manager was + * replaced (disposed and created again), the sources start on the new one. + * Failures are logged, never thrown: events are best-effort. + */ + async ensureStarted(): Promise<void> { + const manager = getCdpManager(this.context); + if (manager === this.#manager) { + await this.#starting; + return; + } + this.#manager = manager; + const previous = this.#subscriptions; + this.#subscriptions = []; + const starting = (async (): Promise<void> => { + await Promise.all( + previous.map(async (subscription) => + subscription.unsubscribe().catch(() => undefined), + ), + ); + const results = await Promise.allSettled( + this.#sources.map(async (source) => source.start(manager, this)), + ); + const started = results.flatMap((result) => { + if (result.status === 'fulfilled') { + return [result.value]; + } + debugWarn('session-events.start', result.reason); + return []; + }); + if (this.#manager !== manager) { + // The CDP manager was replaced while the sources started: these + // subscriptions belong to the old manager, not to this session. + await Promise.all( + started.map(async (subscription) => + subscription.unsubscribe().catch(() => undefined), + ), + ); + return; + } + this.#subscriptions = started; + })(); + this.#starting = starting; + await starting; + } +} + +/** + * Creates the sources of a new session. + * + * @returns The sources. + */ +function createSources(): SessionEventSource[] { + return []; +} + +const sessions = new WeakMap<BrowserContext, SessionEvents>(); + +/** + * Returns the events of a browser session, creating them (and a new buffer + * with a new `startedAt`) on first use. A relaunched session has a new + * browser context, so it gets a new buffer. + * + * @param context - The browser context of the session. + * @returns Its events. + */ +export function getSessionEvents(context: BrowserContext): SessionEvents { + let events = sessions.get(context); + if (!events) { + events = new SessionEvents(context, createSources()); + sessions.set(context, events); + } + return events; +} diff --git a/src/tools/events.test.ts b/src/tools/events.test.ts new file mode 100644 index 00000000..5e3c61b6 --- /dev/null +++ b/src/tools/events.test.ts @@ -0,0 +1,97 @@ +import type { BrowserContext } from '@playwright/test'; +import { describe, expect, it, vi } from 'vitest'; + +import { eventsTool } from './events.js'; +import { createMockSessionManager } from './test-utils/mock-factories.js'; +import { ErrorCodes } from './types/errors.js'; +import { getSessionEvents } from '../events/session-events.js'; +import type { ToolContext } from '../types/http.js'; + +vi.mock('../platform/cdp-manager.js', () => ({ + getCdpManager: vi.fn().mockReturnValue({}), +})); + +/** + * Builds a tool context around a fake browser context. + * + * @param hasActive - Whether a session is active. + * @returns The context and its browser context. + */ +function createContext(hasActive = true): { + context: ToolContext; + browserContext: BrowserContext; +} { + const browserContext = {} as BrowserContext; + const sessionManager = createMockSessionManager({ hasActive }); + sessionManager.getContext.mockReturnValue(browserContext); + return { + context: { sessionManager } as unknown as ToolContext, + browserContext, + }; +} + +describe('eventsTool', () => { + it('fails without a session', async () => { + const { context } = createContext(false); + const result = await eventsTool({ action: 'mark' }, context); + expect(result).toStrictEqual({ + ok: false, + error: { + code: ErrorCodes.MM_NO_ACTIVE_SESSION, + message: 'No active session. Call launch first.', + }, + }); + }); + + it('mark returns the current seq and the summary', async () => { + const { context, browserContext } = createContext(); + const { buffer } = getSessionEvents(browserContext); + buffer.append('console', { + t: 1, + target: { kind: 'sw', id: 'W', url: 'chrome-extension://x/bg.js' }, + }); + + const result = await eventsTool({ action: 'mark' }, context); + + expect(result).toStrictEqual({ + ok: true, + result: { + action: 'mark', + cursor: 1, + summary: { + startedAt: buffer.startedAt, + seq: 1, + counts: { console: 1, network: 0 }, + dropped: { console: 0, network: 0 }, + }, + }, + }); + }); + + it('clear empties one kind or all, keeping seq', async () => { + const { context, browserContext } = createContext(); + const { buffer } = getSessionEvents(browserContext); + const target = { kind: 'page' as const, id: 'P', url: 'about:blank' }; + buffer.append('console', { t: 1, target }); + buffer.append('network', { t: 1, target }); + + const one = await eventsTool({ action: 'clear', kind: 'network' }, context); + expect(one).toMatchObject({ + ok: true, + result: { + action: 'clear', + cleared: ['network'], + summary: { seq: 2, counts: { console: 1, network: 0 } }, + }, + }); + + const all = await eventsTool({ action: 'clear' }, context); + expect(all).toMatchObject({ + ok: true, + result: { + cleared: ['console', 'network'], + summary: { seq: 2, counts: { console: 0, network: 0 } }, + }, + }); + }); +}); diff --git a/src/tools/events.ts b/src/tools/events.ts new file mode 100644 index 00000000..efae4d2b --- /dev/null +++ b/src/tools/events.ts @@ -0,0 +1,44 @@ +import type { EventsInput, EventsResult } from './types'; +import { createToolSuccess, requireActiveSession } from './utils.js'; +import { getSessionEvents } from '../events/session-events.js'; +import type { ToolContext, ToolResponse } from '../types/http.js'; + +/** + * Bookmarks or clears the session event buffer (`mm events mark|clear`). + * + * `mark` returns the current cursor: pass it to `mm logs` and `mm network` + * later to read only what happened after it. `clear` empties one kind or + * every kind without resetting the cursor. + * + * @param input - The action. + * @param context - The tool execution context. + * @returns The cursor (mark) or the cleared kinds, with the buffer summary. + */ +export async function eventsTool( + input: EventsInput, + context: ToolContext, +): Promise<ToolResponse<EventsResult>> { + const missingSession = requireActiveSession<EventsResult>(context); + if (missingSession) { + return missingSession; + } + + const events = getSessionEvents(context.sessionManager.getContext()); + await events.ensureStarted(); + const { buffer } = events; + + if (input.action === 'clear') { + const cleared = buffer.clear(input.kind); + return createToolSuccess({ + action: 'clear', + cleared, + summary: buffer.summary(), + }); + } + + return createToolSuccess({ + action: 'mark', + cursor: buffer.seq, + summary: buffer.summary(), + }); +} diff --git a/src/tools/launch.test.ts b/src/tools/launch.test.ts index 5042e17e..025a268d 100644 --- a/src/tools/launch.test.ts +++ b/src/tools/launch.test.ts @@ -13,8 +13,15 @@ import { DriverLifecycle } from '../server/cleanup-session.js'; import type { SessionLaunchResult } from '../server/session-manager.js'; import { createMockSessionManager } from './test-utils/mock-factories.js'; import { ErrorCodes } from './types/errors.js'; +import { getSessionEvents } from '../events/session-events.js'; import type { ToolContext } from '../types/http.js'; +vi.mock('../events/session-events.js', () => ({ + getSessionEvents: vi.fn(), +})); + +const ensureStarted = vi.fn(); + function createMockContext( options: { hasActive?: boolean; @@ -33,6 +40,74 @@ function createMockContext( describe('launchTool', () => { beforeEach(() => { vi.clearAllMocks(); + ensureStarted.mockResolvedValue(undefined); + vi.mocked(getSessionEvents).mockReturnValue({ + ensureStarted, + } as unknown as ReturnType<typeof getSessionEvents>); + }); + + describe('session events', () => { + it('starts the session events of a browser session', async () => { + const context = createMockContext({ hasActive: false }); + const browserContext = {}; + vi.mocked(context.sessionManager.getContext).mockReturnValue( + browserContext as ReturnType<typeof context.sessionManager.getContext>, + ); + + const result = await launchTool({}, context); + + expect(result.ok).toBe(true); + expect(getSessionEvents).toHaveBeenCalledWith(browserContext); + expect(ensureStarted).toHaveBeenCalledTimes(1); + }); + + it('does not start them on mobile', async () => { + const context = createMockContext({ hasActive: false }); + context.sessionManager.getPlatformDriver = () => + ({ getPlatform: () => 'ios' }) as unknown as NonNullable< + ReturnType< + NonNullable<typeof context.sessionManager.getPlatformDriver> + > + >; + + await launchTool({ platform: 'ios' }, context); + + expect(getSessionEvents).not.toHaveBeenCalled(); + }); + + it('does not start them for a mobile launch input without a driver', async () => { + const context = createMockContext({ hasActive: false }); + + await launchTool({ platform: 'android' }, context); + + expect(getSessionEvents).not.toHaveBeenCalled(); + }); + + it('never fails the launch when they fail to start', async () => { + const context = createMockContext({ hasActive: false }); + vi.mocked(getSessionEvents).mockImplementation(() => { + throw new Error('no context'); + }); + + const result = await launchTool({}, context); + + expect(result.ok).toBe(true); + }); + + it('does not hold the launch on a slow start', async () => { + vi.useFakeTimers(); + try { + const context = createMockContext({ hasActive: false }); + ensureStarted.mockReturnValue(new Promise(() => undefined)); + + const launched = launchTool({}, context); + await vi.advanceTimersByTimeAsync(5_000); + + expect((await launched).ok).toBe(true); + } finally { + vi.useRealTimers(); + } + }); }); describe('successful launch', () => { diff --git a/src/tools/launch.ts b/src/tools/launch.ts index 4d7fd770..e2692f1a 100644 --- a/src/tools/launch.ts +++ b/src/tools/launch.ts @@ -1,11 +1,15 @@ import type { LaunchInput, LaunchPrerequisite, LaunchResult } from './types'; import { ErrorCodes } from './types'; import { createToolError, createToolSuccess } from './utils.js'; +import { getSessionEvents } from '../events/session-events.js'; import { cleanupSession } from '../server/cleanup-session.js'; import type { ISessionManager } from '../server/session-manager.js'; import type { ToolContext, ToolResponse } from '../types/http.js'; import { debugWarn, extractErrorMessage } from '../utils'; +/** How long a launch waits for the session event sources to attach. */ +const SESSION_EVENTS_START_WAIT_MS = 5_000; + const PROD_MODE_PREREQUISITES: LaunchPrerequisite[] = [ { step: 'Unlock Wallet', @@ -46,6 +50,42 @@ function applyHermesDefaults( }); } +/** + * Starts the session event buffer of a browser session (`mm logs`, + * `mm network`), so it records from launch on. Best-effort: a failure never + * fails the launch, and the next `events`/`logs`/`network` call retries. + * + * @param context - The tool execution context. + * @param input - The launch input. + */ +async function startSessionEvents( + context: ToolContext, + input: LaunchInput, +): Promise<void> { + try { + const platform = + context.sessionManager.getPlatformDriver?.()?.getPlatform() ?? + input.platform ?? + 'browser'; + if (platform !== 'browser') { + return; + } + const started = getSessionEvents( + context.sessionManager.getContext(), + ).ensureStarted(); + // Do not hold the launch on a slow attach: the sources keep starting. + let timer: ReturnType<typeof setTimeout> | undefined; + await Promise.race([ + started, + new Promise<void>((resolve) => { + timer = setTimeout(resolve, SESSION_EVENTS_START_WAIT_MS); + }), + ]).finally(() => clearTimeout(timer)); + } catch (error) { + debugWarn('launch.session-events', error); + } +} + /** * Launches a new browser session with the configured extension. * @@ -96,6 +136,7 @@ export async function launchTool( throw error; }); applyHermesDefaults(sessionManager, input); + await startSessionEvents(context, input); const isProdMode = sessionManager.getEnvironmentMode() === 'prod'; return createToolSuccess({ diff --git a/src/tools/mock-network.ts b/src/tools/mock-network.ts index f4ac53fd..03cc54dd 100644 --- a/src/tools/mock-network.ts +++ b/src/tools/mock-network.ts @@ -633,7 +633,7 @@ export function redactHeaders( * @param name - The JSON field name. * @returns True if the field value must be redacted. */ -function isSensitiveBodyField(name: string): boolean { +export function isSensitiveBodyField(name: string): boolean { return SENSITIVE_BODY_FIELDS.has(name.toLowerCase().replace(/[-_]/gu, '')); } diff --git a/src/tools/platform-gating.test.ts b/src/tools/platform-gating.test.ts index 549b1317..9637e292 100644 --- a/src/tools/platform-gating.test.ts +++ b/src/tools/platform-gating.test.ts @@ -14,6 +14,7 @@ describe('isBrowserOnlyTool', () => { expect(isBrowserOnlyTool('wait_for_notification')).toBe(true); expect(isBrowserOnlyTool('clipboard')).toBe(true); expect(isBrowserOnlyTool('mock_network')).toBe(true); + expect(isBrowserOnlyTool('events')).toBe(true); expect(isBrowserOnlyTool('reload')).toBe(true); expect(isBrowserOnlyTool('build')).toBe(true); expect(isBrowserOnlyTool('inspect')).toBe(true); diff --git a/src/tools/registry.test.ts b/src/tools/registry.test.ts index 433b2ba5..a26f9595 100644 --- a/src/tools/registry.test.ts +++ b/src/tools/registry.test.ts @@ -22,6 +22,7 @@ describe('toolRegistry', () => { 'describe_screen', 'clipboard', 'mock_network', + 'events', 'run_steps', 'cdp', 'hermes_targets', @@ -41,7 +42,7 @@ describe('toolRegistry', () => { }); it('has the expected number of entries', () => { - expect(toolRegistry.size).toBe(49); + expect(toolRegistry.size).toBe(50); }); it('stores only functions as values', () => { @@ -95,6 +96,10 @@ describe('TOOL_CATEGORIES and getToolCategory', () => { }, ); + it('getToolCategory returns readonly for events', () => { + expect(getToolCategory('events')).toBe('readonly'); + }); + it('getToolCategory returns readonly for get_context', () => { expect(getToolCategory('get_context')).toBe('readonly'); }); @@ -124,6 +129,7 @@ describe('isBrowserOnlyTool', () => { 'wait_for_notification', 'clipboard', 'mock_network', + 'events', 'reload', 'build', 'inspect', diff --git a/src/tools/registry.ts b/src/tools/registry.ts index e661968d..581d7c6a 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -27,6 +27,7 @@ import { describeScreenTool, listTestIdsTool, } from './discovery-tools.js'; +import { eventsTool } from './events.js'; import { hermesTargetsTool } from './hermes.js'; import { clickTool, @@ -98,6 +99,7 @@ export const toolRegistry = new Map<string, ToolFunction<any, any>>([ ['hermes_targets', hermesTargetsTool], ['get_window_size', getWindowSizeTool], ['mock_network', mockNetworkTool], + ['events', eventsTool], ['scroll_to_element', scrollToElementTool], ['device_swipe', deviceSwipeTool], ['long_press', longPressTool], @@ -165,7 +167,7 @@ export const TOOL_CATEGORIES: Record<string, ToolCategory> = { press_button: 'mutating', device_context: 'mutating', device_clipboard: 'mutating', - // READONLY (13) + // READONLY (14) hermes_targets: 'readonly', get_window_size: 'readonly', get_alert_text: 'readonly', @@ -182,6 +184,8 @@ export const TOOL_CATEGORIES: Record<string, ToolCategory> = { set_context: 'readonly', list_contracts: 'readonly', get_contract_address: 'readonly', + // `events clear` empties the session event buffer; it never touches the UI. + events: 'readonly', // DISCOVERY (4) describe_screen: 'discovery', list_testids: 'discovery', @@ -212,6 +216,7 @@ const BROWSER_ONLY_TOOLS = new Set([ 'wait_for_notification', 'clipboard', 'mock_network', + 'events', 'reload', 'build', 'inspect', diff --git a/src/tools/types/events.ts b/src/tools/types/events.ts new file mode 100644 index 00000000..d92f9535 --- /dev/null +++ b/src/tools/types/events.ts @@ -0,0 +1,60 @@ +/** + * Session event records: console messages (`mm logs`) and network requests + * (`mm network`), kept in one buffer per session with a shared cursor. + */ + +/** The record kinds of the session event buffer. */ +export type EventKind = 'console' | 'network'; + +/** The target a record came from. */ +export type EventRecordTarget = { + /** `page` (tab, popup, side panel), `sw` (Extension service worker), or `hermes` (mobile, later). */ + kind: 'page' | 'sw' | 'hermes'; + /** The CDP target ID. Chrome can reuse a service worker's ID after a restart. */ + id: string; + /** The target URL (redacted). */ + url: string; +}; + +/** Fields every record has. */ +export type EventRecordBase = { + /** + * Position in the session, shared by every kind. Starts at 1 for each new + * session and only grows. + */ + seq: number; + /** Time of the event (a request: its start), epoch ms. */ + t: number; + target: EventRecordTarget; +}; + +/** Buffer state, returned with every read and by `mm events mark`. */ +export type EventSummary = { + /** + * When this session's buffer started, epoch ms. It changes when the + * session is relaunched; cursors from before are then meaningless. + */ + startedAt: number; + /** The newest `seq` given out. Use it as a cursor. */ + seq: number; + /** Records kept now, by kind. */ + counts: Record<EventKind, number>; + /** Records dropped because the buffer was full, by kind. */ + dropped: Record<EventKind, number>; +}; + +/** One page of records. */ +export type EventPage<RecordType> = { + /** Oldest first. */ + records: RecordType[]; + /** Pass as `cursor` to the next read to continue without duplicates. */ + cursor: number; + /** More records match than `limit` allowed: read again with `cursor`. */ + hasMore: boolean; + /** + * Records after the given cursor (or `since`) were dropped, or the cursor + * was from another session (above the newest `seq`). + */ + gap: boolean; + summary: EventSummary; +}; diff --git a/src/tools/types/index.ts b/src/tools/types/index.ts index 2ed53aef..7ac8597e 100644 --- a/src/tools/types/index.ts +++ b/src/tools/types/index.ts @@ -5,3 +5,4 @@ export type * from './tool-outputs.js'; export * from './observation.js'; export * from './discovery.js'; export type * from './session.js'; +export type * from './events.js'; diff --git a/src/tools/types/tool-inputs.ts b/src/tools/types/tool-inputs.ts index c8530950..9e29b029 100644 --- a/src/tools/types/tool-inputs.ts +++ b/src/tools/types/tool-inputs.ts @@ -1,3 +1,4 @@ +import type { EventKind } from './events.js'; import type { SmartContractName } from './seeding.js'; export type TabRole = 'extension' | 'notification' | 'dapp' | 'other'; @@ -312,6 +313,10 @@ export type MockNetworkInput = includeBodies?: boolean; }; +export type EventsInput = + | { action: 'mark' } + | { action: 'clear'; kind?: EventKind }; + export type SetContextInput = { context: 'e2e' | 'prod'; options?: Record<string, unknown>; diff --git a/src/tools/types/tool-outputs.ts b/src/tools/types/tool-outputs.ts index b258ff8b..3b95fa3e 100644 --- a/src/tools/types/tool-outputs.ts +++ b/src/tools/types/tool-outputs.ts @@ -1,4 +1,5 @@ import type { TestIdItem, A11yNodeTrimmed } from './discovery.js'; +import type { EventKind, EventSummary } from './events.js'; import type { NetworkMockRequestRecord, NetworkMockRouteRule, @@ -285,6 +286,19 @@ export type MockNetworkResult = summary: NetworkMockSummary; }; +export type EventsResult = + | { + action: 'mark'; + /** Pass to `mm logs --cursor` and `mm network --cursor` later. */ + cursor: number; + summary: EventSummary; + } + | { + action: 'clear'; + cleared: EventKind[]; + summary: EventSummary; + }; + export type SetContextResult = { previousContext: 'e2e' | 'prod'; newContext: 'e2e' | 'prod'; diff --git a/src/validation/schemas.test.ts b/src/validation/schemas.test.ts index fd148c3a..b1c5b521 100644 --- a/src/validation/schemas.test.ts +++ b/src/validation/schemas.test.ts @@ -19,6 +19,7 @@ import { setViewportInputSchema, networkMockRouteRuleSchema, mockNetworkInputSchema, + eventsInputSchema, launchInputSchema, scrollToElementInputSchema, clickInputSchema, @@ -541,6 +542,26 @@ describe('network mock schemas', () => { }); }); +describe('eventsInputSchema', () => { + it('accepts mark and clear with an optional kind', () => { + expect(eventsInputSchema.safeParse({ action: 'mark' }).success).toBe(true); + expect(eventsInputSchema.safeParse({ action: 'clear' }).success).toBe(true); + expect( + eventsInputSchema.safeParse({ action: 'clear', kind: 'console' }).success, + ).toBe(true); + }); + + it('rejects an unknown kind, action or field', () => { + expect( + eventsInputSchema.safeParse({ action: 'clear', kind: 'dom' }).success, + ).toBe(false); + expect(eventsInputSchema.safeParse({ action: 'read' }).success).toBe(false); + expect( + eventsInputSchema.safeParse({ action: 'mark', cursor: 1 }).success, + ).toBe(false); + }); +}); + describe('launchInputSchema', () => { it('preserves platform field', () => { const input = { platform: 'ios' }; @@ -1152,6 +1173,7 @@ describe('observe field', () => { clipboard: { action: 'read' }, cdp: { method: 'Runtime.evaluate' }, mock_network: { action: 'list' }, + events: { action: 'mark' }, scroll_to_element: { testId: 'row' }, device_swipe: { direction: 'up' }, long_press: { testId: 'row' }, diff --git a/src/validation/schemas.ts b/src/validation/schemas.ts index 12cd8f9a..37016867 100644 --- a/src/validation/schemas.ts +++ b/src/validation/schemas.ts @@ -838,6 +838,30 @@ export const mockNetworkInputSchema = z.union([ }), ]); +export const eventKindSchema = z.enum(['console', 'network']); + +export const eventsInputSchema = z.discriminatedUnion('action', [ + z + .object({ + action: z + .literal('mark') + .describe( + 'Return the current cursor; pass it to logs/network --cursor later', + ), + }) + .strict(), + z + .object({ + action: z + .literal('clear') + .describe('Empty the buffer; the cursor keeps counting'), + kind: eventKindSchema + .describe('Only clear this kind (default: every kind)') + .optional(), + }) + .strict(), +]); + export const cdpInputSchema = z.object({ method: z .string() @@ -1095,6 +1119,7 @@ export type ClipboardInputZ = z.infer<typeof clipboardInputSchema>; export type CdpInputZ = z.infer<typeof cdpInputSchema>; export type HermesTargetsInputZ = z.infer<typeof hermesTargetsInputSchema>; export type MockNetworkInputZ = z.infer<typeof mockNetworkInputSchema>; +export type EventsInputZ = z.infer<typeof eventsInputSchema>; export type ScrollToElementInputZ = z.infer<typeof scrollToElementInputSchema>; export type DeviceSwipeInputZ = z.infer<typeof deviceSwipeInputSchema>; export type LongPressInputZ = z.infer<typeof longPressInputSchema>; @@ -1148,6 +1173,7 @@ export const toolSchemas = { hermes_targets: withObserve(hermesTargetsInputSchema), get_window_size: withObserve(getWindowSizeInputSchema), mock_network: withObserve(mockNetworkInputSchema), + events: withObserve(eventsInputSchema), scroll_to_element: withObserve(scrollToElementInputSchema), device_swipe: withObserve(deviceSwipeInputSchema), long_press: withObserve(longPressInputSchema), From 94291edd1771d869845b07332ce33e4a7f9854c5 Mon Sep 17 00:00:00 2001 From: cryptotavares <joao.tavares@consensys.net> Date: Fri, 20 Nov 2026 13:39:35 +0000 Subject: [PATCH 2/3] fix: bound the session event start and record source errors in the summary Review of #107, carried to #109: - ensureStarted waits at most 5 s (SESSION_EVENTS_START_WAIT_MS) for a start in progress. A start held by a target that does not answer no longer makes every later mm events/logs/network call hang on the stored promise. - SessionEvents.reportError records an event source error: it counts it in the buffer summary (captureErrors, lastCaptureError, redacted and cut at 300 characters) and writes it to the debug log. A source that fails to start is recorded the same way. --- SKILL.md | 2 +- src/events/event-buffer.test.ts | 14 ++++ src/events/event-buffer.ts | 19 ++++++ src/events/session-events.test.ts | 103 +++++++++++++++++++++++++++++- src/events/session-events.ts | 60 ++++++++++++++++- src/tools/events.test.ts | 1 + src/tools/types/events.ts | 9 +++ 7 files changed, 203 insertions(+), 5 deletions(-) diff --git a/SKILL.md b/SKILL.md index c9e8438c..ae6086d3 100644 --- a/SKILL.md +++ b/SKILL.md @@ -759,7 +759,7 @@ Returns `{ cursor, summary }`. Take it at the start of a flow. Empties the buffer (one kind or all). The cursor keeps counting, so older cursors stay valid. -`summary` is `{ startedAt, seq, counts: { console, network }, dropped: { console, network } }`. `startedAt` (epoch ms) changes when the session is relaunched; `seq` then starts at 1 again. The buffer keeps the newest 1000 console and 2000 network records; older ones are dropped and counted. +`summary` is `{ startedAt, seq, counts: { console, network }, dropped: { console, network }, captureErrors, lastCaptureError? }`. `startedAt` (epoch ms) changes when the session is relaunched; `seq` then starts at 1 again. The buffer keeps the newest 1000 console and 2000 network records; older ones are dropped and counted. `captureErrors` counts the times the session could not listen to a page or the service worker (for example a target that did not answer within 5 s, or a domain that could not be enabled); `lastCaptureError` is the newest one, redacted. When it grows during a flow, events of that target can be missing. A call that starts the recording waits at most 5 s for a target that does not answer. ### Mobile device actions (iOS/Android only) diff --git a/src/events/event-buffer.test.ts b/src/events/event-buffer.test.ts index a23070c5..6577226a 100644 --- a/src/events/event-buffer.test.ts +++ b/src/events/event-buffer.test.ts @@ -37,6 +37,7 @@ describe('EventBuffer', () => { seq: 3, counts: { console: 2, network: 1 }, dropped: { console: 0, network: 0 }, + captureErrors: 0, }); }); @@ -261,4 +262,17 @@ describe('EventBuffer', () => { const third = new EventBuffer(); expect(third.startedAt).toBeGreaterThan(second.startedAt); }); + + it('counts capture errors in the summary without taking a seq', () => { + const buffer = new EventBuffer(); + buffer.noteCaptureError('first'); + buffer.noteCaptureError('Runtime.enable on page x timed out after 5000ms'); + + expect(buffer.seq).toBe(0); + expect(buffer.summary()).toMatchObject({ + seq: 0, + captureErrors: 2, + lastCaptureError: 'Runtime.enable on page x timed out after 5000ms', + }); + }); }); diff --git a/src/events/event-buffer.ts b/src/events/event-buffer.ts index 2a0d0619..62e49537 100644 --- a/src/events/event-buffer.ts +++ b/src/events/event-buffer.ts @@ -65,6 +65,10 @@ export class EventBuffer { #seq = 0; + #captureErrors = 0; + + #lastCaptureError: string | undefined; + /** * @param options - Buffer options. * @param options.capacity - Records kept per kind; the oldest record of a @@ -196,6 +200,17 @@ export class EventBuffer { return kinds; } + /** + * Counts an error of an event source, reported in the summary. It takes + * no `seq`: it is not a record. + * + * @param message - The error text, already redacted. + */ + noteCaptureError(message: string): void { + this.#captureErrors += 1; + this.#lastCaptureError = message; + } + /** * @returns The buffer state. */ @@ -211,6 +226,10 @@ export class EventBuffer { console: this.#kinds.console.dropped, network: this.#kinds.network.dropped, }, + captureErrors: this.#captureErrors, + ...(this.#lastCaptureError === undefined + ? {} + : { lastCaptureError: this.#lastCaptureError }), }; } } diff --git a/src/events/session-events.test.ts b/src/events/session-events.test.ts index 5f828d5b..859020c5 100644 --- a/src/events/session-events.test.ts +++ b/src/events/session-events.test.ts @@ -2,7 +2,11 @@ import type { BrowserContext } from '@playwright/test'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { SessionEventSource } from './session-events.js'; -import { getSessionEvents, SessionEvents } from './session-events.js'; +import { + getSessionEvents, + SESSION_EVENTS_START_WAIT_MS, + SessionEvents, +} from './session-events.js'; import { getCdpManager } from '../platform/cdp-manager.js'; vi.mock('../platform/cdp-manager.js', () => ({ @@ -113,6 +117,103 @@ describe('SessionEvents', () => { }); }); +describe('SessionEvents start bound and errors', () => { + beforeEach(() => { + getCdpManagerMock.mockReset(); + }); + + /** + * Tracks whether a promise settled. + * + * @param promise - The promise. + * @returns Read `settled` later. + */ + function track(promise: Promise<unknown>): { settled: boolean } { + const state = { settled: false }; + promise + .finally(() => { + state.settled = true; + }) + .catch(() => undefined); + return state; + } + + it('does not hang later calls on a start that never finishes', async () => { + vi.useFakeTimers(); + try { + getCdpManagerMock.mockReturnValue({ id: 1 } as never); + const source = { + start: vi.fn(async () => new Promise<never>(() => undefined)), + }; + const events = new SessionEvents({} as BrowserContext, [source]); + + const first = track(events.ensureStarted()); + await vi.advanceTimersByTimeAsync(SESSION_EVENTS_START_WAIT_MS); + expect(first.settled).toBe(true); + + // The start is still running: a later call waits one bound, not + // forever, and does not start the sources again. + const later = track(events.ensureStarted()); + await vi.advanceTimersByTimeAsync(SESSION_EVENTS_START_WAIT_MS - 1); + expect(later.settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(later.settled).toBe(true); + expect(source.start).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + it('returns as soon as the sources started', async () => { + getCdpManagerMock.mockReturnValue({ id: 1 } as never); + const { source } = createSource(); + const events = new SessionEvents({} as BrowserContext, [source]); + + expect(await events.ensureStarted()).toBeUndefined(); + expect(source.start).toHaveBeenCalledTimes(1); + }); + + it('records a source that fails to start as a capture error', async () => { + getCdpManagerMock.mockReturnValue({ id: 1 } as never); + const failing = { + start: vi + .fn() + .mockRejectedValue( + new Error( + 'boom at https://mainnet.infura.io/v3/0123456789abcdef0123456789abcdef', + ), + ), + }; + const events = new SessionEvents({} as BrowserContext, [failing]); + + await events.ensureStarted(); + + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 1, + lastCaptureError: 'boom at https://mainnet.infura.io/v3/[REDACTED]', + }); + }); + + it('reportError counts, redacts and cuts an error, and never throws', () => { + const events = new SessionEvents({} as BrowserContext, []); + + events.reportError(new Error('x'.repeat(400))); + expect(events.buffer.summary().lastCaptureError).toBe( + `${'x'.repeat(300)}…`, + ); + events.reportError('plain text'); + expect(events.buffer.summary()).toMatchObject({ + captureErrors: 2, + lastCaptureError: 'plain text', + }); + + vi.spyOn(events.buffer, 'noteCaptureError').mockImplementation(() => { + throw new Error('buffer broken'); + }); + expect(() => events.reportError(new Error('y'))).not.toThrowError(); + }); +}); + describe('getSessionEvents', () => { it('returns one instance per browser context, with its own buffer', () => { const first = {} as BrowserContext; diff --git a/src/events/session-events.ts b/src/events/session-events.ts index 05031670..79ed8cfd 100644 --- a/src/events/session-events.ts +++ b/src/events/session-events.ts @@ -1,9 +1,20 @@ import type { BrowserContext } from '@playwright/test'; import { EventBuffer } from './event-buffer.js'; +import { redactText, truncateText } from './redact.js'; import type { CdpManager, CdpSubscription } from '../platform/cdp-manager.js'; import { getCdpManager } from '../platform/cdp-manager.js'; -import { debugWarn } from '../utils'; +import { debugWarn, extractErrorMessage } from '../utils'; + +/** + * How long a call waits for the sources to start. Each attach step of the + * CDP manager is bounded already; this caps the wait as a whole, so a call + * never hangs on a start that is still running. The start keeps going. + */ +export const SESSION_EVENTS_START_WAIT_MS = 5_000; + +/** Longest capture error text kept in the buffer summary. */ +const MAX_CAPTURE_ERROR_LENGTH = 300; /** * A producer of event records: it listens to CDP events of every page and @@ -45,13 +56,56 @@ export class SessionEvents { this.#sources = sources; } + /** + * Records an error of an event source: it is counted in the buffer + * summary (`captureErrors`, `lastCaptureError`) and written to the debug + * log. Sources pass it as the `onError` of their CDP subscription. Never + * throws. + * + * @param error - The error. + */ + readonly reportError = (error: unknown): void => { + try { + debugWarn('session-events.source', error); + this.buffer.noteCaptureError( + truncateText( + redactText(extractErrorMessage(error)), + MAX_CAPTURE_ERROR_LENGTH, + ), + ); + } catch { + // Error reporting must never break event dispatch. + } + }; + /** * Starts every source, once per CDP manager. Safe to call often: a call * while the sources run does nothing. When the context's CDP manager was * replaced (disposed and created again), the sources start on the new one. - * Failures are logged, never thrown: events are best-effort. + * Failures are recorded (see {@link reportError}), never thrown: events + * are best-effort. + * + * Waits at most {@link SESSION_EVENTS_START_WAIT_MS} for a start in + * progress, so a caller (`mm launch`, `mm logs`, …) never hangs on a + * target that does not answer; the start keeps going. */ async ensureStarted(): Promise<void> { + let timer: ReturnType<typeof setTimeout> | undefined; + await Promise.race([ + this.#start(), + new Promise<void>((resolve) => { + timer = setTimeout(resolve, SESSION_EVENTS_START_WAIT_MS); + }), + ]).finally(() => clearTimeout(timer)); + } + + /** + * Starts every source once per CDP manager, or returns the start in + * progress. + * + * @returns Settles when the sources started. Never rejects. + */ + async #start(): Promise<void> { const manager = getCdpManager(this.context); if (manager === this.#manager) { await this.#starting; @@ -73,7 +127,7 @@ export class SessionEvents { if (result.status === 'fulfilled') { return [result.value]; } - debugWarn('session-events.start', result.reason); + this.reportError(result.reason); return []; }); if (this.#manager !== manager) { diff --git a/src/tools/events.test.ts b/src/tools/events.test.ts index 5e3c61b6..c585c318 100644 --- a/src/tools/events.test.ts +++ b/src/tools/events.test.ts @@ -63,6 +63,7 @@ describe('eventsTool', () => { seq: 1, counts: { console: 1, network: 0 }, dropped: { console: 0, network: 0 }, + captureErrors: 0, }, }, }); diff --git a/src/tools/types/events.ts b/src/tools/types/events.ts index d92f9535..70a285eb 100644 --- a/src/tools/types/events.ts +++ b/src/tools/types/events.ts @@ -41,6 +41,15 @@ export type EventSummary = { counts: Record<EventKind, number>; /** Records dropped because the buffer was full, by kind. */ dropped: Record<EventKind, number>; + /** + * Errors of the event sources in this session: a page or the service + * worker that could not be attached in time, a domain that could not be + * enabled, a source that did not start. Events of that target can be + * missing from the reads. + */ + captureErrors: number; + /** The newest of those errors, redacted and cut at 300 characters. */ + lastCaptureError?: string; }; /** One page of records. */ From 9a87408ff5abe88fe31319fcc3990dc4f3045d36 Mon Sep 17 00:00:00 2001 From: cryptotavares <joao.tavares@consensys.net> Date: Mon, 23 Nov 2026 10:49:10 +0000 Subject: [PATCH 3/3] fix: redact a key value and drop the duplicate launch race - Redact a key-like query or fragment value even under a harmless name (isSecretUrlSegment/isOpaquePathKey), not only a JWT. - Remove the duplicate SESSION_EVENTS_START_WAIT_MS and the outer race in launch: ensureStarted already bounds the wait at 5 s and never rejects. --- src/events/redact.test.ts | 10 ++++++++++ src/events/redact.ts | 9 ++++++--- src/tools/launch.test.ts | 16 +++++----------- src/tools/launch.ts | 17 +++-------------- 4 files changed, 24 insertions(+), 28 deletions(-) diff --git a/src/events/redact.test.ts b/src/events/redact.test.ts index 1c6351a8..07bb0a22 100644 --- a/src/events/redact.test.ts +++ b/src/events/redact.test.ts @@ -75,6 +75,16 @@ describe('redactUrl', () => { 'https://x.io/p?data=eyJhbGciOiJub25lIn0.eyJzdWIiOiIxIn0.sig', `https://x.io/p?data=${REDACTED_VALUE}`, ], + [ + 'hex key value under a harmless name', + 'https://x.io/?data=0123456789abcdef0123456789abcdef', + `https://x.io/?data=${REDACTED_VALUE}`, + ], + [ + 'digitless key value under a harmless fragment name', + 'https://x.io/#state=AbCdEfGhIjKlMnOpQrStUvWxYzAbCdEf', + `https://x.io/#state=${REDACTED_VALUE}`, + ], [ '0x address kept', `https://api.example.com/accounts/${ADDRESS}/balances`, diff --git a/src/events/redact.ts b/src/events/redact.ts index 08980588..ffebd292 100644 --- a/src/events/redact.ts +++ b/src/events/redact.ts @@ -309,8 +309,9 @@ function redactParameters(parameters: string, prefix: '?' | '#'): string { /** * Redacts one `name=value` parameter when its name is sensitive or its value - * is a JWT. A bare part (no `=`) is redacted when it looks like a key, as in - * `#<jwt>`. + * looks like a key (a JWT, or an opaque segment such as an Infura project + * ID), even under a harmless name. A bare part (no `=`) is redacted when it + * looks like a key, as in `#<jwt>`. * * @param pair - The encoded parameter. * @returns The parameter with its value replaced, or the input. @@ -322,7 +323,9 @@ function redactPair(pair: string): string { } const name = decodeQueryName(pair.slice(0, separator)); const value = decodeQueryName(pair.slice(separator + 1)); - return isSensitiveQueryParam(name) || JWT_PATTERN.test(value) + return isSensitiveQueryParam(name) || + isSecretUrlSegment(value) || + isOpaquePathKey(value) ? `${pair.slice(0, separator)}=${REDACTED_VALUE}` : pair; } diff --git a/src/tools/launch.test.ts b/src/tools/launch.test.ts index 025a268d..7764aafc 100644 --- a/src/tools/launch.test.ts +++ b/src/tools/launch.test.ts @@ -94,19 +94,13 @@ describe('launchTool', () => { expect(result.ok).toBe(true); }); - it('does not hold the launch on a slow start', async () => { - vi.useFakeTimers(); - try { - const context = createMockContext({ hasActive: false }); - ensureStarted.mockReturnValue(new Promise(() => undefined)); + it('never fails the launch when the event start rejects', async () => { + const context = createMockContext({ hasActive: false }); + ensureStarted.mockRejectedValue(new Error('attach failed')); - const launched = launchTool({}, context); - await vi.advanceTimersByTimeAsync(5_000); + const result = await launchTool({}, context); - expect((await launched).ok).toBe(true); - } finally { - vi.useRealTimers(); - } + expect(result.ok).toBe(true); }); }); diff --git a/src/tools/launch.ts b/src/tools/launch.ts index e2692f1a..4e80f39a 100644 --- a/src/tools/launch.ts +++ b/src/tools/launch.ts @@ -7,9 +7,6 @@ import type { ISessionManager } from '../server/session-manager.js'; import type { ToolContext, ToolResponse } from '../types/http.js'; import { debugWarn, extractErrorMessage } from '../utils'; -/** How long a launch waits for the session event sources to attach. */ -const SESSION_EVENTS_START_WAIT_MS = 5_000; - const PROD_MODE_PREREQUISITES: LaunchPrerequisite[] = [ { step: 'Unlock Wallet', @@ -70,17 +67,9 @@ async function startSessionEvents( if (platform !== 'browser') { return; } - const started = getSessionEvents( - context.sessionManager.getContext(), - ).ensureStarted(); - // Do not hold the launch on a slow attach: the sources keep starting. - let timer: ReturnType<typeof setTimeout> | undefined; - await Promise.race([ - started, - new Promise<void>((resolve) => { - timer = setTimeout(resolve, SESSION_EVENTS_START_WAIT_MS); - }), - ]).finally(() => clearTimeout(timer)); + // `ensureStarted` is bounded (5 s) and never rejects: it does not hold + // the launch on a slow attach, and the sources keep starting. + await getSessionEvents(context.sessionManager.getContext()).ensureStarted(); } catch (error) { debugWarn('launch.session-events', error); }