@getmaapp/signal-wasm

中文文档
0.6.6发布于 2026/08/19AGPL-3.0-onlyTypeScriptES Module零依赖近 30 天下载 2038

Signal Protocol compiled to WebAssembly for browser-based E2EE messaging

原始使用文档
文档目录23 节
  1. Features
  2. Installation
  3. Quick Start
  4. API Reference
  5. Crypto Primitives
  6. Protocol Address
  7. Stores (In-Memory)
  8. Key Generation
  9. Protocol Operations
  10. Error Handling
  11. Safety Numbers
  12. Identity Proof-of-Possession
  13. GV2 (Private Groups)
  14. Data Structures
  15. Utility Functions
  16. Vite Configuration
  17. Testing
  18. Build from Source
  19. Security
  20. Memory Safety & Zeroization
  21. ⚠️ Panics Brick the Instance
  22. Licence
  23. Disclaimer

@getmaapp/signal-wasm

Signal Protocol compiled to WebAssembly for browser-based E2EE messaging

License: AGPL-3.0 WASM Version

Features

  • 🔐 End-to-End Encryption — Signal Protocol (PQXDH + Triple Ratchet)
  • 🛡️ Post-Quantum Ready — Kyber1024 (PQXDH) support
  • 👥 Group Messaging — Sender Keys and Private Groups (GV2)
  • 🆔 Flexible Identities — Any string identifier (Firebase UIDs, usernames, UUIDs)
  • 🔢 Safety Numbers — Identity verification fingerprints
  • 💾 Serialisation — Export/import for IndexedDB persistence
  • 🌐 Browser-First — Uses Web Crypto API for randomness

Installation

npm install @getmaapp/signal-wasm

Quick Start

import init, {
  PrivateKey,
  IdentityKeyPair,
  ProtocolAddress,
  InMemIdentityKeyStore,
  InMemSessionStore,
  InMemPreKeyStore,
  InMemSignedPreKeyStore,
  InMemKyberPreKeyStore,
  generateRegistrationId,
  generatePreKeys,
  generateSignedPreKey,
  generateKyberPreKey,
  processPreKeyBundle,
  encryptMessage,
  decryptMessage,
} from "@getmaapp/signal-wasm";

// 1. Initialise the WASM module
await init();

// 2. Generate an identity (no device ID required)
const privateKey = PrivateKey.generate();
const publicKey = privateKey.getPublicKey();
const identityKeyPair = new IdentityKeyPair(publicKey, privateKey);
const registrationId = generateRegistrationId();

// 3. Create stores
const identityStore = new InMemIdentityKeyStore(identityKeyPair, registrationId);
const sessionStore = new InMemSessionStore();
const prekeyStore = new InMemPreKeyStore();
const signedPrekeyStore = new InMemSignedPreKeyStore();
const kyberPrekeyStore = new InMemKyberPreKeyStore();

// 4. Generate keys for registration
const prekeys = await generatePreKeys(1, 100, prekeyStore);
const signedPreKey = await generateSignedPreKey(1, identityKeyPair, signedPrekeyStore);
const kyberPreKey = await generateKyberPreKey(1, identityKeyPair, kyberPrekeyStore);

// 5. Addressing (device ID is only used here)
const localAddress = new ProtocolAddress("alice-firebase-uid", 1);
const bobAddress = new ProtocolAddress("bob-firebase-uid", 1);

// 6. Establish a session (Alice processes Bob's PreKey bundle)
await processPreKeyBundle(
  bobAddress,
  localAddress,
  bobRegistrationId,
  bobIdentityKey,
  bobSignedPreKey.id,
  bobSignedPreKeyPublic,
  bobSignedPreKey.signature,
  bobPreKey.id,
  bobPreKey.public_key,
  bobKyberPreKey.id,
  bobKyberPreKey.public_key,
  bobKyberPreKey.signature,
  sessionStore,
  identityStore,
);

// 7. Encrypt a message
const plaintext = new TextEncoder().encode("Hello Bob! 🔒");
const ciphertext = await encryptMessage(
  plaintext,
  bobAddress,
  localAddress,
  sessionStore,
  identityStore,
);

