@gainratio/browser

中文文档
0.4.6发布于 2026/11/11MITTypeScriptES Module构建来源已验证近 30 天下载 5019

For web developers: have the browser check that downloaded data was signed by you and not changed, then keep it for offline use.

原始使用文档
文档目录8 节
  1. Try it
  2. How it works
  3. What it does not do
  4. When to use something else
  5. Install
  6. Develop
  7. More detail
  8. License

@gainratio/browser

For web developers: have the browser check that downloaded data was signed by you and not changed, then keep it for offline use.

npm install @gainratio/browser (version 0.4.6; @edgeproc/browser is the old, deprecated name)

Docs: browser.gainratio.com · Getting started · Examples

CI npm License

Many web apps download data files and work with them inside the page: a product catalog, a search index, a price list, a model. The page trusts whatever the server or CDN sends back. If a mirror serves an old copy, or a file is changed or cut short on the way, the app uses it anyway and nobody notices.

This package lets the page check the data itself. You sign the data once when you publish it. The page downloads it in a background thread (a Web Worker), checks your signature and every piece, and refuses anything that does not match. It keeps the checked copy in the browser, so the next visit downloads only what changed and still works offline. AlmaMesh uses it to download its chart engine.

Technical docs: Architecture · API guide · Getting started for developers · Security

Try it

You need Node 22.13 or newer, and uv to run the Python tool that signs the data. This takes about a minute.

  1. Make a project and install the package, plus Vite to serve the page:

    mkdir signed-data-demo && cd signed-data-demo
    npm init -y
    npm install @gainratio/browser vite
    
  2. Sign a folder of data with the edgeproc command from the Python edge-proc package:

    mkdir data
    echo '{"sku": "A-100", "name": "Blue mug", "price": 12.5}' > data/prices.json
    uvx --from 'edge-proc[bundles]' edgeproc keygen --out keys
    uvx --from 'edge-proc[bundles]' edgeproc publish --src data --origin-dir public/bundle \
      --key keys/private.key --bundle-id prices --version v1 --sequence 1
    cp keys/public.key public/public.key
    

    keygen prints wrote keys/private.key and keys/public.key and a key id. publish prints the signed pointer as JSON. public/bundle now holds that pointer (latest), a file list (manifest/) and the data in pieces (chunk/). Keep --sequence 1: the browser refuses a bundle without a sequence number, and you raise it each time you publish.

  3. Add a page. Create these three files:

    edgeproc.worker.js

    import "@gainratio/browser/worker";
    

    main.js

    import { EngineClient } from "@gainratio/browser";
    import EdgeProcWorker from "./edgeproc.worker.js?worker";
    
    const out = document.querySelector("#out");
    const client = new EngineClient(new EdgeProcWorker());
    try {
      const result = await client.sync("/bundle", "/public.key");
      const bytes = await client.readFile("prices.json");
      out.textContent = `verified ${result.version} (${result.chunksFetched} fetched, ${result.chunksReused} reused)\n` +
        new TextDecoder().decode(bytes);
    } catch (error) {
      out.textContent = `refused (${error.code}): ${error.message}`;
    }
    

    index.html

    <!doctype html>
    <h1>Signed data check</h1>
    <pre id="out" style="white-space: pre-wrap; word-break: break-all">checking...</pre>
    <script type="module" src="/main.js"></script>
    
  4. Run npx vite and open http://localhost:5173. The page downloads the bundle, checks it, and shows the file:

    The demo page after a good download: "verified v1 (1 fetched, 0 reused)" followed by the contents of prices.json

    Reload the page. It now says verified v1 (0 fetched, 1 reused): the checked copy was already stored in the browser, so nothing was downloaded again.

  5. Now play a bad mirror. Change one byte of the stored data piece:

    node -e "const fs=require('fs'),d='public/bundle/chunk/',p=d+fs.readdirSync(d)[0],b=fs.readFileSync(p);b[9]^=1;fs.writeFileSync(p,b)"
    

    Open http://localhost:5173 in a new private window. The page refuses the data instead of showing it:

    The same page with the changed file: "refused (integrity): chunk 34fa4548... failed content-address check"

    refused (integrity): chunk 34fa454858ceada20cfa0cd5236eb70f90e1021ed3bd03a6c9d5332597b3cc12 failed content-address check
    

    A private window is needed because your normal window already holds the checked copy and does not download that piece again. Run the node -e line once more to undo the change.

No browser? The same check in Node

The checking core also runs in Node. Save this as check.mjs in the same folder and run node check.mjs (with the data unchanged). The "server" is a function that reads the local files, and the second run flips one byte in each piece it serves:

import { readFile } from "node:fs/promises";
import { MemoryCacheStore, materializeFile, syncIndex, verifyEd25519 } from "@gainratio/browser";

const key = new Uint8Array(await readFile("public/public.key"));
const verify = (message, signature) => verifyEd25519(key, message, signature);
// Stands in for a web server: "/bundle/latest" is read from public/bundle/latest.
const server = async (url) => new Uint8Array(await readFile(`public${url}`));
// A bad mirror: flips one byte in every data chunk it serves.
const tampered = async (url) => {
  const bytes = await server(url);
  if (url.includes("/chunk/")) bytes[9] ^= 1;
  return bytes;
};

const store = new MemoryCacheStore();
const ok = await syncIndex({ baseUrl: "/bundle", store, fetchBytes: server, verify });
const manifest = JSON.parse(new TextDecoder().decode(await store.getManifest(ok.manifestHash)));
const bytes = await materializeFile(store, manifest, "prices.json");
console.log(`accepted ${ok.version}: ${new TextDecoder().decode(bytes).trim()}`);

