@johnhenry/mallory-cli 0.0.0-stage → 0.1.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.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,1138 @@
|
|
|
1
|
+
// The http pane's engine (src/panes/http.js): HTTP messages as values, no network. Pure: no DOM, no storage, no timers, and nothing
|
|
2
|
+
// here reaches a socket (test/http-pane.test.mjs runs every mode with fetch, XMLHttpRequest, WebSocket and EventSource made to throw,
|
|
3
|
+
// and scans this file and the pane's others for them).
|
|
4
|
+
//
|
|
5
|
+
// convert a curl command, a fetch(…) call, a raw HTTP request, a HAR file or a request object -> a request value + curl / fetch / HAR / raw text
|
|
6
|
+
// compose fields (method, url, headers, query, body; a wired input overrides one) -> a request value + text
|
|
7
|
+
// diff two requests (any of the above) -> what differs: the request line, the header set, the body (JSON paths or lines)
|
|
8
|
+
// rewrite rules (set / remove a header, change the path, the query, the body…) applied to a request
|
|
9
|
+
//
|
|
10
|
+
// A request value is { method, url, headers: { "lowercase-name": "value" }, body? }. Credentials never leave this module in the clear:
|
|
11
|
+
// a header like Authorization, Cookie or X-Api-Key, a key in a URL's user:pass@ or in its query (?api_key=…) comes out as "[redacted]"
|
|
12
|
+
// unless it is a secret() placeholder (mallory-secret:NAME, which the page fills in only where a request is made). The same goes for
|
|
13
|
+
// every text and for the diff, so neither the pane's value, a WebMCP snapshot nor the run log holds one. A literal credential is also
|
|
14
|
+
// refused in the settings (httpProblem), because the settings are saved in the canvas.
|
|
15
|
+
import * as converter from "@johnhenry/http-converter";
|
|
16
|
+
import { detectType } from "@johnhenry/http-converter/core/utils";
|
|
17
|
+
import * as stringLib from "@johnhenry/http-converter/string";
|
|
18
|
+
import * as curlLib from "@johnhenry/http-converter/curl";
|
|
19
|
+
import * as fetchLib from "@johnhenry/http-converter/fetch";
|
|
20
|
+
import * as harLib from "@johnhenry/http-converter/har";
|
|
21
|
+
import { cleanProxy, proxyProblem } from "./proxy.js";
|
|
22
|
+
import { compileSafeRegex, slashRegex, slashRegexProblem, SAFE_REGEX_LIMITS } from "./safe-regex.js";
|
|
23
|
+
import { REDACTED, SECRET_SHAPES, isCredentialHeader, isCredentialParam, isPlaceholderValue, redactBody, redactHeaderValue, redactHeaders, redactUrl } from "../security/redact.js";
|
|
24
|
+
|
|
25
|
+
const SHAPES = SECRET_SHAPES.map((r) => new RegExp(r.pattern, r.flags.replace("g", "")));
|
|
26
|
+
/** Does a header value look like a key by its shape (Bearer …, sk-…, ghp_…), and is not wholly a placeholder? */
|
|
27
|
+
const keyShaped = (value) => !isPlaceholderValue(value) && SHAPES.some((re) => re.test(String(value)));
|
|
28
|
+
|
|
29
|
+
export { REDACTED, isCredentialHeader, isCredentialParam, redactUrl };
|
|
30
|
+
|
|
31
|
+
export const HTTP_MODES = ["convert", "compose", "diff", "rewrite", "send", "tap", "proxy", "static"];
|
|
32
|
+
// Send mode (src/model/http-send.js) keeps its limits here, with the other settings; this file only cleans and checks them.
|
|
33
|
+
// The tap mode's settings (src/model/http-tap.js, #846): whether bodies are kept (a person's setting, like send.auto), how many bytes of each, how many entries show.
|
|
34
|
+
export const TAP_LIMITS = Object.freeze({ bodyBytes: [256, 1048576], limit: [1, 500] }); // 1 MiB is prism's `--max-body-size` default; 4 KiB stays ours (page memory), and the ring bounds the total
|
|
35
|
+
export const TAP_DEFAULTS = Object.freeze({ bodies: false, bodyBytes: 4096, limit: 100 });
|
|
36
|
+
export const SEND_LIMITS = Object.freeze({ timeoutMs: [100, 120000], maxBytes: [1024, 1048576] });
|
|
37
|
+
/** Where a send goes: the page's own network policy (the default), or the person's paired companion's http-tap module (prism T4, #850). */
|
|
38
|
+
export const SEND_VIAS = ["page", "companion"];
|
|
39
|
+
export const TARGETS = ["curl", "fetch", "har", "raw"];
|
|
40
|
+
export const TARGET_LABELS = { curl: "cURL", fetch: "fetch()", har: "HAR", raw: "raw HTTP" };
|
|
41
|
+
export const REQUEST_OPS = ["set-header", "remove-header", "set-method", "set-url", "set-path", "replace-path", "set-query", "remove-query", "set-body", "replace-body"];
|
|
42
|
+
/** Rules for a RESPONSE (prism parity RWR-02): override its status, set or remove a header, replace its body or patch a JSON path of it. */
|
|
43
|
+
export const RESPONSE_OPS = ["set-status", "set-status-text", "set-response-header", "remove-response-header", "set-response-body", "replace-response-body", "set-response-json", "remove-response-json"];
|
|
44
|
+
export const REWRITE_OPS = [...REQUEST_OPS, ...RESPONSE_OPS];
|
|
45
|
+
export const MAX_TEXT_CHARS = 1048576; // the text one pane reads or writes
|
|
46
|
+
export const MAX_ENTRIES = 200; // requests in one HAR
|
|
47
|
+
export const MAX_HEADERS = 100;
|
|
48
|
+
export const MAX_DIFF_DEPTH = 64; // jsonDiff's recursion limit
|
|
49
|
+
export const MAX_RAW_HEADER_LINES = 200; // header lines in a raw HTTP request, counted BEFORE the converter parses it (#949)
|
|
50
|
+
export const MAX_HAR_HEADERS = 1000; // headers in one HAR entry's request
|
|
51
|
+
export const MAX_RULES = 50;
|
|
52
|
+
export const MAX_BODY_DIFF_LINES = 2000; // beyond this the line diff keeps the common start and end and says the middle changed
|
|
53
|
+
|
|
54
|
+
const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
55
|
+
const METHOD = /^[A-Z]{3,10}$/;
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
const hasPlaceholder = isPlaceholderValue; // the whole value, not a value that merely mentions one (src/security/redact.js)
|
|
59
|
+
const one = (value) => (Array.isArray(value) ? value.join(", ") : String(value ?? ""));
|
|
60
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
61
|
+
|
|
62
|
+
// ── credentials ──────────────────────────────────────────────────────────────
|
|
63
|
+
|
|
64
|
+
/** A request with every credential header value, URL credential and credential body field replaced by "[redacted]". Returns { request, redacted: [header and URL names] }. */
|
|
65
|
+
export function redactRequest(request) {
|
|
66
|
+
const { headers, redacted } = redactHeaders(request.headers ?? {});
|
|
67
|
+
const u = redactUrl(request.url);
|
|
68
|
+
redacted.push(...u.redacted);
|
|
69
|
+
let body = request.body;
|
|
70
|
+
if (typeof body === "string") {
|
|
71
|
+
const type = Object.entries(headers).find(([n]) => n.toLowerCase() === "content-type")?.[1] ?? "";
|
|
72
|
+
const shown = redactBody(body, String(type));
|
|
73
|
+
body = shown; // a body field is taken out of what is shown, but is not listed in `redacted`: a body may carry a login the person means to send
|
|
74
|
+
}
|
|
75
|
+
return { request: { method: request.method, url: u.url, headers, ...(body !== undefined ? { body } : {}) }, redacted: [...new Set(redacted)] };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ── reading any form into a request ──────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
const LOOPBACK = /^(localhost|127(\.\d{1,3}){3}|\[::1\])(:\d+)?$/i;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Refuse raw HTTP with too many header lines BEFORE the converter's parser sees it: that parser is quadratic in repeated same-name
|
|
84
|
+
* headers (a 1 MB paste stalled the page for minutes, #949). A linear scan from the request line to the first blank line.
|
|
85
|
+
*/
|
|
86
|
+
export function checkRawHeaderLines(text, max = MAX_RAW_HEADER_LINES) {
|
|
87
|
+
const s = String(text);
|
|
88
|
+
let count = 0;
|
|
89
|
+
let at = s.indexOf("\n");
|
|
90
|
+
while (at >= 0) {
|
|
91
|
+
const next = s.indexOf("\n", at + 1);
|
|
92
|
+
const end = next < 0 ? s.length : next;
|
|
93
|
+
if (/^\s*$/.test(s.slice(at + 1, end))) break; // the blank line ends the head
|
|
94
|
+
if (end > at + 1 && ++count > max) throw new Error(`a request has at most ${max} headers`);
|
|
95
|
+
at = next;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Refuse a HAR entry with more headers than MAX_HAR_HEADERS before the converter reads it. */
|
|
100
|
+
export function checkHarHeaders(request, max = MAX_HAR_HEADERS) {
|
|
101
|
+
if (Array.isArray(request?.headers) && request.headers.length > max) throw new Error(`a request has at most ${max} headers`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** One request object as { method, url, headers (lowercase names), body? }. */
|
|
105
|
+
function shape(raw) {
|
|
106
|
+
if (!isObject(raw)) throw new Error("a request is an object with a url");
|
|
107
|
+
let url = String(raw.url ?? "");
|
|
108
|
+
const headers = Object.create(null); // header names are data: "constructor" and "__proto__" are ordinary names (#950 F6)
|
|
109
|
+
const source = raw.headers;
|
|
110
|
+
if (Array.isArray(source)) {
|
|
111
|
+
for (const h of source) if (h && h.name !== undefined) add(headers, h.name, h.value);
|
|
112
|
+
} else if (isObject(source)) {
|
|
113
|
+
for (const [name, value] of Object.entries(source)) add(headers, name, value);
|
|
114
|
+
}
|
|
115
|
+
if (url && !/^[a-z][a-z0-9+.-]*:\/\//i.test(url) && url.startsWith("/") && headers.host) {
|
|
116
|
+
const host = headers.host;
|
|
117
|
+
url = `${LOOPBACK.test(host) ? "http" : "https"}://${host}${url}`;
|
|
118
|
+
}
|
|
119
|
+
const method = String(raw.method || "GET").toUpperCase();
|
|
120
|
+
if (!METHOD.test(method)) throw new Error(`"${method.slice(0, 20)}" isn't an HTTP method`);
|
|
121
|
+
const body = raw.body === undefined || raw.body === null || raw.body === "" ? undefined : typeof raw.body === "string" ? raw.body : JSON.stringify(raw.body);
|
|
122
|
+
if (body !== undefined && body.length > MAX_TEXT_CHARS) throw new Error("the body is too large");
|
|
123
|
+
if (Object.keys(headers).length > MAX_HEADERS) throw new Error(`a request has at most ${MAX_HEADERS} headers`);
|
|
124
|
+
return { method, url, headers: Object.fromEntries(Object.entries(headers)), ...(body !== undefined ? { body } : {}) }; // own properties on a plain object, even "__proto__"
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function add(headers, name, value) {
|
|
128
|
+
const key = String(name).toLowerCase();
|
|
129
|
+
if (!key || key.startsWith(":")) return;
|
|
130
|
+
headers[key] = Object.hasOwn(headers, key) ? `${headers[key]}, ${one(value)}` : one(value);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* A HAR entry's request as { method, url, headers, body? }. The body's type is also `postData.mimeType`, which a HAR may give with no content-type header
|
|
135
|
+
* (and `postData.params` instead of text): it becomes the content-type header, as src/model/http-import.js does, so redaction reads the body by its type.
|
|
136
|
+
*/
|
|
137
|
+
function harShape(request, options) {
|
|
138
|
+
const out = shape(harLib.toRequest({ request: { ...request, headers: (request.headers ?? []).filter((h) => h?.name) } }, options));
|
|
139
|
+
const mime = request.postData?.mimeType || (Array.isArray(request.postData?.params) && request.postData.params.length ? "application/x-www-form-urlencoded" : undefined); // params with no type are a form
|
|
140
|
+
if (typeof mime === "string" && mime && out.body !== undefined && !Object.keys(out.headers).some((k) => k.toLowerCase() === "content-type")) out.headers["content-type"] = mime.slice(0, 256);
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Read what was given: a curl command, a fetch(…) call (read as literals, never run), a raw HTTP request, a HAR file or entry (JSON
|
|
146
|
+
* text or an object), or a request object. Returns { kind, requests: [request…] }; throws an Error that says what is wrong.
|
|
147
|
+
*/
|
|
148
|
+
export function readRequests(input) {
|
|
149
|
+
if (input === undefined || input === null || input === "") throw new Error("nothing to read: give it a request");
|
|
150
|
+
if (typeof input === "string") {
|
|
151
|
+
if (input.length > MAX_TEXT_CHARS) throw new Error("that text is too large");
|
|
152
|
+
const text = input.replace(/\r\n?/g, "\n").trim();
|
|
153
|
+
if (text.startsWith("{") || text.startsWith("[")) {
|
|
154
|
+
let json;
|
|
155
|
+
try {
|
|
156
|
+
json = JSON.parse(text);
|
|
157
|
+
} catch {
|
|
158
|
+
throw new Error("that looks like JSON but isn't valid");
|
|
159
|
+
}
|
|
160
|
+
return readRequests(json);
|
|
161
|
+
}
|
|
162
|
+
const kind = /^curl(\.exe)?\s/i.test(text) ? "curl" : detectType(text);
|
|
163
|
+
const isRaw = kind === "request" || /^\s*[A-Z]{3,10}[ \t]+\S+([ \t]+HTTP\/\d(\.\d)?)?[ \t]*(\n|$)/.test(text);
|
|
164
|
+
if (isRaw && kind !== "curl" && kind !== "fetch") checkRawHeaderLines(text);
|
|
165
|
+
try {
|
|
166
|
+
if (kind === "curl") return { kind, requests: [shape(curlLib.toRequest(text))] };
|
|
167
|
+
if (kind === "fetch") return { kind, requests: [shape(fetchLib.parse(text))] };
|
|
168
|
+
if (kind === "request" || /^\s*[A-Z]{3,10}[ \t]+\S+([ \t]+HTTP\/\d(\.\d)?)?[ \t]*(\n|$)/.test(text)) return { kind: "http", requests: [shape(stringLib.parseRequest(text))] };
|
|
169
|
+
} catch (problem) {
|
|
170
|
+
throw new Error(`that isn't a ${kind === "request" ? "raw HTTP" : kind} request I can read: ${String(problem.message).replace(/^Cannot parse fetch\(\) source: /, "")}`);
|
|
171
|
+
}
|
|
172
|
+
throw new Error("can't tell what that is: a curl command, a fetch() call, a raw HTTP request or a HAR file");
|
|
173
|
+
}
|
|
174
|
+
if (Array.isArray(input)) {
|
|
175
|
+
if (!input.length) throw new Error("no requests given");
|
|
176
|
+
if (input.length > MAX_ENTRIES) throw new Error(`at most ${MAX_ENTRIES} requests`);
|
|
177
|
+
return { kind: "list", requests: input.map((r) => readRequests(r).requests[0]) };
|
|
178
|
+
}
|
|
179
|
+
if (isObject(input)) {
|
|
180
|
+
if (Array.isArray(input.log?.entries)) {
|
|
181
|
+
const entries = input.log.entries.slice(0, MAX_ENTRIES).filter((e) => e?.request && /^https?:\/\//i.test(String(e.request.url ?? "")));
|
|
182
|
+
for (const e of entries) checkHarHeaders(e.request);
|
|
183
|
+
if (!entries.length) throw new Error("this HAR file has no http(s) requests");
|
|
184
|
+
return { kind: "har", requests: entries.map((entry) => harShape(entry.request, { includeCookies: true })) };
|
|
185
|
+
}
|
|
186
|
+
if (isObject(input.request) && (input.request.url || input.request.method)) checkHarHeaders(input.request);
|
|
187
|
+
if (isObject(input.request) && (input.request.url || input.request.method)) return { kind: "har", requests: [harShape(input.request, { includeCookies: true })] };
|
|
188
|
+
if (isCapture(input)) return { kind: "capture", requests: [fromCapture(input)] };
|
|
189
|
+
return { kind: "object", requests: [shape(input)] };
|
|
190
|
+
}
|
|
191
|
+
throw new Error("give it text (curl, fetch(), raw HTTP, HAR) or a request object");
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A webhook's `capture: "raw"` value (a method, a path, header pairs, the body as base64): the request exactly as it arrived (wave P-E, CAP-01). */
|
|
195
|
+
const isCapture = (v) => isObject(v) && !("url" in v) && typeof v.method === "string" && typeof v.path === "string" && Array.isArray(v.headers) && v.headers.every((h) => Array.isArray(h));
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A raw capture as a request: the URL is built from the Host header it carried (http, as it arrived), the headers are the pairs it listed
|
|
199
|
+
* (credentials were never in it), and the body is its text when the bytes are UTF-8. Bytes that aren't text are left out (a cURL line or a HAR
|
|
200
|
+
* entry can't hold them); `size` still says they were there.
|
|
201
|
+
*/
|
|
202
|
+
function fromCapture(v) {
|
|
203
|
+
const headers = v.headers.map(([name, value]) => ({ name, value }));
|
|
204
|
+
const host = String(v.headers.find(([n]) => String(n).toLowerCase() === "host")?.[1] ?? "localhost");
|
|
205
|
+
let body;
|
|
206
|
+
if (v.encoding === "base64" && typeof v.body === "string" && v.body !== "") {
|
|
207
|
+
try {
|
|
208
|
+
body = new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(atob(v.body), (c) => c.charCodeAt(0)));
|
|
209
|
+
} catch {
|
|
210
|
+
body = undefined;
|
|
211
|
+
}
|
|
212
|
+
} else if (typeof v.body === "string") body = v.body;
|
|
213
|
+
const url = `http://${host}${String(v.path).startsWith("/") ? "" : "/"}${v.path}${v.search ?? ""}`;
|
|
214
|
+
return shape({ method: v.method, url, headers, ...(body ? { body } : {}) });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ── writing a request in each form ───────────────────────────────────────────
|
|
218
|
+
|
|
219
|
+
const GET_LIKE = new Set(["GET", "HEAD"]);
|
|
220
|
+
|
|
221
|
+
/** curl, fetch(), HAR and raw HTTP for one (already redacted) request. The HAR's date is the epoch, so the same request gives the same text. */
|
|
222
|
+
export async function formatsOf(request) {
|
|
223
|
+
const plain = { method: request.method, url: request.url, headers: { ...request.headers }, ...(request.body !== undefined && !GET_LIKE.has(request.method) ? { body: request.body } : {}) };
|
|
224
|
+
const all = await converter.allFormats(plain);
|
|
225
|
+
const har = { ...all.har, startedDateTime: "1970-01-01T00:00:00.000Z" };
|
|
226
|
+
return { curl: all.curl, fetch: all.fetchCode, har, raw: String(all.httpString).replace(/\r\n/g, "\n") };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The text in one target form for a list of (redacted) requests: one HAR log, or each request's text one after the other. */
|
|
230
|
+
export async function textFor(requests, to) {
|
|
231
|
+
const all = [];
|
|
232
|
+
for (const request of requests) all.push(await formatsOf(request));
|
|
233
|
+
if (to === "har") return JSON.stringify({ log: { version: "1.2", creator: { name: "mallory http pane", version: "1" }, entries: all.map((f) => f.har) } }, null, 2);
|
|
234
|
+
const joined = all.map((f) => f[to]);
|
|
235
|
+
return joined.join(to === "curl" ? "\n" : "\n\n");
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ── diff ─────────────────────────────────────────────────────────────────────
|
|
239
|
+
|
|
240
|
+
/** A line diff: [{ op: "=" | "-" | "+", line }]. LCS up to MAX_BODY_DIFF_LINES lines a side; above that the common start and end are kept and the middle is one change. */
|
|
241
|
+
export function lineDiff(a, b) {
|
|
242
|
+
return lineDiffBounded(a, b).lines;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* lineDiff and whether it gave up exactness: `{ lines, coarse }`. `coarse` is true when the differing middle was longer than
|
|
247
|
+
* MAX_BODY_DIFF_LINES lines on a side, so it is shown as all removed then all added instead of matched line by line (prism's table is 16-bit
|
|
248
|
+
* and overflows at 65,535 lines: this one is 32-bit and bounded, so an input of any size is answered, DIF-04).
|
|
249
|
+
*/
|
|
250
|
+
export function lineDiffBounded(a, b) {
|
|
251
|
+
const x = a === "" ? [] : String(a).split("\n");
|
|
252
|
+
const y = b === "" ? [] : String(b).split("\n");
|
|
253
|
+
let start = 0;
|
|
254
|
+
while (start < x.length && start < y.length && x[start] === y[start]) start++;
|
|
255
|
+
let endX = x.length;
|
|
256
|
+
let endY = y.length;
|
|
257
|
+
while (endX > start && endY > start && x[endX - 1] === y[endY - 1]) {
|
|
258
|
+
endX--;
|
|
259
|
+
endY--;
|
|
260
|
+
}
|
|
261
|
+
const head = x.slice(0, start).map((line) => ({ op: "=", line }));
|
|
262
|
+
const tail = x.slice(endX).map((line) => ({ op: "=", line }));
|
|
263
|
+
const mx = x.slice(start, endX);
|
|
264
|
+
const my = y.slice(start, endY);
|
|
265
|
+
let middle;
|
|
266
|
+
const coarse = mx.length > MAX_BODY_DIFF_LINES || my.length > MAX_BODY_DIFF_LINES;
|
|
267
|
+
if (coarse) {
|
|
268
|
+
// At most MAX_BODY_DIFF_LINES lines of each side are listed; the rest is one marker (the output is bounded as well as the work).
|
|
269
|
+
const side = (list, op) => [...list.slice(0, MAX_BODY_DIFF_LINES).map((line) => ({ op, line })), ...(list.length > MAX_BODY_DIFF_LINES ? [{ op: "=", line: `… ${list.length - MAX_BODY_DIFF_LINES} more ${op === "-" ? "removed" : "added"} lines`, skipped: list.length - MAX_BODY_DIFF_LINES }] : [])];
|
|
270
|
+
middle = [...side(mx, "-"), ...side(my, "+")];
|
|
271
|
+
} else {
|
|
272
|
+
// A table of lengths in 32-bit cells (a 16-bit one overflows at 65,535 lines).
|
|
273
|
+
const w = my.length + 1;
|
|
274
|
+
const table = new Uint32Array((mx.length + 1) * w);
|
|
275
|
+
for (let i = mx.length - 1; i >= 0; i--) for (let j = my.length - 1; j >= 0; j--) table[i * w + j] = mx[i] === my[j] ? table[(i + 1) * w + j + 1] + 1 : Math.max(table[(i + 1) * w + j], table[i * w + j + 1]);
|
|
276
|
+
middle = [];
|
|
277
|
+
let i = 0;
|
|
278
|
+
let j = 0;
|
|
279
|
+
while (i < mx.length && j < my.length) {
|
|
280
|
+
if (mx[i] === my[j]) middle.push({ op: "=", line: mx[i++] }), j++;
|
|
281
|
+
else if (table[(i + 1) * w + j] >= table[i * w + j + 1]) middle.push({ op: "-", line: mx[i++] });
|
|
282
|
+
else middle.push({ op: "+", line: my[j++] });
|
|
283
|
+
}
|
|
284
|
+
while (i < mx.length) middle.push({ op: "-", line: mx[i++] });
|
|
285
|
+
while (j < my.length) middle.push({ op: "+", line: my[j++] });
|
|
286
|
+
}
|
|
287
|
+
return { lines: [...head, ...middle, ...tail], coarse };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** The header sets of two requests: { added: {name: value}, removed: {name: value}, changed: {name: [from, to]} }. */
|
|
291
|
+
export function headerDiff(a, b) {
|
|
292
|
+
const out = { added: Object.create(null), removed: Object.create(null), changed: Object.create(null) };
|
|
293
|
+
for (const [name, value] of Object.entries(a)) {
|
|
294
|
+
if (!Object.hasOwn(b, name)) out.removed[name] = value;
|
|
295
|
+
else if (b[name] !== value) out.changed[name] = [value, b[name]];
|
|
296
|
+
}
|
|
297
|
+
for (const [name, value] of Object.entries(b)) if (!Object.hasOwn(a, name)) out.added[name] = value;
|
|
298
|
+
return { added: Object.fromEntries(Object.entries(out.added)), removed: Object.fromEntries(Object.entries(out.removed)), changed: Object.fromEntries(Object.entries(out.changed)) };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** A structural diff of two JSON values: [{ path, op: "added" | "removed" | "changed", from?, to? }], at most 200. */
|
|
302
|
+
export function jsonDiff(a, b, path = "$", out = [], depth = 0) {
|
|
303
|
+
if (out.length >= 200) return out;
|
|
304
|
+
if (depth > MAX_DIFF_DEPTH) {
|
|
305
|
+
out.push({ path, op: "changed", note: `deeper than ${MAX_DIFF_DEPTH} levels: not compared` }); // a guard against a value nested to the stack's limit
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
const kind = (v) => (v === null ? "null" : Array.isArray(v) ? "array" : typeof v);
|
|
309
|
+
if (kind(a) !== kind(b) || (kind(a) !== "object" && kind(a) !== "array")) {
|
|
310
|
+
if (JSON.stringify(a) !== JSON.stringify(b)) out.push({ path, op: "changed", from: a, to: b });
|
|
311
|
+
return out;
|
|
312
|
+
}
|
|
313
|
+
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
314
|
+
for (const key of keys) {
|
|
315
|
+
const child = Array.isArray(a) ? `${path}[${key}]` : `${path}.${key}`;
|
|
316
|
+
if (!Object.hasOwn(a, key)) out.push({ path: child, op: "added", to: b[key] });
|
|
317
|
+
else if (!Object.hasOwn(b, key)) out.push({ path: child, op: "removed", from: a[key] });
|
|
318
|
+
else jsonDiff(a[key], b[key], child, out, depth + 1);
|
|
319
|
+
}
|
|
320
|
+
return out;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const COMPACT_LINES = 400;
|
|
324
|
+
const CONTEXT_LINES = 3;
|
|
325
|
+
|
|
326
|
+
/** A line diff with each run of unchanged lines longer than the context on both sides replaced by one `{ op: "=", skipped: n, line: "… n unchanged lines" }`. */
|
|
327
|
+
export function compactLines(lines) {
|
|
328
|
+
const near = new Array(lines.length).fill(false);
|
|
329
|
+
lines.forEach((l, i) => {
|
|
330
|
+
if (l.op === "=") return;
|
|
331
|
+
for (let j = Math.max(0, i - CONTEXT_LINES); j <= Math.min(lines.length - 1, i + CONTEXT_LINES); j++) near[j] = true;
|
|
332
|
+
});
|
|
333
|
+
const out = [];
|
|
334
|
+
let run = 0;
|
|
335
|
+
const flush = () => {
|
|
336
|
+
if (run) out.push({ op: "=", line: `… ${run} unchanged line${run === 1 ? "" : "s"}`, skipped: run });
|
|
337
|
+
run = 0;
|
|
338
|
+
};
|
|
339
|
+
lines.forEach((l, i) => {
|
|
340
|
+
if (l.op !== "=" || near[i]) {
|
|
341
|
+
flush();
|
|
342
|
+
out.push(l);
|
|
343
|
+
} else run++;
|
|
344
|
+
});
|
|
345
|
+
flush();
|
|
346
|
+
return out;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** A form-urlencoded body as { name: value | [values] }. */
|
|
350
|
+
const formFields = (text) => {
|
|
351
|
+
const out = Object.create(null);
|
|
352
|
+
for (const [k, v] of new URLSearchParams(text)) out[k] = k in out ? [].concat(out[k], v) : v;
|
|
353
|
+
return out;
|
|
354
|
+
};
|
|
355
|
+
const isForm = (headers) => /x-www-form-urlencoded/i.test(String(headers?.["content-type"] ?? ""));
|
|
356
|
+
|
|
357
|
+
const parseJson = (text) => {
|
|
358
|
+
try {
|
|
359
|
+
const value = JSON.parse(text);
|
|
360
|
+
return value !== null && typeof value === "object" ? { value } : null;
|
|
361
|
+
} catch {
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
/** Two (redacted) requests compared. */
|
|
367
|
+
export function diffRequests(a, b) {
|
|
368
|
+
const line = (r) => `${r.method} ${r.url}`;
|
|
369
|
+
const requestLine = line(a) === line(b) ? null : { from: line(a), to: line(b) };
|
|
370
|
+
const headers = headerDiff(a.headers, b.headers);
|
|
371
|
+
const A = a.body ?? "";
|
|
372
|
+
const B = b.body ?? "";
|
|
373
|
+
let body = null;
|
|
374
|
+
if (A !== B) {
|
|
375
|
+
const ja = parseJson(A);
|
|
376
|
+
const jb = parseJson(B);
|
|
377
|
+
const text = () => {
|
|
378
|
+
const { lines, coarse } = lineDiffBounded(A, B);
|
|
379
|
+
// A long body keeps the changed lines with a few around them and one marker for each unchanged run, so a diff of a 70,000-line body is a few lines.
|
|
380
|
+
const kept = lines.length > COMPACT_LINES ? compactLines(lines) : lines;
|
|
381
|
+
return { kind: "text", lines: kept, ...(kept !== lines ? { totalLines: lines.length } : {}), ...(coarse ? { coarse: true } : {}) };
|
|
382
|
+
};
|
|
383
|
+
body = ja && jb ? { kind: "json", changes: jsonDiff(ja.value, jb.value) } : text();
|
|
384
|
+
// A form body is compared by field, so a reordered form is not a change (the same rule as a JSON body's keys).
|
|
385
|
+
if (!body.changes && isForm(a.headers) && isForm(b.headers)) body = { kind: "form", changes: jsonDiff(formFields(A), formFields(B)).map((c) => ({ ...c, path: c.path.replace(/^\$\./, "") })) };
|
|
386
|
+
if ((body.kind === "json" || body.kind === "form") && !body.changes.length) body = text(); // same data, different spelling
|
|
387
|
+
}
|
|
388
|
+
const headerCount = Object.keys(headers.added).length + Object.keys(headers.removed).length + Object.keys(headers.changed).length;
|
|
389
|
+
return { identical: !requestLine && !headerCount && !body, requestLine, headers, body };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Two (redacted) requests compared WRITTEN in a target form (prism's diff in cURL or fetch() form, DIF-02): `to` is "curl", "fetch", "raw" or
|
|
394
|
+
* "har"; the two texts are compared line by line. `{ form, identical, lines (the changed ones), coarse, text }`.
|
|
395
|
+
*/
|
|
396
|
+
export async function diffForms(a, b, to) {
|
|
397
|
+
if (!TARGETS.includes(to)) throw new Error(`unknown form "${to}": use ${TARGETS.join(", ")}`);
|
|
398
|
+
const [fa, fb] = await Promise.all([formatsOf(a), formatsOf(b)]);
|
|
399
|
+
const written = (f) => (to === "har" ? JSON.stringify(f.har, null, 2) : f[to]);
|
|
400
|
+
const { lines, coarse } = lineDiffBounded(written(fa), written(fb));
|
|
401
|
+
const changed = lines.filter((l) => l.op !== "=" || l.skipped > 0 && /more (removed|added) lines/.test(l.line));
|
|
402
|
+
return { form: to, identical: changed.length === 0, lines: changed, ...(coarse ? { coarse: true } : {}), text: changed.length ? changed.map((l) => `${l.op} ${l.line}`).join("\n") : `the requests are the same as ${TARGET_LABELS[to]}` };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** The diff as text, one change a line (- from, + to), for a person and for a text pane. */
|
|
406
|
+
export function diffText(diff) {
|
|
407
|
+
if (diff.identical) return "the requests are the same";
|
|
408
|
+
const out = [];
|
|
409
|
+
if (diff.requestLine) out.push(`- ${diff.requestLine.from}`, `+ ${diff.requestLine.to}`);
|
|
410
|
+
for (const [name, value] of Object.entries(diff.headers.removed)) out.push(`- ${name}: ${value}`);
|
|
411
|
+
for (const [name, [from, to]] of Object.entries(diff.headers.changed)) out.push(`- ${name}: ${from}`, `+ ${name}: ${to}`);
|
|
412
|
+
for (const [name, value] of Object.entries(diff.headers.added)) out.push(`+ ${name}: ${value}`);
|
|
413
|
+
if (diff.body?.kind === "json" || diff.body?.kind === "form") for (const c of diff.body.changes) out.push(`${c.op === "added" ? "+" : c.op === "removed" ? "-" : "~"} ${diff.body.kind === "form" ? "field" : "body"} ${c.path}${c.op === "changed" ? `: ${JSON.stringify(c.from)} -> ${JSON.stringify(c.to)}` : c.op === "added" ? `: ${JSON.stringify(c.to)}` : `: ${JSON.stringify(c.from)}`}`);
|
|
414
|
+
else if (diff.body) {
|
|
415
|
+
for (const l of diff.body.lines) if (l.op !== "=") out.push(`${l.op} body: ${l.line}`);
|
|
416
|
+
if (diff.body.coarse) out.push(`(the body differs over more than ${MAX_BODY_DIFF_LINES} lines, so the changed part is shown as removed lines then added lines, not matched line by line)`);
|
|
417
|
+
}
|
|
418
|
+
return out.join("\n");
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ── rewrite ──────────────────────────────────────────────────────────────────
|
|
422
|
+
|
|
423
|
+
const MAX_PATTERN = 200;
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Replace LITERAL text (no regular expressions: a pattern the person or an agent writes ran over a body as a RegExp and `^(a+)+$` froze the page).
|
|
427
|
+
* `pattern` is plain text; a leading `^` anchors it to the start and a trailing `$` to the end (those two only). `all` (default true) replaces every
|
|
428
|
+
* occurrence, `all: false` the first. Returns the new text (the same text when nothing matched).
|
|
429
|
+
*/
|
|
430
|
+
export function literalReplace(text, pattern, replacement, all = true) {
|
|
431
|
+
let find = String(pattern ?? "");
|
|
432
|
+
if (!find || find.length > MAX_PATTERN + 2) return text;
|
|
433
|
+
const start = find.startsWith("^");
|
|
434
|
+
if (start) find = find.slice(1);
|
|
435
|
+
const end = find.endsWith("$") && !find.endsWith("\\$");
|
|
436
|
+
if (end) find = find.slice(0, -1);
|
|
437
|
+
if (!find && !start && !end) return text;
|
|
438
|
+
if (start && end) return text === find ? replacement : text;
|
|
439
|
+
if (start) return text.startsWith(find) ? replacement + text.slice(find.length) : text;
|
|
440
|
+
if (end) return text.endsWith(find) ? text.slice(0, text.length - find.length) + replacement : text;
|
|
441
|
+
if (!find) return text;
|
|
442
|
+
return all ? text.split(find).join(replacement) : text.replace(find, () => replacement);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function ruleMatches(when, request) {
|
|
446
|
+
if (!when) return true;
|
|
447
|
+
let host = "";
|
|
448
|
+
let path = request.url;
|
|
449
|
+
try {
|
|
450
|
+
const u = new URL(request.url, "http://relative.invalid");
|
|
451
|
+
host = u.host === "relative.invalid" ? "" : u.host;
|
|
452
|
+
path = u.pathname;
|
|
453
|
+
} catch {}
|
|
454
|
+
if (when.method && String(when.method).toUpperCase() !== request.method) return false;
|
|
455
|
+
if (when.host && when.host !== host) return false;
|
|
456
|
+
if (when.pathPrefix && !pathMatches(when.pathPrefix, path)) return false;
|
|
457
|
+
return true;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* A rule's path condition: a prefix, or `/regex/` (`/regex/i`; at least one operator inside, so `/api/` stays the prefix it was) run by the
|
|
462
|
+
* linear-time matcher (src/model/safe-regex.js). A pattern that cannot be used matches nothing; httpProblem says why.
|
|
463
|
+
*/
|
|
464
|
+
const patternCache = new Map();
|
|
465
|
+
function compiledFor(wanted) {
|
|
466
|
+
const key = `${wanted.ignoreCase ? "i" : "c"}:${wanted.pattern}`;
|
|
467
|
+
let compiled = patternCache.get(key);
|
|
468
|
+
if (!compiled) {
|
|
469
|
+
compiled = compileSafeRegex(wanted.pattern, { ignoreCase: wanted.ignoreCase });
|
|
470
|
+
if (patternCache.size >= 200) patternCache.clear();
|
|
471
|
+
patternCache.set(key, compiled);
|
|
472
|
+
}
|
|
473
|
+
return compiled;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* `replace-path` with a /regex/ in `name` (prism's rewritePath, which ran `pathname.replace(regex, replacement)`): the first match, or every match unless the
|
|
478
|
+
* rule says `all: false`: `all` (default true, as for the literal op) is every match, `all: false` the first (what prism's rule did). `$1`…`$9`, `$&`, `$$`, `` $` ``
|
|
479
|
+
* and `$'` in the replacement are String.prototype.replace's. A path it cannot answer for refuses the exchange, as a regex condition does.
|
|
480
|
+
*/
|
|
481
|
+
function regexReplacePath(path, wanted, replacement, all) {
|
|
482
|
+
const compiled = compiledFor(wanted);
|
|
483
|
+
if (!compiled.ok) throw new RuleRefusal(`replace-path: the /regex/ cannot be used (${compiled.error}), so the request is refused rather than sent unchanged`);
|
|
484
|
+
if (compiled.groups > 9) throw new RuleRefusal("replace-path: the /regex/ has more than 9 groups, so the request is refused rather than sent unchanged");
|
|
485
|
+
const done = compiled.replace(path, replacement, { all });
|
|
486
|
+
if (done.answer === "done") return done.text;
|
|
487
|
+
throw new RuleRefusal(`replace-path: the path is ${done.answer === "too-long" ? `too long (over ${SAFE_REGEX_LIMITS.input} characters)` : "too costly to test"} for the /regex/ in name, so the request is refused rather than sent unchanged`);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function pathMatches(condition, path) {
|
|
491
|
+
const wanted = slashRegex(condition);
|
|
492
|
+
if (!wanted) return path.startsWith(condition);
|
|
493
|
+
const compiled = compiledFor(wanted);
|
|
494
|
+
if (!compiled.ok) return false;
|
|
495
|
+
const answer = compiled.check(path);
|
|
496
|
+
if (answer === "match") return true;
|
|
497
|
+
if (answer === "none") return false;
|
|
498
|
+
// The rule could not be evaluated for this path. "No" would be a lie: a rule that scrubs a header would be skipped and the header would go out.
|
|
499
|
+
throw new RuleRefusal(`a rule's path pattern was not tried: the path is ${answer === "too-long" ? `too long (over ${SAFE_REGEX_LIMITS.input} characters)` : "too costly to test"} for the /regex/ in when.pathPrefix, so the request is refused rather than sent without the rule`);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** A rewrite rule could not be evaluated, so the request or response it would change is refused (never passed through unchanged). */
|
|
503
|
+
export class RuleRefusal extends Error {
|
|
504
|
+
constructor(message) {
|
|
505
|
+
super(message);
|
|
506
|
+
this.name = "RuleRefusal";
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** Split a URL into [origin part, path, query, hash] without needing it to be absolute. */
|
|
511
|
+
function parts(url) {
|
|
512
|
+
const m = /^((?:[a-z][a-z0-9+.-]*:\/\/)?[^/?#]*)([^?#]*)(\?[^#]*)?(#.*)?$/i.exec(url);
|
|
513
|
+
return { origin: m?.[1] ?? "", path: m?.[2] ?? "", query: m?.[3] ?? "", hash: m?.[4] ?? "" };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const queryPairs = (query) => (query ? query.slice(1).split("&").filter(Boolean) : []);
|
|
517
|
+
const pairName = (pair) => {
|
|
518
|
+
const name = pair.split("=")[0];
|
|
519
|
+
try {
|
|
520
|
+
return decodeURIComponent(name.replace(/\+/g, " "));
|
|
521
|
+
} catch {
|
|
522
|
+
return name;
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
/** Apply one rule to a request; returns the new request and a note, or null when it changed nothing. */
|
|
527
|
+
function applyRule(request, rule) {
|
|
528
|
+
const next = { ...request, headers: { ...request.headers } };
|
|
529
|
+
const name = String(rule.name ?? "").toLowerCase();
|
|
530
|
+
const value = rule.value === undefined ? "" : String(rule.value);
|
|
531
|
+
switch (rule.op) {
|
|
532
|
+
case "set-header":
|
|
533
|
+
if (next.headers[name] === value) return null;
|
|
534
|
+
next.headers[name] = value;
|
|
535
|
+
return { request: next, note: `set header ${name}` };
|
|
536
|
+
case "remove-header":
|
|
537
|
+
if (!(name in next.headers)) return null;
|
|
538
|
+
delete next.headers[name];
|
|
539
|
+
return { request: next, note: `removed header ${name}` };
|
|
540
|
+
case "set-method":
|
|
541
|
+
if (next.method === value.toUpperCase()) return null;
|
|
542
|
+
next.method = value.toUpperCase();
|
|
543
|
+
return { request: next, note: `method is now ${next.method}` };
|
|
544
|
+
case "set-url":
|
|
545
|
+
if (next.url === value) return null;
|
|
546
|
+
next.url = value;
|
|
547
|
+
return { request: next, note: "replaced the URL" };
|
|
548
|
+
case "set-path": {
|
|
549
|
+
const p = parts(next.url);
|
|
550
|
+
const path = value.startsWith("/") ? value : `/${value}`;
|
|
551
|
+
if (p.path === path) return null;
|
|
552
|
+
next.url = `${p.origin}${path}${p.query}${p.hash}`;
|
|
553
|
+
return { request: next, note: `path is now ${path}` };
|
|
554
|
+
}
|
|
555
|
+
case "replace-path": {
|
|
556
|
+
const p = parts(next.url);
|
|
557
|
+
const wanted = slashRegex(rule.name);
|
|
558
|
+
const path = wanted ? regexReplacePath(p.path, wanted, value, rule.all !== false) : literalReplace(p.path, rule.name, value, rule.all !== false);
|
|
559
|
+
if (path === p.path) return null;
|
|
560
|
+
next.url = `${p.origin}${path}${p.query}${p.hash}`;
|
|
561
|
+
return { request: next, note: `path is now ${path}` };
|
|
562
|
+
}
|
|
563
|
+
case "set-query": {
|
|
564
|
+
const p = parts(next.url);
|
|
565
|
+
const key = String(rule.name ?? "");
|
|
566
|
+
const pair = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
567
|
+
const pairs = queryPairs(p.query);
|
|
568
|
+
const at = pairs.findIndex((x) => pairName(x) === key);
|
|
569
|
+
if (at >= 0) pairs[at] = pair;
|
|
570
|
+
else pairs.push(pair);
|
|
571
|
+
next.url = `${p.origin}${p.path}?${pairs.join("&")}${p.hash}`;
|
|
572
|
+
return { request: next, note: `query ${key} set` };
|
|
573
|
+
}
|
|
574
|
+
case "remove-query": {
|
|
575
|
+
const p = parts(next.url);
|
|
576
|
+
const key = String(rule.name ?? "");
|
|
577
|
+
const pairs = queryPairs(p.query);
|
|
578
|
+
const kept = pairs.filter((x) => pairName(x) !== key);
|
|
579
|
+
if (kept.length === pairs.length) return null;
|
|
580
|
+
next.url = `${p.origin}${p.path}${kept.length ? `?${kept.join("&")}` : ""}${p.hash}`;
|
|
581
|
+
return { request: next, note: `query ${key} removed` };
|
|
582
|
+
}
|
|
583
|
+
case "set-body":
|
|
584
|
+
if (next.body === value) return null;
|
|
585
|
+
if (value === "") delete next.body;
|
|
586
|
+
else next.body = value;
|
|
587
|
+
return { request: next, note: "body replaced" };
|
|
588
|
+
case "replace-body": {
|
|
589
|
+
if (next.body === undefined) return null;
|
|
590
|
+
const body = literalReplace(next.body, rule.name, value, rule.all !== false);
|
|
591
|
+
if (body === next.body) return null;
|
|
592
|
+
next.body = body;
|
|
593
|
+
return { request: next, note: "body text replaced" };
|
|
594
|
+
}
|
|
595
|
+
default:
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Rules applied in order to a request: { request, changes: [{ rule: index, note }] }. A rule that matches nothing, or changes nothing, is skipped. */
|
|
601
|
+
export function rewriteRequest(request, rules) {
|
|
602
|
+
let current = request;
|
|
603
|
+
const changes = [];
|
|
604
|
+
rules.forEach((rule, index) => {
|
|
605
|
+
try {
|
|
606
|
+
if (!ruleMatches(rule.when, current)) return;
|
|
607
|
+
const done = applyRule(current, rule);
|
|
608
|
+
if (!done) return;
|
|
609
|
+
current = done.request;
|
|
610
|
+
changes.push({ rule: index, note: done.note });
|
|
611
|
+
} catch (error) {
|
|
612
|
+
if (error instanceof RuleRefusal) throw error;
|
|
613
|
+
changes.push({ rule: index, skipped: true, note: `skipped: ${String(error?.message ?? error).slice(0, 100)}` }); // one bad rule does not stop the rest
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
return { request: current, changes };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// ── rewrite a response (prism parity RWR-02) ─────────────────────────────────
|
|
620
|
+
|
|
621
|
+
const REASONS = { 200: "OK", 201: "Created", 202: "Accepted", 204: "No Content", 301: "Moved Permanently", 302: "Found", 304: "Not Modified", 307: "Temporary Redirect", 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 409: "Conflict", 410: "Gone", 418: "I'm a teapot", 422: "Unprocessable Entity", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
|
|
622
|
+
const MAX_PATH_DEPTH = 32;
|
|
623
|
+
const MAX_PATH_INDEX = 1e5;
|
|
624
|
+
const UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
625
|
+
const byteLength = (text) => new TextEncoder().encode(text).byteLength;
|
|
626
|
+
|
|
627
|
+
/** A response header list or object as an object with lowercase names, credentials and URLs in URL-ish headers redacted. */
|
|
628
|
+
function responseHeaders(raw) {
|
|
629
|
+
const pairs = Array.isArray(raw) ? raw.map((h) => (Array.isArray(h) ? h : [h?.name, h?.value])) : isObject(raw) ? Object.entries(raw) : [];
|
|
630
|
+
const out = {};
|
|
631
|
+
for (const [name, value] of pairs) {
|
|
632
|
+
const key = String(name ?? "").toLowerCase();
|
|
633
|
+
if (!key || key.startsWith(":")) continue;
|
|
634
|
+
const text = String(value ?? "");
|
|
635
|
+
const safe = redactHeaderValue(key, text) !== text ? REDACTED : URLISH_RESPONSE_HEADERS.has(key) ? redactUrl(text).url : text;
|
|
636
|
+
out[key] = key in out && safe !== REDACTED ? `${out[key]}, ${safe}` : safe;
|
|
637
|
+
}
|
|
638
|
+
return out;
|
|
639
|
+
}
|
|
640
|
+
const URLISH_RESPONSE_HEADERS = new Set(["location", "content-location", "link", "referer"]);
|
|
641
|
+
|
|
642
|
+
const bodyText = (b) => (typeof b === "string" ? b : isObject(b) && typeof b.text === "string" ? b.text : isObject(b) && "json" in b && b.json !== undefined ? JSON.stringify(b.json) : undefined);
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* A response read from what a pane holds: a send value (`{ status, headers, body: { text } }`), a traffic entry (`responseHeaders`, `responseBody`),
|
|
646
|
+
* a HAR entry or log, an object `{ status, statusText, headers, body }`, or the text of a raw HTTP response ("HTTP/1.1 404 Not Found", headers, a
|
|
647
|
+
* blank line, the body) or of one of those as JSON. Returns `{ status, statusText, headers, body? }` with credential headers and credential fields of
|
|
648
|
+
* a body already "[redacted]" (src/security/redact.js). Throws a plain Error if there is no status.
|
|
649
|
+
*/
|
|
650
|
+
export function readResponse(input) {
|
|
651
|
+
let v = input;
|
|
652
|
+
if (typeof v === "string") {
|
|
653
|
+
const text = v.replace(/^/, "").replace(/\r\n/g, "\n");
|
|
654
|
+
const line = /^HTTP\/[\d.]+\s+(\d{3})[ \t]*([^\n]*)\n?/.exec(text);
|
|
655
|
+
if (line) {
|
|
656
|
+
const rest = text.slice(line[0].length);
|
|
657
|
+
const split = rest.indexOf("\n\n");
|
|
658
|
+
const head = split < 0 ? rest : rest.slice(0, split);
|
|
659
|
+
const headers = head.split("\n").filter((l) => l.includes(":")).map((l) => [l.slice(0, l.indexOf(":")).trim(), l.slice(l.indexOf(":") + 1).trim()]);
|
|
660
|
+
v = { status: Number(line[1]), statusText: line[2].trim(), headers, body: split < 0 ? undefined : rest.slice(split + 2) };
|
|
661
|
+
} else {
|
|
662
|
+
try {
|
|
663
|
+
v = JSON.parse(text);
|
|
664
|
+
} catch {
|
|
665
|
+
throw new Error("a response is raw HTTP (HTTP/1.1 200 OK, headers, a blank line, the body) or an object with a status");
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
if (Array.isArray(v?.log?.entries)) v = v.log.entries[0];
|
|
670
|
+
if (isObject(v) && isObject(v.response) && !("status" in v)) v = v.response;
|
|
671
|
+
if (!isObject(v)) throw new Error("a response is raw HTTP (HTTP/1.1 200 OK, headers, a blank line, the body) or an object with a status");
|
|
672
|
+
const status = Number(v.status);
|
|
673
|
+
if (!Number.isInteger(status) || status < 100 || status > 599) throw new Error("the response has no status (a whole number from 100 to 599)");
|
|
674
|
+
const headers = responseHeaders(v.headers ?? v.responseHeaders);
|
|
675
|
+
let body = bodyText(v.body ?? v.responseBody ?? v.content);
|
|
676
|
+
if (body !== undefined) body = redactBody(body, headers["content-type"] ?? "");
|
|
677
|
+
return { status, statusText: String(v.statusText ?? REASONS[status] ?? "").slice(0, 100), headers, ...(body !== undefined ? { body } : {}) };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** A path into JSON: `$.a.b[0]`, `a.b[0]`, `.a`, or a JSON pointer `/a/b/0`. Returns the keys, or null when it can't be one (empty, or a key that would reach a prototype). */
|
|
681
|
+
export function jsonPathKeys(path) {
|
|
682
|
+
const text = String(path ?? "").trim();
|
|
683
|
+
if (!text || text === "$" || text === "/") return null;
|
|
684
|
+
const keys = text.startsWith("/") ? text.slice(1).split("/").map((k) => k.replace(/~1/g, "/").replace(/~0/g, "~")) : [...text.replace(/^\$/, "").matchAll(/\[(\d+)\]|\.?([^.[\]]+)/g)].map((m) => m[1] ?? m[2]);
|
|
685
|
+
if (!keys.length || keys.length > MAX_PATH_DEPTH || keys.some((k) => k === "" || UNSAFE_KEYS.has(k) || (/^\d+$/.test(k) && Number(k) > MAX_PATH_INDEX))) return null;
|
|
686
|
+
return keys;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** Set (value given) or remove (`remove`) the JSON at `keys`; returns whether it changed. Creates objects on the way when setting; never walks through a non-object. */
|
|
690
|
+
function patchJson(root, keys, { value, remove = false } = {}) {
|
|
691
|
+
// An array's key is an index (never `length` or a name); setting may append one past the end, never leave a hole.
|
|
692
|
+
const slot = (node, key) => {
|
|
693
|
+
if (!Array.isArray(node)) return Object.hasOwn(node, key) ? "own" : "absent";
|
|
694
|
+
if (!/^\d+$/.test(key)) return "bad";
|
|
695
|
+
const i = Number(key);
|
|
696
|
+
return i < node.length ? "own" : i === node.length ? "end" : "bad";
|
|
697
|
+
};
|
|
698
|
+
let node = root;
|
|
699
|
+
for (const key of keys.slice(0, -1)) {
|
|
700
|
+
if (!isObject(node) && !Array.isArray(node)) return false;
|
|
701
|
+
const where = slot(node, key);
|
|
702
|
+
if (where === "bad") return false;
|
|
703
|
+
if (where !== "own") {
|
|
704
|
+
if (remove) return false;
|
|
705
|
+
node[key] = {};
|
|
706
|
+
}
|
|
707
|
+
node = node[key];
|
|
708
|
+
}
|
|
709
|
+
const last = keys[keys.length - 1];
|
|
710
|
+
if (!isObject(node) && !Array.isArray(node)) return false;
|
|
711
|
+
const where = slot(node, last);
|
|
712
|
+
if (where === "bad") return false;
|
|
713
|
+
if (remove) {
|
|
714
|
+
if (where !== "own") return false;
|
|
715
|
+
if (Array.isArray(node)) node.splice(Number(last), 1);
|
|
716
|
+
else delete node[last];
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
if (where === "own" && JSON.stringify(node[last]) === JSON.stringify(value)) return false;
|
|
720
|
+
node[last] = value;
|
|
721
|
+
return true;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const statusMatches = (want, status) => (typeof want === "number" || /^\d{3}$/.test(String(want)) ? Number(want) === status : /^[1-5]xx$/i.test(String(want)) ? String(status)[0] === String(want)[0] : false);
|
|
725
|
+
|
|
726
|
+
function responseRuleMatches(when, response, request) {
|
|
727
|
+
if (!when) return true;
|
|
728
|
+
if (when.status !== undefined && !statusMatches(when.status, response.status)) return false;
|
|
729
|
+
if ((when.method || when.host || when.pathPrefix) && !request) return false; // a condition on the request needs the request
|
|
730
|
+
return request ? ruleMatches({ ...when, status: undefined }, request) : true;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function applyResponseRule(response, rule) {
|
|
734
|
+
const next = { ...response, headers: { ...response.headers } };
|
|
735
|
+
const name = String(rule.name ?? "").toLowerCase();
|
|
736
|
+
const value = rule.value === undefined ? "" : String(rule.value);
|
|
737
|
+
const setBody = (body) => {
|
|
738
|
+
if (body === undefined) delete next.body;
|
|
739
|
+
else next.body = body;
|
|
740
|
+
if ("content-length" in next.headers) next.headers["content-length"] = String(body === undefined ? 0 : byteLength(body)); // the length that was there no longer applies
|
|
741
|
+
};
|
|
742
|
+
switch (rule.op) {
|
|
743
|
+
case "set-status": {
|
|
744
|
+
const status = Number(value);
|
|
745
|
+
if (!Number.isInteger(status) || status < 100 || status > 599 || status === next.status) return null;
|
|
746
|
+
next.status = status;
|
|
747
|
+
next.statusText = REASONS[status] ?? "";
|
|
748
|
+
return { response: next, note: `status is now ${status}${next.statusText ? ` ${next.statusText}` : ""}` };
|
|
749
|
+
}
|
|
750
|
+
case "set-status-text":
|
|
751
|
+
if (next.statusText === value) return null;
|
|
752
|
+
next.statusText = value.slice(0, 100);
|
|
753
|
+
return { response: next, note: `status text is now "${next.statusText}"` };
|
|
754
|
+
case "set-response-header":
|
|
755
|
+
if (next.headers[name] === value) return null;
|
|
756
|
+
next.headers[name] = value;
|
|
757
|
+
return { response: next, note: `set response header ${name}` };
|
|
758
|
+
case "remove-response-header":
|
|
759
|
+
if (!(name in next.headers)) return null;
|
|
760
|
+
delete next.headers[name];
|
|
761
|
+
return { response: next, note: `removed response header ${name}` };
|
|
762
|
+
case "set-response-body":
|
|
763
|
+
if ((next.body ?? "") === value) return null;
|
|
764
|
+
setBody(value === "" ? undefined : value);
|
|
765
|
+
return { response: next, note: "response body replaced" };
|
|
766
|
+
case "replace-response-body": {
|
|
767
|
+
if (next.body === undefined) return null;
|
|
768
|
+
const body = literalReplace(next.body, rule.name, value, rule.all !== false);
|
|
769
|
+
if (body === next.body) return null;
|
|
770
|
+
setBody(body);
|
|
771
|
+
return { response: next, note: "response body text replaced" };
|
|
772
|
+
}
|
|
773
|
+
case "set-response-json":
|
|
774
|
+
case "remove-response-json": {
|
|
775
|
+
const keys = jsonPathKeys(rule.name);
|
|
776
|
+
if (!keys || next.body === undefined) return null;
|
|
777
|
+
let doc;
|
|
778
|
+
try {
|
|
779
|
+
doc = JSON.parse(next.body);
|
|
780
|
+
} catch {
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
if (doc === null || typeof doc !== "object") return null;
|
|
784
|
+
let patch;
|
|
785
|
+
if (rule.op === "set-response-json") {
|
|
786
|
+
try {
|
|
787
|
+
patch = JSON.parse(value);
|
|
788
|
+
} catch {
|
|
789
|
+
patch = value; // not JSON: the text itself
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
if (!patchJson(doc, keys, rule.op === "set-response-json" ? { value: patch } : { remove: true })) return null;
|
|
793
|
+
setBody(JSON.stringify(doc));
|
|
794
|
+
return { response: next, note: `${rule.op === "set-response-json" ? "set" : "removed"} response JSON ${String(rule.name)}` };
|
|
795
|
+
}
|
|
796
|
+
default:
|
|
797
|
+
return null;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Response rules applied in order to a response (RWR-02): `{ response, changes: [{ rule: index, note }] }`. Only the response ops count
|
|
803
|
+
* (RESPONSE_OPS); a request op in the same list is left for rewriteRequest. `request` (optional) is what a rule's `when.method`, `host` and
|
|
804
|
+
* `pathPrefix` are checked against; `when.status` (`404`, `"4xx"`) is checked against the response so far. A rule that matches nothing, or
|
|
805
|
+
* changes nothing, is skipped. Pure: no network, and the input is not changed. The result is redacted again, so a rule can't write a credential into it.
|
|
806
|
+
*/
|
|
807
|
+
export function rewriteResponse(response, rules, { request } = {}) {
|
|
808
|
+
const done = applyResponseRules(readResponse(response), rules, { request });
|
|
809
|
+
return { response: readResponse(done.response), changes: done.changes };
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* The same rules over a response that is already `{ status, statusText, headers (lowercase object), body? (text) }`, WITHOUT the redaction
|
|
814
|
+
* readResponse does: for the response a served proxy route really sends (wave P-E, RWR-04), which must reach the client as the upstream
|
|
815
|
+
* made it, less what the rules change. Whatever is recorded of it is redacted separately. Pure; the input is not changed.
|
|
816
|
+
*/
|
|
817
|
+
export function applyResponseRules(response, rules, { request } = {}) {
|
|
818
|
+
let current = response;
|
|
819
|
+
const changes = [];
|
|
820
|
+
rules.forEach((rule, index) => {
|
|
821
|
+
if (!RESPONSE_OPS.includes(rule.op)) return;
|
|
822
|
+
try {
|
|
823
|
+
if (!responseRuleMatches(rule.when, current, request)) return;
|
|
824
|
+
const done = applyResponseRule(current, rule);
|
|
825
|
+
if (!done) return;
|
|
826
|
+
current = done.response;
|
|
827
|
+
changes.push({ rule: index, note: done.note });
|
|
828
|
+
} catch (error) {
|
|
829
|
+
if (error instanceof RuleRefusal) throw error;
|
|
830
|
+
changes.push({ rule: index, skipped: true, note: `skipped: ${String(error?.message ?? error).slice(0, 100)}` });
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
return { response: current, changes };
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** A response as raw HTTP text (what the rewrite pane shows and a text pane reads). */
|
|
837
|
+
export function responseText(r) {
|
|
838
|
+
const head = `HTTP/1.1 ${r.status}${r.statusText ? ` ${r.statusText}` : ""}`;
|
|
839
|
+
const lines = Object.entries(r.headers).map(([k, v]) => `${k}: ${v}`);
|
|
840
|
+
return `${[head, ...lines].join("\n")}${r.body !== undefined ? `\n\n${r.body}` : ""}`;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** Is this a response rather than a request: raw HTTP starting with a status line, or an object with a status and no method or URL? */
|
|
844
|
+
export const looksLikeResponse = (v) => (typeof v === "string" ? /^\s*HTTP\/[\d.]+\s+\d{3}/.test(v) : isObject(v) && Number.isInteger(v.status) && !("method" in v) && !("url" in v) && !("request" in v));
|
|
845
|
+
|
|
846
|
+
/** Two responses compared like two requests (status line, headers, body by JSON path or form field); the status is the "line". */
|
|
847
|
+
export function diffResponses(a, b) {
|
|
848
|
+
const as = (r) => ({ method: "→", url: `${r.status}${r.statusText ? ` ${r.statusText}` : ""}`, headers: r.headers, ...(r.body !== undefined ? { body: r.body } : {}) });
|
|
849
|
+
return diffRequests(as(a), as(b));
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// ── settings ─────────────────────────────────────────────────────────────────
|
|
853
|
+
|
|
854
|
+
export const defaultHttp = () => ({
|
|
855
|
+
mode: "convert",
|
|
856
|
+
to: "curl",
|
|
857
|
+
compose: { method: "GET", url: "https://api.example.com/items", headers: [{ name: "accept", value: "application/json" }], query: [], body: "" },
|
|
858
|
+
rules: [],
|
|
859
|
+
send: { auto: false, timeoutMs: 15000, maxBytes: 262144 },
|
|
860
|
+
tap: { ...TAP_DEFAULTS },
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
/** The static mode's settings (wave P-E, RTE-12): which file answers a directory, and whether an unknown path answers the index (a single-page app). */
|
|
864
|
+
export const STATIC_DEFAULTS = Object.freeze({ index: "index.html", spa: false, notFound: "" });
|
|
865
|
+
|
|
866
|
+
/** The tap settings as they are used: unknown keys dropped, defaults filled in, a number out of range falls back. */
|
|
867
|
+
export function cleanTap(raw) {
|
|
868
|
+
const r = isObject(raw) ? raw : {};
|
|
869
|
+
const int = (v, [low, high], d) => (Number.isInteger(v) && v >= low && v <= high ? v : d);
|
|
870
|
+
return { bodies: r.bodies === true, bodyBytes: int(r.bodyBytes, TAP_LIMITS.bodyBytes, TAP_DEFAULTS.bodyBytes), limit: int(r.limit, TAP_LIMITS.limit, TAP_DEFAULTS.limit) };
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/** What is wrong with these tap settings, or "". */
|
|
874
|
+
export function tapProblem(raw) {
|
|
875
|
+
if (raw === undefined) return "";
|
|
876
|
+
if (!isObject(raw)) return "tap must be an object";
|
|
877
|
+
if (raw.bodies !== undefined && typeof raw.bodies !== "boolean") return "tap.bodies must be true or false";
|
|
878
|
+
for (const key of ["bodyBytes", "limit"]) {
|
|
879
|
+
const [low, high] = TAP_LIMITS[key];
|
|
880
|
+
if (raw[key] !== undefined && !(Number.isInteger(raw[key]) && raw[key] >= low && raw[key] <= high)) return `tap.${key} must be a whole number from ${low} to ${high}`;
|
|
881
|
+
}
|
|
882
|
+
return "";
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
const clampInt = (value, [low, high], fallback) => (Number.isInteger(value) && value >= low && value <= high ? value : fallback);
|
|
886
|
+
|
|
887
|
+
const pairList = (list) => (Array.isArray(list) ? list.filter((x) => isObject(x)).map((x) => ({ name: String(x.name ?? ""), value: String(x.value ?? "") })) : []);
|
|
888
|
+
|
|
889
|
+
/** The settings as they are used: unknown keys dropped, defaults filled in. */
|
|
890
|
+
export function cleanHttp(raw) {
|
|
891
|
+
const d = defaultHttp();
|
|
892
|
+
const r = isObject(raw) ? raw : {};
|
|
893
|
+
const c = isObject(r.compose) ? r.compose : {};
|
|
894
|
+
return {
|
|
895
|
+
mode: HTTP_MODES.includes(r.mode) ? r.mode : d.mode,
|
|
896
|
+
to: TARGETS.includes(r.to) ? r.to : d.to,
|
|
897
|
+
compose: {
|
|
898
|
+
method: String(c.method ?? d.compose.method).toUpperCase(),
|
|
899
|
+
url: String(c.url ?? d.compose.url),
|
|
900
|
+
headers: c.headers === undefined ? d.compose.headers : pairList(c.headers),
|
|
901
|
+
query: pairList(c.query),
|
|
902
|
+
body: String(c.body ?? ""),
|
|
903
|
+
},
|
|
904
|
+
rules: Array.isArray(r.rules) ? r.rules.filter((x) => isObject(x)).map((x) => ({ ...(isObject(x.when) ? { when: cleanWhen(x.when) } : {}), op: String(x.op ?? ""), ...(x.name !== undefined ? { name: String(x.name) } : {}), ...(x.value !== undefined ? { value: String(x.value) } : {}), ...(x.all === false || x.all === "false" ? { all: false } : {}) })) : [],
|
|
905
|
+
send: { auto: r.send?.auto === true, timeoutMs: clampInt(r.send?.timeoutMs, SEND_LIMITS.timeoutMs, d.send.timeoutMs), maxBytes: clampInt(r.send?.maxBytes, SEND_LIMITS.maxBytes, d.send.maxBytes), ...(r.send?.via === "companion" ? { via: "companion" } : {}) },
|
|
906
|
+
tap: cleanTap(r.tap),
|
|
907
|
+
// Made from a capture log entry (a replay): its address, headers and body came from a log agents may not read, so agents read nothing of it (src/webmcp/hidden.js).
|
|
908
|
+
// Only the boolean true is kept, and an agent's change cannot clear it (httpPatch).
|
|
909
|
+
...(r.fromLog === true ? { fromLog: true } : {}),
|
|
910
|
+
// (only when the pane has them: an http pane that never proxied keeps saving the settings it always did)
|
|
911
|
+
...(r.proxy !== undefined ? { proxy: cleanProxy(r.proxy) } : {}),
|
|
912
|
+
...(r.static !== undefined ? { static: cleanStatic(r.static) } : {}),
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
const cleanStatic = (raw) => {
|
|
917
|
+
const r = isObject(raw) ? raw : {};
|
|
918
|
+
const name = (v, d) => (typeof v === "string" && v.length <= 128 && !/[\0\\]/.test(v) && !v.startsWith("/") && !v.split("/").includes("..") ? v : d);
|
|
919
|
+
return { index: name(r.index, STATIC_DEFAULTS.index) || STATIC_DEFAULTS.index, spa: r.spa === true, notFound: name(r.notFound, STATIC_DEFAULTS.notFound) };
|
|
920
|
+
};
|
|
921
|
+
|
|
922
|
+
function cleanWhen(w) {
|
|
923
|
+
return { ...(w.status !== undefined && /^([1-5]\d\d|[1-5]xx)$/i.test(String(w.status)) ? { status: /^\d+$/.test(String(w.status)) ? Number(w.status) : String(w.status).toLowerCase() } : {}), ...(w.method ? { method: String(w.method).toUpperCase() } : {}), ...(w.host ? { host: String(w.host) } : {}), ...(w.pathPrefix ? { pathPrefix: String(w.pathPrefix) } : {}) };
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* What is wrong with these settings, or "" (they are saved in the canvas, so a literal credential is refused here: it would be kept in the
|
|
928
|
+
* document). Run on every edit and every saved pane.
|
|
929
|
+
*/
|
|
930
|
+
export function httpProblem(raw) {
|
|
931
|
+
if (raw !== undefined && raw !== null && !isObject(raw)) return "http must be an object";
|
|
932
|
+
const s = cleanHttp(raw);
|
|
933
|
+
if (isObject(raw) && raw.mode !== undefined && !HTTP_MODES.includes(raw.mode)) return `mode must be one of ${HTTP_MODES.join(", ")}`;
|
|
934
|
+
if (isObject(raw) && raw.to !== undefined && !TARGETS.includes(raw.to)) return `to must be one of ${TARGETS.join(", ")}`;
|
|
935
|
+
if (isObject(raw) && raw.send !== undefined) {
|
|
936
|
+
if (!isObject(raw.send)) return "send must be an object";
|
|
937
|
+
if (raw.send.auto !== undefined && typeof raw.send.auto !== "boolean") return "send.auto must be true or false";
|
|
938
|
+
if (raw.send.via !== undefined && !SEND_VIAS.includes(raw.send.via)) return `send.via must be one of ${SEND_VIAS.join(", ")}`;
|
|
939
|
+
for (const key of ["timeoutMs", "maxBytes"]) {
|
|
940
|
+
const [low, high] = SEND_LIMITS[key];
|
|
941
|
+
if (raw.send[key] !== undefined && !(Number.isInteger(raw.send[key]) && raw.send[key] >= low && raw.send[key] <= high)) return `send.${key} must be a whole number from ${low} to ${high}`;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
const badTap = tapProblem(isObject(raw) ? raw.tap : undefined);
|
|
945
|
+
if (badTap) return badTap;
|
|
946
|
+
const badProxy = proxyProblem(isObject(raw) ? raw.proxy : undefined);
|
|
947
|
+
if (badProxy) return badProxy;
|
|
948
|
+
if (isObject(raw) && raw.static !== undefined) {
|
|
949
|
+
if (!isObject(raw.static)) return "static must be an object";
|
|
950
|
+
for (const key of Object.keys(raw.static)) if (!["index", "spa", "notFound"].includes(key)) return `static has no setting "${key}"`;
|
|
951
|
+
if (raw.static.spa !== undefined && typeof raw.static.spa !== "boolean") return "static.spa must be true or false";
|
|
952
|
+
for (const key of ["index", "notFound"]) if (raw.static[key] !== undefined && (typeof raw.static[key] !== "string" || cleanStatic({ [key]: raw.static[key] })[key] !== raw.static[key])) return `static.${key} must be a file path inside the folder (no leading /, no ..)`;
|
|
953
|
+
}
|
|
954
|
+
const credential = "is a credential: keep it in a secret pane and use its placeholder, so it is not saved in the canvas";
|
|
955
|
+
if (!METHOD.test(s.compose.method)) return "compose.method is not an HTTP method";
|
|
956
|
+
if (s.compose.url.length > 8192) return "compose.url is too long";
|
|
957
|
+
if (s.compose.body.length > MAX_TEXT_CHARS) return "compose.body is too large";
|
|
958
|
+
if (s.compose.headers.length > MAX_HEADERS || s.compose.query.length > MAX_HEADERS) return `compose has at most ${MAX_HEADERS} headers and ${MAX_HEADERS} query parameters`;
|
|
959
|
+
const u = redactUrl(s.compose.url);
|
|
960
|
+
if (u.redacted.length) return `compose.url holds ${u.redacted[0]}, which ${credential}`;
|
|
961
|
+
for (const { name, value } of s.compose.headers) {
|
|
962
|
+
if (name !== "" && !HEADER_NAME.test(name)) return `compose header "${name.slice(0, 40)}" isn't a header name`;
|
|
963
|
+
if (isCredentialHeader(name) && value !== "" && !hasPlaceholder(value)) return `compose header ${name} ${credential}`;
|
|
964
|
+
if (value !== "" && (redactHeaderValue(name, value) !== value || keyShaped(value))) return `compose header ${name} holds a key by its shape, which ${credential}`;
|
|
965
|
+
}
|
|
966
|
+
// A body is checked by its values too: a JSON or form field named like a credential, with a literal in it, is a credential.
|
|
967
|
+
if (s.compose.body !== "") {
|
|
968
|
+
const type = String(s.compose.headers.find((x) => x.name.toLowerCase() === "content-type")?.value ?? "");
|
|
969
|
+
const types = type ? [type] : ["", "application/x-www-form-urlencoded"];
|
|
970
|
+
if (types.some((t) => redactBody(s.compose.body, t) !== s.compose.body)) return `compose.body holds a credential field, which ${credential}`;
|
|
971
|
+
}
|
|
972
|
+
for (const { name, value } of s.compose.query) if (isCredentialParam(name) && value !== "" && !hasPlaceholder(value)) return `compose query ${name} ${credential}`;
|
|
973
|
+
if (s.rules.length > MAX_RULES) return `at most ${MAX_RULES} rules`;
|
|
974
|
+
for (const [i, rule] of s.rules.entries()) {
|
|
975
|
+
const at = `rule ${i + 1}`;
|
|
976
|
+
if (!REWRITE_OPS.includes(rule.op)) return `${at}: op must be one of ${REWRITE_OPS.join(", ")}`;
|
|
977
|
+
if ((rule.op === "replace-path" || rule.op === "replace-body" || rule.op === "replace-response-body") && (!rule.name || rule.name.length > MAX_PATTERN)) return `${at}: ${rule.op} needs the text to find in name (at most ${MAX_PATTERN} characters; it is plain text${rule.op === "replace-path" ? ", or a /regex/ with $1 in value" : ", not a regular expression"})`;
|
|
978
|
+
if (rule.op === "replace-path" && slashRegex(rule.name)) {
|
|
979
|
+
const wanted = slashRegex(rule.name);
|
|
980
|
+
const bad = slashRegexProblem(rule.name);
|
|
981
|
+
if (bad) return `${at}: replace-path name: ${bad}`;
|
|
982
|
+
if (compileSafeRegex(wanted.pattern).groups > 9) return `${at}: replace-path name: a regular expression with at most 9 groups`;
|
|
983
|
+
}
|
|
984
|
+
if (rule.when?.pathPrefix) {
|
|
985
|
+
const bad = slashRegexProblem(rule.when.pathPrefix);
|
|
986
|
+
if (bad) return `${at}: when.pathPrefix: ${bad}`;
|
|
987
|
+
}
|
|
988
|
+
if (rule.op === "set-header" && (!HEADER_NAME.test(rule.name ?? ""))) return `${at}: set-header needs a header name`;
|
|
989
|
+
if (rule.op === "set-header" && isCredentialHeader(rule.name) && (rule.value ?? "") !== "" && !hasPlaceholder(rule.value)) return `${at}: header ${rule.name} ${credential}`;
|
|
990
|
+
if (rule.op === "set-query" && isCredentialParam(rule.name) && (rule.value ?? "") !== "" && !hasPlaceholder(rule.value)) return `${at}: query ${rule.name} ${credential}`;
|
|
991
|
+
if ((rule.op === "set-query" || rule.op === "remove-query" || rule.op === "remove-header") && !rule.name) return `${at}: ${rule.op} needs a name`;
|
|
992
|
+
if (rule.op === "set-status" && !(Number.isInteger(Number(rule.value)) && Number(rule.value) >= 100 && Number(rule.value) <= 599 && String(rule.value ?? "").trim() !== "")) return `${at}: set-status needs a status from 100 to 599 in value`;
|
|
993
|
+
if (rule.op === "set-response-header" && !HEADER_NAME.test(rule.name ?? "")) return `${at}: set-response-header needs a header name`;
|
|
994
|
+
if (rule.op === "remove-response-header" && !rule.name) return `${at}: remove-response-header needs a name`;
|
|
995
|
+
if (rule.op === "set-response-header" && isCredentialHeader(rule.name) && (rule.value ?? "") !== "" && !hasPlaceholder(rule.value)) return `${at}: header ${rule.name} ${credential}`;
|
|
996
|
+
if ((rule.op === "set-response-json" || rule.op === "remove-response-json") && !jsonPathKeys(rule.name)) return `${at}: ${rule.op} needs a path in name ($.user.name, items[0].id or /user/name)`;
|
|
997
|
+
if (rule.op === "set-response-json") {
|
|
998
|
+
// The value is checked under its own key: a password is a credential because of the field it is written to, not because of its look.
|
|
999
|
+
const key = jsonPathKeys(rule.name)?.at(-1) ?? "value";
|
|
1000
|
+
let parsed;
|
|
1001
|
+
try {
|
|
1002
|
+
parsed = JSON.parse(rule.value ?? "");
|
|
1003
|
+
} catch {
|
|
1004
|
+
parsed = String(rule.value ?? "");
|
|
1005
|
+
}
|
|
1006
|
+
const wrapped = JSON.stringify({ [key]: parsed });
|
|
1007
|
+
if (redactBody(wrapped, "application/json") !== wrapped) return `${at}: the JSON value holds a credential, which ${credential}`;
|
|
1008
|
+
}
|
|
1009
|
+
if (["set-body", "replace-body", "set-response-body", "replace-response-body"].includes(rule.op) && (rule.value ?? "") !== "") {
|
|
1010
|
+
const v = String(rule.value);
|
|
1011
|
+
if (["", "application/json", "application/x-www-form-urlencoded"].some((t) => redactBody(v, t) !== v) || keyShaped(v)) return `${at}: the ${rule.op} value holds a credential, which ${credential}`;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
return "";
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/** The settings' words for the Markdown format and an agent. */
|
|
1018
|
+
export function describeHttp(raw) {
|
|
1019
|
+
const s = cleanHttp(raw);
|
|
1020
|
+
if (s.fromLog && (s.mode === "send" || s.mode === "compose")) return `${s.mode} a request taken from a capture log (its address, headers and body are withheld from agents)`;
|
|
1021
|
+
if (s.mode === "convert") return `convert any HTTP request to ${TARGET_LABELS[s.to]}`;
|
|
1022
|
+
if (s.mode === "compose") return `compose ${s.compose.method} ${redactUrl(s.compose.url).url} as ${TARGET_LABELS[s.to]}`;
|
|
1023
|
+
if (s.mode === "diff") return "diff two requests";
|
|
1024
|
+
if (s.mode === "send") return `send ${s.compose.method} ${redactUrl(s.compose.url).url} through the network policy${s.send.auto ? " on every run" : " when run (▶)"}`;
|
|
1025
|
+
if (s.mode === "proxy") {
|
|
1026
|
+
const p = cleanProxy(s.proxy);
|
|
1027
|
+
return `proxy a served request to ${p.targets.length ? `${p.targets.length + (p.upstream ? 1 : 0)} fixed upstreams` : p.upstream ? "a fixed upstream" : "an upstream (not set)"} through the network policy, recording each exchange (credentials redacted, bodies ${p.bodies ? "kept" : "off"})`;
|
|
1028
|
+
}
|
|
1029
|
+
if (s.mode === "static") {
|
|
1030
|
+
const st = cleanStatic(s.static);
|
|
1031
|
+
return `answer a served request from a wired folder (index ${st.index}${st.spa ? ", unknown paths get the index" : ""})`;
|
|
1032
|
+
}
|
|
1033
|
+
if (s.mode === "tap") return `tap this canvas's own requests as they pass the network policy (read-only, credentials redacted, bodies ${s.tap.bodies ? "kept" : "off"})`;
|
|
1034
|
+
return `rewrite a request with ${s.rules.length} rule${s.rules.length === 1 ? "" : "s"} as ${TARGET_LABELS[s.to]}`;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
// ── the run ──────────────────────────────────────────────────────────────────
|
|
1038
|
+
|
|
1039
|
+
/** The compose settings as a request, with any wired input laid over it (url, method, body, headers: {…}, query: {…}). */
|
|
1040
|
+
export function composeRequest(settings, inputs = {}) {
|
|
1041
|
+
const c = settings.compose;
|
|
1042
|
+
let url = String(inputs.url ?? c.url);
|
|
1043
|
+
const headers = {};
|
|
1044
|
+
for (const { name, value } of c.headers) if (name !== "") add(headers, name, value);
|
|
1045
|
+
if (isObject(inputs.headers)) for (const [name, value] of Object.entries(inputs.headers)) headers[String(name).toLowerCase()] = one(value);
|
|
1046
|
+
const query = [...c.query.map((q) => [q.name, q.value])];
|
|
1047
|
+
if (isObject(inputs.query)) for (const [name, value] of Object.entries(inputs.query)) query.push([name, one(value)]);
|
|
1048
|
+
const filled = query.filter(([name]) => name !== "");
|
|
1049
|
+
if (filled.length) {
|
|
1050
|
+
const p = parts(url);
|
|
1051
|
+
const extra = filled.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`);
|
|
1052
|
+
url = `${p.origin}${p.path}?${[...queryPairs(p.query), ...extra].join("&")}${p.hash}`;
|
|
1053
|
+
}
|
|
1054
|
+
const raw = inputs.body !== undefined ? inputs.body : c.body;
|
|
1055
|
+
const body = typeof raw === "string" ? raw : raw === undefined || raw === null ? "" : JSON.stringify(raw);
|
|
1056
|
+
if (body !== "" && typeof raw !== "string" && !headers["content-type"]) headers["content-type"] = "application/json";
|
|
1057
|
+
if (!url) throw new Error("compose needs a url");
|
|
1058
|
+
return shape({ method: String(inputs.method ?? c.method), url, headers, body });
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* Run the pane: `inputs` is { name: value } of what is wired in, in wire order (`list`). Returns the pane's value. Nothing here sends a request.
|
|
1063
|
+
* Convert reads the first input as the request; diff reads `a` and `b` (or the first two); rewrite reads `request` (or the first);
|
|
1064
|
+
* rules can also come in on an input named `rules`.
|
|
1065
|
+
*/
|
|
1066
|
+
export async function runHttp(raw, inputs = {}, list = []) {
|
|
1067
|
+
const problem = httpProblem(raw);
|
|
1068
|
+
if (problem) throw new Error(problem);
|
|
1069
|
+
const s = cleanHttp(raw);
|
|
1070
|
+
if (s.mode === "tap") throw new Error("tap mode runs in a canvas, beside its network policy (src/model/http-tap.js); this engine reads no traffic");
|
|
1071
|
+
if (s.mode === "proxy") throw new Error("proxy mode runs in a served canvas, through its network policy (src/model/runners/http-proxy.js); this engine sends nothing");
|
|
1072
|
+
if (s.mode === "static") throw new Error("static mode answers a request from a folder (src/model/runners/http-static.js)");
|
|
1073
|
+
if (s.mode === "send") throw new Error("send mode runs in a canvas, through its network policy (src/model/http-send.js); this engine sends nothing");
|
|
1074
|
+
const positional = list.filter((n) => n !== "rules" && !(s.mode === "rewrite" && n === "response"));
|
|
1075
|
+
const pick = (...names) => {
|
|
1076
|
+
for (const n of names) if (inputs[n] !== undefined) return inputs[n];
|
|
1077
|
+
return inputs[positional.find((n) => !["a", "b"].includes(n))];
|
|
1078
|
+
};
|
|
1079
|
+
if (s.mode === "compose") {
|
|
1080
|
+
const { request, redacted } = redactRequest(composeRequest(s, inputs));
|
|
1081
|
+
return { mode: "compose", request, text: await textFor([request], s.to), formats: await formatsOf(request), redacted };
|
|
1082
|
+
}
|
|
1083
|
+
if (s.mode === "diff") {
|
|
1084
|
+
const rest = positional.filter((n) => n !== "a" && n !== "b");
|
|
1085
|
+
const a = inputs.a ?? inputs[rest.shift()];
|
|
1086
|
+
const b = inputs.b ?? inputs[rest.shift()];
|
|
1087
|
+
if (a === undefined || b === undefined) throw new Error("wire two requests in, named a and b");
|
|
1088
|
+
if (looksLikeResponse(a) && looksLikeResponse(b)) {
|
|
1089
|
+
// Two responses (raw HTTP "HTTP/1.1 200 OK…", or objects with a status): the status line, the headers and the body by path or field.
|
|
1090
|
+
const ra = readResponse(a);
|
|
1091
|
+
const rb = readResponse(b);
|
|
1092
|
+
const diff = diffResponses(ra, rb);
|
|
1093
|
+
return { mode: "diff", kind: "response", identical: diff.identical, text: diff.identical ? "the responses are the same" : diffText(diff), changes: diff, a: ra, b: rb, redacted: [] };
|
|
1094
|
+
}
|
|
1095
|
+
const left = redactRequest(readRequests(a).requests[0]);
|
|
1096
|
+
const right = redactRequest(readRequests(b).requests[0]);
|
|
1097
|
+
const diff = diffRequests(left.request, right.request);
|
|
1098
|
+
// The same two requests written in the pane's target form (`to`: cURL, fetch(), raw HTTP, HAR) and compared line by line (DIF-02).
|
|
1099
|
+
const form = await diffForms(left.request, right.request, s.to);
|
|
1100
|
+
return { mode: "diff", identical: diff.identical, text: diffText(diff), changes: diff, form, a: left.request, b: right.request, redacted: [...new Set([...left.redacted, ...right.redacted])] };
|
|
1101
|
+
}
|
|
1102
|
+
const responseIn = s.mode === "rewrite" ? inputs.response : undefined;
|
|
1103
|
+
const source = s.mode === "rewrite" ? pick("request") : pick("request", "input");
|
|
1104
|
+
if (source === undefined && responseIn === undefined) throw new Error(s.mode === "rewrite" ? "wire a request in (or a response)" : "wire a request in (a curl command, a fetch() call, raw HTTP or a HAR file)");
|
|
1105
|
+
if (source === undefined) return rewriteResponseOnly(s, responseIn, inputs);
|
|
1106
|
+
const { kind, requests } = readRequests(source);
|
|
1107
|
+
if (s.mode === "convert") {
|
|
1108
|
+
const safe = requests.map(redactRequest);
|
|
1109
|
+
const list2 = safe.map((x) => x.request);
|
|
1110
|
+
return { mode: "convert", kind, to: s.to, count: list2.length, request: list2[0], requests: list2, text: await textFor(list2, s.to), formats: await formatsOf(list2[0]), redacted: [...new Set(safe.flatMap((x) => x.redacted))] };
|
|
1111
|
+
}
|
|
1112
|
+
// rewrite
|
|
1113
|
+
const wired = Array.isArray(inputs.rules) ? cleanHttp({ rules: inputs.rules }).rules : [];
|
|
1114
|
+
const rules = [...s.rules, ...wired];
|
|
1115
|
+
const bad = httpProblem({ rules });
|
|
1116
|
+
if (bad) throw new Error(bad);
|
|
1117
|
+
const before = redactRequest(requests[0]);
|
|
1118
|
+
const done = rewriteRequest(requests[0], rules);
|
|
1119
|
+
const after = redactRequest(done.request);
|
|
1120
|
+
const value = { mode: "rewrite", request: after.request, before: before.request, text: await textFor([after.request], s.to), formats: await formatsOf(after.request), changes: done.changes, redacted: [...new Set([...before.redacted, ...after.redacted])] };
|
|
1121
|
+
if (responseIn !== undefined) Object.assign(value, responseSide(responseIn, rules, requests[0]));
|
|
1122
|
+
return value;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/** The response side of a rewrite: the response wired in, before and after the rules (RWR-02), with raw HTTP text of each. */
|
|
1126
|
+
function responseSide(input, rules, request) {
|
|
1127
|
+
const before = readResponse(input);
|
|
1128
|
+
const done = rewriteResponse(before, rules, { request });
|
|
1129
|
+
return { response: done.response, responseBefore: before, responseText: responseText(done.response), responseChanges: done.changes };
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
async function rewriteResponseOnly(s, input, inputs) {
|
|
1133
|
+
const wired = Array.isArray(inputs.rules) ? cleanHttp({ rules: inputs.rules }).rules : [];
|
|
1134
|
+
const rules = [...s.rules, ...wired];
|
|
1135
|
+
const bad = httpProblem({ rules });
|
|
1136
|
+
if (bad) throw new Error(bad);
|
|
1137
|
+
return { mode: "rewrite", ...responseSide(input, rules, undefined), changes: [], redacted: [] };
|
|
1138
|
+
}
|