diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 43bca6e..1acaac9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,6 +55,34 @@ jobs: - name: Build run: npm run build + - name: Verify SDK distribution + run: npm run check:sdk-dist + + - name: Load the classic and module distributions in Chrome + run: | + python3 -m http.server 8765 --bind 127.0.0.1 --directory dist >/dev/null 2>&1 & + server=$! + trap 'kill "$server"' EXIT + node scripts/check-sdk-browser.mjs http://127.0.0.1:8765/ + + - name: Exercise the Java runtime provider + run: | + archive="$RUNNER_TEMP/graaljs.tar.gz" + release=https://github.com/oracle/graaljs/releases/download/graal-25.0.1 + curl -fsSL "$release/graaljs-community-jvm-25.0.1-linux-amd64.tar.gz" -o "$archive" + echo "7dfa228b2e9af3ad4fad77635aa105d55a31838ba522200772131db7d4560af5 $archive" | sha256sum -c - + mkdir "$RUNNER_TEMP/graaljs" + tar -xzf "$archive" --strip-components=1 -C "$RUNNER_TEMP/graaljs" + "$RUNNER_TEMP/graaljs/bin/js" -e ' + load("dist/api.js"); + if (DecodeBox.capabilities().runtime !== "graaljs-java") throw Error("Java provider missing"); + DecodeBox.executeOperation("sha-256", "abc").then(print); + ' | grep -Fx ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad + node_modules/.bin/rolldown src/engine/tests/java-key-handles.check.js \ + --format iife --platform neutral --file "$RUNNER_TEMP/key-handles.js" + "$RUNNER_TEMP/graaljs/bin/js" "$RUNNER_TEMP/key-handles.js" | tee "$RUNNER_TEMP/key-handles.log" + grep -Fxq 'Java key handles passed' "$RUNNER_TEMP/key-handles.log" + - name: Report bundle size run: | { @@ -67,7 +95,7 @@ jobs: } >> "$GITHUB_STEP_SUMMARY" - name: Upload build output - if: matrix.node-version == '22' + if: matrix.node-version == '24' uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: dist @@ -113,7 +141,7 @@ jobs: - name: Use Node LTS uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version: '22' + node-version-file: '.nvmrc' cache: npm - name: Install clean packages diff --git a/.github/workflows/deploy-pages.yml b/.github/workflows/deploy-pages.yml index f694709..8e3b5f0 100644 --- a/.github/workflows/deploy-pages.yml +++ b/.github/workflows/deploy-pages.yml @@ -16,9 +16,7 @@ name: Deploy to GitHub Pages # nothing at all — the site was blank for an afternoon while every check passed. # # The branch is force-pushed as a single orphan commit each time. The output is -# 2.7 MB and every file in it is content-hashed, so keeping its history would -# add that much to the repository on every deploy, and not one byte of it would -# ever be read again. +# generated from source. Each tree carries its immutable SDK release directories forward. on: push: @@ -44,6 +42,7 @@ jobs: # The only privilege in this workflow, and it exists for one command: the # push to gh-pages at the end. contents: write + pages: read steps: - name: Checkout @@ -56,7 +55,7 @@ jobs: - name: Use Node LTS uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version: '22' + node-version-file: '.nvmrc' cache: npm - name: Install clean packages @@ -65,44 +64,47 @@ jobs: - name: Build run: npm run build - # The build ships no CNAME, so no repository claims a domain it does not - # control. Relative asset paths support both the configured custom domain - # and a github.io project URL when no custom domain is configured. - # - # On a branch-served site the CNAME file *is* the custom domain setting, - # and this branch is force-pushed. A repository that has a domain - # configured would lose it the moment it deploys: Pages reads the setting - # back from a file that is no longer there and quietly unsets it. That is - # how a staging site once turned into a 404 in the middle of a release, - # with every check in this workflow green. - # - # So whatever domain the repository has configured is carried forward. - # Pages is asked what it currently is, with the branch's own file as a - # second opinion in case that read is not permitted. - - name: Keep this repository's own custom domain + - name: Check new SDK artifacts and retain published versions env: GH_TOKEN: ${{ github.token }} run: | - rm -f dist/CNAME - - raw="https://raw.githubusercontent.com/$GITHUB_REPOSITORY/gh-pages/CNAME" - - domain=$(gh api "repos/$GITHUB_REPOSITORY/pages" --jq '.cname // empty' 2>/dev/null || true) - if [ -z "$domain" ]; then - domain=$(curl -fsSL --max-time 30 "$raw" 2>/dev/null | tr -d '[:space:]' || true) + npm run check:sdk-dist + settings=$(gh api "repos/$GITHUB_REPOSITORY/pages") + jq -e '.source.branch == "gh-pages" and .source.path == "/"' <<< "$settings" >/dev/null + domain=$(jq -r '.cname // empty' <<< "$settings") + previous_ref=$(git ls-remote --heads origin refs/heads/gh-pages) + if [[ -n "$previous_ref" ]]; then + git fetch --no-tags --depth=1 origin refs/heads/gh-pages + if [[ -z "$domain" ]] && git cat-file -e FETCH_HEAD:CNAME 2>/dev/null; then + domain=$(git show FETCH_HEAD:CNAME) + fi + if git cat-file -e FETCH_HEAD:sdk 2>/dev/null; then + previous=$(mktemp -d) + git archive FETCH_HEAD sdk | tar -x -C "$previous" + for series in "$previous"/sdk/v*; do + [[ -d "$series" ]] || continue + name=$(basename "$series") + [[ "$name" =~ ^v[0-9]+$ ]] || continue + for release in "$series"/*/; do + target="dist/sdk/$name/$(basename "$release")" + if [[ -d "$release" && -d "$target" ]]; then + diff -qr "$release" "$target" + fi + done + mkdir -p "dist/sdk/$name" + cp -an "$series/." "dist/sdk/$name/" + done + fi fi - - if [ -n "$domain" ]; then - echo "$domain" > dist/CNAME - echo "Keeping the custom domain $domain." - else - echo "No custom domain is configured, so the site stays on github.io." + rm -f dist/CNAME + if [[ -n "$domain" ]]; then + printf '%s\n' "$domain" > dist/CNAME fi - name: Verify the build is static and complete run: | - test -f dist/index.html || { echo "::error::dist/index.html is missing"; exit 1; } - test -f dist/decodebox.html || { echo "::error::dist/decodebox.html is missing - the download button would 404"; exit 1; } + test -s dist/index.html || { echo "::error::dist/index.html is missing"; exit 1; } + test -s dist/decodebox.html || { echo "::error::dist/decodebox.html is missing - the download button would 404"; exit 1; } # The application must never call out to a third party at runtime. This is a # coarse check, but it catches an accidental CDN reference before it ships. if grep -rIloE 'https?://(cdn|unpkg|jsdelivr)' dist --include='*.js' --include='*.html' | head -1 | grep -q .; then @@ -176,9 +178,11 @@ jobs: case "$body" in *"$entry"*) echo "$url is serving this build." + npm run check:sdk-dist -- dist "$url" + node scripts/check-sdk-browser.mjs "${url%/}/" exit 0 ;; - *src/main.tsx*) + *src/app/main.tsx*) # This one never resolves itself: it means Pages is pointed at # the source branch, so there is no reason to keep waiting. echo "::error::$url is serving this repository's source index.html instead of the build, so the page is blank. Set Settings -> Pages -> Build and deployment -> Source to 'Deploy from a branch', branch 'gh-pages' / (root)." diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index ae8e286..ded32a9 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -105,7 +105,8 @@ jobs: if: steps.target.outputs.tag != '' uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version: '22.23.5' + # Rebuild historical pre-SDK tags with their original toolchain. + node-version: ${{ hashFiles('released-source/scripts/build-sdk.mjs') != '' && '24.18.0' || '22.23.5' }} package-manager-cache: false - name: Build the standalone edition @@ -150,6 +151,26 @@ jobs: .tag_name == $tag and .name == ("OWASP DecodeBox " + $tag) and any(.assets[]; .name == $name and .state == "uploaded" and .digest == $digest)' + - name: Attach SDK integrity manifest to the tagged release + if: steps.target.outputs.tag != '' + working-directory: released-source + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ steps.target.outputs.tag }} + run: | + # Historical tags predate the SDK distribution. + if [[ -f scripts/check-sdk-dist.mjs ]]; then + npm run check:sdk-dist + manifest="dist/sdk/v1/${RELEASE_TAG#v}/SHA256SUMS" + asset="DecodeBox-SDK-$RELEASE_TAG-SHA256SUMS" + cp "$manifest" "$RUNNER_TEMP/$asset" + if gh release view "$RELEASE_TAG" --json assets --jq '.assets[].name' | grep -Fx "$asset"; then + gh release download "$RELEASE_TAG" --pattern "$asset" --output - | cmp - "$manifest" + else + gh release upload "$RELEASE_TAG" "$RUNNER_TEMP/$asset" + fi + fi + - name: Create or update the Release Please PR if: inputs.release_tag == '' env: diff --git a/.github/workflows/sbom.yml b/.github/workflows/sbom.yml index 965dbcb..3693389 100644 --- a/.github/workflows/sbom.yml +++ b/.github/workflows/sbom.yml @@ -29,7 +29,7 @@ jobs: - name: Use Node LTS uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - node-version: '22' + node-version-file: '.nvmrc' cache: npm - name: Install clean packages diff --git a/.nvmrc b/.nvmrc index 2bd5a0a..a45fd52 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -22 +24 diff --git a/README.md b/README.md index 609157e..bf43a97 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # OWASP DecodeBox +DecodeBox logo + [![OWASP Project: Incubator](https://img.shields.io/badge/OWASP_Project-Incubator-blue.svg)](https://owasp.org/projects/) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE) [![Live Site](https://img.shields.io/badge/demo-decodebox.owasp.org-orange.svg)](https://decodebox.owasp.org/) @@ -21,23 +23,36 @@ evidence you can inspect, and the steps that reach a layer can become an editabl - **Detection.** Follow nested encodings, including encoded fields inside structured data. The analysis shows where it found each indicator and what triggered each security finding. -- **Recipes.** Choose from 504 operations to convert formats, decompress data, compute hashes, +- **Recipes.** Use the operation catalogue to convert formats, decompress data, compute hashes, or extract values. Adjust the arguments, reorder steps, and save the recipe for another input. - **Capture the flag (CTF).** Search decoded layers for flag patterns, review ranked hints for the next transformation, and copy the findings into a Markdown report. -## Development +## JavaScript SDK + +Embed operation discovery, recipes and multilayer analysis in a browser or Java-enabled GraalJS. +The SDK uses the same local processing engine as the workbench. Run `npm ci` and +`npm run build` with Node.js 24. Save this example as `dist/example.html`, open it in a +browser and check the console for `Hello`. + +```html + + + +``` -For local development, clone the [source repository](https://github.com/OWASP/DecodeBox) -and run these commands from its root with Node.js **22.12.0 or later**. +See the [SDK guide](docs/sdk/README.md) for versioned downloads, module imports and integrity +verification. See [runtime integrations](docs/sdk/integrations.md) for TypeScript and ZAP. -```sh -npm ci -npm run dev -``` +## Development -Run `npm test -- --run` to execute the 1,205 tests. Run `npm run build` to produce the static -site and the standalone edition. +Use Node.js 24, run `npm ci`, then `npm run dev`. The [development guide](docs/development.md) +covers regression tests and builds for the site, standalone application and SDK. See the +[documentation index](docs/README.md) for the project layout and API reference. ## Standalone Edition @@ -60,20 +75,6 @@ Contributions to operations should include test vectors. Follow the [OWASP contributing guidelines](https://github.com/OWASP/.github/blob/master/CONTRIBUTING.md) and [Code of Conduct](https://policy.owasp.org/operational/code-of-conduct). -
-Source layout - -- The [engine interface] exposes decoding and analysis to the React [interface components]. -- The engine separates [operations], [format detection], and [recursive analysis]. - -
- -[Interface components]: src/components/ -[engine interface]: src/engine/index.ts -[operations]: src/engine/operations/ -[format detection]: src/engine/detection/ -[recursive analysis]: src/engine/analysis/ - ## Project Leader [Mohammad Hossein Sadeghian](https://github.com/m4sh-wacker) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..53efa8b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,10 @@ +# DecodeBox documentation + +Use the [workbench](https://decodebox.owasp.org/) to inspect data interactively, or embed the +same operations and analysis engine in an application. + +- [Architecture](architecture.md) describes the workbench, worker, engine and runtime providers. +- [Development](development.md) covers local development, tests, builds and publishing. +- [JavaScript SDK](sdk/README.md) covers installation-free loading, distribution and versioning. +- [API reference](sdk/api-reference.md) documents inputs, options, results and failure handling. +- [Integrations](sdk/integrations.md) covers browsers, TypeScript, GraalJS and ZAP. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..bc011cd --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,24 @@ +# Architecture + +The React entry point lives in [src/app](../src/app/). Components, hooks, Zustand state, +translations and styles have their own directories under `src/`. UI conveniences such as +favorites, recipe sharing and browser storage belong to the application. + +The application calls the [engine façade](../src/engine/index.ts), which loads the processing +code on demand. The [worker](../src/engine/worker/) handles work away from the UI thread. +The standalone HTML embeds its scripts, styles and fonts and runs the engine on the main thread. + +The [operation registry](../src/engine/operations/index.ts) owns operation IDs, arguments, +metadata and implementations. [Core](../src/engine/core/) executes recipes and handles bytes. +Detection, recursive analysis, inspection and CTF hints use these same operations. +Engine regression tests live in [src/engine/tests](../src/engine/tests/). + +The [SDK](../src/sdk/index.ts) validates requests and exposes detached registry metadata. +The classic entry point installs the global object. The module entry point exports the same API. +Neither calls React, the application store or the worker client. + +Platform services implement the [runtime interface](../src/engine/runtime/provider.ts). +The web provider uses native browser primitives. The SDK selects the Java provider when GraalJS +exposes Java interop. It uses JCA, SecureRandom, in-memory ZIP streams and Java time zone rules. +Bundled encoding and URL parsers cover APIs that plain GraalJS lacks. The host controls access +to Java classes. New adapters belong behind this internal interface. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..40b487a --- /dev/null +++ b/docs/development.md @@ -0,0 +1,44 @@ +# Development + +Use Node.js 24 for development and distribution. CI also verifies Node.js 22.12 or later in the +22.x series. Install the locked dependencies at the repository root. + +```sh +npm ci +npm run dev +``` + +Before submitting changes, run the same checks as CI. + +```sh +npm run lint +npm run typecheck +npm test -- --run +npm run build +npm run check:sdk-dist +``` + +The build writes the site to `dist/`, the offline application to `dist/decodebox.html`, and +the SDK to the [distribution paths](sdk/README.md#distribution). Use `npm run preview` for +the site, or open the standalone file from disk. `npm run build:sdk` rebuilds the SDK alone. +The distribution check executes both module formats and verifies alias bytes and release hashes. +CI also loads every JavaScript entry point in Chrome and checks SHA-256 with the Java provider. +To run the browser check against a local preview, use the URL printed by Vite. + +```sh +node scripts/check-sdk-browser.mjs http://localhost:4173/ +``` + +## Changes and releases + +Add operations to the existing registry and supply operation-specific regression vectors. +Keep platform-dependent services in the runtime providers. Changes to public SDK functions +also need contract tests in [src/sdk/sdk.test.ts](../src/sdk/sdk.test.ts) and an API reference +update. Submit changes on a temporary branch targeting `main`. + +Release Please manages the project version. The SDK's API major is independent of that version. +The Pages workflow builds from source, carries forward previous SDK releases and the configured +custom domain, and publishes generated files to the root of `gh-pages`. It stops if an existing +version directory would change. A changed release artifact needs a new engine version through +the normal release process. For tags that contain the SDK, the release workflow attaches +the matching checksum manifest. Production bundles and test output stay outside the source tree. diff --git a/docs/sdk/README.md b/docs/sdk/README.md new file mode 100644 index 0000000..f27fc61 --- /dev/null +++ b/docs/sdk/README.md @@ -0,0 +1,59 @@ +# JavaScript SDK + +DecodeBox exposes the workbench engine to browsers and Java-enabled GraalJS. Processing takes +place in the consuming runtime. The `/api` resource distributes the classic JavaScript SDK. +There is no REST endpoint for submitting data. + +## Quick start + +From the repository root with Node.js 24 installed, run `npm ci` and `npm run build`. +Save the following as `dist/example.html`, alongside the generated `api.js`. Open it in +a browser and look for `Hello` in the developer console. This example works offline once built. + +```html + + + +``` + +## Distribution + +| Format | Following the current build | Fixed engine release | +| --- | --- | --- | +| Classic | `/api`, `/api.js`, `/sdk/decodebox.js`, `/sdk/v1/decodebox.js` | `/sdk/v1/{engineVersion}/decodebox.js` | +| ES module | `/sdk/decodebox.mjs`, `/sdk/v1/decodebox.esm.js` | `/sdk/v1/{engineVersion}/decodebox.mjs` | +| Module declarations | `/sdk/decodebox.d.mts` | `/sdk/v1/{engineVersion}/decodebox.d.mts` | + +The integration build also emits `/sdk/v1/{engineVersion}/SHA256SUMS`. The API version tracks +the public contract. The engine version follows the project's release. Applications that rely +on particular operation behavior can pin a release and verify its bytes. + +Publication at `https://decodebox.owasp.org` is pending deployment. GitHub Pages controls +the response type of `/api`. Use `/api.js` for hosts that require a JavaScript MIME type +and the module path for imports. The classic bundle carries a UTF-8 signature for pages with +a legacy character encoding. + +## Integrity and offline use + +For an official release that includes the SDK, obtain `DecodeBox-SDK-vX.Y.Z-SHA256SUMS` +from the corresponding [OWASP release](https://github.com/OWASP/DecodeBox/releases). +Download the three versioned files into one directory and run the following there, +substituting the actual release tag. + +```sh +sha256sum -c DecodeBox-SDK-vX.Y.Z-SHA256SUMS +``` + +Use the hash of the exact file your integration loads. A digest fetched alongside a file can +detect corruption. Establish provenance through a separately trusted release or a pin supplied +by your administrator. The Pages manifest alone cannot authenticate the publisher. + +You can serve the verified files from your own static origin, next to the consuming app, or +load the classic bundle from disk. A local copy includes the engine and its dependencies. +Processing requires no external network access or package installation. + +See the [API reference](api-reference.md) and [runtime integrations](integrations.md). diff --git a/docs/sdk/api-reference.md b/docs/sdk/api-reference.md new file mode 100644 index 0000000..de9d301 --- /dev/null +++ b/docs/sdk/api-reference.md @@ -0,0 +1,74 @@ +# SDK API reference + +The classic bundle exposes `globalThis.DecodeBox`. ES modules provide a default export, +a named `DecodeBox`, individual methods and the `DecodeBoxError` class. Initialization installs +the classic namespace synchronously. Await `ready` before beginning work. + +| Member | Result | +| --- | --- | +| `apiVersion`, `engineVersion` | Public contract and engine release version strings. | +| `capabilities()` | Active runtime, available crypto, randomness, compression formats, charsets and size limits. | +| `listOperations()` | Detached operation definitions with stable IDs, aliases and argument metadata. | +| `getOperation(id)` | One definition, or `null` for an unknown ID. | +| `executeOperation(id, input, args?)` | Promise of a string. Rejects on validation or execution failure. | +| `bake(input, recipe)` | Promise of output, output type, byte length, elapsed time, completed operation IDs and an optional step error. | +| `detect(input)` | Ranked candidates with evidence, previews and recipe steps. | +| `autoDecode(input, options?)` | Tree of decoded layers with stopping reasons. | +| `identify(input)` | Hash identification or `null`. | +| `analyse(input, options?)` | Analysis tree, indicators, findings and truncation information. | +| `inspect(input, {decode?, analyse?}?)` | Decoded root and analysis together. | +| `hints(input, options?)` | CTF flags and suggested transformations. | + +Processing and analysis methods return promises. Discovery and capability methods are synchronous. + +## Discovery, arguments and recipes + +```js +const op = DecodeBox.getOperation("to-base64"); +console.log(op.id, op.args.map(({ name, value }) => [name, value])); +const digest = await DecodeBox.executeOperation("sha-256", "abc"); +const recipe = [{ opId: "gzip" }, { opId: "gunzip" }, { opId: "to-base64" }]; +const result = await DecodeBox.bake(Uint8Array.of(0, 128, 255), recipe); +if (result.error) throw new Error(result.error.message); +console.log(digest, result.output); // binary round trip: AID/ +``` + +Omitted arguments use the values in the operation definition. Supply exact argument names +and the declared types, options and ranges. A toggle-string accepts a string or +`{ value, format }` using one of its `toggleValues`. A recipe accepts an array of +`{ opId, args?, disabled? }`, engine steps returned by detection, or an object with a +`steps` array. Unknown IDs, unknown arguments and invalid option values fail validation. + +Strings carry text. Supply a `Uint8Array` or `ArrayBuffer` for bytes; views preserve their +offset and length. Binary operation results are strings with one code unit per byte. +Convert a binary result with `Uint8Array.from(output, c => c.charCodeAt(0))`. For Unicode text, +use the operation's charset setting where available. The output type on a recipe is descriptive. + +## Detection and bounded analysis + +```js +const input = "U0dWc2JHOD0="; +const candidates = await DecodeBox.detect(input); +const { root, analysis } = await DecodeBox.inspect(input, { + decode: { maxDepth: 4 }, analyse: { maxNodes: 32 }, +}); +console.log(candidates.length, root, analysis); +``` + +Automatic decoding defaults to depth 64, 10,000 ms and confidence threshold 0.55. Analysis +defaults to depth 64, 128 nodes, 10,000 ms and threshold 0.5. Both accept up to 60,000 ms. +Analysis accepts at most 1,024 nodes. Hints accept a format string, depth and time budget. + +## Errors and limits + +Inspect `error.code` on rejected SDK validation and operation calls. Codes are +`INVALID_INPUT`, `UNKNOWN_OPERATION`, `LIMIT_EXCEEDED` and `OPERATION_FAILED`. +A recipe that fails inside the engine resolves with `error.stepIndex` and `error.message`; +validation can reject the recipe before execution begins. Check both outcomes. + +Inputs and aggregate string arguments are limited to 4 MiB in bytes or UTF-16 code units. +Recipes accept up to 128 steps. Step output and decompression are bounded at 16 MiB. +Some formats and algorithms impose tighter limits. Time budgets are cooperative. A synchronous +regular expression, KDF or host operation can occupy its thread until it returns. Execute +untrusted recipes in a terminable worker or a resource-limited host process when a hard wall +clock or memory limit is required. diff --git a/docs/sdk/integrations.md b/docs/sdk/integrations.md new file mode 100644 index 0000000..f17f38f --- /dev/null +++ b/docs/sdk/integrations.md @@ -0,0 +1,82 @@ +# Runtime integrations + +## Browser and TypeScript + +Load a classic script as shown in the [quick start](README.md#quick-start), or import the ES +module in a module script. Serve the file with a JavaScript MIME type. Cross-origin imports +also require CORS. For a restrictive CSP, serve a verified copy from an allowed origin. +Browser cryptography requires the host's secure-context APIs. + +```js +import DecodeBox from "./sdk/decodebox.mjs"; +await DecodeBox.ready; +const encoded = await DecodeBox.executeOperation("to-base64", "Hello"); +console.log(encoded); // SGVsbG8= +``` + +For TypeScript, keep `decodebox.d.mts` next to `decodebox.mjs` and use a resolver that +understands ESM declarations, such as `NodeNext` or `Bundler`. + +```ts +import sdk, { type Step } from "./sdk/decodebox.mjs"; +const steps: Step[] = [{ opId: "from-base64" }]; +const result = await sdk.bake("SGVsbG8=", steps); +if (result.error) throw new Error(result.error.message); +console.log(result.output); // Hello +``` + +Node.js 22.12+ and 24 can also import the locally built `./sdk/decodebox.mjs` from an +ES module beside the `sdk` directory. The example above uses only the shared Web APIs. + +The web provider uses Web Crypto, secure random bytes, platform encoders, URL parsing and +compression streams. Inspect `capabilities()` for the actual host. Updating browser or JDK +time zone data can change historical abbreviations. + +## GraalJS + +Supply the verified classic bundle as a local script to a Java-enabled GraalJS context. +Shell-style `load` and `print` must be available for this example. + +```js +load("decodebox.js"); +DecodeBox.ready + .then(() => DecodeBox.executeOperation("sha-256", "abc")) + .then(print); +``` + +Java class lookup and access to the provider's JCA, time, encoding, byte-array and compression +services must be permitted by the embedding host. Restrict host access to trusted scripts. +Loading by URL requires host I/O and a GraalJS configuration permitting `js.load-from-url`. +A locally verified bundle avoids granting remote-loading permission. Processing makes no +outbound requests. Promises settle at the owning context's microtask checkpoints. Operations +that sleep or call synchronous Java code occupy that thread. The provider checks its deadline +after a blocking call returns. Hosts that require a hard deadline must enforce it externally. + +The Java adapter keeps JCA keys and secret bytes in the provider instance that created them. +Handles carry read-only metadata. Only an extractable key can be exported. For JWK conversion, +the adapter accepts two-prime RSA private keys with complete CRT fields, and P-256, P-384 or +P-521 EC keys. It checks declared uses, algorithm identifiers and public/private components. +Choose the matching RSA hash in the JWK to PEM operation. + +## ZAP + +In the Script Console, select **Stand Alone** and **ECMAScript : Graal.js**. Set the +`DECODEBOX_SDK` environment variable to the absolute path to a verified local classic bundle +before starting ZAP. Run this script and check its output in the console. + +```js +const path = Java.type("java.lang.System").getenv("DECODEBOX_SDK"); +if (!path) throw new Error("Set DECODEBOX_SDK to a verified local file"); +load(String(path)); +DecodeBox.ready.then(async () => { + const output = await DecodeBox.executeOperation("from-base64", "SGVsbG8gWkFQ"); + if (output !== "Hello ZAP") throw new Error("Unexpected decoded text"); + print(output); +}); +``` + +The separate [native ZAP add-on](https://github.com/m4sh-wacker/DecodeBox-ZAP-Addon) +has its own trust policy. It checks SDK size, API major and SHA-256. A changed bundle needs +a separately trusted digest or the add-on's supported approval process. A plain checksum list +does not satisfy its signed-manifest mode. Host permissions and trusted pins are managed by the +consumer. See [integrity and offline use](README.md#integrity-and-offline-use). diff --git a/eslint.config.js b/eslint.config.js index 461c0ee..ee2dd75 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -6,6 +6,17 @@ import reactRefresh from 'eslint-plugin-react-refresh'; export default tseslint.config( { ignores: ['dist', 'node_modules'] }, + { + files: ['scripts/*.mjs', 'src/engine/runtime/*.js'], + extends: [js.configs.recommended], + languageOptions: { globals: { ...globals.node, Java: 'readonly' } }, + rules: { + 'no-empty': ['error', { allowEmptyCatch: true }], + 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], + 'no-eval': 'error', + 'no-new-func': 'error', + }, + }, { extends: [js.configs.recommended, ...tseslint.configs.recommended], files: ['**/*.{ts,tsx}'], diff --git a/index.html b/index.html index 38bba43..33e0149 100644 --- a/index.html +++ b/index.html @@ -50,6 +50,6 @@ DecodeBox runs entirely in your browser and needs JavaScript enabled. Nothing you paste is ever uploaded — the processing has to happen locally, which is the point. - + diff --git a/package-lock.json b/package-lock.json index db18443..86d7661 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,9 +9,12 @@ "version": "0.2.0", "license": "Apache-2.0", "dependencies": { + "@exodus/bytes": "1.16.0", + "@noble/curves": "2.4.0", "lucide-react": "1.64.0", "react": "19.3.1", "react-dom": "19.3.1", + "whatwg-url": "16.0.1", "zustand": "5.0.16" }, "devDependencies": { @@ -21,12 +24,14 @@ "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "@vitejs/plugin-react": "6.1.2", + "dts-bundle-generator": "9.5.1", "eslint": "10.13.0", "eslint-plugin-react-hooks": "7.1.1", "eslint-plugin-react-refresh": "0.5.7", "fast-check": "4.10.2", "globals": "16.5.0", "happy-dom": "21.0.4", + "playwright-core": "1.65.1", "postcss": "8.5.32", "tailwindcss": "4.3.3", "typescript": "5.9.3", @@ -35,7 +40,7 @@ "vitest": "5.0.5" }, "engines": { - "node": ">=22.12.0" + "node": "^22.12.0 || >=24.0.0" } }, "node_modules/@alloc/quick-lru": { @@ -435,6 +440,23 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -575,6 +597,33 @@ "dev": true, "license": "MIT" }, + "node_modules/@noble/curves": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@oxc-project/types": { "version": "0.154.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.154.0.tgz", @@ -1661,6 +1710,32 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1799,6 +1874,41 @@ "node": ">=18" } }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -1863,6 +1973,23 @@ "node": ">=8" } }, + "node_modules/dts-bundle-generator": { + "version": "9.5.1", + "resolved": "https://registry.npmjs.org/dts-bundle-generator/-/dts-bundle-generator-9.5.1.tgz", + "integrity": "sha512-DxpJOb2FNnEyOzMkG11sxO2dmxPjthoVWxfKqWYJ/bI/rT1rvTMktF5EKjAYrRZu6Z6t3NhOUZ0sZ5ZXevOfbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "typescript": ">=5.0.2", + "yargs": "^17.6.0" + }, + "bin": { + "dts-bundle-generator": "dist/bin/dts-bundle-generator.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.458", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.458.tgz", @@ -1870,6 +1997,13 @@ "dev": true, "license": "ISC" }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, "node_modules/enhanced-resolve": { "version": "5.26.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", @@ -2247,6 +2381,16 @@ "node": ">=6.9.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -2366,6 +2510,16 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -2954,6 +3108,19 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/postcss": { "version": "8.5.32", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", @@ -2997,7 +3164,6 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -3061,6 +3227,16 @@ "react": "^19.3.1" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/rolldown": { "version": "1.2.14", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.14.tgz", @@ -3151,6 +3327,34 @@ "dev": true, "license": "MIT" }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/tailwindcss": { "version": "4.3.3", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz", @@ -3227,6 +3431,18 @@ } } }, + "node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -3773,6 +3989,15 @@ } } }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, "node_modules/whatwg-mimetype": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", @@ -3783,6 +4008,20 @@ "node": ">=12" } }, + "node_modules/whatwg-url": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3822,6 +4061,24 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, "node_modules/ws": { "version": "8.23.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", @@ -3844,6 +4101,16 @@ } } }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", @@ -3851,6 +4118,35 @@ "dev": true, "license": "ISC" }, + "node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index cb72468..d1ac6a4 100644 --- a/package.json +++ b/package.json @@ -11,20 +11,25 @@ "url": "https://github.com/OWASP/DecodeBox.git" }, "engines": { - "node": ">=22.12.0" + "node": "^22.12.0 || >=24.0.0" }, "scripts": { "dev": "vite", - "build": "tsc --noEmit && vite build && vite build --mode standalone", + "build": "tsc --noEmit && vite build && vite build --mode standalone && npm run build:sdk", "preview": "vite preview", "lint": "eslint .", "typecheck": "tsc --noEmit", - "test": "vitest" + "test": "vitest", + "build:sdk": "node scripts/build-sdk.mjs", + "check:sdk-dist": "node scripts/check-sdk-dist.mjs" }, "dependencies": { + "@exodus/bytes": "1.16.0", + "@noble/curves": "2.4.0", "lucide-react": "1.64.0", "react": "19.3.1", "react-dom": "19.3.1", + "whatwg-url": "16.0.1", "zustand": "5.0.16" }, "devDependencies": { @@ -34,12 +39,14 @@ "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "@vitejs/plugin-react": "6.1.2", + "dts-bundle-generator": "9.5.1", "eslint": "10.13.0", "eslint-plugin-react-hooks": "7.1.1", "eslint-plugin-react-refresh": "0.5.7", "fast-check": "4.10.2", "globals": "16.5.0", "happy-dom": "21.0.4", + "playwright-core": "1.65.1", "postcss": "8.5.32", "tailwindcss": "4.3.3", "typescript": "5.9.3", diff --git a/scripts/build-sdk.mjs b/scripts/build-sdk.mjs new file mode 100644 index 0000000..a7e4614 --- /dev/null +++ b/scripts/build-sdk.mjs @@ -0,0 +1,78 @@ +import { createHash } from 'node:crypto'; +import { generateDtsBundle } from 'dts-bundle-generator'; +import { build } from 'vite'; +import { readFile, copyFile, mkdir, writeFile, appendFile, unlink } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { aliases, releasePath } from './sdk-paths.mjs'; + +const dir = 'dist' + releasePath; +const projectNotice = (await Promise.all( + ['NOTICE', 'LICENSE'].map((file) => readFile(file, 'utf8')), +)).join('\n').replaceAll('\r\n', '\n'); +await mkdir(dir, { recursive: true }); +for (const [entry, format, name] of [ + ['classic', 'iife', 'decodebox.js'], + ['index', 'es', 'decodebox.mjs'], +]) { + await build({ + configFile: false, + publicDir: false, + resolve: { + // Keep dependency paths in ESM region comments relative to this distribution's project. + preserveSymlinks: true, + conditions: ['module', 'production'], + mainFields: ['module', 'main'], + }, + plugins: [ + { + name: 'whatwg-url-encoding', + enforce: 'pre', + // The parser constructs these encoders at import time. Scope the standard + // implementations to that module so an embedding application's globals stay intact. + transform(code, id) { + if (id.replaceAll('\\', '/').endsWith('/whatwg-url/lib/encoding.js')) { + return ( + "const { TextEncoder, TextDecoder } = require('@exodus/bytes/encoding.js');\n" + code + ); + } + }, + }, + ], + build: { + target: 'es2022', + emptyOutDir: false, + outDir: dir, + minify: 'oxc', + license: { fileName: 'bundled-licenses.txt' }, + lib: { + entry: resolve('src/sdk/' + entry + '.ts'), + name: 'DecodeBoxSDK', + formats: [format], + fileName: () => name, + }, + rolldownOptions: { platform: 'neutral', output: { codeSplitting: false } }, + }, + }); + const licensePath = dir + '/bundled-licenses.txt'; + const notices = projectNotice + '\n' + await readFile(licensePath, 'utf8'); + // Classic scripts can inherit a legacy document encoding when the host omits a charset. + // A UTF-8 signature preserves Unicode literals on extensionless static hosts. + if (format === 'iife') { + const code = await readFile(dir + '/' + name); + await writeFile(dir + '/' + name, Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), code])); + } + await appendFile(dir + '/' + name, '\n/*!\n' + notices.replaceAll('*/', '* /') + '\n*/\n'); + await unlink(licensePath); +} + +const [types] = generateDtsBundle([{ filePath: 'src/sdk/index.ts', output: { noBanner: true, exportReferencedTypes: false } }], { + preferredConfigPath: 'tsconfig.json', +}); +await writeFile(dir + '/decodebox.d.mts', types); +const checksums = []; +for (const [file, paths] of Object.entries(aliases)) { + const digest = createHash('sha256').update(await readFile(dir + '/' + file)).digest('hex'); + checksums.push(digest + ' ' + file); + for (const path of paths) await copyFile(dir + '/' + file, 'dist' + path); +} +await writeFile(dir + '/SHA256SUMS', checksums.join('\n') + '\n'); diff --git a/scripts/check-sdk-browser.mjs b/scripts/check-sdk-browser.mjs new file mode 100644 index 0000000..4de19fc --- /dev/null +++ b/scripts/check-sdk-browser.mjs @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict'; +import { chromium } from 'playwright-core'; +import { aliases, releasePath } from './sdk-paths.mjs'; + +const base = new URL(process.argv[2]); +const consumer = new URL('__sdk_browser_check__', base).href; +const browser = await chromium.launch({ channel: 'chrome' }); +try { + for (const file of ['decodebox.js', 'decodebox.mjs']) { + for (const path of [...aliases[file], releasePath + '/' + file]) { + const url = new URL(path.slice(1), base).href; + const page = await browser.newPage(); + page.on('pageerror', (error) => console.error(url, error.message)); + page.on('console', (message) => { + if (message.type() === 'error') console.error(url, message.text()); + }); + try { + // Leave the document charset unspecified to exercise classic-script decoding. + // Every SDK request, including the extensionless alias, reaches the static host. + await page.route(consumer, (route) => + route.fulfill({ contentType: 'text/html', body: 'Consumer' }), + ); + await page.goto(consumer); + if (file.endsWith('.js')) await page.addScriptTag({ url }); + const output = await page.evaluate(async ({ file, url }) => { + const sdk = file.endsWith('.mjs') ? (await import(url)).default : globalThis.DecodeBox; + await sdk.ready; + return sdk.executeOperation('from-base64', 'SGVsbG8='); + }, { file, url }); + assert.equal(output, 'Hello'); + console.log('Chromium loaded', url); + } finally { + await page.close(); + } + } + } +} finally { + await browser.close(); +} diff --git a/scripts/check-sdk-dist.mjs b/scripts/check-sdk-dist.mjs new file mode 100644 index 0000000..fb5ba70 --- /dev/null +++ b/scripts/check-sdk-dist.mjs @@ -0,0 +1,52 @@ +import { createHash } from 'node:crypto'; +import { pathToFileURL } from 'node:url'; +import { readFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { aliases, releasePath } from './sdk-paths.mjs'; + +const root = process.argv[2] ?? 'dist'; +const origin = process.argv[3]; +const checksums = []; + +async function readArtifact(path) { + const bytes = await readFile(join(root, path)); + if (!bytes.length) throw new Error('Empty SDK artifact: ' + join(root, path)); + if (origin) { + const url = new URL(path.slice(1), origin.replace(/\/?$/, '/')); + const response = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(30000) }); + const type = (response.headers.get('content-type') ?? '').split(';')[0]; + if (response.status !== 200 || !Buffer.from(await response.arrayBuffer()).equals(bytes)) + throw new Error('Unexpected HTTP status or content for ' + url + ' (' + response.status + ')'); + if (path === '/api' && type === 'application/octet-stream' && + !response.headers.has('x-content-type-options')) { + console.log('/api is served as binary data. Use /api.js for strict MIME consumers.'); + } else if ((path === '/api' || /\.m?js$/.test(path)) && + !/^(text|application)\/(java|ecma)script$/i.test(type)) { + throw new Error('Unexpected script MIME type for ' + url + ': ' + type); + } + } + return bytes; +} + +for (const [file, paths] of Object.entries(aliases)) { + const source = releasePath + '/' + file; + const expected = await readArtifact(source); + checksums.push(createHash('sha256').update(expected).digest('hex') + ' ' + file); + for (const path of paths) { + if (!(await readArtifact(path)).equals(expected)) { + throw new Error(path + ' differs from ' + source); + } + } + console.log([source, ...paths].join(', ') + ' verified (' + expected.length + ' bytes each)'); +} + +if ((await readArtifact(releasePath + '/SHA256SUMS')).toString() !== checksums.join('\n') + '\n') + throw new Error('SDK release checksums do not match the distribution.'); + +await import(pathToFileURL(resolve(root, 'api.js')).href); +const { default: esm } = await import(pathToFileURL(resolve(root, 'sdk/decodebox.mjs')).href); +for (const sdk of [globalThis.DecodeBox, esm]) { + await sdk.ready; + if (!sdk.getOperation('to-base64') || await sdk.executeOperation('to-base64', 'Hi') !== 'SGk=') + throw new Error('SDK bundle failed the operation smoke test.'); +} diff --git a/scripts/sdk-paths.mjs b/scripts/sdk-paths.mjs new file mode 100644 index 0000000..b9a6397 --- /dev/null +++ b/scripts/sdk-paths.mjs @@ -0,0 +1,10 @@ +import project from '../package.json' with { type: 'json' }; + +// A version is a single path segment, including when testing a prerelease. +if (!/^\d[0-9A-Za-z.+-]*$/.test(project.version)) throw new Error('Invalid SDK version path.'); +export const releasePath = '/sdk/v1/' + project.version; +export const aliases = { + 'decodebox.js': ['/api', '/api.js', '/sdk/v1/decodebox.js', '/sdk/decodebox.js'], + 'decodebox.mjs': ['/sdk/v1/decodebox.esm.js', '/sdk/decodebox.mjs'], + 'decodebox.d.mts': ['/sdk/decodebox.d.mts'], +}; diff --git a/src/App.tsx b/src/app/App.tsx similarity index 61% rename from src/App.tsx rename to src/app/App.tsx index 75704c2..3124c40 100644 --- a/src/App.tsx +++ b/src/app/App.tsx @@ -1,18 +1,18 @@ import { useEffect } from 'react'; -import { useStore } from './store/useStore'; -import { t } from './i18n/en'; -import { useAnalysis } from './hooks/useAnalysis'; -import { useHotkeys } from './hooks/useHotkeys'; -import { Header } from './components/layout/Header'; -import { Workspace } from './components/layout/Workspace'; -import { ActivityBar } from './components/layout/ActivityBar'; -import { useIsDesktop } from './hooks/useMediaQuery'; -import { StatusBar } from './components/layout/StatusBar'; -import { CtfView } from './components/ctf/CtfView'; -import { HelpDialog } from './components/ui/HelpDialog'; -import { ShareDialog } from './components/ui/ShareDialog'; -import { RecipeLibrary } from './components/ui/RecipeLibrary'; -import { DownloadDialog } from './components/ui/DownloadDialog'; +import { useStore } from '../store/useStore'; +import { t } from '../i18n/en'; +import { useAnalysis } from '../hooks/useAnalysis'; +import { useHotkeys } from '../hooks/useHotkeys'; +import { Header } from '../components/layout/Header'; +import { Workspace } from '../components/layout/Workspace'; +import { ActivityBar } from '../components/layout/ActivityBar'; +import { useIsDesktop } from '../hooks/useMediaQuery'; +import { StatusBar } from '../components/layout/StatusBar'; +import { CtfView } from '../components/ctf/CtfView'; +import { HelpDialog } from '../components/ui/HelpDialog'; +import { ShareDialog } from '../components/ui/ShareDialog'; +import { RecipeLibrary } from '../components/ui/RecipeLibrary'; +import { DownloadDialog } from '../components/ui/DownloadDialog'; export default function App() { const loadOperations = useStore((s) => s.loadOperations); diff --git a/src/main.tsx b/src/app/main.tsx similarity index 79% rename from src/main.tsx rename to src/app/main.tsx index ec939a8..d17d1b8 100644 --- a/src/main.tsx +++ b/src/app/main.tsx @@ -1,8 +1,8 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import App from './App'; -import { ErrorBoundary } from './components/ui/ErrorBoundary'; -import './styles/theme.css'; +import { ErrorBoundary } from '../components/ui/ErrorBoundary'; +import '../styles/theme.css'; const container = document.getElementById('root'); if (!container) throw new Error('Root element is missing from index.html'); diff --git a/src/site.test.ts b/src/app/site.test.ts similarity index 100% rename from src/site.test.ts rename to src/app/site.test.ts diff --git a/src/engine/analysis/explore.ts b/src/engine/analysis/explore.ts index e02841c..d74da10 100644 --- a/src/engine/analysis/explore.ts +++ b/src/engine/analysis/explore.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import type { Layer, RecipeStep } from '../types'; import { getOperation } from '../operations'; import { byteLength, previewText } from '../core/bytes'; @@ -36,7 +37,7 @@ interface Budget { } function exhausted(budget: Budget, options: AnalyseOptions): boolean { - if (budget.nodes >= options.maxNodes || performance.now() > budget.deadline) { + if (budget.nodes >= options.maxNodes || runtime.now() > budget.deadline) { budget.truncated = true; return true; } @@ -187,7 +188,7 @@ export async function explore( const budget: Budget = { nodes: 1, - deadline: performance.now() + options.budgetMs, + deadline: runtime.now() + options.budgetMs, seen: new Set([input]), truncated: false, }; diff --git a/src/engine/analysis/index.ts b/src/engine/analysis/index.ts index f4c80bf..8f818ce 100644 --- a/src/engine/analysis/index.ts +++ b/src/engine/analysis/index.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import type { Analysis, AnalyseOptions } from './types'; import { DEFAULT_ANALYSE_OPTIONS, SEVERITY_ORDER } from './types'; import { explore, type Spine } from './explore'; @@ -10,7 +11,7 @@ export async function analyse( options: Partial = {}, spine: Spine = null, ): Promise { - const started = performance.now(); + const started = runtime.now(); const settings = { ...DEFAULT_ANALYSE_OPTIONS, ...options }; const { root, nodes, truncated } = await explore(input, settings, spine); @@ -32,7 +33,7 @@ export async function analyse( maxDepth: Math.max(...all.map((node) => node.depth)), indicators, findings, - durationMs: performance.now() - started, + durationMs: runtime.now() - started, truncated, }; } diff --git a/src/engine/core/bake.ts b/src/engine/core/bake.ts index d634554..852b724 100644 --- a/src/engine/core/bake.ts +++ b/src/engine/core/bake.ts @@ -1,3 +1,5 @@ +import { checkSize } from '../runtime/limits'; +import { runtime } from '../runtime'; import type { BakeResult, OperationArg, OutputType, Recipe, RecipeStep } from '../types'; import { OperationError } from '../types'; import { getOperation } from '../operations'; @@ -28,21 +30,6 @@ function classify(output: string): OutputType { return 'text'; } -async function withTimeout(work: Promise, opName: string, budget: number): Promise { - let timer: ReturnType; - const timeout = new Promise((_, reject) => { - timer = setTimeout( - () => reject(new OperationError(`${opName} took longer than ${budget}ms.`)), - budget, - ); - }); - try { - return await Promise.race([work, timeout]); - } finally { - clearTimeout(timer!); - } -} - function unescape(text: string): string { return text .replace(/\\n/g, '\n') @@ -114,10 +101,11 @@ async function runStep( const budget = operation.budgetMs ?? STEP_TIMEOUT_MS; if (budget > STEP_TIMEOUT_MS) { - machine.deadline = Math.max(machine.deadline, performance.now() + budget + 1000); + machine.deadline = Math.max(machine.deadline, runtime.now() + budget + 1000); } - return withTimeout(Promise.resolve(operation.run(value, prepared.args)), operation.name, budget); + return runtime.timed(() => operation.run(value, prepared.args), budget, + () => new OperationError(operation.name + ' took longer than ' + budget + 'ms.')); } async function execute( @@ -130,7 +118,7 @@ async function execute( let pc = 0; while (pc < steps.length) { - if (performance.now() > machine.deadline) { + if (runtime.now() > machine.deadline) { throw new OperationError(`The recipe ran for longer than ${RECIPE_TIMEOUT_MS}ms.`); } @@ -212,6 +200,7 @@ async function execute( ); const results: string[] = []; + let total = 0; for (const branch of branches) { try { results.push(await execute(body, branch, machine, offset + pc + 1)); @@ -219,6 +208,8 @@ async function execute( if (error instanceof ReturnSignal || !forgiving) throw error; results.push(branch); } + total += results[results.length - 1]!.length + (results.length > 1 ? joinWith.length : 0); + checkSize(total); } value = results.join(joinWith); @@ -254,6 +245,7 @@ async function execute( if (error instanceof ReturnSignal || !forgiving) throw error; out += found[0]; } + checkSize(out.length); cursor = at + found[0].length; } @@ -267,6 +259,7 @@ async function execute( pc++; } } + checkSize(value.length); } catch (error) { completed = error instanceof ReturnSignal && step.opId === 'return'; if (error instanceof ReturnSignal) throw error; @@ -285,7 +278,7 @@ async function execute( } export async function bake(input: string, recipe: Recipe): Promise { - const started = performance.now(); + const started = runtime.now(); const machine: Machine = { completed: new Set(), registers: [], @@ -302,7 +295,7 @@ export async function bake(input: string, recipe: Recipe): Promise { output, outputType: classify(output), byteLength: byteLength(output), - durationMs: performance.now() - started, + durationMs: runtime.now() - started, }; } catch (error) { if (error instanceof ReturnSignal) { @@ -311,7 +304,7 @@ export async function bake(input: string, recipe: Recipe): Promise { output: error.value, outputType: classify(error.value), byteLength: byteLength(error.value), - durationMs: performance.now() - started, + durationMs: runtime.now() - started, }; } @@ -320,7 +313,7 @@ export async function bake(input: string, recipe: Recipe): Promise { output: '', outputType: 'text', byteLength: 0, - durationMs: performance.now() - started, + durationMs: runtime.now() - started, error: { stepIndex: machine.failedAt ?? 0, message: diff --git a/src/engine/core/bytes.ts b/src/engine/core/bytes.ts index 264c14e..fc3234c 100644 --- a/src/engine/core/bytes.ts +++ b/src/engine/core/bytes.ts @@ -1,15 +1,16 @@ +import { runtime } from '../runtime'; export function toBytes(text: string): Uint8Array { - return new TextEncoder().encode(text); + return runtime.encode(text); } export function fromBytes(bytes: Uint8Array): string { - return new TextDecoder('utf-8', { fatal: false }).decode(bytes); + return runtime.decoder('utf-8', { fatal: false }).decode(bytes); } export function tryDecodeUtf8(bytes: Uint8Array): string | null { try { - return new TextDecoder('utf-8', { fatal: true }).decode(bytes); + return runtime.decoder('utf-8', { fatal: true }).decode(bytes); } catch { return null; } diff --git a/src/engine/core/charsets.ts b/src/engine/core/charsets.ts index e2ef27d..b5b4fb0 100644 --- a/src/engine/core/charsets.ts +++ b/src/engine/core/charsets.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { bytesToLatin1 } from './bytes'; @@ -54,7 +55,7 @@ const DEFINITIONS: CharsetDefinition[] = [ function supported(definition: CharsetDefinition): boolean { if (definition.identity) return true; try { - new TextDecoder(definition.label); + runtime.decoder(definition.label); return true; } catch { return false; @@ -85,7 +86,7 @@ const CP1252_C1 = [ const CP1252_IS_HONEST = (() => { try { - return new TextDecoder('windows-1252').decode(new Uint8Array([0x80])) === '€'; + return runtime.decoder('windows-1252').decode(new Uint8Array([0x80])) === '€'; } catch { return false; } @@ -104,7 +105,7 @@ export function decodeCharset(name: string, bytes: Uint8Array): string { const definition = definitionFor(name); if (definition.identity) return bytesToLatin1(bytes); if (definition.label === 'windows-1252' && !CP1252_IS_HONEST) return decodeCp1252(bytes); - return new TextDecoder(definition.label).decode(bytes); + return runtime.decoder(definition.label).decode(bytes); } @@ -114,7 +115,7 @@ function reverseTable(definition: CharsetDefinition): Map { const cached = reverseTables.get(definition.label); if (cached) return cached; - const decoder = new TextDecoder(definition.label, { fatal: true }); + const decoder = runtime.decoder(definition.label, { fatal: true }); const table = new Map(); const patched = definition.label === 'windows-1252' && !CP1252_IS_HONEST; @@ -174,7 +175,7 @@ export function encodeCharset(name: string, text: string): Uint8Array { } return out; } - if (definition.label === 'utf-8') return new TextEncoder().encode(text); + if (definition.label === 'utf-8') return runtime.encode(text); if (definition.label === 'utf-16le') return encodeUtf16(text, true); if (definition.label === 'utf-16be') return encodeUtf16(text, false); diff --git a/src/engine/core/image.ts b/src/engine/core/image.ts index 3c50ec3..d4aee7a 100644 --- a/src/engine/core/image.ts +++ b/src/engine/core/image.ts @@ -1,3 +1,5 @@ +import { checkSize, MAX_OUTPUT } from '../runtime/limits'; +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { imageMime, isBmp, isPng } from './imageSignature'; @@ -12,7 +14,7 @@ export interface Image { const PNG_MAGIC = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; -const MAX_PIXELS = 64 * 1024 * 1024; +const MAX_PIXELS = MAX_OUTPUT / 4; export function makeImage(width: number, height: number): Image { if (width <= 0 || height <= 0) throw new OperationError('An image needs a positive size.'); @@ -23,14 +25,8 @@ export function makeImage(width: number, height: number): Image { } -async function inflate(bytes: Uint8Array): Promise { - const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate')); - return new Uint8Array(await new Response(stream).arrayBuffer()); -} - async function deflate(bytes: Uint8Array): Promise { - const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new CompressionStream('deflate')); - return new Uint8Array(await new Response(stream).arrayBuffer()); + return runtime.transform(bytes, 'deflate', true); } @@ -158,6 +154,11 @@ export async function decodePng(bytes: Uint8Array): Promise { if (channels === undefined) throw new OperationError(`Colour type ${colourType} is not one PNG defines.`); if (![1, 2, 4, 8, 16].includes(depth)) throw new OperationError(`A bit depth of ${depth} is not one PNG defines.`); + const bitsPerPixel = channels * depth; + const rowBytes = Math.ceil((bitsPerPixel * width) / 8); + const bytesPerPixel = Math.max(1, bitsPerPixel >> 3); + const inflatedLength = (rowBytes + 1) * height; + checkSize(inflatedLength); const image = makeImage(width, height); const total = idat.reduce((sum, part) => sum + part.length, 0); @@ -170,14 +171,13 @@ export async function decodePng(bytes: Uint8Array): Promise { let raw: Uint8Array; try { - raw = await inflate(joined); - } catch { + raw = await runtime.transform(joined, 'deflate', false, inflatedLength); + if (raw.length !== inflatedLength) throw new OperationError('PNG scanline size mismatch.'); + } catch (error) { + if (error instanceof OperationError) throw error; throw new OperationError("The PNG's compressed data could not be decompressed: the file is damaged."); } - const bitsPerPixel = channels * depth; - const rowBytes = Math.ceil((bitsPerPixel * width) / 8); - const bytesPerPixel = Math.max(1, bitsPerPixel >> 3); const pixels = unfilter(raw, width, height, bytesPerPixel, rowBytes); const sample = (row: number, index: number): number => { diff --git a/src/engine/core/uid.ts b/src/engine/core/uid.ts index a7b3f4e..1dcf750 100644 --- a/src/engine/core/uid.ts +++ b/src/engine/core/uid.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; /* * Identifiers for recipe steps, analysis nodes and saved recipes. They only have to be unique * within one browser, never secret, but drawing them from the platform's CSPRNG costs nothing and @@ -6,6 +7,6 @@ * may be. */ export function randomId(prefix: string): string { - const [high = 0, low = 0] = crypto.getRandomValues(new Uint32Array(2)); + const [high = 0, low = 0] = runtime.random(new Uint32Array(2)); return `${prefix}-${high.toString(36)}${low.toString(36)}`; } diff --git a/src/engine/ctf/hints.ts b/src/engine/ctf/hints.ts index d145477..04bec3d 100644 --- a/src/engine/ctf/hints.ts +++ b/src/engine/ctf/hints.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import type { Layer, RecipeStep } from '../types'; import { getOperation } from '../operations'; import { previewText } from '../core/bytes'; @@ -333,7 +334,7 @@ export async function ctfHints( input: string, options: Partial = {}, ): Promise { - const started = performance.now(); + const started = runtime.now(); const opts = { ...DEFAULT_CTF_OPTIONS, ...options }; const deadline = started + opts.budgetMs; @@ -361,7 +362,7 @@ export async function ctfHints( for (const site of sites) { flags.push(...findFlags(site.text, site.depth, site.path, opts.format)); - if (performance.now() > deadline) { + if (runtime.now() > deadline) { truncated = true; break; } @@ -411,6 +412,6 @@ export async function ctfHints( hints: ranked.slice(0, MAX_HINTS), layers: sites.length, truncated: truncated || ranked.length > MAX_HINTS, - durationMs: performance.now() - started, + durationMs: runtime.now() - started, }; } diff --git a/src/engine/detection/autoDecode.ts b/src/engine/detection/autoDecode.ts index e658a80..d2f364a 100644 --- a/src/engine/detection/autoDecode.ts +++ b/src/engine/detection/autoDecode.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import type { Candidate, Layer, RecipeStep, Terminus, TerminusReason } from '../types'; import { getOperation } from '../operations'; import { byteLength } from '../core/bytes'; @@ -138,7 +139,7 @@ export async function autoDecode( ): Promise { const opts = { ...DEFAULT_OPTIONS, ...options }; const limit = Math.max(1, Math.min(opts.maxDepth, MAX_AUTO_DEPTH)); - const deadline = performance.now() + opts.budgetMs; + const deadline = runtime.now() + opts.budgetMs; const root: Layer = { id: 'input', @@ -171,7 +172,7 @@ export async function autoDecode( node.terminus = ending('plain'); return root; } - if (performance.now() > deadline) { + if (runtime.now() > deadline) { node.terminus = ending('budget'); return root; } diff --git a/src/engine/heavy.ts b/src/engine/heavy.ts index 23812e0..3eadd9e 100644 --- a/src/engine/heavy.ts +++ b/src/engine/heavy.ts @@ -1,5 +1,5 @@ -export { publicDefinitions, getOperation } from './operations'; +export { publicDefinitions, publicDefinition, getOperation } from './operations'; export { bake } from './core/bake'; export { detect } from './detection/detect'; export { autoDecode } from './detection/autoDecode'; diff --git a/src/engine/operations/amf.ts b/src/engine/operations/amf.ts index 4c856ed..8007cae 100644 --- a/src/engine/operations/amf.ts +++ b/src/engine/operations/amf.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -73,7 +74,7 @@ class Reader { utf8(length: number): string { this.need(length); - const text = new TextDecoder().decode(this.bytes.subarray(this.at, this.at + length)); + const text = runtime.decoder().decode(this.bytes.subarray(this.at, this.at + length)); this.at += length; return text; } @@ -417,7 +418,7 @@ function writeAmf0(w: Writer, value: Json, depth: number): void { w.byte(0x00); w.double(value); } else if (typeof value === 'string') { - const utf8 = new TextEncoder().encode(value); + const utf8 = runtime.encode(value); if (utf8.length > 0xffff) { w.byte(0x0c); w.u32(utf8.length); @@ -433,7 +434,7 @@ function writeAmf0(w: Writer, value: Json, depth: number): void { } else { w.byte(0x03); for (const [key, child] of Object.entries(value)) { - const utf8 = new TextEncoder().encode(key); + const utf8 = runtime.encode(key); w.u16(utf8.length); w.bytes(utf8); writeAmf0(w, child, depth + 1); @@ -444,7 +445,7 @@ function writeAmf0(w: Writer, value: Json, depth: number): void { } function writeAmf3String(w: Writer, text: string): void { - const utf8 = new TextEncoder().encode(text); + const utf8 = runtime.encode(text); w.u29((utf8.length << 1) | 1); w.bytes(utf8); } diff --git a/src/engine/operations/archives.ts b/src/engine/operations/archives.ts index f0d626f..ae90d51 100644 --- a/src/engine/operations/archives.ts +++ b/src/engine/operations/archives.ts @@ -1,13 +1,14 @@ +import { checkSize } from '../runtime/limits'; +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; -const utf8 = new TextEncoder(); + async function deflateRaw(bytes: Uint8Array): Promise { - const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new CompressionStream('deflate-raw')); - return new Uint8Array(await new Response(stream).arrayBuffer()); + return runtime.transform(bytes, 'deflate-raw', true); } const CRC_TABLE = (() => { @@ -56,7 +57,7 @@ const TAR_BLOCK = 512; function tarHeader(name: string, size: number): Uint8Array { const header = new Uint8Array(TAR_BLOCK); const write = (text: string, at: number, width: number) => { - const bytes = utf8.encode(text.slice(0, width - 1)); + const bytes = runtime.encode(text.slice(0, width - 1)); header.set(bytes, at); }; @@ -161,7 +162,9 @@ function lz4DecompressBlock(bytes: Uint8Array, out: number[]): void { literals += more; } } - for (let i = 0; i < literals && at < bytes.length; i++) out.push(bytes[at++] as number); + if (at + literals > bytes.length) throw new OperationError('Truncated LZ4 literals.'); + checkSize(out.length + literals); + for (let i = 0; i < literals; i++) out.push(bytes[at++] as number); if (at + 1 >= bytes.length) break; const offset = (bytes[at++] as number) | ((bytes[at++] as number) << 8); @@ -176,6 +179,7 @@ function lz4DecompressBlock(bytes: Uint8Array, out: number[]): void { } length += 4; + checkSize(out.length + length); const start = out.length - offset; if (start < 0) throw new OperationError('An LZ4 match points before the start of the data.'); for (let i = 0; i < length; i++) out.push(out[start + i] as number); @@ -297,6 +301,7 @@ function lzStringDecompress(length: number, resetValue: number, at: (index: numb let numBits = 3; let entry = ''; const result: string[] = []; + let outputLength = 1; let position = resetValue; let index = 0; @@ -354,6 +359,8 @@ function lzStringDecompress(length: number, resetValue: number, at: (index: numb throw new OperationError('The compressed stream refers to an unknown dictionary entry.'); } + outputLength += entry.length; + checkSize(outputLength); result.push(entry); dictionary[dictSize++] = word + entry.charAt(0); enlargeIn--; @@ -380,6 +387,7 @@ function lznt1Decompress(bytes: Uint8Array): Uint8Array { const compressed = (header & 0x8000) !== 0; const end = Math.min(at + size, bytes.length); + checkSize(out.length + 4096); if (!compressed) { for (; at < end; at++) out.push(bytes[at] as number); continue; @@ -405,7 +413,8 @@ function lznt1Decompress(bytes: Uint8Array): Uint8Array { const length = (pair & ((1 << shift) - 1)) + 3; const offset = (pair >> shift) + 1; const from = out.length - offset; - if (from < 0) throw new OperationError('An LZNT1 reference points before the chunk.'); + if (out.length - chunkStart + length > 4096) throw new OperationError('LZNT1 chunk exceeds 4 KiB.'); + if (from < chunkStart) throw new OperationError('An LZNT1 reference points before the chunk.'); for (let i = 0; i < length; i++) out.push(out[from + i] as number); } } @@ -437,11 +446,11 @@ export const archiveOperations: Operation[] = [ const content = asBytes(input); const body = deflated ? await deflateRaw(content) : content; - const nameBytes = utf8.encode(name); + const nameBytes = runtime.encode(name); const crc = crc32(content); const local = new Bytes(); - local.add(utf8.encode('PK\x03\x04')); + local.add(runtime.encode('PK\x03\x04')); local.le(20, 2); local.le(0, 2); local.le(deflated ? 8 : 0, 2); @@ -456,7 +465,7 @@ export const archiveOperations: Operation[] = [ local.add(body); const central = new Bytes(); - central.add(utf8.encode('PK\x01\x02')); + central.add(runtime.encode('PK\x01\x02')); central.le(20, 2); central.le(20, 2); central.le(0, 2); @@ -476,8 +485,8 @@ export const archiveOperations: Operation[] = [ central.add(nameBytes); const end = new Bytes(); - const commentBytes = utf8.encode(comment); - end.add(utf8.encode('PK\x05\x06')); + const commentBytes = runtime.encode(comment); + end.add(runtime.encode('PK\x05\x06')); end.le(0, 2); end.le(0, 2); end.le(1, 2); @@ -603,6 +612,8 @@ export const archiveOperations: Operation[] = [ const uncompressed = (size & 0x80000000) !== 0; const length = size & 0x7fffffff; + if (at + length > bytes.length) throw new OperationError('Truncated LZ4 block.'); + if (uncompressed) checkSize(out.length + length); const block = bytes.subarray(at, at + length); at += length; if (uncompressed) for (const byte of block) out.push(byte); diff --git a/src/engine/operations/argon2.ts b/src/engine/operations/argon2.ts index a6eb255..fbca3e6 100644 --- a/src/engine/operations/argon2.ts +++ b/src/engine/operations/argon2.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, toBytes } from '../core/bytes'; import { arg, toggle, type Operation } from './types'; @@ -139,6 +140,10 @@ export function argon2(options: Argon2Options): Uint8Array { const secret = options.secret ?? new Uint8Array(0); const associated = options.associated ?? new Uint8Array(0); + if (![options.memoryKiB, passes, parallelism, tagLength].every(Number.isSafeInteger) || + options.memoryKiB < 8 || options.memoryKiB > 262144 || passes > 20 || parallelism > 16 || tagLength > 512) { + throw new OperationError('Argon2 parameters exceed the supported resource limits.'); + } if (parallelism < 1) throw new OperationError('Argon2 needs at least one lane.'); if (passes < 1) throw new OperationError('Argon2 needs at least one pass.'); if (tagLength < 4) throw new OperationError('An Argon2 tag is at least four bytes.'); @@ -280,12 +285,12 @@ function hex(bytes: Uint8Array): string { function base64(bytes: Uint8Array): string { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); - return btoa(binary).replace(/=+$/, ''); + return runtime.toBase64(binary).replace(/=+$/, ''); } function fromBase64(text: string): Uint8Array { const padded = text.replace(/-/g, '+').replace(/_/g, '/'); - const binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4)); + const binary = runtime.fromBase64(padded + '='.repeat((4 - (padded.length % 4)) % 4)); return Uint8Array.from(binary, (c) => c.charCodeAt(0)); } diff --git a/src/engine/operations/asn1.ts b/src/engine/operations/asn1.ts index cbcd1d5..deb8b1d 100644 --- a/src/engine/operations/asn1.ts +++ b/src/engine/operations/asn1.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1, latin1ToBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -118,7 +119,7 @@ export const ASN1_FORMAT_ARG = { function fromBase64(text: string, what: string): Uint8Array { try { - return latin1ToBytes(atob(text.replace(/[^A-Za-z0-9+/=]/g, ''))); + return latin1ToBytes(runtime.fromBase64(text.replace(/[^A-Za-z0-9+/=]/g, ''))); } catch { throw new OperationError(`${what} does not hold valid Base64.`); } @@ -310,7 +311,7 @@ function nodeValue(node: Node): string { case 22: case 26: case 27: - return new TextDecoder().decode(node.content); + return runtime.decoder().decode(node.content); case 23: case 24: return readTime(node); @@ -344,7 +345,7 @@ function readName(node: Node): string { const value = pair.children[1]; if (!oid || !value) continue; const name = OIDS[decodeOid(oid.content)] ?? decodeOid(oid.content); - parts.push(`${DN_SHORT[name] ?? name}=${new TextDecoder().decode(value.content)}`); + parts.push(`${DN_SHORT[name] ?? name}=${runtime.decoder().decode(value.content)}`); } } return parts.join(', '); @@ -507,7 +508,7 @@ function parseSshKey(input: string): string { let bytes: Uint8Array; try { - bytes = latin1ToBytes(atob(match[1] as string)); + bytes = latin1ToBytes(runtime.fromBase64(match[1] as string)); } catch { throw new OperationError('The key is not valid Base64.'); } @@ -692,7 +693,7 @@ export const asn1Operations: Operation[] = [ if (!key) throw new OperationError('The certificate has no subject public key.'); const der = bytes.subarray(key.header, key.end); - const base64 = btoa(bytesToLatin1(der)); + const base64 = runtime.toBase64(bytesToLatin1(der)); const lines = base64.match(/.{1,64}/g) ?? []; return ['-----BEGIN PUBLIC KEY-----', ...lines, '-----END PUBLIC KEY-----', ''].join('\n'); }, diff --git a/src/engine/operations/avro.ts b/src/engine/operations/avro.ts index f9546b2..1c54fb0 100644 --- a/src/engine/operations/avro.ts +++ b/src/engine/operations/avro.ts @@ -1,3 +1,5 @@ +import { checkSize, MAX_OUTPUT } from '../runtime/limits'; +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -12,7 +14,7 @@ class Reader { at = 0; readonly view: DataView; - constructor(readonly bytes: Uint8Array) { + constructor(readonly bytes: Uint8Array, readonly budget = { values: 0 }) { this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); } @@ -21,7 +23,7 @@ class Reader { } need(count: number): void { - if (this.at + count > this.bytes.length) { + if (!Number.isSafeInteger(count) || count < 0 || this.at + count > this.bytes.length) { throw new OperationError( `The file ends in the middle of a value (wanted ${count} more bytes at offset ${this.at}).`, ); @@ -70,7 +72,7 @@ class Reader { string(): string { const length = Number(this.long()); if (length < 0) throw new OperationError('A string claims a negative length.'); - return new TextDecoder().decode(this.take(length)); + return runtime.decoder().decode(this.take(length)); } } @@ -111,6 +113,7 @@ function logical(schema: Schema, value: Json): Json { } function readValue(r: Reader, schema: Schema, named: Named, namespace: string, depth: number): Json { + checkSize(++r.budget.values, 1_000_000); if (depth > 64) throw new OperationError('The schema nests more than 64 levels deep.'); if (typeof schema === 'string' && named.has(schema)) { @@ -172,7 +175,7 @@ function readValue(r: Reader, schema: Schema, named: Named, namespace: string, d } case 'map': { const values = object?.values ?? null; - const out: { [key: string]: Json } = {}; + const out: { [key: string]: Json } = Object.create(null); for (;;) { let count = Number(r.long()); if (count === 0) break; @@ -197,7 +200,7 @@ function readValue(r: Reader, schema: Schema, named: Named, namespace: string, d const fields = object?.fields; if (!Array.isArray(fields)) throw new OperationError('A record has no fields.'); const inner = object ? fullName(object, namespace).split('.').slice(0, -1).join('.') : namespace; - const out: { [key: string]: Json } = {}; + const out: { [key: string]: Json } = Object.create(null); for (const field of fields) { if (!field || typeof field !== 'object' || Array.isArray(field)) { throw new OperationError('A record field is not an object.'); @@ -239,10 +242,6 @@ function collectNames(schema: Schema, named: Named, namespace: string): void { if (kind === 'map') collectNames(schema.values ?? null, named, inner); } -async function inflate(bytes: Uint8Array, format: 'deflate-raw' | 'deflate'): Promise { - const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream(format)); - return new Uint8Array(await new Response(stream).arrayBuffer()); -} export const avroOperations: Operation[] = [ { @@ -286,13 +285,13 @@ export const avroOperations: Operation[] = [ if (!schemaText) throw new OperationError('The file header carries no avro.schema.'); let schema: Schema; try { - schema = JSON.parse(new TextDecoder().decode(schemaText)) as Schema; + schema = JSON.parse(runtime.decoder().decode(schemaText)) as Schema; } catch { throw new OperationError('The schema in the header is not valid JSON.'); } const codec = meta.has('avro.codec') - ? new TextDecoder().decode(meta.get('avro.codec')!) + ? runtime.decoder().decode(meta.get('avro.codec')!) : 'null'; if (codec !== 'null' && codec !== 'deflate') { throw new OperationError( @@ -305,19 +304,23 @@ export const avroOperations: Operation[] = [ collectNames(schema, named, ''); const records: Json[] = []; + let remaining = MAX_OUTPUT; while (!r.done) { const count = Number(r.long()); const size = Number(r.long()); let block: Uint8Array = r.take(size).slice(); if (codec === 'deflate') { try { - block = await inflate(block, 'deflate-raw'); + block = await runtime.transform(block, 'deflate-raw', false, remaining); } catch { throw new OperationError('A deflate block in this file could not be decompressed.'); } } - const inner = new Reader(block); + checkSize(block.length, remaining); + remaining -= block.length; + checkSize(records.length + count, 1_000_000); + const inner = new Reader(block, r.budget); for (let i = 0; i < count; i++) { records.push(readValue(inner, schema, named, '', 0)); } diff --git a/src/engine/operations/binaryFormats.ts b/src/engine/operations/binaryFormats.ts index 323e3eb..ede3271 100644 --- a/src/engine/operations/binaryFormats.ts +++ b/src/engine/operations/binaryFormats.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -80,8 +81,8 @@ class Reader { } } -const utf8 = new TextEncoder(); -const fromUtf8 = new TextDecoder('utf-8', { fatal: false }); + +const fromUtf8 = runtime.decoder('utf-8', { fatal: false }); const MAX_DEPTH = 64; @@ -130,7 +131,7 @@ function encodeCbor(value: unknown, out: Writer, depth = 0): void { return; } if (typeof value === 'string') { - const bytes = utf8.encode(value); + const bytes = runtime.encode(value); writeCborHead(out, 3, bytes.length); out.bytes(bytes); return; @@ -295,7 +296,7 @@ function encodeMsgpack(value: unknown, out: Writer, depth = 0): void { return; } if (typeof value === 'string') { - const bytes = utf8.encode(value); + const bytes = runtime.encode(value); if (bytes.length < 32) { out.byte(0xa0 | bytes.length); } else if (bytes.length < 0x100) { @@ -426,7 +427,7 @@ function decodeMsgpack(reader: Reader, depth = 0): unknown { function encodeBsonValue(out: Writer, key: string, value: unknown, depth: number): void { checkDepth(depth); const name = () => { - out.bytes(utf8.encode(key)); + out.bytes(runtime.encode(key)); out.byte(0); }; @@ -456,7 +457,7 @@ function encodeBsonValue(out: Writer, key: string, value: unknown, depth: number if (typeof value === 'string') { out.byte(0x02); name(); - const bytes = utf8.encode(value); + const bytes = runtime.encode(value); out.uintLE(bytes.length + 1, 4); out.bytes(bytes); out.byte(0); diff --git a/src/engine/operations/binaryInspect.ts b/src/engine/operations/binaryInspect.ts index 20c84c2..29514da 100644 --- a/src/engine/operations/binaryInspect.ts +++ b/src/engine/operations/binaryInspect.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -100,11 +101,11 @@ function readBinaryPlist(bytes: Uint8Array): Json { } case 0x5: { const { length, next } = lengthAt(at); - return new TextDecoder('ascii').decode(bytes.subarray(next, next + length)); + return runtime.decoder('ascii').decode(bytes.subarray(next, next + length)); } case 0x6: { const { length, next } = lengthAt(at); - return new TextDecoder('utf-16be').decode(bytes.subarray(next, next + length * 2)); + return runtime.decoder('utf-16be').decode(bytes.subarray(next, next + length * 2)); } case 0x8: return `UID ${r.int(at + 1, (marker & 0x0f) + 1)}`; @@ -203,7 +204,7 @@ function readXmlPlist(text: string): Json { case 'data': { const cleaned = body.replace(/\s+/g, ''); try { - place(hex(Uint8Array.from(atob(cleaned), (c) => c.charCodeAt(0)))); + place(hex(Uint8Array.from(runtime.fromBase64(cleaned), (c) => c.charCodeAt(0)))); } catch { throw new OperationError('A element is not valid Base64.'); } @@ -342,7 +343,7 @@ function readElf(bytes: Uint8Array, wanted: string): string { const cString = (at: number): string => { let end = at; while (end < bytes.length && bytes[end] !== 0) end++; - return new TextDecoder('ascii').decode(bytes.subarray(at, end)); + return runtime.decoder('ascii').decode(bytes.subarray(at, end)); }; let stringTable = -1; @@ -406,7 +407,7 @@ export const binaryInspectOperations: Operation[] = [ args: [{ name: 'Indent', type: 'number', value: 2, min: 0, max: 8 }], run: (input, args) => { const bytes = asBytes(input); - const isBinary = new TextDecoder('ascii').decode(bytes.subarray(0, 8)) === 'bplist00'; + const isBinary = runtime.decoder('ascii').decode(bytes.subarray(0, 8)) === 'bplist00'; const value = isBinary ? readBinaryPlist(bytes) : readXmlPlist(input); if (!isBinary && value === null && !/ b.toString(16).padStart(2, '0')) diff --git a/src/engine/operations/bombe.ts b/src/engine/operations/bombe.ts index 9ddd5e3..c6dcc6f 100644 --- a/src/engine/operations/bombe.ts +++ b/src/engine/operations/bombe.ts @@ -1,6 +1,6 @@ import { OperationError } from '../types'; import { arg, type Operation } from './types'; -import { ROTORS, REFLECTORS, makeRotor, through, type Rotor } from './enigma'; +import { ROTORS, REFLECTORS, makeRotor, through } from './enigma'; const A = 'A'.charCodeAt(0); @@ -24,23 +24,37 @@ function buildTables(names: string[], rings: string, reflectorName: string): Tab const perm = new Uint8Array(POSITIONS * 26); const next = new Uint16Array(POSITIONS); - const rotors: Rotor[] = names.map((name, i) => makeRotor(name, rings[i]!, 'A')); + // A rotor's wiring depends only on its own position and ring. Compute + // each permutation once, including the reflector path through the left rotor. + const wiringAt = names.map((name, i) => { + const rotor = makeRotor(name, rings[i]!, 'A'); + const forward = new Uint8Array(26 * 26); + const reverse = new Uint8Array(26 * 26); + for (let position = 0; position < 26; position++) { + rotor.position = position; + for (let letter = 0; letter < 26; letter++) { + const out = through(rotor, letter, false); + forward[position * 26 + letter] = i === 0 ? through(rotor, reflector[out]!, true) : out; + reverse[position * 26 + letter] = through(rotor, letter, true); + } + } + return {forward, reverse}; + }); + const leftPath = wiringAt[0]!.forward; + const middleRotor = wiringAt[1]!; + const rightRotor = wiringAt[2]!; for (let index = 0; index < POSITIONS; index++) { const left = Math.floor(index / 676); const middle = Math.floor(index / 26) % 26; const right = index % 26; - rotors[0]!.position = left; - rotors[1]!.position = middle; - rotors[2]!.position = right; - const base = index * 26; for (let c = 0; c < 26; c++) { - let signal = c; - for (let i = 2; i >= 0; i--) signal = through(rotors[i]!, signal, false); - signal = reflector[signal]!; - for (let i = 0; i < 3; i++) signal = through(rotors[i]!, signal, true); - perm[base + c] = signal; + const first = rightRotor.forward[right * 26 + c]!; + const second = middleRotor.forward[middle * 26 + first]!; + const reflected = leftPath[left * 26 + second]!; + const returning = middleRotor.reverse[middle * 26 + reflected]!; + perm[base + c] = rightRotor.reverse[right * 26 + returning]!; } const rightOnNotch = notches[2]!.includes(right); @@ -55,7 +69,7 @@ function buildTables(names: string[], rings: string, reflectorName: string): Tab } interface Menu { - edges: Array<{ from: number; to: number; at: number }>; + connections: Array>; test: number; span: number; } @@ -71,8 +85,7 @@ function buildMenu(crib: string, cipher: string, offset: number): Menu { ); } - const edges: Menu['edges'] = []; - const degree = new Array(26).fill(0); + const connections: Menu['connections'] = Array.from({ length: 26 }, () => []); for (let i = 0; i < plain.length; i++) { const from = plain.charCodeAt(i) - A; @@ -83,15 +96,14 @@ function buildMenu(crib: string, cipher: string, offset: number): Menu { `'${plain[i]}' to itself, which Enigma never does.`, ); } - edges.push({ from, to, at: offset + i }); - degree[from]!++; - degree[to]!++; + connections[from]!.push({ target: to, at: offset + i }); + connections[to]!.push({ target: from, at: offset + i }); } let test = 0; - for (let c = 1; c < 26; c++) if (degree[c]! > degree[test]!) test = c; + for (let c = 1; c < 26; c++) if (connections[c]!.length > connections[test]!.length) test = c; - return { edges, test, span: offset + plain.length }; + return { connections, test, span: offset + plain.length }; } function letters(index: number): string { @@ -123,28 +135,30 @@ function search(tables: Tables, menu: Menu, limit: number): Stop[] { live.fill(0); let top = 0; - stack[top++] = menu.test * 26 + menu.test; + const first = menu.test * 26 + menu.test; + stack[top++] = first; + live[first] = 1; let testWires = 0; while (top > 0) { const wire = stack[--top]!; - if (live[wire]) continue; - live[wire] = 1; const node = Math.floor(wire / 26); const value = wire % 26; if (node === menu.test && ++testWires === 26) break; - if (!live[value * 26 + node]) stack[top++] = value * 26 + node; - - for (const edge of menu.edges) { - if (edge.from === node) { - const out = tables.perm[scramblers[edge.at]! + value]!; - if (!live[edge.to * 26 + out]) stack[top++] = edge.to * 26 + out; - } - if (edge.to === node) { - const out = tables.perm[scramblers[edge.at]! + value]!; - if (!live[edge.from * 26 + out]) stack[top++] = edge.from * 26 + out; + // Mark on enqueue so each wire occupies at most one of the 676 stack slots. + const diagonal = value * 26 + node; + if (!live[diagonal]) { + live[diagonal] = 1; + stack[top++] = diagonal; + } + for (const edge of menu.connections[node]!) { + const signal = tables.perm[scramblers[edge.at]! + value]!; + const destination = edge.target * 26 + signal; + if (!live[destination]) { + live[destination] = 1; + stack[top++] = destination; } } } diff --git a/src/engine/operations/bzip2.ts b/src/engine/operations/bzip2.ts index 8ff8fce..a7eb42e 100644 --- a/src/engine/operations/bzip2.ts +++ b/src/engine/operations/bzip2.ts @@ -1,3 +1,4 @@ +import { checkSize, MAX_OUTPUT } from '../runtime/limits'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -164,25 +165,27 @@ function inverseBwt(block: Uint8Array, origPtr: number): Uint8Array { return out; } -function undoRle(bytes: Uint8Array): Uint8Array { +function undoRle(bytes: Uint8Array, remaining: number): Uint8Array { const out: number[] = []; let i = 0; while (i < bytes.length) { const byte = bytes[i]!; let run = 1; while (run < 4 && i + run < bytes.length && bytes[i + run] === byte) run++; + checkSize(out.length + run, remaining); for (let k = 0; k < run; k++) out.push(byte); i += run; if (run === 4) { if (i >= bytes.length) throw new OperationError('A run in this block has no length byte.'); const extra = bytes[i++]!; + checkSize(out.length + extra, remaining); for (let k = 0; k < extra; k++) out.push(byte); } } return new Uint8Array(out); } -function decodeBlock(reader: BitReader, blockSize: number): { data: Uint8Array; crc: number } { +function decodeBlock(reader: BitReader, blockSize: number, remaining: number): { data: Uint8Array; crc: number } { const crc = reader.bits(32); if (reader.bit() !== 0) { throw new OperationError( @@ -263,7 +266,7 @@ function decodeBlock(reader: BitReader, blockSize: number): { data: Uint8Array; if (symbol <= 1) { runLength += (symbol + 1) << runBit; - runBit++; + if (runLength > blockSize || ++runBit > 21) throw new OperationError('Oversize bzip2 run.'); continue; } @@ -285,7 +288,7 @@ function decodeBlock(reader: BitReader, blockSize: number): { data: Uint8Array; } if (origPtr >= written) throw new OperationError('The block pointer points outside the block.'); - const data = undoRle(inverseBwt(block.subarray(0, written), origPtr)); + const data = undoRle(inverseBwt(block.subarray(0, written), origPtr), remaining); const actual = crc32(data); if (actual !== crc) { @@ -307,6 +310,7 @@ function decompress(bytes: Uint8Array): Uint8Array { const reader = new BitReader(bytes.subarray(4)); const pieces: Uint8Array[] = []; + let remaining = MAX_OUTPUT; let combined = 0; for (;;) { @@ -324,7 +328,8 @@ function decompress(bytes: Uint8Array): Uint8Array { throw new OperationError('A block does not begin with the expected marker.'); } - const piece = decodeBlock(reader, level * 100000); + const piece = decodeBlock(reader, level * 100000, remaining); + remaining -= piece.data.length; combined = (((combined << 1) | (combined >>> 31)) ^ piece.crc) >>> 0; pieces.push(piece.data); diff --git a/src/engine/operations/compression.ts b/src/engine/operations/compression.ts index 065ffe8..465057b 100644 --- a/src/engine/operations/compression.ts +++ b/src/engine/operations/compression.ts @@ -1,31 +1,23 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; -async function transform( - bytes: Uint8Array, - stream: CompressionStream | DecompressionStream, -): Promise { - const source = new Blob([bytes as BlobPart]).stream(); - const piped = source.pipeThrough(stream as ReadableWritablePair); - const buffer = await new Response(piped).arrayBuffer(); - return new Uint8Array(buffer); -} - function asBinary(input: string): Uint8Array { return asBytes(input); } async function decompress(input: string, format: 'gzip' | 'deflate' | 'deflate-raw') { try { - return bytesToLatin1(await transform(asBinary(input), new DecompressionStream(format))); - } catch { + return bytesToLatin1(await runtime.transform(asBinary(input), format, false)); + } catch (error) { + if (error instanceof OperationError) throw error; throw new OperationError(`Input is not valid ${format} data.`); } } async function compress(input: string, format: 'gzip' | 'deflate' | 'deflate-raw') { - return bytesToLatin1(await transform(asBytes(input), new CompressionStream(format))); + return bytesToLatin1(await runtime.transform(asBytes(input), format, true)); } function withGzipHeader( @@ -97,7 +89,7 @@ export const compressionOperations: Operation[] = [ { name: 'Timestamp', type: 'number', value: 0, min: 0 }, ], run: async (input, args) => { - const raw = await transform(asBytes(input), new CompressionStream('gzip')); + const raw = await runtime.transform(asBytes(input), 'gzip', true); const when = String(arg(args, 'Modification time', 'None')); const mtime = when === 'Now' diff --git a/src/engine/operations/crypto.ts b/src/engine/operations/crypto.ts index 95f61e4..b9aa2cf 100644 --- a/src/engine/operations/crypto.ts +++ b/src/engine/operations/crypto.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1, latin1ToBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -37,10 +38,10 @@ function rotateSelective(input: string, options: RotateOptions): string { } async function digest(algorithm: string, input: string): Promise { - if (!globalThis.crypto?.subtle) { + if (!runtime.subtle) { throw new OperationError('Hashing needs a secure context (HTTPS or localhost).'); } - const buffer = await crypto.subtle.digest(algorithm, asBytes(input) as BufferSource); + const buffer = await runtime.subtle!.digest(algorithm, asBytes(input) as BufferSource); return Array.from(new Uint8Array(buffer)) .map((b) => b.toString(16).padStart(2, '0')) .join(''); diff --git a/src/engine/operations/dataFormat.ts b/src/engine/operations/dataFormat.ts index c99dee2..6508b05 100644 --- a/src/engine/operations/dataFormat.ts +++ b/src/engine/operations/dataFormat.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError, type OperationArg } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { decodeBaseN, encodeBaseN } from '../core/alphabet'; @@ -655,7 +656,7 @@ export const dataFormatOperations: Operation[] = [ const trimmed = bytes.length % 2 === 0 ? bytes : bytes.subarray(0, bytes.length - 1); const encoding = arg(args, 'Byte order', 'Little-endian') === 'Big-endian' ? 'utf-16be' : 'utf-16le'; - let decoded = new TextDecoder(encoding).decode(trimmed as BufferSource); + let decoded = runtime.decoder(encoding).decode(trimmed); if (arg(args, 'Remove the byte order mark', true) && decoded.charCodeAt(0) === 0xfeff) { decoded = decoded.slice(1); } diff --git a/src/engine/operations/datetime.ts b/src/engine/operations/datetime.ts index c3c960a..3f3c83b 100644 --- a/src/engine/operations/datetime.ts +++ b/src/engine/operations/datetime.ts @@ -3,6 +3,7 @@ import { arg, type Operation } from './types'; const FILETIME_EPOCH_DIFF = 11644473600n; const TICKS_PER_SECOND = 10000000n; +const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; function requireDate(value: number, what: string): Date { const date = new Date(value); @@ -39,7 +40,7 @@ function describe(date: Date): string { `Local: ${date.toString()}`, `Unix (s): ${Math.floor(date.getTime() / 1000)}`, `Unix (ms): ${date.getTime()}`, - `Day: ${date.toLocaleDateString('en', { weekday: 'long', timeZone: 'UTC' })}`, + `Day: ${WEEKDAYS[date.getUTCDay()]}`, `Relative: ${relative}`, ].join('\n'); } diff --git a/src/engine/operations/datetimeFormat.ts b/src/engine/operations/datetimeFormat.ts index 4aeee29..f383883 100644 --- a/src/engine/operations/datetimeFormat.ts +++ b/src/engine/operations/datetimeFormat.ts @@ -1,19 +1,9 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { arg, type Operation } from './types'; -function zoneNames(): string[] { - try { - const supported = ( - Intl as unknown as { supportedValuesOf?: (key: string) => string[] } - ).supportedValuesOf?.('timeZone'); - if (supported && supported.length > 0) return ['UTC', ...supported]; - } catch { - } - return ['UTC']; -} - -const ZONES = zoneNames(); +const ZONES = runtime.timeZones(); const MONTHS = [ 'January', @@ -276,31 +266,6 @@ function fieldsFromInstant(instant: number): Partial { }; } -function zoneOffset(zone: string, instant: number): number { - if (zone === 'UTC') return 0; - const formatter = new Intl.DateTimeFormat('en-GB', { - timeZone: zone, - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - hour12: false, - }); - const parts: Record = {}; - for (const part of formatter.formatToParts(new Date(instant))) parts[part.type] = part.value; - const asUtc = Date.UTC( - Number(parts.year), - Number(parts.month) - 1, - Number(parts.day), - Number(parts.hour) % 24, - Number(parts.minute), - Number(parts.second), - ); - return Math.round((asUtc - Math.floor(instant / 1000) * 1000) / 60000); -} - function buildParser(format: string): { regex: RegExp; readers: Array<(f: Fields, t: string) => void> } { const readers: Array<(f: Fields, t: string) => void> = []; let pattern = ''; @@ -359,25 +324,13 @@ function parseDateTime(input: string, format: string, zone: string): number { if (Number.isNaN(naive)) throw new OperationError('Those fields are not a real date.'); if (fields.offset !== null) return naive - fields.offset * 60000; - const first = naive - zoneOffset(zone, naive) * 60000; - const second = naive - zoneOffset(zone, first) * 60000; + const first = naive - runtime.zoneOffset(zone, naive) * 60000; + const second = naive - runtime.zoneOffset(zone, first) * 60000; return second; } -function zoneAbbreviation(zone: string, instant: number): string { - try { - const parts = new Intl.DateTimeFormat('en-US', { - timeZone: zone, - timeZoneName: 'short', - }).formatToParts(new Date(instant)); - return parts.find((part) => part.type === 'timeZoneName')?.value ?? zone; - } catch { - return zone; - } -} - function partsFor(instant: number, zone: string): Parts { - const offset = zoneOffset(zone, instant); + const offset = runtime.zoneOffset(zone, instant); const shifted = new Date(instant + offset * 60000); return { year: shifted.getUTCFullYear(), @@ -395,7 +348,7 @@ function partsFor(instant: number, zone: string): Parts { function formatDateTime(instant: number, format: string, zone: string): string { const parts = partsFor(instant, zone); - const abbreviation = zoneAbbreviation(zone, instant); + const abbreviation = runtime.zoneAbbreviation(zone, instant); let out = ''; for (let i = 0; i < format.length; ) { diff --git a/src/engine/operations/encodings.ts b/src/engine/operations/encodings.ts index 488a7f1..8a60779 100644 --- a/src/engine/operations/encodings.ts +++ b/src/engine/operations/encodings.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { DELIMITER_OPTIONS, delimiterFor, splitOnAnyDelimiter } from '../core/delimiters'; @@ -598,7 +599,7 @@ export const encodingOperations: Operation[] = [ args: [], run: (input) => { try { - return new URL(`http://${input.trim()}`).hostname; + return runtime.parseUrl(`http://${input.trim()}`).hostname; } catch { throw new OperationError('Input is not a domain name.'); } diff --git a/src/engine/operations/files.ts b/src/engine/operations/files.ts index 2fb229c..72afe85 100644 --- a/src/engine/operations/files.ts +++ b/src/engine/operations/files.ts @@ -1,3 +1,5 @@ +import { runtime } from '../runtime'; +import { checkSize } from '../runtime/limits'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -266,9 +268,14 @@ async function extractZipEntry(bytes: Uint8Array, entry: ZipEntry): Promise bytes.length) throw new OperationError('Truncated ZIP entry.'); const data = bytes.subarray(start, start + entry.compressed); - if (entry.method === 0) return data; + if (entry.method === 0) { + if (entry.compressed !== entry.uncompressed) throw new OperationError('Stored ZIP entry size mismatch.'); + return data; + } if (entry.method !== 8) { throw new OperationError( `This entry uses compression method ${entry.method}. Only stored and deflate are supported.`, @@ -276,11 +283,11 @@ async function extractZipEntry(bytes: Uint8Array, entry: ZipEntry): Promise); - return new Uint8Array(await new Response(stream).arrayBuffer()); - } catch { + const output = await runtime.transform(data, 'deflate-raw', false, entry.uncompressed); + if (output.length !== entry.uncompressed) throw new OperationError('ZIP entry size mismatch.'); + return output; + } catch (error) { + if (error instanceof OperationError) throw error; throw new OperationError('The entry is not valid deflate data. It may be encrypted.'); } } @@ -349,7 +356,7 @@ export const fileOperations: Operation[] = [ 'SVG is not rendered. It is markup that can carry script, and this is a tool for untrusted input.', ); } - return `data:${info.mime};base64,${btoa(bytesToLatin1(bytes))}`; + return `data:${info.mime};base64,${runtime.toBase64(bytesToLatin1(bytes))}`; }, }, { @@ -592,7 +599,7 @@ export const fileOperations: Operation[] = [ stated === 'auto' || stated.length === 0 ? (readImage(bytes)?.mime ?? 'application/octet-stream') : stated; - return `data:${mime};base64,${btoa(bytesToLatin1(bytes))}`; + return `data:${mime};base64,${runtime.toBase64(bytesToLatin1(bytes))}`; }, }, { @@ -609,7 +616,7 @@ export const fileOperations: Operation[] = [ const payload = match[4] ?? ''; if (match[3]) { try { - const binary = atob(payload.replace(/\s/g, '')); + const binary = runtime.fromBase64(payload.replace(/\s/g, '')); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return bytesToLatin1(bytes); @@ -645,11 +652,11 @@ export const fileOperations: Operation[] = [ ], run: async (input, args) => { const bytes = asBytes(input); - if (!globalThis.crypto?.subtle) { + if (!runtime.subtle) { throw new OperationError('Hashing needs a secure context (HTTPS or localhost).'); } const digest = async (algorithm: string) => - Array.from(new Uint8Array(await crypto.subtle.digest(algorithm, bytes as BufferSource))) + Array.from(new Uint8Array(await runtime.subtle!.digest(algorithm, bytes as BufferSource))) .map((b) => b.toString(16).padStart(2, '0')) .join(''); diff --git a/src/engine/operations/hashing.ts b/src/engine/operations/hashing.ts index 62fd08a..8e669c3 100644 --- a/src/engine/operations/hashing.ts +++ b/src/engine/operations/hashing.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, toBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -123,11 +124,11 @@ function hex(value: number, digits: number): string { } -function requireSubtle(): SubtleCrypto { - if (!globalThis.crypto?.subtle) { +function requireSubtle(): NonNullable { + if (!runtime.subtle) { throw new OperationError('This needs a secure context (HTTPS or localhost).'); } - return crypto.subtle; + return runtime.subtle; } function toHex(buffer: ArrayBuffer): string { diff --git a/src/engine/operations/index.ts b/src/engine/operations/index.ts index 4a4e1db..e87af63 100644 --- a/src/engine/operations/index.ts +++ b/src/engine/operations/index.ts @@ -257,14 +257,20 @@ provideRegistry((id) => BY_ID.get(id), DETECTABLE); export { CATEGORY_ORDER } from './categories'; -export function publicDefinitions(): OperationDef[] { - return OPERATIONS.map(({ id, name, category, description, aliases, args, isFlowControl }) => ({ - id, - name, - category, - description, - aliases, +export function publicDefinition({ id, name, category, description, aliases, args, isFlowControl }: Operation): OperationDef { + return { + id, name, category, description, + aliases: [...aliases], ...(isFlowControl ? { isFlowControl } : {}), - args: args.map((a) => ({ ...a })), - })); + args: args.map(a => ({ + ...a, + ...(a.options && { options: [...a.options] }), + ...(a.optionLabels && { optionLabels: { ...a.optionLabels } }), + ...(a.toggleValues && { toggleValues: [...a.toggleValues] }), + })), + }; +} + +export function publicDefinitions(): OperationDef[] { + return OPERATIONS.map(publicDefinition); } diff --git a/src/engine/operations/kdf.ts b/src/engine/operations/kdf.ts index 9ac0d32..99f1621 100644 --- a/src/engine/operations/kdf.ts +++ b/src/engine/operations/kdf.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1, latin1ToBytes } from '../core/bytes'; import { aes } from '../core/aes'; @@ -17,11 +18,11 @@ function parseHexOrText(value: string, format: string): Uint8Array { return parseKey(value, format, true); } -function subtle(): SubtleCrypto { - if (typeof crypto === 'undefined' || !crypto.subtle) { +function subtle(): NonNullable { + if (!runtime.subtle) { throw new OperationError('This browser does not expose Web Crypto.'); } - return crypto.subtle; + return runtime.subtle; } async function hmac(hash: string, key: Uint8Array, data: Uint8Array): Promise { @@ -225,13 +226,13 @@ function lmKey(seven: Uint8Array): Uint8Array { const JWT_ALGORITHMS = ['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'ES256', 'ES384']; function base64Url(bytes: Uint8Array): string { - return btoa(bytesToLatin1(bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); + return runtime.toBase64(bytesToLatin1(bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } function fromBase64Url(text: string): Uint8Array { const padded = text.replace(/-/g, '+').replace(/_/g, '/'); try { - return latin1ToBytes(atob(padded + '='.repeat((4 - (padded.length % 4)) % 4))); + return latin1ToBytes(runtime.fromBase64(padded + '='.repeat((4 - (padded.length % 4)) % 4))); } catch { throw new OperationError('A token segment is not valid base64url.'); } @@ -241,7 +242,7 @@ function pemToDer(pem: string): Uint8Array { const match = /-----BEGIN [^-]+-----([\s\S]*?)-----END [^-]+-----/.exec(pem); if (!match) throw new OperationError('Expected a PEM key.'); try { - return latin1ToBytes(atob((match[1] as string).replace(/[^A-Za-z0-9+/=]/g, ''))); + return latin1ToBytes(runtime.fromBase64((match[1] as string).replace(/[^A-Za-z0-9+/=]/g, ''))); } catch { throw new OperationError('The PEM block does not hold valid base64.'); } @@ -467,15 +468,14 @@ export const kdfOperations: Operation[] = [ if (String(arg(args, 'Private/Secret key', '')).length === 0) { throw new OperationError('A signing key is required.'); } - const encoder = new TextEncoder(); const parts = [ - base64Url(encoder.encode(JSON.stringify({ alg: algorithm, typ: 'JWT', ...header }))), - base64Url(encoder.encode(JSON.stringify(payload))), + base64Url(runtime.encode(JSON.stringify({ alg: algorithm, typ: 'JWT', ...header }))), + base64Url(runtime.encode(JSON.stringify(payload))), ]; const key = await jwtKey(algorithm, String(arg(args, 'Private/Secret key', '')), 'sign'); const signature = new Uint8Array( - await subtle().sign(jwtAlgorithmParams(algorithm), key, encoder.encode(parts.join('.'))), + await subtle().sign(jwtAlgorithmParams(algorithm), key, runtime.encode(parts.join('.'))), ); return `${parts.join('.')}.${base64Url(signature)}`; }, @@ -493,7 +493,7 @@ export const kdfOperations: Operation[] = [ let header: { alg?: string }; try { - header = JSON.parse(new TextDecoder().decode(fromBase64Url(parts[0] as string))) as { + header = JSON.parse(runtime.decoder().decode(fromBase64Url(parts[0] as string))) as { alg?: string; }; } catch { @@ -514,11 +514,11 @@ export const kdfOperations: Operation[] = [ jwtAlgorithmParams(algorithm), key, fromBase64Url(parts[2] as string) as BufferSource, - new TextEncoder().encode(`${parts[0]}.${parts[1]}`), + runtime.encode(`${parts[0]}.${parts[1]}`), ); if (!valid) throw new OperationError('The signature does not verify with that key.'); - return new TextDecoder().decode(fromBase64Url(parts[1] as string)); + return runtime.decoder().decode(fromBase64Url(parts[1] as string)); }, }, ]; diff --git a/src/engine/operations/keys.ts b/src/engine/operations/keys.ts index d1d63ae..08bff0d 100644 --- a/src/engine/operations/keys.ts +++ b/src/engine/operations/keys.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { latin1ToBytes, toBytes } from '../core/bytes'; @@ -15,7 +16,7 @@ export function parseKey(value: string, format: string, allowEmpty = true): Uint if (format === 'Base64') { try { - return latin1ToBytes(atob(value.trim())); + return latin1ToBytes(runtime.fromBase64(value.trim())); } catch { throw new OperationError('Key is not valid Base64.'); } diff --git a/src/engine/operations/lzma.ts b/src/engine/operations/lzma.ts index fba3bf1..0f19cdf 100644 --- a/src/engine/operations/lzma.ts +++ b/src/engine/operations/lzma.ts @@ -1,3 +1,4 @@ +import { checkSize, MAX_OUTPUT } from '../runtime/limits'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -251,7 +252,7 @@ function decompress(bytes: Uint8Array): Uint8Array { const declared = view.getBigUint64(5, true); const unknownSize = declared === 0xffffffffffffffffn; - if (!unknownSize && declared > 1n << 31n) { + if (!unknownSize && declared > BigInt(MAX_OUTPUT)) { throw new OperationError( `This file declares ${declared} bytes, which is more than a browser tab can hold.`, ); @@ -292,6 +293,7 @@ function decompress(bytes: Uint8Array): Uint8Array { symbol = (symbol << 1) | decoder.bit(model.literal, offset + symbol); } + checkSize(out.length + 1); out.push(symbol & 0xff); state = literalState(state); continue; @@ -303,6 +305,7 @@ function decompress(bytes: Uint8Array): Uint8Array { if (decoder.bit(model.isRepG0, state) === 0) { if (decoder.bit(model.isRep0Long, (state << 4) + posState) === 0) { state = shortRepState(state); + checkSize(out.length + 1); out.push(out[position - reps[0]! - 1] ?? 0); continue; } @@ -352,6 +355,7 @@ function decompress(bytes: Uint8Array): Uint8Array { } } + checkSize(out.length + Math.min(length, target - out.length)); for (let i = 0; i < length && out.length < target; i++) { out.push(out[out.length - reps[0]! - 1]!); } diff --git a/src/engine/operations/magic.ts b/src/engine/operations/magic.ts index 326e975..951b3fe 100644 --- a/src/engine/operations/magic.ts +++ b/src/engine/operations/magic.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { previewText } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -41,7 +42,7 @@ export const magicOperations: Operation[] = [ const crib = String(arg(args, 'Crib', '')); const withPreviews = Boolean(arg(args, 'Show previews', true)); - const deadline = performance.now() + BUDGET_MS; + const deadline = runtime.now() + BUDGET_MS; const seen = new Set([input]); const found: Chain[] = []; let nodes = 0; @@ -52,7 +53,7 @@ export const magicOperations: Operation[] = [ const next: Array<{ value: string; labels: string[] }> = []; for (const node of frontier) { - if (performance.now() > deadline || nodes >= MAX_NODES) break; + if (runtime.now() > deadline || nodes >= MAX_NODES) break; for (const candidate of await detect(node.value)) { if (candidate.confidence < threshold) break; diff --git a/src/engine/operations/metadata.ts b/src/engine/operations/metadata.ts index 84d0605..2aa508f 100644 --- a/src/engine/operations/metadata.ts +++ b/src/engine/operations/metadata.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -64,11 +65,11 @@ function decodeText(bytes: Uint8Array): string { const body = bytes.subarray(1); let text: string; - if (encoding === 0) text = new TextDecoder('windows-1252').decode(body); - else if (encoding === 1) text = new TextDecoder('utf-16').decode(body); - else if (encoding === 2) text = new TextDecoder('utf-16be').decode(body); - else if (encoding === 3) text = new TextDecoder().decode(body); - else text = new TextDecoder('windows-1252').decode(bytes); + if (encoding === 0) text = runtime.decoder('windows-1252').decode(body); + else if (encoding === 1) text = runtime.decoder('utf-16').decode(body); + else if (encoding === 2) text = runtime.decoder('utf-16be').decode(body); + else if (encoding === 3) text = runtime.decoder().decode(body); + else text = runtime.decoder('windows-1252').decode(bytes); return stripNulls(text).split(NUL).join(' / ').trim(); } @@ -91,7 +92,7 @@ function readId3v2(bytes: Uint8Array): string[] { const end = Math.min(bytes.length, 10 + size); while (at + idLength + (version === 2 ? 3 : 6) <= end) { - const id = new TextDecoder('ascii').decode(bytes.subarray(at, at + idLength)); + const id = runtime.decoder('ascii').decode(bytes.subarray(at, at + idLength)); if (!/^[A-Z0-9]+$/.test(id)) break; let length: number; @@ -128,7 +129,7 @@ function readId3v2(bytes: Uint8Array): string[] { function readId3v1(bytes: Uint8Array): string[] { const at = bytes.length - 128; const field = (from: number, length: number): string => { - const raw = new TextDecoder('windows-1252').decode( + const raw = runtime.decoder('windows-1252').decode( bytes.subarray(at + from, at + from + length), ); return untilNul(raw).trim(); @@ -156,7 +157,7 @@ function readVorbisComments(bytes: Uint8Array, at: number): string[] { const vendorLength = view.getUint32(at, true); at += 4; - const vendor = new TextDecoder().decode(bytes.subarray(at, at + vendorLength)); + const vendor = runtime.decoder().decode(bytes.subarray(at, at + vendorLength)); at += vendorLength; if (vendor.length > 0) lines.push(`${'Vendor'.padEnd(18)} ${vendor}`); @@ -165,7 +166,7 @@ function readVorbisComments(bytes: Uint8Array, at: number): string[] { for (let i = 0; i < count && at + 4 <= bytes.length; i++) { const length = view.getUint32(at, true); at += 4; - const entry = new TextDecoder().decode(bytes.subarray(at, at + length)); + const entry = runtime.decoder().decode(bytes.subarray(at, at + length)); at += length; const split = entry.indexOf('='); if (split === -1) continue; @@ -212,12 +213,12 @@ function readFlac(bytes: Uint8Array): string[] { function readRiff(bytes: Uint8Array): string[] { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const kind = new TextDecoder('ascii').decode(bytes.subarray(8, 12)); + const kind = runtime.decoder('ascii').decode(bytes.subarray(8, 12)); const lines = [`RIFF ${kind}`]; let at = 12; while (at + 8 <= bytes.length) { - const id = new TextDecoder('ascii').decode(bytes.subarray(at, at + 4)); + const id = runtime.decoder('ascii').decode(bytes.subarray(at, at + 4)); const length = view.getUint32(at + 4, true); const body = at + 8; @@ -226,14 +227,14 @@ function readRiff(bytes: Uint8Array): string[] { lines.push(`${'Sample rate'.padEnd(18)} ${view.getUint32(body + 4, true)} Hz`); lines.push(`${'Bit depth'.padEnd(18)} ${view.getUint16(body + 14, true)}`); } else if (id === 'LIST') { - const listType = new TextDecoder('ascii').decode(bytes.subarray(body, body + 4)); + const listType = runtime.decoder('ascii').decode(bytes.subarray(body, body + 4)); if (listType === 'INFO') { let inner = body + 4; while (inner + 8 <= body + length) { - const tag = new TextDecoder('ascii').decode(bytes.subarray(inner, inner + 4)); + const tag = runtime.decoder('ascii').decode(bytes.subarray(inner, inner + 4)); const size = view.getUint32(inner + 4, true); const value = stripNulls( - new TextDecoder('windows-1252').decode(bytes.subarray(inner + 8, inner + 8 + size)), + runtime.decoder('windows-1252').decode(bytes.subarray(inner + 8, inner + 8 + size)), ); lines.push(`${tag.padEnd(18)} ${value}`); inner += 8 + size + (size % 2); diff --git a/src/engine/operations/network.ts b/src/engine/operations/network.ts index e0b30e1..880354a 100644 --- a/src/engine/operations/network.ts +++ b/src/engine/operations/network.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { arg, type Operation } from './types'; @@ -115,9 +116,9 @@ export const networkOperations: Operation[] = [ }, ], run: (input, args) => { - let url: URL; + let url: ReturnType; try { - url = new URL(input.trim()); + url = runtime.parseUrl(input.trim()); } catch { throw new OperationError('Not a valid absolute URL. Include the scheme, such as https://.'); } @@ -131,7 +132,7 @@ export const networkOperations: Operation[] = [ username: url.username || null, password: url.password || null, path: url.pathname, - query: Object.fromEntries(url.searchParams.entries()), + query: Object.fromEntries(url.searchParams), fragment: url.hash ? url.hash.slice(1) : null, }, null, @@ -149,7 +150,7 @@ export const networkOperations: Operation[] = [ ...(url.hash ? [`Fragment: ${url.hash.slice(1)}`] : []), ]; - const params = [...url.searchParams.entries()]; + const params = [...url.searchParams]; if (params.length > 0) { lines.push('', 'Query parameters:'); const width = Math.max(...params.map(([k]) => k.length)); @@ -186,15 +187,15 @@ export const networkOperations: Operation[] = [ }, ], run: (input, args) => { - const params = new URLSearchParams(input.trim().replace(/^[?&]/, '')); - const entries = [...params.entries()]; + const params = runtime.query(input.trim().replace(/^[?&]/, '')); + const entries = [...params]; if (entries.length === 0) throw new OperationError('No parameters found.'); if (arg(args, 'Sort by name', false)) entries.sort(([a], [b]) => a.localeCompare(b)); const output = String(arg(args, 'Output', 'Aligned')); if (output === 'JSON') { - const grouped: Record = {}; + const grouped: Record = Object.create(null); for (const [key, value] of entries) { const seen = grouped[key]; if (seen === undefined) grouped[key] = value; diff --git a/src/engine/operations/otp.ts b/src/engine/operations/otp.ts index 74e94c2..8e9dcea 100644 --- a/src/engine/operations/otp.ts +++ b/src/engine/operations/otp.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, toBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -43,8 +44,8 @@ function secretBytes(input: string, encoding: string): Uint8Array { return asBytes(input); } -function requireSubtle(): SubtleCrypto { - const subtle = globalThis.crypto?.subtle; +function requireSubtle(): NonNullable { + const subtle = runtime.subtle; if (!subtle) { throw new OperationError('One-time passwords need Web Crypto, which this browser has not exposed.'); } diff --git a/src/engine/operations/passwordHashes.ts b/src/engine/operations/passwordHashes.ts index c4a8986..3b5dd0a 100644 --- a/src/engine/operations/passwordHashes.ts +++ b/src/engine/operations/passwordHashes.ts @@ -1,20 +1,21 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes } from '../core/bytes'; import { PI_HEX_DIGITS } from '../core/piDigits'; import { arg, type Operation } from './types'; -const utf8 = new TextEncoder(); + function hex(bytes: Uint8Array): string { return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); } -function subtle(): SubtleCrypto { - if (typeof crypto === 'undefined' || !crypto.subtle) { +function subtle(): NonNullable { + if (!runtime.subtle) { throw new OperationError('This browser does not expose Web Crypto.'); } - return crypto.subtle; + return runtime.subtle; } @@ -131,7 +132,7 @@ function eksBlowfish(password: Uint8Array, salt: Uint8Array, cost: number) { expand(salt, null); } - const magic = utf8.encode('OrpheanBeholderScryDoubt'); + const magic = runtime.encode('OrpheanBeholderScryDoubt'); const words: number[] = []; for (let i = 0; i < 6; i++) { words.push( @@ -184,7 +185,7 @@ function bcrypt(password: string, salt: Uint8Array, cost: number, version: strin } if (salt.length !== 16) throw new OperationError('A bcrypt salt is 16 bytes.'); - const bytes = utf8.encode(password).subarray(0, 72); + const bytes = runtime.encode(password).subarray(0, 72); const keyed = new Uint8Array(bytes.length + 1); keyed.set(bytes); @@ -255,7 +256,8 @@ async function scrypt( ): Promise { if (n < 2 || (n & (n - 1)) !== 0) throw new OperationError('N must be a power of two above 1.'); if (r < 1 || p < 1) throw new OperationError('r and p must be at least 1.'); - if (128 * r * n > MAX_SCRYPT_BYTES) { + if (![n, r, p, length].every(Number.isSafeInteger)) throw new OperationError('Scrypt parameters must be integers.'); + if (128 * r * Math.max(n, p) > MAX_SCRYPT_BYTES) { throw new OperationError(`128 * r * N is ${128 * r * n} bytes; the limit here is ${MAX_SCRYPT_BYTES}.`); } @@ -307,7 +309,7 @@ export const passwordHashOperations: Operation[] = [ let salt: Uint8Array; if (saltText === '') { salt = new Uint8Array(16); - crypto.getRandomValues(salt); + runtime.random(salt); } else { salt = bcryptBase64Decode(saltText.slice(0, 22)); if (salt.length !== 16) throw new OperationError('A bcrypt salt is 22 characters.'); @@ -371,7 +373,7 @@ export const passwordHashOperations: Operation[] = [ const saltText = String(arg(args, 'Salt', '')); const salt = args.find((a) => a.name === 'Salt')?.toggleValue === 'UTF-8' - ? utf8.encode(saltText) + ? runtime.encode(saltText) : new Uint8Array((saltText.replace(/[^0-9a-fA-F]/g, '').match(/../g) ?? []).map((p) => parseInt(p, 16))); const out = await scrypt( diff --git a/src/engine/operations/pgp.ts b/src/engine/operations/pgp.ts index 674dbfd..50ba9a9 100644 --- a/src/engine/operations/pgp.ts +++ b/src/engine/operations/pgp.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -140,7 +141,7 @@ function skipMpi(body: Uint8Array, at: number): { next: number; bits: number } { } async function fingerprint(body: Uint8Array): Promise { - const subtle = globalThis.crypto?.subtle; + const subtle = runtime.subtle; if (!subtle) return '(needs Web Crypto)'; const data = new Uint8Array(3 + body.length); @@ -258,7 +259,7 @@ export const pgpOperations: Operation[] = [ .filter((line) => line.trim().length > 0 && !line.includes(':') && !line.startsWith('=')) .join(''); try { - bytes = Uint8Array.from(atob(body), (c) => c.charCodeAt(0)); + bytes = Uint8Array.from(runtime.fromBase64(body), (c) => c.charCodeAt(0)); } catch { throw new OperationError('The armored block is not valid Base64.'); } @@ -292,7 +293,7 @@ export const pgpOperations: Operation[] = [ } break; case 13: - lines.push(`User ID: ${new TextDecoder().decode(packet.body)}`); + lines.push(`User ID: ${runtime.decoder().decode(packet.body)}`); break; case 17: lines.push(`User attribute: ${packet.body.length} bytes (usually a photograph)`); diff --git a/src/engine/operations/primes.ts b/src/engine/operations/primes.ts index 4c4574f..c4f4ccd 100644 --- a/src/engine/operations/primes.ts +++ b/src/engine/operations/primes.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { arg, type Operation } from './types'; @@ -63,7 +64,7 @@ function randomBelow(limit: bigint): bigint { const buffer = new Uint8Array(bytes); for (;;) { - globalThis.crypto.getRandomValues(buffer); + runtime.random(buffer); let value = 0n; for (const byte of buffer) value = (value << 8n) | BigInt(byte); value >>= BigInt(bytes * 8 - bits); @@ -74,7 +75,7 @@ function randomBelow(limit: bigint): bigint { function randomOfBits(bits: number): bigint { const bytes = Math.ceil(bits / 8); const buffer = new Uint8Array(bytes); - globalThis.crypto.getRandomValues(buffer); + runtime.random(buffer); let value = 0n; for (const byte of buffer) value = (value << 8n) | BigInt(byte); diff --git a/src/engine/operations/publicKey.ts b/src/engine/operations/publicKey.ts index 0cb5b34..331fc4d 100644 --- a/src/engine/operations/publicKey.ts +++ b/src/engine/operations/publicKey.ts @@ -1,10 +1,11 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; -function subtle(): SubtleCrypto { - const api = globalThis.crypto?.subtle; +function subtle(): NonNullable { + const api = runtime.subtle; if (!api) { throw new OperationError('This needs Web Crypto, which the browser has not exposed here.'); } @@ -15,7 +16,7 @@ function subtle(): SubtleCrypto { function fromBase64(text: string): Uint8Array { const cleaned = text.replace(/\s+/g, ''); try { - return Uint8Array.from(atob(cleaned), (c) => c.charCodeAt(0)); + return Uint8Array.from(runtime.fromBase64(cleaned), (c) => c.charCodeAt(0)); } catch { throw new OperationError('The key is not valid Base64.'); } @@ -24,7 +25,7 @@ function fromBase64(text: string): Uint8Array { function toBase64(bytes: Uint8Array): string { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); - return btoa(binary); + return runtime.toBase64(binary); } function toPem(label: string, bytes: Uint8Array): string { @@ -347,7 +348,7 @@ export const publicKeyOperations: Operation[] = [ const key = await importPrivate(String(arg(args, 'Key', '')), pss ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5', hash, 'P-256', ['sign']); const parameters = pss - ? { name: 'RSA-PSS', saltLength: Number(hash.slice(4)) / 8 } + ? { name: 'RSA-PSS', saltLength: hash === 'SHA-1' ? 20 : Number(hash.slice(4)) / 8 } : { name: 'RSASSA-PKCS1-v1_5' }; const signature = await subtle().sign(parameters, key, asBytes(input) as BufferSource); return encodeOutput(new Uint8Array(signature), String(arg(args, 'Output', 'Base64'))); @@ -379,7 +380,7 @@ export const publicKeyOperations: Operation[] = [ if (signature.length === 0) throw new OperationError('There is no signature to check.'); const parameters = pss - ? { name: 'RSA-PSS', saltLength: Number(hash.slice(4)) / 8 } + ? { name: 'RSA-PSS', saltLength: hash === 'SHA-1' ? 20 : Number(hash.slice(4)) / 8 } : { name: 'RSASSA-PKCS1-v1_5' }; const valid = await subtle().verify( parameters, @@ -568,17 +569,28 @@ export const publicKeyOperations: Operation[] = [ } catch { throw new OperationError('That is not valid JSON.'); } - if (!jwk.kty) throw new OperationError("A JWK needs a 'kty' saying what kind of key it is."); + if (!jwk?.kty) throw new OperationError("A JWK needs a 'kty' saying what kind of key it is."); + + if ((jwk.alg !== undefined && typeof jwk.alg !== 'string') || + (jwk.key_ops !== undefined && !Array.isArray(jwk.key_ops))) + throw new OperationError('Invalid JWK algorithm or key operations.'); const isPrivate = typeof jwk.d === 'string'; + const oaepUsages: KeyUsage[] = isPrivate ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey']; + const oaep = jwk.alg?.startsWith('RSA-OAEP') || jwk.use === 'enc' || + jwk.key_ops?.some(usage => oaepUsages.includes(usage as KeyUsage)); + const rsaName = oaep ? 'RSA-OAEP' : jwk.alg?.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5'; const algorithm: RsaHashedImportParams | EcKeyImportParams = jwk.kty === 'EC' ? { name: 'ECDSA', namedCurve: jwk.crv ?? 'P-256' } - : { name: 'RSASSA-PKCS1-v1_5', hash: String(arg(args, 'Hash', 'SHA-256')) }; + : { name: rsaName, hash: String(arg(args, 'Hash', 'SHA-256')) }; let key: CryptoKey; try { - key = await subtle().importKey('jwk', jwk, algorithm, true, isPrivate ? ['sign'] : ['verify']); + const usage = algorithm.name === 'RSA-OAEP' + ? oaepUsages.find(value => jwk.key_ops?.includes(value)) ?? (isPrivate ? 'decrypt' : 'encrypt') + : isPrivate ? 'sign' : 'verify'; + key = await subtle().importKey('jwk', jwk, algorithm, true, [usage]); } catch (error) { throw new OperationError( `That JWK could not be read: ${error instanceof Error ? error.message : 'import failed'}`, diff --git a/src/engine/operations/sequence.ts b/src/engine/operations/sequence.ts index 25938b4..e1b74da 100644 --- a/src/engine/operations/sequence.ts +++ b/src/engine/operations/sequence.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -164,7 +165,7 @@ export const sequenceOperations: Operation[] = [ const pieces = delimiter === '' ? [...input] : input.split(delimiter); const random = new Uint32Array(pieces.length); - crypto.getRandomValues(random); + runtime.random(random); for (let i = pieces.length - 1; i > 0; i--) { const j = (random[i] as number) % (i + 1); [pieces[i], pieces[j]] = [pieces[j] as string, pieces[i] as string]; @@ -238,7 +239,7 @@ export const sequenceOperations: Operation[] = [ run: async (input, args) => { const wanted = Number(arg(args, 'Time (ms)', 1000)); const time = Math.min(Math.max(0, wanted), MAX_SLEEP_MS); - await new Promise((resolve) => setTimeout(resolve, time)); + await runtime.delay(time); return input; }, }, @@ -260,7 +261,7 @@ export const sequenceOperations: Operation[] = [ run: (_input, args) => { const count = Math.min(65536, Math.max(1, Number(arg(args, 'Number of bytes', 32)))); const bytes = new Uint8Array(count); - crypto.getRandomValues(bytes); + runtime.random(bytes); switch (String(arg(args, 'Output as', 'Hex'))) { case 'Integer': { @@ -303,7 +304,7 @@ export const sequenceOperations: Operation[] = [ const out: number[] = []; const buffer = new Uint32Array(1); while (out.length < count) { - crypto.getRandomValues(buffer); + runtime.random(buffer); const value = buffer[0] as number; if (value < limit) out.push(min + (value % range)); } diff --git a/src/engine/operations/streamCiphers.ts b/src/engine/operations/streamCiphers.ts index 770015c..6a7f433 100644 --- a/src/engine/operations/streamCiphers.ts +++ b/src/engine/operations/streamCiphers.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError, type OperationArg } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { parseKey, KEY_FORMATS } from './keys'; @@ -491,7 +492,7 @@ export const streamCipherOperations: Operation[] = [ const data = asBytes(input); const iv = new Uint8Array(10); - crypto.getRandomValues(iv); + runtime.random(iv); const schedule = new Uint8Array(key.length + 10); schedule.set(key); schedule.set(iv, key.length); diff --git a/src/engine/operations/structured.ts b/src/engine/operations/structured.ts index ef47ae5..2126d50 100644 --- a/src/engine/operations/structured.ts +++ b/src/engine/operations/structured.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { removeAll } from '../core/strip'; import { arg, type Operation } from './types'; @@ -335,7 +336,7 @@ export const structuredOperations: Operation[] = [ const decode = (segment: string) => { const padded = segment.replace(/-/g, '+').replace(/_/g, '/'); try { - return JSON.parse(atob(padded + '='.repeat((4 - (padded.length % 4)) % 4))) as Record< + return JSON.parse(runtime.fromBase64(padded + '='.repeat((4 - (padded.length % 4)) % 4))) as Record< string, unknown >; diff --git a/src/engine/operations/symmetric.ts b/src/engine/operations/symmetric.ts index a11d776..a6ab31d 100644 --- a/src/engine/operations/symmetric.ts +++ b/src/engine/operations/symmetric.ts @@ -1,13 +1,14 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1, toBytes } from '../core/bytes'; import { arg, type Operation } from './types'; -function requireSubtle(): SubtleCrypto { - if (!globalThis.crypto?.subtle) { +function requireSubtle(): NonNullable { + if (!runtime.subtle) { throw new OperationError('AES needs a secure context (HTTPS or localhost).'); } - return crypto.subtle; + return runtime.subtle; } function parseBytes(value: string, format: string, label: string): Uint8Array { @@ -25,7 +26,7 @@ function parseBytes(value: string, format: string, label: string): Uint8Array { if (format === 'Base64') { try { - const binary = atob(value.replace(/\s/g, '')); + const binary = runtime.fromBase64(value.replace(/\s/g, '')); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); return bytes; @@ -158,7 +159,7 @@ export const symmetricOperations: Operation[] = [ args: [{ name: 'Bits', type: 'option', value: '256', options: ['128', '192', '256'] }], run: (_input, args) => { const bytes = new Uint8Array(Number(arg(args, 'Bits', '256')) / 8); - crypto.getRandomValues(bytes); + runtime.random(bytes); return Array.from(bytes) .map((b) => b.toString(16).padStart(2, '0')) .join(''); @@ -173,7 +174,7 @@ export const symmetricOperations: Operation[] = [ args: [{ name: 'Bytes', type: 'number', value: 12, min: 8, max: 32 }], run: (_input, args) => { const bytes = new Uint8Array(Number(arg(args, 'Bytes', 12))); - crypto.getRandomValues(bytes); + runtime.random(bytes); return Array.from(bytes) .map((b) => b.toString(16).padStart(2, '0')) .join(''); @@ -191,9 +192,9 @@ export const symmetricOperations: Operation[] = [ ], run: (_input, args) => { const bytes = new Uint8Array(Number(arg(args, 'Bytes', 32))); - crypto.getRandomValues(bytes); + runtime.random(bytes); const format = String(arg(args, 'Output', 'Hex')); - if (format === 'Base64') return btoa(bytesToLatin1(bytes)); + if (format === 'Base64') return runtime.toBase64(bytesToLatin1(bytes)); if (format === 'Raw') return bytesToLatin1(bytes); return Array.from(bytes) .map((b) => b.toString(16).padStart(2, '0')) @@ -208,7 +209,7 @@ export const symmetricOperations: Operation[] = [ aliases: ['uuid', 'guid', 'new uuid'], args: [{ name: 'Count', type: 'number', value: 1, min: 1, max: 500 }], run: (_input, args) => - Array.from({ length: Number(arg(args, 'Count', 1)) }, () => crypto.randomUUID()).join('\n'), + Array.from({ length: Number(arg(args, 'Count', 1)) }, () => runtime.uuid()).join('\n'), }, { id: 'generate-password', @@ -229,7 +230,7 @@ export const symmetricOperations: Operation[] = [ return Array.from({ length: Number(arg(args, 'Count', 1)) }, () => { const values = new Uint32Array(length); - crypto.getRandomValues(values); + runtime.random(values); return Array.from(values, (v) => alphabet[v % alphabet.length]!).join(''); }).join('\n'); }, diff --git a/src/engine/operations/tls.ts b/src/engine/operations/tls.ts index 798e4ef..46a1fe0 100644 --- a/src/engine/operations/tls.ts +++ b/src/engine/operations/tls.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { md5 } from './hashing'; @@ -125,7 +126,7 @@ const JA4_VERSIONS: Record = { }; async function truncatedSha256(text: string): Promise { - const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)); + const digest = await runtime.subtle!.digest('SHA-256', runtime.encode(text)); const hex = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join(''); return hex.slice(0, JA4_TRUNCATION); } @@ -242,7 +243,7 @@ function decodeProtobuf(bytes: Uint8Array, depth = 0): ProtoField[] { const nested = decodeProtobuf(body, depth + 1); value = nested.length > 0 ? nested : `0x${bytesToHex(body)}`; } catch { - const text = new TextDecoder('utf-8', { fatal: true }); + const text = runtime.decoder('utf-8', { fatal: true }); try { value = text.decode(body); } catch { @@ -368,7 +369,7 @@ export const tlsOperations: Operation[] = [ const ciphers = joinNonGrease(hello.ciphers, 2); const text = [String(hello.version), ciphers, types.join('-'), curves, pointFormats].join(','); - const hash = md5(new TextEncoder().encode(text)); + const hash = md5(runtime.encode(text)); return fingerprintOutput( String(arg(args, 'Output format', 'Hash digest')), @@ -421,7 +422,7 @@ export const tlsOperations: Operation[] = [ } const text = [String(version), String(cipher), types.join('-')].join(','); - const hash = md5(new TextEncoder().encode(text)); + const hash = md5(runtime.encode(text)); return fingerprintOutput( String(arg(args, 'Output format', 'Hash digest')), hash, @@ -623,7 +624,7 @@ export const tlsOperations: Operation[] = [ const text = String(entry.value); const body = /^0x[0-9a-f]*$/i.test(text) ? new Uint8Array((text.slice(2).match(/../g) ?? []).map((p) => parseInt(p, 16))) - : new TextEncoder().encode(text); + : runtime.encode(text); writeVarint(BigInt(body.length)); out.push(...body); } else { @@ -661,7 +662,7 @@ function hassh(input: string, args: Parameters[1], client: boo ? [kex, encryptionC2S, macC2S, compressionC2S] : [kex, encryptionS2C, macS2C, compressionS2C]; const text = parts.join(';'); - const hash = md5(new TextEncoder().encode(text)); + const hash = md5(runtime.encode(text)); return fingerprintOutput( String(arg(args, 'Output format', 'Hash digest')), diff --git a/src/engine/operations/tokens.ts b/src/engine/operations/tokens.ts index 156b534..f07479b 100644 --- a/src/engine/operations/tokens.ts +++ b/src/engine/operations/tokens.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1, toBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -8,7 +9,7 @@ function base64UrlToBytes(text: string): Uint8Array { const normalised = text.trim().replace(/-/g, '+').replace(/_/g, '/'); const padded = normalised + '='.repeat((4 - (normalised.length % 4)) % 4); try { - return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0)); + return Uint8Array.from(runtime.fromBase64(padded), (c) => c.charCodeAt(0)); } catch { throw new OperationError('That is not valid URL-safe Base64.'); } @@ -17,12 +18,12 @@ function base64UrlToBytes(text: string): Uint8Array { function bytesToBase64Url(bytes: Uint8Array, padded = false): string { let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); - const encoded = btoa(binary).replace(/\+/g, '-').replace(/\//g, '_'); + const encoded = runtime.toBase64(binary).replace(/\+/g, '-').replace(/\//g, '_'); return padded ? encoded : encoded.replace(/=+$/, ''); } -function subtle(): SubtleCrypto { - const api = globalThis.crypto?.subtle; +function subtle(): NonNullable { + const api = runtime.subtle; if (!api) throw new OperationError('This needs Web Crypto, which the browser has not exposed here.'); return api; } @@ -87,13 +88,11 @@ async function flaskKey(secret: string, salt: string): Promise { } async function inflate(bytes: Uint8Array): Promise { - const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate')); - return new Uint8Array(await new Response(stream).arrayBuffer()); + return runtime.transform(bytes, 'deflate', false); } async function deflate(bytes: Uint8Array): Promise { - const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new CompressionStream('deflate')); - return new Uint8Array(await new Response(stream).arrayBuffer()); + return runtime.transform(bytes, 'deflate', true); } function encodeTimestamp(seconds: number): Uint8Array { @@ -154,7 +153,7 @@ export const tokenOperations: Operation[] = [ const seconds = given > 0 ? Math.trunc(given) : Math.floor(Date.now() / 1000); const iv = new Uint8Array(16); - globalThis.crypto.getRandomValues(iv); + runtime.random(iv); const header = new Uint8Array(9); header[0] = FERNET_VERSION; diff --git a/src/engine/operations/units.ts b/src/engine/operations/units.ts index 02159a5..4499c86 100644 --- a/src/engine/operations/units.ts +++ b/src/engine/operations/units.ts @@ -139,7 +139,7 @@ const MASS: Record = { const SPEED: Record = { 'Metres per second (m/s)': 1, - 'Kilometres per hour (km/h)': 0.2778, + 'Kilometres per hour (km/h)': 1000 / 3600, 'Miles per hour (mph)': 0.44704, 'Knots (kn)': 0.5144, 'Human hair growth rate': 4.8e-9, diff --git a/src/engine/operations/utils.ts b/src/engine/operations/utils.ts index 7c5ffa5..85fafe3 100644 --- a/src/engine/operations/utils.ts +++ b/src/engine/operations/utils.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { latin1ToBytes } from '../core/bytes'; import { DELIMITER_OPTIONS, delimiterFor } from '../core/delimiters'; @@ -7,7 +8,7 @@ function decodeJwtSegment(segment: string): string { const padded = segment.replace(/-/g, '+').replace(/_/g, '/'); const full = padded + '='.repeat((4 - (padded.length % 4)) % 4); try { - return new TextDecoder().decode(latin1ToBytes(atob(full))); + return runtime.decoder().decode(latin1ToBytes(runtime.fromBase64(full))); } catch { throw new OperationError('JWT segment is not valid Base64url.'); } diff --git a/src/engine/operations/wire.ts b/src/engine/operations/wire.ts index 2fc4670..399059d 100644 --- a/src/engine/operations/wire.ts +++ b/src/engine/operations/wire.ts @@ -1,3 +1,4 @@ +import { runtime } from '../runtime'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1, latin1ToBytes } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -31,7 +32,7 @@ function isPlainContentByte(byte: number, convertSpaces: boolean): boolean { function decodeCharset(charset: string, bytes: Uint8Array): string { try { - return new TextDecoder(charset.toLowerCase(), { fatal: false }).decode(bytes); + return runtime.decoder(charset.toLowerCase(), { fatal: false }).decode(bytes); } catch { throw new OperationError(`'${charset}' is not a character set this browser knows.`); } @@ -173,7 +174,7 @@ export const wireOperations: Operation[] = [ const base64 = input.slice(bodyStart, bodyEnd).replace(/[^A-Za-z0-9+/=]/g, ''); try { - blocks.push(hexOf(latin1ToBytes(atob(base64)))); + blocks.push(hexOf(latin1ToBytes(runtime.fromBase64(base64)))); } catch { throw new OperationError(`The ${label} block does not hold valid Base64.`); } @@ -199,7 +200,7 @@ export const wireOperations: Operation[] = [ if (!/^[A-Z][A-Z0-9 ]*$/.test(label)) { throw new OperationError('A PEM label is upper-case letters, digits and spaces.'); } - const base64 = btoa(bytesToLatin1(parseHex(input))); + const base64 = runtime.toBase64(bytesToLatin1(parseHex(input))); const lines = base64.match(new RegExp(`.{1,${PEM_LINE_LENGTH}}`, 'g')) ?? []; return [`-----BEGIN ${label}-----`, ...lines, `-----END ${label}-----`, ''].join('\n'); }, @@ -282,7 +283,7 @@ export const wireOperations: Operation[] = [ let bytes: Uint8Array; if (encoding.toLowerCase() === 'b') { try { - bytes = latin1ToBytes(atob(body.replace(/[^A-Za-z0-9+/=]/g, ''))); + bytes = latin1ToBytes(runtime.fromBase64(body.replace(/[^A-Za-z0-9+/=]/g, ''))); } catch { throw new OperationError('An encoded word does not hold valid Base64.'); } @@ -365,7 +366,7 @@ export const wireOperations: Operation[] = [ let bytes: Uint8Array; if (String(arg(args, 'Input format', 'Raw')) === 'Base64') { try { - bytes = latin1ToBytes(atob(input.replace(/[^A-Za-z0-9+/=]/g, ''))); + bytes = latin1ToBytes(runtime.fromBase64(input.replace(/[^A-Za-z0-9+/=]/g, ''))); } catch { throw new OperationError('Input is not valid Base64.'); } @@ -383,7 +384,7 @@ export const wireOperations: Operation[] = [ for (let offset = 0; offset < 3; offset++) { const padded = new Uint8Array(offset + bytes.length); padded.set(bytes, offset); - const encoded = btoa(bytesToLatin1(padded)); + const encoded = runtime.toBase64(bytesToLatin1(padded)); const head = offset === 0 ? 0 : offset + 1; const unpadded = encoded.indexOf('=') === -1 ? encoded.length : encoded.indexOf('='); diff --git a/src/engine/operations/xpress.ts b/src/engine/operations/xpress.ts index e8052d1..1742bc5 100644 --- a/src/engine/operations/xpress.ts +++ b/src/engine/operations/xpress.ts @@ -1,3 +1,4 @@ +import { MAX_OUTPUT } from '../runtime/limits'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { arg, type Operation } from './types'; @@ -28,7 +29,7 @@ class Input { } } -const MAX_OUTPUT = 64 * 1024 * 1024; + function grow(out: number[], length: number): void { if (out.length + length > MAX_OUTPUT) { diff --git a/src/engine/runtime/browser.ts b/src/engine/runtime/browser.ts new file mode 100644 index 0000000..5cf1db1 --- /dev/null +++ b/src/engine/runtime/browser.ts @@ -0,0 +1,132 @@ +import type { Compression, RuntimeProvider } from './provider'; +import { checkSize, MAX_OUTPUT } from './limits'; + +function zoneNames(): string[] { + try { + const supported = ( + Intl as unknown as { supportedValuesOf?: (key: string) => string[] } + ).supportedValuesOf?.('timeZone'); + if (supported && supported.length > 0) return ['UTC', ...supported]; + } catch {} + return ['UTC']; +} + +function zoneOffset(zone: string, instant: number): number { + if (zone === 'UTC') return 0; + const formatter = new Intl.DateTimeFormat('en-GB', { + timeZone: zone, + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + hour12: false, + }); + const parts: Record = {}; + for (const part of formatter.formatToParts(new Date(instant))) parts[part.type] = part.value; + const asUtc = Date.UTC( + Number(parts.year), + Number(parts.month) - 1, + Number(parts.day), + Number(parts.hour) % 24, + Number(parts.minute), + Number(parts.second), + ); + return Math.round((asUtc - Math.floor(instant / 1000) * 1000) / 60000); +} + +function zoneAbbreviation(zone: string, instant: number): string { + try { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone: zone, + timeZoneName: 'short', + }).formatToParts(new Date(instant)); + return parts.find((part) => part.type === 'timeZoneName')?.value ?? zone; + } catch { + return zone; + } +} + +export const browserProvider: RuntimeProvider = { + name: 'web', + timeZones: zoneNames, + zoneOffset, + zoneAbbreviation, + get secureRandom() { + return typeof globalThis.crypto?.getRandomValues === 'function'; + }, + compressionFormats() { + const formats: Compression[] = ['gzip', 'deflate', 'deflate-raw']; + return formats.filter((format) => { + try { + new CompressionStream(format); + new DecompressionStream(format); + return true; + } catch { + return false; + } + }); + }, + get subtle() { + return globalThis.crypto?.subtle; + }, + decoder: (label, options) => new TextDecoder(label, options), + encode: (text) => new TextEncoder().encode(text), + toBase64: (binary) => btoa(binary), + fromBase64: (encoded) => atob(encoded), + parseUrl: (text) => new URL(text), + query: (text) => new URLSearchParams(text), + random(target) { + const bytes = new Uint8Array(target.buffer, target.byteOffset, target.byteLength); + for (let i = 0; i < bytes.length; i += 65536) + crypto.getRandomValues(bytes.subarray(i, i + 65536)); + return target; + }, + uuid: () => crypto.randomUUID(), + now: () => performance.now(), + delay: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + async timed(work, ms, timeout) { + const start = performance.now(); + let timer: ReturnType | undefined; + try { + const result = await Promise.race([ + work(), + new Promise((_, reject) => { + timer = setTimeout(() => reject(timeout()), ms); + }), + ]); + if (performance.now() - start > ms) throw timeout(); + return result; + } finally { + clearTimeout(timer); + } + }, + async transform(bytes, format, compress, limit = MAX_OUTPUT) { + const transform = compress ? new CompressionStream(format) : new DecompressionStream(format); + const reader = new Blob([bytes as BlobPart]).stream().pipeThrough(transform).getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + for (;;) { + const part = await reader.read(); + if (part.done) break; + length += part.value.byteLength; + checkSize(length, limit); + chunks.push(part.value); + } + } catch (error) { + await reader.cancel().catch(() => {}); + throw error; + } finally { + reader.releaseLock(); + } + const out = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.length; + } + return out; + }, +}; diff --git a/src/engine/runtime/graal.d.ts b/src/engine/runtime/graal.d.ts new file mode 100644 index 0000000..77cb0f4 --- /dev/null +++ b/src/engine/runtime/graal.d.ts @@ -0,0 +1,2 @@ +import type { RuntimeProvider } from './provider'; +export function createGraalProvider(): RuntimeProvider; diff --git a/src/engine/runtime/graal.js b/src/engine/runtime/graal.js new file mode 100644 index 0000000..b03e72c --- /dev/null +++ b/src/engine/runtime/graal.js @@ -0,0 +1,127 @@ +import { TextDecoder, TextEncoder } from '@exodus/bytes/encoding.js'; +import urls from 'whatwg-url/lib/url-state-machine.js'; +import forms from 'whatwg-url/lib/urlencoded.js'; +import { javaBytes, jsBytes } from './java-bytes'; +import { javaCrypto } from './java-crypto'; +import { checkSize, MAX_OUTPUT } from './limits'; + +function transform(bytes, format, compress, limit = MAX_OUTPUT) { + const source = new (Java.type('java.io.ByteArrayInputStream'))(javaBytes(bytes)); + const sink = new (Java.type('java.io.ByteArrayOutputStream'))(); + const raw = format === 'deflate-raw'; + let codec, stream; + try { + if (compress) { + if (format === 'gzip') stream = new (Java.type('java.util.zip.GZIPOutputStream'))(sink); + else { + codec = new (Java.type('java.util.zip.Deflater'))(-1, raw); + stream = new (Java.type('java.util.zip.DeflaterOutputStream'))(sink, codec); + } + source.transferTo(stream); + stream.finish(); + checkSize(sink.size(), limit); + } else { + if (format === 'gzip') stream = new (Java.type('java.util.zip.GZIPInputStream'))(source); + else { + codec = new (Java.type('java.util.zip.Inflater'))(raw); + stream = new (Java.type('java.util.zip.InflaterInputStream'))(source, codec); + } + const buffer = new (Java.type('byte[]'))(8192); + for (let count; (count = stream.read(buffer)) !== -1; ) { + checkSize(sink.size() + count, limit); + sink.write(buffer, 0, count); + } + if (codec && !codec.finished()) throw new Error('Incomplete DEFLATE stream.'); + } + return jsBytes(sink.toByteArray()); + } finally { + try { + stream?.close(); + } finally { + codec?.end(); + } + } +} + +export function createGraalProvider() { + const rng = new (Java.type('java.security.SecureRandom'))(); + const base64 = Java.type('java.util.Base64'); + const clock = Java.type('java.lang.System'); + const now = () => Number(clock.nanoTime()) / 1e6; + const ZoneId = Java.type('java.time.ZoneId'); + const Instant = Java.type('java.time.Instant'); + const DateTimeFormatter = Java.type('java.time.format.DateTimeFormatter'); + const zoneName = DateTimeFormatter.ofPattern('z', Java.type('java.util.Locale').US); + const encoder = new TextEncoder(); + return { + name: 'graaljs-java', + timeZones: () => [ + 'UTC', + ...Array.from(ZoneId.getAvailableZoneIds().toArray(), String) + .filter((z) => z.includes('/')) + .sort(), + ], + zoneOffset(zone, instant) { + return ( + ZoneId.of(zone).getRules().getOffset(Instant.ofEpochMilli(instant)).getTotalSeconds() / 60 + ); + }, + zoneAbbreviation(zone, instant) { + return String(zoneName.format(Instant.ofEpochMilli(instant).atZone(ZoneId.of(zone)))); + }, + secureRandom: true, + compressionFormats: () => ['gzip', 'deflate', 'deflate-raw'], + subtle: javaCrypto(), + decoder: (label, options) => new TextDecoder(label, options), + encode: (text) => encoder.encode(text), + toBase64(binary) { + if (/[\u0100-\uffff]/.test(binary)) throw new TypeError('Base64 requires bytes.'); + return String( + base64 + .getEncoder() + .encodeToString(javaBytes(Uint8Array.from(binary, (c) => c.charCodeAt(0)))), + ); + }, + fromBase64(encoded) { + const bytes = jsBytes(base64.getDecoder().decode(encoded.replace(/[\t\n\f\r ]/g, ''))); + let text = ''; + for (let i = 0; i < bytes.length; i += 8192) + text += String.fromCharCode(...bytes.subarray(i, i + 8192)); + return text; + }, + parseUrl(text) { + const u = urls.parseURL(text); + if (!u) throw new TypeError('Invalid URL.'); + return { + protocol: u.scheme + ':', + hostname: u.host === null ? '' : urls.serializeHost(u.host), + port: String(u.port ?? ''), + username: u.username, + password: u.password, + pathname: urls.serializePath(u), + hash: u.fragment ? '#' + u.fragment : '', + searchParams: forms.parseUrlencodedString(u.query ?? ''), + }; + }, + query: (text) => forms.parseUrlencodedString(text), + random(target) { + const buffer = new (Java.type('byte[]'))(target.byteLength); + rng.nextBytes(buffer); + new Uint8Array(target.buffer, target.byteOffset, target.byteLength).set(buffer); + return target; + }, + uuid: () => String(Java.type('java.util.UUID').randomUUID()), + transform: async (...args) => transform(...args), + now, + // Plain Graal contexts have no event loop. Java work stays on the owning thread. + async delay(ms) { + Java.type('java.lang.Thread').sleep(ms); + }, + async timed(work, ms, timeout) { + const start = now(); + const result = await work(); + if (now() - start > ms) throw timeout(); + return result; + }, + }; +} diff --git a/src/engine/runtime/index.ts b/src/engine/runtime/index.ts new file mode 100644 index 0000000..5ac6112 --- /dev/null +++ b/src/engine/runtime/index.ts @@ -0,0 +1,9 @@ +import { browserProvider } from './browser'; +import type { RuntimeProvider } from './provider'; + +export let runtime: RuntimeProvider = browserProvider; + +// Called during SDK module initialization, before registry modules probe character sets. +export function installProvider(provider: RuntimeProvider): void { + runtime = provider; +} diff --git a/src/engine/runtime/java-bytes.js b/src/engine/runtime/java-bytes.js new file mode 100644 index 0000000..e92fcdd --- /dev/null +++ b/src/engine/runtime/java-bytes.js @@ -0,0 +1,14 @@ +// Java bytes are signed. Reinterpret exactly the addressed view, including its offset. +export function javaBytes(value) { + if (!ArrayBuffer.isView(value) && !(value instanceof ArrayBuffer)) + throw new TypeError('Expected a BufferSource.'); + const view = ArrayBuffer.isView(value) + ? new Int8Array(value.buffer, value.byteOffset, value.byteLength) + : new Int8Array(value); + return Java.to(view, 'byte[]'); +} +export function jsBytes(value) { + const bytes = new Uint8Array(value.length); + bytes.set(value); + return bytes; +} diff --git a/src/engine/runtime/java-crypto.js b/src/engine/runtime/java-crypto.js new file mode 100644 index 0000000..330989b --- /dev/null +++ b/src/engine/runtime/java-crypto.js @@ -0,0 +1,387 @@ +import { checkSize } from './limits'; +import { TextDecoder } from '@exodus/bytes/encoding.js'; +import { javaBytes, jsBytes } from './java-bytes'; +import { curveSpec, importAsymmetric, exportAsymmetric } from './java-keys'; + +const nameOf = (value) => (typeof value === 'string' ? value : value.name); +function hashName(value) { + const hash = nameOf(value); + if (!['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'].includes(hash)) + throw new Error('Unsupported hash.'); + return hash; +} +const hmacName = (hash) => 'Hmac' + nameOf(hash).replace('-', ''); +const mgf = (hash) => new (Java.type('java.security.spec.MGF1ParameterSpec'))(hash); + +function macFor(hash, raw) { + const mac = Java.type('javax.crypto.Mac').getInstance(hmacName(hash)); + // HMAC pads a short key with zeros. JCA rejects a zero-length SecretKeySpec. + const bytes = raw.length ? raw : new (Java.type('byte[]'))(1); + mac.init(new (Java.type('javax.crypto.spec.SecretKeySpec'))(bytes, hmacName(hash))); + return mac; +} +function derive(params, raw, length) { + const hash = hashName(params.hash); + checkSize(length / 8); + const salt = javaBytes(params.salt); + if ( + !Number.isSafeInteger(params.iterations) || + params.iterations < 1 || + params.iterations > 5_000_000 || + !Number.isSafeInteger(length) || + length < 8 || + length % 8 + ) { + throw new Error('Invalid PBKDF2 parameters.'); + } + let password; + try { + password = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(jsBytes(raw)); + } catch {} + if (password !== undefined && salt.length) { + const chars = Java.to(password.split(''), 'char[]'); + const spec = new (Java.type('javax.crypto.spec.PBEKeySpec'))( + chars, + salt, + params.iterations, + length, + ); + try { + const factory = Java.type('javax.crypto.SecretKeyFactory').getInstance( + 'PBKDF2With' + hmacName(hash), + ); + return jsBytes(factory.generateSecret(spec).getEncoded()).buffer; + } finally { + spec.clearPassword(); + } + } + // PBEKeySpec accepts characters. Preserve arbitrary binary passwords using RFC 8018 F. + const mac = macFor(hash, raw); + const out = new Uint8Array(length / 8); + for (let offset = 0, block = 1; offset < out.length; block++) { + mac.update(salt); + let u = mac.doFinal(javaBytes(Uint8Array.of(block >>> 24, block >>> 16, block >>> 8, block))); + const t = jsBytes(u); + for (let i = 1; i < params.iterations; i++) { + u = mac.doFinal(u); + for (let j = 0; j < t.length; j++) t[j] ^= u[j]; + } + out.set(t.subarray(0, out.length - offset), offset); + offset += t.length; + } + return out.buffer; +} +function signature(params, material) { + const name = material.algorithm.name; + const hash = name === 'ECDSA' ? hashName(params.hash) : material.algorithm.hash; + const jca = + name === 'RSA-PSS' + ? 'RSASSA-PSS' + : hash.replace('-', '') + (name === 'ECDSA' ? 'withECDSAinP1363Format' : 'withRSA'); + const signer = Java.type('java.security.Signature').getInstance(jca); + if (name === 'RSA-PSS') + signer.setParameter( + new (Java.type('java.security.spec.PSSParameterSpec'))( + hash, + 'MGF1', + mgf(hash), + params.saltLength, + 1, + ), + ); + return signer; +} +function crypt(params, material, input, encrypt) { + const name = material.algorithm.name; + const Cipher = Java.type('javax.crypto.Cipher'); + let spec, cipher, key; + if (name === 'RSA-OAEP') { + const hash = material.algorithm.hash; + cipher = Cipher.getInstance('RSA/ECB/OAEPPadding'); + spec = new (Java.type('javax.crypto.spec.OAEPParameterSpec'))( + hash, + 'MGF1', + mgf(hash), + params.label === undefined + ? Java.type('javax.crypto.spec.PSource$PSpecified').DEFAULT + : new (Java.type('javax.crypto.spec.PSource$PSpecified'))(javaBytes(params.label)), + ); + key = material.key; + } else { + const modes = { + 'AES-GCM': 'AES/GCM/NoPadding', + 'AES-CBC': 'AES/CBC/PKCS5Padding', + 'AES-CTR': 'AES/CTR/NoPadding', + }; + if (!Object.hasOwn(modes, name)) throw new Error('Unsupported cipher ' + name); + cipher = Cipher.getInstance(modes[name]); + key = new (Java.type('javax.crypto.spec.SecretKeySpec'))(material.raw, 'AES'); + spec = + name === 'AES-GCM' + ? new (Java.type('javax.crypto.spec.GCMParameterSpec'))( + params.tagLength ?? 128, + javaBytes(params.iv), + ) + : new (Java.type('javax.crypto.spec.IvParameterSpec'))( + javaBytes(name === 'AES-CTR' ? params.counter : params.iv), + ); + } + cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key, spec); + if (name === 'AES-GCM' && params.additionalData !== undefined) + cipher.updateAAD(javaBytes(params.additionalData)); + // JCA increments the entire counter. Preserve the nonce when the low field wraps. + if (name === 'AES-CTR') { + const bits = params.length; + if (!Number.isInteger(bits) || bits < 1 || bits > 128) + throw new Error('Invalid AES counter length.'); + const range = 1n << BigInt(bits); + if (BigInt(Math.ceil(input.byteLength / 16)) > range) throw new Error('AES counter exhausted.'); + const counter = jsBytes(spec.getIV()); + const view = new DataView(counter.buffer); + const initial = (view.getBigUint64(0) << 64n) | view.getBigUint64(8); + const low = initial % range; + const beforeWrap = (range - low) * 16n; + if (beforeWrap < BigInt(input.byteLength)) { + const cut = Number(beforeWrap); + const data = jsBytes(javaBytes(input)); + const output = new Uint8Array(data.length); + output.set(jsBytes(cipher.doFinal(javaBytes(data.subarray(0, cut))))); + const nonce = initial - low; + view.setBigUint64(0, nonce >> 64n); + view.setBigUint64(8, nonce); + const next = new (Java.type('javax.crypto.spec.IvParameterSpec'))(javaBytes(counter)); + cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key, next); + output.set(jsBytes(cipher.doFinal(javaBytes(data.subarray(cut)))), cut); + return output.buffer; + } + } + return jsBytes(cipher.doFinal(javaBytes(input))).buffer; +} +const signing = { public: ['verify'], private: ['sign'] }; +const encryption = { public: ['encrypt', 'wrapKey'], private: ['decrypt', 'unwrapKey'] }; +const aes = { secret: [...encryption.public, ...encryption.private] }; +const permissions = { + ECDSA: signing, + 'RSASSA-PKCS1-v1_5': signing, + 'RSA-PSS': signing, + 'RSA-OAEP': encryption, + 'AES-GCM': aes, + 'AES-CBC': aes, + 'AES-CTR': aes, + HMAC: { secret: ['sign', 'verify'] }, + PBKDF2: { secret: ['deriveBits', 'deriveKey'] }, +}; + +function keyAlgorithm(params) { + const name = nameOf(params); + if (!Object.hasOwn(permissions, name)) throw new Error('Unsupported key algorithm.'); + if (name === 'ECDSA') return { name, namedCurve: params.namedCurve }; + if (name === 'HMAC' || !permissions[name].secret) { + return { name, hash: hashName(params.hash) }; + } + return { name }; +} + +function exponentBytes(integer) { + const bytes = jsBytes(integer.toByteArray()); + return bytes[0] === 0 ? bytes.slice(1) : bytes; +} + +function checkUsages(usages, allowed, requireUsage) { + if ( + !Array.isArray(usages) || + new Set(usages).size !== usages.length || + (requireUsage && !usages.length) || + usages.some((usage) => !allowed.includes(usage)) + ) { + throw new Error('Invalid usages for this key.'); + } +} + +// Each provider owns its handles. Only this map holds JCA keys and secret byte arrays. +export function javaCrypto() { + const materials = new WeakMap(); + function makeHandle(material, type, extractable, usages) { + const algorithm = material.algorithm; + const handle = Object.freeze({ + type, + extractable: Boolean(extractable), + usages: Object.freeze([...usages]), + get algorithm() { + const copy = { ...algorithm }; + if (algorithm.hash) copy.hash = { name: algorithm.hash }; + if (algorithm.publicExponent) copy.publicExponent = algorithm.publicExponent.slice(); + return copy; + }, + }); + materials.set(handle, material); + return handle; + } + + function keyFor(handle, params, usage) { + const key = materials.get(handle); + if (!key || key.algorithm.name !== nameOf(params) || !handle.usages.includes(usage)) { + throw new Error('Key does not permit this operation.'); + } + return key; + } + return { + async digest(hash, bytes) { + return jsBytes( + Java.type('java.security.MessageDigest') + .getInstance(hashName(hash)) + .digest(javaBytes(bytes)), + ).buffer; + }, + async importKey(format, data, params, extractable, usages) { + usages = Array.from(usages); + if (format === 'jwk') { + data = { ...data }; + if (Array.isArray(data.key_ops)) data.key_ops = Array.from(data.key_ops); + } + const algorithm = keyAlgorithm(params); + const roles = permissions[algorithm.name]; + if (roles.secret) { + if (format !== 'raw' || !(ArrayBuffer.isView(data) || data instanceof ArrayBuffer)) + throw new Error('Expected raw secret key bytes.'); + checkUsages(usages, roles.secret, true); + if (algorithm.name === 'PBKDF2' && extractable) + throw new Error('PBKDF2 keys cannot be exported.'); + if (roles === aes && ![16, 24, 32].includes(data.byteLength)) + throw new Error('Invalid AES key size.'); + if ( + algorithm.name === 'HMAC' && + (!data.byteLength || + (params.length !== undefined && params.length !== data.byteLength * 8)) + ) + throw new Error('Expected a non-empty, byte-aligned HMAC key.'); + if (algorithm.name !== 'PBKDF2') algorithm.length = data.byteLength * 8; + return makeHandle({ raw: javaBytes(data), algorithm }, 'secret', extractable, usages); + } + if (!['jwk', 'pkcs8', 'spki'].includes(format)) + throw new Error('Unsupported asymmetric key format.'); + const type = + format === 'pkcs8' || (format === 'jwk' && data.d !== undefined) ? 'private' : 'public'; + checkUsages(usages, roles[type], type === 'private'); + const key = importAsymmetric(format, data, algorithm, usages, extractable, roles[type]); + if (algorithm.name !== 'ECDSA') { + algorithm.modulusLength = key.key.getModulus().bitLength(); + if (key.key.getPublicExponent) + algorithm.publicExponent = exponentBytes(key.key.getPublicExponent()); + } + return makeHandle(key, type, extractable, usages); + }, + async generateKey(params, extractable, usages) { + usages = Array.from(usages); + const algorithm = keyAlgorithm(params); + const roles = permissions[algorithm.name]; + if (!roles.private) throw new Error('Unsupported key generation algorithm.'); + checkUsages(usages, [...roles.private, ...roles.public], true); + const privateUsages = usages.filter((usage) => roles.private.includes(usage)); + checkUsages(privateUsages, roles.private, true); + const ec = algorithm.name === 'ECDSA'; + const generator = Java.type('java.security.KeyPairGenerator').getInstance(ec ? 'EC' : 'RSA'); + if (ec) generator.initialize(curveSpec(algorithm.namedCurve)); + else { + if ( + !Number.isInteger(params.modulusLength) || + params.modulusLength < 512 || + params.modulusLength > 16384 || + !(params.publicExponent instanceof Uint8Array) + ) + throw new Error('Invalid RSA generation parameters.'); + const e = new (Java.type('java.math.BigInteger'))(1, javaBytes(params.publicExponent)); + if (!e.testBit(0) || e.bitLength() < 2 || e.bitLength() > 32) + throw new Error('Unsupported RSA exponent.'); + generator.initialize( + new (Java.type('java.security.spec.RSAKeyGenParameterSpec'))(params.modulusLength, e), + ); + algorithm.modulusLength = params.modulusLength; + algorithm.publicExponent = exponentBytes(e); + } + const pair = generator.generateKeyPair(); + return { + publicKey: makeHandle( + { key: pair.getPublic(), algorithm, secret: false }, + 'public', + true, + usages.filter((usage) => roles.public.includes(usage)), + ), + privateKey: makeHandle( + { key: pair.getPrivate(), algorithm, secret: true }, + 'private', + extractable, + privateUsages, + ), + }; + }, + async exportKey(format, handle) { + const key = materials.get(handle); + if (!key || !handle.extractable) throw new Error('Key cannot be exported.'); + if (handle.type === 'secret') { + if (format !== 'raw') throw new Error('Unsupported secret key export format.'); + return jsBytes(key.raw).buffer; + } + if (format !== 'jwk' && format !== (handle.type === 'private' ? 'pkcs8' : 'spki')) + throw new Error('Export format does not match the key type.'); + return exportAsymmetric(format, { ...key, usages: [...handle.usages] }); + }, + async deriveBits(params, handle, length) { + const key = keyFor(handle, params, 'deriveBits'); + return derive(params, key.raw, length); + }, + async deriveKey(params, handle, target, extractable, usages) { + const key = keyFor(handle, params, 'deriveKey'); + const algorithm = keyAlgorithm(target); + const roles = permissions[algorithm.name]; + if (roles !== aes && algorithm.name !== 'HMAC') throw new Error('Unsupported derived key.'); + const length = + target.length ?? + (algorithm.name === 'HMAC' + ? ['SHA-384', 'SHA-512'].includes(algorithm.hash) + ? 1024 + : 512 + : undefined); + if (roles === aes && ![128, 192, 256].includes(length)) + throw new Error('Invalid AES key size.'); + usages = Array.from(usages); + checkUsages(usages, roles.secret, true); + algorithm.length = length; + return makeHandle( + { raw: javaBytes(derive(params, key.raw, length)), algorithm }, + 'secret', + extractable, + usages, + ); + }, + async sign(params, handle, input) { + const key = keyFor(handle, params, 'sign'); + if (key.algorithm.name === 'HMAC') + return jsBytes(macFor(key.algorithm.hash, key.raw).doFinal(javaBytes(input))).buffer; + const s = signature(params, key); + s.initSign(key.key); + s.update(javaBytes(input)); + return jsBytes(s.sign()).buffer; + }, + async verify(params, handle, sig, input) { + const key = keyFor(handle, params, 'verify'); + if (key.algorithm.name === 'HMAC') + return Java.type('java.security.MessageDigest').isEqual( + javaBytes(sig), + macFor(key.algorithm.hash, key.raw).doFinal(javaBytes(input)), + ); + const s = signature(params, key); + s.initVerify(key.key); + s.update(javaBytes(input)); + return s.verify(javaBytes(sig)); + }, + async encrypt(params, handle, data) { + const key = keyFor(handle, params, 'encrypt'); + return crypt(params, key, data, true); + }, + async decrypt(params, handle, data) { + const key = keyFor(handle, params, 'decrypt'); + return crypt(params, key, data, false); + }, + }; +} diff --git a/src/engine/runtime/java-keys.js b/src/engine/runtime/java-keys.js new file mode 100644 index 0000000..f505664 --- /dev/null +++ b/src/engine/runtime/java-keys.js @@ -0,0 +1,191 @@ +import { p256, p384, p521 } from '@noble/curves/nist.js'; +import { javaBytes, jsBytes } from './java-bytes'; + +const curves = { + 'P-256': ['secp256r1', p256, 32], + 'P-384': ['secp384r1', p384, 48], + 'P-521': ['secp521r1', p521, 66], +}; +const rsaFields = { + n: 'getModulus', + e: 'getPublicExponent', + d: 'getPrivateExponent', + p: 'getPrimeP', + q: 'getPrimeQ', + dp: 'getPrimeExponentP', + dq: 'getPrimeExponentQ', + qi: 'getCrtCoefficient', +}; + +// RSA JWK integers use minimal unsigned encodings. EC fields have a fixed width. +function integer(text, width) { + if ( + typeof text !== 'string' || + text.length > Math.ceil(((width ?? 2048) * 4) / 3) || + !/^[A-Za-z0-9_-]+$/.test(text) + ) + throw new Error('Invalid JWK integer.'); + const bytes = Java.type('java.util.Base64').getUrlDecoder().decode(text); + if (encode(jsBytes(bytes)) !== text || (width ? bytes.length !== width : bytes[0] === 0)) + throw new Error('Noncanonical JWK integer.'); + return new (Java.type('java.math.BigInteger'))(1, bytes); +} + +function jwa(algorithm) { + if (algorithm.name === 'ECDSA') + return { 'P-256': 'ES256', 'P-384': 'ES384', 'P-521': 'ES512' }[algorithm.namedCurve]; + const bits = algorithm.hash.slice(4); + if (algorithm.name === 'RSA-OAEP') return bits === '1' ? 'RSA-OAEP' : 'RSA-OAEP-' + bits; + return (algorithm.name === 'RSA-PSS' ? 'PS' : 'RS') + bits; +} + +function rsaSpec(data, secret) { + const fields = Object.keys(rsaFields); + if (data.oth !== undefined || (!secret && fields.slice(2).some((f) => data[f] !== undefined))) + throw new Error('Expected a public or two-prime private RSA key.'); + const n = integer(data.n); + const e = integer(data.e); + if (!n.testBit(0) || !e.testBit(0) || e.bitLength() < 2 || e.compareTo(n) >= 0) + throw new Error('Invalid RSA modulus or exponent.'); + if (!secret) return new (Java.type('java.security.spec.RSAPublicKeySpec'))(n, e); + const [d, p, q, dp, dq, qi] = fields.slice(2).map((f) => integer(data[f])); + const one = Java.type('java.math.BigInteger').ONE; + if ( + !p.testBit(0) || + !q.testBit(0) || + p.equals(q) || + !p.multiply(q).equals(n) || + p.compareTo(one) <= 0 || + q.compareTo(one) <= 0 || + d.compareTo(n) >= 0 + ) + throw new Error('Inconsistent RSA private components.'); + const pm = p.subtract(one); + const qm = q.subtract(one); + if ( + !d.mod(pm).equals(dp) || + !d.mod(qm).equals(dq) || + !e.multiply(dp).mod(pm).equals(one) || + !e.multiply(dq).mod(qm).equals(one) || + qi.compareTo(p) >= 0 || + !qi.multiply(q).mod(p).equals(one) || + !p.isProbablePrime(100) || + !q.isProbablePrime(100) + ) + throw new Error('Invalid RSA CRT components.'); + return new (Java.type('java.security.spec.RSAPrivateCrtKeySpec'))(n, e, d, p, q, dp, dq, qi); +} +function unsigned(integer, width) { + let bytes = jsBytes(integer.toByteArray()); + if (bytes.length > 1 && bytes[0] === 0) bytes = bytes.subarray(1); + if (!width) return bytes; + const padded = new Uint8Array(width); + padded.set(bytes, width - bytes.length); + return padded; +} +function encode(bytes) { + return String( + Java.type('java.util.Base64').getUrlEncoder().withoutPadding().encodeToString(javaBytes(bytes)), + ); +} +export function curveSpec(name) { + if (typeof name !== 'string' || !Object.hasOwn(curves, name)) + throw new Error('Unsupported EC curve.'); + return new (Java.type('java.security.spec.ECGenParameterSpec'))(curves[name][0]); +} +function ecParameters(name) { + const ap = Java.type('java.security.AlgorithmParameters').getInstance('EC'); + ap.init(curveSpec(name)); + return ap.getParameterSpec(Java.type('java.security.spec.ECParameterSpec').class); +} +export function importAsymmetric(format, data, algorithm, usages, extractable, allowed) { + const ec = algorithm.name === 'ECDSA'; + const factory = Java.type('java.security.KeyFactory').getInstance(ec ? 'EC' : 'RSA'); + const secret = format === 'pkcs8' || (format === 'jwk' && data.d !== undefined); + let spec; + if (format === 'jwk') { + if (data.ext !== undefined && (typeof data.ext !== 'boolean' || (!data.ext && extractable))) { + throw new Error('Requested extractability conflicts with the JWK.'); + } + if (data.use !== undefined && data.use !== (algorithm.name === 'RSA-OAEP' ? 'enc' : 'sig')) + throw new Error('JWK use conflicts with the requested algorithm.'); + if (data.alg !== undefined && data.alg !== jwa(algorithm)) + throw new Error('JWK algorithm does not match the requested algorithm.'); + if ( + data.kty !== (ec ? 'EC' : 'RSA') || + (data.key_ops !== undefined && + (!Array.isArray(data.key_ops) || + new Set(data.key_ops).size !== data.key_ops.length || + data.key_ops.some((u) => !allowed.includes(u)) || + !usages.every((u) => data.key_ops.includes(u)))) + ) { + throw new Error('Key type or usage mismatch.'); + } + if (ec) { + if (data.crv !== algorithm.namedCurve) throw new Error('EC curve mismatch.'); + const params = ecParameters(data.crv); + const [, curve, width] = curves[data.crv]; + const x = integer(data.x, width); + const y = integer(data.y, width); + const d = secret ? integer(data.d, width) : undefined; + if (secret) { + const point = curve.getPublicKey(unsigned(d, width), false); + if ( + encode(point.slice(1, 1 + width)) !== data.x || + encode(point.slice(1 + width)) !== data.y + ) { + throw new Error('JWK public and private EC components do not match.'); + } + } else { + curve.Point.fromAffine({ + x: BigInt(x.toString()), + y: BigInt(y.toString()), + }).assertValidity(); + } + spec = secret + ? new (Java.type('java.security.spec.ECPrivateKeySpec'))(d, params) + : new (Java.type('java.security.spec.ECPublicKeySpec'))( + new (Java.type('java.security.spec.ECPoint'))(x, y), + params, + ); + } else { + spec = rsaSpec(data, secret); + } + } else { + const Spec = Java.type( + secret ? 'java.security.spec.PKCS8EncodedKeySpec' : 'java.security.spec.X509EncodedKeySpec', + ); + spec = new Spec(javaBytes(data)); + } + const key = secret ? factory.generatePrivate(spec) : factory.generatePublic(spec); + if (ec && !key.getParams().getOrder().equals(ecParameters(algorithm.namedCurve).getOrder())) { + throw new Error('The key has a different named curve.'); + } + return { key, secret, algorithm }; +} +export function exportAsymmetric(format, { key, secret, algorithm, usages }) { + if (format !== 'jwk') return jsBytes(key.getEncoded()).buffer; + const jwk = { key_ops: usages, ext: true }; + if (algorithm.name === 'ECDSA') { + const [, curve, width] = curves[algorithm.namedCurve]; + Object.assign(jwk, { kty: 'EC', crv: algorithm.namedCurve }); + if (secret) { + const d = unsigned(key.getS(), width); + const point = curve.getPublicKey(d, false); + Object.assign(jwk, { + d: encode(d), + x: encode(point.slice(1, 1 + width)), + y: encode(point.slice(1 + width)), + }); + } else { + jwk.x = encode(unsigned(key.getW().getAffineX(), width)); + jwk.y = encode(unsigned(key.getW().getAffineY(), width)); + } + } else { + jwk.kty = 'RSA'; + for (const name of secret ? Object.keys(rsaFields) : ['n', 'e']) + jwk[name] = encode(unsigned(key[rsaFields[name]]())); + jwk.alg = jwa(algorithm); + } + return jwk; +} diff --git a/src/engine/runtime/limits.ts b/src/engine/runtime/limits.ts new file mode 100644 index 0000000..fd65bd4 --- /dev/null +++ b/src/engine/runtime/limits.ts @@ -0,0 +1,7 @@ +import { OperationError } from '../types'; +export const MAX_OUTPUT = 16 * 1024 * 1024; +export function checkSize(size: number, limit = MAX_OUTPUT): void { + if (!Number.isSafeInteger(size) || size < 0 || size > limit) { + throw new OperationError('Output exceeds the processing limit of ' + limit + ' bytes.'); + } +} diff --git a/src/engine/runtime/provider.ts b/src/engine/runtime/provider.ts new file mode 100644 index 0000000..b99a634 --- /dev/null +++ b/src/engine/runtime/provider.ts @@ -0,0 +1,45 @@ +import type { OperationError } from '../types'; + +export type Compression = 'gzip' | 'deflate' | 'deflate-raw'; +export type EngineCrypto = Pick< + SubtleCrypto, + | 'digest' + | 'importKey' + | 'exportKey' + | 'generateKey' + | 'encrypt' + | 'decrypt' + | 'deriveBits' + | 'sign' + | 'verify' +>; +export type EngineUrl = Pick< + URL, + 'protocol' | 'hostname' | 'port' | 'username' | 'password' | 'pathname' | 'hash' +> & { searchParams: Iterable<[string, string]> }; +export interface RuntimeProvider { + readonly name: string; + readonly secureRandom: boolean; + timeZones(): string[]; + zoneOffset(zone: string, instant: number): number; + zoneAbbreviation(zone: string, instant: number): string; + compressionFormats(): Compression[]; + readonly subtle: EngineCrypto | undefined; + decoder(label?: string, options?: TextDecoderOptions): { decode(input: Uint8Array): string }; + encode(text: string): Uint8Array; + toBase64(binary: string): string; + fromBase64(base64: string): string; + parseUrl(url: string): EngineUrl; + query(text: string): Iterable<[string, string]>; + random(target: T): T; + uuid(): string; + transform( + bytes: Uint8Array, + format: Compression, + compress: boolean, + limit?: number, + ): Promise; + now(): number; + delay(ms: number): Promise; + timed(work: () => T | Promise, ms: number, timeout: () => OperationError): Promise; +} diff --git a/src/engine/alphabet.test.ts b/src/engine/tests/alphabet.test.ts similarity index 97% rename from src/engine/alphabet.test.ts rename to src/engine/tests/alphabet.test.ts index 0139b7c..6cf9463 100644 Binary files a/src/engine/alphabet.test.ts and b/src/engine/tests/alphabet.test.ts differ diff --git a/src/engine/amf.test.ts b/src/engine/tests/amf.test.ts similarity index 97% rename from src/engine/amf.test.ts rename to src/engine/tests/amf.test.ts index 1b70efd..afb972e 100644 --- a/src/engine/amf.test.ts +++ b/src/engine/tests/amf.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/analysis.test.ts b/src/engine/tests/analysis.test.ts similarity index 98% rename from src/engine/analysis.test.ts rename to src/engine/tests/analysis.test.ts index 0a8c07b..8175a65 100644 --- a/src/engine/analysis.test.ts +++ b/src/engine/tests/analysis.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { analyse, flatten, toMarkdown } from './index'; -import { extractIndicators } from './analysis/indicators'; +import { analyse, flatten, toMarkdown } from '../index'; +import { extractIndicators } from '../analysis/indicators'; const LAYERED = 'SDRzSUFBQUFBQUFBQ2hYTnpXNkNRQUJGNFZjaHN5NXFXazBOaVlzei9FbEZLYkVtYlhjSUU2QWlUQ3AyYkp1K2V6UEw4eTN1L1JYbHVSS2UwSU5SbjVkR2RaM2o5b04yWE9NMGJWV3AzbkZWWHpyN1hFWkVOUWtNaEhQZWMvbUFQK1BGeUpaNHNQM0JPaWRCWnNRSEtyZ1NsZFpid2kxSHBMWityT1VNLzBSYXk1QjRTV1hrbGRod05MSWh6amtZT1dPZFVPVFdTemJRRTlkVVdJZXM1Z3QveVRablFaQ1ExdHdJM3Nqc1h4RGFYaENjU08yZVA2ZEUvbGgvTW1oWXJjU2RLTytGSjVweDFONTBlaTY2dG15SDY4VlZ0K0tzT3pVWkJ6MnRpMUZOZEtQRm5UaXBiK0VKTmdsSnRvK3lZTGQ3REYvWlBxZWgrUHNIQ3o5RSt6c0JBQUE9'; diff --git a/src/engine/archives.test.ts b/src/engine/tests/archives.test.ts similarity index 97% rename from src/engine/archives.test.ts rename to src/engine/tests/archives.test.ts index 171319e..f87c6b2 100644 --- a/src/engine/archives.test.ts +++ b/src/engine/tests/archives.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/argon2.test.ts b/src/engine/tests/argon2.test.ts similarity index 96% rename from src/engine/argon2.test.ts rename to src/engine/tests/argon2.test.ts index 8496c05..a7f50c0 100644 --- a/src/engine/argon2.test.ts +++ b/src/engine/tests/argon2.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import { argon2 } from './operations/argon2'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import { argon2 } from '../operations/argon2'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/arguments.test.ts b/src/engine/tests/arguments.test.ts similarity index 99% rename from src/engine/arguments.test.ts rename to src/engine/tests/arguments.test.ts index a8216a3..3cfc284 100644 --- a/src/engine/arguments.test.ts +++ b/src/engine/tests/arguments.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { OPERATIONS } from './operations/index'; -import { renderText } from './core/bytes'; +import { OPERATIONS } from '../operations/index'; +import { renderText } from '../core/bytes'; const BS = String.fromCharCode(92); diff --git a/src/engine/ascon.test.ts b/src/engine/tests/ascon.test.ts similarity index 97% rename from src/engine/ascon.test.ts rename to src/engine/tests/ascon.test.ts index 72a59ca..4d52c39 100644 --- a/src/engine/ascon.test.ts +++ b/src/engine/tests/ascon.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/asn1.test.ts b/src/engine/tests/asn1.test.ts similarity index 98% rename from src/engine/asn1.test.ts rename to src/engine/tests/asn1.test.ts index 3744a80..d73ace2 100644 --- a/src/engine/asn1.test.ts +++ b/src/engine/tests/asn1.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; const CERTIFICATE = `-----BEGIN CERTIFICATE----- diff --git a/src/engine/avro.test.ts b/src/engine/tests/avro.test.ts similarity index 98% rename from src/engine/avro.test.ts rename to src/engine/tests/avro.test.ts index 906cfd8..6a42e79 100644 --- a/src/engine/avro.test.ts +++ b/src/engine/tests/avro.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/binaryformats.test.ts b/src/engine/tests/binaryformats.test.ts similarity index 98% rename from src/engine/binaryformats.test.ts rename to src/engine/tests/binaryformats.test.ts index b72c499..1d92543 100644 --- a/src/engine/binaryformats.test.ts +++ b/src/engine/tests/binaryformats.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/binaryinspect.test.ts b/src/engine/tests/binaryinspect.test.ts similarity index 97% rename from src/engine/binaryinspect.test.ts rename to src/engine/tests/binaryinspect.test.ts index f91abb3..b040739 100644 --- a/src/engine/binaryinspect.test.ts +++ b/src/engine/tests/binaryinspect.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/blake3.test.ts b/src/engine/tests/blake3.test.ts similarity index 95% rename from src/engine/blake3.test.ts rename to src/engine/tests/blake3.test.ts index 89430b9..0fe75f2 100644 --- a/src/engine/blake3.test.ts +++ b/src/engine/tests/blake3.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import { blake3 } from './operations/blake3'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import { blake3 } from '../operations/blake3'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/blockciphers.test.ts b/src/engine/tests/blockciphers.test.ts similarity index 97% rename from src/engine/blockciphers.test.ts rename to src/engine/tests/blockciphers.test.ts index 240fb5f..91bdfbe 100644 --- a/src/engine/blockciphers.test.ts +++ b/src/engine/tests/blockciphers.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/bytes.test.ts b/src/engine/tests/bytes.test.ts similarity index 97% rename from src/engine/bytes.test.ts rename to src/engine/tests/bytes.test.ts index fb034b1..01f4191 100644 --- a/src/engine/bytes.test.ts +++ b/src/engine/tests/bytes.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, encodeInput, INPUT_ENCODINGS, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, encodeInput, INPUT_ENCODINGS, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; function recipe(...entries: Array]>): Recipe { diff --git a/src/engine/bzip2.test.ts b/src/engine/tests/bzip2.test.ts similarity index 97% rename from src/engine/bzip2.test.ts rename to src/engine/tests/bzip2.test.ts index 96a1908..847e487 100644 --- a/src/engine/bzip2.test.ts +++ b/src/engine/tests/bzip2.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/catalogue.smoke.test.ts b/src/engine/tests/catalogue.smoke.test.ts similarity index 97% rename from src/engine/catalogue.smoke.test.ts rename to src/engine/tests/catalogue.smoke.test.ts index 6e6c97b..8d5d273 100644 --- a/src/engine/catalogue.smoke.test.ts +++ b/src/engine/tests/catalogue.smoke.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { OPERATIONS } from './operations/index'; -import { identifyHash } from './detection/hashes'; +import { OPERATIONS } from '../operations/index'; +import { identifyHash } from '../detection/hashes'; const SAMPLES: Record = { diff --git a/src/engine/catalogue.test.ts b/src/engine/tests/catalogue.test.ts similarity index 99% rename from src/engine/catalogue.test.ts rename to src/engine/tests/catalogue.test.ts index dc5a201..672af57 100644 --- a/src/engine/catalogue.test.ts +++ b/src/engine/tests/catalogue.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation, OPERATIONS, CATEGORY_ORDER } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation, OPERATIONS, CATEGORY_ORDER } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/charts.test.ts b/src/engine/tests/charts.test.ts similarity index 97% rename from src/engine/charts.test.ts rename to src/engine/tests/charts.test.ts index c0764d9..d1ee349 100644 --- a/src/engine/charts.test.ts +++ b/src/engine/tests/charts.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import { decodeImage } from './core/image'; -import { asBytes } from './core/bytes'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import { decodeImage } from '../core/image'; +import { asBytes } from '../core/bytes'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/classical.test.ts b/src/engine/tests/classical.test.ts similarity index 97% rename from src/engine/classical.test.ts rename to src/engine/tests/classical.test.ts index 405e8b2..0836679 100644 --- a/src/engine/classical.test.ts +++ b/src/engine/tests/classical.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/codetidy.test.ts b/src/engine/tests/codetidy.test.ts similarity index 97% rename from src/engine/codetidy.test.ts rename to src/engine/tests/codetidy.test.ts index e469fd2..483abfa 100644 --- a/src/engine/codetidy.test.ts +++ b/src/engine/tests/codetidy.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/ctf.test.ts b/src/engine/tests/ctf.test.ts similarity index 98% rename from src/engine/ctf.test.ts rename to src/engine/tests/ctf.test.ts index ddfd14b..7890c62 100644 --- a/src/engine/ctf.test.ts +++ b/src/engine/tests/ctf.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { bake, hints, renderText } from './index'; +import { bake, hints, renderText } from '../index'; import { alphabetHints, caesarShift, @@ -7,9 +7,9 @@ import { indexOfCoincidence, letters, vigenereKey, -} from './ctf'; -import { getOperation } from './operations'; -import type { Hint } from './ctf'; +} from '../ctf'; +import { getOperation } from '../operations'; +import type { Hint } from '../ctf'; const b64 = (text: string): string => Buffer.from(text, 'latin1').toString('base64'); diff --git a/src/engine/dataformat.test.ts b/src/engine/tests/dataformat.test.ts similarity index 99% rename from src/engine/dataformat.test.ts rename to src/engine/tests/dataformat.test.ts index b03365a..3622b60 100644 --- a/src/engine/dataformat.test.ts +++ b/src/engine/tests/dataformat.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/datetime.test.ts b/src/engine/tests/datetime.test.ts similarity index 95% rename from src/engine/datetime.test.ts rename to src/engine/tests/datetime.test.ts index cb62b51..7d5af75 100644 --- a/src/engine/datetime.test.ts +++ b/src/engine/tests/datetime.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/detection.redos.test.ts b/src/engine/tests/detection.redos.test.ts similarity index 95% rename from src/engine/detection.redos.test.ts rename to src/engine/tests/detection.redos.test.ts index bebca68..7fe7c87 100644 --- a/src/engine/detection.redos.test.ts +++ b/src/engine/tests/detection.redos.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { detect } from './index'; -import { getOperation } from './operations'; +import { detect } from '../index'; +import { getOperation } from '../operations'; /* * Detection runs on whatever is pasted, before anyone has decided it is CSV, so every diff --git a/src/engine/detection.strength.test.ts b/src/engine/tests/detection.strength.test.ts similarity index 97% rename from src/engine/detection.strength.test.ts rename to src/engine/tests/detection.strength.test.ts index 712df8b..3e7af98 100644 --- a/src/engine/detection.strength.test.ts +++ b/src/engine/tests/detection.strength.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { autoDecode, bake, detect, lastLayer, terminusOf, toChain } from './index'; -import { findEmbedded } from './detection/embedded'; -import { getOperation } from './operations'; -import { shortCandidates } from './detection/short'; -import type { RecipeStep } from './types'; +import { autoDecode, bake, detect, lastLayer, terminusOf, toChain } from '../index'; +import { findEmbedded } from '../detection/embedded'; +import { getOperation } from '../operations'; +import { shortCandidates } from '../detection/short'; +import type { RecipeStep } from '../types'; function utf8Base64(text: string): string { return btoa(String.fromCharCode(...new TextEncoder().encode(text))); diff --git a/src/engine/engine.test.ts b/src/engine/tests/engine.test.ts similarity index 98% rename from src/engine/engine.test.ts rename to src/engine/tests/engine.test.ts index d0be634..191e0b9 100644 --- a/src/engine/engine.test.ts +++ b/src/engine/tests/engine.test.ts @@ -7,11 +7,11 @@ import { listOperations, renderText, toChain, -} from './index'; -import { identify } from './detection/identify'; -import { SAMPLES } from './samples'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +} from '../index'; +import { identify } from '../detection/identify'; +import { SAMPLES } from '../samples'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; function sample(id: string): string { const found = SAMPLES.find((s) => s.id === id); diff --git a/src/engine/enigma.test.ts b/src/engine/tests/enigma.test.ts similarity index 97% rename from src/engine/enigma.test.ts rename to src/engine/tests/enigma.test.ts index 5b8ae9b..df0133d 100644 --- a/src/engine/enigma.test.ts +++ b/src/engine/tests/enigma.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import { makeRotor, step } from './operations/enigma'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import { makeRotor, step } from '../operations/enigma'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/entropy.test.ts b/src/engine/tests/entropy.test.ts similarity index 99% rename from src/engine/entropy.test.ts rename to src/engine/tests/entropy.test.ts index 4545e32..f1e6fcb 100644 --- a/src/engine/entropy.test.ts +++ b/src/engine/tests/entropy.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { bandOf, entropyProfile, MIN_FOR_PROFILE, standoutRegions } from './index'; +import { bandOf, entropyProfile, MIN_FOR_PROFILE, standoutRegions } from '../index'; function bytesOf(text: string): Uint8Array { diff --git a/src/engine/explain.test.ts b/src/engine/tests/explain.test.ts similarity index 98% rename from src/engine/explain.test.ts rename to src/engine/tests/explain.test.ts index 64322c4..b09eee9 100644 --- a/src/engine/explain.test.ts +++ b/src/engine/tests/explain.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { analyse, autoDecode, explain } from './index'; +import { analyse, autoDecode, explain } from '../index'; function wrap(value: string, times: number): string { diff --git a/src/engine/find.test.ts b/src/engine/tests/find.test.ts similarity index 98% rename from src/engine/find.test.ts rename to src/engine/tests/find.test.ts index efa2f91..5ddc0c8 100644 --- a/src/engine/find.test.ts +++ b/src/engine/tests/find.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { analyse, findInLayers, isValidQuery } from './index'; +import { analyse, findInLayers, isValidQuery } from '../index'; function wrap(value: string, times: number): string { diff --git a/src/engine/flow.test.ts b/src/engine/tests/flow.test.ts similarity index 98% rename from src/engine/flow.test.ts rename to src/engine/tests/flow.test.ts index 85d1319..873e8d6 100644 --- a/src/engine/flow.test.ts +++ b/src/engine/tests/flow.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/fuzzyhash.test.ts b/src/engine/tests/fuzzyhash.test.ts similarity index 97% rename from src/engine/fuzzyhash.test.ts rename to src/engine/tests/fuzzyhash.test.ts index b203d5d..04867c1 100644 --- a/src/engine/fuzzyhash.test.ts +++ b/src/engine/tests/fuzzyhash.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/geoprimes.test.ts b/src/engine/tests/geoprimes.test.ts similarity index 97% rename from src/engine/geoprimes.test.ts rename to src/engine/tests/geoprimes.test.ts index d4a839a..20589f7 100644 --- a/src/engine/geoprimes.test.ts +++ b/src/engine/tests/geoprimes.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/gost.test.ts b/src/engine/tests/gost.test.ts similarity index 97% rename from src/engine/gost.test.ts rename to src/engine/tests/gost.test.ts index 03b8d11..f99fde6 100644 --- a/src/engine/gost.test.ts +++ b/src/engine/tests/gost.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/images.test.ts b/src/engine/tests/images.test.ts similarity index 98% rename from src/engine/images.test.ts rename to src/engine/tests/images.test.ts index 44ba64b..4ae4a56 100644 --- a/src/engine/images.test.ts +++ b/src/engine/tests/images.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import { decodeImage } from './core/image'; -import { asBytes } from './core/bytes'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import { decodeImage } from '../core/image'; +import { asBytes } from '../core/bytes'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/inspect.test.ts b/src/engine/tests/inspect.test.ts similarity index 94% rename from src/engine/inspect.test.ts rename to src/engine/tests/inspect.test.ts index 2726bd9..1184192 100644 --- a/src/engine/inspect.test.ts +++ b/src/engine/tests/inspect.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { inspect } from './inspect'; -import { analyse } from './analysis'; -import { toChain, lastLayer, terminusOf } from './detection/chain'; -import { flatten } from './analysis/report'; -import { decodeBaseN, encodeBaseN } from './core/alphabet'; -import { OperationError } from './types'; +import { inspect } from '../inspect'; +import { analyse } from '../analysis'; +import { toChain, lastLayer, terminusOf } from '../detection/chain'; +import { flatten } from '../analysis/report'; +import { decodeBaseN, encodeBaseN } from '../core/alphabet'; +import { OperationError } from '../types'; function wrap(value: string, times: number): string { let out = value; diff --git a/src/engine/tests/java-key-handles.check.js b/src/engine/tests/java-key-handles.check.js new file mode 100644 index 0000000..9b2aca4 --- /dev/null +++ b/src/engine/tests/java-key-handles.check.js @@ -0,0 +1,301 @@ +import { javaCrypto } from '../runtime/java-crypto.js'; + +async function run() { + const api = javaCrypto(); + const message = Uint8Array.of(1, 2, 3); + const ec = { name: 'ECDSA', namedCurve: 'P-256' }; + const sign = { name: 'ECDSA', hash: 'SHA-256' }; + const usages = ['sign', 'verify']; + const pair = await api.generateKey(ec, false, usages); + const signature = await api.sign(sign, pair.privateKey, message); + const exported = await api.exportKey('jwk', pair.publicKey); + const imported = await api.importKey('jwk', exported, ec, true, ['verify']); + const macAlgorithm = { name: 'HMAC', hash: { name: 'SHA-256' } }; + const requested = ['verify']; + const source = Uint8Array.of(9, 1, 2, 3, 8); + const mac = await api.importKey('raw', source.subarray(1, 4), macAlgorithm, true, requested); + source[1] = 77; + requested.push('sign'); + macAlgorithm.hash.name = 'SHA-512'; + const aes = await api.importKey('raw', new Uint8Array(16), 'AES-CBC', false, ['encrypt']); + const params = { name: 'AES-CBC', iv: new Uint8Array(16) }; + const encrypted = await api.encrypt(params, aes, message); + const checks = []; + const expect = (name, fn) => checks.push([name, fn]); + const rejected = async (fn) => { + try { + await fn(); + } catch { + return true; + } + return false; + }; + expect('EC public JWK verifies', () => api.verify(sign, imported, signature, message)); + expect('generated public key is exportable', () => pair.publicKey.extractable === true); + expect('private Java material is opaque', () => !('key' in pair.privateKey) && !('raw' in mac)); + expect('non-extractable private key rejects export', () => + rejected(() => api.exportKey('pkcs8', pair.privateKey)), + ); + expect('wrong asymmetric export format rejects', () => + rejected(() => api.exportKey('pkcs8', pair.publicKey)), + ); + expect('verify-only HMAC rejects signing', () => rejected(() => api.sign('HMAC', mac, message))); + expect( + 'handle metadata is detached', + () => mac.algorithm.hash.name === 'SHA-256' && mac.usages.join() === 'verify', + ); + expect('raw secret export copies the input view', async () => { + const result = new Uint8Array(await api.exportKey('raw', mac)); + result[0] = 99; + const again = await api.exportKey('raw', mac); + return again instanceof ArrayBuffer && Array.from(new Uint8Array(again)).join() === '1,2,3'; + }); + expect('foreign provider rejects handle', () => + rejected(() => javaCrypto().verify(sign, imported, signature, message)), + ); + expect('copied handle rejects', () => + rejected(() => api.verify(sign, { ...imported }, signature, message)), + ); + expect('encrypt-only key rejects decryption', () => + rejected(() => api.decrypt(params, aes, encrypted)), + ); + expect('AES key rejects a different mode', () => + rejected(() => api.encrypt({ name: 'AES-CTR', counter: params.iv, length: 64 }, aes, message)), + ); + expect('invalid EC usage rejects', () => + rejected(() => api.importKey('jwk', { ...exported, key_ops: ['sign'] }, ec, true, ['sign'])), + ); + expect('non-extractable JWK can be imported', async () => { + const k = await api.importKey('jwk', { ...exported, ext: false }, ec, false, ['verify']); + return ( + (await api.verify(sign, k, signature, message)) && + (await rejected(() => api.exportKey('jwk', k))) + ); + }); + expect('PBKDF2 rejects extractable import', () => + rejected(() => api.importKey('raw', message, 'PBKDF2', true, ['deriveBits'])), + ); + expect('deriveKey-only password rejects deriveBits', async () => { + const password = await api.importKey('raw', message, 'PBKDF2', false, ['deriveKey']); + return rejected(() => + api.deriveBits( + { name: 'PBKDF2', salt: message, iterations: 1, hash: 'SHA-256' }, + password, + 128, + ), + ); + }); + expect('malformed JWK key_ops rejects', () => + rejected(() => api.importKey('jwk', { ...exported, key_ops: 'verify' }, ec, true, ['verify'])), + ); + const same = (left, right) => { + const a = new Uint8Array(left); + const b = new Uint8Array(right); + return a.length === b.length && a.every((v, i) => v === b[i]); + }; + const rsa = { + name: 'RSA-PSS', + hash: 'SHA-256', + modulusLength: 2048, + publicExponent: Uint8Array.of(1, 0, 1), + }; + const original = await api.generateKey(rsa, true, usages); + const spki = await api.exportKey('spki', original.publicKey); + const pkcs8 = await api.exportKey('pkcs8', original.privateKey); + const privateJwk = await api.exportKey('jwk', original.privateKey); + const publicJwk = await api.exportKey('jwk', original.publicKey); + for (const [name, alg, hash] of [ + ['RSA-OAEP', 'RSA-OAEP', 'SHA-1'], + ['RSA-OAEP', 'RSA-OAEP-256', 'SHA-256'], + ['RSA-OAEP', 'RSA-OAEP-384', 'SHA-384'], + ['RSA-OAEP', 'RSA-OAEP-512', 'SHA-512'], + ['RSA-PSS', 'PS256', 'SHA-256'], + ['RSA-PSS', 'PS384', 'SHA-384'], + ['RSA-PSS', 'PS512', 'SHA-512'], + ['RSASSA-PKCS1-v1_5', 'RS256', 'SHA-256'], + ['RSASSA-PKCS1-v1_5', 'RS384', 'SHA-384'], + ['RSASSA-PKCS1-v1_5', 'RS512', 'SHA-512'], + ]) { + expect(alg + ' interoperable public and private JWK', async () => { + const enc = name === 'RSA-OAEP'; + const p = { name, hash, saltLength: 16, label: message }; + const use = enc ? 'enc' : 'sig'; + async function roundTrip(format, bytes, usage) { + const key = await api.importKey(format, bytes, p, true, [usage]); + const jwk = await api.exportKey('jwk', key); + if (jwk.alg !== alg || jwk.ext !== true || jwk.key_ops.join() !== usage) + throw Error('wrong metadata'); + return api.importKey('jwk', { ...jwk, use }, p, false, [usage]); + } + const pub = await roundTrip('spki', spki, enc ? 'encrypt' : 'verify'); + const priv = await roundTrip('pkcs8', pkcs8, enc ? 'decrypt' : 'sign'); + if (!enc) return api.verify(p, pub, await api.sign(p, priv, message), message); + const ciphertext = await api.encrypt(p, pub, message); + return ( + same(await api.decrypt(p, priv, ciphertext), message) && + (await rejected(() => api.decrypt({ ...p, label: Uint8Array.of(0) }, priv, ciphertext))) + ); + }); + } + for (const [field, value] of Object.entries({ + kty: 'EC', + alg: 'RS256', + use: 'enc', + ext: 'false', + key_ops: ['sign', 'sign'], + n: 'AQ', + e: 'Ag', + d: 'Ag', + p: 'Ag', + q: 'Ag', + dp: 'Ag', + dq: 'Ag', + qi: 'Ag', + oth: [], + })) { + expect('RSA rejects conflicting ' + field, () => + rejected(() => api.importKey('jwk', { ...privateJwk, [field]: value }, rsa, true, ['sign'])), + ); + } + for (const [label, patch] of [ + ['forbidden export', { ext: false }], + ['padded integer', { e: 'AQAB=' }], + ['nonminimal integer', { e: 'AAEAAQ' }], + ['noncanonical final bits', { e: 'Ax' }], + ['missing modulus', { n: undefined }], + ['partial private key', { dp: privateJwk.dp }], + ['unknown usage', { key_ops: ['verify', 'read'] }], + ['missing requested usage', { key_ops: [] }], + ['wrong key role', { key_ops: ['sign', 'verify'] }], + ['nonstring usage', { key_ops: [42] }], + ]) + expect('public RSA rejects ' + label, () => + rejected(() => api.importKey('jwk', { ...publicJwk, ...patch }, rsa, true, ['verify'])), + ); + expect('missing private CRT field rejects', () => + rejected(() => api.importKey('jwk', { ...privateJwk, qi: undefined }, rsa, true, ['sign'])), + ); + expect('duplicate requested usage rejects', () => + rejected(() => api.importKey('spki', spki, rsa, true, ['verify', 'verify'])), + ); + for (const [namedCurve, alg, hash] of [ + ['P-256', 'ES256', 'SHA-256'], + ['P-384', 'ES384', 'SHA-384'], + ['P-521', 'ES512', 'SHA-512'], + ]) { + expect(alg + ' valid public/private components', async () => { + const p = { name: 'ECDSA', namedCurve, hash }; + const keys = await api.generateKey(p, true, usages); + const pub = await api.exportKey('jwk', keys.publicKey); + const priv = await api.exportKey('jwk', keys.privateKey); + const verifying = await api.importKey('jwk', { ...pub, alg }, p, true, ['verify']); + const signing = await api.importKey('jwk', { ...priv, alg }, p, false, ['sign']); + return api.verify(p, verifying, await api.sign(p, signing, message), message); + }); + } + for (const [label, patch] of [ + ['curve', { crv: 'P-384' }], + ['alg', { alg: 'ES512' }], + ['wrong width', { x: 'AQ' }], + ['off-curve point', { x: 'A'.repeat(43), y: 'A'.repeat(43) }], + ['zero private scalar', { d: 'A'.repeat(43) }], + ['missing coordinate', { y: undefined }], + ['invalid alphabet', { x: '%%%=' }], + ]) + expect('EC rejects ' + label, () => + rejected(() => + api.importKey( + 'jwk', + { ...exported, ...patch, key_ops: undefined }, + ec, + true, + patch.d ? ['sign'] : ['verify'], + ), + ), + ); + expect('sign-only HMAC rejects verification', async () => { + const key = await api.importKey('raw', message, macAlgorithm, false, ['sign']); + return rejected(() => api.verify('HMAC', key, signature, message)); + }); + expect('decrypt-only AES rejects encryption', async () => { + const key = await api.importKey('raw', new Uint8Array(16), 'AES-CBC', true, ['decrypt']); + return ( + same(await api.decrypt(params, key, encrypted), message) && + (await rejected(() => api.encrypt(params, key, message))) + ); + }); + expect('GCM authenticates associated data', async () => { + const key = await api.importKey('raw', new Uint8Array(16), 'AES-GCM', false, [ + 'encrypt', + 'decrypt', + ]); + const p = { name: 'AES-GCM', iv: new Uint8Array(12), additionalData: message }; + const data = await api.encrypt(p, key, message); + return ( + same(await api.decrypt(p, key, data), message) && + (await rejected(() => api.decrypt({ ...p, additionalData: new Uint8Array() }, key, data))) + ); + }); + expect('CTR wraps only the counter field', async () => { + const key = await api.importKey('raw', new Uint8Array(16), 'AES-CTR', false, ['encrypt']); + const counter = new Uint8Array(16); + counter[15] = 0xff; + const p = { name: 'AES-CTR', counter, length: 1 }; + const first = await api.encrypt(p, key, new Uint8Array(32)); + counter[15] = 0xfe; + return ( + same(first.slice(16), await api.encrypt(p, key, new Uint8Array(16))) && + (await rejected(() => api.encrypt(p, key, new Uint8Array(33)))) + ); + }); + expect('derived AES key keeps usages and extractability', async () => { + const password = await api.importKey('raw', message, 'PBKDF2', false, ['deriveKey']); + const key = await api.deriveKey( + { name: 'PBKDF2', salt: message, iterations: 1, hash: 'SHA-256' }, + password, + { name: 'AES-CBC', length: 128 }, + false, + ['encrypt'], + ); + return ( + (await api.encrypt(params, key, message)).byteLength === 16 && + (await rejected(() => api.exportKey('raw', key))) && + (await rejected(() => api.decrypt(params, key, encrypted))) + ); + }); + expect('non-extractable AES rejects raw export', () => rejected(() => api.exportKey('raw', aes))); + expect('forged key metadata cannot authorize an export', () => + rejected(() => + api.exportKey('raw', { + type: 'secret', + extractable: true, + algorithm: aes.algorithm, + usages: aes.usages, + }), + ), + ); + expect('returned RSA exponent is an independent copy', () => { + original.publicKey.algorithm.publicExponent[0] = 0; + return original.publicKey.algorithm.publicExponent[0] === 1; + }); + expect('EC private scalar must identify its supplied point', async () => { + const keys = await api.generateKey(ec, true, usages); + const privatePart = await api.exportKey('jwk', keys.privateKey); + return rejected(() => + api.importKey('jwk', { ...privatePart, x: exported.x, y: exported.y }, ec, true, ['sign']), + ); + }); + let passed = 0; + for (const [name, test] of checks) { + try { + if (!(await test())) throw new Error('unexpected result'); + passed++; + } catch (error) { + print('FAIL ' + name + ': ' + error.message); + } + } + print('Java key handles: ' + passed + '/' + checks.length); + if (passed === checks.length) print('Java key handles passed'); +} + +run().catch((error) => print('FAIL Java key handles: ' + error.message)); diff --git a/src/engine/kdf.test.ts b/src/engine/tests/kdf.test.ts similarity index 97% rename from src/engine/kdf.test.ts rename to src/engine/tests/kdf.test.ts index 62a7b6b..238b5a8 100644 --- a/src/engine/kdf.test.ts +++ b/src/engine/tests/kdf.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/legacyciphers.test.ts b/src/engine/tests/legacyciphers.test.ts similarity index 97% rename from src/engine/legacyciphers.test.ts rename to src/engine/tests/legacyciphers.test.ts index be4a369..9debcd0 100644 --- a/src/engine/legacyciphers.test.ts +++ b/src/engine/tests/legacyciphers.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/lorenz.test.ts b/src/engine/tests/lorenz.test.ts similarity index 97% rename from src/engine/lorenz.test.ts rename to src/engine/tests/lorenz.test.ts index 8bbf520..03f4192 100644 --- a/src/engine/lorenz.test.ts +++ b/src/engine/tests/lorenz.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/lzma.test.ts b/src/engine/tests/lzma.test.ts similarity index 97% rename from src/engine/lzma.test.ts rename to src/engine/tests/lzma.test.ts index 6654fbc..016bba5 100644 --- a/src/engine/lzma.test.ts +++ b/src/engine/tests/lzma.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/markup.test.ts b/src/engine/tests/markup.test.ts similarity index 97% rename from src/engine/markup.test.ts rename to src/engine/tests/markup.test.ts index 7dff92d..0e459e9 100644 --- a/src/engine/markup.test.ts +++ b/src/engine/tests/markup.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; const HTML = ` diff --git a/src/engine/metadata.test.ts b/src/engine/tests/metadata.test.ts similarity index 98% rename from src/engine/metadata.test.ts rename to src/engine/tests/metadata.test.ts index 520afca..3325fe6 100644 --- a/src/engine/metadata.test.ts +++ b/src/engine/tests/metadata.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/morehashes.test.ts b/src/engine/tests/morehashes.test.ts similarity index 95% rename from src/engine/morehashes.test.ts rename to src/engine/tests/morehashes.test.ts index 3eada43..7de582f 100644 --- a/src/engine/morehashes.test.ts +++ b/src/engine/tests/morehashes.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/network.detection.test.ts b/src/engine/tests/network.detection.test.ts similarity index 97% rename from src/engine/network.detection.test.ts rename to src/engine/tests/network.detection.test.ts index b3dc464..08b134d 100644 --- a/src/engine/network.detection.test.ts +++ b/src/engine/tests/network.detection.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { autoDecode, bake, detect, inspect, lastLayer, terminusOf, toChain } from './index'; -import { getOperation } from './operations'; -import type { Candidate, Layer } from './types'; +import { autoDecode, bake, detect, inspect, lastLayer, terminusOf, toChain } from '../index'; +import { getOperation } from '../operations'; +import type { Candidate, Layer } from '../types'; function addressCandidate(candidates: Candidate[]) { return candidates.find((candidate) => candidate.steps.at(-1)?.opId === 'change-ip-format'); diff --git a/src/engine/network.test.ts b/src/engine/tests/network.test.ts similarity index 96% rename from src/engine/network.test.ts rename to src/engine/tests/network.test.ts index d433c58..7f43e9f 100644 --- a/src/engine/network.test.ts +++ b/src/engine/tests/network.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/operations.verified.test.ts b/src/engine/tests/operations.verified.test.ts similarity index 98% rename from src/engine/operations.verified.test.ts rename to src/engine/tests/operations.verified.test.ts index 1416e91..5f5dc5a 100644 --- a/src/engine/operations.verified.test.ts +++ b/src/engine/tests/operations.verified.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { bake, encodeInput, renderText } from './index'; -import { getOperation, TEXT_OPERATION_IDS } from './operations'; -import { rewrap } from './core/rewrap'; -import { tryDecodeUtf8 } from './core/bytes'; -import type { Recipe, RecipeStep } from './types'; +import { bake, encodeInput, renderText } from '../index'; +import { getOperation, TEXT_OPERATION_IDS } from '../operations'; +import { rewrap } from '../core/rewrap'; +import { tryDecodeUtf8 } from '../core/bytes'; +import type { Recipe, RecipeStep } from '../types'; type Value = string | number | boolean; type Entry = string | [string, Record]; @@ -261,7 +261,7 @@ describe('Re-wrap inverts structured formats with the right settings', () => { async function viaRewrap(input: string, forward: Entry): Promise { const first = step(forward, 0); const mid = await bytesOut(input, forward); - const all = (await import('./operations/index')).OPERATIONS; + const all = (await import('../operations/index')).OPERATIONS; const plan = rewrap([first], all, () => 'inverse'); if (!plan.ok) throw new Error(plan.blockers.map((b) => b.reason).join('; ')); const result = await bake(mid, { id: 'r', name: 'r', steps: plan.steps }); diff --git a/src/engine/otp.test.ts b/src/engine/tests/otp.test.ts similarity index 96% rename from src/engine/otp.test.ts rename to src/engine/tests/otp.test.ts index a75dc9a..4d190da 100644 --- a/src/engine/otp.test.ts +++ b/src/engine/tests/otp.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/packets.test.ts b/src/engine/tests/packets.test.ts similarity index 98% rename from src/engine/packets.test.ts rename to src/engine/tests/packets.test.ts index 86a0ff8..27e841e 100644 --- a/src/engine/packets.test.ts +++ b/src/engine/tests/packets.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/passwordhashes.test.ts b/src/engine/tests/passwordhashes.test.ts similarity index 96% rename from src/engine/passwordhashes.test.ts rename to src/engine/tests/passwordhashes.test.ts index c815b3d..cb1c1fa 100644 --- a/src/engine/passwordhashes.test.ts +++ b/src/engine/tests/passwordhashes.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/pgp.test.ts b/src/engine/tests/pgp.test.ts similarity index 97% rename from src/engine/pgp.test.ts rename to src/engine/tests/pgp.test.ts index a7534ba..57e4b2d 100644 --- a/src/engine/pgp.test.ts +++ b/src/engine/tests/pgp.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/properties.test.ts b/src/engine/tests/properties.test.ts similarity index 97% rename from src/engine/properties.test.ts rename to src/engine/tests/properties.test.ts index c898b10..dd06cb1 100644 --- a/src/engine/properties.test.ts +++ b/src/engine/tests/properties.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; import fc from 'fast-check'; -import { analyse, bake, encodeInput, findInLayers, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe, RecipeStep } from './types'; +import { analyse, bake, encodeInput, findInLayers, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe, RecipeStep } from '../types'; /* * Property-based tests: fast-check generates thousands of inputs, including diff --git a/src/engine/publickey.test.ts b/src/engine/tests/publickey.test.ts similarity index 96% rename from src/engine/publickey.test.ts rename to src/engine/tests/publickey.test.ts index 19607b7..a198a7f 100644 --- a/src/engine/publickey.test.ts +++ b/src/engine/tests/publickey.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; @@ -314,6 +314,16 @@ describe('key generation and conversion', () => { expect(back.replace(/\s/g, '')).toBe(EC_PUBLIC.replace(/\s/g, '')); }, 30000); + it.each([ + ['RSA-OAEP-256', 'enc', 'wrapKey'], + ['PS256', 'sig', 'verify'], + ['RS256', 'sig', 'verify'], + ])('converts %s JWK metadata to the original public PEM', async (alg, use, usage) => { + const jwk = JSON.parse(await run(RSA_PUBLIC, 'pem-to-jwk')); + const input = JSON.stringify({ ...jwk, alg, use, key_ops: [usage] }); + expect((await run(input, 'jwk-to-pem')).replace(/\s/g, '')).toBe(RSA_PUBLIC.replace(/\s/g, '')); + }); + it('converts an RSA public key to JWK', async () => { const jwk = JSON.parse(await run(RSA_PUBLIC, 'pem-to-jwk')) as { kty: string; diff --git a/src/engine/rewrap.test.ts b/src/engine/tests/rewrap.test.ts similarity index 97% rename from src/engine/rewrap.test.ts rename to src/engine/tests/rewrap.test.ts index bf116ae..4e79526 100644 --- a/src/engine/rewrap.test.ts +++ b/src/engine/tests/rewrap.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { OPERATIONS } from './operations/index'; -import { INVERSES, carryArgs, rewrap, whyNotInvertible } from './core/rewrap'; -import { bake } from './core/bake'; -import type { RecipeStep } from './types'; +import { OPERATIONS } from '../operations/index'; +import { INVERSES, carryArgs, rewrap, whyNotInvertible } from '../core/rewrap'; +import { bake } from '../core/bake'; +import type { RecipeStep } from '../types'; const byId = new Map(OPERATIONS.map((o) => [o.id, o])); diff --git a/src/engine/salt.test.ts b/src/engine/tests/salt.test.ts similarity index 98% rename from src/engine/salt.test.ts rename to src/engine/tests/salt.test.ts index c7cd257..ae45022 100644 --- a/src/engine/salt.test.ts +++ b/src/engine/tests/salt.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { identify } from './index'; +import { identify } from '../index'; const MD5 = '5d41402abc4b2a76b9719d911017c592'; diff --git a/src/engine/streamciphers.test.ts b/src/engine/tests/streamciphers.test.ts similarity index 97% rename from src/engine/streamciphers.test.ts rename to src/engine/tests/streamciphers.test.ts index 860d7e2..620894a 100644 --- a/src/engine/streamciphers.test.ts +++ b/src/engine/tests/streamciphers.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/strip.test.ts b/src/engine/tests/strip.test.ts similarity index 94% rename from src/engine/strip.test.ts rename to src/engine/tests/strip.test.ts index 771fc95..dc10637 100644 --- a/src/engine/strip.test.ts +++ b/src/engine/tests/strip.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { removeAll } from './core/strip'; -import { getOperation } from './operations'; +import { removeAll } from '../core/strip'; +import { getOperation } from '../operations'; async function runOp(id: string, input: string, overrides: Record = {}) { const op = getOperation(id); diff --git a/src/engine/terminus.test.ts b/src/engine/tests/terminus.test.ts similarity index 98% rename from src/engine/terminus.test.ts rename to src/engine/tests/terminus.test.ts index b8956d5..1553bc3 100644 --- a/src/engine/terminus.test.ts +++ b/src/engine/tests/terminus.test.ts @@ -1,5 +1,5 @@ import { gzipSync } from 'node:zlib'; -import type { Layer } from './index'; +import type { Layer } from '../index'; import { describe, expect, it } from 'vitest'; import { autoDecode, @@ -11,8 +11,8 @@ import { terminusOf, terminusName, toChain, -} from './index'; -import { terminalIdentification } from './detection/identify'; +} from '../index'; +import { terminalIdentification } from '../detection/identify'; const b64 = (text: string): string => Buffer.from(text, 'latin1').toString('base64'); diff --git a/src/engine/tls.test.ts b/src/engine/tests/tls.test.ts similarity index 99% rename from src/engine/tls.test.ts rename to src/engine/tests/tls.test.ts index 178a501..c779c1a 100644 --- a/src/engine/tls.test.ts +++ b/src/engine/tests/tls.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/tokens.test.ts b/src/engine/tests/tokens.test.ts similarity index 98% rename from src/engine/tokens.test.ts rename to src/engine/tests/tokens.test.ts index a3d0215..b2d7e86 100644 --- a/src/engine/tokens.test.ts +++ b/src/engine/tests/tokens.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/twofish.test.ts b/src/engine/tests/twofish.test.ts similarity index 96% rename from src/engine/twofish.test.ts rename to src/engine/tests/twofish.test.ts index 70c23d5..a7a05f0 100644 --- a/src/engine/twofish.test.ts +++ b/src/engine/tests/twofish.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/utils.test.ts b/src/engine/tests/utils.test.ts similarity index 98% rename from src/engine/utils.test.ts rename to src/engine/tests/utils.test.ts index d704f81..0c9d51b 100644 --- a/src/engine/utils.test.ts +++ b/src/engine/tests/utils.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/xpress.test.ts b/src/engine/tests/xpress.test.ts similarity index 97% rename from src/engine/xpress.test.ts rename to src/engine/tests/xpress.test.ts index 9402495..330100b 100644 --- a/src/engine/xpress.test.ts +++ b/src/engine/tests/xpress.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/yaml.test.ts b/src/engine/tests/yaml.test.ts similarity index 97% rename from src/engine/yaml.test.ts rename to src/engine/tests/yaml.test.ts index 0e90437..d0e9049 100644 --- a/src/engine/yaml.test.ts +++ b/src/engine/tests/yaml.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { bake, renderText } from './index'; -import { getOperation } from './operations'; -import type { Recipe } from './types'; +import { bake, renderText } from '../index'; +import { getOperation } from '../operations'; +import type { Recipe } from '../types'; type Entry = string | [string, Record]; diff --git a/src/engine/yara.test.ts b/src/engine/tests/yara.test.ts similarity index 98% rename from src/engine/yara.test.ts rename to src/engine/tests/yara.test.ts index 81e56f6..b81f692 100644 Binary files a/src/engine/yara.test.ts and b/src/engine/tests/yara.test.ts differ diff --git a/src/sdk/classic.ts b/src/sdk/classic.ts new file mode 100644 index 0000000..248cc87 --- /dev/null +++ b/src/sdk/classic.ts @@ -0,0 +1,2 @@ +import { DecodeBox } from './index'; +Object.defineProperty(globalThis, 'DecodeBox', { value: DecodeBox, configurable: true }); diff --git a/src/sdk/index.ts b/src/sdk/index.ts new file mode 100644 index 0000000..6b9b112 --- /dev/null +++ b/src/sdk/index.ts @@ -0,0 +1,219 @@ +import './select'; +import * as engine from '../engine/heavy'; +import type { AutoDecodeOptions } from '../engine/detection/autoDecode'; +import type { AnalyseOptions } from '../engine/analysis/types'; +import type { CtfOptions } from '../engine/ctf/types'; +import type { InspectOptions } from '../engine/inspect'; +import type { OperationArg, Recipe, RecipeStep } from '../engine/types'; +import { bytesToLatin1 } from '../engine/core/bytes'; +import { CHARSET_NAMES } from '../engine/core/charsets'; +import { runtime } from '../engine/runtime'; +import { MAX_OUTPUT } from '../engine/runtime/limits'; +import { version } from '../../package.json'; + +export type Input = string | Uint8Array | ArrayBuffer; +type Value = OperationArg['value']; +export type Arguments = Record; +export interface Step { + opId: string; + args?: Arguments; + disabled?: boolean; +} + +export class DecodeBoxError extends Error { + readonly name = 'DecodeBoxError'; + constructor( + readonly code: 'INVALID_INPUT' | 'UNKNOWN_OPERATION' | 'OPERATION_FAILED' | 'LIMIT_EXCEEDED', + message: string, + ) { + super(message); + } +} +const MAX_INPUT = 4 * 1024 * 1024; +const MAX_STEPS = 128; +const bad = (message: string): never => { + throw new DecodeBoxError('INVALID_INPUT', message); +}; +function checkLength(size: number, limit: number) { + if (size > limit) + throw new DecodeBoxError('LIMIT_EXCEEDED', 'Value exceeds limit of ' + limit + '.'); +} +function inputOf(value: Input) { + if (typeof value === 'string') { + checkLength(value.length, MAX_INPUT); + return value; + } + if (!(value instanceof Uint8Array || value instanceof ArrayBuffer)) + return bad('Expected a string, Uint8Array or ArrayBuffer.'); + checkLength(value.byteLength, MAX_INPUT); + return bytesToLatin1(value instanceof Uint8Array ? value : new Uint8Array(value)); +} +function record(value: unknown): value is Record { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) + ); +} +type RecipeInput = readonly (Step | RecipeStep)[] | Pick; + +function argumentValues(args: Arguments | OperationArg[] | undefined, maxArgs: number): Arguments { + if (args === undefined) return {}; + if (!Array.isArray(args)) { + if (!record(args)) return bad('Expected an argument map.'); + return args; + } + if (args.length > maxArgs) return bad('Too many recipe arguments.'); + const result: Arguments = Object.create(null); + for (const item of args) { + if (!record(item) || typeof item.name !== 'string' || Object.hasOwn(result, item.name)) { + return bad('Invalid or duplicate recipe argument.'); + } + result[item.name] = + item.toggleValue === undefined + ? item.value + : { value: String(item.value), format: item.toggleValue }; + } + return result; +} + +function prepare(step: Step | RecipeStep, i: number): RecipeStep { + if (!record(step) || typeof step.opId !== 'string') return bad('Expected a step with an opId.'); + const op = engine.getOperation(step.opId); + if (!op) throw new DecodeBoxError('UNKNOWN_OPERATION', 'Unknown operation: ' + step.opId); + if (step.disabled !== undefined && typeof step.disabled !== 'boolean') + return bad('disabled must be boolean.'); + const values = argumentValues(step.args, op.args.length); + if (!record(values) || Object.keys(values).some((key) => !op.args.some((a) => a.name === key))) + return bad('Unknown or invalid arguments for ' + op.id); + const args = op.args.map((a) => { + if (!Object.hasOwn(values, a.name)) return { ...a }; + const raw = values[a.name]; + const v = record(raw) ? raw.value : raw; + if (typeof v !== typeof a.value || v === undefined) return bad('Invalid type for ' + a.name); + if (typeof v === 'string') checkLength(v.length, MAX_INPUT); + if ( + typeof v === 'number' && + (!Number.isFinite(v) || v < (a.min ?? -Infinity) || v > (a.max ?? Infinity)) + ) + return bad('Out of range: ' + a.name); + if (a.options && !a.options.includes(String(v))) return bad('Invalid option for ' + a.name); + if (record(raw) && (a.type !== 'toggleString' || !a.toggleValues?.includes(raw.format))) + return bad('Invalid format for ' + a.name); + return { ...a, value: v as Value, ...(record(raw) ? { toggleValue: raw.format } : {}) }; + }); + return { uid: String(i), opId: op.id, disabled: step.disabled ?? false, args }; +} +function options(value: T | undefined, bounds: Record): T | undefined { + if (value === undefined) return undefined; + if (!record(value)) return bad('Expected an options object.'); + for (const [k, v] of Object.entries(value)) { + const max = bounds[k]; + if (!Object.hasOwn(bounds, k)) return bad('Unknown option: ' + k); + if (typeof max === 'string') { + if (typeof v !== 'string' || v.length > 256) return bad('Invalid option: ' + k); + } else if ( + typeof v !== 'number' || + !Number.isFinite(v) || + v < 0 || + v > max! || + (k !== 'threshold' && !Number.isSafeInteger(v)) + ) + return bad('Out of range: ' + k); + } + return value; +} +const decodeBounds = { maxDepth: 64, budgetMs: 60000, threshold: 1 }; +const analysisBounds = { ...decodeBounds, maxNodes: 1024 }; +export const apiVersion = '1.0.0'; +export const engineVersion = version; +export const ready: Promise = Promise.resolve(); +export function capabilities() { + return { + runtime: runtime.name, + cryptography: !!runtime.subtle, + secureRandom: runtime.secureRandom, + compressionFormats: runtime.compressionFormats(), + charsets: [...CHARSET_NAMES], + maxInputLength: MAX_INPUT, + maxOutputLength: MAX_OUTPUT, + maxSteps: MAX_STEPS, + }; +} +export function listOperations() { + return engine.publicDefinitions(); +} +export function getOperation(id: string) { + const op = engine.getOperation(id); + return op ? engine.publicDefinition(op) : null; +} +export async function bake(input: Input, recipe: RecipeInput) { + const steps = Array.isArray(recipe) ? recipe : (recipe as Pick | null)?.steps; + if (!Array.isArray(steps) || steps.length > MAX_STEPS) + return bad('Expected an array of at most 128 recipe steps.'); + const value = inputOf(input); + let argumentLength = 0; + const prepared = Array.from(steps, (step, i) => { + const checked = prepare(step, i); + for (const arg of checked.args) { + if (typeof arg.value === 'string') argumentLength += arg.value.length; + } + checkLength(argumentLength, MAX_INPUT); + return checked; + }); + return engine.bake(value, { id: 'sdk', name: 'SDK', steps: prepared }); +} +export async function executeOperation( + opId: string, + input: Input, + args?: Arguments, +): Promise { + const result = await bake(input, [{ opId, args }]); + if (result.error) throw new DecodeBoxError('OPERATION_FAILED', result.error.message); + return result.output; +} +export async function detect(input: Input) { + return engine.detect(inputOf(input)); +} +export async function autoDecode(input: Input, opts?: Partial) { + return engine.autoDecode(inputOf(input), options(opts, decodeBounds)); +} +export async function identify(input: Input) { + return engine.identify(inputOf(input)); +} +export async function analyse(input: Input, opts?: Partial) { + return engine.analyse(inputOf(input), options(opts, analysisBounds)); +} +export async function inspect(input: Input, opts: InspectOptions = {}) { + if (!record(opts) || Object.keys(opts).some((k) => k !== 'decode' && k !== 'analyse')) + return bad('Invalid inspection options.'); + return engine.inspect(inputOf(input), { + decode: options((opts as InspectOptions).decode, decodeBounds), + analyse: options((opts as InspectOptions).analyse, analysisBounds), + }); +} +export async function hints(input: Input, opts?: Partial) { + return engine.ctfHints( + inputOf(input), + options(opts, { maxDepth: 64, budgetMs: 60000, format: '' }), + ); +} + +export const DecodeBox = Object.freeze({ + ready, + apiVersion, + engineVersion, + capabilities, + listOperations, + getOperation, + executeOperation, + bake, + detect, + autoDecode, + identify, + analyse, + inspect, + hints, +}); +export default DecodeBox; diff --git a/src/sdk/sdk.test.ts b/src/sdk/sdk.test.ts new file mode 100644 index 0000000..c38853c --- /dev/null +++ b/src/sdk/sdk.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import sdk from './index'; +import { browserProvider } from '../engine/runtime/browser'; +import { argon2 } from '../engine/operations/argon2'; + +describe('public SDK v1', () => { + it('returns detached definitions and accepts engine recipes returned by detection', async () => { + const op = sdk.getOperation('to-base64')!; + op.aliases.length = 0; + expect(sdk.getOperation(op.id)!.aliases.length).toBeGreaterThan(0); + const input = 'SGVsbG8gRGVjb2RlQm94IQ=='; + const candidates = await sdk.detect(input); + const steps = candidates.find((c) => c.steps.some((s) => s.opId === 'from-base64'))!.steps; + expect((await sdk.bake(input, { steps })).output).toBe('Hello DecodeBox!'); + }); + it('rejects invalid settings before executing a step', async () => { + await expect(sdk.executeOperation('gzip', 'x', { extra: true })).rejects.toMatchObject({ + code: 'INVALID_INPUT', + }); + await expect(sdk.autoDecode('x', { budgetMs: Infinity })).rejects.toMatchObject({ + code: 'INVALID_INPUT', + }); + await expect(sdk.inspect('x', { analyse: { maxNodes: -1 } })).rejects.toMatchObject({ + code: 'INVALID_INPUT', + }); + await expect(sdk.bake('x', new Array(129).fill({ opId: 'comment' }))).rejects.toMatchObject({ + code: 'INVALID_INPUT', + }); + expect((await sdk.bake('x', [{ opId: 'reverse' }, { opId: 'gunzip' }])).error?.stepIndex).toBe( + 1, + ); + }); + it('preserves a sliced binary input through compression', async () => { + const bytes = new Uint8Array(1024 * 1024 + 2).fill(0xff).subarray(1, -1); + const result = await sdk.bake(bytes, [{ opId: 'gzip' }, { opId: 'gunzip' }]); + expect(result.error).toBeUndefined(); + expect(result.output).toBe('\xff'.repeat(bytes.length)); + }); + it('limits expanded bytes while reading even if the consumer declares a smaller limit', async () => { + const compressed = await browserProvider.transform(Uint8Array.of(1, 2, 3, 4), 'deflate', true); + await expect(browserProvider.transform(compressed, 'deflate', false, 3)).rejects.toThrow( + /limit/, + ); + await expect(browserProvider.transform(compressed, 'deflate', false, 4)).resolves.toEqual( + Uint8Array.of(1, 2, 3, 4), + ); + }); + it('bounds memory parameters from encoded password hashes', () => { + expect(() => + argon2({ + password: new Uint8Array(), + salt: new Uint8Array(8), + type: 2, + passes: 1, + parallelism: 1, + tagLength: 32, + memoryKiB: 2 ** 31, + }), + ).toThrow(/limit/); + }); +}); diff --git a/src/sdk/select.ts b/src/sdk/select.ts new file mode 100644 index 0000000..c85b5a3 --- /dev/null +++ b/src/sdk/select.ts @@ -0,0 +1,5 @@ +import { installProvider } from '../engine/runtime'; +import { createGraalProvider } from '../engine/runtime/graal'; +declare const Java: { type: unknown } | undefined; +if (typeof Java !== 'undefined' && typeof Java.type === 'function') + installProvider(createGraalProvider());