await syncIndex({ baseUrl: "/bundle", store: new MemoryCacheStore(), fetchBytes: tampered, verify })
  .catch((error) => console.log(`refused: ${error.name}: ${error.message}`));
accepted v1: {"sku": "A-100", "name": "Blue mug", "price": 12.5}
refused: IntegrityError: chunk 34fa454858ceada20cfa0cd5236eb70f90e1021ed3bd03a6c9d5332597b3cc12 failed content-address check

How it works

The publisher cuts your files into pieces, names each piece by a hash of its contents, and signs one small pointer file that names the list of pieces. Your page gives the bundle URL and the public-key URL to a Web Worker. The Worker checks the pointer's signature against your key, refuses a pointer older than the one it already has, then downloads only the pieces it is missing and checks each one against its hash. Only when everything passes does the new version replace the old one in the browser's storage: one SQLite database on OPFS, or an in-memory one where OPFS is refused (that copy is re-downloaded next session). Pass cacheFallback: "none" to refuse that fallback instead: the sync then rejects at once with EngineStorageUnavailableError and downloads nothing. Any failure is a typed error, and the last good version stays.

The Worker also reports every network request it made back to the page, so you can count them. When your bundle contains a .sqlite database (for example, a product catalog or a reference dataset), the Worker opens that verified SQLite file in OPFS with full-text search (FTS5), JSON1, and vector search, and future updates download only the 64 KB pieces that changed. More in Architecture and SQL in the browser.

What it does not do

  • It does not sign or publish data. You need a publisher for that. Today that is the Python edgeproc publish command shown above.
  • Data flows one way, from publisher to browser. It does not sync user edits back to a server.
  • It does not know what your data means. It hands your app checked bytes. What they are is up to you.
  • It cannot protect a compromised page. A malicious browser extension, or an attacker who controls your public-key URL, is out of reach. Serve the key over HTTPS from your own site, not from the same mirror as the data. Keep the private key off the web server.
  • Chromium gets the full browser suite; Firefox and WebKit get one cross-browser test. In CI, Firefox and WebKit run OPFS open, the memory fallback, a SQL round trip, export/import and memory-profile detection. Playwright's WebKit refuses OPFS, so there the test checks the opfs-unavailable fallback, not OPFS itself. Real Safari is not tested.
  • Early release. 0.1.1 was the first version under @gainratio/browser and the first published by CI with npm provenance. @edgeproc/browser 0.1.0 was published by hand without provenance; that name is deprecated.
  • The optional SQLite app-state store needs a cross-origin-isolated page (COOP and COEP headers). The rest of the package does not.

When to use something else

If youUse
Fully trust your server and every CDN in betweenPlain fetch over HTTPS
Have a few files whose hashes you can put in the HTML at build timeSubresource Integrity (integrity= on a script or link tag)
Want your app's own code and pages to work offlineA service-worker cache, such as Workbox
Need users' edits to flow back to a shared serverA hosted database with sync
Run on devices with Python, not a browserThe Python edge-proc library, which uses the same bundle format
Ship data that changes without redeploying the page, and want the page to refuse anything you did not signThis package

Install

npm install @gainratio/browser

This README documents 0.4.6, which is the same code as main at the time of writing. pnpm and Bun work too. To pin an exact commit instead: pnpm add github:gainratio/edgeproc-browser#<commit-sha>.

Besides the main import there are subpath imports for the Worker entry, unbundled use, vector search, and SQLite state. The API guide lists them all with examples.

Develop

Use Node 24 (Node 26 breaks the corepack pnpm shim) and pnpm 11.5.0 through corepack:

git clone https://github.com/gainratio/edgeproc-browser
cd edgeproc-browser
corepack enable
pnpm install --frozen-lockfile
pnpm gate

pnpm gate runs lint, type checks, the build, a check that the committed dist/ matches a clean build, and the unit tests with coverage. It is the same command CI runs, and takes under a minute. pnpm test:browser runs the real-browser tests that CI also runs (Chromium, plus a cross-browser test in Firefox and WebKit). See Getting started for developers for a code map, known local traps, and a walkthrough of a first change.

More detail

License

MIT. See LICENSE.

版本与发布记录

@gainratio/browser 共发布 13 个版本,首次发布于 2026/10/03;过去 12 个月发布了 13 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.4.6latest2026/11/115 天前
0.4.52026/11/087 天前
0.4.42026/11/0214 天前
0.4.32026/10/2521 天前
0.4.22026/10/1730 天前
0.4.12026/10/071 个月前

其他发布通道:bootstrap → 0.0.0-bootstrap.0。

关于 @gainratio/browser 的常见问题

@gainratio/browser 是什么?

For web developers: have the browser check that downloaded data was signed by you and not changed, then keep it for offline use.

如何安装 @gainratio/browser?

在项目目录运行 npm install @gainratio/browser,或使用 pnpm add / yarn add / bun add。

@gainratio/browser 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gainratio/browser 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gainratio/browser 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.13。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gainratio/browser 可以商用吗?

@gainratio/browser 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gainratio/browser 的下载量有多少?

根据 npm 官方下载统计,@gainratio/browser 在 2026/10/16 – 2026/11/14 这 30 天内被下载 5,019 次,日均约 167 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gainratio/browser 还在维护吗?

最新版本 0.4.6 发布于 2026/11/11(5 天前);至今共发布 13 个版本,其中过去 12 个月发布了 13 个;首次发布于 2026/10/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。