Skip to content

fix(webapi): protect native records with private types - #404

Closed
jderochervlk wants to merge 10 commits into
mainfrom
fix/403-private-native-records
Closed

jderochervlk wants to merge 10 commits into
mainfrom
fix/403-private-native-records

Conversation

@jderochervlk

@jderochervlk jderochervlk commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Protect native-record construction and audited property writes on ReScript 13.0.0-alpha.7. Native instances retain direct field reads and use typed setters for supported mutation; caller-owned options, initializers, and callback dictionaries remain constructible.

Before and after

Write native properties through typed setters; keep direct reads

Before:

let url = WebAPI.URL.make(~url="https://example.com")
url.hash = "#details"
let href = url.href

After:

let url = WebAPI.URL.make(~url="https://example.com")
url->WebAPI.URL.setHash("#details")
let href = url.href

The setter writes the native JavaScript property; it does not create a wrapper or copy. Direct field reads stay available. Use the supported setters instead of private-field assignment, which produces warning 111 on alpha.7.

Construct real native instances instead of record-update copies

Before, the public URL record allowed this:

let copyWithHash = (url: WebAPI.URL.t): WebAPI.URL.t => {
  ...url,
  hash: "#details",
}

That produces an ordinary JavaScript object, not a new native URL. After, the record update is rejected; create a native URL and set its property instead:

let copyWithHash = (url: WebAPI.URL.t): WebAPI.URL.t => {
  let copy = WebAPI.URL.make(~url=url.href)
  copy->WebAPI.URL.setHash("#details")
  copy
}

This restriction applies to browser-owned instance records, not caller-owned dictionaries. Options and initializers remain constructible, for example:

let init: WebAPI.Response.responseInit = {status: 201}
let response = WebAPI.Response.fromString("created", ~init)

Keep identity upcasts tied to concrete native receiver types

Before, an upcast inherited from a public generic functor could turn an unrelated value into a native type:

module StringBlob = WebAPI.Blob.Impl({type t = string})
let forged: WebAPI.Blob.t = StringBlob.asBlob("not a Blob")

After, asBlob is no longer provided by Blob.Impl. Use the concrete helper for an actual native File:

let asBlob = (file: WebAPI.File.t): WebAPI.Blob.t =>
  WebAPI.File.asBlob(file)

WebAPI.File.asBlob("not a Blob") is a type error. These helpers are zero-cost upcasts, not runtime validators. They also provide supported derived-to-base conversions where alpha.7 rejects structural :> coercions into private records. This does not fix every native-returning method in generic functors; that broader boundary remains follow-up #417.

Check union values before narrowing them to native instances

Before, the intersection-root projection was an unchecked identity cast, even though a root can be an Element, Document, or null:

let root = WebAPI.IntersectionObserverRoot.fromNull
let element = WebAPI.IntersectionObserverRoot.toElement(root)
// Typed as an Element, but actually null.

After, it returns an option based on a native-instance check:

let root = WebAPI.IntersectionObserverRoot.fromNull
let element = WebAPI.IntersectionObserverRoot.toElement(root)
// None; an actual Element in the current JavaScript realm yields Some(element).

IntersectionObserverRoot.toDocument, FillStyle.toCanvasGradient, and FillStyle.toCanvasPattern similarly return options. These checks recognize native instances in the current realm, not objects from every iframe or realm.

Scope

Private backing declarations and public record views reject ordinary literals, record-update copies, and structural coercion into protected types. Concrete-receiver upcasts preserve supported inherited operations without unrestricted identity casts in public Impl functors. This is a compile-time record construction/write contract, not a package-wide native-instance soundness or security guarantee.

The migration includes checked Canvas-style and intersection-root downcasts, native stream handle identities, accurate performance-entry arrays, a constructible NodeFilter callback dictionary, nullable default MessageEvent payloads, and a concrete media-key access result. Public media, DOM-node, geometry, options-collection, XML/document-type, and AudioWorklet paths retain supported reads, writes, and conversions.

The branch incorporates current main, including the History/Location, DOMTree/CSSOMCore, and narrow data feature splits. Privacy and typed setters remain intact at the new canonical locations, without broadening those feature dependencies. The inventory covers 294 public modules, with explicit backing/view classifications, abstract identities, public setters, and constructible exceptions. Packed consumers and native browser workflows cover the changed boundaries; declaration checks alone are not treated as proof that every binding is sound.

Follow-up work, not merge prerequisites

  • Enforce the external boundary for native binding functors #417: enforce the external-consumer boundary for generic native binding functors. Native-returning methods still accept arbitrary functor receiver types; the existing sources.public configuration does not enforce that boundary on alpha.7. Library-only alternatives and compiler project-scoped visibility are being investigated separately.
  • Make native Web API object types private #403: broader event-callback payload typing and remaining unknown native unions/results. These are explicitly documented outside this PR's construction/write guarantee.