// 8. Decrypt a message
const result = await decryptMessage(
  ciphertext.body,
  ciphertext.message_type,
  aliceAddress,
  bobAddress,
  sessionStore,
  identityStore,
  prekeyStore,
  signedPrekeyStore,
  kyberPrekeyStore,
);
const plaintext2 = result.plaintext;

// 9. Tombstone any one-time keys the decrypt consumed. All id fields
//    are `undefined` when nothing was consumed (e.g. non-prekey messages).
if (result.kyberPreKeyId !== undefined) {
  // delete kyber prekey result.kyberPreKeyId from your durable store
}
if (result.oneTimePreKeyId !== undefined) {
  // delete X25519 prekey result.oneTimePreKeyId from your durable store
}

API Reference

Crypto Primitives

ClassMethods
PrivateKeygenerate(), getPublicKey(), serialize(), deserialize(data)
PublicKeyserialize(), deserialize(data)
IdentityKeyPairconstructor(publicKey, privateKey), serialize(), deserialize(data)

Protocol Address

ClassDescription
ProtocolAddressconstructor(name, deviceId) — name can be any string (Firebase UID, UUID, etc.)

Stores (In-Memory)

All stores support import/export for IndexedDB persistence.

StoreConstructorImport/Export Methods
InMemIdentityKeyStorenew(identityKeyPair, registrationId)—
InMemSessionStorenew()export_session(address), import_session(address, bytes), has_session(address), archive_session(address), delete_session(address)
InMemPreKeyStorenew()export_pre_key(id), import_pre_key(id, bytes)
InMemSignedPreKeyStorenew()export_signed_pre_key(id), import_signed_pre_key(id, bytes)
InMemKyberPreKeyStorenew()export_kyber_pre_key(id), import_kyber_pre_key(id, bytes), export_kyber_usage(), import_kyber_usage(bytes)
InMemSenderKeyStorenew()export_sender_key(address, distributionId), import_sender_key(address, distributionId, bytes), remove_sender_key(address, distributionId)

Since 0.4.0: every distributionId must be a caller-minted UUID string (e.g. crypto.randomUUID()). The wrapper no longer derives an id from arbitrary group strings. remove_sender_key(address, distributionId) deletes the sender-key record (returns boolean) and must be called before re-creating a distribution on member removal/compromise, otherwise libsignal reuses the existing chain and removed members keep decrypting.

Since 0.6.0: InMemKyberPreKeyStore also carries the kyber anti-replay memory — the set of (kyberId, signedPreKeyId, senderBaseKey) triples the engine has already seen. Persist it (export_kyber_usage() → bytes, import_kyber_usage(bytes) at hydration) alongside the kyber records. Without it the replay guard resets on every reload and a replayed PreKeySignalMessage against a live last-resort key decapsulates again. This matches what Signal's own clients persist (Signal-iOS's KyberPreKeyUseRecord table, Signal-Desktop's kyberPreKey_triples).

Key Generation

FunctionReturnsDescription
generatePreKeys(startId, count, store)Promise<WasmPreKey[]>Batch-generate one-time PreKeys
generateSignedPreKey(id, identityKeyPair, store)Promise<WasmSignedPreKey>Generate a signed PreKey
generateKyberPreKey(id, identityKeyPair, store)Promise<WasmKyberPreKey>Generate a Kyber PreKey (PQXDH)
generateRegistrationId()numberGenerate unbiased registration ID (1–16383)

Protocol Operations

FunctionReturnsDescription
processPreKeyBundle(...)Promise<void>Establish a session from a PreKey bundle
encryptMessage(plaintext, recipient, localAddress, sessionStore, identityStore)Promise<WasmCiphertext>Encrypt a 1:1 message
decryptMessage(ciphertext, type, sender, localAddress, sessionStore, identityStore, prekeyStore, signedPrekeyStore, kyberPrekeyStore)Promise<WasmDecryptResult>Decrypt a 1:1 message. Result getters: plaintext (Uint8Array), plus kyberPreKeyId / oneTimePreKeyId / signedPreKeyId — the one-time pre-key ids consumed establishing a new session (undefined when none). Tombstone consumed ids in your durable store
createSenderKeyDistribution(localAddress, distributionId, senderKeyStore)Promise<Uint8Array>Create a sender key distribution message (distributionId must be a UUID string)
processSenderKeyDistribution(senderAddress, distMessage, senderKeyStore)Promise<void>Process a sender key distribution message (id read from the message)
encryptGroupMessage(localAddress, distributionId, plaintext, senderKeyStore)Promise<Uint8Array>Encrypt a group message (distributionId must be a UUID string)
decryptGroupMessage(senderAddress, ciphertext, senderKeyStore)Promise<Uint8Array>Decrypt a group message (id read from the ciphertext)

