rea-agents 2.4.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/README.md +91 -19
  2. package/bridge/ghidra/ReaGhidraBridge.java +524 -4
  3. package/bridge/hopper_bridge.py +313 -28
  4. package/dist/application/AnalysisClientCleanup.js +14 -0
  5. package/dist/application/AnalysisContextQueries.js +130 -0
  6. package/dist/application/AnalysisSnapshotCache.js +4 -2
  7. package/dist/application/ApplicationWorkflowEvidenceResolver.js +31 -13
  8. package/dist/application/ArtifactInventory/scanCanonical.js +1 -1
  9. package/dist/application/BinarySession.js +20 -8
  10. package/dist/application/BinarySessionComposition.js +21 -0
  11. package/dist/application/BinarySessionRecords.js +79 -9
  12. package/dist/application/BinarySessionStatus.js +31 -1
  13. package/dist/application/BrowserEvidence.js +14 -0
  14. package/dist/application/BrowserScenarioCapturePort.js +1 -0
  15. package/dist/application/BrowserScenarioCaptureService.js +53 -0
  16. package/dist/application/BrowserScenarioEvidence.js +40 -0
  17. package/dist/application/CallPathTracing.js +160 -0
  18. package/dist/application/CapabilityInventory.js +84 -14
  19. package/dist/application/ClientRegistrationStatus.js +4 -1
  20. package/dist/application/CompositeProvider.js +10 -1
  21. package/dist/application/DirectAnalysis.js +13 -4
  22. package/dist/application/EnhancedLiteralTracing.js +118 -0
  23. package/dist/application/EnhancedTools.js +71 -127
  24. package/dist/application/EvidenceLedger.js +45 -16
  25. package/dist/application/JavaScriptApplicationWorkflowEvidence.js +13 -0
  26. package/dist/application/JavaScriptApplicationWorkflowService.js +27 -1
  27. package/dist/application/JavaScriptArtifactAnalysis.js +13 -4
  28. package/dist/application/JavaScriptRuntimeObservationEvidence.js +34 -0
  29. package/dist/application/JavaScriptRuntimeObservationPort.js +1 -0
  30. package/dist/application/JavaScriptRuntimeObservationService.js +46 -0
  31. package/dist/application/JavaScriptSemanticGraphAsyncProjection.js +147 -0
  32. package/dist/application/JavaScriptSemanticGraphBuilder.js +34 -6
  33. package/dist/application/JavaScriptSemanticGraphChildProcessProjection.js +156 -0
  34. package/dist/application/JavaScriptSemanticGraphConstruction.js +2 -2
  35. package/dist/application/JavaScriptSemanticGraphDataProjection.js +203 -0
  36. package/dist/application/JavaScriptSemanticGraphFingerprintProjection.js +25 -0
  37. package/dist/application/JavaScriptSemanticGraphFlowProjection.js +129 -8
  38. package/dist/application/JavaScriptSemanticGraphObjectProjection.js +81 -0
  39. package/dist/application/JavaScriptSemanticGraphProjection.js +14 -7
  40. package/dist/application/JavaScriptSemanticGraphResourceProjection.js +59 -0
  41. package/dist/application/JavaScriptSemanticGraphValueProjection.js +77 -0
  42. package/dist/application/LazyAnalysisProvider.js +77 -0
  43. package/dist/application/LoopbackReplay.js +1 -1
  44. package/dist/application/NativeApiInspection.js +80 -0
  45. package/dist/application/ProcessReactiveEffects.js +6 -0
  46. package/dist/application/ProcessReactiveHarness.js +16 -1
  47. package/dist/application/ProjectPermissionStore.js +1 -0
  48. package/dist/application/ReconstructionObligationAuthority.js +72 -0
  49. package/dist/application/ReconstructionObligationCandidates.js +265 -0
  50. package/dist/application/ReconstructionObligationLedgerDiagnostics.js +47 -0
  51. package/dist/application/ReconstructionObligationLedgerEvaluation.js +263 -0
  52. package/dist/application/ReconstructionObligationLedgerProjection.js +86 -0
  53. package/dist/application/ReconstructionObligationLedgerService.js +72 -0
  54. package/dist/application/ReconstructionObligationOriginalCases.js +33 -0
  55. package/dist/application/ReconstructionObligationPolicies.js +132 -0
  56. package/dist/application/ReconstructionReadinessService.js +48 -0
  57. package/dist/application/SessionProviderRouter.js +6 -6
  58. package/dist/application/SetupClientConfiguration.js +4 -2
  59. package/dist/application/runtime.js +26 -9
  60. package/dist/artifacts/ArtifactProvider.js +87 -22
  61. package/dist/browser/BrowserScenarioSecrets.js +53 -0
  62. package/dist/browser/BrowserScenarioSessionPort.js +1 -0
  63. package/dist/browser/CdpBrowserProvider.js +2 -2
  64. package/dist/browser/CdpCaptureDocuments.js +57 -0
  65. package/dist/browser/CdpCaptureStorage.js +71 -29
  66. package/dist/browser/CdpCaptureStorageFingerprints.js +328 -0
  67. package/dist/browser/CdpEndpoint.js +8 -6
  68. package/dist/browser/CdpPageCapture.js +2 -0
  69. package/dist/browser/JavaScriptRuntimeScope.js +38 -0
  70. package/dist/browser/PlaywrightBrowserScenarioProvider.js +259 -0
  71. package/dist/browser/PlaywrightExecutionBoundary.js +42 -0
  72. package/dist/browser/PlaywrightScenarioActions.js +62 -0
  73. package/dist/browser/PlaywrightScenarioArtifacts.js +238 -0
  74. package/dist/browser/PlaywrightScenarioBrowser.js +144 -0
  75. package/dist/browser/PlaywrightScenarioEvents.js +301 -0
  76. package/dist/browser/PlaywrightScenarioSession.js +300 -0
  77. package/dist/browser/V8InspectorCaptureProjection.js +110 -0
  78. package/dist/browser/V8InspectorEndpoint.js +72 -0
  79. package/dist/browser/V8InspectorProvider.js +267 -0
  80. package/dist/catalogIdentity.js +11 -3
  81. package/dist/cli/artifactCommands.js +44 -3
  82. package/dist/cli/coreAnalysisCommands.js +78 -0
  83. package/dist/cli.js +4 -0
  84. package/dist/cliApplicationCommands.js +30 -2
  85. package/dist/cliBrowserAdvancedCommands.js +17 -5
  86. package/dist/cliBrowserCommands.js +1 -0
  87. package/dist/cliBrowserScenarioCommands.js +43 -0
  88. package/dist/cliCommandNames.js +9 -0
  89. package/dist/cliJavaScriptRuntimeCommands.js +164 -0
  90. package/dist/cliObservationOptions.js +4 -0
  91. package/dist/cliPolicyCommands.js +1 -0
  92. package/dist/config/environment.js +12 -0
  93. package/dist/config/parseConfig.js +88 -17
  94. package/dist/contracts/analysisSearchContract.js +14 -0
  95. package/dist/contracts/applicationToolContracts.js +86 -2
  96. package/dist/contracts/applicationWorkflowInputContracts.js +18 -0
  97. package/dist/contracts/artifactToolContracts.js +29 -2
  98. package/dist/contracts/browserProviderToolContracts.js +7 -0
  99. package/dist/contracts/browserScenarioToolContracts.js +81 -0
  100. package/dist/contracts/browserToolContracts.js +88 -98
  101. package/dist/contracts/enhancedInputs.js +35 -6
  102. package/dist/contracts/functionInstructionContract.js +8 -0
  103. package/dist/contracts/functionWorkflowToolContracts.js +30 -0
  104. package/dist/contracts/hopperMemoryContracts.js +22 -0
  105. package/dist/contracts/javascriptApplicationWorkflowExamples.js +42 -0
  106. package/dist/contracts/javascriptRuntimeObservationToolContracts.js +58 -0
  107. package/dist/contracts/promptContracts.js +14 -15
  108. package/dist/contracts/reconstructionReadinessExample.js +436 -0
  109. package/dist/contracts/toolContractExamples.js +8 -0
  110. package/dist/contracts/toolContractTypes.js +1 -0
  111. package/dist/contracts/toolContracts.js +34 -25
  112. package/dist/contracts/toolEffects.js +25 -0
  113. package/dist/contracts/toolOutputSchemaGroups.js +120 -30
  114. package/dist/contracts/toolOutputSchemaPrimitives.js +37 -0
  115. package/dist/domain/analysisErrorPresentation.js +8 -2
  116. package/dist/domain/analysisErrorProjection.js +9 -0
  117. package/dist/domain/artifactInspection.js +347 -0
  118. package/dist/domain/browserCaptureComparison.js +82 -0
  119. package/dist/domain/browserObservation.js +8 -1
  120. package/dist/domain/browserObservationErrors.js +1 -0
  121. package/dist/domain/browserObservationSchemas.js +26 -0
  122. package/dist/domain/browserScenario.js +165 -0
  123. package/dist/domain/browserScenarioCapture.js +57 -0
  124. package/dist/domain/browserScenarioCaptureValues.js +204 -0
  125. package/dist/domain/browserScenarioDiff.js +324 -0
  126. package/dist/domain/browserScenarioDiffValues.js +157 -0
  127. package/dist/domain/browserScenarioNormalization.js +45 -0
  128. package/dist/domain/browserScenarioValues.js +372 -0
  129. package/dist/domain/bytecodeProvider.js +179 -0
  130. package/dist/domain/conformancePackage.js +169 -0
  131. package/dist/domain/conformanceReplay.js +104 -0
  132. package/dist/domain/conformanceTrustGate.js +193 -0
  133. package/dist/domain/customProtocolCapture.js +137 -0
  134. package/dist/domain/eventProcessTree.js +214 -0
  135. package/dist/domain/evidenceBundle.js +47 -0
  136. package/dist/domain/hopperStartupFailure.js +1 -1
  137. package/dist/domain/hopperValues.js +14 -1
  138. package/dist/domain/inputIssueProjection.js +7 -1
  139. package/dist/domain/javascriptRuntimeObservation.js +170 -0
  140. package/dist/domain/javascriptRuntimeReconciliationParsing.js +120 -2
  141. package/dist/domain/javascriptRuntimeReconciliationResult.js +3 -3
  142. package/dist/domain/javascriptRuntimeReconciliationRuntime.js +2 -2
  143. package/dist/domain/javascriptRuntimeReconciliationSchemas.js +1 -1
  144. package/dist/domain/javascriptSemanticAnalysis.js +13 -16
  145. package/dist/domain/javascriptSemanticAsyncEffects.js +253 -0
  146. package/dist/domain/javascriptSemanticChildProcesses.js +237 -0
  147. package/dist/domain/javascriptSemanticDataEffectHelpers.js +125 -0
  148. package/dist/domain/javascriptSemanticDataEffects.js +284 -0
  149. package/dist/domain/javascriptSemanticDerivedAnalysis.js +41 -0
  150. package/dist/domain/javascriptSemanticFingerprints.js +174 -0
  151. package/dist/domain/javascriptSemanticIr.js +21 -1
  152. package/dist/domain/javascriptSemanticObjects.js +115 -0
  153. package/dist/domain/javascriptSemanticPromises.js +290 -0
  154. package/dist/domain/javascriptSemanticResources.js +136 -0
  155. package/dist/domain/javascriptSourceParser.js +15 -0
  156. package/dist/domain/javascriptStaticAnalysis.js +12 -15
  157. package/dist/domain/javascriptStaticAnalysisBundler.js +38 -0
  158. package/dist/domain/javascriptStaticAnalysisCalls.js +23 -1
  159. package/dist/domain/javascriptStaticAnalysisHelpers.js +8 -0
  160. package/dist/domain/mobileApplicationInvestigation.js +159 -0
  161. package/dist/domain/nativeApiBoundary.js +130 -0
  162. package/dist/domain/objcSwiftMetadata.js +150 -0
  163. package/dist/domain/packageAnalysis.js +123 -0
  164. package/dist/domain/peInspection.js +196 -0
  165. package/dist/domain/processCapture.js +8 -2
  166. package/dist/domain/processReactiveScenario.js +1 -0
  167. package/dist/domain/processReactiveTransition.js +9 -4
  168. package/dist/domain/protocolCapture.js +243 -0
  169. package/dist/domain/providerCleanupError.js +11 -0
  170. package/dist/domain/reconstructionObligationLedgerSchemas.js +278 -0
  171. package/dist/domain/reconstructionReadiness.js +121 -0
  172. package/dist/domain/reconstructionReadinessFindingHelpers.js +17 -0
  173. package/dist/domain/reconstructionReadinessIntegrityFindings.js +118 -0
  174. package/dist/domain/reconstructionReadinessJourneyFindings.js +193 -0
  175. package/dist/domain/reconstructionReadinessSchemas.js +240 -0
  176. package/dist/domain/sourceToBundleComparison.js +335 -0
  177. package/dist/domain/sourceToBundleComparisonSchemas.js +133 -0
  178. package/dist/domain/sourceToBundleSignals.js +202 -0
  179. package/dist/domain/webCaptureDiff.js +141 -27
  180. package/dist/domain/webScreenshot.js +1 -1
  181. package/dist/dotnet/ManagedStaticProvider.js +34 -5
  182. package/dist/generatedMcpToolCatalog.js +37 -0
  183. package/dist/generatedPackageMetadata.js +4 -4
  184. package/dist/ghidra/GhidraDefaults.js +1 -1
  185. package/dist/ghidra/GhidraFunctionValues.js +40 -2
  186. package/dist/ghidra/GhidraProviderCapabilities.js +47 -38
  187. package/dist/hopper/HopperCleanup.js +158 -0
  188. package/dist/hopper/HopperClient.js +93 -99
  189. package/dist/hopper/HopperProvider.js +61 -30
  190. package/dist/hopper/HopperRequestQueue.js +215 -0
  191. package/dist/hopper/HopperResponseStream.js +46 -0
  192. package/dist/hopper/protocol.js +63 -20
  193. package/dist/main/transport.js +24 -27
  194. package/dist/main.js +14 -6
  195. package/dist/mcpDoctor.js +27 -4
  196. package/dist/mcpStartupPolicy.js +14 -0
  197. package/dist/process/ProcessCommandIdentity.js +19 -0
  198. package/dist/process/ProcessOwnership.js +11 -8
  199. package/dist/server/DynamicToolAvailability.js +70 -0
  200. package/dist/server/LazyToolCatalog.js +134 -0
  201. package/dist/server/createServer.js +92 -154
  202. package/dist/server/hydrateServerTools.js +191 -0
  203. package/dist/server/lifecycleProgress.js +10 -0
  204. package/dist/server/permissionFailure.js +12 -0
  205. package/dist/server/registerApplicationTools/compareSourceToBundle.js +35 -0
  206. package/dist/server/registerApplicationTools/helpers.js +11 -7
  207. package/dist/server/registerApplicationTools/obligationLedger.js +27 -0
  208. package/dist/server/registerApplicationTools/readiness.js +55 -0
  209. package/dist/server/registerApplicationTools.js +6 -0
  210. package/dist/server/registerArtifactTools.js +9 -1
  211. package/dist/server/registerBrowserScenarioTool.js +25 -0
  212. package/dist/server/registerBrowserTools.js +2 -2
  213. package/dist/server/registerCloseLifecycleTool.js +57 -0
  214. package/dist/server/registerEnhancedTools.js +28 -7
  215. package/dist/server/registerEvidenceResources.js +54 -101
  216. package/dist/server/registerEvidenceTools.js +9 -2
  217. package/dist/server/registerInvestigationTools.js +1 -2
  218. package/dist/server/registerJavaScriptApplicationGraphResource.js +0 -4
  219. package/dist/server/registerJavaScriptRuntimeObservationTools.js +37 -0
  220. package/dist/server/registerReconstructionObligationLedgerResource.js +32 -0
  221. package/dist/server/registerReconstructionReadinessResource.js +32 -0
  222. package/dist/server/registerSessionRecordTools.js +82 -12
  223. package/dist/server/registerSessionStatusTool.js +11 -8
  224. package/dist/server/registerSessionTools.js +32 -58
  225. package/dist/server/sessionAvailabilityPolicy.js +10 -8
  226. package/dist/server/toolRegistrationOptions.js +21 -6
  227. package/dist/server/toolResult.js +12 -0
  228. package/package.json +28 -11
  229. package/scripts/package-runner-bootstrap.mjs +72 -0
  230. package/scripts/rea.mjs +11 -1
  231. package/skills/reverse-engineer-anything/SKILL.md +10 -3
