mcpfed

package
v2.8.17 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mcpfed implements the pure-CPU Outbound MCP Credential Vault (HKDF-SHA256 + AES-256-GCM), OAuth 2.1 PKCE metadata/state hygiene, Federated MCP untrusted output sanitizer, JSON Schema allowlist rebuilder, Streamable HTTP SSE JSON-RPC parser, and Dual-Source MCP Registry fusion engine.

WASM Dependency Invariant:

  • Zero imports of net/http, crypto/tls, crypto/x509, or host networking packages so cmd/edgefetch-wasm compiles cleanly under GOOS=wasip1 GOARCH=wasm with minimal binary footprint.
  • Cryptographic operations maintain 100% byte-for-byte wire compatibility with WebCrypto envelopes (v2 row-bound 5-field AAD, v2 origin-bound 2-field AAD, legacy v1 length-prefixed & v2.7.0 fallback, and pkce2 OAuth PKCE state blobs).

Index

Constants

View Source
const (
	// MaxRemoteMCPResponseBytes is the 4 MiB hard ceiling on downstream MCP responses.
	MaxRemoteMCPResponseBytes = 4 * 1024 * 1024
	// MaxMCPContentBlocks caps content[] blocks per downstream MCP response (H3).
	MaxMCPContentBlocks = 64
	// MaxMCPBlockTextChars caps raw per-block text BEFORE sanitizing (64 KiB, H3).
	MaxMCPBlockTextChars = 64 * 1024
	// MaxMCPLinkLabelChars caps Markdown link label length in linear dangerous-link stripping.
	MaxMCPLinkLabelChars = 512
	// MaxMCPLinkTargetChars caps Markdown link target length in linear dangerous-link stripping.
	MaxMCPLinkTargetChars = 2048
	// MaxMCPToolSchemaBytes is the 16 KiB ceiling on individual and total tools/list schemas (H3).
	MaxMCPToolSchemaBytes = 16 * 1024

	// MaxStructuredSanitizeDepth caps recursion depth on structuredContent / connector JSON trees.
	MaxStructuredSanitizeDepth = 12
	// MaxStructuredContainerEntries caps object keys / array items per container.
	MaxStructuredContainerEntries = 256
	// MaxStructuredNodeBudget caps total visited nodes across a structured connector JSON tree.
	MaxStructuredNodeBudget = 2048
	// MaxStructuredStringChars caps string leaf length (16 KiB).
	MaxStructuredStringChars = 16 * 1024

	// MaxMCPRPCErrorDataBytes caps JSON-RPC error.data serialized size (4 KiB).
	MaxMCPRPCErrorDataBytes = 4 * 1024
	// MaxMCPRPCErrorDataDepth caps JSON-RPC error.data nesting depth.
	MaxMCPRPCErrorDataDepth = 4
	// MaxMCPRPCErrorDataEntries caps JSON-RPC error.data entries per container.
	MaxMCPRPCErrorDataEntries = 16
	// MaxMCPRPCErrorDataNodes caps JSON-RPC error.data visited node count.
	MaxMCPRPCErrorDataNodes = 64
	// MaxMCPRPCErrorDataStringChars caps JSON-RPC error.data string leaf length.
	MaxMCPRPCErrorDataStringChars = 512
)
View Source
const (
	// OfficialMCPRegistryURL is the upstream Official Model Context Protocol Registry v0 endpoint.
	OfficialMCPRegistryURL = "https://registry.modelcontextprotocol.io/v0/servers"
	// GlamaMCPRegistryURL is the upstream Glama MCP Directory v1 endpoint.
	GlamaMCPRegistryURL = "https://glama.ai/api/mcp/v1/servers"
)
View Source
const (
	// MinVaultMasterKeyLength matches MIN_TOKEN_LENGTH (24) in hub/src/auth.ts.
	MinVaultMasterKeyLength = 24

	// VaultCredentialsPurposeV2 is the HKDF info purpose label for v2 user_mcp_servers credentials.
	VaultCredentialsPurposeV2 = "user_mcp_servers:credentials:v2"

	// VaultPKCEStatePurposeV2 is the HKDF info purpose label for pkce2 mcp_oauth_states blobs.
	VaultPKCEStatePurposeV2 = "mcp_oauth_states:pkce:v2"
)

Variables

This section is empty.

Functions

func BuildOAuthBindMACInputs

func BuildOAuthBindMACInputs(vaultMasterKey, userID, state, sessionCSRF string) (macKey, macMessage string)

BuildOAuthBindMACInputs returns the canonical HMAC-SHA256 key and message strings for MCP OAuth bind cookies.

func BuildPerUserOriginHKDFInfo

func BuildPerUserOriginHKDFInfo(userID, remoteOrigin, purpose string) string

BuildPerUserOriginHKDFInfo returns the length-prefixed HKDF-SHA256 info string for a user/origin/purpose tuple.

func ComputeMCPOAuthBindHMAC

func ComputeMCPOAuthBindHMAC(vaultMasterKey, userID, state, sessionCSRF string) string

ComputeMCPOAuthBindHMAC computes the HMAC-SHA256 bind cookie signature over userId|state|sessionCsrf.

func ExtractMarkdownFromQueryMCPBody

func ExtractMarkdownFromQueryMCPBody(rawBody json.RawMessage) string

ExtractMarkdownFromQueryMCPBody extracts joined Markdown/text from a query_mcp response body.

