From c1d8ab43782e7117b28d6242b5baf2c9d858fabb Mon Sep 17 00:00:00 2001 From: "Mark S. Miller" Date: Mon, 5 Aug 2024 15:46:51 -0700 Subject: [PATCH] feat(immutable-arraybuffer): transferToImmutable shim --- packages/immutable-arraybuffer/CHANGELOG.md | 4 + packages/immutable-arraybuffer/LICENSE | 201 ++++++++++++++++++ packages/immutable-arraybuffer/NEWS.md | 1 + packages/immutable-arraybuffer/README.md | 66 ++++++ packages/immutable-arraybuffer/SECURITY.md | 38 ++++ packages/immutable-arraybuffer/index.js | 152 +++++++++++++ packages/immutable-arraybuffer/package.json | 67 ++++++ packages/immutable-arraybuffer/shim.js | 34 +++ .../immutable-arraybuffer/test/index.test.js | 92 ++++++++ .../immutable-arraybuffer/test/shim.test.js | 89 ++++++++ .../immutable-arraybuffer/tsconfig.build.json | 12 ++ packages/immutable-arraybuffer/tsconfig.json | 9 + yarn.lock | 11 + 13 files changed, 776 insertions(+) create mode 100644 packages/immutable-arraybuffer/CHANGELOG.md create mode 100644 packages/immutable-arraybuffer/LICENSE create mode 100644 packages/immutable-arraybuffer/NEWS.md create mode 100644 packages/immutable-arraybuffer/README.md create mode 100644 packages/immutable-arraybuffer/SECURITY.md create mode 100644 packages/immutable-arraybuffer/index.js create mode 100644 packages/immutable-arraybuffer/package.json create mode 100644 packages/immutable-arraybuffer/shim.js create mode 100644 packages/immutable-arraybuffer/test/index.test.js create mode 100644 packages/immutable-arraybuffer/test/shim.test.js create mode 100644 packages/immutable-arraybuffer/tsconfig.build.json create mode 100644 packages/immutable-arraybuffer/tsconfig.json diff --git a/packages/immutable-arraybuffer/CHANGELOG.md b/packages/immutable-arraybuffer/CHANGELOG.md new file mode 100644 index 0000000000..e4d87c4d45 --- /dev/null +++ b/packages/immutable-arraybuffer/CHANGELOG.md @@ -0,0 +1,4 @@ +# Change Log + +All notable changes to this project will be documented in this file. +See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. diff --git a/packages/immutable-arraybuffer/LICENSE b/packages/immutable-arraybuffer/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/packages/immutable-arraybuffer/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/immutable-arraybuffer/NEWS.md b/packages/immutable-arraybuffer/NEWS.md new file mode 100644 index 0000000000..ece5c67e3f --- /dev/null +++ b/packages/immutable-arraybuffer/NEWS.md @@ -0,0 +1 @@ +User visible changes in `@endo/immutable-arraybuffer`: diff --git a/packages/immutable-arraybuffer/README.md b/packages/immutable-arraybuffer/README.md new file mode 100644 index 0000000000..7d91e66122 --- /dev/null +++ b/packages/immutable-arraybuffer/README.md @@ -0,0 +1,66 @@ +# `@endo/immutable-arraybuffer` + +This `@endo/immutable-arraybuffer` package provides both a ponyfill and a shim for a proposed new JavaScript feature: *Immutable ArrayBuffers*. +- A ponyfill just defines and exports new things without modifying old things. The `index.js` file implements the ponyfill, providing the exports of the unqualified `@endo/immutable-arraybuffer` package. +- A shim modifies the existing JavaScript primordials as needed to most closely emulate the feature as proposed. The `shim.js` file uses the exports from `index.js` to modify `ArrayBuffer.prototype` to resemble the API being proposed. Importing `@endo/immutable-arraybuffer/shim.js` will cause these changes. + +Below, we use the term "buffer" to refer informally to an instance of an `ArrayBuffer`, whether immutable or not. + +## Background + +Prior proposals [In-Place Resizable and Growable `ArrayBuffer`s](https://github.com/tc39/proposal-resizablearraybuffer) and [ArrayBuffer.prototype.transfer and friends](https://github.com/tc39/proposal-arraybuffer-transfer) have both reached stage 4, and so are now an official part of JavaScript. Altogether, `ArrayBuffer.prototype` now has the following methods: +- `transfer(newByteLength?: number) :ArrayBuffer` -- move the contents of the original buffer to a new buffer, detach the original buffer, and return the new buffer. The new buffer will be as resizable as the original was. +- `transferToFixedLength(newByteLength?: number) :ArrayBuffer` -- like `transfer` but the new buffer is not resizable. +- `resize(newByteLength: number) :void` -- change the size of this buffer if possible, or throw otherwise. +- `slice(start?: number, end?: number) :ArrayBuffer` -- Return a new buffer whose initial contents are a copy of that region of the original buffer. The original buffer is unmodified. + +and the following read-only accessor properties +- `detached: boolean` -- is this buffer detached, or are its contents still available from this buffer object? +- `resizable: boolean` -- can this buffer be resized, or is it fixed-length? +- `byteLength: number` -- how big are the current contents of this buffer? +- `maxByteLength: number` -- how big could this buffer be resized to be? + +None of the operations above enable the creation of an immutable buffer, i.e., a non-detached buffer whose contents cannot be changed, resized, or detached. + +Both a `DataView` object and a `TypedArray` object are views into a buffer backing store. For a `TypedArray` object, the contents of the backing store appear as indexed data properties of the `TypeArray` object that reflect the current contents of this backing store. Currently, because there is no way to prevent the contents of the backing store from being changed, `TypedArray`s cannot be frozen. + +Some JavaScript implementations, like Moddable XS, bring JavaScript to embedded systems, like device controllers, where ROM is much more plentiful and cheaper than RAM. These systems need to place voluminous fixed data into ROM, and currently do so using semantics outside the official JavaScript standard. + +The [OCapN](https://ocapn.org/) network protocol treats strings and byte-arrays as distinct forms of bulk data to be transmitted by copy. At JavaScript endpoints speaking OCapN such as `@endo/pass-style` + `@endo/marshal`, JavaScript strings represent OCapN strings. The immutability of strings in the JavaScript language reflects their by-copy nature in the protocol. Likewise, to reflect an OCapN byte-array well into the JavaScript language, we need an immutable container of bulk binary data. There currently are none. An Immutable `ArrayBuffer` would provide exactly the low-level machinery we need. + +## Overview of the *Immutable ArrayBuffer* Proposal + +The *Immutable ArrayBuffer* proposal introduces additional methods and read-only accessor properties to `ArrayBuffer.prototype` that fit naturally into those explained above. Just as a buffer can be resizable or not, or detached or not, this proposal enables buffers to be immutable or not. Just as `transferToFixedSize` moves the contents of a original buffer into a newly created non-resizable buffer, this proposal provides a transfer operation that moves the contents of an original original buffer into a newly created immutable buffer. Altogether, this proposal only adds to `ArrayBuffer.prototype` one method +- `transferToImmutable() :ArrayBuffer` -- move the contents of the original buffer into a new immutable buffer, detach the original buffer, and return the new buffer. + +and one read-only accessor +- `immutable: boolean` -- is this buffer immutable, or can its contents be changed? + +An immutable buffer cannot be detached or resized. Its `maxByteLength` is the same as its `byteLength`. A `DataView` or `TypedArray` using an immutable buffer as its backing store can be frozen and immutable. `ArrayBuffer`s, `DataView`s, and `TypedArray`s that are frozen and immutable could be placed in ROM without going beyond JavaScript's official semantics. + +## The Ponyfill + +The proposal would add methods to `ArrayBuffer.prototype`. But a ponyfill, by definition, cannot do so. Instead, it defines and exports two functions corresponding to the two additions above +- `transferBufferToImmutable(buffer: ArrayBuffer) :ArrayBuffer` +- `isBufferImmutable(buffer: ArrayBuffer) :boolean` + +In order for `transferBufferToImmutable` to be able to return something of type `ArrayBuffer` that is actually immutable, that object cannot be an actual `ArrayBuffer` exotic object. Instead, an emulated immutable buffer implements the full proposed `ArrayBuffer` API and ultimately inherits from `ArrayBuffer.prototype`. Thus, `x instanceof ArrayBuffer` will act as proposed. + +The emulated immutable buffers inherit directly from an intermediate prototype we refer to as `immutableArrayBufferPrototype`. This intermediate prototype contains all the methods and read-only accessor properties proposed here, as well as overrides of those inherited from `ArrayBuffer.prototype` as needed to emulate the behavior of an immutable instance. For each emulated immutable buffer, the implementation encapsulates a genuine `ArrayBuffer` that it has exclusive access to, so it can enforce immutability simply by never modifying it. + +## The Shim + +The immutable-arraybuffer shim additionally adds to `ArrayBuffer.prototype` a +- `transferToImmutable` method trivially derived from the ponyfill's `transferBufferToImmutable`. +- `immutable` read-only accessor property trivially derived from the ponyfill's `isBufferImmutable`. + +## Caveats + +The *Immutable ArrayBuffer* shim falls short of the proposal in the following ways +- The ponyfill and shim rely on the underlying platform having either `structuredClone` or `ArrayBuffer.prototype.transfer`. However, Node <= 16 has neither. Node 17 introduces `structuredClone` and Node 21 introduces `ArrayBuffer.prototype.transfer`. Without either, the ponyfill and shim fail to initialize. +- The proposal does not introduce an intermediate prototype, but rather modifies the behavior of the built-in methods on `ArrayBuffer.prototype` itself, to act appropriately on immutable `ArrayBuffer`s. By contrast, the ponyfill's and shim's emulated immutable buffers inherit directly from an intermediate prototype we refer to as `immutableArrayBufferPrototype`. That intermediate prototype directly inherits from `ArrayBuffer.prototype`. All the differential behavior for immutable buffers are provided by overrides found on `immutableArrayBufferPrototype`. +- The `immutableArrayBufferPrototype` intermediate prototype is an artifact of the emulation, but it is not encapsulated. It is trivially discoverable as the object that emulated immutable buffers directly inherit from. +- The shim's emulated immutable buffers are not real `ArrayBuffer` exotic objects. If they were, the shim would not be able to protect them from being written. Even though they implement the full proposed `ArrayBuffer` API, they cannot be plug compatible -- they cannot be used as the backing stores of `DataView`s or `TypedArray`s. Perhaps follow-on shims might modify `DataView` and `TypedArray` to emulate that as well, but that is hard and beyond the ambition of this ponyfill + shim. +- Unlike genuine `ArrayBuffer` or `SharedArrayBuffer` exotic objects, the shim's emulated immutable buffers cannot be cloned or transfered between JS threads. +- Even after the *Immutable ArrayBuffer* proposal is implemented by the platform, the current code will still replace it with the shim implementation, in accord with shim best practices. See https://github.com/endojs/endo/pull/2311#discussion_r1632607527 . It will require a later manual step to delete the shim, after manual analysis of the compat implications. +- This is a plain *JavaScript* ponyfill/shim, not by itself a *Hardened JavaScript* polufill/shim. Thus, the objects and function it creates are not hardened by this ponyfill/shim itself. Rather, the ses-shim is expected to import these, and then treat the resulting objects as if they were additional primordials, to be hardened during `lockdown`'s harden phase. diff --git a/packages/immutable-arraybuffer/SECURITY.md b/packages/immutable-arraybuffer/SECURITY.md new file mode 100644 index 0000000000..17272ea788 --- /dev/null +++ b/packages/immutable-arraybuffer/SECURITY.md @@ -0,0 +1,38 @@ +# Security Policy + +## Supported Versions + +The SES package and associated Endo packages are still undergoing development and security review, and all +users are encouraged to use the latest version available. Security fixes will +be made for the most recent branch only. + +## Coordinated Vulnerability Disclosure of Security Bugs + +SES stands for fearless cooperation, and strong security requires strong collaboration with security researchers. If you believe that you have found a security sensitive bug that should not be disclosed until a fix has been made available, we encourage you to report it. To report a bug in HardenedJS, you have several options that include: + +* Reporting the issue to the [Agoric HackerOne vulnerability rewards program](https://hackerone.com/agoric). + +* Sending an email to security at (@) agoric.com., encrypted or unencrypted. To encrypt, please use @Warner’s personal GPG key [A476E2E6 11880C98 5B3C3A39 0386E81B 11CAA07A](http://www.lothar.com/warner-gpg.html) . + +* Sending a message on Keybase to `@agoric_security`, or sharing code and other log files via Keybase’s encrypted file system. ((_keybase_private/agoric_security,$YOURNAME). + +* It is important to be able to provide steps that reproduce the issue and demonstrate its impact with a Proof of Concept example in an initial bug report. Before reporting a bug, a reporter may want to have another trusted individual reproduce the issue. + +* A bug reporter can expect acknowledgment of a potential vulnerability reported through [security@agoric.com](mailto:security@agoric.com) within one business day of submitting a report. If an acknowledgement of an issue is not received within this time frame, especially during a weekend or holiday period, please reach out again. Any issues reported to the HackerOne program will be acknowledged within the time frames posted on the program page. + * The bug triage team and Agoric code maintainers are primarily located in the San Francisco Bay Area with business hours in [Pacific Time](https://www.timeanddate.com/worldclock/usa/san-francisco) . + +* For the safety and security of those who depend on the code, bug reporters should avoid publicly sharing the details of a security bug on Twitter, Discord, Telegram, or in public Github issues during the coordination process. + +* Once a vulnerability report has been received and triaged: + * Agoric code maintainers will confirm whether it is valid, and will provide updates to the reporter on validity of the report. + * It may take up to 72 hours for an issue to be validated, especially if reported during holidays or on weekends. + +* When the Agoric team has verified an issue, remediation steps and patch release timeline information will be shared with the reporter. + * Complexity, severity, impact, and likelihood of exploitation are all vital factors that determine the amount of time required to remediate an issue and distribute a software patch. + * If an issue is Critical or High Severity, Agoric code maintainers will release a security advisory to notify impacted parties to prepare for an emergency patch. + * While the current industry standard for vulnerability coordination resolution is 90 days, Agoric code maintainers will strive to release a patch as quickly as possible. + +When a bug patch is included in a software release, the Agoric code maintainers will: + * Confirm the version and date of the software release with the reporter. + * Provide information about the security issue that the software release resolves. + * Credit the bug reporter for discovery by adding thanks in release notes, securing a CVE designation, or adding the researcher’s name to a Hall of Fame. diff --git a/packages/immutable-arraybuffer/index.js b/packages/immutable-arraybuffer/index.js new file mode 100644 index 0000000000..2a1dbf1fc9 --- /dev/null +++ b/packages/immutable-arraybuffer/index.js @@ -0,0 +1,152 @@ +/* global globalThis */ + +const { setPrototypeOf, getOwnPropertyDescriptor } = Object; +const { apply } = Reflect; +const { prototype: arrayBufferPrototype } = ArrayBuffer; + +const { + slice, + // @ts-expect-error At the time of this writing, the `ArrayBuffer` type built + // into TypeScript does not know about the recent standard `transfer` method. + // Indeed, the `transfer` method is absent from Node <= 20. + transfer, +} = arrayBufferPrototype; + +/** + * Enforces that `arrayBuffer` is a genuine `ArrayBuffer` exotic object. + * + * @param {ArrayBuffer} arrayBuffer + * @param {number} [start] + * @param {number} [end] + * @returns {ArrayBuffer} + */ +const arrayBufferSlice = (arrayBuffer, start = undefined, end = undefined) => + apply(slice, arrayBuffer, [start, end]); + +/** + * Enforces that `arrayBuffer` is a genuine `ArrayBuffer` exotic object. + * Return a new fresh `ArrayBuffer` exotic object, where the contents of the + * original `arrayBuffer` has been moved into the new one, and the original + * `arrayBuffer` has been detached. + * + * @param {ArrayBuffer} arrayBuffer + * @returns {ArrayBuffer} + */ +let arrayBufferClone; + +if (transfer) { + arrayBufferClone = arrayBuffer => apply(transfer, arrayBuffer, []); +} else if (globalThis.structuredClone) { + arrayBufferClone = arrayBuffer => { + // Hopefully, a zero-length slice is cheap, but still enforces that + // `arrayBuffer` is a genuine `ArrayBuffer` exotic object. + arrayBufferSlice(arrayBuffer, 0, 0); + return globalThis.structuredClone(arrayBuffer, { transfer: [arrayBuffer] }); + }; +} else { + // Indeed, Node <= 16 has neither. + throw TypeError( + `Can only emulate immutable ArrayBuffer on a platform with either "structuredClone" or "ArrayBuffer.prototype.transfer"`, + ); +} + +/** + * This class only exists as an artifact or this ponyfill and shim, + * as a convience for imperfectly emulating the + * *Immutable ArrayBuffer* proposal, which would not have this class. + * In the proposal, + * `transferToImmutable` makes a new `ArrayBuffer` that inherits directly from + * `ArrayBuffer.prototype` as you'd expect. In the ponyfill and shim, + * `transferToImmutable` makes a normal object that inherits directly from + * `immutableArrayBufferPrototype`, which has been surgically + * altered to inherit directly from `ArrayBuffer.prototype`. The constructor is + * captured for use internal to this module, and is made otherwise inaccessible. + * Therefore, `immutableArrayBufferPrototype` and all its methods + * and accessor functions effectively become hidden intrinsics. + * They are not encapsulated. Rather, they are trivially discoverable if you + * know how, but are not discoverable merely by enumerating naming paths. + */ +class ImmutableArrayBufferInternal { + /** @type {ArrayBuffer} */ + #buffer; + + constructor(buffer) { + // This constructor is deleted from the prototype below. + this.#buffer = arrayBufferClone(buffer); + } + + get byteLength() { + return this.#buffer.byteLength; + } + + get detached() { + this.#buffer; // shim brand check + return false; + } + + get maxByteLength() { + // Not underlying maxByteLength, which is irrelevant + return this.#buffer.byteLength; + } + + get resizable() { + this.#buffer; // shim brand check + return false; + } + + get immutable() { + this.#buffer; // shim brand check + return true; + } + + slice(begin = 0, end = undefined) { + return arrayBufferSlice(this.#buffer, begin, end); + } + + resize(_newByteLength = undefined) { + this.#buffer; // shim brand check + throw TypeError('Cannot resize an immutable ArrayBuffer'); + } + + transfer(_newLength = undefined) { + this.#buffer; // shim brand check + throw TypeError('Cannot detach an immutable ArrayBuffer'); + } + + transferToFixedLength(_newLength = undefined) { + this.#buffer; // shim brand check + throw TypeError('Cannot detach an immutable ArrayBuffer'); + } + + transferToImmutable(_newLength = undefined) { + this.#buffer; // shim brand check + throw TypeError('Cannot detach an immutable ArrayBuffer'); + } +} + +const immutableArrayBufferPrototype = ImmutableArrayBufferInternal.prototype; +// @ts-expect-error can only delete optionals +delete immutableArrayBufferPrototype.constructor; + +const { + // @ts-expect-error We know it is there. + get: isImmutableGetter, +} = getOwnPropertyDescriptor(immutableArrayBufferPrototype, 'immutable'); + +setPrototypeOf(immutableArrayBufferPrototype, arrayBufferPrototype); + +export const transferBufferToImmutable = buffer => + new ImmutableArrayBufferInternal(buffer); + +export const isBufferImmutable = buffer => { + try { + return apply(isImmutableGetter, buffer, []); + } catch (err) { + if (err instanceof TypeError) { + // TODO: Should this test if `buffer` is a genuine `ArrayBuffer` exotic + // object, and throw if not? + return false; + } + throw err; + } +}; diff --git a/packages/immutable-arraybuffer/package.json b/packages/immutable-arraybuffer/package.json new file mode 100644 index 0000000000..2686b995d8 --- /dev/null +++ b/packages/immutable-arraybuffer/package.json @@ -0,0 +1,67 @@ +{ + "name": "@endo/immutable-arraybuffer", + "version": "0.1.0", + "private": true, + "description": null, + "keywords": [], + "author": "Endo contributors", + "license": "Apache-2.0", + "homepage": "https://github.com/endojs/endo/tree/master/packages/skel#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/endojs/endo.git", + "directory": "packages/immutable-arraybuffer" + }, + "bugs": { + "url": "https://github.com/endojs/endo/issues" + }, + "type": "module", + "main": "./index.js", + "module": "./index.js", + "exports": { + ".": "./index.js", + "./shim.js": "./shim.js", + "./package.json": "./package.json" + }, + "scripts": { + "build": "exit 0", + "lint": "yarn lint:types && yarn lint:eslint", + "lint-check": "yarn lint", + "lint-fix": "yarn lint:eslint --fix && yarn lint:types", + "lint:eslint": "eslint '**/*.js'", + "lint:types": "tsc", + "postpack": "git clean -f '*.d.ts*'", + "prepack": "tsc --build tsconfig.build.json", + "test": "ava", + "test:c8": "c8 $C8_OPTIONS ava --config=ava-nesm.config.js", + "test:xs": "exit 0" + }, + "devDependencies": { + "ava": "^6.1.3", + "c8": "^7.14.0", + "tsd": "^0.30.7", + "typescript": "5.5.2" + }, + "files": [ + "*.js", + "*.ts", + "LICENSE*", + "SECURITY*", + "src" + ], + "publishConfig": { + "access": "public" + }, + "eslintConfig": { + "extends": [ + "plugin:@endo/internal" + ] + }, + "ava": { + "files": [ + "test/**/test-*.*", + "test/**/*.test.*" + ], + "timeout": "2m" + } +} diff --git a/packages/immutable-arraybuffer/shim.js b/packages/immutable-arraybuffer/shim.js new file mode 100644 index 0000000000..8c0be9ba9c --- /dev/null +++ b/packages/immutable-arraybuffer/shim.js @@ -0,0 +1,34 @@ +import { transferBufferToImmutable, isBufferImmutable } from './index.js'; + +const { getOwnPropertyDescriptors, defineProperties } = Object; +const { prototype: arrayBufferPrototype } = ArrayBuffer; + +const arrayBufferMethods = { + transferToImmutable() { + return transferBufferToImmutable(this); + }, + get immutable() { + return isBufferImmutable(this); + }, +}; + +if ('transferToImmutable' in arrayBufferPrototype) { + // Modern shim practice frowns on conditional installation, at least for + // proposals prior to stage 3. This is so changes to the proposal since + // an old shim was distributed don't need to worry about the proposal + // breaking old code depending on the old shim. Thus, if we detect that + // we're about to overwrite a prior installation, we simply issue this + // warning and continue. + // + // TODO, if the primordials are frozen after the prior implementation, such as + // by `lockdown`, then this precludes overwriting as expected. However, for + // this case, the following warning text will be confusing. + console.warn( + 'About to overwrite a prior implementation of "transferToImmutable"', + ); +} + +defineProperties( + arrayBufferPrototype, + getOwnPropertyDescriptors(arrayBufferMethods), +); diff --git a/packages/immutable-arraybuffer/test/index.test.js b/packages/immutable-arraybuffer/test/index.test.js new file mode 100644 index 0000000000..db9ff5c8b6 --- /dev/null +++ b/packages/immutable-arraybuffer/test/index.test.js @@ -0,0 +1,92 @@ +import test from 'ava'; +import { + transferBufferToImmutable, + // isBufferImmutable, +} from '../index.js'; + +const { isFrozen, getPrototypeOf } = Object; + +test('Immutable ArrayBuffer ponyfill installed and not hardened', t => { + const ab1 = new ArrayBuffer(0); + const iab = transferBufferToImmutable(ab1); + const iabProto = getPrototypeOf(iab); + t.false(isFrozen(iabProto)); + t.false(isFrozen(iabProto.slice)); +}); + +test('Immutable ArrayBuffer ponyfill ops', t => { + // Absent on Node <= 18 + const canResize = 'maxByteLength' in ArrayBuffer.prototype; + + const ab1 = new ArrayBuffer(2, { maxByteLength: 7 }); + const ta1 = new Uint8Array(ab1); + ta1[0] = 3; + ta1[1] = 4; + const iab = transferBufferToImmutable(ab1); + t.true(iab instanceof ArrayBuffer); + ta1[1] = 5; + const ab2 = iab.slice(0); + const ta2 = new Uint8Array(ab2); + t.is(ta1[1], undefined); + t.is(ta2[1], 4); + ta2[1] = 6; + + const ab3 = iab.slice(0); + t.true(ab3 instanceof ArrayBuffer); + + const ta3 = new Uint8Array(ab3); + t.is(ta1[1], undefined); + t.is(ta2[1], 6); + t.is(ta3[1], 4); + + t.is(ab1.byteLength, 0); + t.is(iab.byteLength, 2); + t.is(ab2.byteLength, 2); + + t.is(iab.maxByteLength, 2); + if (canResize) { + t.is(ab1.maxByteLength, 0); + t.is(ab2.maxByteLength, 2); + } + + if ('detached' in ab1) { + t.true(ab1.detached); + t.false(ab2.detached); + t.false(ab3.detached); + } + t.false(iab.detached); + t.false(iab.resizable); +}); + +// This could have been written as a test.failing as compared to +// the immutable ArrayBuffer we'll propose. However, I'd rather test what +// the shim purposely does instead. +test('Immutable ArrayBuffer ponyfill limitations', t => { + const ab1 = new ArrayBuffer(2); + const dv1 = new DataView(ab1); + t.is(dv1.buffer, ab1); + t.is(dv1.byteLength, 2); + const ta1 = new Uint8Array(ab1); + ta1[0] = 3; + ta1[1] = 4; + t.is(ta1.byteLength, 2); + + t.throws(() => new DataView({}), { instanceOf: TypeError }); + // Unfortutanely, calling a TypeArray constructor with an object that + // is not a TypeArray, ArrayBuffer, or Iterable just creates a useless + // empty TypedArray, rather than throwing. + const ta2 = new Uint8Array({}); + t.is(ta2.byteLength, 0); + + const iab = transferBufferToImmutable(ab1); + t.throws(() => new DataView(iab), { + instanceOf: TypeError, + }); + // Unfortunately, unlike the immutable ArrayBuffer to be proposed, + // calling a TypedArray constructor with the shim implementation of + // an immutable ArrayBuffer as argument treats it as an unrecognized object, + // rather than throwing an error. + t.is(iab.byteLength, 2); + const ta3 = new Uint8Array(iab); + t.is(ta3.byteLength, 0); +}); diff --git a/packages/immutable-arraybuffer/test/shim.test.js b/packages/immutable-arraybuffer/test/shim.test.js new file mode 100644 index 0000000000..36cb940891 --- /dev/null +++ b/packages/immutable-arraybuffer/test/shim.test.js @@ -0,0 +1,89 @@ +import test from 'ava'; +import '../shim.js'; + +const { isFrozen, getPrototypeOf } = Object; + +test('Immutable ArrayBuffer shim installed but not hardened', t => { + const ab1 = new ArrayBuffer(0); + const iab = ab1.transferToImmutable(); + const iabProto = getPrototypeOf(iab); + t.false(isFrozen(iabProto)); + t.false(isFrozen(iabProto.slice)); +}); + +test('Immutable ArrayBuffer shim ops', t => { + // Absent on Node <= 18 + const canResize = 'maxByteLength' in ArrayBuffer.prototype; + + const ab1 = new ArrayBuffer(2, { maxByteLength: 7 }); + const ta1 = new Uint8Array(ab1); + ta1[0] = 3; + ta1[1] = 4; + const iab = ab1.transferToImmutable(); + t.true(iab instanceof ArrayBuffer); + ta1[1] = 5; + const ab2 = iab.slice(0); + const ta2 = new Uint8Array(ab2); + t.is(ta1[1], undefined); + t.is(ta2[1], 4); + ta2[1] = 6; + + const ab3 = iab.slice(0); + t.true(ab3 instanceof ArrayBuffer); + + const ta3 = new Uint8Array(ab3); + t.is(ta1[1], undefined); + t.is(ta2[1], 6); + t.is(ta3[1], 4); + + t.is(ab1.byteLength, 0); + t.is(iab.byteLength, 2); + t.is(ab2.byteLength, 2); + + t.is(iab.maxByteLength, 2); + if (canResize) { + t.is(ab1.maxByteLength, 0); + t.is(ab2.maxByteLength, 2); + } + + if ('detached' in ab1) { + t.true(ab1.detached); + t.false(ab2.detached); + t.false(ab3.detached); + } + t.false(iab.detached); + t.false(iab.resizable); +}); + +// This could have been written as a test.failing as compared to +// the immutable ArrayBuffer we'll propose. However, I'd rather test what +// the shim purposely does instead. +test('Immutable ArrayBuffer shim limitations', t => { + const ab1 = new ArrayBuffer(2); + const dv1 = new DataView(ab1); + t.is(dv1.buffer, ab1); + t.is(dv1.byteLength, 2); + const ta1 = new Uint8Array(ab1); + ta1[0] = 3; + ta1[1] = 4; + t.is(ta1.byteLength, 2); + + t.throws(() => new DataView({}), { instanceOf: TypeError }); + // Unfortutanely, calling a TypeArray constructor with an object that + // is not a TypeArray, ArrayBuffer, or Iterable just creates a useless + // empty TypedArray, rather than throwing. + const ta2 = new Uint8Array({}); + t.is(ta2.byteLength, 0); + + const iab = ab1.transferToImmutable(); + t.throws(() => new DataView(iab), { + instanceOf: TypeError, + }); + // Unfortunately, unlike the immutable ArrayBuffer to be proposed, + // calling a TypedArray constructor with the shim implementation of + // an immutable ArrayBuffer as argument treats it as an unrecognized object, + // rather than throwing an error. + t.is(iab.byteLength, 2); + const ta3 = new Uint8Array(iab); + t.is(ta3.byteLength, 0); +}); diff --git a/packages/immutable-arraybuffer/tsconfig.build.json b/packages/immutable-arraybuffer/tsconfig.build.json new file mode 100644 index 0000000000..3e3877ed37 --- /dev/null +++ b/packages/immutable-arraybuffer/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": [ + "./tsconfig.json", + "../../tsconfig-build-options.json" + ], + "compilerOptions": { + "allowJs": true + }, + "exclude": [ + "test/" + ] +} diff --git a/packages/immutable-arraybuffer/tsconfig.json b/packages/immutable-arraybuffer/tsconfig.json new file mode 100644 index 0000000000..f77b8008a1 --- /dev/null +++ b/packages/immutable-arraybuffer/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.eslint-base.json", + "include": [ + "*.js", + "*.ts", + "src/**/*.js", + "src/**/*.ts" + ] +} diff --git a/yarn.lock b/yarn.lock index 5d0a5e264e..74bd617dd5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -494,6 +494,17 @@ __metadata: languageName: unknown linkType: soft +"@endo/immutable-arraybuffer@workspace:packages/immutable-arraybuffer": + version: 0.0.0-use.local + resolution: "@endo/immutable-arraybuffer@workspace:packages/immutable-arraybuffer" + dependencies: + ava: "npm:^6.1.3" + c8: "npm:^7.14.0" + tsd: "npm:^0.30.7" + typescript: "npm:5.5.2" + languageName: unknown + linkType: soft + "@endo/import-bundle@npm:^1.2.1, @endo/import-bundle@workspace:packages/import-bundle": version: 0.0.0-use.local resolution: "@endo/import-bundle@workspace:packages/import-bundle"