package render import ( "bytes" "context" "encoding/json" "errors" "fmt" "image/png" "io" "math" "net/url" "os" "strings" "sync" "sync/atomic" "time" ) // callTimeout and memoryLimit are CallTimeout and MemoryLimit; tests // lower them. launch is Launch (a seam for the tests). var ( callTimeout = CallTimeout memoryLimit int64 = MemoryLimit launch = Launch ) var ( errCallTimeout = errors.New("the call ran out of time") errOverMemory = errors.New("the sandbox used more than its memory") ) // Render renders pages of the site in cfg in one sandbox: for each, the // viewport, the navigation, the wait for load and then network idle, the // capture, the title, console errors, failed loads, same-site links that // answer 404 and the accessibility outline. It writes each capture // (page-N.png) and report.json to out and returns the report. // // out is the runner's own directory, never in the sandbox: captures // arrive over the browser's pipe and the runner writes them. It must be // an empty directory, mode 0700, owned by this user and reached through // no symlink; anything else is refused before the sandbox starts. // // The call has CallTimeout and MemoryLimit: past either the sandbox is // killed and the error is an *Error, CodeTimeout or CodeCrashed, as it // is for a renderer or browser that dies. The report then holds the // pages finished before. A tree that does not verify is the launch's // *release.RendererError, and nothing runs. func Render(ctx context.Context, cfg LaunchConfig, out string, pages []Page) (*Report, error) { if err := checkPages(pages); err != nil { return nil, err } root, err := openOut(out) if err != nil { return nil, err } defer root.Close() began := time.Now() ctx, cancel := context.WithTimeoutCause(ctx, callTimeout, errCallTimeout) defer cancel() s, err := launch(ctx, cfg) if err != nil { if errors.Is(context.Cause(ctx), errCallTimeout) { // The timeout's code first, with the launch's own error // kept: a sandbox that did not end is still ErrNotEnded // (Health.Ended stops every later render on it). return nil, errors.Join(&Error{Code: CodeTimeout, Detail: errCallTimeout.Error()}, err) } return nil, err } defer s.Close() var over atomic.Bool stopWatch := watchMemory(s, memoryLimit, func() { over.Store(true) cancel() s.stop() }) report, err := drive(ctx, s.FromBrowser, s.ToBrowser, s.Site, root, pages) stopWatch() switch { case err == nil: case over.Load(): err = &Error{Code: CodeCrashed, Detail: errOverMemory.Error()} case errors.Is(context.Cause(ctx), errCallTimeout): err = &Error{Code: CodeTimeout, Detail: errCallTimeout.Error()} case ctx.Err() != nil: err = ctx.Err() } if code := ErrorCode(err); code != "" { report.Error = code } closeErr := s.Close() report.ElapsedMS = time.Since(began).Milliseconds() if werr := writeReport(root, report); werr != nil && err == nil { err = werr } return report, withClose(err, closeErr) } // withClose is a call's error with its sandbox's Close error: both when // both happened, so a failed render whose sandbox did not end still // shows ErrNotEnded (Health.Ended stops every later render on it) beside // its code. func withClose(err, closeErr error) error { switch { case closeErr == nil: return err case err == nil: return closeErr } return errors.Join(err, closeErr) } // checkPages refuses what no render may ask for. func checkPages(pages []Page) error { if len(pages) == 0 || len(pages) > MaxPages { return fmt.Errorf("render: %d pages (1 to %d)", len(pages), MaxPages) } for _, p := range pages { if _, _, ok := p.Viewport.Size(); !ok { return fmt.Errorf("render: viewport %q", p.Viewport) } if !sitePath(p.Path) { return fmt.Errorf("render: page path %q", p.Path) } } return nil } // sitePath is a path on the site: absolute, no scheme or host, no // fragment, printable ASCII, at most 1024 bytes. func sitePath(p string) bool { if len(p) == 0 || len(p) > 1024 || p[0] != '/' || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "#\\") { return false } for i := 0; i < len(p); i++ { if p[i] <= ' ' || p[i] >= 0x7f { return false } } return true } func writeReport(out *os.Root, r *Report) error { raw, err := json.MarshalIndent(r, "", " ") if err != nil { return err } f, err := out.OpenFile(ReportName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return err } if _, err = f.Write(append(raw, '\n')); err != nil { f.Close() return err } return f.Close() } // driver drives one browser over CDP for one call. type driver struct { conn *cdpConn site *url.URL out *os.Root mu sync.Mutex page *pageState } // drive renders pages over the browser's pipe (from, to), with the site // served at site and captures written to out. The report is never nil. func drive(ctx context.Context, from io.Reader, to deadlineWriter, site string, out *os.Root, pages []Page) (*Report, error) { report := &Report{Schema: ReportSchema, Pages: []PageReport{}} u, err := url.Parse(site) if err != nil || u.Scheme != "http" || u.Host == "" { return report, fmt.Errorf("render: site %q", site) } d := &driver{site: u, out: out} d.conn = newConn(from, to, maxFrame, d.event) // Downloads go nowhere. d.conn.call(ctx, "", "Browser.setDownloadBehavior", map[string]any{"behavior": "deny"}, nil) for i, p := range pages { pr, err := d.render(ctx, i+1, p) if err != nil { return report, d.ended(ctx, err) } report.Pages = append(report.Pages, pr) } return report, nil } // ended is the error a page's failure ends the call with: a crashed // renderer, or a browser whose pipe ended or broke the protocol, is // CodeCrashed; the call's own deadline is reported by Render. func (d *driver) ended(ctx context.Context, err error) error { if ctx.Err() != nil { return err } if errors.Is(err, errRendererCrashed) { return &Error{Code: CodeCrashed, Detail: errRendererCrashed.Error()} } if cerr := d.conn.Err(); cerr != nil { return &Error{Code: CodeCrashed, Detail: cerr.Error()} } return err } // event routes the browser's events: the current page's session gets its // own; a page session that detaches is a page gone. func (d *driver) event(session, method string, params json.RawMessage) { d.mu.Lock() p := d.page d.mu.Unlock() if p == nil { return } switch { case session == p.session: p.event(method, params) case session == "" && method == "Target.detachedFromTarget": var e struct { SessionID string `json:"sessionId"` } if json.Unmarshal(params, &e) == nil && e.SessionID == p.session { p.event("Inspector.targetCrashed", nil) } } } // render renders one page in a fresh target; n numbers its capture. func (d *driver) render(ctx context.Context, n int, p Page) (PageReport, error) { w, h, _ := p.Viewport.Size() r := PageReport{Path: p.Path, Viewport: p.Viewport, Width: w, Height: h, FullPage: p.FullPage} var target struct { TargetID string `json:"targetId"` } if err := d.conn.call(ctx, "", "Target.createTarget", map[string]any{"url": "about:blank"}, &target); err != nil { return r, err } defer func() { closeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() if ctx.Err() == nil { d.conn.call(closeCtx, "", "Target.closeTarget", map[string]any{"targetId": target.TargetID}, nil) } d.mu.Lock() d.page = nil d.mu.Unlock() }() var attached struct { SessionID string `json:"sessionId"` } if err := d.conn.call(ctx, "", "Target.attachToTarget", map[string]any{"targetId": target.TargetID, "flatten": true}, &attached); err != nil { return r, err } pctx, cancel := context.WithCancelCause(ctx) defer cancel(nil) // A browser that ends, or breaks the protocol, ends every wait. go func() { select { case <-d.conn.done: cancel(d.conn.Err()) case <-pctx.Done(): } }() ps := newPageState(d.site, attached.SessionID, cancel) d.mu.Lock() d.page = ps d.mu.Unlock() call := func(method string, params, result any) error { return d.conn.call(pctx, ps.session, method, params, result) } var tree struct { FrameTree struct { Frame struct { ID string `json:"id"` } `json:"frame"` } `json:"frameTree"` } if err := call("Page.getFrameTree", nil, &tree); err != nil { return r, err } ps.setMain(tree.FrameTree.Frame.ID) steps := []struct { method string params any }{ {"Inspector.enable", nil}, {"Page.enable", nil}, {"Page.setLifecycleEventsEnabled", map[string]any{"enabled": true}}, {"Runtime.enable", nil}, {"Network.enable", nil}, {"Emulation.setDeviceMetricsOverride", map[string]any{"width": w, "height": h, "deviceScaleFactor": 1, "mobile": p.Viewport.mobile()}}, } for _, s := range steps { if err := call(s.method, s.params, nil); err != nil { return r, err } } page := *d.site page.Path, page.RawQuery = "", "" addr := strings.TrimSuffix(page.String(), "/") + p.Path if err := call("Page.navigate", map[string]any{"url": addr}, nil); err != nil { return r, err } if err := ps.waitLoaded(pctx); err != nil { return r, err } if err := d.capture(pctx, call, n, p, &r); err != nil { return r, err } ps.finish(&r) if err := d.inspect(pctx, call, tree.FrameTree.Frame.ID, &r); err != nil { return r, err } var ax struct { Nodes []axNode `json:"nodes"` } if err := call("Accessibility.getFullAXTree", nil, &ax); err != nil { return r, err } r.Outline, r.OutlineCut = outline(ax.Nodes, maxOutline) if context.Cause(pctx) != nil { return r, context.Cause(pctx) } return r, nil } // capture takes the page's PNG and writes it to the out directory: the // viewport, or the full page clipped at MaxCaptureHeight. func (d *driver) capture(ctx context.Context, call func(string, any, any) error, n int, p Page, r *PageReport) error { params := map[string]any{"format": "png", "fromSurface": true} if p.FullPage { var m struct { CSSContentSize struct { Height float64 `json:"height"` } `json:"cssContentSize"` } if err := call("Page.getLayoutMetrics", nil, &m); err != nil { return err } h := float64(r.Height) if c := m.CSSContentSize.Height; !math.IsNaN(c) && c > h { h = math.Min(math.Ceil(c), MaxCaptureHeight) } params["captureBeyondViewport"] = true params["clip"] = map[string]any{"x": 0, "y": 0, "width": r.Width, "height": h, "scale": 1} } var shot struct { Data []byte `json:"data"` } if err := call("Page.captureScreenshot", params, &shot); err != nil { return err } cfg, err := png.DecodeConfig(bytes.NewReader(shot.Data)) if err != nil { return &Error{Code: CodeCrashed, Detail: "the capture is not a PNG"} } if cfg.Width > r.Width || cfg.Height > max(r.Height, MaxCaptureHeight) { return &Error{Code: CodeCrashed, Detail: fmt.Sprintf("the capture is %dx%d", cfg.Width, cfg.Height)} } name := fmt.Sprintf("page-%d.png", n) f, err := d.out.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return err } if _, err = f.Write(shot.Data); err != nil { f.Close() return err } if err = f.Close(); err != nil { return err } r.Capture, r.CaptureWidth, r.CaptureHeight = name, cfg.Width, cfg.Height return nil } // linkCheck runs in an isolated world, where the page's own scripts // cannot change what it calls: the title, and each distinct same-site // anchor (at most maxLinks, without its fragment) asked for with HEAD, // four at a time, each within 3 seconds. A link that answers 404 is // broken. const linkCheck = `(async (site, maxLinks) => { const seen = new Set(), links = []; for (const a of document.querySelectorAll("a[href]")) { let u; try { u = new URL(a.getAttribute("href"), document.baseURI); } catch (e) { continue; } if (u.origin !== site) continue; u.hash = ""; if (seen.has(u.href)) continue; seen.add(u.href); links.push(u.href); if (links.length >= maxLinks) break; } const broken = []; let next = 0; const work = async () => { while (next < links.length) { const u = links[next++]; try { const r = await fetch(u, {method: "HEAD", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(3000)}); if (r.status === 404) broken.push(u); } catch (e) {} } }; await Promise.all([work(), work(), work(), work()]); return {title: String(document.title), checked: links.length, broken: broken}; })(%s, %d)` // maxLinks bounds the anchors one page's check asks for. const maxLinks = 200 // inspect reads the title and checks the page's same-site links. func (d *driver) inspect(ctx context.Context, call func(string, any, any) error, frame string, r *PageReport) error { var world struct { ContextID int `json:"executionContextId"` } if err := call("Page.createIsolatedWorld", map[string]any{"frameId": frame, "worldName": "equipo-render"}, &world); err != nil { return err } origin := d.site.Scheme + "://" + d.site.Host quoted, _ := json.Marshal(origin) var res struct { Result struct { Value struct { Title string `json:"title"` Checked int `json:"checked"` Broken []string `json:"broken"` } `json:"value"` } `json:"result"` ExceptionDetails *json.RawMessage `json:"exceptionDetails"` } expr := fmt.Sprintf(linkCheck, quoted, maxLinks) if err := call("Runtime.evaluate", map[string]any{"expression": expr, "contextId": world.ContextID, "awaitPromise": true, "returnByValue": true}, &res); err != nil { return err } v := res.Result.Value r.Title = clean(v.Title, maxTitle) r.LinksChecked = min(max(v.Checked, 0), maxLinks) r.BrokenLinks = []string{} for _, link := range v.Broken { u, err := url.Parse(link) if err != nil || u.Scheme != d.site.Scheme || u.Host != d.site.Host { continue } if len(r.BrokenLinks) < maxBrokenLinks { r.BrokenLinks = append(r.BrokenLinks, clean(link, maxURL)) } else { r.BrokenLinksOmitted++ } } return nil }