func ExtractRegistrableDomain

func ExtractRegistrableDomain(hostname string) string

ExtractRegistrableDomain returns the eTLD+1 registrable domain (or "" when unregistrable / bare suffix / IP).

func FormatFenceSafeUntrustedMCPEnvelope

func FormatFenceSafeUntrustedMCPEnvelope(tag string, attrs OrderedObject, content string, maxChars int) string

FormatFenceSafeUntrustedMCPEnvelope wraps untrusted text in a fence-safe + boundary-tag-safe XML envelope.

func InferAssociatedDomains

func InferAssociatedDomains() []string

InferAssociatedDomains enforces Security Invariant H1: never infer foreign domains from untrusted manifests.

func IsCachedMCPToolPermitted

func IsCachedMCPToolPermitted(serverSlug string, tool CachedMCPToolSchema, allowedSet map[string]bool) bool

IsCachedMCPToolPermitted enforces S6 readOnlyHint/destructiveHint gating unless explicitly allowlisted as "<slug>/<tool>".

func IsJSONDepthWithinLimit

func IsJSONDepthWithinLimit(rawJSON string, maxDepth int) bool

IsJSONDepthWithinLimit verifies in O(N) time that bracket/brace nesting never exceeds maxDepth.

func IsSafeMCPIdentifier

func IsSafeMCPIdentifier(raw string) bool

IsSafeMCPIdentifier validates tool/property names against prototype pollution, "__", and prompt-injection verbs.

func IsSafePublicHostname

func IsSafePublicHostname(rawHost, selfHost string) bool

IsSafePublicHostname validates that rawHost is a public DNS name (no IP literals, loopback/LAN/metadata, rebinding, or self-hub).

func IsSharedHostingHostname

func IsSharedHostingHostname(hostname string) bool

IsSharedHostingHostname delegates to extract.HasPrivateSharedHostingSuffix for PSL PRIVATE DOMAINS isolation.

func IsValidMCPConnectorSlug

func IsValidMCPConnectorSlug(raw string) bool

IsValidMCPConnectorSlug validates lowercase connector slugs (1..48 chars, no "__").

func MarshalUnescapedJSON

func MarshalUnescapedJSON(v any) ([]byte, error)

MarshalUnescapedJSON marshals v to compact JSON without escaping <, >, or &.

func MeasureOrderedJSONSizeCapped

func MeasureOrderedJSONSizeCapped(rawValue any, maxBytes int) int

MeasureOrderedJSONSizeCapped estimates serialized JSON size in UTF-16 code units, aborting as soon as acc > maxBytes.

func NeutralizeUntrustedMCPBoundaryTags

func NeutralizeUntrustedMCPBoundaryTags(input string) string

NeutralizeUntrustedMCPBoundaryTags escapes <untrusted_... and </untrusted_... tags inside untrusted text.

func NormalizeConfirmedAuthOrigin

func NormalizeConfirmedAuthOrigin(raw, selfHost string) (origin string, ok bool, reason string)

NormalizeConfirmedAuthOrigin validates an optional https:// origin without path or query.

func NormalizeMCPConnectorSlug

func NormalizeMCPConnectorSlug(rawName string) string

NormalizeMCPConnectorSlug derives a safe lowercase connector slug from an arbitrary server name.

func ParseAllowedMCPTools

func ParseAllowedMCPTools(raw json.RawMessage) (allowed []string, ok bool, errCode string, message string)

ParseAllowedMCPTools validates exact "<slug>/<tool>" allowlist entries (<= 128 items, no wildcards or "__").

func ParseOrderedJSON

func ParseOrderedJSON(data []byte, maxDepth int) (any, error)

ParseOrderedJSON parses arbitrary JSON into OrderedObject, []any, string, json.Number, bool, or nil, enforcing maxDepth and converting bridged JS sentinels into SpecialSentinel values.

func PreparePKCEStateSeal

func PreparePKCEStateSeal(userID, remoteOrigin string, blob OrderedObject) (hkdfInfo, aad, plaintext string, err error)

PreparePKCEStateSeal builds the canonical HKDF info, AAD, and JSON plaintext for pkce2 state blobs.

func PreparePKCEStateUnseal

func PreparePKCEStateUnseal(userID, remoteOrigin, ciphertext string) (hkdfInfo, aad, saltB64, ivB64, ctB64 string, salt, iv, ct []byte, ok bool)

PreparePKCEStateUnseal validates a pkce2 ciphertext header and returns HKDF info, AAD, and decoded byte slices.

func RandomBase64URL

func RandomBase64URL(byteLen int) (string, error)

RandomBase64URL generates byteLen CSPRNG bytes encoded as unpadded base64url.

func RedactVaultSecretsFromText

func RedactVaultSecretsFromText(raw string, secret *VaultSecretPayload) string

RedactVaultSecretsFromText scrubs Bearer tokens and decrypted vault header/OAuth secrets from untrusted error/tool text.

func ResolveCallerUserID

func ResolveCallerUserID(userID, principal string) string

ResolveCallerUserID resolves the isolated tenant user_id per the Pillar 1 shared interface contract.

func SHA256Base64URL

func SHA256Base64URL(input string) string

SHA256Base64URL computes unpadded base64url(SHA-256(UTF8(input))) for RFC 7636 S256 PKCE challenges and state hashes.

func SanitizeMCPMarkdownOutput

