@tonyclaw/agent-inspector 4.0.1 → 4.0.3
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/.output/backend/nitro.json +1 -1
- package/.output/cli.js +193 -110
- package/.output/server/_ssr/index.mjs +1 -1
- package/.output/server/_ssr/{router-CTHqmroT.mjs → router-ChILzhmz.mjs} +92 -4
- package/.output/server/index.mjs +1 -1
- package/.output/ui/assets/{CompareDrawer-L3n4J-Or.js → CompareDrawer-Co3cUF_I.js} +1 -1
- package/.output/ui/assets/{InspectorPet-D5o_3OZS.js → InspectorPet-jFcrL37X.js} +1 -1
- package/.output/ui/assets/{ProxyViewerContainer-Ocagx75S.js → ProxyViewerContainer-BPzt_VpM.js} +4 -4
- package/.output/ui/assets/{ReplayDialog-Bk7x1h-y.js → ReplayDialog-C6O_zuwI.js} +1 -1
- package/.output/ui/assets/{RequestAnatomy-U4lzL7Sc.js → RequestAnatomy-Ca6NvB7L.js} +1 -1
- package/.output/ui/assets/{ResponseView-LOWfvBLK.js → ResponseView-BzqKcveJ.js} +1 -1
- package/.output/ui/assets/{StreamingChunkSequence-DPfsrrXQ.js → StreamingChunkSequence-9pCZIsS_.js} +1 -1
- package/.output/ui/assets/{_sessionId-0MlWS-CO.js → _sessionId-BMP3KVGR.js} +1 -1
- package/.output/ui/assets/{_sessionId-OdX2Jvt1.js → _sessionId-y4eRoT1H.js} +1 -1
- package/.output/ui/assets/{index-Ea-c8hPg.js → index-CH5w-haG.js} +1 -1
- package/.output/ui/assets/{index-zVVS53Hd.js → index-CmocEhyU.js} +1 -1
- package/.output/ui/assets/{index-Du4qNOOt.js → index-DT8sMJ_n.js} +2 -2
- package/.output/ui/assets/{index-gvFj_9K6.js → index-bfsbIRZa.js} +1 -1
- package/.output/ui/assets/{json-viewer-C1WAMzg3.js → json-viewer-BfFOSDG5.js} +1 -1
- package/.output/ui/assets/{jszip.min-B8AKu2zm.js → jszip.min-BkbVkOsp.js} +1 -1
- package/.output/ui/index.html +1 -1
- package/package.json +5 -10
- package/src/assets/IDE/claudecode-color.svg +0 -1
- package/src/assets/IDE/codex-color.svg +0 -1
- package/src/assets/IDE/opencode.svg +0 -1
- package/src/assets/IDE/xiaomimimo.svg +0 -1
- package/src/assets/favicon.svg +0 -21
- package/src/assets/logos/alibaba.svg +0 -1
- package/src/assets/logos/anthropic.svg +0 -1
- package/src/assets/logos/claude-code.svg +0 -4
- package/src/assets/logos/deepseek.svg +0 -1
- package/src/assets/logos/minimax.jpeg +0 -0
- package/src/assets/logos/openai.svg +0 -1
- package/src/assets/logos/opencode.svg +0 -4
- package/src/assets/logos/qwen.webp +0 -0
- package/src/assets/logos/zhipuai.svg +0 -219
- package/src/backend/router.tsx +0 -36
- package/src/backend/routes/$.ts +0 -26
- package/src/backend/routes/__root.ts +0 -4
- package/src/backend/routes/api/-instances.ts +0 -7
- package/src/backend/routes/api/alerts.summary.ts +0 -28
- package/src/backend/routes/api/alerts.ts +0 -70
- package/src/backend/routes/api/config.paths.ts +0 -14
- package/src/backend/routes/api/config.ts +0 -73
- package/src/backend/routes/api/ecosystem.packages.$packageId.help.ts +0 -11
- package/src/backend/routes/api/ecosystem.packages.$packageId.install.ts +0 -11
- package/src/backend/routes/api/ecosystem.packages.$packageId.runner-presets.ts +0 -11
- package/src/backend/routes/api/ecosystem.packages.$packageId.upgrade.ts +0 -11
- package/src/backend/routes/api/ecosystem.packages.ts +0 -21
- package/src/backend/routes/api/ecosystem.recipes.$recipeId.run.ts +0 -11
- package/src/backend/routes/api/ecosystem.tasks.$taskId.ts +0 -16
- package/src/backend/routes/api/ecosystem.tasks.ts +0 -12
- package/src/backend/routes/api/groups.$groupId.evidence.ts +0 -55
- package/src/backend/routes/api/groups.$groupId.sessions.ts +0 -50
- package/src/backend/routes/api/groups.$groupId.ts +0 -93
- package/src/backend/routes/api/groups.ts +0 -79
- package/src/backend/routes/api/health.ts +0 -22
- package/src/backend/routes/api/instances.$name.connection.ts +0 -12
- package/src/backend/routes/api/instances.$name.restart.ts +0 -23
- package/src/backend/routes/api/instances.$name.start.ts +0 -18
- package/src/backend/routes/api/instances.$name.stop.ts +0 -23
- package/src/backend/routes/api/instances.$name.ts +0 -12
- package/src/backend/routes/api/instances.ts +0 -16
- package/src/backend/routes/api/knowledge.candidates.$candidateId.promote.ts +0 -32
- package/src/backend/routes/api/knowledge.candidates.$candidateId.ts +0 -50
- package/src/backend/routes/api/knowledge.candidates.ts +0 -10
- package/src/backend/routes/api/knowledge.project-context.ts +0 -29
- package/src/backend/routes/api/knowledge.search.ts +0 -62
- package/src/backend/routes/api/knowledge.sessions.$sessionId.candidates.ts +0 -26
- package/src/backend/routes/api/logs.$id.body.ts +0 -58
- package/src/backend/routes/api/logs.$id.chunks.ts +0 -37
- package/src/backend/routes/api/logs.$id.replay.ts +0 -297
- package/src/backend/routes/api/logs.$id.ts +0 -23
- package/src/backend/routes/api/logs.import.ts +0 -39
- package/src/backend/routes/api/logs.stream.ts +0 -174
- package/src/backend/routes/api/logs.ts +0 -214
- package/src/backend/routes/api/mcp.ts +0 -25
- package/src/backend/routes/api/models.ts +0 -10
- package/src/backend/routes/api/pi-agent.ts +0 -29
- package/src/backend/routes/api/providers.$providerId.model-metadata.ts +0 -173
- package/src/backend/routes/api/providers.$providerId.test.log.ts +0 -342
- package/src/backend/routes/api/providers.$providerId.ts +0 -111
- package/src/backend/routes/api/providers.export.ts +0 -44
- package/src/backend/routes/api/providers.import.ts +0 -81
- package/src/backend/routes/api/providers.scan.ts +0 -28
- package/src/backend/routes/api/providers.ts +0 -102
- package/src/backend/routes/api/runs.$runId.evidence.ts +0 -55
- package/src/backend/routes/api/runs.$runId.ts +0 -50
- package/src/backend/routes/api/runs.ts +0 -62
- package/src/backend/routes/api/runtime.ts +0 -46
- package/src/backend/routes/api/sessions.ts +0 -51
- package/src/backend/routes/api/storage.ts +0 -56
- package/src/backend/routes/livez.ts +0 -13
- package/src/backend/routes/metrics.ts +0 -14
- package/src/backend/routes/proxy/$.ts +0 -15
- package/src/backend/routes/readyz.ts +0 -18
- package/src/backend/start.ts +0 -10
- package/src/cli/alias.ts +0 -431
- package/src/cli/detect-tools.ts +0 -123
- package/src/cli/doctor.ts +0 -836
- package/src/cli/instance.ts +0 -1071
- package/src/cli/instanceApi.ts +0 -213
- package/src/cli/instanceArgs.ts +0 -301
- package/src/cli/instanceControl.ts +0 -191
- package/src/cli/instanceModel.ts +0 -276
- package/src/cli/instanceRegistry.ts +0 -731
- package/src/cli/networkHints.ts +0 -170
- package/src/cli/onboard.ts +0 -1668
- package/src/cli/onboardTarget.ts +0 -228
- package/src/cli/rustBackendPackage.ts +0 -458
- package/src/cli/startupOutput.ts +0 -16
- package/src/cli/templates/codex-skill-onboard.ts +0 -320
- package/src/cli/templates/command-onboard.ts +0 -25
- package/src/cli/templates/skill-onboard.ts +0 -625
- package/src/cli.ts +0 -1433
- package/src/components/OnboardingBanner.tsx +0 -115
- package/src/components/ProxyViewer.tsx +0 -2259
- package/src/components/ProxyViewerContainer.tsx +0 -1076
- package/src/components/alerts/AlertsDialog.tsx +0 -615
- package/src/components/clients/ClientLogo.tsx +0 -175
- package/src/components/ecosystem/AgentLabDialog.tsx +0 -947
- package/src/components/errors/SafeErrorBoundary.tsx +0 -201
- package/src/components/groups/GroupsDialog.tsx +0 -1304
- package/src/components/inspector-pet/InspectorPet.tsx +0 -398
- package/src/components/inspector-pet/InspectorPetCrab3D.tsx +0 -455
- package/src/components/inspector-pet/inspectorPetLogic.ts +0 -272
- package/src/components/pi-agent/PiAgentPanel.tsx +0 -446
- package/src/components/pi-agent/piAgentChatLogic.ts +0 -273
- package/src/components/providers/ImportWizardDialog.tsx +0 -281
- package/src/components/providers/ProviderCard.tsx +0 -347
- package/src/components/providers/ProviderForm.tsx +0 -1183
- package/src/components/providers/ProviderLogo.tsx +0 -122
- package/src/components/providers/ProviderTestResultsView.tsx +0 -734
- package/src/components/providers/ProvidersPanel.tsx +0 -714
- package/src/components/providers/SettingsDialog.tsx +0 -1042
- package/src/components/providers/providerFormCapabilities.ts +0 -36
- package/src/components/proxy-viewer/AgentTraceSummary.tsx +0 -902
- package/src/components/proxy-viewer/AnswerMarkdown.tsx +0 -51
- package/src/components/proxy-viewer/ApplicationBar.tsx +0 -123
- package/src/components/proxy-viewer/CompareDrawer.tsx +0 -984
- package/src/components/proxy-viewer/ConversationGroup.tsx +0 -208
- package/src/components/proxy-viewer/ConversationGroupList.tsx +0 -652
- package/src/components/proxy-viewer/ConversationHeader.tsx +0 -429
- package/src/components/proxy-viewer/LiveConnectionStatus.tsx +0 -186
- package/src/components/proxy-viewer/LogEntry.tsx +0 -1419
- package/src/components/proxy-viewer/LogEntryHeader.tsx +0 -596
- package/src/components/proxy-viewer/ProviderLogoStack.tsx +0 -57
- package/src/components/proxy-viewer/RawExportWarning.tsx +0 -77
- package/src/components/proxy-viewer/ReplayDialog.tsx +0 -636
- package/src/components/proxy-viewer/RequestToolsPanel.tsx +0 -299
- package/src/components/proxy-viewer/ResponseView.tsx +0 -202
- package/src/components/proxy-viewer/SessionLoadProgressBar.tsx +0 -61
- package/src/components/proxy-viewer/StreamingChunkSequence.tsx +0 -265
- package/src/components/proxy-viewer/ThreadConnector.tsx +0 -165
- package/src/components/proxy-viewer/ToolTraceEvents.tsx +0 -64
- package/src/components/proxy-viewer/TurnGroup.tsx +0 -383
- package/src/components/proxy-viewer/TurnGroupList.tsx +0 -156
- package/src/components/proxy-viewer/accessibility.ts +0 -8
- package/src/components/proxy-viewer/anatomy/RequestAnatomy.tsx +0 -887
- package/src/components/proxy-viewer/anatomy/SegmentBar.tsx +0 -222
- package/src/components/proxy-viewer/anatomy/contextIntelligence.ts +0 -737
- package/src/components/proxy-viewer/anatomy/sessionContextSummary.ts +0 -268
- package/src/components/proxy-viewer/anatomy/tokenEstimate.ts +0 -53
- package/src/components/proxy-viewer/anatomy/types.ts +0 -41
- package/src/components/proxy-viewer/anatomy/useAnatomyJump.ts +0 -114
- package/src/components/proxy-viewer/bodyHydration.ts +0 -123
- package/src/components/proxy-viewer/cacheTrend.ts +0 -50
- package/src/components/proxy-viewer/diff/DiffView.tsx +0 -321
- package/src/components/proxy-viewer/diff/computeDiff.ts +0 -178
- package/src/components/proxy-viewer/diff/index.ts +0 -3
- package/src/components/proxy-viewer/formats/anthropic/ContentBlocks.tsx +0 -194
- package/src/components/proxy-viewer/formats/anthropic/ResponseView.tsx +0 -81
- package/src/components/proxy-viewer/formats/anthropic/thinkingExtract.ts +0 -21
- package/src/components/proxy-viewer/formats/index.tsx +0 -47
- package/src/components/proxy-viewer/formats/openai/ResponseView.tsx +0 -442
- package/src/components/proxy-viewer/index.ts +0 -9
- package/src/components/proxy-viewer/lazy.ts +0 -41
- package/src/components/proxy-viewer/liveConnectionState.ts +0 -158
- package/src/components/proxy-viewer/log-formats/anthropic.ts +0 -191
- package/src/components/proxy-viewer/log-formats/index.ts +0 -23
- package/src/components/proxy-viewer/log-formats/openai.ts +0 -256
- package/src/components/proxy-viewer/log-formats/types.ts +0 -40
- package/src/components/proxy-viewer/log-formats/unknown.ts +0 -18
- package/src/components/proxy-viewer/logEntryVisibility.ts +0 -73
- package/src/components/proxy-viewer/logFocus.ts +0 -54
- package/src/components/proxy-viewer/proxyViewerContainerLogic.ts +0 -124
- package/src/components/proxy-viewer/proxyViewerLogic.ts +0 -488
- package/src/components/proxy-viewer/replayComparison.ts +0 -131
- package/src/components/proxy-viewer/requestDiff.ts +0 -277
- package/src/components/proxy-viewer/requestTools.ts +0 -220
- package/src/components/proxy-viewer/useCopyFeedback.ts +0 -38
- package/src/components/proxy-viewer/useKeyboardNavigation.ts +0 -232
- package/src/components/proxy-viewer/viewerState.ts +0 -176
- package/src/components/ui/badge.tsx +0 -47
- package/src/components/ui/button.tsx +0 -47
- package/src/components/ui/collapsible.tsx +0 -21
- package/src/components/ui/confirm-dialog.tsx +0 -51
- package/src/components/ui/crab-logo.tsx +0 -45
- package/src/components/ui/crab-variants.tsx +0 -467
- package/src/components/ui/dialog.tsx +0 -130
- package/src/components/ui/icon-trigger.ts +0 -2
- package/src/components/ui/json-viewer-bulk.ts +0 -132
- package/src/components/ui/json-viewer.tsx +0 -508
- package/src/components/ui/scroll-area.tsx +0 -54
- package/src/components/ui/select.tsx +0 -178
- package/src/components/ui/separator.tsx +0 -28
- package/src/components/ui/tabs.tsx +0 -88
- package/src/components/ui/tooltip.tsx +0 -51
- package/src/components/ui/transient-toast.tsx +0 -105
- package/src/contracts/anthropic.ts +0 -230
- package/src/contracts/index.ts +0 -59
- package/src/contracts/json.ts +0 -37
- package/src/contracts/log.ts +0 -139
- package/src/contracts/openai.ts +0 -267
- package/src/index.css +0 -11
- package/src/knowledge/candidateStore.ts +0 -94
- package/src/knowledge/distiller.ts +0 -98
- package/src/knowledge/openclawClient.ts +0 -161
- package/src/knowledge/openclawGatewayClient.ts +0 -249
- package/src/knowledge/openclawMarkdown.ts +0 -146
- package/src/knowledge/redactor.ts +0 -80
- package/src/knowledge/types.ts +0 -83
- package/src/lib/alertContract.ts +0 -76
- package/src/lib/apiClient.ts +0 -166
- package/src/lib/apiFormat.ts +0 -29
- package/src/lib/backendImplementation.ts +0 -16
- package/src/lib/basePath.ts +0 -107
- package/src/lib/browserRuntimeContract.ts +0 -124
- package/src/lib/browserRuntimeResolver.ts +0 -333
- package/src/lib/chunkLoadRecovery.ts +0 -83
- package/src/lib/claudeCodeStrip.ts +0 -98
- package/src/lib/clipboard.ts +0 -67
- package/src/lib/codingAgentEndpoints.ts +0 -54
- package/src/lib/ecosystemContract.ts +0 -130
- package/src/lib/export-logs.ts +0 -287
- package/src/lib/groupContract.ts +0 -166
- package/src/lib/instanceContract.ts +0 -239
- package/src/lib/jsonFile.ts +0 -46
- package/src/lib/logImportContract.ts +0 -12
- package/src/lib/managedInstance.ts +0 -112
- package/src/lib/mask.ts +0 -4
- package/src/lib/objectUtils.ts +0 -22
- package/src/lib/piAgentContract.ts +0 -102
- package/src/lib/providerContract.ts +0 -125
- package/src/lib/providerImportContract.ts +0 -27
- package/src/lib/providerModelMetadata.ts +0 -458
- package/src/lib/providerTestContract.ts +0 -170
- package/src/lib/providerTestPrompt.ts +0 -100
- package/src/lib/publicBasePathContext.ts +0 -137
- package/src/lib/resourceLimits.ts +0 -345
- package/src/lib/runContract.ts +0 -164
- package/src/lib/runtimeConfig.ts +0 -43
- package/src/lib/safeDiagnostic.ts +0 -38
- package/src/lib/safeFetch.ts +0 -508
- package/src/lib/serverPort.ts +0 -47
- package/src/lib/sessionInfoContract.ts +0 -78
- package/src/lib/sessionUrl.ts +0 -46
- package/src/lib/ssrfGuard.ts +0 -133
- package/src/lib/stopReason.ts +0 -130
- package/src/lib/themeMode.ts +0 -41
- package/src/lib/timeDisplay.ts +0 -22
- package/src/lib/toolTrace.ts +0 -290
- package/src/lib/uiScale.ts +0 -117
- package/src/lib/unknown.ts +0 -27
- package/src/lib/upstreamUrl.ts +0 -150
- package/src/lib/useAlerts.ts +0 -82
- package/src/lib/useGroupEvidence.ts +0 -37
- package/src/lib/useGroups.ts +0 -32
- package/src/lib/useOnboarding.ts +0 -93
- package/src/lib/useProviders.ts +0 -30
- package/src/lib/useStripConfig.ts +0 -154
- package/src/lib/useThemeMode.ts +0 -40
- package/src/lib/useUiScale.ts +0 -52
- package/src/lib/utils.ts +0 -78
- package/src/mcp/currentContext.ts +0 -65
- package/src/mcp/instanceHandlers.ts +0 -151
- package/src/mcp/loopback.ts +0 -88
- package/src/mcp/mode.ts +0 -75
- package/src/mcp/previewExtractor.ts +0 -233
- package/src/mcp/server.ts +0 -2274
- package/src/mcp/toolHandlers.ts +0 -1533
- package/src/proxy/alerts.ts +0 -664
- package/src/proxy/chunkStorage.ts +0 -123
- package/src/proxy/config.ts +0 -218
- package/src/proxy/constants.ts +0 -66
- package/src/proxy/dataDir.ts +0 -147
- package/src/proxy/ecosystemExecutionConfirmation.ts +0 -114
- package/src/proxy/ecosystemExecutionRoute.ts +0 -116
- package/src/proxy/ecosystemRegistry.ts +0 -296
- package/src/proxy/ecosystemTasks.ts +0 -415
- package/src/proxy/evidenceAnalysis.ts +0 -526
- package/src/proxy/evidenceExporter.ts +0 -235
- package/src/proxy/formats/anthropic/anthropicProvider.ts +0 -75
- package/src/proxy/formats/anthropic/handler.ts +0 -75
- package/src/proxy/formats/anthropic/index.ts +0 -13
- package/src/proxy/formats/anthropic/register.ts +0 -4
- package/src/proxy/formats/anthropic/schemas.ts +0 -6
- package/src/proxy/formats/anthropic/stream.ts +0 -205
- package/src/proxy/formats/handler.ts +0 -46
- package/src/proxy/formats/index.ts +0 -13
- package/src/proxy/formats/jsonSchema.ts +0 -2
- package/src/proxy/formats/openai/alibabaProvider.ts +0 -34
- package/src/proxy/formats/openai/codexMetadata.ts +0 -61
- package/src/proxy/formats/openai/handler.ts +0 -133
- package/src/proxy/formats/openai/index.ts +0 -33
- package/src/proxy/formats/openai/provider.ts +0 -50
- package/src/proxy/formats/openai/register.ts +0 -4
- package/src/proxy/formats/openai/schemas.ts +0 -25
- package/src/proxy/formats/openai/stream.ts +0 -600
- package/src/proxy/formats/openai/zhipuProvider.ts +0 -31
- package/src/proxy/formats/providerAdapter.ts +0 -50
- package/src/proxy/formats/providerRegistry.ts +0 -51
- package/src/proxy/formats/providers/index.ts +0 -3
- package/src/proxy/formats/registry.ts +0 -65
- package/src/proxy/groupEvidenceExporter.ts +0 -371
- package/src/proxy/groupStore.ts +0 -336
- package/src/proxy/handler.ts +0 -729
- package/src/proxy/identityProxy.ts +0 -1842
- package/src/proxy/jsonlRecovery.ts +0 -554
- package/src/proxy/logBodyChunks.ts +0 -91
- package/src/proxy/logFinalizer.ts +0 -777
- package/src/proxy/logFinalizer.worker.ts +0 -24
- package/src/proxy/logImportUpload.ts +0 -128
- package/src/proxy/logImporter.ts +0 -813
- package/src/proxy/logIndex.ts +0 -663
- package/src/proxy/logSearch.ts +0 -122
- package/src/proxy/logger.ts +0 -537
- package/src/proxy/openaiOrphanToolStrip.ts +0 -142
- package/src/proxy/platformCommands.ts +0 -258
- package/src/proxy/privateDataPath.ts +0 -419
- package/src/proxy/providerImporters.ts +0 -578
- package/src/proxy/providerScanStore.ts +0 -87
- package/src/proxy/providerSecretStore.ts +0 -216
- package/src/proxy/providers.ts +0 -998
- package/src/proxy/rawStreamCapture.ts +0 -342
- package/src/proxy/runFailures.ts +0 -94
- package/src/proxy/runStore.ts +0 -214
- package/src/proxy/runtimeAdmission.ts +0 -55
- package/src/proxy/runtimeHealth.ts +0 -221
- package/src/proxy/runtimeMetrics.ts +0 -149
- package/src/proxy/runtimeShutdown.ts +0 -157
- package/src/proxy/schemas.ts +0 -112
- package/src/proxy/sessionArchive.ts +0 -479
- package/src/proxy/sessionInfo.ts +0 -266
- package/src/proxy/sessionProcess.ts +0 -194
- package/src/proxy/sessionRuntime.ts +0 -121
- package/src/proxy/sessionSupervisor.ts +0 -305
- package/src/proxy/sessionWorkerEntry.ts +0 -26
- package/src/proxy/shutdownCoordinator.ts +0 -90
- package/src/proxy/socketTracker.ts +0 -639
- package/src/proxy/sqliteLogIndex.ts +0 -733
- package/src/proxy/storageLifecycle.ts +0 -432
- package/src/proxy/store.ts +0 -1773
- package/src/proxy/streamTiming.ts +0 -31
- package/src/proxy/toolSchemaWarnings.ts +0 -529
- package/src/proxy/uiAssetServer.ts +0 -106
- package/src/proxy/upstream.ts +0 -127
- package/src/services/alerts.ts +0 -12
- package/src/services/groups.ts +0 -119
- package/src/services/piAgent.ts +0 -421
- package/src/services/piAgentRetrieval.ts +0 -1180
- package/src/services/result.ts +0 -17
- package/src/services/runs.ts +0 -76
- package/src/ui/bootstrap.ts +0 -167
- package/src/ui/index.html +0 -38
- package/src/ui/logsStreamClient.ts +0 -20
- package/src/ui/main.tsx +0 -13
- package/src/ui/public/runtime-config.js +0 -2
- package/src/ui/router.tsx +0 -13
- package/src/ui/routes/__root.tsx +0 -69
- package/src/ui/routes/index.tsx +0 -35
- package/src/ui/routes/session/$sessionId.tsx +0 -50
- package/src/ui/runtimeDiscovery.ts +0 -50
|
@@ -1,1842 +0,0 @@
|
|
|
1
|
-
import http from "node:http";
|
|
2
|
-
import { Buffer } from "node:buffer";
|
|
3
|
-
import { createHash, timingSafeEqual } from "node:crypto";
|
|
4
|
-
import { isIP } from "node:net";
|
|
5
|
-
import {
|
|
6
|
-
BROWSER_RUNTIME_JSON_PLACEHOLDER,
|
|
7
|
-
BROWSER_RUNTIME_SCHEMA_VERSION,
|
|
8
|
-
type BrowserRuntimeDeployment,
|
|
9
|
-
} from "../lib/browserRuntimeContract";
|
|
10
|
-
import {
|
|
11
|
-
AGENT_INSPECTOR_BACKEND_HEADER,
|
|
12
|
-
type BackendImplementation,
|
|
13
|
-
} from "../lib/backendImplementation";
|
|
14
|
-
import {
|
|
15
|
-
AGENT_INSPECTOR_BASE_PATH_META_NAME,
|
|
16
|
-
AGENT_INSPECTOR_PUBLIC_BASE_PATH_HEADER,
|
|
17
|
-
AGENT_INSPECTOR_PUBLIC_ORIGIN_HEADER,
|
|
18
|
-
AGENT_INSPECTOR_PUBLIC_PORT_HEADER,
|
|
19
|
-
getConfiguredBasePath,
|
|
20
|
-
normalizePublicBasePath,
|
|
21
|
-
stripBasePath,
|
|
22
|
-
stripBasePathFromRequestPath,
|
|
23
|
-
withBasePath,
|
|
24
|
-
} from "../lib/basePath";
|
|
25
|
-
import {
|
|
26
|
-
MANAGED_INSTANCE_CONTROL_PATH,
|
|
27
|
-
MANAGED_INSTANCE_SHUTDOWN_PATH,
|
|
28
|
-
MANAGED_INSTANCE_TOKEN_HEADER,
|
|
29
|
-
} from "../lib/managedInstance";
|
|
30
|
-
import { lookupClientByPort } from "./socketTracker";
|
|
31
|
-
import { loadUiAsset } from "./uiAssetServer";
|
|
32
|
-
|
|
33
|
-
const IDENTITY_HEADERS = {
|
|
34
|
-
pid: "x-agent-inspector-client-pid",
|
|
35
|
-
port: "x-agent-inspector-client-port",
|
|
36
|
-
cwd: "x-agent-inspector-client-cwd",
|
|
37
|
-
projectFolder: "x-agent-inspector-client-project-folder",
|
|
38
|
-
} as const;
|
|
39
|
-
|
|
40
|
-
const IDENTITY_HEADER_PREFIX = "x-agent-inspector-";
|
|
41
|
-
const PROXY_TOKEN_HEADER = "x-agent-inspector-proxy-token";
|
|
42
|
-
const CSRF_HEADER = "x-agent-inspector-csrf";
|
|
43
|
-
const FORWARDED_AGENT_HEADER_ALLOWLIST = new Set<string>([CSRF_HEADER]);
|
|
44
|
-
const DEFAULT_MAX_REQUEST_BYTES = 64 * 1024 * 1024;
|
|
45
|
-
const DEFAULT_REQUEST_TIMEOUT_MS = 120_000;
|
|
46
|
-
const ALIAS_CONTROL_MAX_REQUEST_BYTES = 8 * 1024;
|
|
47
|
-
const INSTANCE_API_MAX_REQUEST_BYTES = 64 * 1024;
|
|
48
|
-
const LOCAL_CONTROL_MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
49
|
-
|
|
50
|
-
export const IDENTITY_PROXY_CONTROL_NAMESPACE = "/.agent-inspector";
|
|
51
|
-
export const IDENTITY_PROXY_ALIAS_CONTROL_PATH = `${IDENTITY_PROXY_CONTROL_NAMESPACE}/base-path-aliases`;
|
|
52
|
-
|
|
53
|
-
export type BasePathAliasResolution = {
|
|
54
|
-
effectiveBasePath: string;
|
|
55
|
-
isAlias: boolean;
|
|
56
|
-
upstreamPath: string;
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
export type BasePathAliasMutationResult =
|
|
60
|
-
| { ok: true; basePath: string }
|
|
61
|
-
| {
|
|
62
|
-
ok: false;
|
|
63
|
-
code: "canonical" | "duplicate" | "invalid" | "not-found" | "overlap" | "reserved";
|
|
64
|
-
error: string;
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
export type BasePathAliasRegistry = {
|
|
68
|
-
canonicalBasePath: string;
|
|
69
|
-
add: (basePath: string) => BasePathAliasMutationResult;
|
|
70
|
-
list: () => readonly string[];
|
|
71
|
-
remove: (basePath: string) => BasePathAliasMutationResult;
|
|
72
|
-
resolve: (rawPath: string) => BasePathAliasResolution;
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
function normalizedAliasCandidate(
|
|
76
|
-
value: string,
|
|
77
|
-
): { ok: true; basePath: string } | { ok: false; code: "invalid" | "reserved"; error: string } {
|
|
78
|
-
const normalized = normalizePublicBasePath(value);
|
|
79
|
-
if (normalized === null) {
|
|
80
|
-
return {
|
|
81
|
-
ok: false,
|
|
82
|
-
code: "invalid",
|
|
83
|
-
error: "Base Path aliases may contain only URL-safe path segments.",
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
if (normalized.length === 0) {
|
|
87
|
-
return {
|
|
88
|
-
ok: false,
|
|
89
|
-
code: "invalid",
|
|
90
|
-
error: "Base Path aliases must be non-root paths such as /inspector.",
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
if (
|
|
94
|
-
normalized === IDENTITY_PROXY_CONTROL_NAMESPACE ||
|
|
95
|
-
normalized.startsWith(`${IDENTITY_PROXY_CONTROL_NAMESPACE}/`)
|
|
96
|
-
) {
|
|
97
|
-
return {
|
|
98
|
-
ok: false,
|
|
99
|
-
code: "reserved",
|
|
100
|
-
error: `${normalized} collides with the reserved Agent Inspector control path.`,
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
const publicNamespace = ["/api", "/assets", "/proxy", "/session", "/livez", "/readyz"].find(
|
|
104
|
-
(namespace) => normalized === namespace || normalized.startsWith(`${namespace}/`),
|
|
105
|
-
);
|
|
106
|
-
if (publicNamespace !== undefined) {
|
|
107
|
-
return {
|
|
108
|
-
ok: false,
|
|
109
|
-
code: "reserved",
|
|
110
|
-
error: `${normalized} collides with the reserved ${publicNamespace} public namespace.`,
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
return { ok: true, basePath: normalized };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function pathMatchesBasePath(pathname: string, basePath: string): boolean {
|
|
117
|
-
return pathname === basePath || pathname.startsWith(`${basePath}/`);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function basePathsOverlap(left: string, right: string): boolean {
|
|
121
|
-
return pathMatchesBasePath(left, right) || pathMatchesBasePath(right, left);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Create an in-memory registry owned by one identity ingress. Runtime aliases
|
|
126
|
-
* intentionally disappear when that ingress exits.
|
|
127
|
-
*/
|
|
128
|
-
export function createBasePathAliasRegistry(
|
|
129
|
-
canonicalBasePath: string,
|
|
130
|
-
initialAliases: readonly string[] = [],
|
|
131
|
-
): BasePathAliasRegistry {
|
|
132
|
-
const canonical = normalizePublicBasePath(canonicalBasePath) ?? "";
|
|
133
|
-
const aliases: string[] = [];
|
|
134
|
-
|
|
135
|
-
const add = (value: string): BasePathAliasMutationResult => {
|
|
136
|
-
const candidate = normalizedAliasCandidate(value);
|
|
137
|
-
if (!candidate.ok) return candidate;
|
|
138
|
-
if (candidate.basePath === canonical) {
|
|
139
|
-
return {
|
|
140
|
-
ok: false,
|
|
141
|
-
code: "canonical",
|
|
142
|
-
error: `${candidate.basePath} is already the canonical Base Path.`,
|
|
143
|
-
};
|
|
144
|
-
}
|
|
145
|
-
if (canonical.length > 0 && basePathsOverlap(candidate.basePath, canonical)) {
|
|
146
|
-
return {
|
|
147
|
-
ok: false,
|
|
148
|
-
code: "overlap",
|
|
149
|
-
error: `${candidate.basePath} overlaps the canonical Base Path ${canonical}.`,
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
if (aliases.includes(candidate.basePath)) {
|
|
153
|
-
return {
|
|
154
|
-
ok: false,
|
|
155
|
-
code: "duplicate",
|
|
156
|
-
error: `${candidate.basePath} is already an active runtime alias.`,
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
const overlappingAlias = aliases.find((alias) => basePathsOverlap(candidate.basePath, alias));
|
|
160
|
-
if (overlappingAlias !== undefined) {
|
|
161
|
-
return {
|
|
162
|
-
ok: false,
|
|
163
|
-
code: "overlap",
|
|
164
|
-
error: `${candidate.basePath} overlaps the active runtime alias ${overlappingAlias}.`,
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
aliases.push(candidate.basePath);
|
|
168
|
-
aliases.sort((left, right) => right.length - left.length || left.localeCompare(right));
|
|
169
|
-
return { ok: true, basePath: candidate.basePath };
|
|
170
|
-
};
|
|
171
|
-
|
|
172
|
-
const remove = (value: string): BasePathAliasMutationResult => {
|
|
173
|
-
const candidate = normalizedAliasCandidate(value);
|
|
174
|
-
if (!candidate.ok) return candidate;
|
|
175
|
-
if (candidate.basePath === canonical) {
|
|
176
|
-
return {
|
|
177
|
-
ok: false,
|
|
178
|
-
code: "canonical",
|
|
179
|
-
error: `${candidate.basePath} is the canonical Base Path and cannot be removed.`,
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
const index = aliases.indexOf(candidate.basePath);
|
|
183
|
-
if (index === -1) {
|
|
184
|
-
return {
|
|
185
|
-
ok: false,
|
|
186
|
-
code: "not-found",
|
|
187
|
-
error: `${candidate.basePath} is not an active runtime alias.`,
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
aliases.splice(index, 1);
|
|
191
|
-
return { ok: true, basePath: candidate.basePath };
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
const resolve = (rawPath: string): BasePathAliasResolution => {
|
|
195
|
-
const requestUrl = new URL(rawPath, "http://localhost");
|
|
196
|
-
const alias = aliases.find((candidate) => pathMatchesBasePath(requestUrl.pathname, candidate));
|
|
197
|
-
const effectiveBasePath = alias ?? canonical;
|
|
198
|
-
return {
|
|
199
|
-
effectiveBasePath,
|
|
200
|
-
isAlias: alias !== undefined,
|
|
201
|
-
upstreamPath: stripBasePathFromRequestPath(rawPath, effectiveBasePath),
|
|
202
|
-
};
|
|
203
|
-
};
|
|
204
|
-
|
|
205
|
-
const registry: BasePathAliasRegistry = {
|
|
206
|
-
canonicalBasePath: canonical,
|
|
207
|
-
add,
|
|
208
|
-
list: () => [...aliases],
|
|
209
|
-
remove,
|
|
210
|
-
resolve,
|
|
211
|
-
};
|
|
212
|
-
for (const alias of initialAliases) add(alias);
|
|
213
|
-
return registry;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
export function resolveBasePathAliasRequest(
|
|
217
|
-
registry: BasePathAliasRegistry,
|
|
218
|
-
rawPath: string,
|
|
219
|
-
): BasePathAliasResolution {
|
|
220
|
-
return registry.resolve(rawPath);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
type IdentityProxyRuntimeState = {
|
|
224
|
-
acceptingRequests: boolean;
|
|
225
|
-
activeRequests: number;
|
|
226
|
-
drainWaiters: Set<() => void>;
|
|
227
|
-
};
|
|
228
|
-
|
|
229
|
-
const identityProxyRuntimeStates = new WeakMap<http.Server, IdentityProxyRuntimeState>();
|
|
230
|
-
|
|
231
|
-
const REQUEST_HOP_BY_HOP = new Set([
|
|
232
|
-
"connection",
|
|
233
|
-
"keep-alive",
|
|
234
|
-
"proxy-authenticate",
|
|
235
|
-
"proxy-authorization",
|
|
236
|
-
"te",
|
|
237
|
-
"trailers",
|
|
238
|
-
"transfer-encoding",
|
|
239
|
-
"upgrade",
|
|
240
|
-
"content-length",
|
|
241
|
-
]);
|
|
242
|
-
|
|
243
|
-
const RESPONSE_HOP_BY_HOP = new Set([
|
|
244
|
-
"connection",
|
|
245
|
-
"keep-alive",
|
|
246
|
-
"proxy-authenticate",
|
|
247
|
-
"proxy-authorization",
|
|
248
|
-
"te",
|
|
249
|
-
"trailers",
|
|
250
|
-
"transfer-encoding",
|
|
251
|
-
"upgrade",
|
|
252
|
-
]);
|
|
253
|
-
|
|
254
|
-
const BASE_SECURITY_HEADERS = {
|
|
255
|
-
"permissions-policy": "camera=(), microphone=(), geolocation=()",
|
|
256
|
-
"referrer-policy": "no-referrer",
|
|
257
|
-
"x-content-type-options": "nosniff",
|
|
258
|
-
"x-frame-options": "DENY",
|
|
259
|
-
} as const;
|
|
260
|
-
|
|
261
|
-
const DOCUMENT_CONTENT_SECURITY_POLICY = [
|
|
262
|
-
"default-src 'self'",
|
|
263
|
-
"base-uri 'self'",
|
|
264
|
-
"connect-src 'self'",
|
|
265
|
-
"font-src 'self' data:",
|
|
266
|
-
"frame-ancestors 'none'",
|
|
267
|
-
"img-src 'self' data: blob:",
|
|
268
|
-
"object-src 'none'",
|
|
269
|
-
"script-src 'self' 'unsafe-inline'",
|
|
270
|
-
"style-src 'self' 'unsafe-inline'",
|
|
271
|
-
"worker-src 'self' blob:",
|
|
272
|
-
].join("; ");
|
|
273
|
-
|
|
274
|
-
function htmlAttributeEscape(value: string): string {
|
|
275
|
-
return value
|
|
276
|
-
.replace(/&/gu, "&")
|
|
277
|
-
.replace(/"/gu, """)
|
|
278
|
-
.replace(/</gu, "<")
|
|
279
|
-
.replace(/>/gu, ">");
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
function rewriteRootRelativePublicPath(
|
|
283
|
-
value: string,
|
|
284
|
-
effectiveBasePath: string,
|
|
285
|
-
sourceBasePath: string,
|
|
286
|
-
): string {
|
|
287
|
-
if (!value.startsWith("/") || value.startsWith("//")) return value;
|
|
288
|
-
const normalizedEffective = normalizePublicBasePath(effectiveBasePath);
|
|
289
|
-
const normalizedSource = normalizePublicBasePath(sourceBasePath);
|
|
290
|
-
if (normalizedEffective === null || normalizedSource === null) return value;
|
|
291
|
-
const suffixIndex = value.search(/[?#]/u);
|
|
292
|
-
const pathname = suffixIndex === -1 ? value : value.slice(0, suffixIndex);
|
|
293
|
-
const suffix = suffixIndex === -1 ? "" : value.slice(suffixIndex);
|
|
294
|
-
if (normalizedEffective.length > 0 && pathMatchesBasePath(pathname, normalizedEffective)) {
|
|
295
|
-
return value;
|
|
296
|
-
}
|
|
297
|
-
const rootRelativePath =
|
|
298
|
-
normalizedSource.length > 0 && pathMatchesBasePath(pathname, normalizedSource)
|
|
299
|
-
? pathname.slice(normalizedSource.length) || "/"
|
|
300
|
-
: pathname;
|
|
301
|
-
const rewritten = withBasePath(rootRelativePath, normalizedEffective);
|
|
302
|
-
const trailingSlash = pathname.endsWith("/") && !rewritten.endsWith("/") ? "/" : "";
|
|
303
|
-
return `${rewritten}${trailingSlash}${suffix}`;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
function rewriteQuotedAssetPaths(
|
|
307
|
-
source: string,
|
|
308
|
-
effectiveBasePath: string,
|
|
309
|
-
sourceBasePath: string,
|
|
310
|
-
escape: (value: string, quote: string) => string,
|
|
311
|
-
): string {
|
|
312
|
-
return source.replace(
|
|
313
|
-
/(["'])(\/(?:[^"'/]+\/)*assets\/)/gu,
|
|
314
|
-
(_match: string, quote: string, assetPrefix: string) =>
|
|
315
|
-
`${quote}${escape(
|
|
316
|
-
rewriteRootRelativePublicPath(assetPrefix, effectiveBasePath, sourceBasePath),
|
|
317
|
-
quote,
|
|
318
|
-
)}`,
|
|
319
|
-
);
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
export function rewriteHtmlForBasePath(
|
|
323
|
-
html: string,
|
|
324
|
-
basePath: string,
|
|
325
|
-
sourceBasePath = "",
|
|
326
|
-
): string {
|
|
327
|
-
const normalized = normalizePublicBasePath(basePath);
|
|
328
|
-
const normalizedSource = normalizePublicBasePath(sourceBasePath);
|
|
329
|
-
if (normalized === null || normalizedSource === null) return html;
|
|
330
|
-
const escaped = htmlAttributeEscape(normalized);
|
|
331
|
-
const meta = `<meta name="${AGENT_INSPECTOR_BASE_PATH_META_NAME}" content="${escaped}">`;
|
|
332
|
-
const metaPattern = new RegExp(
|
|
333
|
-
`<meta\\b[^>]*\\bname\\s*=\\s*("|')${AGENT_INSPECTOR_BASE_PATH_META_NAME}\\1[^>]*>`,
|
|
334
|
-
"giu",
|
|
335
|
-
);
|
|
336
|
-
let replacedMeta = false;
|
|
337
|
-
const withReplacedMeta = html.replace(metaPattern, () => {
|
|
338
|
-
if (replacedMeta) return "";
|
|
339
|
-
replacedMeta = true;
|
|
340
|
-
return meta;
|
|
341
|
-
});
|
|
342
|
-
const withMeta = replacedMeta
|
|
343
|
-
? withReplacedMeta
|
|
344
|
-
: withReplacedMeta.replace(/<head(\s[^>]*)?>/iu, (match) => `${match}${meta}`);
|
|
345
|
-
const withRewrittenAttributes = withMeta.replace(
|
|
346
|
-
/\b(href|src|action)=(["'])(\/(?!\/)[^"']*)\2/giu,
|
|
347
|
-
(_match: string, attribute: string, quote: string, path: string) =>
|
|
348
|
-
`${attribute}=${quote}${htmlAttributeEscape(
|
|
349
|
-
rewriteRootRelativePublicPath(path, normalized, normalizedSource),
|
|
350
|
-
)}${quote}`,
|
|
351
|
-
);
|
|
352
|
-
return rewriteQuotedAssetPaths(withRewrittenAttributes, normalized, normalizedSource, (value) =>
|
|
353
|
-
htmlAttributeEscape(value),
|
|
354
|
-
);
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
function javaScriptStringEscape(value: string, quote: string): string {
|
|
358
|
-
const escaped = value
|
|
359
|
-
.replace(/\\/gu, "\\\\")
|
|
360
|
-
.replace(/\r/gu, "\\r")
|
|
361
|
-
.replace(/\n/gu, "\\n")
|
|
362
|
-
.replace(/\u2028/gu, "\\u2028")
|
|
363
|
-
.replace(/\u2029/gu, "\\u2029")
|
|
364
|
-
.replace(/&/gu, "\\u0026")
|
|
365
|
-
.replace(/</gu, "\\u003c")
|
|
366
|
-
.replace(/>/gu, "\\u003e");
|
|
367
|
-
return quote === "'" ? escaped.replace(/'/gu, "\\'") : escaped.replace(/"/gu, '\\"');
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
export function rewriteJavaScriptForBasePath(
|
|
371
|
-
source: string,
|
|
372
|
-
basePath: string,
|
|
373
|
-
sourceBasePath = "",
|
|
374
|
-
): string {
|
|
375
|
-
const normalized = normalizePublicBasePath(basePath);
|
|
376
|
-
const normalizedSource = normalizePublicBasePath(sourceBasePath);
|
|
377
|
-
if (normalized === null || normalizedSource === null) return source;
|
|
378
|
-
const escaped = javaScriptStringEscape(normalized, '"');
|
|
379
|
-
const withRouterBasePath = source.replace(
|
|
380
|
-
/\bbasepath:\s*(["'])[^"']*\1/gu,
|
|
381
|
-
`basepath:"${escaped}"`,
|
|
382
|
-
);
|
|
383
|
-
const withDynamicPaths = withRouterBasePath.replace(
|
|
384
|
-
/return(["'])(\/(?!\/)[^"']*)\1\+([A-Za-z_$][\w$]*)/gu,
|
|
385
|
-
(_match: string, quote: string, path: string, variable: string) => {
|
|
386
|
-
const rewritten = rewriteRootRelativePublicPath(path, normalized, normalizedSource);
|
|
387
|
-
return `return${quote}${javaScriptStringEscape(rewritten, quote)}${quote}+${variable}`;
|
|
388
|
-
},
|
|
389
|
-
);
|
|
390
|
-
return rewriteQuotedAssetPaths(
|
|
391
|
-
withDynamicPaths,
|
|
392
|
-
normalized,
|
|
393
|
-
normalizedSource,
|
|
394
|
-
javaScriptStringEscape,
|
|
395
|
-
);
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
function publicOriginForRequest(req: http.IncomingMessage, options: IdentityProxyOptions): string {
|
|
399
|
-
if (options.publicOrigin !== undefined) {
|
|
400
|
-
try {
|
|
401
|
-
return new URL(options.publicOrigin).origin;
|
|
402
|
-
} catch {
|
|
403
|
-
// Invalid explicit values are rejected by the CLI; retain a safe local fallback for embedders.
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
return `http://${req.headers.host ?? "localhost"}`;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
function browserRuntimeForRequest(
|
|
410
|
-
req: http.IncomingMessage,
|
|
411
|
-
options: IdentityProxyOptions,
|
|
412
|
-
basePath: string,
|
|
413
|
-
): BrowserRuntimeDeployment {
|
|
414
|
-
const origin = publicOriginForRequest(req, options);
|
|
415
|
-
const normalized = normalizePublicBasePath(basePath) ?? "";
|
|
416
|
-
const baseUrl = normalized.length === 0 ? origin : `${origin}${normalized}`;
|
|
417
|
-
return {
|
|
418
|
-
schemaVersion: BROWSER_RUNTIME_SCHEMA_VERSION,
|
|
419
|
-
deploymentMode: "composed",
|
|
420
|
-
ui: { basePath: normalized.length === 0 ? "/" : normalized },
|
|
421
|
-
control: { baseUrl },
|
|
422
|
-
agent: { baseUrl },
|
|
423
|
-
capabilities: {
|
|
424
|
-
rest: true,
|
|
425
|
-
sse: true,
|
|
426
|
-
proxy: true,
|
|
427
|
-
mcp: true,
|
|
428
|
-
},
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
function safeInlineJson(value: unknown): string {
|
|
433
|
-
return JSON.stringify(value)
|
|
434
|
-
.replace(/&/gu, "\\u0026")
|
|
435
|
-
.replace(/</gu, "\\u003c")
|
|
436
|
-
.replace(/>/gu, "\\u003e")
|
|
437
|
-
.replace(/\u2028/gu, "\\u2028")
|
|
438
|
-
.replace(/\u2029/gu, "\\u2029");
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
function injectBrowserRuntime(html: string, runtime: BrowserRuntimeDeployment): string {
|
|
442
|
-
const runtimeJson = safeInlineJson(runtime);
|
|
443
|
-
if (html.includes(BROWSER_RUNTIME_JSON_PLACEHOLDER)) {
|
|
444
|
-
return html.replaceAll(BROWSER_RUNTIME_JSON_PLACEHOLDER, runtimeJson);
|
|
445
|
-
}
|
|
446
|
-
const bootstrap = `<script>window.__AGENT_INSPECTOR_RUNTIME__=${runtimeJson};</script>`;
|
|
447
|
-
return html.replace(/<head(\s[^>]*)?>/iu, (head) => `${head}${bootstrap}`);
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
async function tryServeUiAsset(
|
|
451
|
-
req: http.IncomingMessage,
|
|
452
|
-
res: http.ServerResponse,
|
|
453
|
-
options: IdentityProxyOptions,
|
|
454
|
-
pathname: string,
|
|
455
|
-
basePath: string,
|
|
456
|
-
sourceBasePath: string,
|
|
457
|
-
): Promise<boolean> {
|
|
458
|
-
const method = (req.method ?? "GET").toUpperCase();
|
|
459
|
-
if ((method !== "GET" && method !== "HEAD") || options.uiDirectory === undefined) return false;
|
|
460
|
-
const asset = await loadUiAsset(options.uiDirectory, pathname);
|
|
461
|
-
if (asset === null) return false;
|
|
462
|
-
let body = asset.body;
|
|
463
|
-
if (asset.document) {
|
|
464
|
-
const rewritten = rewriteHtmlForBasePath(body.toString("utf8"), basePath, sourceBasePath);
|
|
465
|
-
body = Buffer.from(
|
|
466
|
-
injectBrowserRuntime(rewritten, browserRuntimeForRequest(req, options, basePath)),
|
|
467
|
-
"utf8",
|
|
468
|
-
);
|
|
469
|
-
} else if (basePath.length > 0 && asset.contentType.includes("javascript")) {
|
|
470
|
-
body = Buffer.from(
|
|
471
|
-
rewriteJavaScriptForBasePath(body.toString("utf8"), basePath, sourceBasePath),
|
|
472
|
-
"utf8",
|
|
473
|
-
);
|
|
474
|
-
}
|
|
475
|
-
const headers: Record<string, string | number> = {
|
|
476
|
-
...BASE_SECURITY_HEADERS,
|
|
477
|
-
"cache-control": asset.cacheControl,
|
|
478
|
-
"content-length": body.byteLength,
|
|
479
|
-
"content-type": asset.contentType,
|
|
480
|
-
};
|
|
481
|
-
if (asset.document) headers["content-security-policy"] = DOCUMENT_CONTENT_SECURITY_POLICY;
|
|
482
|
-
res.writeHead(200, headers);
|
|
483
|
-
if (method === "HEAD") res.end();
|
|
484
|
-
else res.end(body);
|
|
485
|
-
req.resume();
|
|
486
|
-
return true;
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
export type IdentityProxyOptions = {
|
|
490
|
-
/** Backend child implementation supervised behind this protected ingress. */
|
|
491
|
-
backendImplementation?: BackendImplementation;
|
|
492
|
-
/** Public port to listen on. Clients point at this. */
|
|
493
|
-
listenPort: number;
|
|
494
|
-
/** Interface exposed to clients. Defaults are chosen by the CLI. */
|
|
495
|
-
listenHost: string;
|
|
496
|
-
/** Host the upstream TanStack Start server listens on. */
|
|
497
|
-
upstreamHost: string;
|
|
498
|
-
/** Port the upstream TanStack Start server listens on. */
|
|
499
|
-
upstreamPort: number;
|
|
500
|
-
/** Restrict non-proxy routes for clients outside the local machine. */
|
|
501
|
-
restrictRemoteControl?: boolean;
|
|
502
|
-
/** Explicitly expose UI, REST, and MCP to remote peers. */
|
|
503
|
-
allowRemoteControl?: boolean;
|
|
504
|
-
/** Optional Bearer token for remote control-plane API clients. */
|
|
505
|
-
controlToken?: string;
|
|
506
|
-
/** Dedicated credential for non-loopback model-proxy clients. */
|
|
507
|
-
proxyToken?: string;
|
|
508
|
-
/** Temporary compatibility escape hatch for legacy unauthenticated remote proxy clients. */
|
|
509
|
-
allowUnauthenticatedRemoteProxy?: boolean;
|
|
510
|
-
/** Additional public hostnames accepted by the ingress Host boundary. */
|
|
511
|
-
trustedHosts?: readonly string[];
|
|
512
|
-
/** Exact browser UI origins allowed to call control REST/SSE across origins. */
|
|
513
|
-
allowedUiOrigins?: readonly string[];
|
|
514
|
-
/** Independent static UI artifact directory served only by the protected ingress. */
|
|
515
|
-
uiDirectory?: string;
|
|
516
|
-
/** Explicit public origin for reverse-proxy deployments; never inferred from forwarded headers. */
|
|
517
|
-
publicOrigin?: string;
|
|
518
|
-
/** Maximum declared or streamed request body size. */
|
|
519
|
-
maxRequestBytes?: number;
|
|
520
|
-
/** Deadline for receiving and forwarding one request body. */
|
|
521
|
-
requestTimeoutMs?: number;
|
|
522
|
-
/** Runtime-scoped additional public Base Path mounts. */
|
|
523
|
-
aliasRegistry?: BasePathAliasRegistry;
|
|
524
|
-
/** Private lifecycle identity exposed only to the owning local instance manager. */
|
|
525
|
-
managedInstance?: ManagedInstanceControlOptions;
|
|
526
|
-
/** Optional Node-supervisor instance API retained when the selected backend is Rust. */
|
|
527
|
-
instanceApiHandler?: (request: Request) => Promise<Response>;
|
|
528
|
-
};
|
|
529
|
-
|
|
530
|
-
export type ManagedInstanceControlOptions = {
|
|
531
|
-
backend?: BackendImplementation;
|
|
532
|
-
name: string;
|
|
533
|
-
instanceId: string;
|
|
534
|
-
launchId: string;
|
|
535
|
-
controlToken: string;
|
|
536
|
-
supervisorPid: number;
|
|
537
|
-
startedAt: string;
|
|
538
|
-
publicPort: number;
|
|
539
|
-
upstreamPort: number;
|
|
540
|
-
requestShutdown: () => void;
|
|
541
|
-
};
|
|
542
|
-
|
|
543
|
-
function isLoopbackPeer(address: string | undefined): boolean {
|
|
544
|
-
if (address === undefined) return false;
|
|
545
|
-
const normalized = address.toLowerCase();
|
|
546
|
-
return (
|
|
547
|
-
normalized === "::1" || normalized.startsWith("127.") || normalized.startsWith("::ffff:127.")
|
|
548
|
-
);
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
function bearerToken(authorization: string | undefined): string | null {
|
|
552
|
-
if (authorization === undefined) return null;
|
|
553
|
-
const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
|
|
554
|
-
return match?.[1] ?? null;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
function tokensMatch(received: string | null, expected: string | undefined): boolean {
|
|
558
|
-
if (received === null || expected === undefined || expected === "") return false;
|
|
559
|
-
const receivedBuffer = Buffer.from(received);
|
|
560
|
-
const expectedBuffer = Buffer.from(expected);
|
|
561
|
-
return (
|
|
562
|
-
receivedBuffer.byteLength === expectedBuffer.byteLength &&
|
|
563
|
-
timingSafeEqual(receivedBuffer, expectedBuffer)
|
|
564
|
-
);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
function managedInstanceTokensMatch(received: string | undefined, expected: string): boolean {
|
|
568
|
-
if (received === undefined || received.length === 0 || expected.length === 0) return false;
|
|
569
|
-
const receivedDigest = createHash("sha256").update(received).digest();
|
|
570
|
-
const expectedDigest = createHash("sha256").update(expected).digest();
|
|
571
|
-
return timingSafeEqual(receivedDigest, expectedDigest);
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
function firstHeader(value: string | readonly string[] | undefined): string | undefined {
|
|
575
|
-
return typeof value === "string" ? value : value?.[0];
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
function normalizedHostname(value: string): string | null {
|
|
579
|
-
const candidate = value.trim();
|
|
580
|
-
if (candidate.length === 0) return null;
|
|
581
|
-
try {
|
|
582
|
-
return new URL(`http://${candidate}`).hostname.toLowerCase().replace(/^\[|]$/g, "");
|
|
583
|
-
} catch {
|
|
584
|
-
return null;
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
function isLoopbackHostname(hostname: string): boolean {
|
|
589
|
-
const normalized = hostname.toLowerCase().replace(/^\[|]$/g, "");
|
|
590
|
-
if (normalized === "localhost" || normalized === "::1") return true;
|
|
591
|
-
if (isIP(normalized) !== 4) return false;
|
|
592
|
-
return normalized.split(".", 1)[0] === "127";
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
export type UiOriginAllowlist = {
|
|
596
|
-
origins: readonly string[];
|
|
597
|
-
rejected: readonly string[];
|
|
598
|
-
};
|
|
599
|
-
|
|
600
|
-
function parseUrl(value: string): URL | null {
|
|
601
|
-
try {
|
|
602
|
-
return new URL(value);
|
|
603
|
-
} catch {
|
|
604
|
-
return null;
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
export function parseUiOriginAllowlist(value: string | undefined): UiOriginAllowlist {
|
|
609
|
-
const origins: string[] = [];
|
|
610
|
-
const rejected: string[] = [];
|
|
611
|
-
for (const entry of (value ?? "").split(",")) {
|
|
612
|
-
const candidate = entry.trim();
|
|
613
|
-
if (candidate.length === 0) continue;
|
|
614
|
-
const parsed = parseUrl(candidate);
|
|
615
|
-
const valid =
|
|
616
|
-
parsed !== null &&
|
|
617
|
-
(parsed.protocol === "http:" || parsed.protocol === "https:") &&
|
|
618
|
-
parsed.username.length === 0 &&
|
|
619
|
-
parsed.password.length === 0 &&
|
|
620
|
-
parsed.pathname === "/" &&
|
|
621
|
-
parsed.search.length === 0 &&
|
|
622
|
-
parsed.hash.length === 0 &&
|
|
623
|
-
isLoopbackHostname(parsed.hostname.toLowerCase().replace(/^\[|\]$/gu, ""));
|
|
624
|
-
if (!valid || parsed === null) {
|
|
625
|
-
rejected.push(candidate);
|
|
626
|
-
continue;
|
|
627
|
-
}
|
|
628
|
-
if (!origins.includes(parsed.origin)) origins.push(parsed.origin);
|
|
629
|
-
}
|
|
630
|
-
return { origins, rejected };
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
function normalizeTrustedPublicOrigin(value: string | undefined): string | null | undefined {
|
|
634
|
-
if (value === undefined) return undefined;
|
|
635
|
-
return normalizedRequestOrigin(value.trim());
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
export function isTrustedIdentityProxyHost(
|
|
639
|
-
host: string | undefined,
|
|
640
|
-
options: Pick<IdentityProxyOptions, "listenHost" | "trustedHosts">,
|
|
641
|
-
): boolean {
|
|
642
|
-
if (host === undefined) return false;
|
|
643
|
-
const hostname = normalizedHostname(host);
|
|
644
|
-
if (hostname === null) return false;
|
|
645
|
-
if (isLoopbackHostname(hostname) || isIP(hostname) !== 0) return true;
|
|
646
|
-
|
|
647
|
-
const listenHostname = normalizedHostname(options.listenHost);
|
|
648
|
-
if (listenHostname !== null && hostname === listenHostname) return true;
|
|
649
|
-
return (options.trustedHosts ?? []).some(
|
|
650
|
-
(trustedHost) => normalizedHostname(trustedHost) === hostname,
|
|
651
|
-
);
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
function isSafeMethod(method: string | undefined): boolean {
|
|
655
|
-
const normalized = (method ?? "GET").toUpperCase();
|
|
656
|
-
return normalized === "GET" || normalized === "HEAD" || normalized === "OPTIONS";
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
const UI_CORS_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] as const;
|
|
660
|
-
const UI_CORS_HEADERS = ["authorization", "content-type", "last-event-id", CSRF_HEADER] as const;
|
|
661
|
-
|
|
662
|
-
function normalizedRequestOrigin(origin: string): string | null {
|
|
663
|
-
try {
|
|
664
|
-
const parsed = new URL(origin);
|
|
665
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
|
666
|
-
if (parsed.username.length > 0 || parsed.password.length > 0) return null;
|
|
667
|
-
if (parsed.pathname !== "/" || parsed.search.length > 0 || parsed.hash.length > 0) return null;
|
|
668
|
-
return parsed.origin;
|
|
669
|
-
} catch {
|
|
670
|
-
return null;
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
function parsedRequestOrigin(origin: string): URL | null {
|
|
675
|
-
const normalized = normalizedRequestOrigin(origin);
|
|
676
|
-
if (normalized === null) return null;
|
|
677
|
-
return new URL(normalized);
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
function isSameOrLoopbackAliasOrigin(left: URL, right: URL): boolean {
|
|
681
|
-
if (left.origin === right.origin) return true;
|
|
682
|
-
return (
|
|
683
|
-
left.protocol === right.protocol &&
|
|
684
|
-
left.port === right.port &&
|
|
685
|
-
isLoopbackHostname(left.hostname) &&
|
|
686
|
-
isLoopbackHostname(right.hostname)
|
|
687
|
-
);
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
function isSameRequestOrigin(
|
|
691
|
-
origin: string,
|
|
692
|
-
host: string | undefined,
|
|
693
|
-
publicOrigin?: string,
|
|
694
|
-
): boolean {
|
|
695
|
-
const parsedOrigin = parsedRequestOrigin(origin);
|
|
696
|
-
if (parsedOrigin === null) return false;
|
|
697
|
-
const expected = parsedRequestOrigin(publicOrigin ?? `http://${host ?? "localhost"}`);
|
|
698
|
-
return expected !== null && isSameOrLoopbackAliasOrigin(parsedOrigin, expected);
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
function matchedUiOrigin(
|
|
702
|
-
origin: string | undefined,
|
|
703
|
-
allowedUiOrigins: readonly string[] | undefined,
|
|
704
|
-
): string | null {
|
|
705
|
-
if (origin === undefined) return null;
|
|
706
|
-
return (allowedUiOrigins ?? []).find((candidate) => candidate === origin) ?? null;
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
function isUiControlPath(pathname: string): boolean {
|
|
710
|
-
if (pathname === "/livez" || pathname === "/readyz") return true;
|
|
711
|
-
if (pathname === "/api/mcp") return false;
|
|
712
|
-
return pathname === "/api" || pathname.startsWith("/api/");
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
function isModelProxyPath(pathname: string): boolean {
|
|
716
|
-
return pathname === "/proxy" || pathname.startsWith("/proxy/");
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
function uiCorsHeaders(origin: string | null): Record<string, string> {
|
|
720
|
-
if (origin === null) return {};
|
|
721
|
-
return {
|
|
722
|
-
"access-control-allow-origin": origin,
|
|
723
|
-
"access-control-expose-headers": "Content-Disposition",
|
|
724
|
-
vary: "Origin",
|
|
725
|
-
};
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
function appendVaryHeader(existing: string | string[] | undefined, name: string): string {
|
|
729
|
-
const values = (Array.isArray(existing) ? existing.join(",") : (existing ?? ""))
|
|
730
|
-
.split(",")
|
|
731
|
-
.map((value) => value.trim())
|
|
732
|
-
.filter((value) => value.length > 0);
|
|
733
|
-
if (!values.some((value) => value.toLowerCase() === name.toLowerCase())) values.push(name);
|
|
734
|
-
return values.join(", ");
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
function requestedCorsHeaders(value: string | undefined): readonly string[] {
|
|
738
|
-
return (value ?? "")
|
|
739
|
-
.split(",")
|
|
740
|
-
.map((header) => header.trim().toLowerCase())
|
|
741
|
-
.filter((header) => header.length > 0);
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
function handleUiCorsPreflight(
|
|
745
|
-
req: http.IncomingMessage,
|
|
746
|
-
res: http.ServerResponse,
|
|
747
|
-
origin: string,
|
|
748
|
-
): void {
|
|
749
|
-
const requestedMethod = firstHeader(req.headers["access-control-request-method"])?.toUpperCase();
|
|
750
|
-
const requestedHeaders = requestedCorsHeaders(
|
|
751
|
-
firstHeader(req.headers["access-control-request-headers"]),
|
|
752
|
-
);
|
|
753
|
-
const methodAllowed =
|
|
754
|
-
requestedMethod !== undefined && UI_CORS_METHODS.some((method) => method === requestedMethod);
|
|
755
|
-
const headersAllowed = requestedHeaders.every((header) =>
|
|
756
|
-
UI_CORS_HEADERS.some((allowedHeader) => allowedHeader === header),
|
|
757
|
-
);
|
|
758
|
-
if (!methodAllowed || !headersAllowed) {
|
|
759
|
-
res.writeHead(403, {
|
|
760
|
-
"content-type": "application/json; charset=utf-8",
|
|
761
|
-
"cache-control": "no-store",
|
|
762
|
-
...uiCorsHeaders(origin),
|
|
763
|
-
});
|
|
764
|
-
res.end(JSON.stringify({ error: "CORS preflight is not allowed for this request." }));
|
|
765
|
-
req.resume();
|
|
766
|
-
return;
|
|
767
|
-
}
|
|
768
|
-
res.writeHead(204, {
|
|
769
|
-
"cache-control": "no-store",
|
|
770
|
-
"access-control-allow-origin": origin,
|
|
771
|
-
"access-control-allow-methods": UI_CORS_METHODS.join(", "),
|
|
772
|
-
"access-control-allow-headers": UI_CORS_HEADERS.join(", "),
|
|
773
|
-
"access-control-max-age": "600",
|
|
774
|
-
vary: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
|
775
|
-
});
|
|
776
|
-
res.end();
|
|
777
|
-
req.resume();
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
function isPublicHealthPath(pathname: string): boolean {
|
|
781
|
-
return pathname === "/livez" || pathname === "/readyz" || pathname === "/api/health";
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
function isInstanceManagementPath(pathname: string): boolean {
|
|
785
|
-
return pathname === "/api/instances" || pathname.startsWith("/api/instances/");
|
|
786
|
-
}
|
|
787
|
-
|
|
788
|
-
function configuredPositiveInteger(value: number | undefined, fallback: number): number {
|
|
789
|
-
return value !== undefined && Number.isSafeInteger(value) && value > 0 ? value : fallback;
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
function declaredContentLength(value: string | undefined): number | null {
|
|
793
|
-
if (value === undefined) return null;
|
|
794
|
-
if (!/^\d+$/.test(value)) return Number.NaN;
|
|
795
|
-
const parsed = Number(value);
|
|
796
|
-
return Number.isSafeInteger(parsed) ? parsed : Number.NaN;
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
export function isBrowserMutationAllowed(input: {
|
|
800
|
-
path: string;
|
|
801
|
-
basePath?: string;
|
|
802
|
-
method?: string;
|
|
803
|
-
host?: string;
|
|
804
|
-
origin?: string;
|
|
805
|
-
secFetchSite?: string;
|
|
806
|
-
csrfToken?: string;
|
|
807
|
-
allowedUiOrigins?: readonly string[];
|
|
808
|
-
publicOrigin?: string;
|
|
809
|
-
}): boolean {
|
|
810
|
-
if (isSafeMethod(input.method)) return true;
|
|
811
|
-
const pathname = stripBasePath(
|
|
812
|
-
new URL(input.path, "http://localhost").pathname,
|
|
813
|
-
input.basePath ?? getConfiguredBasePath(process.env),
|
|
814
|
-
);
|
|
815
|
-
const fetchSite = input.secFetchSite?.toLowerCase();
|
|
816
|
-
const browserRequest = input.origin !== undefined || fetchSite !== undefined;
|
|
817
|
-
if (!browserRequest) return true;
|
|
818
|
-
const sameOrigin =
|
|
819
|
-
input.origin !== undefined
|
|
820
|
-
? isSameRequestOrigin(input.origin, input.host, input.publicOrigin)
|
|
821
|
-
: false;
|
|
822
|
-
if (isModelProxyPath(pathname)) {
|
|
823
|
-
if (fetchSite !== undefined && fetchSite !== "same-origin" && !sameOrigin) return false;
|
|
824
|
-
if (input.origin !== undefined && !sameOrigin) {
|
|
825
|
-
return false;
|
|
826
|
-
}
|
|
827
|
-
return input.csrfToken === "1";
|
|
828
|
-
}
|
|
829
|
-
const allowedOrigin = matchedUiOrigin(input.origin, input.allowedUiOrigins);
|
|
830
|
-
if (
|
|
831
|
-
fetchSite !== undefined &&
|
|
832
|
-
fetchSite !== "same-origin" &&
|
|
833
|
-
!sameOrigin &&
|
|
834
|
-
allowedOrigin === null
|
|
835
|
-
)
|
|
836
|
-
return false;
|
|
837
|
-
if (input.origin !== undefined) {
|
|
838
|
-
if (!sameOrigin && allowedOrigin === null) {
|
|
839
|
-
return false;
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
return input.csrfToken === "1";
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
export function isIdentityProxyRequestAllowed(input: {
|
|
846
|
-
path: string;
|
|
847
|
-
basePath?: string;
|
|
848
|
-
remoteAddress?: string;
|
|
849
|
-
authorization?: string;
|
|
850
|
-
proxyAuthorization?: string;
|
|
851
|
-
proxyTokenHeader?: string;
|
|
852
|
-
options: Pick<
|
|
853
|
-
IdentityProxyOptions,
|
|
854
|
-
| "restrictRemoteControl"
|
|
855
|
-
| "allowRemoteControl"
|
|
856
|
-
| "controlToken"
|
|
857
|
-
| "proxyToken"
|
|
858
|
-
| "allowUnauthenticatedRemoteProxy"
|
|
859
|
-
>;
|
|
860
|
-
}): boolean {
|
|
861
|
-
const pathname = stripBasePath(
|
|
862
|
-
new URL(input.path, "http://localhost").pathname,
|
|
863
|
-
input.basePath ?? getConfiguredBasePath(process.env),
|
|
864
|
-
);
|
|
865
|
-
if (!isLoopbackPeer(input.remoteAddress) && isInstanceManagementPath(pathname)) {
|
|
866
|
-
return tokensMatch(bearerToken(input.authorization), input.options.controlToken);
|
|
867
|
-
}
|
|
868
|
-
if (input.options.restrictRemoteControl !== true) return true;
|
|
869
|
-
if (input.options.allowRemoteControl === true) return true;
|
|
870
|
-
if (isLoopbackPeer(input.remoteAddress)) return true;
|
|
871
|
-
|
|
872
|
-
if (pathname === "/proxy" || pathname.startsWith("/proxy/")) {
|
|
873
|
-
if (input.options.allowUnauthenticatedRemoteProxy === true) return true;
|
|
874
|
-
const proxyCredential = bearerToken(input.proxyAuthorization) ?? input.proxyTokenHeader ?? null;
|
|
875
|
-
return tokensMatch(proxyCredential, input.options.proxyToken);
|
|
876
|
-
}
|
|
877
|
-
if (isPublicHealthPath(pathname)) return true;
|
|
878
|
-
return tokensMatch(bearerToken(input.authorization), input.options.controlToken);
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
type AliasControlBodyResult =
|
|
882
|
-
| { ok: true; body: string }
|
|
883
|
-
| { ok: false; status: number; error: string };
|
|
884
|
-
|
|
885
|
-
function readAliasControlBody(req: http.IncomingMessage): Promise<AliasControlBodyResult> {
|
|
886
|
-
const contentLength = declaredContentLength(req.headers["content-length"]);
|
|
887
|
-
if (contentLength !== null && (!Number.isFinite(contentLength) || contentLength < 0)) {
|
|
888
|
-
req.resume();
|
|
889
|
-
return Promise.resolve({ ok: false, status: 400, error: "Invalid Content-Length header" });
|
|
890
|
-
}
|
|
891
|
-
if (contentLength !== null && contentLength > ALIAS_CONTROL_MAX_REQUEST_BYTES) {
|
|
892
|
-
req.resume();
|
|
893
|
-
return Promise.resolve({
|
|
894
|
-
ok: false,
|
|
895
|
-
status: 413,
|
|
896
|
-
error: `Alias control body exceeds ${String(ALIAS_CONTROL_MAX_REQUEST_BYTES)} bytes`,
|
|
897
|
-
});
|
|
898
|
-
}
|
|
899
|
-
|
|
900
|
-
return new Promise((resolve) => {
|
|
901
|
-
const chunks: Buffer[] = [];
|
|
902
|
-
let receivedBytes = 0;
|
|
903
|
-
let settled = false;
|
|
904
|
-
const finish = (result: AliasControlBodyResult): void => {
|
|
905
|
-
if (settled) return;
|
|
906
|
-
settled = true;
|
|
907
|
-
resolve(result);
|
|
908
|
-
};
|
|
909
|
-
req.on("data", (chunk: unknown) => {
|
|
910
|
-
if (settled) return;
|
|
911
|
-
const buffer = toBuffer(chunk);
|
|
912
|
-
receivedBytes += buffer.byteLength;
|
|
913
|
-
if (receivedBytes > ALIAS_CONTROL_MAX_REQUEST_BYTES) {
|
|
914
|
-
finish({
|
|
915
|
-
ok: false,
|
|
916
|
-
status: 413,
|
|
917
|
-
error: `Alias control body exceeds ${String(ALIAS_CONTROL_MAX_REQUEST_BYTES)} bytes`,
|
|
918
|
-
});
|
|
919
|
-
return;
|
|
920
|
-
}
|
|
921
|
-
chunks.push(buffer);
|
|
922
|
-
});
|
|
923
|
-
req.on("end", () => {
|
|
924
|
-
finish({ ok: true, body: Buffer.concat(chunks).toString("utf8") });
|
|
925
|
-
});
|
|
926
|
-
req.on("aborted", () => {
|
|
927
|
-
finish({ ok: false, status: 400, error: "Client aborted alias control request" });
|
|
928
|
-
});
|
|
929
|
-
req.on("error", () => {
|
|
930
|
-
finish({ ok: false, status: 400, error: "Alias control request body failed" });
|
|
931
|
-
});
|
|
932
|
-
});
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
type LocalControlBodyResult =
|
|
936
|
-
| { ok: true; body: Buffer }
|
|
937
|
-
| { ok: false; status: number; error: string };
|
|
938
|
-
|
|
939
|
-
function readLocalControlBody(
|
|
940
|
-
req: http.IncomingMessage,
|
|
941
|
-
maxBytes: number,
|
|
942
|
-
timeoutMs: number,
|
|
943
|
-
): Promise<LocalControlBodyResult> {
|
|
944
|
-
return new Promise((resolve) => {
|
|
945
|
-
const chunks: Buffer[] = [];
|
|
946
|
-
let receivedBytes = 0;
|
|
947
|
-
let settled = false;
|
|
948
|
-
const timer = setTimeout(() => {
|
|
949
|
-
finish({ ok: false, status: 408, error: "Instance request body timed out" });
|
|
950
|
-
req.resume();
|
|
951
|
-
}, timeoutMs);
|
|
952
|
-
const finish = (result: LocalControlBodyResult): void => {
|
|
953
|
-
if (settled) return;
|
|
954
|
-
settled = true;
|
|
955
|
-
clearTimeout(timer);
|
|
956
|
-
resolve(result);
|
|
957
|
-
};
|
|
958
|
-
req.on("data", (chunk: unknown) => {
|
|
959
|
-
if (settled) return;
|
|
960
|
-
const buffer = toBuffer(chunk);
|
|
961
|
-
receivedBytes += buffer.byteLength;
|
|
962
|
-
if (receivedBytes > maxBytes) {
|
|
963
|
-
finish({
|
|
964
|
-
ok: false,
|
|
965
|
-
status: 413,
|
|
966
|
-
error: `Instance request body exceeds ${String(maxBytes)} bytes`,
|
|
967
|
-
});
|
|
968
|
-
req.resume();
|
|
969
|
-
return;
|
|
970
|
-
}
|
|
971
|
-
chunks.push(buffer);
|
|
972
|
-
});
|
|
973
|
-
req.on("end", () => finish({ ok: true, body: Buffer.concat(chunks) }));
|
|
974
|
-
req.on("aborted", () =>
|
|
975
|
-
finish({ ok: false, status: 400, error: "Client aborted instance request body" }),
|
|
976
|
-
);
|
|
977
|
-
req.on("error", () =>
|
|
978
|
-
finish({ ok: false, status: 400, error: "Instance request body failed" }),
|
|
979
|
-
);
|
|
980
|
-
});
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
function writeLocalControlError(
|
|
984
|
-
res: http.ServerResponse,
|
|
985
|
-
status: number,
|
|
986
|
-
error: string,
|
|
987
|
-
allowedUiOrigin: string | null,
|
|
988
|
-
): void {
|
|
989
|
-
res.writeHead(status, {
|
|
990
|
-
"content-type": "application/json; charset=utf-8",
|
|
991
|
-
"cache-control": "no-store",
|
|
992
|
-
...uiCorsHeaders(allowedUiOrigin),
|
|
993
|
-
});
|
|
994
|
-
res.end(JSON.stringify({ error }));
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
async function handleLocalInstanceApi(
|
|
998
|
-
req: http.IncomingMessage,
|
|
999
|
-
res: http.ServerResponse,
|
|
1000
|
-
handler: (request: Request) => Promise<Response>,
|
|
1001
|
-
upstreamPath: string,
|
|
1002
|
-
requestPublicOrigin: string,
|
|
1003
|
-
allowedUiOrigin: string | null,
|
|
1004
|
-
maxRequestBytes: number,
|
|
1005
|
-
requestTimeoutMs: number,
|
|
1006
|
-
): Promise<void> {
|
|
1007
|
-
const body = await readLocalControlBody(
|
|
1008
|
-
req,
|
|
1009
|
-
Math.min(maxRequestBytes, INSTANCE_API_MAX_REQUEST_BYTES),
|
|
1010
|
-
requestTimeoutMs,
|
|
1011
|
-
);
|
|
1012
|
-
if (!body.ok) {
|
|
1013
|
-
writeLocalControlError(res, body.status, body.error, allowedUiOrigin);
|
|
1014
|
-
return;
|
|
1015
|
-
}
|
|
1016
|
-
const method = (req.method ?? "GET").toUpperCase();
|
|
1017
|
-
const headers = new Headers();
|
|
1018
|
-
const contentType = firstHeader(req.headers["content-type"]);
|
|
1019
|
-
if (contentType !== undefined) headers.set("content-type", contentType);
|
|
1020
|
-
const request = new Request(new URL(upstreamPath, requestPublicOrigin), {
|
|
1021
|
-
method,
|
|
1022
|
-
headers,
|
|
1023
|
-
body: method === "GET" || method === "HEAD" ? undefined : body.body.toString("utf8"),
|
|
1024
|
-
});
|
|
1025
|
-
let response: Response;
|
|
1026
|
-
try {
|
|
1027
|
-
response = await handler(request);
|
|
1028
|
-
} catch {
|
|
1029
|
-
writeLocalControlError(res, 503, "Instance supervisor request failed", allowedUiOrigin);
|
|
1030
|
-
return;
|
|
1031
|
-
}
|
|
1032
|
-
const responseBody = Buffer.from(await response.arrayBuffer());
|
|
1033
|
-
if (responseBody.byteLength > LOCAL_CONTROL_MAX_RESPONSE_BYTES) {
|
|
1034
|
-
writeLocalControlError(
|
|
1035
|
-
res,
|
|
1036
|
-
502,
|
|
1037
|
-
"Instance supervisor response exceeded its resource limit",
|
|
1038
|
-
allowedUiOrigin,
|
|
1039
|
-
);
|
|
1040
|
-
return;
|
|
1041
|
-
}
|
|
1042
|
-
const responseHeaders: Record<string, string> = {
|
|
1043
|
-
...uiCorsHeaders(allowedUiOrigin),
|
|
1044
|
-
"content-length": String(responseBody.byteLength),
|
|
1045
|
-
};
|
|
1046
|
-
response.headers.forEach((value, name) => {
|
|
1047
|
-
const lowerName = name.toLowerCase();
|
|
1048
|
-
if (!REQUEST_HOP_BY_HOP.has(lowerName) && lowerName !== "content-length") {
|
|
1049
|
-
responseHeaders[lowerName] = value;
|
|
1050
|
-
}
|
|
1051
|
-
});
|
|
1052
|
-
responseHeaders["cache-control"] = "no-store";
|
|
1053
|
-
res.writeHead(response.status, responseHeaders);
|
|
1054
|
-
res.end(responseBody);
|
|
1055
|
-
}
|
|
1056
|
-
|
|
1057
|
-
function isUnknownRecord(value: unknown): value is Record<string, unknown> {
|
|
1058
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
function aliasBasePathFromJson(
|
|
1062
|
-
body: string,
|
|
1063
|
-
): { ok: true; basePath: string } | { ok: false; error: string } {
|
|
1064
|
-
let parsed: unknown;
|
|
1065
|
-
try {
|
|
1066
|
-
parsed = JSON.parse(body);
|
|
1067
|
-
} catch {
|
|
1068
|
-
return { ok: false, error: "Alias control body must be valid JSON." };
|
|
1069
|
-
}
|
|
1070
|
-
if (!isUnknownRecord(parsed) || typeof parsed.basePath !== "string") {
|
|
1071
|
-
return { ok: false, error: 'Alias control body must contain a string "basePath" field.' };
|
|
1072
|
-
}
|
|
1073
|
-
return { ok: true, basePath: parsed.basePath };
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
function writeAliasControlResponse(
|
|
1077
|
-
res: http.ServerResponse,
|
|
1078
|
-
registry: BasePathAliasRegistry,
|
|
1079
|
-
status: number,
|
|
1080
|
-
result:
|
|
1081
|
-
| { basePath?: string; code?: string; error?: string }
|
|
1082
|
-
| { basePath: string }
|
|
1083
|
-
| undefined = undefined,
|
|
1084
|
-
extraHeaders: Readonly<Record<string, string>> = {},
|
|
1085
|
-
): void {
|
|
1086
|
-
res.writeHead(status, {
|
|
1087
|
-
"content-type": "application/json; charset=utf-8",
|
|
1088
|
-
"cache-control": "no-store",
|
|
1089
|
-
...extraHeaders,
|
|
1090
|
-
});
|
|
1091
|
-
res.end(
|
|
1092
|
-
JSON.stringify({
|
|
1093
|
-
canonicalBasePath: registry.canonicalBasePath,
|
|
1094
|
-
aliases: registry.list(),
|
|
1095
|
-
runtimeScoped: true,
|
|
1096
|
-
...result,
|
|
1097
|
-
}),
|
|
1098
|
-
);
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
async function handleAliasControlRequest(
|
|
1102
|
-
req: http.IncomingMessage,
|
|
1103
|
-
res: http.ServerResponse,
|
|
1104
|
-
registry: BasePathAliasRegistry,
|
|
1105
|
-
): Promise<void> {
|
|
1106
|
-
if (!isLoopbackPeer(req.socket.remoteAddress)) {
|
|
1107
|
-
req.resume();
|
|
1108
|
-
writeAliasControlResponse(res, registry, 403, {
|
|
1109
|
-
error: "Base Path aliases can only be managed from the local machine.",
|
|
1110
|
-
});
|
|
1111
|
-
return;
|
|
1112
|
-
}
|
|
1113
|
-
if (
|
|
1114
|
-
!isBrowserMutationAllowed({
|
|
1115
|
-
path: req.url ?? IDENTITY_PROXY_ALIAS_CONTROL_PATH,
|
|
1116
|
-
basePath: "",
|
|
1117
|
-
method: req.method,
|
|
1118
|
-
host: req.headers.host,
|
|
1119
|
-
origin: req.headers.origin,
|
|
1120
|
-
secFetchSite: firstHeader(req.headers["sec-fetch-site"]),
|
|
1121
|
-
csrfToken: firstHeader(req.headers[CSRF_HEADER]),
|
|
1122
|
-
})
|
|
1123
|
-
) {
|
|
1124
|
-
req.resume();
|
|
1125
|
-
writeAliasControlResponse(res, registry, 403, {
|
|
1126
|
-
error: "Browser mutation requires same-origin CSRF proof.",
|
|
1127
|
-
});
|
|
1128
|
-
return;
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
const method = (req.method ?? "GET").toUpperCase();
|
|
1132
|
-
if (method === "GET") {
|
|
1133
|
-
req.resume();
|
|
1134
|
-
writeAliasControlResponse(res, registry, 200);
|
|
1135
|
-
return;
|
|
1136
|
-
}
|
|
1137
|
-
if (method !== "POST" && method !== "DELETE") {
|
|
1138
|
-
req.resume();
|
|
1139
|
-
writeAliasControlResponse(
|
|
1140
|
-
res,
|
|
1141
|
-
registry,
|
|
1142
|
-
405,
|
|
1143
|
-
{ error: "Alias control supports GET, POST, and DELETE." },
|
|
1144
|
-
{ allow: "GET, POST, DELETE" },
|
|
1145
|
-
);
|
|
1146
|
-
return;
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
const bodyResult = await readAliasControlBody(req);
|
|
1150
|
-
if (!bodyResult.ok) {
|
|
1151
|
-
writeAliasControlResponse(res, registry, bodyResult.status, { error: bodyResult.error });
|
|
1152
|
-
return;
|
|
1153
|
-
}
|
|
1154
|
-
const input = aliasBasePathFromJson(bodyResult.body);
|
|
1155
|
-
if (!input.ok) {
|
|
1156
|
-
writeAliasControlResponse(res, registry, 400, { error: input.error });
|
|
1157
|
-
return;
|
|
1158
|
-
}
|
|
1159
|
-
const mutation =
|
|
1160
|
-
method === "POST" ? registry.add(input.basePath) : registry.remove(input.basePath);
|
|
1161
|
-
if (mutation.ok) {
|
|
1162
|
-
writeAliasControlResponse(res, registry, method === "POST" ? 201 : 200, {
|
|
1163
|
-
basePath: mutation.basePath,
|
|
1164
|
-
});
|
|
1165
|
-
return;
|
|
1166
|
-
}
|
|
1167
|
-
const status =
|
|
1168
|
-
mutation.code === "duplicate" || mutation.code === "overlap"
|
|
1169
|
-
? 409
|
|
1170
|
-
: mutation.code === "not-found"
|
|
1171
|
-
? 404
|
|
1172
|
-
: 400;
|
|
1173
|
-
writeAliasControlResponse(res, registry, status, {
|
|
1174
|
-
code: mutation.code,
|
|
1175
|
-
error: mutation.error,
|
|
1176
|
-
});
|
|
1177
|
-
}
|
|
1178
|
-
|
|
1179
|
-
function writeManagedInstanceControlResponse(
|
|
1180
|
-
res: http.ServerResponse,
|
|
1181
|
-
status: number,
|
|
1182
|
-
body: Readonly<Record<string, unknown>>,
|
|
1183
|
-
extraHeaders: Readonly<Record<string, string>> = {},
|
|
1184
|
-
onFinished: (() => void) | undefined = undefined,
|
|
1185
|
-
): void {
|
|
1186
|
-
res.writeHead(status, {
|
|
1187
|
-
"content-type": "application/json; charset=utf-8",
|
|
1188
|
-
"cache-control": "no-store",
|
|
1189
|
-
...extraHeaders,
|
|
1190
|
-
});
|
|
1191
|
-
res.end(JSON.stringify(body), onFinished);
|
|
1192
|
-
}
|
|
1193
|
-
|
|
1194
|
-
function handleManagedInstanceControlRequest(
|
|
1195
|
-
req: http.IncomingMessage,
|
|
1196
|
-
res: http.ServerResponse,
|
|
1197
|
-
pathname: string,
|
|
1198
|
-
managedInstance: ManagedInstanceControlOptions | undefined,
|
|
1199
|
-
): void {
|
|
1200
|
-
req.resume();
|
|
1201
|
-
if (managedInstance === undefined) {
|
|
1202
|
-
writeManagedInstanceControlResponse(res, 404, { error: "Control endpoint not found" });
|
|
1203
|
-
return;
|
|
1204
|
-
}
|
|
1205
|
-
const authorized = managedInstanceTokensMatch(
|
|
1206
|
-
firstHeader(req.headers[MANAGED_INSTANCE_TOKEN_HEADER]),
|
|
1207
|
-
managedInstance.controlToken,
|
|
1208
|
-
);
|
|
1209
|
-
if (!authorized) {
|
|
1210
|
-
writeManagedInstanceControlResponse(res, 403, { error: "Instance control access denied" });
|
|
1211
|
-
return;
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
const method = (req.method ?? "GET").toUpperCase();
|
|
1215
|
-
if (pathname === MANAGED_INSTANCE_CONTROL_PATH) {
|
|
1216
|
-
if (method !== "GET") {
|
|
1217
|
-
writeManagedInstanceControlResponse(
|
|
1218
|
-
res,
|
|
1219
|
-
405,
|
|
1220
|
-
{ error: "Instance identity supports GET only" },
|
|
1221
|
-
{ allow: "GET" },
|
|
1222
|
-
);
|
|
1223
|
-
return;
|
|
1224
|
-
}
|
|
1225
|
-
writeManagedInstanceControlResponse(res, 200, {
|
|
1226
|
-
schemaVersion: 1,
|
|
1227
|
-
backend: managedInstance.backend ?? "typescript",
|
|
1228
|
-
name: managedInstance.name,
|
|
1229
|
-
instanceId: managedInstance.instanceId,
|
|
1230
|
-
launchId: managedInstance.launchId,
|
|
1231
|
-
supervisorPid: managedInstance.supervisorPid,
|
|
1232
|
-
startedAt: managedInstance.startedAt,
|
|
1233
|
-
publicPort: managedInstance.publicPort,
|
|
1234
|
-
upstreamPort: managedInstance.upstreamPort,
|
|
1235
|
-
});
|
|
1236
|
-
return;
|
|
1237
|
-
}
|
|
1238
|
-
if (method !== "POST") {
|
|
1239
|
-
writeManagedInstanceControlResponse(
|
|
1240
|
-
res,
|
|
1241
|
-
405,
|
|
1242
|
-
{ error: "Instance shutdown supports POST only" },
|
|
1243
|
-
{ allow: "POST" },
|
|
1244
|
-
);
|
|
1245
|
-
return;
|
|
1246
|
-
}
|
|
1247
|
-
writeManagedInstanceControlResponse(
|
|
1248
|
-
res,
|
|
1249
|
-
202,
|
|
1250
|
-
{ accepted: true, launchId: managedInstance.launchId },
|
|
1251
|
-
{},
|
|
1252
|
-
() => {
|
|
1253
|
-
process.nextTick(managedInstance.requestShutdown);
|
|
1254
|
-
},
|
|
1255
|
-
);
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
function isIdentityProxyControlPath(pathname: string): boolean {
|
|
1259
|
-
return (
|
|
1260
|
-
pathname === IDENTITY_PROXY_CONTROL_NAMESPACE ||
|
|
1261
|
-
pathname.startsWith(`${IDENTITY_PROXY_CONTROL_NAMESPACE}/`)
|
|
1262
|
-
);
|
|
1263
|
-
}
|
|
1264
|
-
|
|
1265
|
-
/**
|
|
1266
|
-
* Start a tiny native Node HTTP server that:
|
|
1267
|
-
* 1. Reads the client connection's source port (`req.socket.remotePort`).
|
|
1268
|
-
* 2. Resolves that port to a PID via the OS connection table
|
|
1269
|
-
* (`Get-NetTCPConnection -LocalPort <port>` on Windows,
|
|
1270
|
-
* `ss -tanp state established` on Linux/macOS).
|
|
1271
|
-
* 3. Resolves the PID's cwd / project folder.
|
|
1272
|
-
* 4. Injects everything as `X-Agent-Inspector-Client-*` headers.
|
|
1273
|
-
* 5. Reverse-proxies the request to the upstream inspector (TanStack
|
|
1274
|
-
* Start, which already reads those headers via `getClientInfo`).
|
|
1275
|
-
*
|
|
1276
|
-
* Why this exists: TanStack Start strips the underlying TCP socket from
|
|
1277
|
-
* the fetch-API `Request` before it reaches the proxy handler, so the
|
|
1278
|
-
* handler cannot read `socket.remotePort`. Sitting in front of TanStack
|
|
1279
|
-
* Start as a native Node server restores the ability to look up the
|
|
1280
|
-
* client PID at the socket level — no wrapper script, no client-side
|
|
1281
|
-
* changes, no header configuration by the AI tool author.
|
|
1282
|
-
*
|
|
1283
|
-
* The proxy degrades gracefully when the OS lookup fails (missing
|
|
1284
|
-
* permissions, port not found): the request is still forwarded, just
|
|
1285
|
-
* without identity headers, so it falls back to the existing
|
|
1286
|
-
* best-effort scan inside TanStack Start.
|
|
1287
|
-
*/
|
|
1288
|
-
export function startIdentityProxy(options: IdentityProxyOptions): Promise<http.Server> {
|
|
1289
|
-
const allowedUiOrigins = parseUiOriginAllowlist(options.allowedUiOrigins?.join(","));
|
|
1290
|
-
if (allowedUiOrigins.rejected.length > 0) {
|
|
1291
|
-
return Promise.reject(
|
|
1292
|
-
new Error(
|
|
1293
|
-
`Unsafe UI origins are not accepted: ${allowedUiOrigins.rejected.join(", ")}. Only exact loopback HTTP(S) origins are supported.`,
|
|
1294
|
-
),
|
|
1295
|
-
);
|
|
1296
|
-
}
|
|
1297
|
-
const publicOrigin = normalizeTrustedPublicOrigin(options.publicOrigin);
|
|
1298
|
-
if (publicOrigin === null) {
|
|
1299
|
-
return Promise.reject(
|
|
1300
|
-
new Error(
|
|
1301
|
-
"publicOrigin must be an exact HTTP(S) origin without credentials, path, or query.",
|
|
1302
|
-
),
|
|
1303
|
-
);
|
|
1304
|
-
}
|
|
1305
|
-
const effectiveOptions: IdentityProxyOptions = {
|
|
1306
|
-
...options,
|
|
1307
|
-
allowedUiOrigins: allowedUiOrigins.origins,
|
|
1308
|
-
publicOrigin,
|
|
1309
|
-
};
|
|
1310
|
-
return new Promise((resolve, reject) => {
|
|
1311
|
-
const server = http.createServer();
|
|
1312
|
-
const aliasRegistry =
|
|
1313
|
-
options.aliasRegistry ?? createBasePathAliasRegistry(getConfiguredBasePath(process.env));
|
|
1314
|
-
const runtimeState: IdentityProxyRuntimeState = {
|
|
1315
|
-
acceptingRequests: true,
|
|
1316
|
-
activeRequests: 0,
|
|
1317
|
-
drainWaiters: new Set(),
|
|
1318
|
-
};
|
|
1319
|
-
identityProxyRuntimeStates.set(server, runtimeState);
|
|
1320
|
-
// Eagerly resolve client identity on `connection` — at that point the
|
|
1321
|
-
// socket is fresh and the OS connection table still lists it as
|
|
1322
|
-
// ESTABLISHED. By the time `request` fires (let alone after we finish
|
|
1323
|
-
// reading the body) HTTP/1.0 clients have already closed their side
|
|
1324
|
-
// and the row is in TIME_WAIT with PID 0.
|
|
1325
|
-
server.on("connection", (socket: import("node:net").Socket) => {
|
|
1326
|
-
const remotePort = socket.remotePort;
|
|
1327
|
-
if (remotePort !== undefined && remotePort > 0) {
|
|
1328
|
-
void lookupClientByPort(remotePort).catch(() => null);
|
|
1329
|
-
}
|
|
1330
|
-
});
|
|
1331
|
-
server.on("request", (req, res) => {
|
|
1332
|
-
if (!runtimeState.acceptingRequests) {
|
|
1333
|
-
res.writeHead(503, {
|
|
1334
|
-
"content-type": "application/json; charset=utf-8",
|
|
1335
|
-
"cache-control": "no-store",
|
|
1336
|
-
connection: "close",
|
|
1337
|
-
"retry-after": "5",
|
|
1338
|
-
});
|
|
1339
|
-
res.end(JSON.stringify({ error: "Agent Inspector is shutting down" }));
|
|
1340
|
-
req.resume();
|
|
1341
|
-
return;
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
runtimeState.activeRequests += 1;
|
|
1345
|
-
let released = false;
|
|
1346
|
-
const release = (): void => {
|
|
1347
|
-
if (released) return;
|
|
1348
|
-
released = true;
|
|
1349
|
-
runtimeState.activeRequests = Math.max(0, runtimeState.activeRequests - 1);
|
|
1350
|
-
if (runtimeState.activeRequests !== 0) return;
|
|
1351
|
-
for (const resolveDrain of runtimeState.drainWaiters) resolveDrain();
|
|
1352
|
-
runtimeState.drainWaiters.clear();
|
|
1353
|
-
};
|
|
1354
|
-
res.once("finish", release);
|
|
1355
|
-
res.once("close", release);
|
|
1356
|
-
void handleRequest(req, res, effectiveOptions, aliasRegistry).catch((err: unknown) => {
|
|
1357
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1358
|
-
if (!res.headersSent) {
|
|
1359
|
-
res.writeHead(502, { "content-type": "text/plain" });
|
|
1360
|
-
}
|
|
1361
|
-
res.end(`Identity proxy error: ${message}`);
|
|
1362
|
-
});
|
|
1363
|
-
});
|
|
1364
|
-
server.once("error", reject);
|
|
1365
|
-
server.listen(options.listenPort, options.listenHost, () => {
|
|
1366
|
-
server.removeListener("error", reject);
|
|
1367
|
-
resolve(server);
|
|
1368
|
-
});
|
|
1369
|
-
});
|
|
1370
|
-
}
|
|
1371
|
-
|
|
1372
|
-
export function stopIdentityProxyAdmission(server: http.Server): void {
|
|
1373
|
-
const state = identityProxyRuntimeStates.get(server);
|
|
1374
|
-
if (state !== undefined) state.acceptingRequests = false;
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1377
|
-
export async function waitForIdentityProxyDrain(server: http.Server): Promise<void> {
|
|
1378
|
-
const state = identityProxyRuntimeStates.get(server);
|
|
1379
|
-
if (state === undefined || state.activeRequests === 0) return;
|
|
1380
|
-
await new Promise<void>((resolve) => {
|
|
1381
|
-
state.drainWaiters.add(resolve);
|
|
1382
|
-
});
|
|
1383
|
-
}
|
|
1384
|
-
|
|
1385
|
-
export async function closeIdentityProxyGracefully(server: http.Server): Promise<void> {
|
|
1386
|
-
stopIdentityProxyAdmission(server);
|
|
1387
|
-
const closed = new Promise<void>((resolve) => {
|
|
1388
|
-
if (!server.listening) {
|
|
1389
|
-
resolve();
|
|
1390
|
-
return;
|
|
1391
|
-
}
|
|
1392
|
-
server.close(() => resolve());
|
|
1393
|
-
});
|
|
1394
|
-
await Promise.all([closed, waitForIdentityProxyDrain(server)]);
|
|
1395
|
-
}
|
|
1396
|
-
|
|
1397
|
-
export function forceCloseIdentityProxy(server: http.Server): void {
|
|
1398
|
-
stopIdentityProxyAdmission(server);
|
|
1399
|
-
server.closeAllConnections();
|
|
1400
|
-
server.close();
|
|
1401
|
-
}
|
|
1402
|
-
|
|
1403
|
-
async function handleRequest(
|
|
1404
|
-
req: http.IncomingMessage,
|
|
1405
|
-
res: http.ServerResponse,
|
|
1406
|
-
options: IdentityProxyOptions,
|
|
1407
|
-
aliasRegistry: BasePathAliasRegistry,
|
|
1408
|
-
): Promise<void> {
|
|
1409
|
-
const requestUrl = new URL(req.url ?? "/", "http://localhost");
|
|
1410
|
-
if (!isTrustedIdentityProxyHost(req.headers.host, options)) {
|
|
1411
|
-
res.writeHead(400, {
|
|
1412
|
-
"content-type": "application/json; charset=utf-8",
|
|
1413
|
-
"cache-control": "no-store",
|
|
1414
|
-
});
|
|
1415
|
-
res.end(JSON.stringify({ error: "Untrusted Host header" }));
|
|
1416
|
-
req.resume();
|
|
1417
|
-
return;
|
|
1418
|
-
}
|
|
1419
|
-
|
|
1420
|
-
if (requestUrl.pathname === IDENTITY_PROXY_ALIAS_CONTROL_PATH) {
|
|
1421
|
-
await handleAliasControlRequest(req, res, aliasRegistry);
|
|
1422
|
-
return;
|
|
1423
|
-
}
|
|
1424
|
-
|
|
1425
|
-
if (
|
|
1426
|
-
requestUrl.pathname === MANAGED_INSTANCE_CONTROL_PATH ||
|
|
1427
|
-
requestUrl.pathname === MANAGED_INSTANCE_SHUTDOWN_PATH
|
|
1428
|
-
) {
|
|
1429
|
-
handleManagedInstanceControlRequest(req, res, requestUrl.pathname, options.managedInstance);
|
|
1430
|
-
return;
|
|
1431
|
-
}
|
|
1432
|
-
|
|
1433
|
-
if (isIdentityProxyControlPath(requestUrl.pathname)) {
|
|
1434
|
-
req.resume();
|
|
1435
|
-
writeManagedInstanceControlResponse(res, 404, { error: "Control endpoint not found" });
|
|
1436
|
-
return;
|
|
1437
|
-
}
|
|
1438
|
-
|
|
1439
|
-
const resolution = resolveBasePathAliasRequest(aliasRegistry, req.url ?? "/");
|
|
1440
|
-
const basePath = resolution.effectiveBasePath;
|
|
1441
|
-
const upstreamPath = resolution.upstreamPath;
|
|
1442
|
-
const upstreamPathname = new URL(upstreamPath, "http://localhost").pathname;
|
|
1443
|
-
const requestOrigin = req.headers.origin;
|
|
1444
|
-
const requestPublicOrigin = publicOriginForRequest(req, options);
|
|
1445
|
-
const crossOriginRequest =
|
|
1446
|
-
requestOrigin !== undefined &&
|
|
1447
|
-
!isSameRequestOrigin(requestOrigin, req.headers.host, requestPublicOrigin);
|
|
1448
|
-
const allowedUiOrigin = crossOriginRequest
|
|
1449
|
-
? matchedUiOrigin(requestOrigin, options.allowedUiOrigins)
|
|
1450
|
-
: null;
|
|
1451
|
-
|
|
1452
|
-
if (crossOriginRequest && isModelProxyPath(upstreamPathname)) {
|
|
1453
|
-
res.writeHead(403, {
|
|
1454
|
-
"content-type": "application/json; charset=utf-8",
|
|
1455
|
-
"cache-control": "no-store",
|
|
1456
|
-
});
|
|
1457
|
-
res.end(
|
|
1458
|
-
JSON.stringify({ error: "Cross-origin browser access to the model proxy is forbidden." }),
|
|
1459
|
-
);
|
|
1460
|
-
req.resume();
|
|
1461
|
-
return;
|
|
1462
|
-
}
|
|
1463
|
-
|
|
1464
|
-
if (crossOriginRequest && upstreamPathname === "/api/mcp") {
|
|
1465
|
-
res.writeHead(403, {
|
|
1466
|
-
"content-type": "application/json; charset=utf-8",
|
|
1467
|
-
"cache-control": "no-store",
|
|
1468
|
-
});
|
|
1469
|
-
res.end(JSON.stringify({ error: "Browser CORS is not enabled for the MCP endpoint." }));
|
|
1470
|
-
req.resume();
|
|
1471
|
-
return;
|
|
1472
|
-
}
|
|
1473
|
-
|
|
1474
|
-
if (crossOriginRequest && isUiControlPath(upstreamPathname)) {
|
|
1475
|
-
if (allowedUiOrigin === null) {
|
|
1476
|
-
res.writeHead(403, {
|
|
1477
|
-
"content-type": "application/json; charset=utf-8",
|
|
1478
|
-
"cache-control": "no-store",
|
|
1479
|
-
});
|
|
1480
|
-
res.end(
|
|
1481
|
-
JSON.stringify({ error: "UI origin is not allowed by this Agent Inspector runtime." }),
|
|
1482
|
-
);
|
|
1483
|
-
req.resume();
|
|
1484
|
-
return;
|
|
1485
|
-
}
|
|
1486
|
-
if ((req.method ?? "GET").toUpperCase() === "OPTIONS") {
|
|
1487
|
-
handleUiCorsPreflight(req, res, allowedUiOrigin);
|
|
1488
|
-
return;
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
|
|
1492
|
-
if (basePath.length > 0 && requestUrl.pathname.startsWith("/assets/")) {
|
|
1493
|
-
res.writeHead(307, {
|
|
1494
|
-
location: `${basePath}${requestUrl.pathname}${requestUrl.search}`,
|
|
1495
|
-
"cache-control": "no-store",
|
|
1496
|
-
});
|
|
1497
|
-
res.end();
|
|
1498
|
-
req.resume();
|
|
1499
|
-
return;
|
|
1500
|
-
}
|
|
1501
|
-
|
|
1502
|
-
if (
|
|
1503
|
-
!isBrowserMutationAllowed({
|
|
1504
|
-
path: req.url ?? "/",
|
|
1505
|
-
basePath,
|
|
1506
|
-
method: req.method,
|
|
1507
|
-
host: req.headers.host,
|
|
1508
|
-
origin: req.headers.origin,
|
|
1509
|
-
secFetchSite: firstHeader(req.headers["sec-fetch-site"]),
|
|
1510
|
-
csrfToken: firstHeader(req.headers[CSRF_HEADER]),
|
|
1511
|
-
allowedUiOrigins: options.allowedUiOrigins,
|
|
1512
|
-
publicOrigin: requestPublicOrigin,
|
|
1513
|
-
})
|
|
1514
|
-
) {
|
|
1515
|
-
res.writeHead(403, {
|
|
1516
|
-
"content-type": "application/json; charset=utf-8",
|
|
1517
|
-
"cache-control": "no-store",
|
|
1518
|
-
...uiCorsHeaders(allowedUiOrigin),
|
|
1519
|
-
});
|
|
1520
|
-
res.end(JSON.stringify({ error: "Browser mutation requires same-origin CSRF proof" }));
|
|
1521
|
-
req.resume();
|
|
1522
|
-
return;
|
|
1523
|
-
}
|
|
1524
|
-
|
|
1525
|
-
if (
|
|
1526
|
-
!isIdentityProxyRequestAllowed({
|
|
1527
|
-
path: req.url ?? "/",
|
|
1528
|
-
basePath,
|
|
1529
|
-
remoteAddress: req.socket.remoteAddress,
|
|
1530
|
-
authorization: req.headers.authorization,
|
|
1531
|
-
proxyAuthorization: req.headers["proxy-authorization"],
|
|
1532
|
-
proxyTokenHeader: firstHeader(req.headers[PROXY_TOKEN_HEADER]),
|
|
1533
|
-
options,
|
|
1534
|
-
})
|
|
1535
|
-
) {
|
|
1536
|
-
res.writeHead(403, {
|
|
1537
|
-
"content-type": "application/json; charset=utf-8",
|
|
1538
|
-
"cache-control": "no-store",
|
|
1539
|
-
...uiCorsHeaders(allowedUiOrigin),
|
|
1540
|
-
});
|
|
1541
|
-
res.end(
|
|
1542
|
-
JSON.stringify({
|
|
1543
|
-
error: "Remote access requires a credential scoped to this endpoint.",
|
|
1544
|
-
}),
|
|
1545
|
-
);
|
|
1546
|
-
req.resume();
|
|
1547
|
-
return;
|
|
1548
|
-
}
|
|
1549
|
-
|
|
1550
|
-
if (
|
|
1551
|
-
await tryServeUiAsset(
|
|
1552
|
-
req,
|
|
1553
|
-
res,
|
|
1554
|
-
options,
|
|
1555
|
-
upstreamPathname,
|
|
1556
|
-
basePath,
|
|
1557
|
-
aliasRegistry.canonicalBasePath,
|
|
1558
|
-
)
|
|
1559
|
-
) {
|
|
1560
|
-
return;
|
|
1561
|
-
}
|
|
1562
|
-
|
|
1563
|
-
// The connection-time lookup already populated the per-port cache; this
|
|
1564
|
-
// call now hits the cache and returns the result synchronously.
|
|
1565
|
-
const remotePort = req.socket.remotePort;
|
|
1566
|
-
let identity: Awaited<ReturnType<typeof lookupClientByPort>> | null = null;
|
|
1567
|
-
if (remotePort !== undefined && remotePort > 0) {
|
|
1568
|
-
try {
|
|
1569
|
-
identity = await lookupClientByPort(remotePort);
|
|
1570
|
-
} catch {
|
|
1571
|
-
identity = null;
|
|
1572
|
-
}
|
|
1573
|
-
}
|
|
1574
|
-
|
|
1575
|
-
// Validate declared size before any body allocation, then forward the raw
|
|
1576
|
-
// stream with backpressure while enforcing the actual-byte budget below.
|
|
1577
|
-
const maxRequestBytes = configuredPositiveInteger(
|
|
1578
|
-
options.maxRequestBytes,
|
|
1579
|
-
DEFAULT_MAX_REQUEST_BYTES,
|
|
1580
|
-
);
|
|
1581
|
-
const contentLength = declaredContentLength(req.headers["content-length"]);
|
|
1582
|
-
if (contentLength !== null && (!Number.isFinite(contentLength) || contentLength < 0)) {
|
|
1583
|
-
res.writeHead(400, {
|
|
1584
|
-
"content-type": "application/json; charset=utf-8",
|
|
1585
|
-
"cache-control": "no-store",
|
|
1586
|
-
...uiCorsHeaders(allowedUiOrigin),
|
|
1587
|
-
});
|
|
1588
|
-
res.end(JSON.stringify({ error: "Invalid Content-Length header" }));
|
|
1589
|
-
req.resume();
|
|
1590
|
-
return;
|
|
1591
|
-
}
|
|
1592
|
-
if (contentLength !== null && contentLength > maxRequestBytes) {
|
|
1593
|
-
res.writeHead(413, {
|
|
1594
|
-
"content-type": "application/json; charset=utf-8",
|
|
1595
|
-
"cache-control": "no-store",
|
|
1596
|
-
...uiCorsHeaders(allowedUiOrigin),
|
|
1597
|
-
});
|
|
1598
|
-
res.end(JSON.stringify({ error: `Request body exceeds ${String(maxRequestBytes)} bytes` }));
|
|
1599
|
-
req.resume();
|
|
1600
|
-
return;
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
const upstreamHeaders: Record<string, string | string[]> = {};
|
|
1604
|
-
for (const [name, value] of Object.entries(req.headers)) {
|
|
1605
|
-
const lowerName = name.toLowerCase();
|
|
1606
|
-
if (REQUEST_HOP_BY_HOP.has(lowerName)) continue;
|
|
1607
|
-
if (
|
|
1608
|
-
basePath.length > 0 &&
|
|
1609
|
-
(lowerName === "accept-encoding" || lowerName === "range" || lowerName === "if-range")
|
|
1610
|
-
)
|
|
1611
|
-
continue;
|
|
1612
|
-
if (
|
|
1613
|
-
lowerName.startsWith(IDENTITY_HEADER_PREFIX) &&
|
|
1614
|
-
!FORWARDED_AGENT_HEADER_ALLOWLIST.has(lowerName)
|
|
1615
|
-
)
|
|
1616
|
-
continue;
|
|
1617
|
-
if (lowerName === "authorization" && !isModelProxyPath(upstreamPathname)) continue;
|
|
1618
|
-
if (value === undefined) continue;
|
|
1619
|
-
upstreamHeaders[name] = value;
|
|
1620
|
-
}
|
|
1621
|
-
upstreamHeaders[AGENT_INSPECTOR_PUBLIC_BASE_PATH_HEADER] = basePath.length === 0 ? "/" : basePath;
|
|
1622
|
-
upstreamHeaders[AGENT_INSPECTOR_PUBLIC_ORIGIN_HEADER] = requestPublicOrigin;
|
|
1623
|
-
const publicPort = req.socket.localPort;
|
|
1624
|
-
if (publicPort !== undefined && publicPort > 0 && publicPort <= 65_535) {
|
|
1625
|
-
upstreamHeaders[AGENT_INSPECTOR_PUBLIC_PORT_HEADER] = String(publicPort);
|
|
1626
|
-
}
|
|
1627
|
-
if (identity !== null && identity.pid !== null) {
|
|
1628
|
-
upstreamHeaders[IDENTITY_HEADERS.pid] = String(identity.pid);
|
|
1629
|
-
if (identity.port !== null) {
|
|
1630
|
-
upstreamHeaders[IDENTITY_HEADERS.port] = String(identity.port);
|
|
1631
|
-
}
|
|
1632
|
-
if (identity.cwd !== null) {
|
|
1633
|
-
upstreamHeaders[IDENTITY_HEADERS.cwd] = identity.cwd;
|
|
1634
|
-
}
|
|
1635
|
-
if (identity.projectFolder !== null) {
|
|
1636
|
-
upstreamHeaders[IDENTITY_HEADERS.projectFolder] = identity.projectFolder;
|
|
1637
|
-
}
|
|
1638
|
-
}
|
|
1639
|
-
|
|
1640
|
-
let terminal = false;
|
|
1641
|
-
const requestTimeoutMs = configuredPositiveInteger(
|
|
1642
|
-
options.requestTimeoutMs,
|
|
1643
|
-
DEFAULT_REQUEST_TIMEOUT_MS,
|
|
1644
|
-
);
|
|
1645
|
-
if (options.instanceApiHandler !== undefined && isInstanceManagementPath(upstreamPathname)) {
|
|
1646
|
-
await handleLocalInstanceApi(
|
|
1647
|
-
req,
|
|
1648
|
-
res,
|
|
1649
|
-
options.instanceApiHandler,
|
|
1650
|
-
upstreamPath,
|
|
1651
|
-
requestPublicOrigin,
|
|
1652
|
-
allowedUiOrigin,
|
|
1653
|
-
maxRequestBytes,
|
|
1654
|
-
requestTimeoutMs,
|
|
1655
|
-
);
|
|
1656
|
-
return;
|
|
1657
|
-
}
|
|
1658
|
-
const proxyReq = http.request(
|
|
1659
|
-
{
|
|
1660
|
-
hostname: options.upstreamHost,
|
|
1661
|
-
port: options.upstreamPort,
|
|
1662
|
-
path: upstreamPath,
|
|
1663
|
-
method: req.method,
|
|
1664
|
-
headers: upstreamHeaders,
|
|
1665
|
-
},
|
|
1666
|
-
(proxyRes) => {
|
|
1667
|
-
if (terminal || res.destroyed) {
|
|
1668
|
-
proxyRes.destroy();
|
|
1669
|
-
return;
|
|
1670
|
-
}
|
|
1671
|
-
const destroyUpstreamResponse = (): void => {
|
|
1672
|
-
proxyRes.destroy();
|
|
1673
|
-
proxyRes.socket.destroy();
|
|
1674
|
-
proxyReq.destroy();
|
|
1675
|
-
};
|
|
1676
|
-
const removeDownstreamListeners = (): void => {
|
|
1677
|
-
res.removeListener("close", destroyUpstreamResponse);
|
|
1678
|
-
res.removeListener("error", destroyUpstreamResponse);
|
|
1679
|
-
req.socket.removeListener("close", destroyUpstreamResponse);
|
|
1680
|
-
};
|
|
1681
|
-
res.once("close", destroyUpstreamResponse);
|
|
1682
|
-
res.once("error", destroyUpstreamResponse);
|
|
1683
|
-
req.socket.once("close", destroyUpstreamResponse);
|
|
1684
|
-
proxyRes.once("end", removeDownstreamListeners);
|
|
1685
|
-
proxyRes.once("close", removeDownstreamListeners);
|
|
1686
|
-
const outHeaders: Record<string, string | string[]> = {};
|
|
1687
|
-
const contentType = firstHeader(proxyRes.headers["content-type"]);
|
|
1688
|
-
const shouldRewriteHtml =
|
|
1689
|
-
basePath.length > 0 && contentType?.toLowerCase().includes("text/html") === true;
|
|
1690
|
-
const shouldRewriteJavaScript =
|
|
1691
|
-
basePath.length > 0 &&
|
|
1692
|
-
(contentType?.toLowerCase().includes("javascript") === true ||
|
|
1693
|
-
upstreamPath.split("?", 1)[0]?.endsWith(".js") === true);
|
|
1694
|
-
const shouldRewriteBody = shouldRewriteHtml || shouldRewriteJavaScript;
|
|
1695
|
-
for (const [name, value] of Object.entries(proxyRes.headers)) {
|
|
1696
|
-
const lowerName = name.toLowerCase();
|
|
1697
|
-
if (RESPONSE_HOP_BY_HOP.has(lowerName)) continue;
|
|
1698
|
-
if (
|
|
1699
|
-
shouldRewriteBody &&
|
|
1700
|
-
(lowerName === "content-length" ||
|
|
1701
|
-
lowerName === "content-range" ||
|
|
1702
|
-
lowerName === "accept-ranges" ||
|
|
1703
|
-
lowerName === "etag" ||
|
|
1704
|
-
lowerName === "last-modified" ||
|
|
1705
|
-
lowerName === "content-md5" ||
|
|
1706
|
-
lowerName === "digest")
|
|
1707
|
-
)
|
|
1708
|
-
continue;
|
|
1709
|
-
if (value === undefined) continue;
|
|
1710
|
-
if (
|
|
1711
|
-
lowerName === "location" &&
|
|
1712
|
-
basePath.length > 0 &&
|
|
1713
|
-
typeof value === "string" &&
|
|
1714
|
-
value.startsWith("/") &&
|
|
1715
|
-
!value.startsWith("//")
|
|
1716
|
-
) {
|
|
1717
|
-
outHeaders[name] = rewriteRootRelativePublicPath(
|
|
1718
|
-
value,
|
|
1719
|
-
basePath,
|
|
1720
|
-
aliasRegistry.canonicalBasePath,
|
|
1721
|
-
);
|
|
1722
|
-
} else {
|
|
1723
|
-
outHeaders[name] = value;
|
|
1724
|
-
}
|
|
1725
|
-
}
|
|
1726
|
-
for (const [name, value] of Object.entries(BASE_SECURITY_HEADERS)) {
|
|
1727
|
-
outHeaders[name] = value;
|
|
1728
|
-
}
|
|
1729
|
-
outHeaders[AGENT_INSPECTOR_BACKEND_HEADER] = options.backendImplementation ?? "typescript";
|
|
1730
|
-
if (allowedUiOrigin !== null && isUiControlPath(upstreamPathname)) {
|
|
1731
|
-
outHeaders["access-control-allow-origin"] = allowedUiOrigin;
|
|
1732
|
-
outHeaders["access-control-expose-headers"] = "Content-Disposition";
|
|
1733
|
-
outHeaders["vary"] = appendVaryHeader(outHeaders["vary"], "Origin");
|
|
1734
|
-
}
|
|
1735
|
-
if (contentType?.toLowerCase().includes("text/html") === true) {
|
|
1736
|
-
outHeaders["content-security-policy"] = DOCUMENT_CONTENT_SECURITY_POLICY;
|
|
1737
|
-
}
|
|
1738
|
-
const responseStatus =
|
|
1739
|
-
shouldRewriteBody && proxyRes.statusCode === 206 ? 200 : (proxyRes.statusCode ?? 502);
|
|
1740
|
-
res.writeHead(responseStatus, outHeaders);
|
|
1741
|
-
if (shouldRewriteBody) {
|
|
1742
|
-
const chunks: Buffer[] = [];
|
|
1743
|
-
proxyRes.on("data", (chunk: unknown) => {
|
|
1744
|
-
chunks.push(toBuffer(chunk));
|
|
1745
|
-
});
|
|
1746
|
-
proxyRes.on("end", () => {
|
|
1747
|
-
const body = Buffer.concat(chunks).toString("utf8");
|
|
1748
|
-
res.write(
|
|
1749
|
-
shouldRewriteHtml
|
|
1750
|
-
? rewriteHtmlForBasePath(body, basePath, aliasRegistry.canonicalBasePath)
|
|
1751
|
-
: rewriteJavaScriptForBasePath(body, basePath, aliasRegistry.canonicalBasePath),
|
|
1752
|
-
);
|
|
1753
|
-
res.end();
|
|
1754
|
-
});
|
|
1755
|
-
proxyRes.on("error", () => {
|
|
1756
|
-
if (!res.writableEnded) res.destroy();
|
|
1757
|
-
});
|
|
1758
|
-
return;
|
|
1759
|
-
}
|
|
1760
|
-
proxyRes.pipe(res);
|
|
1761
|
-
},
|
|
1762
|
-
);
|
|
1763
|
-
const deadline = setTimeout(() => {
|
|
1764
|
-
failRequest(408, "Request body deadline exceeded");
|
|
1765
|
-
}, requestTimeoutMs);
|
|
1766
|
-
deadline.unref();
|
|
1767
|
-
|
|
1768
|
-
function clearDeadline(): void {
|
|
1769
|
-
clearTimeout(deadline);
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
function failRequest(status: number, error: string): void {
|
|
1773
|
-
if (terminal) return;
|
|
1774
|
-
terminal = true;
|
|
1775
|
-
clearDeadline();
|
|
1776
|
-
proxyReq.destroy();
|
|
1777
|
-
if (res.headersSent) {
|
|
1778
|
-
res.destroy();
|
|
1779
|
-
} else {
|
|
1780
|
-
res.writeHead(status, {
|
|
1781
|
-
"content-type": "application/json; charset=utf-8",
|
|
1782
|
-
"cache-control": "no-store",
|
|
1783
|
-
});
|
|
1784
|
-
res.end(JSON.stringify({ error }));
|
|
1785
|
-
}
|
|
1786
|
-
req.resume();
|
|
1787
|
-
}
|
|
1788
|
-
|
|
1789
|
-
proxyReq.on("error", (err) => {
|
|
1790
|
-
if (terminal) return;
|
|
1791
|
-
terminal = true;
|
|
1792
|
-
clearDeadline();
|
|
1793
|
-
if (!res.headersSent) {
|
|
1794
|
-
res.writeHead(502, { "content-type": "text/plain" });
|
|
1795
|
-
}
|
|
1796
|
-
res.end(`Upstream error: ${err.message}`);
|
|
1797
|
-
});
|
|
1798
|
-
proxyReq.on("drain", () => req.resume());
|
|
1799
|
-
res.once("close", () => {
|
|
1800
|
-
clearDeadline();
|
|
1801
|
-
proxyReq.destroy();
|
|
1802
|
-
});
|
|
1803
|
-
|
|
1804
|
-
let receivedBytes = 0;
|
|
1805
|
-
req.on("data", (chunk: unknown) => {
|
|
1806
|
-
if (terminal) return;
|
|
1807
|
-
const buffer = toBuffer(chunk);
|
|
1808
|
-
receivedBytes += buffer.byteLength;
|
|
1809
|
-
if (receivedBytes > maxRequestBytes) {
|
|
1810
|
-
failRequest(413, `Request body exceeds ${String(maxRequestBytes)} bytes`);
|
|
1811
|
-
return;
|
|
1812
|
-
}
|
|
1813
|
-
if (buffer.byteLength > 0 && !proxyReq.write(buffer)) req.pause();
|
|
1814
|
-
});
|
|
1815
|
-
req.on("end", () => {
|
|
1816
|
-
if (terminal) return;
|
|
1817
|
-
clearDeadline();
|
|
1818
|
-
proxyReq.end();
|
|
1819
|
-
});
|
|
1820
|
-
req.on("aborted", () => {
|
|
1821
|
-
failRequest(400, "Client aborted request body");
|
|
1822
|
-
});
|
|
1823
|
-
req.on("error", () => {
|
|
1824
|
-
failRequest(400, "Request body stream failed");
|
|
1825
|
-
});
|
|
1826
|
-
}
|
|
1827
|
-
|
|
1828
|
-
// `Readable` chunks in Node are typed as `any` (they can be Buffer | string
|
|
1829
|
-
// depending on the encoding setting). We narrow them via runtime checks.
|
|
1830
|
-
function toBuffer(chunk: unknown): Buffer {
|
|
1831
|
-
if (Buffer.isBuffer(chunk)) return chunk;
|
|
1832
|
-
if (typeof chunk === "string") return Buffer.from(chunk);
|
|
1833
|
-
// `for await` over a Node Readable always yields Buffer | string; this
|
|
1834
|
-
// branch is only reachable if a custom stream returns something else
|
|
1835
|
-
// (Uint8Array / ArrayBuffer / etc.). The Buffer constructor accepts an
|
|
1836
|
-
// ArrayBuffer directly; we attempt that first, then fall back to a
|
|
1837
|
-
// best-effort empty buffer so we never throw on an unexpected chunk.
|
|
1838
|
-
if (chunk instanceof ArrayBuffer) return Buffer.from(chunk);
|
|
1839
|
-
if (chunk instanceof Uint8Array)
|
|
1840
|
-
return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
1841
|
-
return Buffer.alloc(0);
|
|
1842
|
-
}
|