webapi

package
v2.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxPolyfillDownloadSize = 50 * 1024 * 1024 // 50 MB
)

Pinned versions of unenv and its dependencies.

View Source
const MaxWSMessageBytes = 64 * 1024

MaxWSMessageBytes is the maximum size of a single WebSocket message (64 KB).

View Source
const WsConnectionTimeout = 5 * time.Minute

WsConnectionTimeout is the maximum duration for a WebSocket connection.

Variables

View Source
var EventSourceSSRFEnabled = true

EventSourceSSRFEnabled controls SSRF protection for EventSource connections.

View Source
var EventSourceTransport http.RoundTripper = &http.Transport{
	DialContext: ssrfSafeDialContext,
}

EventSourceTransport is the HTTP transport used for EventSource connections.

View Source
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.

View Source
var FetchTransport http.RoundTripper = &http.Transport{
	DialContext: ssrfSafeDialContext,
}

FetchTransport is the http.RoundTripper used by fetch. Tests can override it.

View Source
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.

View Source
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).

View Source
var TcpSSRFEnabled = true

TcpSSRFEnabled controls SSRF protection for TCP socket connections.

Functions

func AesKeyUnwrap

func AesKeyUnwrap(kek, ciphertext []byte) ([]byte, error)

aesKeyUnwrap implements RFC 3394 AES Key Unwrap.

func AesKeyWrap

func AesKeyWrap(kek, plaintext []byte) ([]byte, error)

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

func BuildEnvObject(rt core.JSRuntime, env *core.Env, reqID uint64) error

BuildEnvObject creates the globalThis.__env object with vars, secrets, and binding namespaces (KV, R2, D1, DO, Queues, Service Bindings, Assets).

func BuildExecContext

func BuildExecContext(rt core.JSRuntime) error

BuildExecContext creates the globalThis.__ctx execution context with waitUntil() and passThroughOnException().

func CryptoHashFromAlgo

func CryptoHashFromAlgo(algo string) crypto.Hash

CryptoHashFromAlgo returns the crypto.Hash for the given algorithm name.

func CurveFromName

func CurveFromName(name string) elliptic.Curve

CurveFromName returns the elliptic curve for the given name.

func DownloadAndExtract

func DownloadAndExtract(url, destDir string) error

DownloadAndExtract fetches an npm tarball and extracts it to destDir, stripping the leading "package/" prefix that npm tarballs use.

func DrainWaitUntil

func DrainWaitUntil(rt core.JSRuntime, deadline time.Time)

DrainWaitUntil drains any promises registered via ctx.waitUntil().

func EnsureUnenv

func EnsureUnenv(dataDir string) (string, error)

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

func ErrInvalidArg(name, reason string) error

ErrInvalidArg returns a formatted error for invalid argument values.

func ErrMissingArg

func ErrMissingArg(name string, required int) error

ErrMissingArg returns a formatted error for functions called with too few arguments.

func GetReqIDFromJS

func GetReqIDFromJS(rt core.JSRuntime) uint64

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

func HashFuncFromAlgo(algo string) func() hash.Hash

HashFuncFromAlgo returns the hash.Hash constructor for the given algorithm name.

func HtmlAttrsToMap

func HtmlAttrsToMap(attrs []gohtml.Attribute) map[string]string

HtmlAttrsToMap converts html.Attribute slice to a string map.

func IsPrivateHostname

func IsPrivateHostname(rawURL string) bool

IsPrivateHostname performs a fast, non-resolving pre-check for obviously private hostnames and literal IP addresses.

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

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

func NormalizeAlgo(name string) string

NormalizeAlgo normalizes algorithm names to their canonical form.

func PadBytes

func PadBytes(b []byte, length int) []byte

PadBytes left-pads b with zeroes to the given length.

func RsaJWKAlg

func RsaJWKAlg(algoName, hashAlgo string) string

RsaJWKAlg returns the JWK "alg" value for an RSA algorithm+hash combination.

func SetupAbort

func SetupAbort(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupAbort evaluates Event, EventTarget, AbortSignal, AbortController, DOMException, ScheduledEvent, and CustomEvent polyfills.

func SetupAssets

func SetupAssets(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupAssets registers global Go functions for Assets operations.

func SetupBYOBReader

func SetupBYOBReader(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupBYOBReader registers ReadableStreamBYOBReader and ReadableByteStreamController, monkey-patching the existing ReadableStream.

func SetupBlobExt

func SetupBlobExt(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupBlobExt evaluates the Blob.stream()/bytes() polyfills.

func SetupBodyTypes

func SetupBodyTypes(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupBodyTypes patches Request/Response with extended body type support. Must be called after SetupWebAPIs, SetupStreams, and SetupFormData.

func SetupCache

func SetupCache(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCache registers the Cache API JS classes and Go-backed functions.

func SetupCompression

func SetupCompression(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCompression registers Go-backed streaming compress/decompress functions and evaluates the JS classes. Must run after SetupStreams and SetupEncoding.

func SetupConsole

func SetupConsole(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupConsole replaces globalThis.console with a Go-backed version that captures output into the per-request log buffer.

func SetupConsoleExt

func SetupConsoleExt(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupConsoleExt evaluates the extended console methods polyfill.

func SetupCrypto

func SetupCrypto(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCrypto registers Go-backed crypto helpers and evaluates the JS wrapper.

func SetupCryptoAesCtrKw

func SetupCryptoAesCtrKw(rt core.JSRuntime, _ *eventloop.EventLoop) error

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

func SetupCryptoDerive(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCryptoDerive registers HKDF and PBKDF2 deriveBits/deriveKey. Must run after SetupCryptoExt.

func SetupCryptoECDH

func SetupCryptoECDH(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCryptoECDH registers ECDH and X25519 key agreement operations. Must run after SetupCryptoDerive.

func SetupCryptoEd25519

func SetupCryptoEd25519(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCryptoEd25519 registers Ed25519 sign/verify/import/export/generate. Must run after SetupCryptoExt.

func SetupCryptoExt

func SetupCryptoExt(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCryptoExt registers extended crypto Go functions and evaluates the JS patches for JWK, ECDSA, generateKey, and AES-CBC. Must run after SetupCrypto.

func SetupCryptoRSA

func SetupCryptoRSA(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupCryptoRSA registers RSA Go functions and evaluates the JS patches. Must run after SetupCryptoExt.

func SetupD1

func SetupD1(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupD1 registers global Go functions for D1 database operations. D1 stores must be provided via Env.D1 (map of binding name -> D1Store).

func SetupDigestStream

func SetupDigestStream(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupDigestStream registers Go-backed helpers for DigestStream and evaluates the JS wrapper.

func SetupDurableObjects

func SetupDurableObjects(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupDurableObjects registers global Go functions for Durable Object operations.

func SetupEncoding

func SetupEncoding(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupEncoding evaluates the pure-JS atob/btoa implementations.

func SetupEventSource

func SetupEventSource(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupEventSource registers Go-backed helpers for EventSource SSE and evaluates the JS wrapper.

func SetupFetch

func SetupFetch(rt core.JSRuntime, cfg core.EngineConfig, el *eventloop.EventLoop) error

SetupFetch registers Go-backed fetch helpers and evaluates the JS polyfill.

func SetupFormData

func SetupFormData(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupFormData evaluates the FormData/Blob/File polyfills.

func SetupGlobals

func SetupGlobals(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupGlobals registers structuredClone, performance.now(), navigator, queueMicrotask, and the Event/EventTarget base classes.

func SetupHTMLRewriter

func SetupHTMLRewriter(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupHTMLRewriter registers the HTMLRewriter JS class and the Go-backed __htmlRewrite function that performs streaming HTML transformation.

func SetupKV

func SetupKV(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupKV registers global Go functions for KV namespace operations. The actual KV binding objects are built in JS via buildEnvObject.

func SetupMessageChannel

func SetupMessageChannel(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupMessageChannel registers MessageChannel and MessagePort globals.

func SetupQueues

func SetupQueues(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupQueues registers global Go functions for Queue operations.

func SetupReportError

func SetupReportError(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupReportError evaluates the reportError/ErrorEvent polyfill.

func SetupScheduler

func SetupScheduler(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupScheduler registers the scheduler global with wait().

func SetupServiceBindings

func SetupServiceBindings(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupServiceBindings registers global Go functions for service binding operations.

func SetupStorage

func SetupStorage(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupStorage registers global Go functions for R2 storage operations.

func SetupStreams

func SetupStreams(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupStreams evaluates the Streams API polyfills.

func SetupTCPSocket

func SetupTCPSocket(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupTCPSocket registers Go-backed TCP helpers and evaluates the JS wrapper.

func SetupTextStreams

func SetupTextStreams(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupTextStreams evaluates the text stream polyfills. Must run after SetupStreams and SetupWebAPIs (for TextEncoder/TextDecoder).

func SetupTimers

func SetupTimers(rt core.JSRuntime, el *eventloop.EventLoop) error

SetupTimers registers Go-backed setTimeout/setInterval/clearTimeout/clearInterval.

func SetupURLPattern

func SetupURLPattern(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupURLPattern evaluates the URLPattern polyfill.

func SetupURLSearchParamsExt

func SetupURLSearchParamsExt(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupURLSearchParamsExt evaluates the URLSearchParams extension polyfill.

func SetupUnhandledRejection

func SetupUnhandledRejection(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupUnhandledRejection registers PromiseRejectionEvent and best-effort unhandled rejection tracking on globalThis.

func SetupWebAPIs

func SetupWebAPIs(rt core.JSRuntime, _ *eventloop.EventLoop) error

SetupWebAPIs registers Go-backed helpers and evaluates the JS class definitions that form the Web API surface available to workers.

func SetupWebSocket

func SetupWebSocket(rt core.JSRuntime, _ *eventloop.EventLoop) error

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

func ValidateDatabaseID(id string) error

ValidateDatabaseID rejects database IDs that contain path traversal characters, null bytes, or are empty/too long.

func VoidElement

func VoidElement(tag string) bool

VoidElement returns true for HTML void elements that have no end tag.

func WrapESModule

func WrapESModule(source string) string

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 AttrMatcher struct {
	Name  string
	Op    string // "" (exists), "=", "*=", "^=", "$=", "~="
	Value string
}

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]", "*"

func (*CSSSelector) Matches

func (sel *CSSSelector) Matches(tagName string, attrs map[string]string) bool

Matches returns true if the selector matches the given element.

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

type D1Bridge struct {
	DB         *sql.DB
	DatabaseID string
}

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

func NewD1BridgeMemory(databaseID string) (*D1Bridge, error)

NewD1BridgeMemory creates an in-memory D1Bridge for testing.

func OpenD1Database

func OpenD1Database(dataDir, databaseID string) (*D1Bridge, error)

OpenD1Database opens (or creates) an isolated SQLite database for the given database ID. The file is stored at {dataDir}/d1/{databaseID}.sqlite3.

func (*D1Bridge) Close

func (d *D1Bridge) Close() error

Close closes the underlying database connection.

func (*D1Bridge) Exec

func (d *D1Bridge) Exec(sqlStr string, bindings []interface{}) (*core.D1ExecResult, error)

Exec runs a SQL statement with optional bindings and returns columns, rows, and metadata.

type ElementInfo

type ElementInfo struct {
	TagName string
	Attrs   map[string]string
	Depth   int
}

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.

func ParseURL

func ParseURL(rawURL, base string) (*URLParsed, error)

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.

func (*WebSocketHandler) Bridge

func (wsh *WebSocketHandler) Bridge(ctx context.Context, httpConn *websocket.Conn)

Bridge starts the WebSocket message bridge between the HTTP connection and the JS runtime. This method blocks until the WebSocket connection closes or the timeout is reached.

Jump to

Keyboard shortcuts

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