func SanitizeMCPMarkdownOutput(rawMarkdown, baseURL string, maxChars int) string

SanitizeMCPMarkdownOutput sanitizes untrusted Markdown/HTML returned by a downstream MCP server.

func SanitizeManifestString

func SanitizeManifestString(raw string, maxLen int) string

SanitizeManifestString strips smuggling runes and redacts prompt-injection directives in third-party registry manifests.

func SanitizeTargetURLForMCPForwarding

func SanitizeTargetURLForMCPForwarding(rawURL, selfHost string) (safeForwardURL string, normalizedTarget string, ok bool)

SanitizeTargetURLForMCPForwarding validates targetURL as safe public HTTPS and strips credentials, hash, and sensitive query params.

func SealPKCEStateBlob

func SealPKCEStateBlob(vaultMasterKey, userID, remoteOrigin string, blob OrderedObject) (string, error)

SealPKCEStateBlob encrypts a downstream OAuth 2.1 PKCE verifier blob using the pkce2 envelope.

func SlugifyMCPServerName

func SlugifyMCPServerName(rawName string) string

SlugifyMCPServerName converts a registry server name (including reverse-DNS / @scope prefixes) into a safe slug.

func StripMCPSmugglingChars

func StripMCPSmugglingChars(s string) string

StripMCPSmugglingChars strips invisible Unicode Tag/Variation Selector smuggling, Bidi controls, zero-width characters, ANSI CSI sequences, and raw ASCII C0/DEL control bytes.

func ValidateConnectorDomains

func ValidateConnectorDomains(rawDomains json.RawMessage, remoteOrigin string, allowUnrelatedDomains bool) ([]string, bool, string)

ValidateConnectorDomains validates operator-supplied connector domains against PSL suffixes, shared-hosting sibling tenants, and origin matching.

func ValidateVaultMasterKey

func ValidateVaultMasterKey(vaultMasterKey string) (clean string, ok bool, message string)

ValidateVaultMasterKey enforces VAULT_MASTER_KEY >= 24 trimmed UTF-16 characters.

func VerifyMCPOAuthBindHMAC

func VerifyMCPOAuthBindHMAC(presented, vaultMasterKey, userID, state, sessionCSRF string) bool

VerifyMCPOAuthBindHMAC compares presented cookie HMAC in constant time.

Types

type CachedMCPToolSchema

type CachedMCPToolSchema struct {
	Name            string        `json:"name"`
	Title           string        `json:"title,omitempty"`
	Description     string        `json:"description,omitempty"`
	InputSchema     OrderedObject `json:"inputSchema"`
	ReadOnlyHint    *bool         `json:"readOnlyHint,omitempty"`
	DestructiveHint *bool         `json:"destructiveHint,omitempty"`
}

CachedMCPToolSchema describes a sanitized tool cached on a connected MCP server row.

func FilterSafeCachedMCPTools

func FilterSafeCachedMCPTools(rawTools json.RawMessage) []CachedMCPToolSchema

FilterSafeCachedMCPTools filters persisted cached_tools_json rows (<= 64 tools, safe names & schema keys).

type DiscoveredRemoteOAuthMetadata

type DiscoveredRemoteOAuthMetadata struct {
	Supported                      bool     `json:"supported"`
	RequiresAuthOriginConfirmation bool     `json:"requiresAuthOriginConfirmation,omitempty"`
	Error                          string   `json:"error,omitempty"`
	AuthOrigin                     string   `json:"authOrigin,omitempty"`
	ConnectorOrigin                string   `json:"connectorOrigin,omitempty"`
	Resource                       string   `json:"resource,omitempty"`
	Issuer                         string   `json:"issuer,omitempty"`
	AuthorizationEndpoint          string   `json:"authorizationEndpoint,omitempty"`
	TokenEndpoint                  string   `json:"tokenEndpoint,omitempty"`
	RegistrationEndpoint           string   `json:"registrationEndpoint,omitempty"`
	ScopesSupported                []string `json:"scopesSupported,omitempty"`
	CodeChallengeMethods           []string `json:"codeChallengeMethods,omitempty"`
}

DiscoveredRemoteOAuthMetadata describes validated RFC 9728 / RFC 8414 OAuth 2.1 endpoints.

func ValidateOAuthAuthorizationServer

func ValidateOAuthAuthorizationServer(
	asRaw json.RawMessage,
	expectedIssuerURL, allowedAuthOrigin, connectorOrigin, resourceURI string,
	prScopes []string,
	selfHost string,
) (meta DiscoveredRemoteOAuthMetadata, abort bool)

ValidateOAuthAuthorizationServer enforces RFC 8414 issuer & endpoint same-origin pinning and S256 PKCE support.

type MCPEnvVarSpec

type MCPEnvVarSpec struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	IsRequired  bool   `json:"isRequired"`
	IsSecret    bool   `json:"isSecret"`
	Default     string `json:"default,omitempty"`
}

MCPEnvVarSpec describes an environment variable advertised by an MCP package manifest.

type MCPPackageSpec

type MCPPackageSpec struct {
	RegistryType         string          `json:"registryType,omitempty"`
	Identifier           string          `json:"identifier"`
	Version              string          `json:"version,omitempty"`
	Transport            string          `json:"transport,omitempty"`
	EnvironmentVariables []MCPEnvVarSpec `json:"environmentVariables"`
}

MCPPackageSpec describes a local package manifest entry for an MCP server.