This PR can be reviewed and merged independently of the Impl redesign. It partially addresses #403 and does not close the broader issue automatically.

@jderochervlk
jderochervlk changed the base branch from main to build/rescript-alpha-7 November 16, 2026 21:04
jderochervlk added a commit that referenced this pull request Nov 16, 2026
Upgrade the compiler baseline before continuing the private-record
migration in #404. ReScript 13.0.0-alpha.7 includes
rescript-lang/rescript#9125, which rejects coercion from another type
into a private record—the loophole reproduced on alpha.5 in #403.

Pin the development compiler and raise the minimum peer version to
alpha.7, update the lockfile and installation guidance, and reject the
former alpha.5 baseline in packed-consumer checks. Add a regression for
forged Response coercion alongside positive coverage for native
construction, direct field reads, outward coercion, and the existing
File-to-Blob helper. This does not introduce package-wide native-record
privacy.

The upgrade also requires a concrete typed-array operation in the
ImageData fixture and support for the compiler's new documentation
parameter/type schema. Preserve rendered signatures and type links,
including callbacks, tuples, and generic parameters. The changes across
40 existing ReScript files are the new compiler's formatting output.

Alpha.7 no longer supports native compilation on Intel Macs
(`darwin-x64`); the migration notes and project status call out that
compatibility break.

Refs #403. This is the prerequisite branch for #404, not the
private-record migration itself.
Base automatically changed from build/rescript-alpha-7 to main November 16, 2026 21:08
@jderochervlk

Copy link
Copy Markdown
Collaborator Author

Updated through 2c182af4 with current main/alpha.7. Merge conflicts are resolved; this remains a draft rather than a merge recommendation.

Local validation passed on Node 26: npm run format:check, npm run build, npm test, npm run check:features, npm run test:negative, npm run test:browser (four Chromium tests), npm run check:consumer, npm run build:docs, npm run check:docs-links, and npm run check:release.

An independent source review identified readonly-property setters, a WaveShaper typed-array mismatch, the missing template empty-string state, inherited conversion gaps, and lost throwing annotations. Those concrete findings were corrected and covered by the subsequent local checks. This is not independent approval of all later edits or a package-wide soundness guarantee.

The main remaining public-functor policy blocker was reproduced separately against the packed alpha.7 package:

module Receiver = {type t = {getRootNode: unit => string}}
module FakeNode = WebAPI.Node.Impl(Receiver)
let forged: WebAPI.Node.t =
  FakeNode.getRootNode({getRootNode: () => "not a node"})

This compiles without unsafe casts, raw JavaScript, consumer externals, or :>, and forged is a string at runtime. Removing generic identity upcasts closes those shortcuts but not arbitrary receiver instantiation of native-returning binding methods. Hiding/constraining that surface versus explicitly excluding it as trusted FFI needs a scope decision. The PR body and inventory also record callback typing, unknown native unions/results, and remaining inherited routes.

@jderochervlk
jderochervlk marked this pull request as ready for review November 17, 2026 13:29
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T13:31:14.819684Z 056e48e Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@jderochervlk

Copy link
Copy Markdown
Collaborator Author

Updated to 056e48e7, incorporating current main (b04c3584) and resolving the feature-split merge conflicts. GitHub reports the branch mergeable; draft status has been removed.

The agreed merge contract is private-record construction/update/coercion protection plus audited supported writes and concrete native conversions—not package-wide native-instance soundness. The public functor boundary is now a separate follow-up, #417; the remaining broader callback/union typing work stays under #403.

The standalone hardening also completes the previously listed DOMImplementation, HTMLOptionsCollection, and AudioWorklet conversion/write paths, with packed consumer and Chromium coverage. An independent review of this revision found no blocking regressions under the narrowed contract.

All local checks passed on Node 26: format, build, Node tests, all 36 feature definitions and narrow-feature isolation probes, negative and packed consumers, four Chromium tests, docs build/link checks, and release validation. The updated Playwright browser was installed into the ignored worktree-local cache for validation. CI is rerunning on this revision; merging into main is still a separate maintainer action.

@jderochervlk

Copy link
Copy Markdown
Collaborator Author

Closing in favor of the preferred consumer API: direct field reads and direct mutation of writable native properties. The private-record migration in this PR requires explicit setter functions on ReScript alpha.7, which is not the API direction we want. We are not landing that migration or its setter-based contributor rules.

Independent binding fixes are tracked in #418 for extraction into smaller, reviewable PRs: checked union narrowing, concrete native result/handle types, constructible NodeFilter callbacks, and MessageEvent default payload typing. #418 also links the existing #403 and #417 work and records that their plans must preserve direct mutation rather than assume this setter migration will proceed.

The branch remains available as reference; this PR is closed without merging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant