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
- func BuildOAuthBindMACInputs(vaultMasterKey, userID, state, sessionCSRF string) (macKey, macMessage string)
- func BuildPerUserOriginHKDFInfo(userID, remoteOrigin, purpose string) string
- func ComputeMCPOAuthBindHMAC(vaultMasterKey, userID, state, sessionCSRF string) string
- func ExtractMarkdownFromQueryMCPBody(rawBody json.RawMessage) string
- func ExtractRegistrableDomain(hostname string) string
- func FormatFenceSafeUntrustedMCPEnvelope(tag string, attrs OrderedObject, content string, maxChars int) string
- func InferAssociatedDomains() []string
- func IsCachedMCPToolPermitted(serverSlug string, tool CachedMCPToolSchema, allowedSet map[string]bool) bool
- func IsJSONDepthWithinLimit(rawJSON string, maxDepth int) bool
- func IsSafeMCPIdentifier(raw string) bool
- func IsSafePublicHostname(rawHost, selfHost string) bool
- func IsSharedHostingHostname(hostname string) bool
- func IsValidMCPConnectorSlug(raw string) bool
- func MarshalUnescapedJSON(v any) ([]byte, error)
- func MeasureOrderedJSONSizeCapped(rawValue any, maxBytes int) int
- func NeutralizeUntrustedMCPBoundaryTags(input string) string
- func NormalizeConfirmedAuthOrigin(raw, selfHost string) (origin string, ok bool, reason string)
- func NormalizeMCPConnectorSlug(rawName string) string
- func ParseAllowedMCPTools(raw json.RawMessage) (allowed []string, ok bool, errCode string, message string)
- func ParseOrderedJSON(data []byte, maxDepth int) (any, error)
- func PreparePKCEStateSeal(userID, remoteOrigin string, blob OrderedObject) (hkdfInfo, aad, plaintext string, err error)
- func PreparePKCEStateUnseal(userID, remoteOrigin, ciphertext string) (hkdfInfo, aad, saltB64, ivB64, ctB64 string, salt, iv, ct []byte, ok bool)
- func RandomBase64URL(byteLen int) (string, error)
- func RedactVaultSecretsFromText(raw string, secret *VaultSecretPayload) string
- func ResolveCallerUserID(userID, principal string) string
- func SHA256Base64URL(input string) string
- func SanitizeMCPMarkdownOutput(rawMarkdown, baseURL string, maxChars int) string
- func SanitizeManifestString(raw string, maxLen int) string
- func SanitizeTargetURLForMCPForwarding(rawURL, selfHost string) (safeForwardURL string, normalizedTarget string, ok bool)
- func SealPKCEStateBlob(vaultMasterKey, userID, remoteOrigin string, blob OrderedObject) (string, error)
- func SlugifyMCPServerName(rawName string) string
- func StripMCPSmugglingChars(s string) string
- func ValidateConnectorDomains(rawDomains json.RawMessage, remoteOrigin string, allowUnrelatedDomains bool) ([]string, bool, string)
- func ValidateVaultMasterKey(vaultMasterKey string) (clean string, ok bool, message string)
- func VerifyMCPOAuthBindHMAC(presented, vaultMasterKey, userID, state, sessionCSRF string) bool
- type CachedMCPToolSchema
- type DiscoveredRemoteOAuthMetadata
- type MCPEnvVarSpec
- type MCPPackageSpec
- type MCPRemoteEndpointSpec
- type MCPRemoteHeaderSpec
- type MaskedAuthSummary
- type MatchedConnectedMCP
- type NormalizedMCPRegistryEntry
- func FuseRegistryEntries(officialEntries, glamaEntries []NormalizedMCPRegistryEntry) []NormalizedMCPRegistryEntry
- func ParseGlamaRegistryPayload(rawJSON json.RawMessage, selfHost string) ([]NormalizedMCPRegistryEntry, error)
- func ParseOfficialRegistryPayload(rawJSON json.RawMessage, selfHost string) ([]NormalizedMCPRegistryEntry, error)
- type OAuthPRMCheckResult
- type OAuthProbePlan
- type OAuthTokenEndpointCheck
- type OrderedEntry
- type OrderedObject
- func BuildPKCEAuthorizationInit(...) (blob OrderedObject, authorizationURL string, err error)
- func BuildPinnedOutboundHeaders(secret *VaultSecretPayload, targetOrigin, sessionID string) (OrderedObject, bool, string)
- func ParseRemoteJSONRPCBody(bodyText, contentType string, expected RPCID) (rpc OrderedObject, depthExceeded bool, found bool)
- func ParseSSEJSONRPCResponse(sseText string, expected RPCID) (OrderedObject, bool)
- func RebuildSafeMCPInputSchema(rawNode any, depth int) (OrderedObject, bool)
- func SanitizeCallToolRPCResponse(rpcObj OrderedObject, ...) (status int, body OrderedObject)
- func SanitizeSecretHeadersInput(bearerToken *string, rawHeaders json.RawMessage, hasHeaders bool) (OrderedObject, bool, string)
- func UnsealPKCEStateBlob(vaultMasterKey, userID, remoteOrigin, ciphertext string) (OrderedObject, bool)
- func VerifyPKCEStatePlaintext(plain []byte) (OrderedObject, bool)
- func (o OrderedObject) Clone() OrderedObject
- func (o *OrderedObject) Delete(key string)
- func (o OrderedObject) Get(key string) (any, bool)
- func (o OrderedObject) GetArray(key string) ([]any, bool)
- func (o OrderedObject) GetBool(key string) (bool, bool)
- func (o OrderedObject) GetObject(key string) (OrderedObject, bool)
- func (o OrderedObject) GetString(key string) (string, bool)
- func (o OrderedObject) MarshalJSON() ([]byte, error)
- func (o *OrderedObject) Set(key string, val any)
- func (o *OrderedObject) UnmarshalJSON(data []byte) error
- type PreparedVaultSeal
- type PreparedVaultUnseal
- type PublicMCPServerSummary
- type RPCID
- type SafeHTTPSURLResult
- type SanitizedConnectorStructuredResult
- type SanitizedConnectorTextResult
- type SanitizedTextResult
- type SanitizedToolDefsResult
- type ScrapeMCPPlan
- type SealVaultParams
- type SealVaultResult
- type SpecialSentinel
- type StoredMCPServerRow
- type StructuredSanitizeOptions
- type UnsealVaultParams
- type UnsealVaultResult
- type VaultSecretOAuth
- type VaultSecretPayload
- type VaultUnsealAttempt
Constants ¶
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 )
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" )
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 ¶
BuildPerUserOriginHKDFInfo returns the length-prefixed HKDF-SHA256 info string for a user/origin/purpose tuple.
func ComputeMCPOAuthBindHMAC ¶
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 ¶
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 ¶
IsJSONDepthWithinLimit verifies in O(N) time that bracket/brace nesting never exceeds maxDepth.
func IsSafeMCPIdentifier ¶
IsSafeMCPIdentifier validates tool/property names against prototype pollution, "__", and prompt-injection verbs.
func IsSafePublicHostname ¶
IsSafePublicHostname validates that rawHost is a public DNS name (no IP literals, loopback/LAN/metadata, rebinding, or self-hub).
func IsSharedHostingHostname ¶
IsSharedHostingHostname delegates to extract.HasPrivateSharedHostingSuffix for PSL PRIVATE DOMAINS isolation.
func IsValidMCPConnectorSlug ¶
IsValidMCPConnectorSlug validates lowercase connector slugs (1..48 chars, no "__").
func MarshalUnescapedJSON ¶
MarshalUnescapedJSON marshals v to compact JSON without escaping <, >, or &.
func MeasureOrderedJSONSizeCapped ¶
MeasureOrderedJSONSizeCapped estimates serialized JSON size in UTF-16 code units, aborting as soon as acc > maxBytes.
func NeutralizeUntrustedMCPBoundaryTags ¶
NeutralizeUntrustedMCPBoundaryTags escapes <untrusted_... and </untrusted_... tags inside untrusted text.
func NormalizeConfirmedAuthOrigin ¶
NormalizeConfirmedAuthOrigin validates an optional https:// origin without path or query.
func NormalizeMCPConnectorSlug ¶
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 ¶
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 ¶
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 ¶
ResolveCallerUserID resolves the isolated tenant user_id per the Pillar 1 shared interface contract.
func SHA256Base64URL ¶
SHA256Base64URL computes unpadded base64url(SHA-256(UTF8(input))) for RFC 7636 S256 PKCE challenges and state hashes.
func SanitizeMCPMarkdownOutput ¶
SanitizeMCPMarkdownOutput sanitizes untrusted Markdown/HTML returned by a downstream MCP server.
func SanitizeManifestString ¶
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 ¶
SlugifyMCPServerName converts a registry server name (including reverse-DNS / @scope prefixes) into a safe slug.
func StripMCPSmugglingChars ¶
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 ¶
ValidateVaultMasterKey enforces VAULT_MASTER_KEY >= 24 trimmed UTF-16 characters.
func VerifyMCPOAuthBindHMAC ¶
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 ¶
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 ¶
RPCID represents an optional string or numeric JSON-RPC 2.0 request ID.
func (*RPCID) UnmarshalJSON ¶
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 ¶
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).