type MCPRemoteEndpointSpec

type MCPRemoteEndpointSpec struct {
	Type    string                `json:"type"`
	URL     string                `json:"url"`
	Headers []MCPRemoteHeaderSpec `json:"headers"`
}

MCPRemoteEndpointSpec describes a validated public HTTPS remote endpoint for an MCP server.

type MCPRemoteHeaderSpec

type MCPRemoteHeaderSpec struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	IsRequired  bool   `json:"isRequired"`
	IsSecret    bool   `json:"isSecret"`
	Default     string `json:"default,omitempty"`
	Placeholder string `json:"placeholder,omitempty"`
}

MCPRemoteHeaderSpec describes a manifest header advertised by a remote MCP server.

type MaskedAuthSummary

type MaskedAuthSummary struct {
	AuthMode        string   `json:"authMode"`
	HeaderNames     []string `json:"headerNames"`
	MaskedBadge     string   `json:"maskedBadge"`
	HasRefreshToken *bool    `json:"hasRefreshToken,omitempty"`
	TokenExpiresAt  *int64   `json:"tokenExpiresAt,omitempty"`
}

MaskedAuthSummary is the write-only public badge describing connector authentication without secrets.

func BuildMaskedAuthSummary

func BuildMaskedAuthSummary(payload VaultSecretPayload) MaskedAuthSummary

BuildMaskedAuthSummary builds a public MaskedAuthSummary without exposing secret values.

type MatchedConnectedMCP

type MatchedConnectedMCP struct {
	Server         PublicMCPServerSummary `json:"server"`
	MatchedDomains []string               `json:"matchedDomains"`
	Score          int                    `json:"score"`
}

MatchedConnectedMCP ranks an enabled connected MCP server against target URLs and query text.

func MatchConnectedMCPsForContext

func MatchConnectedMCPsForContext(servers []StoredMCPServerRow, query string, urls []string) []MatchedConnectedMCP

MatchConnectedMCPsForContext ranks a user's enabled connected MCP servers against URLs and query text.

type NormalizedMCPRegistryEntry

type NormalizedMCPRegistryEntry struct {
	ID            string                  `json:"id"`
	Slug          string                  `json:"slug"`
	Name          string                  `json:"name"`
	Title         string                  `json:"title"`
	Description   string                  `json:"description"`
	Version       string                  `json:"version,omitempty"`
	WebsiteURL    string                  `json:"websiteUrl,omitempty"`
	RepositoryURL string                  `json:"repositoryUrl,omitempty"`
	Sources       []string                `json:"sources"`
	HasRemote     bool                    `json:"hasRemote"`
	Remotes       []MCPRemoteEndpointSpec `json:"remotes"`
	Packages      []MCPPackageSpec        `json:"packages"`
	Domains       []string                `json:"domains"`
}

NormalizedMCPRegistryEntry is a normalized, sanitized, deduplicated MCP server listing.

func FuseRegistryEntries

func FuseRegistryEntries(officialEntries, glamaEntries []NormalizedMCPRegistryEntry) []NormalizedMCPRegistryEntry

FuseRegistryEntries deduplicates, merges, and ranks Official MCP Registry and Glama entries.

func ParseGlamaRegistryPayload

func ParseGlamaRegistryPayload(rawJSON json.RawMessage, selfHost string) ([]NormalizedMCPRegistryEntry, error)

ParseGlamaRegistryPayload normalizes and sanitizes entries from glama.ai/api/mcp/v1/servers.

func ParseOfficialRegistryPayload

func ParseOfficialRegistryPayload(rawJSON json.RawMessage, selfHost string) ([]NormalizedMCPRegistryEntry, error)

ParseOfficialRegistryPayload normalizes and sanitizes entries from registry.modelcontextprotocol.io.

type OAuthPRMCheckResult

type OAuthPRMCheckResult struct {
	Valid                          bool     `json:"valid"`
	RequiresAuthOriginConfirmation bool     `json:"requiresAuthOriginConfirmation,omitempty"`
	Error                          string   `json:"error,omitempty"`
	AuthOrigin                     string   `json:"authOrigin,omitempty"`
	ConnectorOrigin                string   `json:"connectorOrigin,omitempty"`
	ResourceURI                    string   `json:"resourceUri,omitempty"`
	AuthIssuerURL                  string   `json:"authIssuerUrl,omitempty"`
	AllowedAuthOrigin              string   `json:"allowedAuthOrigin,omitempty"`
	ASCandidates                   []string `json:"asCandidates,omitempty"`
	ScopesSupported                []string `json:"scopesSupported,omitempty"`
}

OAuthPRMCheckResult is the result of validating an HTTP 200 RFC 9728 Protected Resource Metadata JSON payload.

func ValidateOAuthProtectedResource

func ValidateOAuthProtectedResource(prRaw json.RawMessage, remoteURL, confirmedAuthOrigin, selfHost string) OAuthPRMCheckResult

ValidateOAuthProtectedResource enforces RFC 9728 §3.3 resource pinning, shared-hosting sibling tenant isolation, and cross-origin authorization server confirmation.

type OAuthProbePlan

type OAuthProbePlan struct {
	OK                 bool     `json:"ok"`
	Reason             string   `json:"reason,omitempty"`
	NormalizedRemote   string   `json:"normalizedRemote,omitempty"`
	ConnectorOrigin    string   `json:"connectorOrigin,omitempty"`
	ConfirmedOrigin    string   `json:"confirmedOrigin,omitempty"`
	PRCandidates       []string `json:"prCandidates,omitempty"`
	FallbackCandidates []string `json:"fallbackCandidates,omitempty"`
}

