@e4a/pg-wasm

中文文档
0.6.10发布于 2026/09/24MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 2536

PostGuard WebAssembly bindings for the browser

原始使用文档
文档目录7 节
  1. pg-wasm
  2. Usage
  3. Fetching keys
  4. Encryption
  5. Decryption
  6. Encrypting Uint8Array
  7. Using Web Workers

pg-wasm

Most consumers want @e4a/pg-js instead of this package directly — it wraps these bindings with a friendlier API, and @e4a/pg-wasm is its dependency.

This package is published to npm on every pg-core release, at pg-core's version, and has no release cycle of its own. For what changed in a given version, read pg-core's changelog for the same version number.

This package contains automatically generated WebAssembly bindings to call into the PostGuard Rust library from Javascript or Typescript. This library has been configured to run in a browser via a bundler.

The ReadableStream and WritableStream Web APIs are required. Most notably, WritableStream is not supported on Firefox until version 100, see WritableStream.

If not available, please consider using a polyfill, see web-streams-polyfill.

Usage

See the examples in postguard-js for working examples.

Fetching keys

Fetching keys from the PKG (for both decryption/signing) is easiest using the Yivi frontend packages and a custom session field.

// The URL of the PKG.
const PKG_URL = "...";

const KeySorts = {
  Encryption: "key",
  Signing: "sign/key",
};

export async function fetchKey(
  sort,
  keyRequest,
  timestamp = undefined,
  signingKeyRequest = undefined
) {
  const session = {
    url: PKG_URL,
    start: {
      url: (o) => `${o.url}/v2/request/start`,
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(keyRequest),
    },
    result: {
      url: (o, { sessionToken }) => `${o.url}/v2/request/jwt/${sessionToken}`,
      parseResponse: (r) => {
        return r
          .text()
          .then((jwt) =>
            fetch(
              `${PKG_URL}/v2/irma/${sort}${
                timestamp ? "/" + timestamp.toString() : ""
              }`,
              {
                method: sort === KeySorts.Encryption ? "GET" : "POST",
                headers: {
                  Authorization: `Bearer ${jwt}`,
                  "Content-Type": "application/json",
                },
                ...(signingKeyRequest && {
                  body: JSON.stringify({ ...signingKeyRequest }),
                }),
              }
            )
          )
          .then((r) => r.json())
          .then((json) => {
            if (json.status !== "DONE" || json.proofStatus !== "VALID")
              throw new Error("not done and valid");
            return sort === KeySorts.Encryption
              ? json.key
              : { pubSignKey: json.pubSignKey, privSignKey: json.privSignKey };
          })
          .catch((e) => console.log("error: ", e));
      },
    },
  };

  const yivi = new YiviCore({ debugging: false, session });
  yivi.use(YiviClient);
  yivi.use(YiviPopup);
  return yivi.start();
}

Encryption

// Load the WASM module.
const { sealStream } = await import("@e4a/pg-wasm");

// Retrieve the public key from PKG API:
const resp = await fetch(`${url}/v2/parameters`);
const pk = await resp.json().then((r) => r.publicKey);

// We provide the policies which we want to use for encryption.
const policy = {
  Bob: {
    ts: Math.round(Date.now() / 1000),
    con: [{ t: "irma-demo.sidn-pbdf.email.email", v: "[email protected]" }],
  },
};

// We provide the policies which we want to sign with.

// This policy is visible to everyone.
const pubSignId = [
  { t: "irma-demo.gemeente.personalData.fullname", v: "Alice" },
];

// This policy is only visible to recipients.
const privSignId = [{ t: "irma-demo.gemeente.personalData.bsn", v: "1234" }];

// We retrieve keys for these policies.
let { pubSignKey, privSignKey } = await fetchKey(
  KeySorts.Signing,
  { con: [...pubSignId, ...privSignId] },
  undefined,
  { pubSignId, privSignId }
);

const sealOptions = {
  policy,
  pubSignKey,
  privSignKey,
};

// The following call reads data from a `ReadableStream` and seals it into `WritableStream`.
// Make sure that only chunks of type `Uint8Array` are enqueued to `readable`.
await sealStream(pk, sealOptions, readable, writable);

Decryption

// Load the WASM module.
const { StreamUnsealer } = await import("@e4a/pg-wasm");

// Retrieve to global verification key.
const vk = await fetch(`${PKG_URL}/v2/sign/parameters`)
  .then((r) => r.json())
  .then((j) => j.publicKey);

// Start reading from the ReadableStream. This will read
// the metadata up until the actual payload. The stream is still locked.
const unsealer = await StreamUnsealer.new(readable, vk);

// Retrieve the recipients (and their respective policies) from the header.
const recipients = unsealer.inspect_header();

// In this case it will yield:
// {
//  'Bob': {                                              // recipient identifier
//    ts: 1643634276,                                     // timestamp
//    con: [                                              // conjunction of attributes
//      { t: "irma-demo.sidn-pbdf.email.email", v: "" },  // type/value pairs
//    ],
//  },
// }

// The disclosed values have to match with the values used for encryption.
// Note that we do not include a timestamp here.
const keyRequest = {
  con: [{ t: "irma-demo.sidn-pbdf.email.email", v: "Bob" }],
};

const timestamp = recipients.get("Bob").ts;
const usk = await fetchKey(KeySorts.Encryption, keyRequest, timestamp);

// Unseal the contents, writing the plaintext to a `WritableStream`.
let sender = await unsealer.unseal("Bob", usk, writable);

// console.log(sender) will give the policy that was used to sign:
// {
//   "public": {
//     "ts": 1680531126,
//     "con": [
//       {
//         "t": "irma-demo.gemeente.personalData.fullname",
//         "v": "Alice"
//       }
//     ]
//   },
//   "private": {
//     "ts": 1680531130,
//     "con": [
//       {
//         "t": "irma-demo.gemeente.personalData.bsn",
//         "v": "1234"
//       }
//     ]
//   }
// }

Encrypting Uint8Array

Encrypting and decrypting Uint8Array works similar as the example above. The WASM module also exports seal and Unsealer, which can be used for this. The function seal returns a new Uint8Array. The Unsealer.unseal method returns an array [plain, policy], where plain is a Uint8Array containing the plaintext and policy is an object containing the sender's signing policy.

Using Web Workers

Since ReadableStream and WritableStream are transferable, it is advised to perform the sealing and unsealing off the main thread, e.g., in a Web Worker. Comlink can be a useful library to communicate between threads.

版本与发布记录

@e4a/pg-wasm 共发布 31 个版本,首次发布于 2023/04/03;过去 12 个月发布了 17 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.6.10latest2026/09/241 个月前
0.6.92026/09/231 个月前
0.6.82026/09/221 个月前
0.6.72026/09/072 个月前
0.6.62026/09/042 个月前
0.6.52026/08/242 个月前

其他发布通道:rc → 0.3.0-rc.4。

关于 @e4a/pg-wasm 的常见问题

@e4a/pg-wasm 是什么?

PostGuard WebAssembly bindings for the browser

如何安装 @e4a/pg-wasm?

在项目目录运行 npm install @e4a/pg-wasm,或使用 pnpm add / yarn add / bun add。

@e4a/pg-wasm 支持 TypeScript 吗?

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

@e4a/pg-wasm 支持 ESM 还是 CommonJS?

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

@e4a/pg-wasm 可以商用吗?

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

@e4a/pg-wasm 的下载量有多少?

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

@e4a/pg-wasm 还在维护吗?

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