Documentation
¶
Index ¶
- Constants
- Variables
- func AesKeyUnwrap(kek, ciphertext []byte) ([]byte, error)
- func AesKeyWrap(kek, plaintext []byte) ([]byte, error)
- func AwaitValue(rt core.JSRuntime, globalVar string, deadline time.Time, ...) error
- func BuildEnvObject(rt core.JSRuntime, env *core.Env, reqID uint64) error
- func BuildExecContext(rt core.JSRuntime) error
- func CryptoHashFromAlgo(algo string) crypto.Hash
- func CurveFromName(name string) elliptic.Curve
- func DownloadAndExtract(url, destDir string) error
- func DrainWaitUntil(rt core.JSRuntime, deadline time.Time)
- func EnsureUnenv(dataDir string) (string, error)
- func ErrInvalidArg(name, reason string) error
- func ErrMissingArg(name string, required int) error
- func GetReqIDFromJS(rt core.JSRuntime) uint64
- func GoRequestToJS(rt core.JSRuntime, req *core.WorkerRequest) error
- func HashFuncFromAlgo(algo string) func() hash.Hash
- func HtmlAttrsToMap(attrs []gohtml.Attribute) map[string]string
- func IsPrivateHostname(rawURL string) bool
- func IsPrivateIP(ip net.IP) bool
- func JsResponseToGo(rt core.JSRuntime) (*core.WorkerResponse, error)
- func NormalizeAlgo(name string) string
- func PadBytes(b []byte, length int) []byte
- func RsaJWKAlg(algoName, hashAlgo string) string
- func SetupAbort(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupAssets(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupBYOBReader(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupBlobExt(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupBodyTypes(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCache(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCompression(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupConsole(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupConsoleExt(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCrypto(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCryptoAesCtrKw(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCryptoDerive(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCryptoECDH(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCryptoEd25519(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCryptoExt(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupCryptoRSA(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupD1(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupDigestStream(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupDurableObjects(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupEncoding(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupEventSource(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupFetch(rt core.JSRuntime, cfg core.EngineConfig, el *eventloop.EventLoop) error
- func SetupFormData(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupGlobals(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupHTMLRewriter(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupKV(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupMessageChannel(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupQueues(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupReportError(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupScheduler(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupServiceBindings(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupStorage(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupStreams(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupTCPSocket(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupTextStreams(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupTimers(rt core.JSRuntime, el *eventloop.EventLoop) error
- func SetupURLPattern(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupURLSearchParamsExt(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupUnhandledRejection(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupWebAPIs(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func SetupWebSocket(rt core.JSRuntime, _ *eventloop.EventLoop) error
- func ShouldSkipContent(stack []*MatchedElement, depth int) bool
- func ValidateDatabaseID(id string) error
- func VoidElement(tag string) bool
- func WrapESModule(source string) string
- type AttrMatcher
- type CSSSelector
- type CombinatorType
- type CompoundSelector
- type D1Bridge
- type ElementInfo
- type MatchedElement
- type SelectorPart
- type URLParsed
- type WebSocketHandler
Constants ¶
const (
MaxPolyfillDownloadSize = 50 * 1024 * 1024 // 50 MB
)
Pinned versions of unenv and its dependencies.
const MaxWSMessageBytes = 64 * 1024
MaxWSMessageBytes is the maximum size of a single WebSocket message (64 KB).
const WsConnectionTimeout = 5 * time.Minute
WsConnectionTimeout is the maximum duration for a WebSocket connection.
Variables ¶
var EventSourceSSRFEnabled = true
EventSourceSSRFEnabled controls SSRF protection for EventSource connections.
var EventSourceTransport http.RoundTripper = &http.Transport{
DialContext: ssrfSafeDialContext,
}
EventSourceTransport is the HTTP transport used for EventSource connections.
var FetchSSRFEnabled = true
FetchSSRFEnabled controls whether the SSRF-safe dialer is used for fetch. Tests set this to false so httptest servers on 127.0.0.1 are reachable.
var FetchTransport http.RoundTripper = &http.Transport{
DialContext: ssrfSafeDialContext,
}
FetchTransport is the http.RoundTripper used by fetch. Tests can override it.
var ForbiddenFetchHeaders = map[string]bool{ "host": true, "transfer-encoding": true, "connection": true, "keep-alive": true, "upgrade": true, "proxy-authorization": true, "proxy-connection": true, "te": true, "trailer": true, "x-forwarded-for": true, "x-forwarded-host": true, "x-forwarded-proto": true, "x-real-ip": true, }
ForbiddenFetchHeaders is the blocklist of headers that workers cannot set.
var PolyfillHashes = map[string]string{}
PolyfillHashes maps download URLs to expected SHA-256 hex digests. Empty map means integrity checking is opt-in (hashes added as packages are pinned).
var TcpSSRFEnabled = true
TcpSSRFEnabled controls SSRF protection for TCP socket connections.
Functions ¶
func AesKeyUnwrap ¶
aesKeyUnwrap implements RFC 3394 AES Key Unwrap.
func AesKeyWrap ¶
aesKeyWrap implements RFC 3394 AES Key Wrap. The plaintext must be a multiple of 8 bytes (64-bit blocks).
func AwaitValue ¶
func AwaitValue(rt core.JSRuntime, globalVar string, deadline time.Time, el *eventloop.EventLoop) error
AwaitValue resolves a potentially-promise value stored in a global variable by pumping the microtask queue. The global variable is updated in-place with the resolved value. Optionally drains the event loop between pumps.
func BuildEnvObject ¶
BuildEnvObject creates the globalThis.__env object with vars, secrets, and binding namespaces (KV, R2, D1, DO, Queues, Service Bindings, Assets).
func BuildExecContext ¶
BuildExecContext creates the globalThis.__ctx execution context with waitUntil() and passThroughOnException().
func CryptoHashFromAlgo ¶
CryptoHashFromAlgo returns the crypto.Hash for the given algorithm name.
func CurveFromName ¶
CurveFromName returns the elliptic curve for the given name.
func DownloadAndExtract ¶
DownloadAndExtract fetches an npm tarball and extracts it to destDir, stripping the leading "package/" prefix that npm tarballs use.
func DrainWaitUntil ¶
DrainWaitUntil drains any promises registered via ctx.waitUntil().
func EnsureUnenv ¶
EnsureUnenv downloads unenv and its dependencies from the npm registry into {dataDir}/polyfills/node_modules/ if not already present. Returns the path to the unenv package directory.
func ErrInvalidArg ¶
ErrInvalidArg returns a formatted error for invalid argument values.
func ErrMissingArg ¶
ErrMissingArg returns a formatted error for functions called with too few arguments.
func GetReqIDFromJS ¶
GetReqIDFromJS reads the __requestID global and parses it to uint64.
func GoRequestToJS ¶
func GoRequestToJS(rt core.JSRuntime, req *core.WorkerRequest) error
GoRequestToJS converts a Go WorkerRequest into a JS Request object stored in globalThis.__req.
func HashFuncFromAlgo ¶
HashFuncFromAlgo returns the hash.Hash constructor for the given algorithm name.
func HtmlAttrsToMap ¶
HtmlAttrsToMap converts html.Attribute slice to a string map.
func IsPrivateHostname ¶
IsPrivateHostname performs a fast, non-resolving pre-check for obviously private hostnames and literal IP addresses.
func IsPrivateIP ¶
IsPrivateIP returns true if the IP is in a private, loopback, or link-local range.
func JsResponseToGo ¶
func JsResponseToGo(rt core.JSRuntime) (*core.WorkerResponse, error)
JsResponseToGo extracts a Go WorkerResponse from the JS Response in globalThis.__result.
func NormalizeAlgo ¶
NormalizeAlgo normalizes algorithm names to their canonical form.
func SetupAbort ¶
SetupAbort evaluates Event, EventTarget, AbortSignal, AbortController, DOMException, ScheduledEvent, and CustomEvent polyfills.
func SetupAssets ¶
SetupAssets registers global Go functions for Assets operations.
func SetupBYOBReader ¶
SetupBYOBReader registers ReadableStreamBYOBReader and ReadableByteStreamController, monkey-patching the existing ReadableStream.
func SetupBlobExt ¶
SetupBlobExt evaluates the Blob.stream()/bytes() polyfills.
func SetupBodyTypes ¶
SetupBodyTypes patches Request/Response with extended body type support. Must be called after SetupWebAPIs, SetupStreams, and SetupFormData.
func SetupCache ¶
SetupCache registers the Cache API JS classes and Go-backed functions.
func SetupCompression ¶
SetupCompression registers Go-backed streaming compress/decompress functions and evaluates the JS classes. Must run after SetupStreams and SetupEncoding.
func SetupConsole ¶
SetupConsole replaces globalThis.console with a Go-backed version that captures output into the per-request log buffer.
func SetupConsoleExt ¶
SetupConsoleExt evaluates the extended console methods polyfill.
func SetupCrypto ¶
SetupCrypto registers Go-backed crypto helpers and evaluates the JS wrapper.
func SetupCryptoAesCtrKw ¶
SetupCryptoAesCtrKw registers AES-CTR and AES-KW Go functions and evaluates the JS patches. Must run after SetupCryptoRSA (or at least after SetupCryptoExt).
func SetupCryptoDerive ¶
SetupCryptoDerive registers HKDF and PBKDF2 deriveBits/deriveKey. Must run after SetupCryptoExt.
func SetupCryptoECDH ¶
SetupCryptoECDH registers ECDH and X25519 key agreement operations. Must run after SetupCryptoDerive.
func SetupCryptoEd25519 ¶
SetupCryptoEd25519 registers Ed25519 sign/verify/import/export/generate. Must run after SetupCryptoExt.
func SetupCryptoExt ¶
SetupCryptoExt registers extended crypto Go functions and evaluates the JS patches for JWK, ECDSA, generateKey, and AES-CBC. Must run after SetupCrypto.
func SetupCryptoRSA ¶
SetupCryptoRSA registers RSA Go functions and evaluates the JS patches. Must run after SetupCryptoExt.
func SetupD1 ¶
SetupD1 registers global Go functions for D1 database operations. D1 stores must be provided via Env.D1 (map of binding name -> D1Store).
func SetupDigestStream ¶
SetupDigestStream registers Go-backed helpers for DigestStream and evaluates the JS wrapper.
func SetupDurableObjects ¶
SetupDurableObjects registers global Go functions for Durable Object operations.
func SetupEncoding ¶
SetupEncoding evaluates the pure-JS atob/btoa implementations.
func SetupEventSource ¶
SetupEventSource registers Go-backed helpers for EventSource SSE and evaluates the JS wrapper.
func SetupFetch ¶
SetupFetch registers Go-backed fetch helpers and evaluates the JS polyfill.
func SetupFormData ¶
SetupFormData evaluates the FormData/Blob/File polyfills.
func SetupGlobals ¶
SetupGlobals registers structuredClone, performance.now(), navigator, queueMicrotask, and the Event/EventTarget base classes.
func SetupHTMLRewriter ¶
SetupHTMLRewriter registers the HTMLRewriter JS class and the Go-backed __htmlRewrite function that performs streaming HTML transformation.
func SetupKV ¶
SetupKV registers global Go functions for KV namespace operations. The actual KV binding objects are built in JS via buildEnvObject.
func SetupMessageChannel ¶
SetupMessageChannel registers MessageChannel and MessagePort globals.
func SetupQueues ¶
SetupQueues registers global Go functions for Queue operations.
func SetupReportError ¶
SetupReportError evaluates the reportError/ErrorEvent polyfill.
func SetupScheduler ¶
SetupScheduler registers the scheduler global with wait().
func SetupServiceBindings ¶
SetupServiceBindings registers global Go functions for service binding operations.
func SetupStorage ¶
SetupStorage registers global Go functions for R2 storage operations.
func SetupStreams ¶
SetupStreams evaluates the Streams API polyfills.
func SetupTCPSocket ¶
SetupTCPSocket registers Go-backed TCP helpers and evaluates the JS wrapper.
func SetupTextStreams ¶
SetupTextStreams evaluates the text stream polyfills. Must run after SetupStreams and SetupWebAPIs (for TextEncoder/TextDecoder).
func SetupTimers ¶
SetupTimers registers Go-backed setTimeout/setInterval/clearTimeout/clearInterval.
func SetupURLPattern ¶
SetupURLPattern evaluates the URLPattern polyfill.
func SetupURLSearchParamsExt ¶
SetupURLSearchParamsExt evaluates the URLSearchParams extension polyfill.
func SetupUnhandledRejection ¶
SetupUnhandledRejection registers PromiseRejectionEvent and best-effort unhandled rejection tracking on globalThis.
func SetupWebAPIs ¶
SetupWebAPIs registers Go-backed helpers and evaluates the JS class definitions that form the Web API surface available to workers.
func SetupWebSocket ¶
SetupWebSocket registers the WebSocket/WebSocketPair JS classes and the Go-backed __wsSend/__wsClose functions that bridge to the HTTP WebSocket.
func ShouldSkipContent ¶
func ShouldSkipContent(stack []*MatchedElement, depth int) bool
ShouldSkipContent returns true if the current depth is inside a matched element that has had its content replaced (setInnerContent) or removed.
func ValidateDatabaseID ¶
ValidateDatabaseID rejects database IDs that contain path traversal characters, null bytes, or are empty/too long.
func VoidElement ¶
VoidElement returns true for HTML void elements that have no end tag.
func WrapESModule ¶
WrapESModule transforms an ES module source into a script that assigns exports to globalThis.__worker_module__. It uses esbuild's Transform API to properly parse the JS AST and wrap the module as an IIFE assigned to globalThis.__worker_module__.
If the source has no exports (already a plain script), the IIFE wrapping is harmless -- the global name is set to the IIFE's return value. If esbuild reports errors, the source is returned unchanged so that callers handle compile errors downstream.
Types ¶
type AttrMatcher ¶
type CSSSelector ¶
type CSSSelector struct {
Tag string
ID string
Classes []string
Attributes []AttrMatcher
}
CSSSelector represents a parsed CSS selector for HTMLRewriter matching. Supports: element, #id, .class, [attr], [attr=val], [attr*=val], [attr^=val], [attr$=val], and combinations thereof.
func ParseSelector ¶
func ParseSelector(s string) *CSSSelector
ParseSelector parses a simple CSS selector string into a CSSSelector. Examples: "div", "#id", ".class", "[href]", "div.class#id[data-x=foo]", "*"
type CombinatorType ¶
type CombinatorType int
CombinatorType represents a CSS combinator between two simple selectors.
const ( CombinatorNone CombinatorType = iota CombinatorDescendant // "A B" — any descendant CombinatorChild // "A > B" — direct child CombinatorAdjacentSibling // "A + B" — immediately following sibling CombinatorGeneralSibling // "A ~ B" — any following sibling )
type CompoundSelector ¶
type CompoundSelector struct {
Parts []SelectorPart
}
compoundSelector represents a full selector that may contain combinators. Parts are ordered left-to-right: parts[0] is the leftmost (ancestor), parts[len-1] is the subject (the element being matched).
func ParseCompoundSelector ¶
func ParseCompoundSelector(s string) *CompoundSelector
ParseCompoundSelector parses a CSS selector string that may contain combinators (>, +, ~, or whitespace for descendant).
func (*CompoundSelector) IsSimple ¶
func (cs *CompoundSelector) IsSimple() bool
isSimple returns true if this compound selector has no combinators (i.e., it is a single simple selector).
func (*CompoundSelector) MatchesWithContext ¶
func (cs *CompoundSelector) MatchesWithContext(tagName string, attrs map[string]string, ancestors []ElementInfo, prevSiblings []ElementInfo) bool
MatchesWithContext checks whether the compound selector matches the given element considering the DOM context (ancestors and siblings). ancestors is ordered from outermost to innermost (the immediate parent is last). prevSiblings is ordered from first to last sibling at the same depth.
func (*CompoundSelector) Subject ¶
func (cs *CompoundSelector) Subject() *CSSSelector
subject returns the rightmost (subject) selector that the element must match.
type D1Bridge ¶
D1Bridge provides Go methods that back the D1 database JS bindings. Each D1 binding gets its own isolated SQLite database, completely separate from the application's main database.
func NewD1BridgeMemory ¶
NewD1BridgeMemory creates an in-memory D1Bridge for testing.
func OpenD1Database ¶
OpenD1Database opens (or creates) an isolated SQLite database for the given database ID. The file is stored at {dataDir}/d1/{databaseID}.sqlite3.
type ElementInfo ¶
ElementInfo captures the tag name and attributes of an element in the DOM context, used for ancestor/sibling matching.
type MatchedElement ¶
type MatchedElement struct {
HandlerIdx int
Depth int
SkipContent bool // setInnerContent or remove was called
Removed bool // element.remove() was called (skip end tag too)
NewTagName string // tagName changed by handler (for end tag rewriting)
InnerContent string // replacement content for setInnerContent
AppendContent string // element.append() — emitted before end tag
AfterContent string // element.after() — emitted after end tag
}
MatchedElement tracks state for elements matched by selectors during rewriting.
type SelectorPart ¶
type SelectorPart struct {
Sel *CSSSelector
Combinator CombinatorType // combinator AFTER this part (toward the subject)
}
SelectorPart represents one segment of a compound selector chain. For "div > p.active", the chain is:
[{Sel: div, combinator: child}, {Sel: p.active, combinator: none}]
type URLParsed ¶
type URLParsed struct {
Href string `json:"href"`
Protocol string `json:"protocol"`
Hostname string `json:"hostname"`
Port string `json:"port"`
Pathname string `json:"pathname"`
Search string `json:"search"`
Hash string `json:"hash"`
Origin string `json:"origin"`
Host string `json:"host"`
Username string `json:"username"`
Password string `json:"password"`
}
URLParsed is the JSON structure returned by __parseURL.
type WebSocketHandler ¶
type WebSocketHandler struct {
// Runtime is the JSRuntime for evaluating JS during the WebSocket bridge.
Runtime core.JSRuntime
// Loop is the event loop for draining pending operations.
Loop *eventloop.EventLoop
// ReqID is the request ID associated with this WebSocket connection.
ReqID uint64
// Timeout is the maximum duration for the WebSocket connection.
Timeout time.Duration
// OnComplete is called when the bridge finishes. The engine uses this
// to return the worker to its pool and clean up request state.
OnComplete func()
}
WebSocketHandler holds references needed for WebSocket bridging after the initial fetch handler returns a 101 response with a webSocket.
Source Files
¶
- abort.go
- assets.go
- bodytypes.go
- byob_reader.go
- cache.go
- compression.go
- console.go
- crypto.go
- crypto_derive.go
- crypto_digeststream.go
- crypto_ecdh.go
- crypto_ed25519.go
- crypto_ext.go
- crypto_kw.go
- crypto_rsa.go
- d1.go
- d1_bridge.go
- durable.go
- encoding.go
- eventsource.go
- execute_helpers.go
- fetch.go
- formdata.go
- globals.go
- helpers.go
- htmlrewriter.go
- kv.go
- messagechannel.go
- polyfills.go
- queues.go
- reporterror.go
- scheduler.go
- selector.go
- servicebinding.go
- storage.go
- streams.go
- tcpsocket.go
- textstreams.go
- timers.go
- unhandledrejection.go
- urlpattern.go
- webapi.go
- websocket.go