OAuthProbePlan holds candidate RFC 9728 Protected Resource Metadata URLs for a remote MCP endpoint.

func PrepareOAuthProbe

func PrepareOAuthProbe(remoteURL, confirmedAuthOrigin, selfHost string) OAuthProbePlan

PrepareOAuthProbe validates remoteURL + confirmedAuthOrigin and computes RFC 9728 / RFC 8414 candidate URLs.

type OAuthTokenEndpointCheck

type OAuthTokenEndpointCheck struct {
	OK            bool   `json:"ok"`
	NormalizedURL string `json:"normalizedUrl,omitempty"`
	Status        int    `json:"status,omitempty"`
	Error         string `json:"error,omitempty"`
	Message       string `json:"message,omitempty"`
}

OAuthTokenEndpointCheck holds the result of validating an OAuth token_endpoint before code exchange or refresh.

func ValidateOAuthTokenEndpoint

func ValidateOAuthTokenEndpoint(tokenEndpoint, expectedIssuer, confirmedAuthOrigin, remoteOrigin, selfHost string) OAuthTokenEndpointCheck

ValidateOAuthTokenEndpoint validates tokenEndpoint + expectedIssuer against allowedAuthOrigin and SSRF rules.

type OrderedEntry

type OrderedEntry struct {
	Key   string
	Value any
}

OrderedEntry represents a single key-value pair in a JSON object preserving wire order.

type OrderedObject

type OrderedObject []OrderedEntry

OrderedObject is an insertion-order-preserving JSON object slice.

func BuildPKCEAuthorizationInit

func BuildPKCEAuthorizationInit(
	authorizationEndpoint, tokenEndpoint, clientID, clientSecret, redirectURI, scope string,
	scopesSupported []string,
	resource, confirmedAuthOrigin, issuer, codeVerifier, codeChallenge, state string,
) (blob OrderedObject, authorizationURL string, err error)

BuildPKCEAuthorizationInit constructs the PKCE OrderedObject state blob and RFC 7636 S256 authorization URL.

func BuildPinnedOutboundHeaders

func BuildPinnedOutboundHeaders(secret *VaultSecretPayload, targetOrigin, sessionID string) (OrderedObject, bool, string)

BuildPinnedOutboundHeaders verifies secret.pinnedOrigin === targetOrigin and constructs outbound JSON-RPC headers.

func ParseRemoteJSONRPCBody

func ParseRemoteJSONRPCBody(bodyText, contentType string, expected RPCID) (rpc OrderedObject, depthExceeded bool, found bool)

ParseRemoteJSONRPCBody parses either application/json or text/event-stream JSON-RPC responses matching expected.

func ParseSSEJSONRPCResponse

func ParseSSEJSONRPCResponse(sseText string, expected RPCID) (OrderedObject, bool)

ParseSSEJSONRPCResponse parses a Streamable HTTP text/event-stream SSE payload and extracts the JSON-RPC 2.0 response matching expected.

func RebuildSafeMCPInputSchema

func RebuildSafeMCPInputSchema(rawNode any, depth int) (OrderedObject, bool)

RebuildSafeMCPInputSchema rebuilds a downstream MCP tool inputSchema via a strict recursive allowlist walker (H3).

func SanitizeCallToolRPCResponse

func SanitizeCallToolRPCResponse(
	rpcObj OrderedObject,
	serverSlug, serverName, remoteOrigin, toolName, sanitizeBaseURL, selfHost string,
	tokenRefreshed bool,
	activeSecret *VaultSecretPayload,
) (status int, body OrderedObject)

SanitizeCallToolRPCResponse sanitizes a complete downstream JSON-RPC tools/call response (result or error) in a single Go pass, enforcing H3/M10 block, byte, depth, and secret-redaction budgets.

func SanitizeSecretHeadersInput

func SanitizeSecretHeadersInput(bearerToken *string, rawHeaders json.RawMessage, hasHeaders bool) (OrderedObject, bool, string)

SanitizeSecretHeadersInput validates custom secret headers and optional bearerToken against smuggling/hop-by-hop headers.

func UnsealPKCEStateBlob

func UnsealPKCEStateBlob(vaultMasterKey, userID, remoteOrigin, ciphertext string) (OrderedObject, bool)

UnsealPKCEStateBlob authenticates and decrypts a pkce2 OAuth state blob.

func VerifyPKCEStatePlaintext

func VerifyPKCEStatePlaintext(plain []byte) (OrderedObject, bool)

VerifyPKCEStatePlaintext validates decrypted pkce2 state JSON.

func (OrderedObject) Clone

func (o OrderedObject) Clone() OrderedObject

Clone shallow-copies the OrderedObject slice.

func (*OrderedObject) Delete

func (o *OrderedObject) Delete(key string)

Delete removes key if present.

func (OrderedObject) Get

func (o OrderedObject) Get(key string) (any, bool)

Get returns the value for key if present.

func (OrderedObject) GetArray

func (o OrderedObject) GetArray(key string) ([]any, bool)

GetArray returns a nested []any if present.

func (OrderedObject) GetBool

func (o OrderedObject) GetBool(key string) (bool, bool)

GetBool returns a boolean field if present and typed as bool.