Error Handling

Every rejected promise throws a real JS Error with:

  • message — "SignalError: <detail>" in debug builds; flattened to "SignalError: Operation failed" in release builds (unchanged behaviour).
  • code — a stable machine-readable string, matched on the libsignal error type so it stays specific even in release builds:
codeMeaning
NoSenderKeyStateNo sender-key record for the message's distribution id (e.g. SKDM not processed yet — retry after pull)
DuplicatedMessageMessage counter already seen (replay/duplicate; usually benign)
ReusedKyberBaseKeyKyber anti-replay rejection: this sender base key was already used with this (kyberId, signedPreKeyId) pair — a replayed PreKeySignalMessage
UntrustedIdentitySender identity key not trusted for the address
InvalidKyberPreKeyIdReferenced Kyber pre-key id is invalid/missing
InvalidPreKeyIdReferenced pre-key id is invalid/missing
InvalidSignedPreKeyIdReferenced signed pre-key id is invalid/missing
FingerprintVersionMismatchScanned QR fingerprint version differs from ours (thrown by verifyScannableFingerprint)
FingerprintParsingErrorScanned QR fingerprint payload is undecodable or malformed
GenericEverything else, including wrapper-side validation failures

Note: String(err) now yields "Error: SignalError: …" (standard Error stringification) instead of the bare message, because the thrown value is a real Error rather than a string. Catch sites reading err.message are unaffected.

Safety Numbers

FunctionReturnsDescription
generateSafetyNumber(localUuid, localIdentityKey, contactUuid, contactIdentityKey)WasmSafetyNumberGenerate a safety number fingerprint (displayable string + scannable QR payload)
verifyScannableFingerprint(scanned, localUuid, localIdentityKey, contactUuid, contactIdentityKey)booleanSince 0.5.0. Canonical cross-perspective QR verification (ScannableFingerprint::compare): checks their.local == our.remote AND their.remote == our.local in constant time. Throws FingerprintVersionMismatch on version mismatch, FingerprintParsingError on an undecodable payload
verifySafetyNumber(...)booleanDeprecated since 0.5.0. Recomputes our own fingerprint and byte-compares — it can never validate a cross-perspective scan. Kept for API compatibility; use verifyScannableFingerprint

Identity Proof-of-Possession

Server-verifiable proof-of-possession of an identity key (e.g. to authorise a re-key). XEdDSA over the X25519 identity key, canonical libsignal signing.

FunctionReturnsDescription
signWithIdentityKey(identityPrivateKey, message)Uint8ArraySign message with the identity private key (64-byte signature)
verifyIdentitySignature(identityPublicKey, message, signature)booleanConstant-time verification; false for wrong key/message or malformed signature

GV2 (Private Groups)

ClassMethods
WasmGroupMasterKeygenerate(), from_bytes(bytes), derive_identifier(), derive_secret_params()
WasmGroupIdentifierserialize
WasmGroupSecretParamsserialize_master_key (since 0.5.0; returns the 32-byte master key, not the full params encoding), get_identifier()

Data Structures

StructProperties
WasmPreKeyid, public_key, record
WasmSignedPreKeyid, public_key, signature, timestamp, record
WasmKyberPreKeyid, public_key, signature, timestamp, record
WasmCiphertextmessage_type, body
WasmSafetyNumberdisplayable (string), scannable (Uint8Array)

Utility Functions

FunctionDescription
generate_random_bytes(length)Generate CSPRNG random bytes (max 1 MiB)
generate_uuid()Generate a UUID v4 (returns 16 bytes)
uuid_to_string(bytes)Convert 16 bytes to UUID string
uuid_from_string(str)Convert UUID string to 16 bytes
message_type_signal()Normal Signal message type constant
message_type_pre_key()PreKey message type constant
message_type_sender_key()Sender key message type constant