@@ -0,0 +1,144 @@
1
+ import { chmod, mkdtemp, rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { chromium, } from "playwright-core";
5
+ import { BrowserObservationError } from "../domain/errors.js";
6
+ const OPERATION = "capture_browser_scenario";
7
+ const allowedBrowserEnvironment = (environment) => {
8
+ const allowed = [
9
+ "DBUS_SESSION_BUS_ADDRESS",
10
+ "DISPLAY",
11
+ "HOME",
12
+ "LANG",
13
+ "LD_LIBRARY_PATH",
14
+ "PATH",
15
+ "SystemRoot",
16
+ "TEMP",
17
+ "TMP",
18
+ "TMPDIR",
19
+ "WAYLAND_DISPLAY",
20
+ "XAUTHORITY",
21
+ "XDG_RUNTIME_DIR",
22
+ ];
23
+ return Object.fromEntries(allowed
24
+ .map((name) => [name, environment[name]])
25
+ .filter((entry) => entry[1] !== undefined));
26
+ };
27
+ const originAllowed = (value, allowedOrigins) => {
28
+ try {
29
+ return allowedOrigins.has(new URL(value).origin);
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ };
35
+ const findConnectedPage = async (browser, targetId, allowedOrigins) => {
36
+ for (const context of browser.contexts())
37
+ for (const page of context.pages()) {
38
+ const session = await context.newCDPSession(page);
39
+ try {
40
+ const { targetInfo } = await session.send("Target.getTargetInfo");
41
+ if (targetInfo.targetId !== targetId)
42
+ continue;
43
+ if (page.url() !== "about:blank" &&
44
+ !originAllowed(page.url(), allowedOrigins))
45
+ throw new BrowserObservationError(OPERATION, "target_not_allowed");
46
+ return { context, page };
47
+ }
48
+ finally {
49
+ await session.detach();
50
+ }
51
+ }
52
+ throw new BrowserObservationError(OPERATION, "target_not_found");
53
+ };
54
+ const configureAttachedEnvironment = async (context, page, scenario) => {
55
+ await page.setViewportSize({
56
+ width: scenario.environment.viewport.width,
57
+ height: scenario.environment.viewport.height,
58
+ });
59
+ await page.emulateMedia({
60
+ colorScheme: scenario.environment.color_scheme,
61
+ reducedMotion: scenario.environment.reduced_motion,
62
+ });
63
+ const session = await context.newCDPSession(page);
64
+ try {
65
+ await session.send("Emulation.setDeviceMetricsOverride", {
66
+ width: scenario.environment.viewport.width,
67
+ height: scenario.environment.viewport.height,
68
+ deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
69
+ mobile: false,
70
+ });
71
+ await session.send("Emulation.setLocaleOverride", {
72
+ locale: scenario.environment.locale,
73
+ });
74
+ await session.send("Emulation.setTimezoneOverride", {
75
+ timezoneId: scenario.environment.timezone,
76
+ });
77
+ }
78
+ finally {
79
+ await session.detach();
80
+ }
81
+ };
82
+ export const openPlaywrightScenarioBrowser = async (scenario, environment, maximumTimeoutMs) => {
83
+ if (scenario.browser.mode === "connect") {
84
+ const browser = await chromium.connectOverCDP(scenario.browser.cdp_endpoint, {
85
+ timeout: Math.min(scenario.limits.navigation_timeout_ms, maximumTimeoutMs),
86
+ });
87
+ try {
88
+ const target = await findConnectedPage(browser, scenario.browser.target_id, new Set(scenario.allowed_origins));
89
+ await configureAttachedEnvironment(target.context, target.page, scenario);
90
+ return { ...target, browser, profilePath: undefined };
91
+ }
92
+ catch (error) {
93
+ await browser.close();
94
+ throw error;
95
+ }
96
+ }
97
+ const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
98
+ await chmod(profilePath, 0o700);
99
+ try {
100
+ const context = await chromium.launchPersistentContext(profilePath, {
101
+ executablePath: scenario.browser.executable_path,
102
+ headless: true,
103
+ acceptDownloads: false,
104
+ viewport: {
105
+ width: scenario.environment.viewport.width,
106
+ height: scenario.environment.viewport.height,
107
+ },
108
+ deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
109
+ locale: scenario.environment.locale,
110
+ timezoneId: scenario.environment.timezone,
111
+ colorScheme: scenario.environment.color_scheme,
112
+ reducedMotion: scenario.environment.reduced_motion,
113
+ serviceWorkers: "block",
114
+ env: allowedBrowserEnvironment(environment),
115
+ handleSIGHUP: false,
116
+ handleSIGINT: false,
117
+ handleSIGTERM: false,
118
+ timeout: maximumTimeoutMs,
119
+ });
120
+ const browser = context.browser();
121
+ if (browser === null) {
122
+ await context.close();
123
+ throw new BrowserObservationError(OPERATION, "protocol_error");
124
+ }
125
+ const page = context.pages()[0] ?? (await context.newPage());
126
+ return { context, page, browser, profilePath };
127
+ }
128
+ catch (error) {
129
+ await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
130
+ throw error;
131
+ }
132
+ };
133
+ export const closePlaywrightScenarioBrowser = async ({ context, browser, profilePath, }) => {
134
+ try {
135
+ if (profilePath === undefined)
136
+ await browser.close();
137
+ else
138
+ await context.close();
139
+ }
140
+ finally {
141
+ if (profilePath !== undefined)
142
+ await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
143
+ }
144
+ };
@@ -0,0 +1,301 @@
1
+ import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
2
+ import { browserScenarioEventSchema, } from "../domain/browserScenarioCapture.js";
3
+ /** Bounded, arrival-ordered Playwright event capture with current-step attribution. */
4
+ export class PlaywrightScenarioEvents {
5
+ items = [];
6
+ truncated = new Set();
7
+ admitted = {
8
+ frames: new WeakSet(),
9
+ workers: new WeakSet(),
10
+ popups: new WeakSet(),
11
+ websockets: new WeakSet(),
12
+ };
13
+ rejected = {
14
+ frames: new WeakSet(),
15
+ workers: new WeakSet(),
16
+ popups: new WeakSet(),
17
+ websockets: new WeakSet(),
18
+ };
19
+ counts = {
20
+ frames: 0,
21
+ workers: 0,
22
+ popups: 0,
23
+ websockets: 0,
24
+ };
25
+ dropped = 0;
26
+ stepIndex = 0;
27
+ sequence = 0;
28
+ enabled;
29
+ limits;
30
+ secrets;
31
+ budget;
32
+ allowedOrigins;
33
+ constructor(options) {
34
+ this.enabled = options.enabled;
35
+ this.limits = options.limits;
36
+ this.secrets = options.secrets;
37
+ this.budget = options.budget;
38
+ this.allowedOrigins = new Set(options.allowedOrigins);
39
+ this.observePage(options.page);
40
+ }
41
+ setStep(index) {
42
+ this.stepIndex = index;
43
+ }
44
+ nextSequence() {
45
+ return this.sequence + 1;
46
+ }
47
+ lastSequence() {
48
+ return this.sequence;
49
+ }
50
+ result() {
51
+ return {
52
+ retained: this.items.length,
53
+ dropped: this.dropped,
54
+ items: this.items,
55
+ };
56
+ }
57
+ truncationSections() {
58
+ return [...this.truncated].sort();
59
+ }
60
+ push(event) {
61
+ this.sequence += 1;
62
+ if (this.items.length >= this.limits.max_events) {
63
+ this.dropped += 1;
64
+ this.truncated.add("events");
65
+ return;
66
+ }
67
+ const parsed = browserScenarioEventSchema.parse({
68
+ ...event,
69
+ sequence: this.sequence,
70
+ step_index: this.stepIndex,
71
+ });
72
+ if (!this.budget.claimMetadata(Buffer.byteLength(JSON.stringify(parsed)))) {
73
+ this.dropped += 1;
74
+ this.truncated.add("events");
75
+ return;
76
+ }
77
+ this.items.push(parsed);
78
+ }
79
+ admit(section, value, maximum) {
80
+ if (this.admitted[section].has(value))
81
+ return true;
82
+ if (this.rejected[section].has(value))
83
+ return false;
84
+ if (this.counts[section] >= maximum) {
85
+ this.rejected[section].add(value);
86
+ this.sequence += 1;
87
+ this.dropped += 1;
88
+ this.truncated.add("events");
89
+ this.truncated.add(section);
90
+ return false;
91
+ }
92
+ this.admitted[section].add(value);
93
+ this.counts[section] += 1;
94
+ return true;
95
+ }
96
+ observePage(page) {
97
+ if (this.enabled.has("console"))
98
+ page.on("console", (message) => {
99
+ if (this.pageInScope(page))
100
+ this.console(message);
101
+ });
102
+ if (this.enabled.has("page-errors"))
103
+ page.on("pageerror", (error) => {
104
+ if (this.pageInScope(page))
105
+ this.push({
106
+ kind: "page-error",
107
+ message: this.secrets.redact(error.message).slice(0, 65_536),
108
+ stack: error.stack === undefined
109
+ ? null
110
+ : this.secrets.redact(error.stack).slice(0, 262_144),
111
+ });
112
+ });
113
+ if (this.enabled.has("network")) {
114
+ page.on("request", (request) => {
115
+ if (this.pageInScope(page))
116
+ this.request("request", request);
117
+ });
118
+ page.on("response", (response) => {
119
+ if (this.pageInScope(page))
120
+ this.response(response);
121
+ });
122
+ page.on("requestfailed", (request) => {
123
+ if (this.pageInScope(page))
124
+ this.request("request-failed", request);
125
+ });
126
+ }
127
+ if (this.enabled.has("websockets"))
128
+ page.on("websocket", (socket) => {
129
+ if (this.pageInScope(page))
130
+ this.webSocket(page, socket);
131
+ });
132
+ if (this.enabled.has("frames")) {
133
+ page.on("frameattached", (frame) => {
134
+ if (this.pageInScope(page))
135
+ this.frame("frame-attached", frame);
136
+ });
137
+ page.on("framedetached", (frame) => {
138
+ if (this.pageInScope(page))
139
+ this.frame("frame-detached", frame);
140
+ });
141
+ page.on("framenavigated", (frame) => {
142
+ if (this.pageInScope(page))
143
+ this.frame("frame-navigated", frame);
144
+ });
145
+ }
146
+ if (this.enabled.has("workers"))
147
+ page.on("worker", (worker) => {
148
+ if (this.pageInScope(page))
149
+ this.worker(page, worker);
150
+ });
151
+ if (this.enabled.has("popups"))
152
+ page.on("popup", (popup) => {
153
+ if (this.pageInScope(page))
154
+ this.popup(popup);
155
+ });
156
+ if (this.enabled.has("downloads"))
157
+ page.on("download", (download) => {
158
+ if (this.pageInScope(page))
159
+ this.download(download);
160
+ });
161
+ }
162
+ pageInScope(page) {
163
+ try {
164
+ return this.allowedOrigins.has(new URL(page.url()).origin);
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ }
170
+ safeUrl(value) {
171
+ return sanitizeBrowserUrl(this.secrets.redact(value));
172
+ }
173
+ console(message) {
174
+ const location = message.location();
175
+ this.push({
176
+ kind: "console",
177
+ level: this.secrets.redact(message.type()).slice(0, 64),
178
+ text: this.secrets.redact(message.text()).slice(0, 65_536),
179
+ url: location.url === "" ? null : this.safeUrl(location.url),
180
+ });
181
+ }
182
+ request(kind, request) {
183
+ this.push({
184
+ kind,
185
+ method: this.secrets.redact(request.method()).slice(0, 32),
186
+ url: this.safeUrl(request.url()),
187
+ resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
188
+ status: null,
189
+ header_names: Object.keys(request.headers())
190
+ .map((name) => this.secrets.redact(name).slice(0, 256))
191
+ .sort()
192
+ .slice(0, 256),
193
+ failure: kind === "request-failed"
194
+ ? this.secrets
195
+ .redact(request.failure()?.errorText ?? "unknown")
196
+ .slice(0, 1_024)
197
+ : null,
198
+ });
199
+ }
200
+ response(response) {
201
+ const request = response.request();
202
+ this.push({
203
+ kind: "response",
204
+ method: this.secrets.redact(request.method()).slice(0, 32),
205
+ url: this.safeUrl(response.url()),
206
+ resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
207
+ status: response.status(),
208
+ header_names: Object.keys(response.headers())
209
+ .map((name) => this.secrets.redact(name).slice(0, 256))
210
+ .sort()
211
+ .slice(0, 256),
212
+ failure: null,
213
+ });
214
+ }
215
+ webSocket(page, socket) {
216
+ if (!this.admit("websockets", socket, this.limits.max_websockets))
217
+ return;
218
+ const url = this.safeUrl(socket.url());
219
+ this.push({ kind: "websocket-opened", url });
220
+ socket.on("framesent", ({ payload }) => {
221
+ if (this.pageInScope(page))
222
+ this.webSocketFrame("websocket-frame-sent", url, payload);
223
+ });
224
+ socket.on("framereceived", ({ payload }) => {
225
+ if (this.pageInScope(page))
226
+ this.webSocketFrame("websocket-frame-received", url, payload);
227
+ });
228
+ socket.on("close", () => {
229
+ if (this.pageInScope(page))
230
+ this.push({ kind: "websocket-closed", url });
231
+ });
232
+ }
233
+ webSocketFrame(kind, url, payload) {
234
+ const bytes = Buffer.byteLength(payload);
235
+ const isText = typeof payload === "string";
236
+ const text = isText ? this.secrets.redact(payload).slice(0, 65_536) : null;
237
+ this.push({
238
+ kind,
239
+ url,
240
+ payload_type: isText ? "text" : "binary",
241
+ payload_bytes: bytes,
242
+ payload_text: text,
243
+ truncated: isText && text !== null && text.length < payload.length,
244
+ });
245
+ }
246
+ frame(kind, frame) {
247
+ if (!this.admit("frames", frame, this.limits.max_frames))
248
+ return;
249
+ this.push({
250
+ kind,
251
+ url: frame.url() === "" ? null : this.safeUrl(frame.url()),
252
+ name: frame.name() === ""
253
+ ? null
254
+ : this.secrets.redact(frame.name()).slice(0, 1_024),
255
+ });
256
+ }
257
+ worker(page, worker) {
258
+ if (!this.admit("workers", worker, this.limits.max_workers))
259
+ return;
260
+ const details = {
261
+ url: this.safeUrl(worker.url()),
262
+ name: null,
263
+ };
264
+ this.push({ kind: "worker-created", ...details });
265
+ worker.on("close", () => {
266
+ if (this.pageInScope(page))
267
+ this.push({ kind: "worker-closed", ...details });
268
+ });
269
+ }
270
+ popup(page) {
271
+ if (!this.pageInScope(page)) {
272
+ void page.close().catch(() => undefined);
273
+ return;
274
+ }
275
+ if (!this.admit("popups", page, this.limits.max_popups))
276
+ return;
277
+ const opened = {
278
+ url: page.url() === "" ? null : this.safeUrl(page.url()),
279
+ name: null,
280
+ };
281
+ this.push({ kind: "popup-opened", ...opened });
282
+ page.on("close", () => this.pageInScope(page)
283
+ ? this.push({
284
+ kind: "popup-closed",
285
+ url: page.url() === "" ? null : this.safeUrl(page.url()),
286
+ name: null,
287
+ })
288
+ : undefined);
289
+ this.observePage(page);
290
+ }
291
+ download(download) {
292
+ this.push({
293
+ kind: "download-cancelled",
294
+ suggested_filename: this.secrets
295
+ .redact(download.suggestedFilename())
296
+ .slice(0, 1_024),
297
+ url: this.safeUrl(download.url()),
298
+ });
299
+ void download.cancel().catch(() => undefined);
300
+ }
301
+ }