func (OrderedObject) GetObject

func (o OrderedObject) GetObject(key string) (OrderedObject, bool)

GetObject returns a nested OrderedObject if present.

func (OrderedObject) GetString

func (o OrderedObject) GetString(key string) (string, bool)

GetString returns a string field if present and typed as string.

func (OrderedObject) MarshalJSON

func (o OrderedObject) MarshalJSON() ([]byte, error)

MarshalJSON serializes OrderedObject as a JSON object without HTML escaping.

func (*OrderedObject) Set

func (o *OrderedObject) Set(key string, val any)

Set inserts or updates key in place while preserving initial insertion order.

func (*OrderedObject) UnmarshalJSON

func (o *OrderedObject) UnmarshalJSON(data []byte) error

UnmarshalJSON parses a JSON object into OrderedObject preserving wire order.

type PreparedVaultSeal

type PreparedVaultSeal struct {
	OK              bool   `json:"ok"`
	CleanKey        string `json:"cleanKey,omitempty"`
	HKDFInfo        string `json:"hkdfInfo,omitempty"`
	AAD             string `json:"aad,omitempty"`
	Plaintext       string `json:"plaintext,omitempty"`
	EnvelopeVersion string `json:"envelopeVersion,omitempty"`
	SecretVersion   int    `json:"secretVersion,omitempty"`
	Status          int    `json:"status,omitempty"`
	Error           string `json:"error,omitempty"`
	Message         string `json:"message,omitempty"`
}

PreparedVaultSeal holds Go-computed HKDF info, AAD, and canonical JSON plaintext for AEAD sealing.

func PrepareSealVaultEnvelope

func PrepareSealVaultEnvelope(params SealVaultParams) PreparedVaultSeal

PrepareSealVaultEnvelope validates parameters and constructs the canonical HKDF info, AAD, and JSON plaintext.

type PreparedVaultUnseal

type PreparedVaultUnseal struct {
	OK        bool                 `json:"ok"`
	CleanKey  string               `json:"cleanKey,omitempty"`
	SaltB64   string               `json:"saltB64,omitempty"`
	IVB64     string               `json:"ivB64,omitempty"`
	CTB64     string               `json:"ctB64,omitempty"`
	SaltBytes []byte               `json:"-"`
	IVBytes   []byte               `json:"-"`
	CTBytes   []byte               `json:"-"`
	Attempts  []VaultUnsealAttempt `json:"attempts,omitempty"`
	Error     string               `json:"error,omitempty"`
	Message   string               `json:"message,omitempty"`
}

PreparedVaultUnseal holds validated envelope components and ordered AEAD attempts.

func PrepareUnsealVaultEnvelope

func PrepareUnsealVaultEnvelope(params UnsealVaultParams) PreparedVaultUnseal

PrepareUnsealVaultEnvelope validates envelope headers, P6/M8 downgrade rules, and builds ordered AEAD attempts.

type PublicMCPServerSummary

type PublicMCPServerSummary struct {
	ID              string                `json:"id"`
	UserID          string                `json:"userId"`
	Slug            string                `json:"slug"`
	Name            string                `json:"name"`
	RemoteURL       string                `json:"remoteUrl"`
	RemoteOrigin    string                `json:"remoteOrigin"`
	Transport       string                `json:"transport"`
	AuthType        string                `json:"authType"`
	AuthSummary     MaskedAuthSummary     `json:"authSummary"`
	Domains         []string              `json:"domains"`
	AutoRouteScrape bool                  `json:"autoRouteScrape"`
	Tools           []CachedMCPToolSchema `json:"tools"`
	ToolCount       int                   `json:"toolCount"`
	Enabled         bool                  `json:"enabled"`
	LastVerifiedAt  *int64                `json:"lastVerifiedAt"`
	LastError       *string               `json:"lastError"`
	CreatedAt       int64                 `json:"createdAt"`
	UpdatedAt       int64                 `json:"updatedAt"`
}

PublicMCPServerSummary is the secret-free projection returned to /admin and query_mcp(list_connected).

func ToPublicMCPServerSummary

func ToPublicMCPServerSummary(row StoredMCPServerRow) PublicMCPServerSummary

ToPublicMCPServerSummary strips ciphertext and secretVersion for safe /admin and query_mcp exposure.

type RPCID

type RPCID struct {
	Present bool
	IsNum   bool
	Str     string
	Num     float64
}

RPCID represents an optional string or numeric JSON-RPC 2.0 request ID.

func (*RPCID) UnmarshalJSON

func (id *RPCID) UnmarshalJSON(data []byte) error

UnmarshalJSON parses an optional string or number JSON-RPC ID.

type SafeHTTPSURLResult