Vite Configuration

// vite.config.ts
import wasm from "vite-plugin-wasm";
import topLevelAwait from "vite-plugin-top-level-await";

export default defineConfig({
  plugins: [wasm(), topLevelAwait()],
});

Testing

We use wasm-bindgen-test for headless browser integration testing.

# Run tests in Headless Chrome
wasm-pack test --headless --chrome

# Run tests in Headless Firefox
wasm-pack test --headless --firefox

Build from Source

# Prerequisites
rustup target add wasm32-unknown-unknown
cargo install wasm-pack

# Build
wasm-pack build --target web --scope getmaapp

Security

  • ✅ #![deny(unsafe_code)] — No unsafe Rust
  • ✅ Input validation on all WASM-bound parameters
  • ✅ Bounded allocations (generate_random_bytes limited to 1 MiB)
  • ✅ PreKey batch generation limited to 500 keys
  • ✅ 24-bit PreKey ID wrapping (matches Signal behaviour)
  • ✅ CSPRNG via Web Crypto API
  • ✅ Generic error messages in production builds
  • ✅ Secret-bearing wrapper buffers zeroised on drop (zeroize::Zeroizing) — see caveats below
  • ✅ log_to_console debug helper is compiled out of release builds

Memory Safety & Zeroization

  • Secret-bearing buffers owned by the wrapper are wrapped in zeroize::Zeroizing and are overwritten with zeroes on drop: serialized PreKey/SignedPreKey/KyberPreKey records (each contains the private half), and the group master-key bytes held by WasmGroupMasterKey / WasmGroupSecretParams.
  • Limitations. The long-term identity key itself is a libsignal PrivateKey — an upstream Copy type over a [u8; 32] that libsignal does not zero on drop, so the wrapper cannot guarantee erasure of the identity scalar while it lives in WASM linear memory. And any bytes exported to JavaScript (via serialize(), getters, etc.) are copies in JS memory subject to the browser's garbage collector; they cannot be erased from Rust. Treat exported keys with extreme care.

⚠️ Panics Brick the Instance

Release builds use panic = "abort" (there is no unwinding across the WASM boundary). A Rust panic therefore permanently bricks the WASM instance — every subsequent call traps — and surfaces to JS as the flattened SignalError: Operation failed with no recoverable detail. A page reload (fresh instance) is the only remedy. Debug builds register console_error_panic_hook so panics are visible in the console during development.

Licence

AGPL-3.0 — See LICENSE

This package is built on libsignal v0.101.0 (commit b056faa6d) by Signal Technology Foundation.

Disclaimer

This package is not affiliated with or endorsed by Signal Technology Foundation. Signal and the Signal Protocol are trademarks of Signal Technology Foundation.

版本与发布记录

@getmaapp/signal-wasm 共发布 13 个版本,首次发布于 2026/01/15;过去 12 个月发布了 13 个版本。

版本发布日期距今
0.6.6latest2026/08/192 个月前
0.6.52026/08/163 个月前
0.6.42026/08/163 个月前
0.6.32026/08/153 个月前
0.6.22026/08/153 个月前
0.6.02026/08/123 个月前

关于 @getmaapp/signal-wasm 的常见问题

@getmaapp/signal-wasm 是什么?

Signal Protocol compiled to WebAssembly for browser-based E2EE messaging

如何安装 @getmaapp/signal-wasm?

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

@getmaapp/signal-wasm 支持 TypeScript 吗?

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

@getmaapp/signal-wasm 支持 ESM 还是 CommonJS?

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

@getmaapp/signal-wasm 可以商用吗?

@getmaapp/signal-wasm 使用 AGPL-3.0-only 许可。最严格的 Copyleft:除分发外,通过网络向用户提供基于它的服务也需要开源对应源码。闭源 SaaS 使用前务必评估。以上为概括,不构成法律意见,请以许可原文为准。

@getmaapp/signal-wasm 的下载量有多少?

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

@getmaapp/signal-wasm 还在维护吗?

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