type SafeHTTPSURLResult struct {
	OK         bool   `json:"ok"`
	Normalized string `json:"normalized,omitempty"`
	Origin     string `json:"origin,omitempty"`
	Hostname   string `json:"hostname,omitempty"`
	Pathname   string `json:"pathname,omitempty"`
	Search     string `json:"search,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

SafeHTTPSURLResult holds the outcome of IsSafePublicHTTPSURL.

func IsSafePublicHTTPSURL

func IsSafePublicHTTPSURL(rawURL, selfHost string) SafeHTTPSURLResult

IsSafePublicHTTPSURL validates that rawURL is a safe public https:// URL on port 443 with no credentials or fragments.

type SanitizedConnectorStructuredResult

type SanitizedConnectorStructuredResult struct {
	Value          any      `json:"value"`
	Sanitized      bool     `json:"sanitized"`
	FullySanitized bool     `json:"fullySanitized"`
	Truncated      bool     `json:"truncated"`
	Detected       bool     `json:"detected"`
	Scrubbed       bool     `json:"scrubbed"`
	Triggers       []string `json:"triggers"`
}

SanitizedConnectorStructuredResult reports recursive structured JSON sanitization results.

func SanitizeConnectorStructuredValue

func SanitizeConnectorStructuredValue(rawValue any, opts StructuredSanitizeOptions) SanitizedConnectorStructuredResult

SanitizeConnectorStructuredValue recursively sanitizes arbitrary connector JSON trees under strict depth/node/entry/char caps.

type SanitizedConnectorTextResult

type SanitizedConnectorTextResult struct {
	Text           string   `json:"text"`
	Sanitized      bool     `json:"sanitized"`
	FullySanitized bool     `json:"fullySanitized"`
	Truncated      bool     `json:"truncated"`
	Detected       bool     `json:"detected"`
	Scrubbed       bool     `json:"scrubbed"`
	Triggers       []string `json:"triggers"`
}

SanitizedConnectorTextResult reports full Markdown + link + injection sanitization on a string.

func SanitizeConnectorText

func SanitizeConnectorText(
	raw string,
	maxChars int,
	baseURL string,
	applyRedact bool,
	redactSecret *VaultSecretPayload,
) SanitizedConnectorTextResult

SanitizeConnectorText runs secret redaction -> prompt-injection scrubbing -> Markdown/HTML/link sanitization + post-verify.

type SanitizedTextResult

type SanitizedTextResult struct {
	Text     string   `json:"text"`
	Detected bool     `json:"detected"`
	Scrubbed bool     `json:"scrubbed"`
	Triggers []string `json:"triggers"`
}

SanitizedTextResult reports prompt-injection scrubbing results from SanitizeRemoteMCPText.

func SanitizeRemoteMCPText

func SanitizeRemoteMCPText(raw string, maxChars int) SanitizedTextResult

SanitizeRemoteMCPText strips smuggling chars and scrubs indirect prompt-injection instructions.

type SanitizedToolDefsResult

type SanitizedToolDefsResult struct {
	Tools                   []CachedMCPToolSchema `json:"tools"`
	PromptInjectionScrubbed bool                  `json:"promptInjectionScrubbed"`
	OversizedRejected       bool                  `json:"oversizedRejected,omitempty"`
}

SanitizedToolDefsResult holds sanitized downstream MCP tools/list schemas.

func SanitizeRemoteMCPToolDefs

func SanitizeRemoteMCPToolDefs(rawToolsJSON []byte) SanitizedToolDefsResult

SanitizeRemoteMCPToolDefs validates and sanitizes a downstream tools/list array under a 16 KiB raw schema ceiling (H3).

type ScrapeMCPPlan

type ScrapeMCPPlan struct {
	Matched          bool          `json:"matched"`
	NormalizedTarget string        `json:"normalizedTarget,omitempty"`
	SafeForwardURL   string        `json:"safeForwardUrl,omitempty"`
	ServerSlug       string        `json:"serverSlug,omitempty"`
	ToolName         string        `json:"toolName,omitempty"`
	ToolArguments    OrderedObject `json:"toolArguments,omitempty"`
}

ScrapeMCPPlan describes the selected MCP connector & read-only URL tool for tryScrapeViaConnectedMcp.

func SelectScrapeMCPCandidate

func SelectScrapeMCPCandidate(
	allRows []StoredMCPServerRow,
	targetURL string,
	query string,
	preferMCP bool,
	hasAllowedServerIDs bool,
	allowedServerIDs map[string]bool,
	allowedTools map[string]bool,
	requireExplicitReadOnlyHint bool,
	selfHost string,
) ScrapeMCPPlan

SelectScrapeMCPCandidate evaluates H1/S6 opt-in scrape routing rules and selects a permitted read-oriented URL tool.

type SealVaultParams

type SealVaultParams struct {
	VaultMasterKey string
	UserID         string
	RemoteOrigin   string
	ID             *string
	ServerID       *string
	Slug           *string
	AuthType       *string
	Payload        OrderedObject
}

SealVaultParams configures SealVaultCredentials / PrepareSealVaultEnvelope.

type SealVaultResult

type SealVaultResult struct {
	OK            bool   `json:"ok"`
	Ciphertext    string `json:"ciphertext,omitempty"`
	SecretVersion int    `json:"secretVersion,omitempty"`
	Status        int    `json:"status,omitempty"`
	Error         string `json:"error,omitempty"`
	Message       string `json:"message,omitempty"`
}

SealVaultResult is the outcome of SealVaultCredentials.

func SealVaultCredentials

func SealVaultCredentials(params SealVaultParams) SealVaultResult

SealVaultCredentials encrypts a VaultSecretPayload with HKDF-SHA256 + AES-256-GCM (v2 envelope).

type SpecialSentinel

type SpecialSentinel struct {
	Kind string
	Raw  string
}

SpecialSentinel represents non-JSON JS values (functions/symbols, BigInt, circular refs) bridged over JSON.

type StoredMCPServerRow

type StoredMCPServerRow struct {
	ID                   string                `json:"id"`
	UserID               string                `json:"userId"`
	Slug                 string                `json:"slug"`
	Name                 string                `json:"name"`
	RemoteURL            string                `json:"remoteUrl"`
	RemoteOrigin         string                `json:"remoteOrigin"`
	Transport            string                `json:"transport"`
	AuthType             string                `json:"authType"`
	EncryptedCredentials *string               `json:"encryptedCredentials"`
	SecretVersion        *int                  `json:"secretVersion,omitempty"`
	AuthSummary          MaskedAuthSummary     `json:"authSummary"`
	Domains              []string              `json:"domains"`
	AutoRouteScrape      bool                  `json:"autoRouteScrape,omitempty"`
	CachedTools          []CachedMCPToolSchema `json:"cachedTools"`
	ToolCount            int                   `json:"toolCount"`
	Enabled              bool                  `json:"enabled"`
	LastVerifiedAt       *int64                `json:"lastVerifiedAt"`
	LastError            *string               `json:"lastError"`
	CreatedAt            int64                 `json:"createdAt"`
	UpdatedAt            int64                 `json:"updatedAt"`
}

StoredMCPServerRow represents a user_mcp_servers persistence row.

type StructuredSanitizeOptions

type StructuredSanitizeOptions struct {
	BaseURL                string
	ApplyRedact            bool
	RedactSecret           *VaultSecretPayload
	MaxDepth               int
	MaxEntriesPerContainer int
	MaxNodeBudget          int
	MaxStringChars         int
	MaxTotalChars          *int
}

StructuredSanitizeOptions configures SanitizeConnectorStructuredValue.

type UnsealVaultParams

type UnsealVaultParams struct {
	VaultMasterKey string
	UserID         string
	RemoteOrigin   string
	RemoteURL      string
	ID             *string
	ServerID       *string
	Slug           *string
	AuthType       *string
	SecretVersion  *int
	Ciphertext     string
}

UnsealVaultParams configures UnsealVaultCredentials / PrepareUnsealVaultEnvelope.

type UnsealVaultResult

type UnsealVaultResult struct {
	OK                    bool          `json:"ok"`
	Payload               OrderedObject `json:"payload,omitempty"`
	ResealedCiphertext    string        `json:"resealedCiphertext,omitempty"`
	ResealedSecretVersion *int          `json:"resealedSecretVersion,omitempty"`
	NeedsReseal           bool          `json:"needsReseal,omitempty"`
	Error                 string        `json:"error,omitempty"`
	Message               string        `json:"message,omitempty"`
}

UnsealVaultResult is the outcome of UnsealVaultCredentials.

func UnsealVaultCredentials

func UnsealVaultCredentials(params UnsealVaultParams) UnsealVaultResult

UnsealVaultCredentials authenticates and decrypts an AES-256-GCM vault envelope with P6/M8 downgrade prevention and automatic reseal-on-read for legacy v1 / 2-field v2 rows.

func VerifyUnsealedVaultPlaintext

func VerifyUnsealedVaultPlaintext(params UnsealVaultParams, plainBuf []byte, attemptShouldReseal bool) UnsealVaultResult

VerifyUnsealedVaultPlaintext validates decrypted JSON credentials against pinned origin, URL, purpose, and row bindings.

type VaultSecretOAuth

type VaultSecretOAuth struct {
	AccessToken         string `json:"accessToken"`
	RefreshToken        string `json:"refreshToken,omitempty"`
	TokenType           string `json:"tokenType,omitempty"`
	ExpiresAt           *int64 `json:"expiresAt,omitempty"`
	Scope               string `json:"scope,omitempty"`
	Issuer              string `json:"issuer,omitempty"`
	Resource            string `json:"resource,omitempty"`
	TokenEndpoint       string `json:"tokenEndpoint"`
	ConfirmedAuthOrigin string `json:"confirmedAuthOrigin,omitempty"`
	ClientID            string `json:"clientId"`
	ClientSecret        string `json:"clientSecret,omitempty"`
}

VaultSecretOAuth holds downstream OAuth 2.1 tokens inside VaultSecretPayload.

type VaultSecretPayload

type VaultSecretPayload struct {
	Kind         string            `json:"kind"`
	PinnedOrigin string            `json:"pinnedOrigin"`
	PinnedURL    string            `json:"pinnedUrl,omitempty"`
	Purpose      string            `json:"purpose,omitempty"`
	ServerID     string            `json:"serverId,omitempty"`
	Slug         string            `json:"slug,omitempty"`
	AuthType     string            `json:"authType,omitempty"`
	Headers      OrderedObject     `json:"headers,omitempty"`
	OAuth        *VaultSecretOAuth `json:"oauth,omitempty"`
}

VaultSecretPayload represents the plaintext credential payload sealed inside user_mcp_servers.

func ParseVaultSecretPayloadObject

func ParseVaultSecretPayloadObject(obj OrderedObject) (VaultSecretPayload, error)

ParseVaultSecretPayloadObject extracts structured fields from an OrderedObject VaultSecretPayload.

type VaultUnsealAttempt

type VaultUnsealAttempt struct {
	HKDFInfo     string `json:"hkdfInfo"`
	AAD          string `json:"aad"`
	ShouldReseal bool   `json:"shouldReseal"`
	FailMessage  string `json:"failMessage"`
}

VaultUnsealAttempt describes one ordered AEAD decryption candidate (primary v2 5-field, legacy v2 2-field, or v1).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL