forked from erici/openclaw-xmpp
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e53c920118 | ||
|
|
2d5e1af36c |
No files matched your search
@@ -1,5 +1,67 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.2-beta.6 - 2026-10-28
|
||||
|
||||
- Publish the reviewed beta.6 package through ClawHub under the explicit `beta`
|
||||
tag. Legacy OMEMO is opt-in; independent OMEMO 2 interoperability remains
|
||||
unproven. No stable/default promotion is included.
|
||||
- Guard xmpp.js against socket data arriving after parser teardown, preventing
|
||||
an uncaught null-parser error. Install the idempotent guard at plugin load
|
||||
so dependency reinstalls cannot remove the fix; add regression coverage.
|
||||
|
||||
- Add explicit `omemo.deliveryPolicy: "trusted-devices"`: exclude undecided,
|
||||
distrusted, retired and missing-bundle devices while requiring a trusted
|
||||
recipient device. Preserve `strict-all` as the default and fail closed on
|
||||
changed identities, corrupt state and transactional trust revocation.
|
||||
- Track delivery health separately from connection/probe health; clear typing
|
||||
after failed encrypted sends and include rate-limited encrypted review notices.
|
||||
- Add owner review/short-code approval and authenticated admin review/approval
|
||||
RPCs. Codes expire after ten minutes, are single-use and reviewer/account/key
|
||||
bound; approval grants `trusted`, never `verified`. In-band XMPP short-code
|
||||
approval remains disabled without authenticated sender-device provenance.
|
||||
|
||||
## 0.1.2-beta.5 - 2026-09-18
|
||||
|
||||
- Accept payload-free legacy OMEMO key-transport stanzas, committing their
|
||||
ratchet and prekey changes without dispatching an empty chat message, and
|
||||
recover committed transports safely after a crash.
|
||||
- Accept encrypted messages without an outer `message@id`: prefer XEP-0359
|
||||
stanza/origin IDs and otherwise derive a deterministic replay key from the
|
||||
authenticated sender and exact encrypted element. Consume every encrypted
|
||||
stanza through the OMEMO handler, including transports with no chat payload.
|
||||
|
||||
## 0.1.2-beta.4 - 2026-09-18
|
||||
|
||||
- Prepare the unpublished `0.1.2-beta.4` activation candidate. Require the
|
||||
`operator.admin` scope on the owner-only OMEMO operator command so OpenClaw
|
||||
2026.9.4 can authorize configured chat owners and expose trusted owner status
|
||||
to the external plugin handler. Keep the handler's explicit fail-closed
|
||||
owner check.
|
||||
|
||||
- Prepare the unpublished `0.1.2-beta.3` legacy OMEMO activation candidate.
|
||||
Exercise manual fingerprint approval, real maintained-fork encrypted
|
||||
delivery, exact-device retirement, restart-safe suppression, byte-identical
|
||||
bundle restoration, and encrypted delivery after rollback in one isolated
|
||||
end-to-end test.
|
||||
|
||||
- Assemble the inactive OMEMO engine, PEP discovery, remote-session creation,
|
||||
transactional send/receive, and durable inbox/outbox recovery behind an
|
||||
explicit off-by-default account switch and injected maintained-library
|
||||
bindings. Reject plaintext message/media fallback while active.
|
||||
- Add mocked two-account end-to-end and restart tests, including an actual
|
||||
maintained-fork encrypted round trip and byte-exact committed-ciphertext
|
||||
replay without repeating ratchet encryption.
|
||||
- Harden the inactive OMEMO boundary so full reconnects and XEP-0198 resumes
|
||||
recover committed deliveries before returning online, only the configured
|
||||
profile is advertised, non-DM encrypted message types fail before ratchet
|
||||
use, and foreign PEP events cannot trigger local reannouncement.
|
||||
- Add an owner-gated OMEMO operator command for fingerprint inspection, exact
|
||||
compare-and-set trust changes, distrust/retirement, guarded identity
|
||||
replacement, and exact-device activation or retirement. Persist retirement
|
||||
before PEP mutation, recover interrupted retirement before presence, refuse
|
||||
sends while retired, and prevent reconnect or self-PEP events from silently
|
||||
restoring a retired device.
|
||||
|
||||
## 0.1.2-beta.2 - 2026-09-10
|
||||
|
||||
- Add a bounded, configurable XEP-0199 probe on the existing authenticated
|
||||
|
||||
@@ -25,3 +25,22 @@ Do not commit credentials, real JIDs, private server names, transcript content,
|
||||
generated media, local backups, or packed tarballs. Public releases also
|
||||
require an explicit SPDX licence, completed live interoperability tests, and
|
||||
maintainer approval.
|
||||
|
||||
## Source synchronization
|
||||
|
||||
Keep private development history and operational notes outside public history.
|
||||
For an owner-authorized synchronization, preserve a source snapshot and Git
|
||||
bundle first. Rebuild and compare the source with the installed artifact,
|
||||
then export only reviewed generic code, tests and documentation onto the
|
||||
existing canonical public branch. Use a generic public project summary; do
|
||||
not export private plans, accounts, state, credentials or deployment evidence.
|
||||
|
||||
Run a clean lockfile install, strict typecheck, full tests, production build,
|
||||
package inspection, dependency audit and current-host import/registration.
|
||||
On older-glibc hosts, use a compatible isolated test machine rather than
|
||||
changing the dependency lock to work around Rollup's native test tooling.
|
||||
Scan every staged file and check the diff before committing. Fast-forward
|
||||
canonical SDF first and mirror the identical commit to GitHub; verify both
|
||||
remote IDs and CI. Never force-push or attach a remote to private history.
|
||||
Source synchronization alone does not authorize tags, package publication,
|
||||
production activation or maintainer outreach.
|
||||
@@ -0,0 +1,106 @@
|
||||
# OMEMO multi-device trust and delivery repair
|
||||
|
||||
Date: 2026-10-08
|
||||
Status: implemented in 0.1.2-beta.6 source; not included in the published beta.2.
|
||||
|
||||
Legacy/manual-trust interoperability has been exercised with Gajim and
|
||||
Conversations. OMEMO 2 has no independent live-client interoperability proof.
|
||||
Admin RPCs and authenticated owner-channel short codes are implemented; no new
|
||||
graphical Control UI page or in-band XMPP approval is claimed.
|
||||
|
||||
## Original finding (before beta.6)
|
||||
|
||||
An established, verified client can receive typing notifications but no answer
|
||||
after another device appears on its account. `src/omemo/session.ts`,
|
||||
`#resolveRecipients`, resolves every advertised recipient and sender device,
|
||||
building each missing session before returning the full device list. A manual
|
||||
trust refusal for any one device aborts the entire send. The outbound cipher
|
||||
also enforces trust for every target. Refusing untrusted keys is correct;
|
||||
making all previously trusted devices unusable is the usability defect.
|
||||
|
||||
`src/inbound.ts` logs the dispatch failure, but `src/transport.ts` does not
|
||||
record an OMEMO send failure in channel status. Ping health can therefore look
|
||||
good while actual replies fail. `OmemoTrustError` already carries address,
|
||||
fingerprint, direction and state, but the current stringified log hides most
|
||||
of that useful diagnostic data.
|
||||
|
||||
## Recommended product behaviour
|
||||
|
||||
1. Continue encrypting replies to currently trusted/verified recipient devices.
|
||||
Exclude undecided, distrusted and retired devices; show that those devices
|
||||
are excluded rather than reporting delivery to all devices. Never send a
|
||||
plaintext fallback or automatically promote an unknown key to verified.
|
||||
2. Require at least one eligible device of the actual recipient. The bot's
|
||||
own sync devices alone never satisfy this condition. If none is eligible,
|
||||
report a delivery-blocked state in the authenticated admin interface.
|
||||
3. Discover and record pending public identities separately from encryption.
|
||||
A failed or untrusted optional device must not prevent discovery of the
|
||||
remaining devices. Use typed failures, bounded network work, and a clear
|
||||
per-device outcome; do not catch every exception and silently continue.
|
||||
4. Preserve strict handling of identity replacement, corrupt state and ratchet
|
||||
errors. Initially, an observed changed identity is a hard failure requiring
|
||||
explicit review, not an ordinary newly discovered device. Re-check selected
|
||||
trust within the encryption transaction to avoid a revoke/send race.
|
||||
5. Keep an explicit strict-all-devices policy for installations that need it.
|
||||
Add a documented trusted-devices policy with migration/onboarding choice;
|
||||
do not silently change existing installations' delivery policy.
|
||||
6. Surface `connected` and `delivery blocked/degraded` independently. Expose
|
||||
pending-device count, last send failure and review action. Do not let a
|
||||
successful ping erase a delivery error. Clear typing state promptly on
|
||||
failure and clear delivery errors only following appropriate recovery.
|
||||
|
||||
## Easier review without weakening identity checks
|
||||
|
||||
- Present pending identities with account, device ID, full fingerprint,
|
||||
observation time and current policy. Device labels are hints, not proof.
|
||||
- Offer an authenticated admin action or a short-lived approval token from an
|
||||
already verified owner device. Bind the token to account, JID, device ID,
|
||||
fingerprint, expected state, permitted action, expiry and requesting owner.
|
||||
Enforce one-time use and exact compare-and-set semantics.
|
||||
- Distinguish owner-approved `trusted` from independently fingerprint-checked
|
||||
`verified`. A click approving a device does not itself prove its identity.
|
||||
- Preserve the authenticated OMEMO sender-device identity through inbound
|
||||
transport and crash recovery before permitting in-band approval. Currently
|
||||
`#omemoIo` drops senderDeviceId, and recovered dispatch uses a placeholder;
|
||||
neither may be used as evidence of an already verified approving device.
|
||||
- Send rate-limited review notices only to eligible trusted devices, or show
|
||||
them locally in the authenticated admin UI. Do not depend on another chat
|
||||
platform being configured. Never expose the reply body in an error notice.
|
||||
- First-device bootstrap still needs an independent trust anchor (fingerprint
|
||||
comparison, QR flow with client support, or explicit first-use trust choice).
|
||||
Do not claim universal automatic cross-client verification without a tested
|
||||
authenticated protocol supported by both clients.
|
||||
|
||||
## Existing TOFU option is not the immediate fix
|
||||
|
||||
`trustMode: tofu` marks a newly observed identity `trusted`, not `verified`.
|
||||
It has a first-contact authenticity trade-off and should remain an explicit
|
||||
setup choice. `observeIdentity` preserves an existing trust record; switching
|
||||
the setting does not promote an already undecided device. Changing the mode
|
||||
is therefore neither an independently verified fix nor a repair for this
|
||||
specific stored record. Marking the record distrusted also does not fix the
|
||||
current all-device planner; it still tries that device.
|
||||
|
||||
## Implementation order and acceptance gates
|
||||
|
||||
1. Add delivery status/error diagnostics and structured per-device failures.
|
||||
2. Implement explicit trusted-device recipient planning, discovery and selected
|
||||
target transaction checks. Keep existing strict policy available.
|
||||
3. Prove in the private VM on exact OpenClaw 2026.9.8: a verified client keeps
|
||||
receiving encrypted replies when a second undecided device is advertised;
|
||||
that second device cannot decrypt. Capture actual client rendering, not
|
||||
only successful socket writes or empty queues.
|
||||
4. Cover all-unknown recipients, revoked/retired devices, unknown own devices,
|
||||
changed keys, corrupt records, missing bundles, trust changes during send,
|
||||
and strict-mode behaviour. Preserve deterministic targets, atomic ratchet
|
||||
commits, exact-ciphertext retries and restart recovery.
|
||||
5. Add the scoped review UX and test authorization, expiry, replay rejection,
|
||||
changed fingerprints, account isolation and recovered sender provenance.
|
||||
6. Run remote full tests/typecheck/build/package and isolated packed import.
|
||||
Stage a versioned candidate with reviewed release notes and rollback.
|
||||
Deployment/restart is a separate step, not part of this investigation.
|
||||
|
||||
Do not promise automatic replay of today's unsent replies: trust refusal
|
||||
occurs before ciphertext outbox creation. Any future queued plaintext must be
|
||||
sealed at rest, bounded, deduplicated and re-authorized at send time. The first
|
||||
repair should use a new client test message after trust/policy remediation.
|
||||
+54
-1135
File diff suppressed because it is too large.
Load diff
@@ -10,12 +10,14 @@ The canonical source repository is
|
||||
is a clearly labelled one-way GitHub mirror that points back to SDF as the
|
||||
source of truth. Eric is the initial maintainer.
|
||||
|
||||
This project is pre-release. Version `0.1.2-beta.2` is available through
|
||||
ClawHub for explicit beta testing; there is no stable/default release yet.
|
||||
This project is pre-release. The source tree is `0.1.2-beta.6`, including
|
||||
opt-in legacy OMEMO, trusted-device delivery and a stale-parser crash guard.
|
||||
The ClawHub beta release is `0.1.2-beta.6`; there is no stable/default release
|
||||
yet. Releases remain on the explicit `beta` tag.
|
||||
Install the reviewed beta explicitly with:
|
||||
|
||||
```bash
|
||||
openclaw plugins install clawhub:openclaw-xmpp@0.1.2-beta.2
|
||||
openclaw plugins install clawhub:openclaw-xmpp@0.1.2-beta.6
|
||||
```
|
||||
|
||||
Core interoperability has been exercised against both Prosody and ejabberd,
|
||||
@@ -42,8 +44,10 @@ The durable project goal, status, decisions, and roadmap are maintained in
|
||||
`filePath`; captions are sent immediately before a URL-only XEP-0428
|
||||
fallback media stanza so Conversations renders supported files inline
|
||||
|
||||
MUC/group chats, OMEMO, reactions, edits, retractions, and inbound file
|
||||
downloads are not supported in the initial release.
|
||||
MUC/group chats, reactions, edits, retractions, and inbound file downloads
|
||||
are not supported. Beta.6 provides explicitly opt-in legacy OMEMO with manual
|
||||
trust controls. OMEMO 2 has no independent live-client interoperability proof
|
||||
and is experimental.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -178,6 +182,89 @@ can cause a later follow-up to start a fresh transcript generation. Check the
|
||||
session documentation for the OpenClaw version you deploy rather than assuming
|
||||
a fixed clock boundary across releases.
|
||||
|
||||
### Opt-in OMEMO operator lifecycle
|
||||
|
||||
The source tree contains an explicitly opt-in OMEMO implementation. It remains
|
||||
disabled by default and is not a claim of general OMEMO 2 interoperability.
|
||||
When an approved test or private activation enables it, the Gateway owner can
|
||||
use `/xmpp-omemo` to review and change trust without editing SQLite state:
|
||||
|
||||
```text
|
||||
/xmpp-omemo list <account>
|
||||
/xmpp-omemo trust <account> <jid.device> <expected-state> <fingerprint> <next-state>
|
||||
/xmpp-omemo replace <account> <jid.device> <expected-state> <old-fingerprint> <new-fingerprint> <next-state>
|
||||
/xmpp-omemo retire-device <account> <legacy|omemo2> <local-device-id>
|
||||
/xmpp-omemo activate-device <account> <legacy|omemo2> <local-device-id>
|
||||
```
|
||||
|
||||
Fingerprints printed by `list` are copy-safe 64-character hexadecimal values.
|
||||
Every mutation compares the reviewed prior state and fingerprint. Identity
|
||||
replacement additionally requires the exact newly observed fingerprint and
|
||||
removes the old ratchet in the same local transaction.
|
||||
|
||||
Device retirement writes a durable local marker before changing PEP, removes
|
||||
only the exact local device from the conflict-aware device list, and then
|
||||
retracts its bundle. An interrupted retirement is completed before presence on
|
||||
restart. While retired, reconnect cannot republish the device and encrypted
|
||||
sends fail closed. Local keys remain available for rollback; `activate-device`
|
||||
publishes the exact retained bundle before clearing the marker. Production
|
||||
configuration changes, Gateway restarts, and activation remain separate
|
||||
operator decisions.
|
||||
|
||||
With `trustMode: "manual"`, a first inbound encrypted stanza is rejected in
|
||||
the same transaction that would otherwise change ratchet state. If no trust
|
||||
record exists yet, make one outbound encrypted attempt to that peer first; it
|
||||
resolves the advertised bundle and records the fingerprint as `undecided`
|
||||
without sending plaintext. Review that fingerprint independently, apply the
|
||||
exact compare-and-set `trust` command, then retry encrypted traffic.
|
||||
|
||||
### Multi-device delivery and review
|
||||
|
||||
Existing configurations retain `omemo.deliveryPolicy: "strict-all"`. To allow
|
||||
trusted devices to keep receiving when a new device appears, explicitly set
|
||||
`channels.xmpp.omemo.deliveryPolicy` (or the account's `omemo.deliveryPolicy`)
|
||||
to `"trusted-devices"`. Keep the existing profile and trust mode. This excludes
|
||||
undecided, distrusted, retired and missing-bundle devices; at least one device
|
||||
of the actual recipient must remain trusted/verified. Changed keys, corrupt
|
||||
records and encryption failures still block delivery. There is no plaintext
|
||||
fallback. `trustMode: "tofu"` is a separate first-use choice, not verification,
|
||||
and does not approve an existing undecided record.
|
||||
|
||||
Delivery status exposes `deliveryState`, `lastDeliveryError`,
|
||||
`lastDeliveryFailureAt`, `excludedDeviceCount` and `pendingDeviceCount`.
|
||||
Counts describe the most recent send attempt, not a complete account inventory.
|
||||
A successful ping does not clear a delivery error. A successful encrypted send
|
||||
clears the error and reports healthy or degraded according to excluded devices.
|
||||
Rate-limited notices are inside the encrypted reply, never its outer body.
|
||||
|
||||
On an authenticated non-XMPP owner channel:
|
||||
|
||||
```text
|
||||
/xmpp-omemo review <account>
|
||||
/xmpp-omemo approve <account> <review-code>
|
||||
```
|
||||
|
||||
Review displays full fingerprints and ready-to-use approval commands. Only
|
||||
approve a device you recognise. Approval sets `trusted`, not `verified`; keep
|
||||
using the exact fingerprint command after independent comparison for verified
|
||||
trust. Review codes expire after ten minutes, are single-use, bound to the
|
||||
reviewer/account/key/state, and invalidated by refreshed reviews or restart.
|
||||
Changed keys require the existing explicit replacement workflow.
|
||||
|
||||
Authenticated admin clients can call `xmpp.omemo.review` with `{ "accountId":
|
||||
"default" }`, then `xmpp.omemo.approve` with `{ "accountId": "default", "code":
|
||||
"<returned-code>" }`. Both require an operator with `operator.admin` scope.
|
||||
Use the same authenticated user, or the same connection when the host does not
|
||||
supply an authenticated user ID. These are Gateway RPCs, not a new built-in
|
||||
Control UI page or model tools. XMPP short-code approval is deliberately
|
||||
unavailable until the host carries verified sender-device provenance.
|
||||
|
||||
A deployment must explicitly enable the new policy. Rollback restores the
|
||||
previous package and removes the new policy field (older schemas reject it).
|
||||
Keep the OMEMO state and keys: no state migration or trust reset is needed.
|
||||
Previously failed replies were not queued and are not automatically replayed;
|
||||
send a fresh message after activation.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This project's roadmap has been informed by Mickaël Rémond and ProcessOne's
|
||||
|
||||
+12
-4
@@ -2,8 +2,8 @@
|
||||
|
||||
## Supported versions
|
||||
|
||||
Public prerelease source is available, but there is no installable package or
|
||||
stable release yet. The current `0.1.x` prerelease requires OpenClaw 2026.8.2
|
||||
The published ClawHub package is `0.1.2-beta.2`; current source is
|
||||
`0.1.2-beta.6`. There is no stable release. The current `0.1.x` prerelease requires OpenClaw 2026.8.2
|
||||
or newer and Node.js 22.22.3 or newer. Security fixes are made on the latest
|
||||
prerelease source only.
|
||||
|
||||
@@ -46,5 +46,13 @@ private network or filesystem resources. Redact secrets and personal data.
|
||||
Public reports are appropriate for ordinary bugs only after removing private
|
||||
data and confirming that the report does not describe a security weakness.
|
||||
|
||||
OMEMO is not currently implemented. Message bodies are protected in transit by
|
||||
TLS but are not end-to-end encrypted by this plugin.
|
||||
OMEMO is not included in the published beta.2. In that package, message bodies
|
||||
are protected in transit by TLS, not end-to-end encrypted by this plugin.
|
||||
Current source includes off-by-default legacy OMEMO with manual fingerprint
|
||||
review, explicit device trust, transactional state and no plaintext fallback.
|
||||
The default delivery policy is `strict-all`; `trusted-devices` is an explicit
|
||||
operator choice and does not approve unknown identities. OMEMO 2 remains
|
||||
experimental without independent live-client interoperability evidence.
|
||||
The implementation uses a pinned, reproducibly
|
||||
rebuilt project fork of `libomemo.js`; it never silently falls back from an
|
||||
OMEMO-required conversation to plaintext.
|
||||
@@ -38,6 +38,29 @@ uses a fresh implementation rather than their source.
|
||||
| XEP-0444 reactions | `src/actions.ts`, `src/actions.test.ts`, and `src/xep0444.ts`; `a78b3e9ac2d718c48b225f5c1f03fe645ff99265`, `6b9c32c45c2a292984f4f67268ee3c7c76dadfec`, and `5d08db7c5b6d5ed50f29439ebfc032eeecfe05af` | None yet | Future protocol/product influence; no code carried into the baseline |
|
||||
| Replies, threads, and MUC shape | `src/channel.ts`, `src/client.ts`, and `src/types.ts` at `a78b3e9ac2d718c48b225f5c1f03fe645ff99265` through the reviewed heads | `PROJECT.md`; no baseline source destination | Requirements input only; replies require a new XEP-0461 investigation and MUC requires a new identity/security design |
|
||||
|
||||
## OMEMO cryptographic dependency
|
||||
|
||||
OMEMO development uses a project-maintained fork of `libomemo.js` 3.0.0 under
|
||||
GPL-3.0. The fork begins at upstream signed-tag commit
|
||||
`d5ba2a36abaa57662c27ac1c27c79cc1c3a8ada9`. Local commit
|
||||
`53b727c20550da10392f3cc5d18a7e60f995b759` adds the explicit `HEAPU8`
|
||||
runtime export needed by pinned Emscripten 6.0.9; commit `cf127f3` records the
|
||||
deterministic rebuilt generated module. The complete corresponding source and
|
||||
built distribution are public at
|
||||
<https://github.com/soilDNRA/libomemo.js-openclaw>. Annotated tag
|
||||
`v3.0.0-openclaw.2` peels to commit
|
||||
`a391ba31f376ba75c0f2dc5baedff3690354de62`; the plugin manifest pins that
|
||||
commit's archive with npm lockfile integrity
|
||||
`sha512-MxCEk0WVSe/MaTcqTGK/fdD95/v2GnmX+0KmW7LFuhJ9ewNhgm4QAbInfc0GcJCwDXYBUxIyKtNMjDXfxZMw7w==`.
|
||||
The immutable `.1` tag is superseded because its source archive did not contain
|
||||
the ignored `dist/` payload and was therefore not directly installable.
|
||||
|
||||
The historical npm WebAssembly bytes are not used as the provenance boundary:
|
||||
upstream did not record their compiler version or publish npm provenance. A
|
||||
release must ship or link the exact corresponding fork source, patch, licence,
|
||||
build instructions, and immutable artefact hash. No `libomemo.js` source has
|
||||
been copied into this plugin tree; npm retrieves the exact commit archive.
|
||||
|
||||
## Rule for later adaptation
|
||||
|
||||
For each future copied or closely adapted contribution, add the exact upstream
|
||||
|
||||
@@ -4,6 +4,9 @@ import {
|
||||
|
||||
import { xmppPlugin } from "./src/channel.js";
|
||||
import { setXmppPluginRuntime } from "./src/inbound.js";
|
||||
import { registerOmemoOperatorCommand } from "./src/omemo/command.js";
|
||||
|
||||
import { registerOmemoAdmin } from "./src/omemo/admin.js";
|
||||
|
||||
const xmppPluginEntry: ReturnType<
|
||||
typeof defineChannelPluginEntry<typeof xmppPlugin>
|
||||
@@ -13,6 +16,10 @@ const xmppPluginEntry: ReturnType<
|
||||
description: "Native XMPP direct-message channel for OpenClaw.",
|
||||
plugin: xmppPlugin,
|
||||
setRuntime: setXmppPluginRuntime,
|
||||
registerFull: (api) => {
|
||||
registerOmemoOperatorCommand(api);
|
||||
registerOmemoAdmin(api);
|
||||
},
|
||||
configSchema: {
|
||||
schema: {
|
||||
type: "object",
|
||||
|
||||
+152
-22
@@ -2,10 +2,13 @@
|
||||
"id": "xmpp",
|
||||
"name": "XMPP",
|
||||
"description": "Native XMPP direct-message channel for OpenClaw.",
|
||||
"version": "0.1.2-beta.2",
|
||||
"version": "0.1.2-beta.6",
|
||||
"activation": {
|
||||
"onStartup": false
|
||||
},
|
||||
"doctorContract": {
|
||||
"stateMigrations": []
|
||||
},
|
||||
"channels": [
|
||||
"xmpp"
|
||||
],
|
||||
@@ -87,21 +90,74 @@
|
||||
"minimum": 1,
|
||||
"maximum": 100
|
||||
},
|
||||
"healthProbe": { "type": "boolean" },
|
||||
"healthProbeIntervalSeconds": { "type": "number", "minimum": 30, "maximum": 3600 },
|
||||
"healthProbeTimeoutSeconds": { "type": "number", "minimum": 5, "maximum": 60 },
|
||||
"reconnectDelaySeconds": { "type": "number", "minimum": 1, "maximum": 60 },
|
||||
"healthProbe": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"healthProbeIntervalSeconds": {
|
||||
"type": "number",
|
||||
"minimum": 30,
|
||||
"maximum": 3600
|
||||
},
|
||||
"healthProbeTimeoutSeconds": {
|
||||
"type": "number",
|
||||
"minimum": 5,
|
||||
"maximum": 60
|
||||
},
|
||||
"reconnectDelaySeconds": {
|
||||
"type": "number",
|
||||
"minimum": 1,
|
||||
"maximum": 60
|
||||
},
|
||||
"omemo": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"profile": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"legacy",
|
||||
"omemo2"
|
||||
]
|
||||
},
|
||||
"trustMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"tofu",
|
||||
"manual"
|
||||
]
|
||||
},
|
||||
"deliveryPolicy": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"strict-all",
|
||||
"trusted-devices"
|
||||
],
|
||||
"default": "strict-all"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dm": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"sessionScope": {
|
||||
"type": "string",
|
||||
"enum": ["per-user", "per-channel-peer", "per-account-channel-peer"]
|
||||
"enum": [
|
||||
"per-user",
|
||||
"per-channel-peer",
|
||||
"per-account-channel-peer"
|
||||
]
|
||||
},
|
||||
"threadReplies": {
|
||||
"type": "string",
|
||||
"enum": ["off", "inbound", "always"]
|
||||
"enum": [
|
||||
"off",
|
||||
"inbound",
|
||||
"always"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -109,10 +165,20 @@
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"idleHours": { "type": "number", "minimum": 0 },
|
||||
"maxAgeHours": { "type": "number", "minimum": 0 },
|
||||
"spawnSessions": { "type": "boolean" }
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"idleHours": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"maxAgeHours": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"spawnSessions": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"accounts": {
|
||||
@@ -146,7 +212,8 @@
|
||||
"enum": [
|
||||
"env",
|
||||
"file",
|
||||
"exec"
|
||||
"exec",
|
||||
"store"
|
||||
]
|
||||
},
|
||||
"provider": {
|
||||
@@ -219,21 +286,74 @@
|
||||
"minimum": 1,
|
||||
"maximum": 100
|
||||
},
|
||||
"healthProbe": { "type": "boolean" },
|
||||
"healthProbeIntervalSeconds": { "type": "number", "minimum": 30, "maximum": 3600 },
|
||||
"healthProbeTimeoutSeconds": { "type": "number", "minimum": 5, "maximum": 60 },
|
||||
"reconnectDelaySeconds": { "type": "number", "minimum": 1, "maximum": 60 },
|
||||
"healthProbe": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"healthProbeIntervalSeconds": {
|
||||
"type": "number",
|
||||
"minimum": 30,
|
||||
"maximum": 3600
|
||||
},
|
||||
"healthProbeTimeoutSeconds": {
|
||||
"type": "number",
|
||||
"minimum": 5,
|
||||
"maximum": 60
|
||||
},
|
||||
"reconnectDelaySeconds": {
|
||||
"type": "number",
|
||||
"minimum": 1,
|
||||
"maximum": 60
|
||||
},
|
||||
"omemo": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"profile": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"legacy",
|
||||
"omemo2"
|
||||
]
|
||||
},
|
||||
"trustMode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"tofu",
|
||||
"manual"
|
||||
]
|
||||
},
|
||||
"deliveryPolicy": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"strict-all",
|
||||
"trusted-devices"
|
||||
],
|
||||
"default": "strict-all"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dm": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"sessionScope": {
|
||||
"type": "string",
|
||||
"enum": ["per-user", "per-channel-peer", "per-account-channel-peer"]
|
||||
"enum": [
|
||||
"per-user",
|
||||
"per-channel-peer",
|
||||
"per-account-channel-peer"
|
||||
]
|
||||
},
|
||||
"threadReplies": {
|
||||
"type": "string",
|
||||
"enum": ["off", "inbound", "always"]
|
||||
"enum": [
|
||||
"off",
|
||||
"inbound",
|
||||
"always"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -241,10 +361,20 @@
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"idleHours": { "type": "number", "minimum": 0 },
|
||||
"maxAgeHours": { "type": "number", "minimum": 0 },
|
||||
"spawnSessions": { "type": "boolean" }
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"idleHours": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"maxAgeHours": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"spawnSessions": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+25
-4
@@ -1,17 +1,18 @@
|
||||
{
|
||||
"name": "openclaw-xmpp",
|
||||
"version": "0.1.2-beta.2",
|
||||
"version": "0.1.2-beta.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "openclaw-xmpp",
|
||||
"version": "0.1.2-beta.2",
|
||||
"version": "0.1.2-beta.6",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@openclaw/fs-safe": "0.5.6",
|
||||
"@xmpp/client": "0.14.0",
|
||||
"@xmpp/xml": "0.14.0"
|
||||
"@xmpp/xml": "0.14.0",
|
||||
"libomemo.js": "https://github.com/soilDNRA/libomemo.js-openclaw/archive/a391ba31f376ba75c0f2dc5baedff3690354de62.tar.gz"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "24.10.1",
|
||||
@@ -4611,6 +4612,27 @@
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/libomemo.js": {
|
||||
"version": "3.0.0-openclaw.2",
|
||||
"resolved": "https://github.com/soilDNRA/libomemo.js-openclaw/archive/a391ba31f376ba75c0f2dc5baedff3690354de62.tar.gz",
|
||||
"integrity": "sha512-MxCEk0WVSe/MaTcqTGK/fdD95/v2GnmX+0KmW7LFuhJ9ewNhgm4QAbInfc0GcJCwDXYBUxIyKtNMjDXfxZMw7w==",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"protobufjs": "^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/libomemo.js/node_modules/protobufjs": {
|
||||
"version": "8.8.0",
|
||||
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-8.8.0.tgz",
|
||||
"integrity": "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"long": "^5.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lie": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
|
||||
@@ -4650,7 +4672,6 @@
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
|
||||
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/ltx": {
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "openclaw-xmpp",
|
||||
"version": "0.1.2-beta.2",
|
||||
"version": "0.1.2-beta.6",
|
||||
"description": "Native XMPP direct-message channel plugin for OpenClaw.",
|
||||
"keywords": [
|
||||
"openclaw",
|
||||
@@ -35,7 +35,8 @@
|
||||
"dependencies": {
|
||||
"@openclaw/fs-safe": "0.5.6",
|
||||
"@xmpp/client": "0.14.0",
|
||||
"@xmpp/xml": "0.14.0"
|
||||
"@xmpp/xml": "0.14.0",
|
||||
"libomemo.js": "https://github.com/soilDNRA/libomemo.js-openclaw/archive/a391ba31f376ba75c0f2dc5baedff3690354de62.tar.gz"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"openclaw": ">=2026.8.2"
|
||||
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env node
|
||||
// Applies maintained dependency patches under patches/<dir>/*.patch.
|
||||
// Format: unified-diff-like; target taken from the '--- a/' header;
|
||||
// '+' lines carry the guarded insertion. Run after every npm install. Idempotent.
|
||||
import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
let applied = 0, skipped = 0;
|
||||
for (const dir of readdirSync(join(root, 'patches'))) {
|
||||
const d = join(root, 'patches', dir);
|
||||
if (!statSync(d).isDirectory()) continue;
|
||||
for (const f of readdirSync(d).filter((f) => f.endsWith('.patch'))) {
|
||||
const text = readFileSync(join(d, f), 'utf8');
|
||||
const header = text.split('\n').find((l) => l.startsWith('--- a/'));
|
||||
if (!header) throw new Error(`no --- a/ header in ${f}`);
|
||||
const rel = header.replace(/^--- a\//, '').split(' ')[0].replace(/^node_modules\//, '');
|
||||
const plus = text.split('\n').filter((l) => l.startsWith('+') && !l.startsWith('+++')).map((l) => l.slice(1));
|
||||
const guard = plus.find((l) => l.trim().startsWith('if (!this.parser) return;'));
|
||||
const marker = plus.find((l) => l.includes('OPENCLAW PATCH'));
|
||||
if (!guard || !marker) throw new Error(`malformed patch ${f}`);
|
||||
const anchor = '_onData(data) {';
|
||||
const p = join(root, 'node_modules', rel);
|
||||
let src = readFileSync(p, 'utf8');
|
||||
if (src.includes(guard.trim())) { skipped++; continue; }
|
||||
if (!src.includes(anchor) || !src.includes('this.parser.write(str);')) {
|
||||
throw new Error(`anchor not found in ${rel}; upstream changed — review ${f}`);
|
||||
}
|
||||
src = src.replace(anchor, anchor + '\n' + plus.join('\n'));
|
||||
writeFileSync(p, src);
|
||||
applied++;
|
||||
}
|
||||
}
|
||||
console.log(`patches applied=${applied} already-present=${skipped}`);
|
||||
@@ -0,0 +1,16 @@
|
||||
// Regression repro for 2026-10-19 Gateway crash:
|
||||
// socket 'data' -> Client._onData -> this.parser.write(str) with parser===null.
|
||||
import Connection from '@xmpp/connection';
|
||||
|
||||
process.on('uncaughtException', (e) => {
|
||||
console.log('UNCAUGHT:', e.constructor.name + ': ' + e.message);
|
||||
process.exit(2);
|
||||
});
|
||||
|
||||
const c = new Connection('example.com');
|
||||
// Post-teardown state: parser detached (as #onParserError/stop() do), socket
|
||||
// 'data' listener still registered until socket close completes.
|
||||
c.parser = null;
|
||||
c._onData(Buffer.from('<stale/>'));
|
||||
console.log('NO CRASH: stale data ignored');
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,13 @@
|
||||
--- a/node_modules/@xmpp/connection/index.js
|
||||
+++ b/node_modules/@xmpp/connection/index.js
|
||||
@@ -48,6 +48,12 @@
|
||||
_onData(data) {
|
||||
+ // OPENCLAW PATCH (2026-10-19): guard against socket "data" arriving after
|
||||
+ // parser detach (stream error, stop, or see-other-host). Fixes uncaught
|
||||
+ // TypeError "Cannot read properties of null (reading 'write')" which
|
||||
+ // can terminate the hosting process. Stale data on
|
||||
+ // a torn-down stream is dropped; protocol errors are unaffected.
|
||||
+ if (!this.parser) return;
|
||||
const str = data.toString("utf8");
|
||||
this.parser.write(str);
|
||||
}
|
||||
+26
-1
@@ -31,6 +31,7 @@ import {
|
||||
type XmppTransportStatus
|
||||
} from "./transport.js";
|
||||
import { xmppSetupWizard } from "./setup.js";
|
||||
import { createProductionOmemoSession } from "./omemo/factory.js";
|
||||
|
||||
function resolveAccountId(cfg: OpenClawConfig, accountId?: string | null): string {
|
||||
return accountId ?? resolveDefaultXmppAccountId(cfg);
|
||||
@@ -230,6 +231,12 @@ function statusSnapshot(
|
||||
? { lastOutboundAt: status.lastOutboundAt }
|
||||
: {}),
|
||||
...(status?.lastError ? { lastError: status.lastError } : {}),
|
||||
...(status?.deliveryState ? { deliveryState: status.deliveryState,
|
||||
lastDeliveryError: status.lastDeliveryError,
|
||||
lastDeliveryFailureAt: status.lastDeliveryFailureAt,
|
||||
excludedDeviceCount: status.excludedDeviceCount,
|
||||
pendingDeviceCount: status.pendingDeviceCount,
|
||||
omemoReviewMethod: "xmpp.omemo.review" } : {}),
|
||||
...(status?.phase ? { phase: status.phase } : {}),
|
||||
...(status?.reconnectAttempts !== undefined
|
||||
? { reconnectAttempts: status.reconnectAttempts }
|
||||
@@ -316,6 +323,15 @@ const basePlugin: Omit<
|
||||
message: xmppMessageAdapter,
|
||||
actions: xmppMessageActions,
|
||||
status: {
|
||||
collectStatusIssues: (accounts) => accounts.flatMap((account) => {
|
||||
const status = account as unknown as XmppTransportStatus;
|
||||
if (status.deliveryState !== "blocked" && status.deliveryState !== "degraded") return [];
|
||||
return [{ channel: "xmpp", accountId: account.accountId, kind: "runtime" as const,
|
||||
message: status.deliveryState === "blocked"
|
||||
? `Encrypted delivery blocked: ${status.lastDeliveryError ?? "review OMEMO devices"}`
|
||||
: `Encrypted delivery excludes ${status.excludedDeviceCount ?? 0} device(s); ${status.pendingDeviceCount ?? 0} awaiting approval.`,
|
||||
fix: "Review devices using xmpp.omemo.review in the authenticated admin interface or /xmpp-omemo review <account> on an authenticated owner channel." }];
|
||||
}),
|
||||
defaultRuntime: {
|
||||
accountId: "default",
|
||||
running: false,
|
||||
@@ -369,7 +385,13 @@ const basePlugin: Omit<
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}, connection.omemo?.enabled ? {
|
||||
omemoSessionFactory: (iq) => createProductionOmemoSession({
|
||||
config: connection,
|
||||
stateRoot: pluginRuntime.state.resolveStateDir(process.env),
|
||||
iq
|
||||
})
|
||||
} : {});
|
||||
const unregister = registerLiveTransport(ctx.accountId, transport);
|
||||
ctx.setStatus(statusSnapshot(ctx.account, transport.status));
|
||||
try {
|
||||
@@ -389,6 +411,9 @@ const basePlugin: Omit<
|
||||
if (!transport?.status.connected) {
|
||||
return { ok: false, reason: "not connected" };
|
||||
}
|
||||
if (transport.status.deliveryState === "blocked") {
|
||||
return { ok: false, reason: "connected but encrypted delivery is blocked; review OMEMO devices" };
|
||||
}
|
||||
if (!transport.config.healthProbe) {
|
||||
return { ok: true, reason: "connected; health probe disabled" };
|
||||
}
|
||||
|
||||
+19
-2
@@ -33,6 +33,13 @@ export interface XmppThreadBindingsConfig {
|
||||
spawnSessions?: boolean;
|
||||
}
|
||||
|
||||
export interface XmppOmemoConfig {
|
||||
enabled?: boolean;
|
||||
profile?: "legacy" | "omemo2";
|
||||
trustMode?: "tofu" | "manual";
|
||||
deliveryPolicy?: "strict-all" | "trusted-devices";
|
||||
}
|
||||
|
||||
export interface XmppAccountConfig {
|
||||
enabled?: boolean;
|
||||
name?: string;
|
||||
@@ -54,6 +61,7 @@ export interface XmppAccountConfig {
|
||||
reconnectDelaySeconds?: number;
|
||||
dm?: XmppDmConfig;
|
||||
threadBindings?: XmppThreadBindingsConfig;
|
||||
omemo?: XmppOmemoConfig;
|
||||
}
|
||||
|
||||
export interface XmppChannelConfig extends XmppAccountConfig {
|
||||
@@ -83,6 +91,7 @@ export interface ResolvedXmppAccount {
|
||||
reconnectDelaySeconds: number;
|
||||
dm?: XmppDmConfig;
|
||||
threadBindings?: XmppThreadBindingsConfig;
|
||||
omemo: { enabled: boolean; profile: "legacy" | "omemo2"; trustMode: "tofu" | "manual"; deliveryPolicy?: "strict-all" | "trusted-devices" };
|
||||
}
|
||||
|
||||
export interface XmppConnectionConfig {
|
||||
@@ -103,6 +112,7 @@ export interface XmppConnectionConfig {
|
||||
healthProbeIntervalMs: number;
|
||||
healthProbeTimeoutMs: number;
|
||||
reconnectDelayMs: number;
|
||||
omemo?: { enabled: boolean; profile: "legacy" | "omemo2"; trustMode: "tofu" | "manual"; deliveryPolicy?: "strict-all" | "trusted-devices" };
|
||||
}
|
||||
|
||||
type ConfigWithChannels = OpenClawConfig & {
|
||||
@@ -246,7 +256,13 @@ export function resolveXmppAccount(
|
||||
60
|
||||
),
|
||||
...(raw.dm ? { dm: raw.dm } : {}),
|
||||
...(raw.threadBindings ? { threadBindings: raw.threadBindings } : {})
|
||||
...(raw.threadBindings ? { threadBindings: raw.threadBindings } : {}),
|
||||
omemo: {
|
||||
enabled: raw.omemo?.enabled === true,
|
||||
profile: raw.omemo?.profile ?? "legacy",
|
||||
trustMode: raw.omemo?.trustMode ?? "manual",
|
||||
deliveryPolicy: raw.omemo?.deliveryPolicy ?? "strict-all"
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -326,7 +342,8 @@ export async function resolveXmppConnectionConfig(
|
||||
healthProbe: account.healthProbe,
|
||||
healthProbeIntervalMs: Math.floor(account.healthProbeIntervalSeconds * 1000),
|
||||
healthProbeTimeoutMs: Math.floor(account.healthProbeTimeoutSeconds * 1000),
|
||||
reconnectDelayMs: Math.floor(account.reconnectDelaySeconds * 1000)
|
||||
reconnectDelayMs: Math.floor(account.reconnectDelaySeconds * 1000),
|
||||
omemo: account.omemo
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// Upstream guards for @xmpp/* defects we cannot fix in-dependency.
|
||||
// These run once at plugin load and survive dependency reinstalls.
|
||||
|
||||
// @xmpp/connection 0.14.0 (latest upstream at time of writing) does not guard
|
||||
// Client._onData against socket "data" arriving after parser detach (stream
|
||||
// error, stop, see-other-host teardown). The uncaught
|
||||
// "TypeError: Cannot read properties of null (reading 'write')" can terminate
|
||||
// the hosting process. Upstream is unguarded, so we
|
||||
// wrap the prototype method: stale data on a torn-down stream is dropped;
|
||||
// protocol errors and live-parser forwarding are unaffected.
|
||||
import Connection from "@xmpp/connection";
|
||||
|
||||
const GUARD_FLAG = "__openclawStaleDataGuardInstalled";
|
||||
|
||||
export function installDependencyGuards(): void {
|
||||
const proto = Connection.prototype as unknown as Record<string, any> | undefined;
|
||||
if (!proto || typeof proto._onData !== "function" || proto[GUARD_FLAG]) return;
|
||||
const original = proto._onData;
|
||||
proto[GUARD_FLAG] = true;
|
||||
proto._onData = function patchedOnData(this: { parser?: unknown }, data: Buffer): void {
|
||||
if (this.parser === null || this.parser === undefined) return;
|
||||
return original.call(this, data);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
|
||||
import { getLiveTransport } from "../transport.js";
|
||||
|
||||
/** Host-authenticated admin actions; never reachable through model tools or XMPP. */
|
||||
export function registerOmemoAdmin(api: OpenClawPluginApi): void {
|
||||
for (const operation of ["review", "approve"] as const) {
|
||||
api.registerGatewayMethod(`xmpp.omemo.${operation}`, async ({ client, params, respond }) => {
|
||||
try {
|
||||
if (!client || client.connect.role !== "operator" || !client.connect.scopes?.includes("operator.admin")) {
|
||||
throw new Error("Authenticated operator.admin access is required.");
|
||||
}
|
||||
// Prefer a verified user identity, otherwise bind to this authenticated
|
||||
// connection. No caller-supplied owner field or unverified client label.
|
||||
const principal = client.authenticatedUserId ?? client.connId;
|
||||
if (!principal) throw new Error("Authenticated reviewer identity is unavailable.");
|
||||
const owner = JSON.stringify(["gateway-admin", client.authenticatedUserId ? "user" : "connection", principal]);
|
||||
const accountId = params.accountId;
|
||||
if (typeof accountId !== "string" || !accountId || accountId.length > 256) throw new Error("Invalid XMPP account ID.");
|
||||
if (Object.keys(params).some((key) => !["accountId", ...(operation === "approve" ? ["code"] : [])].includes(key))) throw new Error("Unexpected review arguments.");
|
||||
const transport = getLiveTransport(accountId);
|
||||
const session = transport?.omemoSession;
|
||||
if (!session) throw new Error("No active OMEMO session for this account.");
|
||||
if (operation === "review") {
|
||||
respond(true, { accountId, policy: session.deliveryPolicy, status: transport.status,
|
||||
excludedDevices: session.excludedDevices,
|
||||
devices: await session.inspectTrust(), approvals: await session.reviewPending(owner),
|
||||
warning: "Approve only devices you recognise. Approval grants trust, not fingerprint verification." });
|
||||
} else {
|
||||
if (typeof params.code !== "string" || !/^[A-Za-z0-9_-]{16}$/.test(params.code)) throw new Error("Invalid review code.");
|
||||
respond(true, { accountId, trust: await session.approveReview(owner, params.code) });
|
||||
}
|
||||
} catch (error) {
|
||||
respond(false, undefined, { code: "INVALID_REQUEST", message: error instanceof Error ? error.message : "OMEMO admin action failed." });
|
||||
}
|
||||
}, { scope: "operator.admin" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import type {
|
||||
OpenClawPluginApi,
|
||||
PluginCommandContext,
|
||||
PluginCommandResult
|
||||
} from "openclaw/plugin-sdk/core";
|
||||
|
||||
import { getLiveTransport } from "../transport.js";
|
||||
import { LEGACY_OMEMO, OMEMO_2, type OmemoVersion } from "./engine.js";
|
||||
import type { OmemoTrustState } from "./libomemo-store.js";
|
||||
|
||||
const TRUST_STATES = new Set<OmemoTrustState>([
|
||||
"undecided", "trusted", "verified", "distrusted", "retired"
|
||||
]);
|
||||
|
||||
export function registerOmemoOperatorCommand(api: OpenClawPluginApi): void {
|
||||
api.registerCommand({
|
||||
name: "xmpp-omemo",
|
||||
description: "Review OMEMO trust and perform guarded device lifecycle operations",
|
||||
acceptsArgs: true,
|
||||
requireAuth: true,
|
||||
requiredScopes: ["operator.admin"],
|
||||
exposeSenderIsOwner: true,
|
||||
handler: handleOmemoOperatorCommand
|
||||
});
|
||||
}
|
||||
|
||||
export async function handleOmemoOperatorCommand(
|
||||
context: PluginCommandContext
|
||||
): Promise<PluginCommandResult> {
|
||||
if (context.senderIsOwner !== true) {
|
||||
return { text: "This OMEMO operator command is restricted to the Gateway owner." };
|
||||
}
|
||||
try {
|
||||
const args = tokenize(context.args ?? "");
|
||||
const operation = args.shift();
|
||||
const accountId = args.shift();
|
||||
if (!operation || !accountId) return { text: usage() };
|
||||
const transport = getLiveTransport(accountId);
|
||||
const session = transport?.omemoSession;
|
||||
if (!transport?.status.connected || !session) {
|
||||
return { text: `XMPP account ${accountId} does not have an active connected OMEMO session.` };
|
||||
}
|
||||
|
||||
if ((operation === "review" && args.length === 0) || (operation === "approve" && args.length === 1)) {
|
||||
// The host command context does not attest an OMEMO sender device.
|
||||
// Never let a bare XMPP owner JID substitute for verified-device proof.
|
||||
if (context.channel === "xmpp" || context.channelId === "xmpp") {
|
||||
return { text: "Use the authenticated Gateway admin review (xmpp.omemo.review), or another authenticated owner channel. XMPP device approval is not available without verified sender-device provenance." };
|
||||
}
|
||||
if (!context.isAuthorizedSender || !context.senderId) throw new Error("Authenticated reviewer identity is required.");
|
||||
const owner = JSON.stringify([context.channel, context.senderId]);
|
||||
if (operation === "approve") {
|
||||
const record = await session.approveReview(owner, args[0]!);
|
||||
return { text: `Device approved as trusted (not fingerprint-verified): ${record.fingerprint}` };
|
||||
}
|
||||
const records = await session.reviewPending(owner);
|
||||
return { text: records.length ? records.map((record) => [
|
||||
`${record.address}: awaiting approval`,
|
||||
`Fingerprint: ${record.fingerprint}`,
|
||||
`First observed: ${new Date(record.firstObservedAt).toISOString()}`,
|
||||
`Policy: ${session.deliveryPolicy}. Approve only if you recognise this device.`,
|
||||
`/xmpp-omemo approve ${accountId} ${record.code}`,
|
||||
"Code expires in 10 minutes. Approval grants trust, not independent verification."
|
||||
].join("\n")).join("\n\n") : "No new devices awaiting approval. Use list to inspect rejected devices or changed identities." };
|
||||
}
|
||||
|
||||
if (operation === "list" && args.length === 0) {
|
||||
const records = await session.inspectTrust();
|
||||
if (records.length === 0) return { text: `No OMEMO remote identities are recorded for ${accountId}.` };
|
||||
return { text: records.map((record) => [
|
||||
`${record.address} ${record.state}`,
|
||||
`fingerprint ${compactFingerprint(record.fingerprint)}`,
|
||||
...(record.candidate ? [
|
||||
`replacement-candidate ${compactFingerprint(record.candidate.observedFingerprint)}`,
|
||||
`candidate-observed-at ${new Date(record.candidate.observedAt).toISOString()}`
|
||||
] : [])
|
||||
].join("\n")).join("\n\n") };
|
||||
}
|
||||
|
||||
if (operation === "trust" && args.length === 4) {
|
||||
const [address, expectedStateText, expectedFingerprint, nextStateText] = args as [string, string, string, string];
|
||||
const expectedState = trustState(expectedStateText);
|
||||
const nextState = trustState(nextStateText);
|
||||
const result = await session.transitionTrust(
|
||||
address, { state: expectedState, fingerprint: normalizeFingerprint(expectedFingerprint) }, nextState
|
||||
);
|
||||
return { text: `OMEMO trust updated for ${address}: ${result.state} ${result.fingerprint}` };
|
||||
}
|
||||
|
||||
if (operation === "replace" && args.length === 5) {
|
||||
const [address, expectedStateText, expectedFingerprint, observedFingerprint, nextStateText] =
|
||||
args as [string, string, string, string, string];
|
||||
const result = await session.replaceIdentity(
|
||||
address,
|
||||
{ state: trustState(expectedStateText), fingerprint: normalizeFingerprint(expectedFingerprint) },
|
||||
normalizeFingerprint(observedFingerprint),
|
||||
trustState(nextStateText)
|
||||
);
|
||||
return { text: `OMEMO identity replaced for ${address}: ${result.state} ${result.fingerprint}` };
|
||||
}
|
||||
|
||||
if (operation === "retire-device" && args.length === 2) {
|
||||
const [profile, deviceIdText] = args as [string, string];
|
||||
const version = profileVersion(profile);
|
||||
const deviceId = Number(deviceIdText);
|
||||
if (!Number.isSafeInteger(deviceId) || deviceId < 1 || deviceId > 0x7fffffff) {
|
||||
throw new Error("Invalid OMEMO device ID.");
|
||||
}
|
||||
await session.retireLocalDevice(version, deviceId);
|
||||
return { text: `OMEMO ${profile} device ${deviceId} is no longer advertised; its bundle item was retracted. Local state was retained for rollback.` };
|
||||
}
|
||||
if (operation === "activate-device" && args.length === 2) {
|
||||
const [profile, deviceIdText] = args as [string, string];
|
||||
const version = profileVersion(profile);
|
||||
const deviceId = Number(deviceIdText);
|
||||
if (!Number.isSafeInteger(deviceId) || deviceId < 1 || deviceId > 0x7fffffff) {
|
||||
throw new Error("Invalid OMEMO device ID.");
|
||||
}
|
||||
await session.activateLocalDevice(version, deviceId);
|
||||
return { text: `OMEMO ${profile} device ${deviceId} bundle and advertisement were restored.` };
|
||||
}
|
||||
return { text: usage() };
|
||||
} catch (error) {
|
||||
return { text: `OMEMO operator command failed: ${error instanceof Error ? error.message : String(error)}` };
|
||||
}
|
||||
}
|
||||
|
||||
function tokenize(value: string): string[] {
|
||||
const tokens = value.trim() ? value.trim().split(/\s+/) : [];
|
||||
if (tokens.some((token) => token.length > 1024) || tokens.length > 8) {
|
||||
throw new Error("Invalid OMEMO operator command arguments.");
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function trustState(value: string): OmemoTrustState {
|
||||
if (!TRUST_STATES.has(value as OmemoTrustState)) throw new Error("Invalid OMEMO trust state.");
|
||||
return value as OmemoTrustState;
|
||||
}
|
||||
|
||||
function profileVersion(value: string): OmemoVersion {
|
||||
if (value === "legacy") return LEGACY_OMEMO;
|
||||
if (value === "omemo2") return OMEMO_2;
|
||||
throw new Error("Invalid OMEMO profile; expected legacy or omemo2.");
|
||||
}
|
||||
|
||||
function normalizeFingerprint(value: string): string {
|
||||
const compact = value.replace(/[:-]/g, "").toLowerCase();
|
||||
if (!/^[0-9a-f]{64}$/.test(compact)) throw new Error("Invalid OMEMO fingerprint.");
|
||||
return compact.match(/.{8}/g)!.join(" ");
|
||||
}
|
||||
|
||||
function compactFingerprint(value: string): string {
|
||||
return value.replace(/\s/g, "");
|
||||
}
|
||||
|
||||
function usage(): string {
|
||||
return [
|
||||
"Usage:",
|
||||
"/xmpp-omemo list <account>",
|
||||
"/xmpp-omemo review <account>",
|
||||
"/xmpp-omemo approve <account> <review-code>",
|
||||
"/xmpp-omemo trust <account> <jid.device> <expected-state> <expected-fingerprint> <next-state>",
|
||||
"/xmpp-omemo replace <account> <jid.device> <expected-state> <old-fingerprint> <new-fingerprint> <next-state>",
|
||||
"/xmpp-omemo retire-device <account> <legacy|omemo2> <local-device-id>",
|
||||
"/xmpp-omemo activate-device <account> <legacy|omemo2> <local-device-id>"
|
||||
].join("\n");
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
import {
|
||||
LibomemoStoreAdapter,
|
||||
OmemoIdentityChangedError,
|
||||
type LibomemoKeyPair,
|
||||
type OmemoTrustMode
|
||||
} from "./libomemo-store.js";
|
||||
import { type OmemoRecordView, OmemoTransactionalStore } from "./store.js";
|
||||
|
||||
export const LEGACY_OMEMO = "eu.siacs.conversations.axolotl";
|
||||
export const OMEMO_2 = "urn:xmpp:omemo:2";
|
||||
export type OmemoVersion = typeof LEGACY_OMEMO | typeof OMEMO_2;
|
||||
|
||||
const LIFECYCLE_KEY = "$key-lifecycle";
|
||||
const LIFECYCLE_VERSION = 1;
|
||||
const DEFAULT_PREKEY_TARGET = 100;
|
||||
const DEFAULT_PREKEY_LOW_WATERMARK = 25;
|
||||
const DEFAULT_SIGNED_PREKEY_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const DEFAULT_RETAINED_SIGNED_PREKEYS = 2;
|
||||
|
||||
interface GeneratedPreKey { keyId: number; keyPair: LibomemoKeyPair }
|
||||
interface GeneratedSignedPreKey extends GeneratedPreKey { signature: ArrayBuffer }
|
||||
|
||||
export interface LibomemoEngineBindings {
|
||||
keyHelper: {
|
||||
generateIdentityKeyPair(): Promise<LibomemoKeyPair>;
|
||||
generateRegistrationId(): number;
|
||||
generatePreKey(keyId: number): Promise<GeneratedPreKey>;
|
||||
generateSignedPreKey(
|
||||
identityKeyPair: LibomemoKeyPair,
|
||||
signedKeyId: number,
|
||||
version: OmemoVersion
|
||||
): Promise<GeneratedSignedPreKey>;
|
||||
};
|
||||
curvePubKeyToEd25519PubKey(publicKey: ArrayBuffer): Promise<ArrayBuffer>;
|
||||
createSessionBuilder(
|
||||
store: LibomemoStoreAdapter,
|
||||
address: string,
|
||||
version: OmemoVersion
|
||||
): { processPreKey(bundle: OmemoRemoteBundle): Promise<void> };
|
||||
}
|
||||
|
||||
export interface OmemoRemoteBundle {
|
||||
identityKey: ArrayBuffer;
|
||||
signedPreKey: { publicKey: ArrayBuffer; signature: ArrayBuffer; keyId: number };
|
||||
preKey?: { publicKey?: ArrayBuffer; keyId: number };
|
||||
registrationId: number;
|
||||
}
|
||||
|
||||
export interface OmemoPublishedBundle {
|
||||
version: OmemoVersion;
|
||||
deviceId: number;
|
||||
identityKey: ArrayBuffer;
|
||||
signedPreKey: { id: number; publicKey: ArrayBuffer; signature: ArrayBuffer };
|
||||
preKeys: Array<{ id: number; publicKey: ArrayBuffer }>;
|
||||
}
|
||||
|
||||
interface SignedPreKeyMetadata { id: number; createdAt: number; signature: string }
|
||||
interface ProfileLifecycle {
|
||||
signedPreKeys: SignedPreKeyMetadata[];
|
||||
preKeyIds: number[];
|
||||
}
|
||||
interface LifecycleRecord {
|
||||
version: 1;
|
||||
nextKeyId: number;
|
||||
profiles: Record<OmemoVersion, ProfileLifecycle>;
|
||||
}
|
||||
|
||||
export interface OmemoEngineOptions {
|
||||
account: string;
|
||||
store: OmemoTransactionalStore;
|
||||
bindings: LibomemoEngineBindings;
|
||||
trustMode: OmemoTrustMode;
|
||||
preKeyTarget?: number;
|
||||
preKeyLowWatermark?: number;
|
||||
signedPreKeyMaxAgeMs?: number;
|
||||
retainedSignedPreKeys?: number;
|
||||
clock?: () => number;
|
||||
}
|
||||
|
||||
/** Transport-independent local-device, bundle and session lifecycle. */
|
||||
export class OmemoEngine {
|
||||
readonly #account: string;
|
||||
readonly #store: OmemoTransactionalStore;
|
||||
readonly #bindings: LibomemoEngineBindings;
|
||||
readonly #trustMode: OmemoTrustMode;
|
||||
readonly #preKeyTarget: number;
|
||||
readonly #preKeyLowWatermark: number;
|
||||
readonly #signedPreKeyMaxAgeMs: number;
|
||||
readonly #retainedSignedPreKeys: number;
|
||||
readonly #clock: () => number;
|
||||
|
||||
constructor(options: OmemoEngineOptions) {
|
||||
if (!options.account) throw new Error("OMEMO account must not be empty.");
|
||||
this.#account = options.account;
|
||||
this.#store = options.store;
|
||||
this.#bindings = options.bindings;
|
||||
this.#trustMode = options.trustMode;
|
||||
this.#preKeyTarget = positiveInteger(options.preKeyTarget ?? DEFAULT_PREKEY_TARGET, "prekey target");
|
||||
this.#preKeyLowWatermark = nonNegativeInteger(
|
||||
options.preKeyLowWatermark ?? DEFAULT_PREKEY_LOW_WATERMARK,
|
||||
"prekey low watermark"
|
||||
);
|
||||
if (this.#preKeyLowWatermark >= this.#preKeyTarget) {
|
||||
throw new Error("OMEMO prekey low watermark must be below the target.");
|
||||
}
|
||||
this.#signedPreKeyMaxAgeMs = positiveInteger(
|
||||
options.signedPreKeyMaxAgeMs ?? DEFAULT_SIGNED_PREKEY_MAX_AGE_MS,
|
||||
"signed-prekey maximum age"
|
||||
);
|
||||
this.#retainedSignedPreKeys = positiveInteger(
|
||||
options.retainedSignedPreKeys ?? DEFAULT_RETAINED_SIGNED_PREKEYS,
|
||||
"retained signed-prekey count"
|
||||
);
|
||||
this.#clock = options.clock ?? Date.now;
|
||||
}
|
||||
|
||||
async initialize(): Promise<Record<OmemoVersion, OmemoPublishedBundle>> {
|
||||
return this.#store.updateRecords(this.#account, async (view) => {
|
||||
const adapter = this.#adapter(view);
|
||||
let identity = adapter.getIdentityKeyPair();
|
||||
let registrationId = adapter.getLocalRegistrationId();
|
||||
if ((identity === undefined) !== (registrationId === undefined)) {
|
||||
throw new Error("Corrupt OMEMO local identity initialization state.");
|
||||
}
|
||||
if (!identity) {
|
||||
identity = await this.#bindings.keyHelper.generateIdentityKeyPair();
|
||||
registrationId = this.#bindings.keyHelper.generateRegistrationId();
|
||||
adapter.put("identityKey", identity);
|
||||
adapter.put("registrationId", registrationId);
|
||||
}
|
||||
const lifecycle = decodeLifecycle(view.get("device", LIFECYCLE_KEY));
|
||||
await this.#maintainProfile(adapter, lifecycle, identity, LEGACY_OMEMO);
|
||||
await this.#maintainProfile(adapter, lifecycle, identity, OMEMO_2);
|
||||
view.set("device", LIFECYCLE_KEY, encodeLifecycle(lifecycle));
|
||||
return this.#bundles(adapter, lifecycle, identity, registrationId!);
|
||||
});
|
||||
}
|
||||
|
||||
/** Replenish consumed one-time keys and rotate aged signed prekeys. */
|
||||
async maintainKeys(): Promise<Record<OmemoVersion, OmemoPublishedBundle>> {
|
||||
return this.initialize();
|
||||
}
|
||||
|
||||
/** Establish a sending session from a validated, parsed remote PEP bundle. */
|
||||
async buildSession(address: string, version: OmemoVersion, bundle: OmemoRemoteBundle): Promise<void> {
|
||||
validateVersion(version);
|
||||
await this.observeIdentity(address, bundle.identityKey);
|
||||
await this.#store.updateRecords(this.#account, async (view) => {
|
||||
const adapter = this.#adapter(view);
|
||||
if (!adapter.getIdentityKeyPair() || adapter.getLocalRegistrationId() === undefined) {
|
||||
throw new Error("OMEMO local device is not initialized.");
|
||||
}
|
||||
await this.#bindings.createSessionBuilder(adapter, address, version).processPreKey(bundle);
|
||||
});
|
||||
}
|
||||
|
||||
/** Discover identities without constructing a session or granting trust. */
|
||||
async observeIdentity(address: string, identityKey: ArrayBuffer): Promise<void> {
|
||||
try {
|
||||
await this.#store.updateRecords(this.#account, (view) => {
|
||||
this.#adapter(view).trust.observeIdentity(address, identityKey);
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OmemoIdentityChangedError) {
|
||||
await this.#store.updateRecords(this.#account, (view) => {
|
||||
this.#adapter(view).trust.stageCandidate(address, error.previousFingerprint, identityKey);
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async hasSession(address: string): Promise<boolean> {
|
||||
return await this.#store.updateRecords(this.#account, (view) =>
|
||||
new LibomemoStoreAdapter(view, { mode: this.#trustMode, clock: this.#clock })
|
||||
.loadSession(address) !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
#adapter(view: OmemoRecordView): LibomemoStoreAdapter {
|
||||
return new LibomemoStoreAdapter(view, { mode: this.#trustMode, clock: this.#clock });
|
||||
}
|
||||
|
||||
async #maintainProfile(
|
||||
adapter: LibomemoStoreAdapter,
|
||||
lifecycle: LifecycleRecord,
|
||||
identity: LibomemoKeyPair,
|
||||
version: OmemoVersion
|
||||
): Promise<void> {
|
||||
const profile = lifecycle.profiles[version];
|
||||
const availablePreKeyIds: number[] = [];
|
||||
for (const id of profile.preKeyIds) {
|
||||
if (await adapter.loadPreKey(id)) availablePreKeyIds.push(id);
|
||||
}
|
||||
profile.preKeyIds = availablePreKeyIds;
|
||||
profile.signedPreKeys = profile.signedPreKeys.filter((key) => adapter.loadSignedPreKey(key.id));
|
||||
const now = validTimestamp(this.#clock());
|
||||
const current = profile.signedPreKeys.at(-1);
|
||||
if (!current || now - current.createdAt >= this.#signedPreKeyMaxAgeMs) {
|
||||
const id = lifecycle.nextKeyId++;
|
||||
const generated = await this.#bindings.keyHelper.generateSignedPreKey(identity, id, version);
|
||||
if (generated.keyId !== id) throw new Error("libomemo.js returned an unexpected signed-prekey ID.");
|
||||
adapter.storeSignedPreKey(id, generated.keyPair);
|
||||
profile.signedPreKeys.push({ id, createdAt: now, signature: bytesToBase64(generated.signature) });
|
||||
}
|
||||
while (profile.signedPreKeys.length > this.#retainedSignedPreKeys) {
|
||||
const expired = profile.signedPreKeys.shift();
|
||||
if (expired) adapter.removeSignedPreKey(expired.id);
|
||||
}
|
||||
if (profile.preKeyIds.length <= this.#preKeyLowWatermark) {
|
||||
while (profile.preKeyIds.length < this.#preKeyTarget) {
|
||||
const id = lifecycle.nextKeyId++;
|
||||
const generated = await this.#bindings.keyHelper.generatePreKey(id);
|
||||
if (generated.keyId !== id) throw new Error("libomemo.js returned an unexpected prekey ID.");
|
||||
adapter.storePreKey(id, generated.keyPair);
|
||||
profile.preKeyIds.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #bundles(
|
||||
adapter: LibomemoStoreAdapter,
|
||||
lifecycle: LifecycleRecord,
|
||||
identity: LibomemoKeyPair,
|
||||
registrationId: number
|
||||
): Promise<Record<OmemoVersion, OmemoPublishedBundle>> {
|
||||
const result = {} as Record<OmemoVersion, OmemoPublishedBundle>;
|
||||
for (const version of [LEGACY_OMEMO, OMEMO_2] as const) {
|
||||
const profile = lifecycle.profiles[version];
|
||||
const signed = profile.signedPreKeys.at(-1);
|
||||
if (!signed) throw new Error("OMEMO signed-prekey lifecycle is empty.");
|
||||
const signedPair = adapter.loadSignedPreKey(signed.id)?.keyPair;
|
||||
if (!signedPair) throw new Error("OMEMO signed-prekey record is missing.");
|
||||
const preKeys = await Promise.all(profile.preKeyIds.map(async (id) => {
|
||||
const pair = (await adapter.loadPreKey(id))?.keyPair;
|
||||
if (!pair) throw new Error("OMEMO prekey record is missing.");
|
||||
return { id, publicKey: wirePreKey(pair.pubKey, version) };
|
||||
}));
|
||||
result[version] = {
|
||||
version,
|
||||
deviceId: registrationId,
|
||||
identityKey: version === OMEMO_2
|
||||
? await this.#bindings.curvePubKeyToEd25519PubKey(identity.pubKey)
|
||||
: identity.pubKey.slice(0),
|
||||
signedPreKey: {
|
||||
id: signed.id,
|
||||
publicKey: wirePreKey(signedPair.pubKey, version),
|
||||
signature: base64ToBytes(signed.signature)
|
||||
},
|
||||
preKeys
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function emptyProfile(): ProfileLifecycle { return { signedPreKeys: [], preKeyIds: [] }; }
|
||||
|
||||
function decodeLifecycle(encoded: Uint8Array | undefined): LifecycleRecord {
|
||||
if (!encoded) return {
|
||||
version: LIFECYCLE_VERSION,
|
||||
nextKeyId: 1,
|
||||
profiles: { [LEGACY_OMEMO]: emptyProfile(), [OMEMO_2]: emptyProfile() }
|
||||
};
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(encoded)); }
|
||||
catch { throw new Error("Corrupt OMEMO key-lifecycle record encoding."); }
|
||||
if (!value || typeof value !== "object") throw new Error("Corrupt OMEMO key-lifecycle record.");
|
||||
const record = value as Partial<LifecycleRecord>;
|
||||
if (record.version !== LIFECYCLE_VERSION || !Number.isSafeInteger(record.nextKeyId) ||
|
||||
(record.nextKeyId ?? 0) < 1 || !record.profiles) {
|
||||
throw new Error("Corrupt OMEMO key-lifecycle record.");
|
||||
}
|
||||
const allocatedIds: number[] = [];
|
||||
for (const version of [LEGACY_OMEMO, OMEMO_2] as const) {
|
||||
const profile = record.profiles[version];
|
||||
validateProfile(profile);
|
||||
allocatedIds.push(...profile.preKeyIds, ...profile.signedPreKeys.map((key) => key.id));
|
||||
}
|
||||
if (new Set(allocatedIds).size !== allocatedIds.length ||
|
||||
allocatedIds.some((id) => id >= record.nextKeyId!)) {
|
||||
throw new Error("Corrupt OMEMO key-lifecycle allocation state.");
|
||||
}
|
||||
return record as LifecycleRecord;
|
||||
}
|
||||
|
||||
function validateProfile(value: unknown): asserts value is ProfileLifecycle {
|
||||
if (!value || typeof value !== "object") throw new Error("Corrupt OMEMO profile lifecycle.");
|
||||
const profile = value as Partial<ProfileLifecycle>;
|
||||
if (!Array.isArray(profile.preKeyIds) || !Array.isArray(profile.signedPreKeys) ||
|
||||
profile.preKeyIds.some((id) => !Number.isSafeInteger(id) || id < 1) ||
|
||||
new Set(profile.preKeyIds).size !== profile.preKeyIds.length) {
|
||||
throw new Error("Corrupt OMEMO profile lifecycle.");
|
||||
}
|
||||
for (const key of profile.signedPreKeys) {
|
||||
if (!key || !Number.isSafeInteger(key.id) || key.id < 1 || !Number.isSafeInteger(key.createdAt) ||
|
||||
key.createdAt < 0 || typeof key.signature !== "string" ||
|
||||
!/^[A-Za-z0-9+/]+={0,2}$/.test(key.signature) || Buffer.from(key.signature, "base64").byteLength !== 64) {
|
||||
throw new Error("Corrupt OMEMO signed-prekey lifecycle.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function encodeLifecycle(record: LifecycleRecord): Buffer { return Buffer.from(JSON.stringify(record), "utf8"); }
|
||||
function wirePreKey(key: ArrayBuffer, version: OmemoVersion): ArrayBuffer {
|
||||
if (!(key instanceof ArrayBuffer) || key.byteLength !== 33 || new Uint8Array(key)[0] !== 0x05) {
|
||||
throw new Error("Invalid OMEMO generated public key.");
|
||||
}
|
||||
return version === OMEMO_2 ? key.slice(1) : key.slice(0);
|
||||
}
|
||||
function bytesToBase64(value: ArrayBuffer): string {
|
||||
if (!(value instanceof ArrayBuffer) || value.byteLength === 0) throw new Error("Invalid OMEMO signature.");
|
||||
return Buffer.from(value).toString("base64");
|
||||
}
|
||||
function base64ToBytes(value: string): ArrayBuffer { return Uint8Array.from(Buffer.from(value, "base64")).buffer; }
|
||||
function validateVersion(value: string): asserts value is OmemoVersion {
|
||||
if (value !== LEGACY_OMEMO && value !== OMEMO_2) throw new Error("Unsupported OMEMO version.");
|
||||
}
|
||||
function nonNegativeInteger(value: number, name: string): number {
|
||||
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return value;
|
||||
}
|
||||
function positiveInteger(value: number, name: string): number {
|
||||
if (!Number.isSafeInteger(value) || value < 1) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return value;
|
||||
}
|
||||
function validTimestamp(value: number): number { return nonNegativeInteger(value, "timestamp"); }
|
||||
@@ -0,0 +1,72 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { chmodSync, mkdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
KeyHelper,
|
||||
SessionBuilder,
|
||||
SessionCipher,
|
||||
curvePubKeyToEd25519PubKey
|
||||
} from "libomemo.js";
|
||||
|
||||
import type { XmppConnectionConfig } from "../config.js";
|
||||
import { LEGACY_OMEMO, OMEMO_2, type OmemoVersion } from "./engine.js";
|
||||
import type { LibomemoStoreAdapter } from "./libomemo-store.js";
|
||||
import { OmemoSession } from "./session.js";
|
||||
import { OmemoTransactionalStore } from "./store.js";
|
||||
import { XmppOmemoPepAdapter, type OmemoIqCaller } from "./xmpp-pep.js";
|
||||
|
||||
const PRIVATE_DIRECTORY_MODE = 0o700;
|
||||
|
||||
function privateDirectory(path: string): void {
|
||||
mkdirSync(path, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
|
||||
chmodSync(path, PRIVATE_DIRECTORY_MODE);
|
||||
}
|
||||
|
||||
export function resolveOmemoStateDirectory(stateRoot: string, accountId: string): string {
|
||||
const slug = accountId.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "account";
|
||||
const suffix = createHash("sha256").update(accountId).digest("hex").slice(0, 12);
|
||||
const channel = join(stateRoot, "xmpp");
|
||||
const accounts = join(channel, "accounts");
|
||||
const account = join(accounts, `${slug}-${suffix}`);
|
||||
const omemo = join(account, "omemo");
|
||||
for (const directory of [channel, accounts, account, omemo]) privateDirectory(directory);
|
||||
return omemo;
|
||||
}
|
||||
|
||||
export function createProductionOmemoSession(params: {
|
||||
config: XmppConnectionConfig;
|
||||
stateRoot: string;
|
||||
iq: OmemoIqCaller;
|
||||
}): OmemoSession {
|
||||
const omemo = params.config.omemo;
|
||||
if (!omemo?.enabled) throw new Error("Cannot create an OMEMO session while OMEMO is disabled.");
|
||||
const version: OmemoVersion = omemo.profile === "omemo2" ? OMEMO_2 : LEGACY_OMEMO;
|
||||
const store = new OmemoTransactionalStore({
|
||||
stateDirectory: resolveOmemoStateDirectory(params.stateRoot, params.config.accountId)
|
||||
});
|
||||
const bindings = {
|
||||
keyHelper: KeyHelper,
|
||||
curvePubKeyToEd25519PubKey,
|
||||
createSessionBuilder: (adapter: LibomemoStoreAdapter, address: string, profile: OmemoVersion) =>
|
||||
new SessionBuilder(adapter, address, profile),
|
||||
createSessionCipher: (adapter: LibomemoStoreAdapter, address: string, profile: OmemoVersion) =>
|
||||
new SessionCipher(adapter, address, profile)
|
||||
};
|
||||
try {
|
||||
return new OmemoSession({
|
||||
account: params.config.jid,
|
||||
version,
|
||||
trustMode: omemo.trustMode,
|
||||
deliveryPolicy: omemo.deliveryPolicy ?? "strict-all",
|
||||
store,
|
||||
engineBindings: bindings,
|
||||
outboundBindings: bindings,
|
||||
inboundBindings: bindings,
|
||||
pep: new XmppOmemoPepAdapter(params.config.jid, params.iq)
|
||||
});
|
||||
} catch (error) {
|
||||
store.close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
|
||||
import { type OmemoRecordView } from "./store.js";
|
||||
|
||||
const LOCAL_IDENTITY_KEY = "$local";
|
||||
const REGISTRATION_ID_KEY = "$registration-id";
|
||||
const KEY_PAIR_VERSION = 1;
|
||||
const TRUST_RECORD_VERSION = 1;
|
||||
const PUBLIC_KEY_BYTES = 33;
|
||||
const PRIVATE_KEY_BYTES = 32;
|
||||
const MAX_REGISTRATION_ID = 0x3fff;
|
||||
const MAX_SESSION_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
export type LibomemoKeyId = number | string;
|
||||
export type LibomemoDirection = 1 | 2;
|
||||
|
||||
export interface LibomemoKeyPair {
|
||||
pubKey: ArrayBuffer;
|
||||
privKey: ArrayBuffer;
|
||||
}
|
||||
|
||||
/** Structural copy of the callback contract published by libomemo.js 3.0.0. */
|
||||
export interface LibomemoStoreCallbacks {
|
||||
store: Record<string, unknown>;
|
||||
put(key: string, value: unknown): void;
|
||||
get<T = unknown>(key: string, defaultValue?: T): T | undefined;
|
||||
remove(key: string): void;
|
||||
isTrustedIdentity(address: string, identityKey: ArrayBuffer, direction: LibomemoDirection): boolean;
|
||||
loadIdentityKey(address: string): ArrayBuffer | undefined;
|
||||
saveIdentity(address: string, identityKey: ArrayBuffer): boolean;
|
||||
loadPreKey(keyId: LibomemoKeyId): Promise<{ keyPair: LibomemoKeyPair } | undefined>;
|
||||
storePreKey(keyId: LibomemoKeyId, keyPair: LibomemoKeyPair): void;
|
||||
removePreKey(keyId: LibomemoKeyId): void;
|
||||
loadSignedPreKey(keyId: number): { keyPair: LibomemoKeyPair } | undefined;
|
||||
storeSignedPreKey(keyId: LibomemoKeyId, keyPair: LibomemoKeyPair): void;
|
||||
removeSignedPreKey(keyId: LibomemoKeyId): void;
|
||||
loadSession(address: string): string | undefined;
|
||||
removeAllSessions(jid: string): void;
|
||||
removeSession(address: string): void;
|
||||
storeSession(address: string, record: string): void;
|
||||
getIdentityKeyPair(): LibomemoKeyPair | undefined;
|
||||
getLocalRegistrationId(): number | undefined;
|
||||
}
|
||||
|
||||
export type OmemoTrustMode = "tofu" | "manual";
|
||||
export type OmemoTrustState = "undecided" | "trusted" | "verified" | "distrusted" | "retired";
|
||||
|
||||
export interface OmemoTrustRecord {
|
||||
state: OmemoTrustState;
|
||||
fingerprint: string;
|
||||
firstObservedAt: number;
|
||||
lastObservedAt: number;
|
||||
}
|
||||
|
||||
export interface OmemoExpectedTrust {
|
||||
state: OmemoTrustState;
|
||||
fingerprint: string;
|
||||
}
|
||||
|
||||
export interface OmemoIdentityCandidate {
|
||||
previousFingerprint: string;
|
||||
observedFingerprint: string;
|
||||
identityKey: ArrayBuffer;
|
||||
observedAt: number;
|
||||
}
|
||||
|
||||
export class OmemoTrustError extends Error {
|
||||
readonly code = "OMEMO_IDENTITY_NOT_TRUSTED";
|
||||
|
||||
constructor(
|
||||
readonly address: string,
|
||||
readonly state: Exclude<OmemoTrustState, "trusted" | "verified">,
|
||||
readonly fingerprint: string,
|
||||
readonly direction: LibomemoDirection
|
||||
) {
|
||||
super(`OMEMO identity is ${state}; operator review required. Device: ${address}; fingerprint: ${fingerprint}`);
|
||||
this.name = "OmemoTrustError";
|
||||
}
|
||||
}
|
||||
|
||||
export class OmemoIdentityChangedError extends Error {
|
||||
readonly code = "OMEMO_IDENTITY_CHANGED";
|
||||
|
||||
constructor(
|
||||
readonly address: string,
|
||||
readonly previousFingerprint: string,
|
||||
readonly observedFingerprint: string
|
||||
) {
|
||||
super(`OMEMO identity key changed; operator review required. Device: ${address}; previous: ${previousFingerprint}; observed: ${observedFingerprint}`);
|
||||
this.name = "OmemoIdentityChangedError";
|
||||
}
|
||||
}
|
||||
|
||||
export class OmemoTrustConflictError extends Error {
|
||||
readonly code = "OMEMO_TRUST_CONFLICT";
|
||||
|
||||
constructor(readonly address: string) {
|
||||
super("OMEMO trust record changed since it was reviewed.");
|
||||
this.name = "OmemoTrustConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface OmemoTrustPolicyOptions {
|
||||
mode: OmemoTrustMode;
|
||||
clock?: () => number;
|
||||
}
|
||||
|
||||
/** Explicit trust policy layered over the operation-local transactional view. */
|
||||
export class OmemoTrustPolicyAdapter {
|
||||
readonly #view: OmemoRecordView;
|
||||
readonly #mode: OmemoTrustMode;
|
||||
readonly #clock: () => number;
|
||||
|
||||
constructor(view: OmemoRecordView, options: OmemoTrustPolicyOptions) {
|
||||
this.#view = view;
|
||||
this.#mode = options.mode;
|
||||
this.#clock = options.clock ?? Date.now;
|
||||
}
|
||||
|
||||
get(address: string): OmemoTrustRecord | undefined {
|
||||
validateDeviceAddress(address);
|
||||
const identity = this.#view.get("identity", address);
|
||||
const encoded = this.#view.get("trust", address);
|
||||
if (!identity && !encoded) return undefined;
|
||||
if (!identity || !encoded) throw new Error("Corrupt OMEMO identity/trust record pair.");
|
||||
|
||||
const record = decodeTrustRecord(encoded);
|
||||
if (record.fingerprint !== formatIdentityFingerprint(toArrayBuffer(identity))) {
|
||||
throw new Error("OMEMO trust fingerprint does not match the stored identity.");
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
candidate(address: string): OmemoIdentityCandidate | undefined {
|
||||
validateDeviceAddress(address);
|
||||
const encoded = this.#view.get("candidate", address);
|
||||
return encoded ? decodeIdentityCandidate(encoded) : undefined;
|
||||
}
|
||||
|
||||
stageCandidate(
|
||||
address: string,
|
||||
previousFingerprint: string,
|
||||
identityKey: ArrayBuffer
|
||||
): OmemoIdentityCandidate {
|
||||
validateDeviceAddress(address);
|
||||
const current = this.get(address);
|
||||
if (!current || current.fingerprint !== previousFingerprint) {
|
||||
throw new OmemoTrustConflictError(address);
|
||||
}
|
||||
const observed = identityKeyBuffer(identityKey);
|
||||
const candidate: OmemoIdentityCandidate = {
|
||||
previousFingerprint,
|
||||
observedFingerprint: formatIdentityFingerprint(toArrayBuffer(observed)),
|
||||
identityKey: toArrayBuffer(observed),
|
||||
observedAt: validTimestamp(this.#clock())
|
||||
};
|
||||
if (candidate.observedFingerprint === current.fingerprint) {
|
||||
throw new Error("OMEMO replacement candidate matches the current identity.");
|
||||
}
|
||||
this.#view.set("candidate", address, encodeIdentityCandidate(candidate));
|
||||
return candidate;
|
||||
}
|
||||
|
||||
observeIdentity(address: string, identityKey: ArrayBuffer): OmemoTrustRecord {
|
||||
validateDeviceAddress(address);
|
||||
const observed = identityKeyBuffer(identityKey);
|
||||
const observedFingerprint = formatIdentityFingerprint(toArrayBuffer(observed));
|
||||
const currentIdentity = this.#view.get("identity", address);
|
||||
|
||||
if (!currentIdentity) {
|
||||
if (this.#view.get("trust", address)) throw new Error("Corrupt OMEMO trust record without identity.");
|
||||
const now = validTimestamp(this.#clock());
|
||||
const record: OmemoTrustRecord = {
|
||||
state: this.#mode === "tofu" ? "trusted" : "undecided",
|
||||
fingerprint: observedFingerprint,
|
||||
firstObservedAt: now,
|
||||
lastObservedAt: now
|
||||
};
|
||||
this.#view.set("identity", address, observed);
|
||||
this.#view.set("trust", address, encodeTrustRecord(record));
|
||||
return { ...record };
|
||||
}
|
||||
|
||||
const currentFingerprint = formatIdentityFingerprint(toArrayBuffer(currentIdentity));
|
||||
if (!equalBytes(currentIdentity, observed)) {
|
||||
throw new OmemoIdentityChangedError(address, currentFingerprint, observedFingerprint);
|
||||
}
|
||||
|
||||
const record = this.get(address);
|
||||
if (!record) throw new Error("Corrupt OMEMO identity/trust record pair.");
|
||||
const lastObservedAt = Math.max(record.lastObservedAt, validTimestamp(this.#clock()));
|
||||
const updated = { ...record, lastObservedAt };
|
||||
this.#view.set("trust", address, encodeTrustRecord(updated));
|
||||
return updated;
|
||||
}
|
||||
|
||||
assertTrusted(
|
||||
address: string,
|
||||
identityKey: ArrayBuffer,
|
||||
direction: LibomemoDirection
|
||||
): OmemoTrustRecord {
|
||||
validateDirection(direction);
|
||||
const record = this.observeIdentity(address, identityKey);
|
||||
const candidate = this.candidate(address);
|
||||
if (candidate) throw new OmemoIdentityChangedError(address, record.fingerprint, candidate.observedFingerprint);
|
||||
if (record.state === "trusted" || record.state === "verified") return record;
|
||||
throw new OmemoTrustError(address, record.state, record.fingerprint, direction);
|
||||
}
|
||||
|
||||
transition(
|
||||
address: string,
|
||||
expected: OmemoExpectedTrust,
|
||||
nextState: OmemoTrustState
|
||||
): OmemoTrustRecord {
|
||||
validateTrustState(nextState);
|
||||
const current = this.get(address);
|
||||
if (!current || current.state !== expected.state || current.fingerprint !== expected.fingerprint) {
|
||||
throw new OmemoTrustConflictError(address);
|
||||
}
|
||||
const updated = { ...current, state: nextState };
|
||||
this.#view.set("trust", address, encodeTrustRecord(updated));
|
||||
return updated;
|
||||
}
|
||||
|
||||
replaceIdentity(
|
||||
address: string,
|
||||
expected: OmemoExpectedTrust,
|
||||
observedIdentityKey: ArrayBuffer,
|
||||
expectedObservedFingerprint: string,
|
||||
nextState: OmemoTrustState = "undecided"
|
||||
): OmemoTrustRecord {
|
||||
validateTrustState(nextState);
|
||||
const current = this.get(address);
|
||||
if (!current || current.state !== expected.state || current.fingerprint !== expected.fingerprint) {
|
||||
throw new OmemoTrustConflictError(address);
|
||||
}
|
||||
|
||||
const observed = identityKeyBuffer(observedIdentityKey);
|
||||
const observedFingerprint = formatIdentityFingerprint(toArrayBuffer(observed));
|
||||
if (observedFingerprint !== expectedObservedFingerprint) throw new OmemoTrustConflictError(address);
|
||||
const currentIdentity = this.#view.get("identity", address);
|
||||
if (!currentIdentity) throw new Error("Corrupt OMEMO identity/trust record pair.");
|
||||
if (equalBytes(currentIdentity, observed)) {
|
||||
throw new Error("OMEMO replacement identity matches the current identity.");
|
||||
}
|
||||
const now = validTimestamp(this.#clock());
|
||||
const replacement: OmemoTrustRecord = {
|
||||
state: nextState,
|
||||
fingerprint: observedFingerprint,
|
||||
firstObservedAt: now,
|
||||
lastObservedAt: now
|
||||
};
|
||||
this.#view.set("identity", address, observed);
|
||||
this.#view.set("trust", address, encodeTrustRecord(replacement));
|
||||
this.#view.delete("session", address);
|
||||
this.#view.delete("candidate", address);
|
||||
return replacement;
|
||||
}
|
||||
}
|
||||
|
||||
const IDENTITY_CANDIDATE_VERSION = 1;
|
||||
|
||||
function encodeIdentityCandidate(candidate: OmemoIdentityCandidate): Buffer {
|
||||
return Buffer.from(JSON.stringify({
|
||||
version: IDENTITY_CANDIDATE_VERSION,
|
||||
previousFingerprint: candidate.previousFingerprint,
|
||||
observedFingerprint: candidate.observedFingerprint,
|
||||
identityKey: Buffer.from(candidate.identityKey).toString("base64"),
|
||||
observedAt: candidate.observedAt
|
||||
}), "utf8");
|
||||
}
|
||||
|
||||
function decodeIdentityCandidate(encoded: Uint8Array): OmemoIdentityCandidate {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(encoded)); }
|
||||
catch { throw new Error("Corrupt OMEMO identity-candidate encoding."); }
|
||||
if (!value || typeof value !== "object") throw new Error("Corrupt OMEMO identity candidate.");
|
||||
const record = value as Record<string, unknown>;
|
||||
if (record.version !== IDENTITY_CANDIDATE_VERSION ||
|
||||
typeof record.previousFingerprint !== "string" ||
|
||||
typeof record.observedFingerprint !== "string" ||
|
||||
typeof record.identityKey !== "string" ||
|
||||
!Number.isSafeInteger(record.observedAt) || Number(record.observedAt) < 0) {
|
||||
throw new Error("Corrupt OMEMO identity candidate.");
|
||||
}
|
||||
const identityKey = Buffer.from(record.identityKey, "base64");
|
||||
if ((identityKey.byteLength !== 32 && identityKey.byteLength !== PUBLIC_KEY_BYTES) ||
|
||||
identityKey.toString("base64") !== record.identityKey) {
|
||||
throw new Error("Corrupt OMEMO identity candidate.");
|
||||
}
|
||||
const observedFingerprint = formatIdentityFingerprint(toArrayBuffer(identityKey));
|
||||
if (observedFingerprint !== record.observedFingerprint) throw new Error("Corrupt OMEMO identity candidate.");
|
||||
return {
|
||||
previousFingerprint: record.previousFingerprint,
|
||||
observedFingerprint,
|
||||
identityKey: toArrayBuffer(identityKey),
|
||||
observedAt: Number(record.observedAt)
|
||||
};
|
||||
}
|
||||
|
||||
export interface LibomemoStoreAdapterOptions extends OmemoTrustPolicyOptions {}
|
||||
|
||||
/**
|
||||
* libomemo.js callbacks backed only by an OmemoRecordView.
|
||||
*
|
||||
* Construct a fresh adapter inside each OmemoTransactionalStore operation.
|
||||
* The compatibility `store` property is deliberately frozen: callback methods
|
||||
* are the only supported mutation path, so writes cannot escape the transaction.
|
||||
*/
|
||||
export class LibomemoStoreAdapter implements LibomemoStoreCallbacks {
|
||||
readonly store: Record<string, unknown> = Object.freeze(Object.create(null) as Record<string, unknown>);
|
||||
readonly trust: OmemoTrustPolicyAdapter;
|
||||
readonly #view: OmemoRecordView;
|
||||
|
||||
constructor(view: OmemoRecordView, options: LibomemoStoreAdapterOptions) {
|
||||
this.#view = view;
|
||||
this.trust = new OmemoTrustPolicyAdapter(view, options);
|
||||
}
|
||||
|
||||
put(key: string, value: unknown): void {
|
||||
if (key === "identityKey") {
|
||||
this.#view.set("identity", LOCAL_IDENTITY_KEY, encodeKeyPair(requireKeyPair(value)));
|
||||
return;
|
||||
}
|
||||
if (key === "registrationId") {
|
||||
this.#view.set("device", REGISTRATION_ID_KEY, encodeRegistrationId(value));
|
||||
return;
|
||||
}
|
||||
throw new Error(`Unsupported libomemo.js generic store key: ${key}`);
|
||||
}
|
||||
|
||||
get<T = unknown>(key: string, defaultValue?: T): T | undefined {
|
||||
let value: unknown;
|
||||
if (key === "identityKey") value = this.getIdentityKeyPair();
|
||||
else if (key === "registrationId") value = this.getLocalRegistrationId();
|
||||
else throw new Error(`Unsupported libomemo.js generic store key: ${key}`);
|
||||
return (value === undefined ? defaultValue : value) as T | undefined;
|
||||
}
|
||||
|
||||
remove(key: string): void {
|
||||
if (key === "identityKey") this.#view.delete("identity", LOCAL_IDENTITY_KEY);
|
||||
else if (key === "registrationId") this.#view.delete("device", REGISTRATION_ID_KEY);
|
||||
else throw new Error(`Unsupported libomemo.js generic store key: ${key}`);
|
||||
}
|
||||
|
||||
getIdentityKeyPair(): LibomemoKeyPair | undefined {
|
||||
const encoded = this.#view.get("identity", LOCAL_IDENTITY_KEY);
|
||||
return encoded ? decodeKeyPair(encoded) : undefined;
|
||||
}
|
||||
|
||||
getLocalRegistrationId(): number | undefined {
|
||||
const encoded = this.#view.get("device", REGISTRATION_ID_KEY);
|
||||
return encoded ? decodeRegistrationId(encoded) : undefined;
|
||||
}
|
||||
|
||||
isTrustedIdentity(
|
||||
address: string,
|
||||
identityKey: ArrayBuffer,
|
||||
direction: LibomemoDirection
|
||||
): boolean {
|
||||
this.trust.assertTrusted(address, identityKey, direction);
|
||||
return true;
|
||||
}
|
||||
|
||||
loadIdentityKey(address: string): ArrayBuffer | undefined {
|
||||
validateDeviceAddress(address);
|
||||
const encoded = this.#view.get("identity", address);
|
||||
return encoded ? toArrayBuffer(identityKeyBuffer(toArrayBuffer(encoded))) : undefined;
|
||||
}
|
||||
|
||||
saveIdentity(address: string, identityKey: ArrayBuffer): boolean {
|
||||
this.trust.observeIdentity(address, identityKey);
|
||||
return false;
|
||||
}
|
||||
|
||||
async loadPreKey(keyId: LibomemoKeyId): Promise<{ keyPair: LibomemoKeyPair } | undefined> {
|
||||
const encoded = this.#view.get("prekey", normalizeKeyId(keyId));
|
||||
return encoded ? { keyPair: decodeKeyPair(encoded) } : undefined;
|
||||
}
|
||||
|
||||
storePreKey(keyId: LibomemoKeyId, keyPair: LibomemoKeyPair): void {
|
||||
this.#view.set("prekey", normalizeKeyId(keyId), encodeKeyPair(keyPair));
|
||||
}
|
||||
|
||||
removePreKey(keyId: LibomemoKeyId): void {
|
||||
this.#view.delete("prekey", normalizeKeyId(keyId));
|
||||
}
|
||||
|
||||
loadSignedPreKey(keyId: number): { keyPair: LibomemoKeyPair } | undefined {
|
||||
const encoded = this.#view.get("signed-prekey", normalizeKeyId(keyId));
|
||||
return encoded ? { keyPair: decodeKeyPair(encoded) } : undefined;
|
||||
}
|
||||
|
||||
storeSignedPreKey(keyId: LibomemoKeyId, keyPair: LibomemoKeyPair): void {
|
||||
this.#view.set("signed-prekey", normalizeKeyId(keyId), encodeKeyPair(keyPair));
|
||||
}
|
||||
|
||||
removeSignedPreKey(keyId: LibomemoKeyId): void {
|
||||
this.#view.delete("signed-prekey", normalizeKeyId(keyId));
|
||||
}
|
||||
|
||||
loadSession(address: string): string | undefined {
|
||||
validateDeviceAddress(address);
|
||||
const encoded = this.#view.get("session", address);
|
||||
if (!encoded) return undefined;
|
||||
if (encoded.byteLength > MAX_SESSION_BYTES) throw new Error("OMEMO session record exceeds the size limit.");
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(encoded);
|
||||
} catch {
|
||||
throw new Error("Corrupt OMEMO session record encoding.");
|
||||
}
|
||||
}
|
||||
|
||||
storeSession(address: string, record: string): void {
|
||||
validateDeviceAddress(address);
|
||||
if (typeof record !== "string" || record.length === 0) throw new Error("Invalid OMEMO session record.");
|
||||
const encoded = Buffer.from(record, "utf8");
|
||||
if (encoded.byteLength > MAX_SESSION_BYTES) throw new Error("OMEMO session record exceeds the size limit.");
|
||||
this.#view.set("session", address, encoded);
|
||||
}
|
||||
|
||||
removeSession(address: string): void {
|
||||
validateDeviceAddress(address);
|
||||
this.#view.delete("session", address);
|
||||
}
|
||||
|
||||
removeAllSessions(jid: string): void {
|
||||
validateAddress(jid);
|
||||
const prefix = `session\u0000${jid}.`;
|
||||
for (const [combined] of this.#view.entries()) {
|
||||
if (combined.startsWith(prefix)) this.#view.delete("session", combined.slice("session\u0000".length));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function formatIdentityFingerprint(identityKey: ArrayBuffer): string {
|
||||
const key = identityKeyBuffer(identityKey);
|
||||
const raw = key.byteLength === PUBLIC_KEY_BYTES ? key.subarray(1) : key;
|
||||
return raw.toString("hex").match(/.{8}/g)?.join(" ") ?? "";
|
||||
}
|
||||
|
||||
function encodeKeyPair(keyPair: LibomemoKeyPair): Buffer {
|
||||
const value = requireKeyPair(keyPair);
|
||||
const publicKey = Buffer.from(value.pubKey);
|
||||
const privateKey = Buffer.from(value.privKey);
|
||||
const encoded = Buffer.alloc(1 + PUBLIC_KEY_BYTES + PRIVATE_KEY_BYTES);
|
||||
encoded[0] = KEY_PAIR_VERSION;
|
||||
publicKey.copy(encoded, 1);
|
||||
privateKey.copy(encoded, 1 + PUBLIC_KEY_BYTES);
|
||||
return encoded;
|
||||
}
|
||||
|
||||
function decodeKeyPair(encoded: Uint8Array): LibomemoKeyPair {
|
||||
if (encoded.byteLength !== 1 + PUBLIC_KEY_BYTES + PRIVATE_KEY_BYTES || encoded[0] !== KEY_PAIR_VERSION) {
|
||||
throw new Error("Corrupt OMEMO key-pair record.");
|
||||
}
|
||||
const value = Buffer.from(encoded);
|
||||
const pubKey = value.subarray(1, 1 + PUBLIC_KEY_BYTES);
|
||||
const privKey = value.subarray(1 + PUBLIC_KEY_BYTES);
|
||||
return { pubKey: toArrayBuffer(pubKey), privKey: toArrayBuffer(privKey) };
|
||||
}
|
||||
|
||||
function requireKeyPair(value: unknown): LibomemoKeyPair {
|
||||
if (!value || typeof value !== "object") throw new Error("Invalid OMEMO key pair.");
|
||||
const candidate = value as Partial<LibomemoKeyPair>;
|
||||
if (!(candidate.pubKey instanceof ArrayBuffer) || candidate.pubKey.byteLength !== PUBLIC_KEY_BYTES) {
|
||||
throw new Error("Invalid OMEMO public key length.");
|
||||
}
|
||||
if (!(candidate.privKey instanceof ArrayBuffer) || candidate.privKey.byteLength !== PRIVATE_KEY_BYTES) {
|
||||
throw new Error("Invalid OMEMO private key length.");
|
||||
}
|
||||
if (new Uint8Array(candidate.pubKey)[0] !== 0x05) throw new Error("Invalid OMEMO public key prefix.");
|
||||
return candidate as LibomemoKeyPair;
|
||||
}
|
||||
|
||||
function identityKeyBuffer(value: ArrayBuffer): Buffer {
|
||||
if (!(value instanceof ArrayBuffer) || (value.byteLength !== 32 && value.byteLength !== PUBLIC_KEY_BYTES)) {
|
||||
throw new Error("Invalid OMEMO identity key length.");
|
||||
}
|
||||
const key = Buffer.from(value);
|
||||
if (key.byteLength === PUBLIC_KEY_BYTES && key[0] !== 0x05) {
|
||||
throw new Error("Invalid OMEMO identity key prefix.");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function encodeRegistrationId(value: unknown): Buffer {
|
||||
if (!Number.isInteger(value) || (value as number) < 0 || (value as number) > MAX_REGISTRATION_ID) {
|
||||
throw new Error("Invalid OMEMO registration ID.");
|
||||
}
|
||||
const encoded = Buffer.alloc(2);
|
||||
encoded.writeUInt16BE(value as number);
|
||||
return encoded;
|
||||
}
|
||||
|
||||
function decodeRegistrationId(encoded: Uint8Array): number {
|
||||
if (encoded.byteLength !== 2) throw new Error("Corrupt OMEMO registration ID record.");
|
||||
const value = Buffer.from(encoded).readUInt16BE(0);
|
||||
if (value > MAX_REGISTRATION_ID) throw new Error("Corrupt OMEMO registration ID record.");
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeKeyId(value: LibomemoKeyId): string {
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isSafeInteger(value) || value < 0) throw new Error("Invalid OMEMO key ID.");
|
||||
return String(value);
|
||||
}
|
||||
if (typeof value !== "string" || value.length === 0 || value.length > 1024 || value.includes("\u0000")) {
|
||||
throw new Error("Invalid OMEMO key ID.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function encodeTrustRecord(record: OmemoTrustRecord): Buffer {
|
||||
return Buffer.from(JSON.stringify({
|
||||
version: TRUST_RECORD_VERSION,
|
||||
state: record.state,
|
||||
fingerprint: record.fingerprint,
|
||||
firstObservedAt: record.firstObservedAt,
|
||||
lastObservedAt: record.lastObservedAt
|
||||
}), "utf8");
|
||||
}
|
||||
|
||||
function decodeTrustRecord(encoded: Uint8Array): OmemoTrustRecord {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(encoded));
|
||||
} catch {
|
||||
throw new Error("Corrupt OMEMO trust record encoding.");
|
||||
}
|
||||
if (!value || typeof value !== "object") throw new Error("Corrupt OMEMO trust record.");
|
||||
const record = value as Record<string, unknown>;
|
||||
validateTrustState(record.state);
|
||||
if (record.version !== TRUST_RECORD_VERSION || typeof record.fingerprint !== "string" ||
|
||||
!/^[0-9a-f]{8}( [0-9a-f]{8}){7}$/.test(record.fingerprint) ||
|
||||
!Number.isSafeInteger(record.firstObservedAt) || !Number.isSafeInteger(record.lastObservedAt) ||
|
||||
(record.firstObservedAt as number) < 0 || (record.lastObservedAt as number) < (record.firstObservedAt as number)) {
|
||||
throw new Error("Corrupt OMEMO trust record.");
|
||||
}
|
||||
return {
|
||||
state: record.state,
|
||||
fingerprint: record.fingerprint,
|
||||
firstObservedAt: record.firstObservedAt as number,
|
||||
lastObservedAt: record.lastObservedAt as number
|
||||
};
|
||||
}
|
||||
|
||||
function validateTrustState(value: unknown): asserts value is OmemoTrustState {
|
||||
if (value !== "undecided" && value !== "trusted" && value !== "verified" &&
|
||||
value !== "distrusted" && value !== "retired") {
|
||||
throw new Error("Invalid OMEMO trust state.");
|
||||
}
|
||||
}
|
||||
|
||||
function validateDirection(value: number): asserts value is LibomemoDirection {
|
||||
if (value !== 1 && value !== 2) throw new Error("Invalid OMEMO message direction.");
|
||||
}
|
||||
|
||||
function validateAddress(value: string): void {
|
||||
if (typeof value !== "string" || value.length === 0 || value.length > 1024 || value.includes("\u0000")) {
|
||||
throw new Error("Invalid OMEMO address.");
|
||||
}
|
||||
}
|
||||
|
||||
function validateDeviceAddress(value: string): void {
|
||||
validateAddress(value);
|
||||
const separator = value.lastIndexOf(".");
|
||||
const deviceId = value.slice(separator + 1);
|
||||
if (separator < 1 || !/^(0|[1-9]\d*)$/.test(deviceId) || !Number.isSafeInteger(Number(deviceId))) {
|
||||
throw new Error("Invalid libomemo.js device address.");
|
||||
}
|
||||
}
|
||||
|
||||
function validTimestamp(value: number): number {
|
||||
if (!Number.isSafeInteger(value) || value < 0) throw new Error("Invalid OMEMO observation timestamp.");
|
||||
return value;
|
||||
}
|
||||
|
||||
function equalBytes(left: Uint8Array, right: Uint8Array): boolean {
|
||||
const a = Buffer.from(left);
|
||||
const b = Buffer.from(right);
|
||||
return a.byteLength === b.byteLength && timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
function toArrayBuffer(value: Uint8Array): ArrayBuffer {
|
||||
return Uint8Array.from(value).buffer;
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
||||
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
import { parse as parseXml } from "ltx";
|
||||
|
||||
import { normalizeBareJid } from "../jid.js";
|
||||
import { LEGACY_OMEMO, OMEMO_2, type OmemoVersion } from "./engine.js";
|
||||
import { LibomemoStoreAdapter, type OmemoTrustMode } from "./libomemo-store.js";
|
||||
import { type OmemoRecordView, type OmemoTransactionalStore, type PendingInbound, type PendingOutbound } from "./store.js";
|
||||
|
||||
const HINTS = "urn:xmpp:hints";
|
||||
const STANZA_IDS = "urn:xmpp:sid:0";
|
||||
const SCE = "urn:xmpp:sce:1";
|
||||
const CLIENT = "jabber:client";
|
||||
const MAX_DEVICE_ID = 0x7fff_ffff;
|
||||
const MAX_KEYS = 2_000;
|
||||
const MAX_PAYLOAD = 16 * 1024 * 1024;
|
||||
|
||||
export interface OmemoEncryptedKey { rid: number; data: Uint8Array; keyExchange?: boolean }
|
||||
export interface OmemoEncryptedKeyGroup { jid?: string; keys: OmemoEncryptedKey[] }
|
||||
export interface OmemoEncryptedEnvelope {
|
||||
version: OmemoVersion;
|
||||
senderDeviceId: number;
|
||||
keyGroups: OmemoEncryptedKeyGroup[];
|
||||
iv?: Uint8Array;
|
||||
payload?: Uint8Array;
|
||||
}
|
||||
|
||||
export interface OmemoRecipientDevices { jid: string; deviceIds: readonly number[] }
|
||||
export interface OmemoSessionEncryptResult { body: string; type: number; kex?: boolean }
|
||||
export interface OmemoOutboundBindings {
|
||||
createSessionCipher(store: LibomemoStoreAdapter, address: string, version: OmemoVersion): {
|
||||
encrypt(plaintext: Uint8Array): Promise<OmemoSessionEncryptResult>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OmemoSessionDecryptResult { plaintext: ArrayBuffer; ratchet?: unknown }
|
||||
export interface OmemoInboundBindings {
|
||||
createSessionCipher(store: LibomemoStoreAdapter, address: string, version: OmemoVersion): {
|
||||
decryptWhisperMessage(ciphertext: Uint8Array, encoding: "binary"): Promise<OmemoSessionDecryptResult>;
|
||||
decryptPreKeyWhisperMessage(ciphertext: Uint8Array, encoding: "binary"): Promise<OmemoSessionDecryptResult>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OmemoInboundMessage {
|
||||
id: string;
|
||||
from: string;
|
||||
text: string;
|
||||
version: OmemoVersion;
|
||||
senderDeviceId: number;
|
||||
}
|
||||
|
||||
export interface OmemoInboundCoordinatorOptions {
|
||||
account: string;
|
||||
localDeviceId: number;
|
||||
store: OmemoTransactionalStore;
|
||||
bindings: OmemoInboundBindings;
|
||||
trustMode: OmemoTrustMode;
|
||||
refreshBundle?(version: OmemoVersion): Promise<void>;
|
||||
}
|
||||
|
||||
/** Decrypts and commits the ratchet with a sealed delivery before dispatch. */
|
||||
export class OmemoInboundCoordinator {
|
||||
readonly #account: string;
|
||||
readonly #localDeviceId: number;
|
||||
readonly #store: OmemoTransactionalStore;
|
||||
readonly #bindings: OmemoInboundBindings;
|
||||
readonly #trustMode: OmemoTrustMode;
|
||||
readonly #refreshBundle: ((version: OmemoVersion) => Promise<void>) | undefined;
|
||||
|
||||
constructor(options: OmemoInboundCoordinatorOptions) {
|
||||
this.#account = bare(options.account, "account");
|
||||
this.#localDeviceId = deviceId(options.localDeviceId);
|
||||
this.#store = options.store;
|
||||
this.#bindings = options.bindings;
|
||||
this.#trustMode = options.trustMode;
|
||||
this.#refreshBundle = options.refreshBundle;
|
||||
}
|
||||
|
||||
async decryptAndDispatch(stanza: Element, dispatch: (message: OmemoInboundMessage) => Promise<void>): Promise<OmemoInboundMessage | undefined> {
|
||||
if (!stanza.is("message")) return undefined;
|
||||
const type = stanza.attrs.type ?? "normal";
|
||||
if (type === "error") return undefined;
|
||||
if (type === "groupchat" || type === "headline" || (type !== "chat" && type !== "normal")) {
|
||||
throw new Error("Unsupported OMEMO message type.");
|
||||
}
|
||||
requireMessageAttrs(stanza);
|
||||
const from = bareJidFrom(stanza.attrs.from);
|
||||
const encrypted = encryptedChild(stanza);
|
||||
if (!encrypted) return undefined;
|
||||
const id = inboundStanzaId(stanza, from, encrypted);
|
||||
const version = encrypted.getNS() as OmemoVersion;
|
||||
const envelope = parseEncryptedEnvelope(version, encrypted);
|
||||
const wrapped = recipientKey(envelope, version, this.#account, this.#localDeviceId);
|
||||
const address = `${from}.${envelope.senderDeviceId}`;
|
||||
const pending = await this.#store.inbound(this.#account, id, from, async (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: this.#trustMode });
|
||||
const cipher = this.#bindings.createSessionCipher(adapter, address, version);
|
||||
const result = wrapped.keyExchange
|
||||
? await cipher.decryptPreKeyWhisperMessage(wrapped.data, "binary")
|
||||
: await cipher.decryptWhisperMessage(wrapped.data, "binary");
|
||||
const material = arrayBuffer(result.plaintext, "decrypted key material");
|
||||
if (!envelope.payload) return new Uint8Array();
|
||||
return version === LEGACY_OMEMO
|
||||
? decryptLegacyPayload(envelope.payload!, envelope.iv!, material)
|
||||
: decryptOmemo2Payload(envelope.payload!, material, from);
|
||||
});
|
||||
if (!envelope.payload) {
|
||||
if (wrapped.keyExchange) await this.#refreshBundle?.(version);
|
||||
this.#store.acknowledgeInbound(this.#account, id);
|
||||
return undefined;
|
||||
}
|
||||
const text = decodePlaintext(pending.plaintext);
|
||||
const message = { id, from, text, version, senderDeviceId: envelope.senderDeviceId };
|
||||
if (wrapped.keyExchange) await this.#refreshBundle?.(version);
|
||||
await dispatch(message);
|
||||
this.#store.acknowledgeInbound(this.#account, id);
|
||||
return message;
|
||||
}
|
||||
|
||||
async dispatchPending(dispatch: (message: Pick<OmemoInboundMessage, "id" | "from" | "text">) => Promise<void>): Promise<number> {
|
||||
const pending = this.#store.listInbound(this.#account);
|
||||
for (const item of pending) {
|
||||
if (item.plaintext.byteLength === 0) {
|
||||
this.#store.acknowledgeInbound(this.#account, item.id);
|
||||
continue;
|
||||
}
|
||||
await dispatch({ id: item.id, from: item.sender, text: decodePlaintext(item.plaintext) });
|
||||
this.#store.acknowledgeInbound(this.#account, item.id);
|
||||
}
|
||||
return pending.length;
|
||||
}
|
||||
}
|
||||
|
||||
export interface OmemoOutboundCoordinatorOptions {
|
||||
account: string;
|
||||
localDeviceId: number;
|
||||
store: OmemoTransactionalStore;
|
||||
bindings: OmemoOutboundBindings;
|
||||
trustMode: OmemoTrustMode;
|
||||
requireTrustedTargets?: boolean;
|
||||
random?: (length: number) => Uint8Array;
|
||||
id?: () => string;
|
||||
}
|
||||
|
||||
/** Atomic ratchet/ciphertext boundary. This class does not build or trust sessions. */
|
||||
export class OmemoOutboundCoordinator {
|
||||
readonly #account: string;
|
||||
readonly #localDeviceId: number;
|
||||
readonly #store: OmemoTransactionalStore;
|
||||
readonly #bindings: OmemoOutboundBindings;
|
||||
readonly #trustMode: OmemoTrustMode;
|
||||
readonly #requireTrustedTargets: boolean;
|
||||
readonly #random: (length: number) => Uint8Array;
|
||||
readonly #id: () => string;
|
||||
|
||||
constructor(options: OmemoOutboundCoordinatorOptions) {
|
||||
this.#account = bare(options.account, "account");
|
||||
this.#localDeviceId = deviceId(options.localDeviceId);
|
||||
this.#store = options.store;
|
||||
this.#bindings = options.bindings;
|
||||
this.#trustMode = options.trustMode;
|
||||
this.#requireTrustedTargets = options.requireTrustedTargets ?? false;
|
||||
this.#random = options.random ?? ((length) => randomBytes(length));
|
||||
this.#id = options.id ?? randomUUID;
|
||||
}
|
||||
|
||||
async encryptAndSend(input: {
|
||||
to: string;
|
||||
text: string;
|
||||
version: OmemoVersion;
|
||||
recipients: readonly OmemoRecipientDevices[];
|
||||
send(stanza: Element): Promise<void>;
|
||||
}): Promise<{ id: string; pending: PendingOutbound }> {
|
||||
const to = bare(input.to, "recipient");
|
||||
if (!input.text) throw new Error("OMEMO plaintext must not be empty.");
|
||||
const targets = planTargets(input.version, input.recipients, this.#account, this.#localDeviceId);
|
||||
if (!targets.some((target) => target.jid === to)) throw new Error("OMEMO recipient has no target devices.");
|
||||
const id = this.#id();
|
||||
if (!id || id.length > 1024) throw new Error("Invalid OMEMO stanza ID.");
|
||||
const pending = await this.#store.outbound(this.#account, id, to, async (view) => {
|
||||
const envelope = await this.#encryptEnvelope(input.version, input.text, targets, view);
|
||||
const stanza = xml("message", { to, type: "chat", id }, serializeEncryptedEnvelope(envelope), xml("store", { xmlns: HINTS }));
|
||||
return new TextEncoder().encode(stanza.toString());
|
||||
});
|
||||
const stanza = parseCommittedStanza(pending.stanza);
|
||||
await input.send(stanza);
|
||||
this.#store.acknowledgeOutbound(this.#account, id);
|
||||
return { id, pending };
|
||||
}
|
||||
|
||||
async #encryptEnvelope(version: OmemoVersion, text: string, targets: PlannedTarget[], view: OmemoRecordView): Promise<OmemoEncryptedEnvelope> {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: this.#trustMode });
|
||||
const content = version === LEGACY_OMEMO
|
||||
? encryptLegacy(new TextEncoder().encode(text), this.#secureRandom(16), this.#secureRandom(12))
|
||||
: encryptOmemo2(sceEnvelope(text, this.#account), this.#secureRandom(32));
|
||||
const groups = new Map<string, OmemoEncryptedKey[]>();
|
||||
for (const target of targets) {
|
||||
const address = `${target.jid}.${target.deviceId}`;
|
||||
if (this.#requireTrustedTargets) {
|
||||
const identity = adapter.loadIdentityKey(address);
|
||||
if (!identity) throw new Error("OMEMO target identity disappeared.");
|
||||
adapter.trust.assertTrusted(address, identity, 1);
|
||||
}
|
||||
const cipher = this.#bindings.createSessionCipher(adapter, address, version);
|
||||
const encrypted = await cipher.encrypt(content.keyMaterial);
|
||||
const data = binaryString(encrypted.body);
|
||||
if (data.byteLength === 0) throw new Error("OMEMO session produced an empty encrypted key.");
|
||||
const keys = groups.get(target.jid) ?? [];
|
||||
keys.push({ rid: target.deviceId, data, ...(isKeyExchange(version, encrypted) ? { keyExchange: true } : {}) });
|
||||
groups.set(target.jid, keys);
|
||||
}
|
||||
const envelope: OmemoEncryptedEnvelope = {
|
||||
version,
|
||||
senderDeviceId: this.#localDeviceId,
|
||||
keyGroups: [...groups].map(([jid, keys]) => ({ ...(version === OMEMO_2 ? { jid } : {}), keys })),
|
||||
payload: content.payload
|
||||
};
|
||||
if (version === LEGACY_OMEMO) envelope.iv = (content as ReturnType<typeof encryptLegacy>).iv;
|
||||
return envelope;
|
||||
}
|
||||
|
||||
#secureRandom(length: number): Uint8Array {
|
||||
const value = this.#random(length);
|
||||
if (!(value instanceof Uint8Array) || value.byteLength !== length) throw new Error("Invalid OMEMO random source output.");
|
||||
return Uint8Array.from(value);
|
||||
}
|
||||
}
|
||||
|
||||
export function serializeEncryptedEnvelope(value: OmemoEncryptedEnvelope): Element {
|
||||
validateVersion(value.version);
|
||||
const sid = deviceId(value.senderDeviceId);
|
||||
const count = value.keyGroups.reduce((sum, group) => sum + group.keys.length, 0);
|
||||
if (count < 1 || count > MAX_KEYS) throw new Error("Invalid OMEMO encrypted-key count.");
|
||||
const seen = new Set<string>();
|
||||
if (value.version === LEGACY_OMEMO) {
|
||||
if (value.iv?.byteLength !== 12) throw new Error("Legacy OMEMO requires a 12-byte IV.");
|
||||
const keys = value.keyGroups.flatMap((group) => group.keys).map((key) => keyElement(value.version, key, seen, ""));
|
||||
return xml("encrypted", { xmlns: value.version },
|
||||
xml("header", { sid: String(sid) }, ...keys, xml("iv", {}, base64(value.iv))),
|
||||
...(value.payload ? [xml("payload", {}, payload(value.payload))] : []));
|
||||
}
|
||||
if (value.iv !== undefined) throw new Error("OMEMO 2 does not carry an XML IV.");
|
||||
const groups = value.keyGroups.map((group) => {
|
||||
const jid = bare(group.jid ?? "", "key-group JID");
|
||||
if (group.keys.length === 0) throw new Error("OMEMO 2 key group must not be empty.");
|
||||
return xml("keys", { jid }, ...group.keys.map((key) => keyElement(value.version, key, seen, jid)));
|
||||
});
|
||||
return xml("encrypted", { xmlns: value.version }, xml("header", { sid: String(sid) }, ...groups),
|
||||
...(value.payload ? [xml("payload", {}, payload(value.payload))] : []));
|
||||
}
|
||||
|
||||
export function parseEncryptedEnvelope(version: OmemoVersion, element: Element): OmemoEncryptedEnvelope {
|
||||
validateVersion(version);
|
||||
if (!element.is("encrypted", version) || Object.keys(element.attrs).some((key) => key !== "xmlns")) throw new Error("Invalid OMEMO encrypted element.");
|
||||
const children = element.getChildElements();
|
||||
const headers = children.filter((child) => child.is("header", version));
|
||||
const payloads = children.filter((child) => child.is("payload", version));
|
||||
if (headers.length !== 1 || payloads.length > 1 || children.length !== 1 + payloads.length) throw new Error("Malformed OMEMO encrypted structure.");
|
||||
const header = headers[0]!;
|
||||
requireAttrs(header, ["sid"]);
|
||||
const senderDeviceId = integerString(header.attrs.sid, "sender device ID");
|
||||
const seen = new Set<string>();
|
||||
let keyGroups: OmemoEncryptedKeyGroup[];
|
||||
let iv: Uint8Array | undefined;
|
||||
if (version === LEGACY_OMEMO) {
|
||||
const ivs = header.getChildren("iv", version);
|
||||
const keys = header.getChildren("key", version);
|
||||
if (ivs.length !== 1 || keys.length < 1 || header.getChildElements().length !== keys.length + 1) throw new Error("Malformed legacy OMEMO header.");
|
||||
iv = decodeElement(ivs[0]!, 12, 12, "IV");
|
||||
keyGroups = [{ keys: keys.map((key) => parseKey(version, key, seen, "")) }];
|
||||
} else {
|
||||
const groups = header.getChildren("keys", version);
|
||||
if (groups.length < 1 || groups.length !== header.getChildElements().length) throw new Error("Malformed OMEMO 2 header.");
|
||||
keyGroups = groups.map((group) => {
|
||||
requireAttrs(group, ["jid"]);
|
||||
const jid = bare(group.attrs.jid ?? "", "key-group JID");
|
||||
const keys = group.getChildren("key", version);
|
||||
if (keys.length < 1 || keys.length !== group.getChildElements().length) throw new Error("Malformed OMEMO 2 key group.");
|
||||
return { jid, keys: keys.map((key) => parseKey(version, key, seen, jid)) };
|
||||
});
|
||||
}
|
||||
if (seen.size > MAX_KEYS) throw new Error("OMEMO encrypted-key count exceeds limit.");
|
||||
const encryptedPayload = payloads[0] ? decodeElement(payloads[0], 1, MAX_PAYLOAD, "payload") : undefined;
|
||||
return { version, senderDeviceId, keyGroups, ...(iv ? { iv } : {}), ...(encryptedPayload ? { payload: encryptedPayload } : {}) };
|
||||
}
|
||||
|
||||
interface PlannedTarget { jid: string; deviceId: number }
|
||||
function planTargets(version: OmemoVersion, recipients: readonly OmemoRecipientDevices[], account: string, ownId: number): PlannedTarget[] {
|
||||
validateVersion(version);
|
||||
if (recipients.length === 0) throw new Error("OMEMO has no recipient device lists.");
|
||||
const result: PlannedTarget[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const recipient of recipients) {
|
||||
const jid = bare(recipient.jid, "recipient device-list JID");
|
||||
for (const rawId of recipient.deviceIds) {
|
||||
const id = deviceId(rawId);
|
||||
if (jid === account && id === ownId) continue;
|
||||
const address = `${jid}.${id}`;
|
||||
if (seen.has(address)) throw new Error("OMEMO target device is duplicated.");
|
||||
seen.add(address);
|
||||
result.push({ jid, deviceId: id });
|
||||
}
|
||||
}
|
||||
if (result.length === 0 || result.length > MAX_KEYS) throw new Error("Invalid OMEMO target-device count.");
|
||||
return result.sort((a, b) => a.jid.localeCompare(b.jid) || a.deviceId - b.deviceId);
|
||||
}
|
||||
|
||||
function encryptLegacy(plaintext: Uint8Array, key: Uint8Array, iv: Uint8Array): { keyMaterial: Uint8Array; payload: Uint8Array; iv: Uint8Array } {
|
||||
const cipher = createCipheriv("aes-128-gcm", key, iv, { authTagLength: 16 });
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
||||
return { keyMaterial: Buffer.concat([key, cipher.getAuthTag()]), payload: ciphertext, iv };
|
||||
}
|
||||
function encryptOmemo2(plaintext: Uint8Array, key: Uint8Array): { keyMaterial: Uint8Array; payload: Uint8Array } {
|
||||
const derived = Buffer.from(hkdfSync("sha256", key, Buffer.alloc(32), "OMEMO Payload", 80));
|
||||
const cipher = createCipheriv("aes-256-cbc", derived.subarray(0, 32), derived.subarray(64, 80));
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
||||
const mac = createHmac("sha256", derived.subarray(32, 64)).update(ciphertext).digest().subarray(0, 16);
|
||||
return { keyMaterial: Buffer.concat([key, mac]), payload: ciphertext };
|
||||
}
|
||||
function decryptLegacyPayload(payloadBytes: Uint8Array, iv: Uint8Array, material: Uint8Array): Uint8Array {
|
||||
if (material.byteLength !== 32) throw new Error("Invalid legacy OMEMO key material.");
|
||||
const decipher = createDecipheriv("aes-128-gcm", material.subarray(0, 16), iv, { authTagLength: 16 });
|
||||
decipher.setAuthTag(material.subarray(16));
|
||||
try { return Buffer.concat([decipher.update(payloadBytes), decipher.final()]); }
|
||||
catch { throw new Error("Legacy OMEMO payload authentication failed."); }
|
||||
}
|
||||
function decryptOmemo2Payload(payloadBytes: Uint8Array, material: Uint8Array, sender: string): Uint8Array {
|
||||
if (material.byteLength !== 48) throw new Error("Invalid OMEMO 2 key material.");
|
||||
const key = material.subarray(0, 32);
|
||||
const derived = Buffer.from(hkdfSync("sha256", key, Buffer.alloc(32), "OMEMO Payload", 80));
|
||||
const mac = createHmac("sha256", derived.subarray(32, 64)).update(payloadBytes).digest().subarray(0, 16);
|
||||
if (!timingSafeEqual(mac, material.subarray(32))) throw new Error("OMEMO 2 payload authentication failed.");
|
||||
try {
|
||||
const decipher = createDecipheriv("aes-256-cbc", derived.subarray(0, 32), derived.subarray(64, 80));
|
||||
return parseSce(Buffer.concat([decipher.update(payloadBytes), decipher.final()]), sender);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.startsWith("Invalid OMEMO 2 SCE")) throw error;
|
||||
throw new Error("OMEMO 2 payload decryption failed.");
|
||||
}
|
||||
}
|
||||
function parseSce(encoded: Uint8Array, sender: string): Uint8Array {
|
||||
let root: Element;
|
||||
try { root = parseXml(new TextDecoder("utf-8", { fatal: true }).decode(encoded)); }
|
||||
catch { throw new Error("Invalid OMEMO 2 SCE encoding."); }
|
||||
if (!root.is("envelope", SCE) || Object.keys(root.attrs).some((key) => key !== "xmlns")) throw new Error("Invalid OMEMO 2 SCE envelope.");
|
||||
const children = root.getChildElements();
|
||||
if (children.length !== 3 || !children[0]?.is("content", SCE) || !children[1]?.is("rpad", SCE) || !children[2]?.is("from", SCE)) throw new Error("Invalid OMEMO 2 SCE structure.");
|
||||
const [content, rpad, from] = children as [Element, Element, Element];
|
||||
requireAttrs(content, []); requireAttrs(rpad, []); requireAttrs(from, ["jid"]);
|
||||
if (bare(from.attrs.jid ?? "", "SCE sender") !== sender) throw new Error("Invalid OMEMO 2 SCE sender binding.");
|
||||
decodeElement(rpad, 1, 4096, "SCE random padding");
|
||||
const bodies = content.getChildren("body", CLIENT);
|
||||
if (bodies.length !== 1 || content.getChildElements().length !== 1) throw new Error("Invalid OMEMO 2 SCE content.");
|
||||
const body = bodies[0]!;
|
||||
requireAttrs(body, ["xmlns"]);
|
||||
if (body.getChildElements().length !== 0) throw new Error("Invalid OMEMO 2 SCE body.");
|
||||
return new TextEncoder().encode(body.getText());
|
||||
}
|
||||
function sceEnvelope(text: string, from: string): Uint8Array {
|
||||
const element = xml("envelope", { xmlns: SCE }, xml("content", {}, xml("body", { xmlns: CLIENT }, text)),
|
||||
xml("rpad", {}, base64(randomBytes(16))), xml("from", { jid: from }));
|
||||
return new TextEncoder().encode(element.toString());
|
||||
}
|
||||
function keyElement(version: OmemoVersion, key: OmemoEncryptedKey, seen: Set<string>, jid: string): Element {
|
||||
const rid = deviceId(key.rid);
|
||||
const identity = `${jid}\u0000${rid}`;
|
||||
if (seen.has(identity)) throw new Error("OMEMO encrypted key contains a duplicate recipient.");
|
||||
seen.add(identity);
|
||||
if (!(key.data instanceof Uint8Array) || key.data.byteLength === 0 || key.data.byteLength > MAX_PAYLOAD) throw new Error("Invalid OMEMO encrypted key.");
|
||||
const attrs: Record<string, string> = { rid: String(rid) };
|
||||
if (key.keyExchange) attrs[version === LEGACY_OMEMO ? "prekey" : "kex"] = "true";
|
||||
return xml("key", attrs, base64(key.data));
|
||||
}
|
||||
function parseKey(version: OmemoVersion, element: Element, seen: Set<string>, jid: string): OmemoEncryptedKey {
|
||||
requireAttrs(element, version === LEGACY_OMEMO ? ["rid", "prekey"] : ["rid", "kex"]);
|
||||
const rid = integerString(element.attrs.rid, "recipient device ID");
|
||||
const flag = element.attrs[version === LEGACY_OMEMO ? "prekey" : "kex"];
|
||||
if (flag !== undefined && flag !== "true") throw new Error("Invalid OMEMO key-exchange flag.");
|
||||
const identity = `${jid}\u0000${rid}`;
|
||||
if (seen.has(identity)) throw new Error("OMEMO encrypted key contains a duplicate recipient.");
|
||||
seen.add(identity);
|
||||
return { rid, data: decodeElement(element, 1, MAX_PAYLOAD, "encrypted key"), ...(flag === "true" ? { keyExchange: true } : {}) };
|
||||
}
|
||||
function isKeyExchange(version: OmemoVersion, result: OmemoSessionEncryptResult): boolean {
|
||||
return version === OMEMO_2 ? result.kex === true : result.type === 3;
|
||||
}
|
||||
function binaryString(value: string): Uint8Array {
|
||||
if (typeof value !== "string") throw new Error("OMEMO session returned an invalid encrypted key.");
|
||||
return Uint8Array.from(value, (character) => character.charCodeAt(0) & 0xff);
|
||||
}
|
||||
function arrayBuffer(value: unknown, name: string): Uint8Array {
|
||||
if (!(value instanceof ArrayBuffer) || value.byteLength === 0 || value.byteLength > MAX_PAYLOAD) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return new Uint8Array(value);
|
||||
}
|
||||
function encryptedChild(stanza: Element): Element | undefined {
|
||||
const children = stanza.getChildElements().filter((child) => child.is("encrypted", LEGACY_OMEMO) || child.is("encrypted", OMEMO_2));
|
||||
if (children.length > 1) throw new Error("OMEMO message contains multiple encrypted payloads.");
|
||||
return children[0];
|
||||
}
|
||||
function inboundStanzaId(stanza: Element, from: string, encrypted: Element): string {
|
||||
const stanzaId = stanza.getChildren("stanza-id", STANZA_IDS)
|
||||
.map((element) => element.attrs.id)
|
||||
.find((value) => typeof value === "string" && value.length > 0);
|
||||
const originId = stanza.getChild("origin-id", STANZA_IDS)?.attrs.id;
|
||||
const candidate = stanzaId ?? originId ?? stanza.attrs.id;
|
||||
if (candidate !== undefined && candidate !== "") return requiredToken(candidate, "stanza ID");
|
||||
return `sha256:${createHash("sha256").update(from).update("\0").update(encrypted.toString()).digest("hex")}`;
|
||||
}
|
||||
function recipientKey(envelope: OmemoEncryptedEnvelope, version: OmemoVersion, account: string, localId: number): OmemoEncryptedKey {
|
||||
const groups = version === LEGACY_OMEMO ? envelope.keyGroups : envelope.keyGroups.filter((group) => group.jid === account);
|
||||
const keys = groups.flatMap((group) => group.keys).filter((key) => key.rid === localId);
|
||||
if (keys.length !== 1) throw new Error("OMEMO message does not contain exactly one key for this device.");
|
||||
return keys[0]!;
|
||||
}
|
||||
function requiredToken(value: unknown, name: string): string {
|
||||
if (typeof value !== "string" || value.length < 1 || value.length > 1024 || /[\u0000-\u001f\u007f]/.test(value)) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return value;
|
||||
}
|
||||
function bareJidFrom(value: unknown): string {
|
||||
if (typeof value !== "string") throw new Error("Invalid OMEMO sender.");
|
||||
return bare(value.split("/", 1)[0] ?? "", "sender");
|
||||
}
|
||||
function requireMessageAttrs(stanza: Element): void {
|
||||
if (Object.keys(stanza.attrs).some((key) => !["from", "to", "type", "id", "xmlns", "xml:lang"].includes(key))) throw new Error("Unexpected OMEMO message attribute.");
|
||||
if (stanza.attrs["xml:lang"] !== undefined) requiredToken(stanza.attrs["xml:lang"], "message language");
|
||||
}
|
||||
function decodePlaintext(value: Uint8Array): string {
|
||||
try {
|
||||
const text = new TextDecoder("utf-8", { fatal: true }).decode(value);
|
||||
if (!text) throw new Error();
|
||||
return text;
|
||||
} catch { throw new Error("Invalid OMEMO plaintext encoding."); }
|
||||
}
|
||||
function parseCommittedStanza(stanza: Uint8Array): Element {
|
||||
// The exact bytes are already durable. Parsing solely reconstructs the Element
|
||||
// required by @xmpp/client without regenerating or modifying the ciphertext.
|
||||
const text = new TextDecoder("utf-8", { fatal: true }).decode(stanza);
|
||||
const element = parseXml(text);
|
||||
if (element.toString() !== text) throw new Error("Committed OMEMO stanza could not be reconstructed exactly.");
|
||||
return element;
|
||||
}
|
||||
function decodeElement(element: Element, min: number, max: number, name: string): Uint8Array {
|
||||
if (element.getChildElements().length !== 0 || element.children.some((child) => typeof child !== "string" && typeof child !== "number")) throw new Error(`Invalid OMEMO ${name} content.`);
|
||||
const raw = element.getText().replace(/[\t\n\r ]/g, "");
|
||||
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(raw)) throw new Error(`Invalid OMEMO ${name} base64.`);
|
||||
const value = Buffer.from(raw, "base64");
|
||||
if (value.toString("base64") !== raw || value.byteLength < min || value.byteLength > max) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return Uint8Array.from(value);
|
||||
}
|
||||
function payload(value: Uint8Array): string {
|
||||
if (!(value instanceof Uint8Array) || value.byteLength < 1 || value.byteLength > MAX_PAYLOAD) throw new Error("Invalid OMEMO payload.");
|
||||
return base64(value);
|
||||
}
|
||||
function base64(value: Uint8Array): string { return Buffer.from(value).toString("base64"); }
|
||||
function requireAttrs(element: Element, allowed: string[]): void {
|
||||
if (Object.keys(element.attrs).some((key) => !allowed.includes(key))) throw new Error("Unexpected OMEMO encrypted XML attribute.");
|
||||
}
|
||||
function bare(value: string, name: string): string {
|
||||
const normalized = normalizeBareJid(value);
|
||||
if (!normalized || normalized !== value || value.includes("/")) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return normalized;
|
||||
}
|
||||
function deviceId(value: number): number {
|
||||
if (!Number.isSafeInteger(value) || value < 1 || value > MAX_DEVICE_ID) throw new Error("Invalid OMEMO device ID.");
|
||||
return value;
|
||||
}
|
||||
function integerString(value: unknown, name: string): number {
|
||||
if (typeof value !== "string" || !/^[1-9][0-9]*$/.test(value)) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return deviceId(Number(value));
|
||||
}
|
||||
function validateVersion(value: string): asserts value is OmemoVersion {
|
||||
if (value !== LEGACY_OMEMO && value !== OMEMO_2) throw new Error("Unsupported OMEMO version.");
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
LibomemoStoreAdapter,
|
||||
type OmemoExpectedTrust,
|
||||
type OmemoIdentityCandidate,
|
||||
type OmemoTrustMode,
|
||||
type OmemoTrustRecord,
|
||||
type OmemoTrustState
|
||||
} from "./libomemo-store.js";
|
||||
import type { OmemoTransactionalStore } from "./store.js";
|
||||
|
||||
export interface OmemoTrustInspection extends OmemoTrustRecord {
|
||||
address: string;
|
||||
candidate?: Omit<OmemoIdentityCandidate, "identityKey">;
|
||||
}
|
||||
|
||||
export class OmemoOperator {
|
||||
constructor(
|
||||
readonly account: string,
|
||||
readonly store: OmemoTransactionalStore,
|
||||
readonly trustMode: OmemoTrustMode
|
||||
) {}
|
||||
|
||||
async inspectTrust(): Promise<OmemoTrustInspection[]> {
|
||||
return await this.store.updateRecords(this.account, (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: this.trustMode });
|
||||
const addresses = [...view.entries()]
|
||||
.filter(([key]) => key.startsWith("trust\u0000"))
|
||||
.map(([key]) => key.slice("trust\u0000".length))
|
||||
.sort();
|
||||
return addresses.map((address) => {
|
||||
const trust = adapter.trust.get(address);
|
||||
if (!trust) throw new Error("Corrupt OMEMO trust index.");
|
||||
const candidate = adapter.trust.candidate(address);
|
||||
return {
|
||||
address,
|
||||
...trust,
|
||||
...(candidate ? { candidate: {
|
||||
previousFingerprint: candidate.previousFingerprint,
|
||||
observedFingerprint: candidate.observedFingerprint,
|
||||
observedAt: candidate.observedAt
|
||||
} } : {})
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async transition(address: string, expected: OmemoExpectedTrust, nextState: OmemoTrustState): Promise<OmemoTrustRecord> {
|
||||
return await this.store.updateRecords(this.account, (view) =>
|
||||
new LibomemoStoreAdapter(view, { mode: this.trustMode }).trust.transition(address, expected, nextState));
|
||||
}
|
||||
|
||||
async replaceIdentity(
|
||||
address: string,
|
||||
expected: OmemoExpectedTrust,
|
||||
expectedObservedFingerprint: string,
|
||||
nextState: OmemoTrustState = "undecided"
|
||||
): Promise<OmemoTrustRecord> {
|
||||
return await this.store.updateRecords(this.account, (view) => {
|
||||
const trust = new LibomemoStoreAdapter(view, { mode: this.trustMode }).trust;
|
||||
const candidate = trust.candidate(address);
|
||||
if (!candidate || candidate.previousFingerprint !== expected.fingerprint ||
|
||||
candidate.observedFingerprint !== expectedObservedFingerprint) {
|
||||
throw new Error("OMEMO identity candidate changed since it was reviewed.");
|
||||
}
|
||||
return trust.replaceIdentity(
|
||||
address, expected, candidate.identityKey, expectedObservedFingerprint, nextState
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { Element } from "@xmpp/xml";
|
||||
|
||||
import type { OmemoPublishedBundle, OmemoVersion } from "./engine.js";
|
||||
import { parseDeviceList, serializeBundle, serializeDeviceList, type OmemoDevice } from "./xml.js";
|
||||
|
||||
export class OmemoPepConflictError extends Error {
|
||||
readonly code = "OMEMO_PEP_CONFLICT";
|
||||
constructor() { super("OMEMO PEP item changed during publication."); }
|
||||
}
|
||||
|
||||
export interface OmemoPepItem { payload?: Element; revision?: string }
|
||||
export interface OmemoPepAdapter {
|
||||
fetchDeviceList(version: OmemoVersion): Promise<OmemoPepItem | undefined>;
|
||||
publishDeviceList(version: OmemoVersion, payload: Element, expectedRevision?: string): Promise<void>;
|
||||
fetchBundle(version: OmemoVersion, deviceId: number): Promise<OmemoPepItem | undefined>;
|
||||
publishBundle(version: OmemoVersion, deviceId: number, payload: Element, expectedRevision?: string): Promise<void>;
|
||||
retractBundle(version: OmemoVersion, deviceId: number, expectedRevision?: string): Promise<void>;
|
||||
}
|
||||
|
||||
export interface OmemoPepPublisherOptions { adapter: OmemoPepAdapter; maxAttempts?: number }
|
||||
|
||||
/** Conflict-aware, transport-independent PEP publication policy. */
|
||||
export class OmemoPepPublisher {
|
||||
readonly #adapter: OmemoPepAdapter;
|
||||
readonly #maxAttempts: number;
|
||||
constructor(options: OmemoPepPublisherOptions) {
|
||||
this.#adapter = options.adapter;
|
||||
this.#maxAttempts = options.maxAttempts ?? 3;
|
||||
if (!Number.isSafeInteger(this.#maxAttempts) || this.#maxAttempts < 1 || this.#maxAttempts > 10) {
|
||||
throw new Error("Invalid OMEMO PEP publication attempt limit.");
|
||||
}
|
||||
}
|
||||
|
||||
async publish(bundle: OmemoPublishedBundle, device?: Omit<OmemoDevice, "id">): Promise<void> {
|
||||
const canonicalBundle = serializeBundle(bundle);
|
||||
await this.#retry(async () => {
|
||||
const current = await this.#adapter.fetchBundle(bundle.version, bundle.deviceId);
|
||||
if (current?.payload && current.payload.toString() === canonicalBundle.toString()) return;
|
||||
await this.#adapter.publishBundle(bundle.version, bundle.deviceId, canonicalBundle, current?.revision);
|
||||
});
|
||||
await this.#retry(async () => {
|
||||
const current = await this.#adapter.fetchDeviceList(bundle.version);
|
||||
const devices = current?.payload ? parseDeviceList(bundle.version, current.payload) : [];
|
||||
const merged = mergeDevice(devices, { id: bundle.deviceId, ...device });
|
||||
const payload = serializeDeviceList(bundle.version, merged);
|
||||
if (current?.payload && current.payload.toString() === payload.toString()) return;
|
||||
await this.#adapter.publishDeviceList(bundle.version, payload, current?.revision);
|
||||
});
|
||||
}
|
||||
|
||||
/** Remove the local advertisement before retracting its now-unreachable bundle. */
|
||||
async retire(version: OmemoVersion, deviceId: number): Promise<void> {
|
||||
await this.#retry(async () => {
|
||||
const current = await this.#adapter.fetchDeviceList(version);
|
||||
const devices = current?.payload ? parseDeviceList(version, current.payload) : [];
|
||||
const retained = devices.filter((device) => device.id !== deviceId);
|
||||
if (retained.length === devices.length) return;
|
||||
await this.#adapter.publishDeviceList(
|
||||
version, serializeDeviceList(version, retained), current?.revision
|
||||
);
|
||||
});
|
||||
await this.#retry(async () => {
|
||||
const current = await this.#adapter.fetchBundle(version, deviceId);
|
||||
if (!current) return;
|
||||
await this.#adapter.retractBundle(version, deviceId, current.revision);
|
||||
});
|
||||
}
|
||||
|
||||
async #retry(operation: () => Promise<void>): Promise<void> {
|
||||
for (let attempt = 1; attempt <= this.#maxAttempts; attempt++) {
|
||||
try { await operation(); return; }
|
||||
catch (error) {
|
||||
if (!(error instanceof OmemoPepConflictError) || attempt === this.#maxAttempts) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function mergeDevice(devices: OmemoDevice[], own: OmemoDevice): OmemoDevice[] {
|
||||
const merged = devices.filter((device) => device.id !== own.id);
|
||||
merged.push(own);
|
||||
return merged;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { OmemoExpectedTrust } from "./libomemo-store.js";
|
||||
import type { OmemoTrustInspection } from "./operator.js";
|
||||
|
||||
interface Ticket {
|
||||
owner: string;
|
||||
address: string;
|
||||
expected: OmemoExpectedTrust;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
/** Session-local approval capabilities. Restart invalidates all outstanding codes. */
|
||||
export class OmemoReviewTickets {
|
||||
readonly #tickets = new Map<string, Ticket>();
|
||||
constructor(readonly clock: () => number = Date.now) {}
|
||||
|
||||
issue(owner: string, records: OmemoTrustInspection[]) {
|
||||
if (!owner || owner.length > 1024) throw new Error("Authenticated reviewer identity is required.");
|
||||
this.#prune();
|
||||
// Refresh invalidates this reviewer's previous snapshot, keeping memory bounded.
|
||||
for (const [code, ticket] of this.#tickets) if (ticket.owner === owner) this.#tickets.delete(code);
|
||||
const pending = records.filter((record) => record.state === "undecided" && !record.candidate);
|
||||
if (this.#tickets.size + pending.length > 256) throw new Error("Too many pending OMEMO reviews.");
|
||||
return pending.map((record) => {
|
||||
const code = randomBytes(12).toString("base64url");
|
||||
const ticket: Ticket = { owner, address: record.address,
|
||||
expected: { state: record.state, fingerprint: record.fingerprint },
|
||||
expiresAt: this.clock() + 10 * 60_000 };
|
||||
this.#tickets.set(code, ticket);
|
||||
return { ...record, code, expiresAt: ticket.expiresAt, action: "trusted" as const };
|
||||
});
|
||||
}
|
||||
|
||||
consume(owner: string, code: string): Ticket {
|
||||
this.#prune();
|
||||
const ticket = this.#tickets.get(code);
|
||||
if (!ticket || ticket.owner !== owner) throw new Error("Invalid, expired, or mismatched OMEMO review code; request a fresh review.");
|
||||
// Consume before awaiting the CAS: concurrent or failed reuse is forbidden.
|
||||
this.#tickets.delete(code);
|
||||
return ticket;
|
||||
}
|
||||
|
||||
clear() { this.#tickets.clear(); }
|
||||
#prune() {
|
||||
for (const [code, ticket] of this.#tickets) if (ticket.expiresAt <= this.clock()) this.#tickets.delete(code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { parse as parseXml } from "ltx";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
|
||||
import {
|
||||
LEGACY_OMEMO,
|
||||
OMEMO_2,
|
||||
OmemoEngine,
|
||||
type LibomemoEngineBindings,
|
||||
type OmemoPublishedBundle,
|
||||
type OmemoVersion
|
||||
} from "./engine.js";
|
||||
import { LibomemoStoreAdapter, OmemoIdentityChangedError, OmemoTrustError } from "./libomemo-store.js";
|
||||
import type { OmemoTrustMode } from "./libomemo-store.js";
|
||||
import type { OmemoExpectedTrust, OmemoTrustState } from "./libomemo-store.js";
|
||||
import { OmemoOperator, type OmemoTrustInspection } from "./operator.js";
|
||||
import {
|
||||
OmemoInboundCoordinator,
|
||||
OmemoOutboundCoordinator,
|
||||
type OmemoInboundBindings,
|
||||
type OmemoInboundMessage,
|
||||
type OmemoOutboundBindings,
|
||||
type OmemoRecipientDevices
|
||||
} from "./message.js";
|
||||
import type { OmemoTransactionalStore } from "./store.js";
|
||||
import { parseBundle, parseDeviceList } from "./xml.js";
|
||||
import { OmemoPepSession, XmppOmemoPepAdapter } from "./xmpp-pep.js";
|
||||
|
||||
import { OmemoReviewTickets } from "./review.js";
|
||||
|
||||
const RETIRED_DEVICE_PREFIX = "$retired-device:";
|
||||
|
||||
export interface OmemoSessionIo {
|
||||
send(stanza: Element): Promise<void>;
|
||||
dispatch(message: OmemoInboundMessage): Promise<void>;
|
||||
}
|
||||
|
||||
export interface OmemoSessionOptions {
|
||||
account: string;
|
||||
version: OmemoVersion;
|
||||
trustMode: OmemoTrustMode;
|
||||
deliveryPolicy?: "strict-all" | "trusted-devices";
|
||||
store: OmemoTransactionalStore;
|
||||
engineBindings: LibomemoEngineBindings;
|
||||
outboundBindings: OmemoOutboundBindings;
|
||||
inboundBindings: OmemoInboundBindings;
|
||||
pep: XmppOmemoPepAdapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inactive-by-default assembly of key lifecycle, PEP, session construction,
|
||||
* transactional encryption/decryption, and durable delivery recovery.
|
||||
*/
|
||||
export class OmemoSession {
|
||||
readonly #account: string;
|
||||
readonly #version: OmemoVersion;
|
||||
readonly #store: OmemoTransactionalStore;
|
||||
readonly #engine: OmemoEngine;
|
||||
readonly #pep: XmppOmemoPepAdapter;
|
||||
readonly #outboundBindings: OmemoOutboundBindings;
|
||||
readonly #inboundBindings: OmemoInboundBindings;
|
||||
readonly #trustMode: OmemoTrustMode;
|
||||
readonly #operator: OmemoOperator;
|
||||
#outbound: OmemoOutboundCoordinator | undefined;
|
||||
#inbound: OmemoInboundCoordinator | undefined;
|
||||
readonly #bundles = new Map<OmemoVersion, OmemoPublishedBundle>();
|
||||
#pepSession: OmemoPepSession | undefined;
|
||||
#io: OmemoSessionIo | undefined;
|
||||
#localDeviceId: number | undefined;
|
||||
#retired = false;
|
||||
readonly #reviews = new OmemoReviewTickets();
|
||||
readonly #noticeAt = new Map<string, number>();
|
||||
#sendTail: Promise<unknown> = Promise.resolve();
|
||||
readonly deliveryPolicy: "strict-all" | "trusted-devices";
|
||||
#excluded: Array<{ address: string; reason: string }> = [];
|
||||
get excludedDevices() { return this.#excluded.map((item) => ({ ...item })); }
|
||||
|
||||
constructor(options: OmemoSessionOptions) {
|
||||
if (options.version !== LEGACY_OMEMO && options.version !== OMEMO_2) {
|
||||
throw new Error("Unsupported OMEMO session profile.");
|
||||
}
|
||||
this.deliveryPolicy = options.deliveryPolicy ?? "strict-all";
|
||||
if (!["strict-all", "trusted-devices"].includes(this.deliveryPolicy)) throw new Error("Invalid OMEMO delivery policy.");
|
||||
this.#account = options.account;
|
||||
this.#version = options.version;
|
||||
this.#store = options.store;
|
||||
this.#pep = options.pep;
|
||||
this.#outboundBindings = options.outboundBindings;
|
||||
this.#inboundBindings = options.inboundBindings;
|
||||
this.#trustMode = options.trustMode;
|
||||
this.#operator = new OmemoOperator(options.account, options.store, options.trustMode);
|
||||
this.#engine = new OmemoEngine({
|
||||
account: options.account,
|
||||
store: options.store,
|
||||
bindings: options.engineBindings,
|
||||
trustMode: options.trustMode
|
||||
});
|
||||
}
|
||||
|
||||
async initialize(io: OmemoSessionIo): Promise<void> {
|
||||
if (this.#io) {
|
||||
// A full XMPP reconnect binds a new stream on the same transport. Re-run
|
||||
// publication and recovery before presence without recreating local key
|
||||
// material or rejecting the reconnect as a duplicate initialization.
|
||||
this.#io = io;
|
||||
await this.#pepSession!.initialize();
|
||||
await this.#recover();
|
||||
return;
|
||||
}
|
||||
const bundles = await this.#engine.initialize();
|
||||
// Advertise only the explicitly configured profile. The engine retains
|
||||
// profile-specific local material, but an unselected profile must not be
|
||||
// presented to other clients as supported.
|
||||
this.#bundles.set(this.#version, bundles[this.#version]);
|
||||
const localDeviceId = bundles[this.#version].deviceId;
|
||||
this.#localDeviceId = localDeviceId;
|
||||
// Coordinators must use the restart-stable registration ID, not a placeholder.
|
||||
this.#outbound = new OmemoOutboundCoordinator({
|
||||
account: this.#account, localDeviceId, store: this.#store,
|
||||
bindings: this.#outboundBindings, trustMode: this.#trustMode, requireTrustedTargets: true
|
||||
});
|
||||
this.#inbound = new OmemoInboundCoordinator({
|
||||
account: this.#account, localDeviceId, store: this.#store,
|
||||
bindings: this.#inboundBindings, trustMode: this.#trustMode,
|
||||
refreshBundle: async (version) => await this.#refreshBundle(version)
|
||||
});
|
||||
this.#retired = await this.#store.updateRecords(this.#account, (view) => {
|
||||
const marker = view.get("device", `${RETIRED_DEVICE_PREFIX}${this.#version}`);
|
||||
if (!marker) return false;
|
||||
if (new TextDecoder("utf-8", { fatal: true }).decode(marker) !== String(localDeviceId)) {
|
||||
throw new Error("Corrupt OMEMO retired-device marker.");
|
||||
}
|
||||
return true;
|
||||
});
|
||||
this.#pepSession = new OmemoPepSession(
|
||||
this.#pep,
|
||||
this.#bundles,
|
||||
new Map(),
|
||||
this.#retired ? new Set([this.#version]) : new Set()
|
||||
);
|
||||
await this.#pepSession.initialize();
|
||||
// Complete an interrupted deactivation before presence. The durable marker
|
||||
// is written before the remote mutation, so a crash cannot republish a
|
||||
// device that the operator intended to retire.
|
||||
if (this.#retired) await this.#pepSession.retire(this.#version, localDeviceId);
|
||||
this.#io = io;
|
||||
await this.#recover();
|
||||
}
|
||||
|
||||
async handleStanza(stanza: Element): Promise<boolean> {
|
||||
if (await this.#pepSession?.handleEvent(stanza)) return true;
|
||||
const encrypted = stanza.is("message") && (
|
||||
stanza.getChild("encrypted", LEGACY_OMEMO) !== undefined ||
|
||||
stanza.getChild("encrypted", OMEMO_2) !== undefined
|
||||
);
|
||||
// Connection-level stanzas can arrive after bind but before PEP
|
||||
// initialization completes. Consume encrypted traffic fail-closed during
|
||||
// that window instead of attempting plaintext handling or throwing.
|
||||
if (encrypted && !this.#io) return true;
|
||||
if (encrypted) {
|
||||
await this.#requireInbound().decryptAndDispatch(stanza, this.#requireIo().dispatch);
|
||||
return true;
|
||||
}
|
||||
// Once enabled, an ordinary body must never silently enter OpenClaw as a
|
||||
// fallback for an undecryptable or unencrypted chat message.
|
||||
return stanza.is("message") && stanza.getChild("body") !== undefined;
|
||||
}
|
||||
|
||||
async sendText(to: string, text: string): Promise<string> {
|
||||
const result = this.#sendTail.then(() => this.#sendText(to, text));
|
||||
this.#sendTail = result.catch(() => undefined);
|
||||
return await result;
|
||||
}
|
||||
|
||||
async #sendText(to: string, text: string): Promise<string> {
|
||||
if (this.#retired) throw new Error("OMEMO local device is retired; restart with OMEMO disabled.");
|
||||
const io = this.#requireIo();
|
||||
const recipients = await this.#resolveRecipients(to);
|
||||
const pending = this.#excluded.filter((item) => item.reason === "undecided").length;
|
||||
const notice = pending > 0 && Date.now() - (this.#noticeAt.get(to) ?? 0) >= 10 * 60_000;
|
||||
const outgoingText = notice ? `${text}\n\n[OMEMO: ${pending} new device(s) awaiting approval and excluded from this encrypted reply. Review devices in the Gateway admin interface or use /xmpp-omemo review on an authenticated owner channel.]` : text;
|
||||
const result = await this.#requireOutbound().encryptAndSend({
|
||||
to, text: outgoingText, version: this.#version, recipients, send: io.send
|
||||
});
|
||||
if (notice) {
|
||||
if (this.#noticeAt.size >= 128) this.#noticeAt.delete(this.#noticeAt.keys().next().value!);
|
||||
this.#noticeAt.set(to, Date.now());
|
||||
}
|
||||
return result.id;
|
||||
}
|
||||
|
||||
/** Replay committed deliveries after XEP-0198 resumes the existing stream. */
|
||||
async resume(io: OmemoSessionIo): Promise<void> {
|
||||
if (!this.#io) throw new Error("OMEMO session is not initialized.");
|
||||
this.#io = io;
|
||||
await this.#recover();
|
||||
}
|
||||
|
||||
async inspectTrust(): Promise<OmemoTrustInspection[]> {
|
||||
return await this.#operator.inspectTrust();
|
||||
}
|
||||
|
||||
async reviewPending(owner: string) {
|
||||
return this.#reviews.issue(owner, await this.inspectTrust());
|
||||
}
|
||||
|
||||
async approveReview(owner: string, code: string) {
|
||||
const ticket = this.#reviews.consume(owner, code);
|
||||
return await this.#store.updateRecords(this.#account, (view) => {
|
||||
const trust = new LibomemoStoreAdapter(view, { mode: this.#trustMode }).trust;
|
||||
if (trust.candidate(ticket.address)) throw new Error("OMEMO identity changed since review; explicit replacement review is required.");
|
||||
return trust.transition(ticket.address, ticket.expected, "trusted");
|
||||
});
|
||||
}
|
||||
|
||||
async transitionTrust(
|
||||
address: string,
|
||||
expected: OmemoExpectedTrust,
|
||||
nextState: OmemoTrustState
|
||||
) {
|
||||
return await this.#operator.transition(address, expected, nextState);
|
||||
}
|
||||
|
||||
async replaceIdentity(
|
||||
address: string,
|
||||
expected: OmemoExpectedTrust,
|
||||
observedFingerprint: string,
|
||||
nextState: OmemoTrustState
|
||||
) {
|
||||
return await this.#operator.replaceIdentity(address, expected, observedFingerprint, nextState);
|
||||
}
|
||||
|
||||
/** Retire only the exact initialized local device; local keys remain for rollback. */
|
||||
async retireLocalDevice(version: OmemoVersion, expectedDeviceId: number): Promise<void> {
|
||||
if (!this.#io || !this.#pepSession || this.#localDeviceId === undefined) {
|
||||
throw new Error("OMEMO session is not initialized.");
|
||||
}
|
||||
if (version !== this.#version || expectedDeviceId !== this.#localDeviceId) {
|
||||
throw new Error("OMEMO retirement target does not match the active local device.");
|
||||
}
|
||||
await this.#store.updateRecords(this.#account, (view) => {
|
||||
view.set("device", `${RETIRED_DEVICE_PREFIX}${version}`, Buffer.from(String(expectedDeviceId), "utf8"));
|
||||
});
|
||||
this.#retired = true;
|
||||
await this.#pepSession.retire(version, expectedDeviceId);
|
||||
}
|
||||
|
||||
async activateLocalDevice(version: OmemoVersion, expectedDeviceId: number): Promise<void> {
|
||||
if (!this.#io || !this.#pepSession || this.#localDeviceId === undefined) {
|
||||
throw new Error("OMEMO session is not initialized.");
|
||||
}
|
||||
if (version !== this.#version || expectedDeviceId !== this.#localDeviceId) {
|
||||
throw new Error("OMEMO activation target does not match the active local device.");
|
||||
}
|
||||
if (!this.#retired) throw new Error("OMEMO local device is already active.");
|
||||
await this.#pepSession.activate(version, expectedDeviceId);
|
||||
await this.#store.updateRecords(this.#account, (view) => {
|
||||
view.delete("device", `${RETIRED_DEVICE_PREFIX}${version}`);
|
||||
});
|
||||
this.#retired = false;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#reviews.clear();
|
||||
this.#store.close();
|
||||
this.#io = undefined;
|
||||
this.#pepSession = undefined;
|
||||
this.#outbound = undefined;
|
||||
this.#inbound = undefined;
|
||||
}
|
||||
|
||||
async #resolveRecipients(to: string): Promise<OmemoRecipientDevices[]> {
|
||||
const result: OmemoRecipientDevices[] = [];
|
||||
this.#excluded = [];
|
||||
let inspected = 0;
|
||||
for (const jid of [...new Set([to, this.#account])]) {
|
||||
const adapter = jid === this.#account ? this.#pep : new XmppOmemoPepAdapter(jid, this.#pep.iq);
|
||||
const item = await adapter.fetchDeviceList(this.#version);
|
||||
if (!item?.payload) throw new Error(`OMEMO device list is unavailable for ${jid}.`);
|
||||
const devices = parseDeviceList(this.#version, item.payload);
|
||||
const selected: number[] = [];
|
||||
for (const device of devices) {
|
||||
if (jid === this.#account && device.id === this.#localDeviceId) continue;
|
||||
if (++inspected > 128) throw new Error("OMEMO device discovery limit exceeded (128).");
|
||||
const address = `${jid}.${device.id}`;
|
||||
// Corruption and already observed replacements remain hard failures,
|
||||
// even if the device subsequently removes its bundle.
|
||||
await this.#store.updateRecords(this.#account, (view) => {
|
||||
const trust = new LibomemoStoreAdapter(view, { mode: this.#trustMode }).trust;
|
||||
const current = trust.get(address);
|
||||
const candidate = trust.candidate(address);
|
||||
if (candidate) throw new OmemoIdentityChangedError(address, current!.fingerprint, candidate.observedFingerprint);
|
||||
});
|
||||
// Refresh advertised identities even with a cached session: a known
|
||||
// replacement must never become an ordinary excluded/unknown device.
|
||||
const bundle = await adapter.fetchBundle(this.#version, device.id);
|
||||
if (!bundle?.payload) {
|
||||
if (this.deliveryPolicy === "strict-all") throw new Error(`OMEMO bundle is unavailable for ${address}.`);
|
||||
this.#excluded.push({ address, reason: "bundle-unavailable" });
|
||||
continue;
|
||||
}
|
||||
const parsed = parseBundle(this.#version, device.id, bundle.payload);
|
||||
await this.#engine.observeIdentity(address, parsed.identityKey);
|
||||
const record = await this.#store.updateRecords(this.#account, (view) => {
|
||||
const trust = new LibomemoStoreAdapter(view, { mode: this.#trustMode }).trust;
|
||||
const current = trust.get(address)!;
|
||||
const candidate = trust.candidate(address);
|
||||
if (candidate) throw new OmemoIdentityChangedError(address, current.fingerprint, candidate.observedFingerprint);
|
||||
return current;
|
||||
});
|
||||
if (record.state !== "trusted" && record.state !== "verified") {
|
||||
this.#excluded.push({ address, reason: record.state });
|
||||
if (this.deliveryPolicy === "strict-all") throw new OmemoTrustError(address, record.state, record.fingerprint, 1);
|
||||
continue;
|
||||
}
|
||||
if (!await this.#engine.hasSession(address)) {
|
||||
await this.#engine.buildSession(address, this.#version, parsed);
|
||||
}
|
||||
selected.push(device.id);
|
||||
}
|
||||
result.push({ jid, deviceIds: selected });
|
||||
}
|
||||
if (!result.some((item) => item.jid === to && item.deviceIds.length > 0)) {
|
||||
throw new Error("OMEMO delivery blocked: recipient has no trusted devices; review pending identities in the admin interface.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async #refreshBundle(version: OmemoVersion): Promise<void> {
|
||||
const bundles = await this.#engine.maintainKeys();
|
||||
this.#bundles.set(version, bundles[version]);
|
||||
await new OmemoPepSession(this.#pep, new Map([[version, bundles[version]]])).initialize();
|
||||
}
|
||||
|
||||
async #recover(): Promise<void> {
|
||||
const io = this.#requireIo();
|
||||
for (const pending of this.#store.listOutbound(this.#account)) {
|
||||
const stanza = parseXml(new TextDecoder("utf-8", { fatal: true }).decode(pending.stanza)) as Element;
|
||||
await io.send(stanza);
|
||||
this.#store.acknowledgeOutbound(this.#account, pending.id);
|
||||
}
|
||||
await this.#requireInbound().dispatchPending(async (message) => await io.dispatch({
|
||||
...message, version: this.#version, senderDeviceId: 0
|
||||
}));
|
||||
}
|
||||
|
||||
#requireIo(): OmemoSessionIo {
|
||||
if (!this.#io) throw new Error("OMEMO session is not initialized.");
|
||||
return this.#io;
|
||||
}
|
||||
|
||||
#requireOutbound(): OmemoOutboundCoordinator {
|
||||
if (!this.#outbound) throw new Error("OMEMO session is not initialized.");
|
||||
return this.#outbound;
|
||||
}
|
||||
|
||||
#requireInbound(): OmemoInboundCoordinator {
|
||||
if (!this.#inbound) throw new Error("OMEMO session is not initialized.");
|
||||
return this.#inbound;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
||||
import { chmodSync, mkdirSync, openSync, readFileSync, writeFileSync, closeSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
|
||||
const SCHEMA_VERSION = 1;
|
||||
const KEY_BYTES = 32;
|
||||
const NONCE_BYTES = 12;
|
||||
const TAG_BYTES = 16;
|
||||
|
||||
export type OmemoRecordKind =
|
||||
| "identity"
|
||||
| "prekey"
|
||||
| "signed-prekey"
|
||||
| "session"
|
||||
| "trust"
|
||||
| "candidate"
|
||||
| "device";
|
||||
|
||||
export interface PendingOutbound {
|
||||
id: string;
|
||||
recipient: string;
|
||||
stanza: Buffer;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface PendingInbound {
|
||||
id: string;
|
||||
sender: string;
|
||||
plaintext: Buffer;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export class OmemoRecordView {
|
||||
readonly #records: Map<string, Buffer>;
|
||||
|
||||
constructor(records: Map<string, Buffer>) {
|
||||
this.#records = records;
|
||||
}
|
||||
|
||||
get(kind: OmemoRecordKind, key: string): Buffer | undefined {
|
||||
const value = this.#records.get(recordKey(kind, key));
|
||||
return value ? Buffer.from(value) : undefined;
|
||||
}
|
||||
|
||||
set(kind: OmemoRecordKind, key: string, value: Uint8Array): void {
|
||||
validateKey(key);
|
||||
if (value.byteLength === 0) throw new Error("OMEMO records must not be empty.");
|
||||
this.#records.set(recordKey(kind, key), Buffer.from(value));
|
||||
}
|
||||
|
||||
delete(kind: OmemoRecordKind, key: string): void {
|
||||
this.#records.delete(recordKey(kind, key));
|
||||
}
|
||||
|
||||
entries(): IterableIterator<[string, Buffer]> {
|
||||
return this.#records.entries();
|
||||
}
|
||||
}
|
||||
|
||||
export interface OmemoStoreOptions {
|
||||
stateDirectory: string;
|
||||
clock?: () => number;
|
||||
/** Test-only crash/fault injection; production callers must omit this. */
|
||||
faultInjector?: (point: "before-commit" | "after-commit") => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Crash-consistent persistence boundary for OMEMO ratchet operations.
|
||||
*
|
||||
* libomemo callbacks mutate only the supplied in-memory view. State and the
|
||||
* exact outbound stanza or encrypted pending inbound delivery are then
|
||||
* committed together. Callers may send/dispatch only after the method returns.
|
||||
*/
|
||||
export class OmemoTransactionalStore {
|
||||
readonly #db: DatabaseSync;
|
||||
readonly #key: Buffer;
|
||||
readonly #clock: () => number;
|
||||
readonly #faultInjector: OmemoStoreOptions["faultInjector"];
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(options: OmemoStoreOptions) {
|
||||
mkdirSync(options.stateDirectory, { recursive: true, mode: 0o700 });
|
||||
chmodSync(options.stateDirectory, 0o700);
|
||||
const keyPath = join(options.stateDirectory, "pending-delivery.key");
|
||||
this.#key = loadOrCreateKey(keyPath);
|
||||
const databasePath = join(options.stateDirectory, "omemo.sqlite");
|
||||
this.#db = new DatabaseSync(databasePath);
|
||||
chmodSync(databasePath, 0o600);
|
||||
this.#clock = options.clock ?? Date.now;
|
||||
this.#faultInjector = options.faultInjector;
|
||||
this.#initialize();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#db.close();
|
||||
this.#key.fill(0);
|
||||
}
|
||||
|
||||
async outbound(
|
||||
account: string,
|
||||
id: string,
|
||||
recipient: string,
|
||||
operation: (view: OmemoRecordView) => Promise<Uint8Array>
|
||||
): Promise<PendingOutbound> {
|
||||
return this.#serialize(async () => {
|
||||
const records = this.#loadRecords(account);
|
||||
const stanza = Buffer.from(await operation(new OmemoRecordView(records)));
|
||||
if (stanza.byteLength === 0) throw new Error("OMEMO outbound stanza must not be empty.");
|
||||
const createdAt = this.#clock();
|
||||
this.#transaction(() => {
|
||||
this.#replaceRecords(account, records, createdAt);
|
||||
this.#db.prepare(
|
||||
"INSERT INTO outbox(account, id, recipient, stanza, created_at) VALUES (?, ?, ?, ?, ?)"
|
||||
).run(account, id, recipient, stanza, createdAt);
|
||||
});
|
||||
return { id, recipient, stanza, createdAt };
|
||||
});
|
||||
}
|
||||
|
||||
async inbound(
|
||||
account: string,
|
||||
id: string,
|
||||
sender: string,
|
||||
operation: (view: OmemoRecordView) => Promise<Uint8Array>
|
||||
): Promise<PendingInbound> {
|
||||
return this.#serialize(async () => {
|
||||
const duplicate = this.#db.prepare(
|
||||
"SELECT 1 AS found FROM inbox WHERE account = ? AND id = ?"
|
||||
).get(account, id) as { found: number } | undefined;
|
||||
if (duplicate) throw new Error("OMEMO inbound delivery is already pending.");
|
||||
const records = this.#loadRecords(account);
|
||||
const plaintext = Buffer.from(await operation(new OmemoRecordView(records)));
|
||||
const sealed = seal(this.#key, plaintext);
|
||||
const createdAt = this.#clock();
|
||||
this.#transaction(() => {
|
||||
this.#replaceRecords(account, records, createdAt);
|
||||
this.#db.prepare(
|
||||
"INSERT INTO inbox(account, id, sender, sealed_plaintext, created_at) VALUES (?, ?, ?, ?, ?)"
|
||||
).run(account, id, sender, sealed, createdAt);
|
||||
});
|
||||
return { id, sender, plaintext, createdAt };
|
||||
});
|
||||
}
|
||||
|
||||
/** Commit non-delivery state changes such as key initialization or trust decisions. */
|
||||
async updateRecords<T>(
|
||||
account: string,
|
||||
operation: (view: OmemoRecordView) => Promise<T> | T
|
||||
): Promise<T> {
|
||||
return this.#serialize(async () => {
|
||||
const records = this.#loadRecords(account);
|
||||
const result = await operation(new OmemoRecordView(records));
|
||||
const updatedAt = this.#clock();
|
||||
this.#transaction(() => this.#replaceRecords(account, records, updatedAt));
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
listOutbound(account: string): PendingOutbound[] {
|
||||
const rows = this.#db.prepare(
|
||||
"SELECT id, recipient, stanza, created_at FROM outbox WHERE account = ? ORDER BY created_at, id"
|
||||
).all(account) as Array<{ id: string; recipient: string; stanza: Uint8Array; created_at: number }>;
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
recipient: row.recipient,
|
||||
stanza: Buffer.from(row.stanza),
|
||||
createdAt: row.created_at
|
||||
}));
|
||||
}
|
||||
|
||||
listInbound(account: string): PendingInbound[] {
|
||||
const rows = this.#db.prepare(
|
||||
"SELECT id, sender, sealed_plaintext, created_at FROM inbox WHERE account = ? ORDER BY created_at, id"
|
||||
).all(account) as Array<{ id: string; sender: string; sealed_plaintext: Uint8Array; created_at: number }>;
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
sender: row.sender,
|
||||
plaintext: open(this.#key, Buffer.from(row.sealed_plaintext)),
|
||||
createdAt: row.created_at
|
||||
}));
|
||||
}
|
||||
|
||||
acknowledgeOutbound(account: string, id: string): void {
|
||||
this.#db.prepare("DELETE FROM outbox WHERE account = ? AND id = ?").run(account, id);
|
||||
}
|
||||
|
||||
acknowledgeInbound(account: string, id: string): void {
|
||||
this.#db.prepare("DELETE FROM inbox WHERE account = ? AND id = ?").run(account, id);
|
||||
}
|
||||
|
||||
integrityCheck(): void {
|
||||
const row = this.#db.prepare("PRAGMA integrity_check").get() as { integrity_check?: string } | undefined;
|
||||
if (row?.integrity_check !== "ok") throw new Error("OMEMO state database integrity check failed.");
|
||||
}
|
||||
|
||||
#initialize(): void {
|
||||
this.#db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; PRAGMA foreign_keys = ON;");
|
||||
this.#db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS records(
|
||||
account TEXT NOT NULL, kind TEXT NOT NULL, record_key TEXT NOT NULL,
|
||||
value BLOB NOT NULL, updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(account, kind, record_key)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS outbox(
|
||||
account TEXT NOT NULL, id TEXT NOT NULL, recipient TEXT NOT NULL,
|
||||
stanza BLOB NOT NULL, created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(account, id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS inbox(
|
||||
account TEXT NOT NULL, id TEXT NOT NULL, sender TEXT NOT NULL,
|
||||
sealed_plaintext BLOB NOT NULL, created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(account, id)
|
||||
);
|
||||
`);
|
||||
const version = this.#db.prepare("SELECT value FROM metadata WHERE key = 'schema_version'").get() as
|
||||
| { value: string }
|
||||
| undefined;
|
||||
if (!version) {
|
||||
this.#db.prepare("INSERT INTO metadata(key, value) VALUES ('schema_version', ?)").run(String(SCHEMA_VERSION));
|
||||
} else if (version.value !== String(SCHEMA_VERSION)) {
|
||||
throw new Error(`Unsupported OMEMO state schema version: ${version.value}`);
|
||||
}
|
||||
this.integrityCheck();
|
||||
}
|
||||
|
||||
#loadRecords(account: string): Map<string, Buffer> {
|
||||
const rows = this.#db.prepare(
|
||||
"SELECT kind, record_key, value FROM records WHERE account = ?"
|
||||
).all(account) as Array<{ kind: OmemoRecordKind; record_key: string; value: Uint8Array }>;
|
||||
return new Map(rows.map((row) => [recordKey(row.kind, row.record_key), Buffer.from(row.value)]));
|
||||
}
|
||||
|
||||
#replaceRecords(account: string, records: Map<string, Buffer>, now: number): void {
|
||||
this.#db.prepare("DELETE FROM records WHERE account = ?").run(account);
|
||||
const insert = this.#db.prepare(
|
||||
"INSERT INTO records(account, kind, record_key, value, updated_at) VALUES (?, ?, ?, ?, ?)"
|
||||
);
|
||||
for (const [combined, value] of records) {
|
||||
const separator = combined.indexOf("\u0000");
|
||||
insert.run(account, combined.slice(0, separator), combined.slice(separator + 1), value, now);
|
||||
}
|
||||
}
|
||||
|
||||
#transaction(operation: () => void): void {
|
||||
this.#db.exec("BEGIN IMMEDIATE");
|
||||
let committed = false;
|
||||
try {
|
||||
operation();
|
||||
this.#faultInjector?.("before-commit");
|
||||
this.#db.exec("COMMIT");
|
||||
committed = true;
|
||||
this.#faultInjector?.("after-commit");
|
||||
} catch (error) {
|
||||
if (!committed) this.#db.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
#serialize<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = this.#tail.then(operation, operation);
|
||||
this.#tail = result.then(() => undefined, () => undefined);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function recordKey(kind: OmemoRecordKind, key: string): string {
|
||||
validateKey(key);
|
||||
return `${kind}\u0000${key}`;
|
||||
}
|
||||
|
||||
function validateKey(key: string): void {
|
||||
if (!key || key.includes("\u0000") || key.length > 1024) throw new Error("Invalid OMEMO record key.");
|
||||
}
|
||||
|
||||
function loadOrCreateKey(path: string): Buffer {
|
||||
try {
|
||||
const key = readFileSync(path);
|
||||
if (key.byteLength !== KEY_BYTES) throw new Error("Invalid OMEMO pending-delivery key length.");
|
||||
chmodSync(path, 0o600);
|
||||
return key;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const descriptor = openSync(path, "wx", 0o600);
|
||||
try {
|
||||
const key = randomBytes(KEY_BYTES);
|
||||
writeFileSync(descriptor, key);
|
||||
return key;
|
||||
} finally {
|
||||
closeSync(descriptor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function seal(key: Buffer, plaintext: Buffer): Buffer {
|
||||
const nonce = randomBytes(NONCE_BYTES);
|
||||
const cipher = createCipheriv("aes-256-gcm", key, nonce);
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
||||
return Buffer.concat([nonce, cipher.getAuthTag(), ciphertext]);
|
||||
}
|
||||
|
||||
function open(key: Buffer, sealed: Buffer): Buffer {
|
||||
if (sealed.byteLength < NONCE_BYTES + TAG_BYTES) throw new Error("Corrupt OMEMO pending delivery.");
|
||||
const nonce = sealed.subarray(0, NONCE_BYTES);
|
||||
const tag = sealed.subarray(NONCE_BYTES, NONCE_BYTES + TAG_BYTES);
|
||||
const ciphertext = sealed.subarray(NONCE_BYTES + TAG_BYTES);
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, nonce);
|
||||
decipher.setAuthTag(tag);
|
||||
try {
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
} catch {
|
||||
throw new Error("OMEMO pending delivery authentication failed.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { randomInt } from "node:crypto";
|
||||
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
|
||||
import {
|
||||
LEGACY_OMEMO,
|
||||
OMEMO_2,
|
||||
type OmemoPublishedBundle,
|
||||
type OmemoRemoteBundle,
|
||||
type OmemoVersion
|
||||
} from "./engine.js";
|
||||
|
||||
const MAX_DEVICE_ID = 0x7fff_ffff;
|
||||
const MAX_KEY_ID = 0x7fff_ffff;
|
||||
const MAX_DEVICES = 1_000;
|
||||
const MAX_PREKEYS = 1_000;
|
||||
const MAX_LABEL_BYTES = 128;
|
||||
|
||||
export interface OmemoDevice { id: number; label?: string; labelSignature?: ArrayBuffer }
|
||||
|
||||
export function deviceListNode(version: OmemoVersion): string {
|
||||
return version === LEGACY_OMEMO ? `${LEGACY_OMEMO}.devicelist` : `${OMEMO_2}:devices`;
|
||||
}
|
||||
|
||||
export function bundleNode(version: OmemoVersion, deviceId: number): string {
|
||||
deviceId = integer(deviceId, "device ID", 1, MAX_DEVICE_ID);
|
||||
return version === LEGACY_OMEMO
|
||||
? `${LEGACY_OMEMO}.bundles:${deviceId}`
|
||||
: `${OMEMO_2}:bundles`;
|
||||
}
|
||||
|
||||
export function serializeDeviceList(version: OmemoVersion, devices: readonly OmemoDevice[]): Element {
|
||||
validateVersion(version);
|
||||
if (devices.length > MAX_DEVICES) throw new Error("OMEMO device list exceeds the size limit.");
|
||||
const ordered = [...devices].sort((a, b) => a.id - b.id);
|
||||
const seen = new Set<number>();
|
||||
const children = ordered.map((device) => {
|
||||
const id = integer(device.id, "device ID", 1, MAX_DEVICE_ID);
|
||||
if (seen.has(id)) throw new Error("OMEMO device list contains a duplicate device ID.");
|
||||
seen.add(id);
|
||||
const attrs: Record<string, string> = { id: String(id) };
|
||||
if (device.label !== undefined || device.labelSignature !== undefined) {
|
||||
if (version !== OMEMO_2 || device.label === undefined || device.labelSignature === undefined) {
|
||||
throw new Error("OMEMO device labels require an OMEMO 2 label signature.");
|
||||
}
|
||||
attrs.label = label(device.label);
|
||||
attrs.labelsig = base64(binary(device.labelSignature, 64, "device-label signature"));
|
||||
}
|
||||
return xml("device", attrs);
|
||||
});
|
||||
return xml(version === LEGACY_OMEMO ? "list" : "devices", { xmlns: version }, ...children);
|
||||
}
|
||||
|
||||
export function parseDeviceList(version: OmemoVersion, payload: Element): OmemoDevice[] {
|
||||
validateVersion(version);
|
||||
requireElement(payload, version === LEGACY_OMEMO ? "list" : "devices", version);
|
||||
requireAttrs(payload, ["xmlns"]);
|
||||
requireNoText(payload);
|
||||
const children = payload.getChildElements();
|
||||
if (children.length > MAX_DEVICES) throw new Error("OMEMO device list exceeds the size limit.");
|
||||
const result: OmemoDevice[] = [];
|
||||
const seen = new Set<number>();
|
||||
for (const child of children) {
|
||||
requireElement(child, "device", version);
|
||||
requireAttrs(child, version === OMEMO_2 ? ["id", "label", "labelsig"] : ["id"]);
|
||||
requireNoChildrenOrText(child);
|
||||
const id = integerString(child.attrs.id, "device ID", 1, MAX_DEVICE_ID);
|
||||
if (seen.has(id)) throw new Error("OMEMO device list contains a duplicate device ID.");
|
||||
seen.add(id);
|
||||
const rawLabel = child.attrs.label;
|
||||
const rawSignature = child.attrs.labelsig;
|
||||
if ((rawLabel === undefined) !== (rawSignature === undefined)) {
|
||||
throw new Error("OMEMO device labels require a label signature.");
|
||||
}
|
||||
result.push({ id, ...(rawLabel === undefined ? {} : {
|
||||
label: label(rawLabel),
|
||||
labelSignature: decodeBase64(rawSignature, 64, "device-label signature")
|
||||
}) });
|
||||
}
|
||||
return result.sort((a, b) => a.id - b.id);
|
||||
}
|
||||
|
||||
export function serializeBundle(bundle: OmemoPublishedBundle): Element {
|
||||
const { version } = bundle;
|
||||
validateVersion(version);
|
||||
integer(bundle.deviceId, "device ID", 1, MAX_DEVICE_ID);
|
||||
const signedId = integer(bundle.signedPreKey.id, "signed-prekey ID", 1, MAX_KEY_ID);
|
||||
const identity = binary(bundle.identityKey, version === LEGACY_OMEMO ? 33 : 32, "identity key");
|
||||
const signed = binary(bundle.signedPreKey.publicKey, version === LEGACY_OMEMO ? 33 : 32, "signed prekey");
|
||||
const signature = binary(bundle.signedPreKey.signature, 64, "signed-prekey signature");
|
||||
if (bundle.preKeys.length === 0) throw new Error("OMEMO bundle has no one-time prekeys.");
|
||||
if (bundle.preKeys.length > MAX_PREKEYS) throw new Error("OMEMO bundle exceeds the prekey limit.");
|
||||
const seen = new Set<number>();
|
||||
const prekeys = [...bundle.preKeys].sort((a, b) => a.id - b.id).map((prekey) => {
|
||||
const id = integer(prekey.id, "prekey ID", 1, MAX_KEY_ID);
|
||||
if (seen.has(id)) throw new Error("OMEMO bundle contains a duplicate prekey ID.");
|
||||
seen.add(id);
|
||||
const value = base64(binary(prekey.publicKey, version === LEGACY_OMEMO ? 33 : 32, "prekey"));
|
||||
return version === LEGACY_OMEMO
|
||||
? xml("preKeyPublic", { preKeyId: String(id) }, value)
|
||||
: xml("pk", { id: String(id) }, value);
|
||||
});
|
||||
if (version === LEGACY_OMEMO) {
|
||||
return xml("bundle", { xmlns: version },
|
||||
xml("signedPreKeyPublic", { signedPreKeyId: String(signedId) }, base64(signed)),
|
||||
xml("signedPreKeySignature", {}, base64(signature)),
|
||||
xml("identityKey", {}, base64(identity)),
|
||||
xml("prekeys", {}, ...prekeys));
|
||||
}
|
||||
return xml("bundle", { xmlns: version },
|
||||
xml("spk", { id: String(signedId) }, base64(signed)),
|
||||
xml("spks", {}, base64(signature)),
|
||||
xml("ik", {}, base64(identity)),
|
||||
xml("prekeys", {}, ...prekeys));
|
||||
}
|
||||
|
||||
export function parseBundle(
|
||||
version: OmemoVersion,
|
||||
deviceId: number,
|
||||
payload: Element,
|
||||
selectPreKey: (count: number) => number = randomInt
|
||||
): OmemoRemoteBundle {
|
||||
validateVersion(version);
|
||||
const registrationId = integer(deviceId, "device ID", 1, MAX_DEVICE_ID);
|
||||
requireElement(payload, "bundle", version);
|
||||
requireAttrs(payload, ["xmlns"]);
|
||||
requireNoText(payload);
|
||||
const names = version === LEGACY_OMEMO
|
||||
? { signed: "signedPreKeyPublic", signedId: "signedPreKeyId", signature: "signedPreKeySignature", identity: "identityKey", prekey: "preKeyPublic", prekeyId: "preKeyId" }
|
||||
: { signed: "spk", signedId: "id", signature: "spks", identity: "ik", prekey: "pk", prekeyId: "id" };
|
||||
const expected = [names.signed, names.signature, names.identity, "prekeys"];
|
||||
const children = payload.getChildElements();
|
||||
if (children.length !== expected.length || expected.some((name) => children.filter((child) => child.is(name, version)).length !== 1)) {
|
||||
throw new Error("Malformed OMEMO bundle structure.");
|
||||
}
|
||||
const signed = payload.getChild(names.signed, version)!;
|
||||
const signature = payload.getChild(names.signature, version)!;
|
||||
const identity = payload.getChild(names.identity, version)!;
|
||||
const prekeys = payload.getChild("prekeys", version)!;
|
||||
requireAttrs(signed, [names.signedId]);
|
||||
requireAttrs(signature, []);
|
||||
requireAttrs(identity, []);
|
||||
requireAttrs(prekeys, []);
|
||||
const signedId = integerString(signed.attrs[names.signedId], "signed-prekey ID", 1, MAX_KEY_ID);
|
||||
const keyBytes = version === LEGACY_OMEMO ? 33 : 32;
|
||||
const parsedPrekeys = prekeys.getChildElements();
|
||||
requireNoText(prekeys);
|
||||
if (parsedPrekeys.length === 0) throw new Error("OMEMO bundle has no one-time prekeys.");
|
||||
if (parsedPrekeys.length > MAX_PREKEYS) throw new Error("OMEMO bundle exceeds the prekey limit.");
|
||||
const seen = new Set<number>();
|
||||
const selectedIndex = selectPreKey(parsedPrekeys.length);
|
||||
if (!Number.isSafeInteger(selectedIndex) || selectedIndex < 0 || selectedIndex >= parsedPrekeys.length) {
|
||||
throw new Error("Invalid OMEMO prekey selection.");
|
||||
}
|
||||
const selected = parsedPrekeys[selectedIndex]!;
|
||||
for (const entry of parsedPrekeys) {
|
||||
requireElement(entry, names.prekey, version);
|
||||
requireAttrs(entry, [names.prekeyId]);
|
||||
requireTextOnly(entry);
|
||||
const id = integerString(entry.attrs[names.prekeyId], "prekey ID", 1, MAX_KEY_ID);
|
||||
if (seen.has(id)) throw new Error("OMEMO bundle contains a duplicate prekey ID.");
|
||||
seen.add(id);
|
||||
}
|
||||
return {
|
||||
registrationId,
|
||||
identityKey: decodeBase64Element(identity, version === LEGACY_OMEMO ? 33 : 32, "identity key"),
|
||||
signedPreKey: {
|
||||
keyId: signedId,
|
||||
publicKey: decodeBase64Element(signed, keyBytes, "signed prekey"),
|
||||
signature: decodeBase64Element(signature, 64, "signed-prekey signature")
|
||||
},
|
||||
preKey: {
|
||||
keyId: integerString(selected.attrs[names.prekeyId], "prekey ID", 1, MAX_KEY_ID),
|
||||
publicKey: decodeBase64Element(selected, keyBytes, "prekey")
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function decodeBase64Element(element: Element, length: number, name: string): ArrayBuffer {
|
||||
requireTextOnly(element);
|
||||
return decodeBase64(element.getText(), length, name);
|
||||
}
|
||||
function decodeBase64(value: unknown, length: number, name: string): ArrayBuffer {
|
||||
const raw = typeof value === "string" ? value : "";
|
||||
if (/[^A-Za-z0-9+/=\t\n\r ]/.test(raw)) throw new Error(`Invalid OMEMO ${name} base64.`);
|
||||
const text = raw.replace(/[\t\n\r ]/g, "");
|
||||
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text)) {
|
||||
throw new Error(`Invalid OMEMO ${name} base64.`);
|
||||
}
|
||||
const decoded = Buffer.from(text, "base64");
|
||||
if (decoded.toString("base64") !== text || decoded.byteLength !== length) {
|
||||
throw new Error(`Invalid OMEMO ${name}.`);
|
||||
}
|
||||
return Uint8Array.from(decoded).buffer;
|
||||
}
|
||||
|
||||
function requireElement(value: Element, name: string, namespace: string): void {
|
||||
if (!value.is(name, namespace)) throw new Error(`Expected OMEMO ${name} element in ${namespace}.`);
|
||||
}
|
||||
function requireAttrs(value: Element, allowed: string[]): void {
|
||||
if (Object.keys(value.attrs).some((key) => !allowed.includes(key))) throw new Error("Unexpected OMEMO XML attribute.");
|
||||
}
|
||||
function requireNoText(value: Element): void {
|
||||
if (value.getText().trim() !== "") throw new Error("Unexpected OMEMO XML text.");
|
||||
}
|
||||
function requireNoChildrenOrText(value: Element): void {
|
||||
if (value.children.length !== 0) throw new Error("Unexpected OMEMO XML content.");
|
||||
}
|
||||
function requireTextOnly(value: Element): void {
|
||||
if (value.getChildElements().length !== 0 || value.children.some((child) => typeof child !== "string" && typeof child !== "number")) {
|
||||
throw new Error("Unexpected OMEMO XML content.");
|
||||
}
|
||||
}
|
||||
function binary(value: ArrayBuffer, length: number, name: string): Uint8Array {
|
||||
if (!(value instanceof ArrayBuffer) || value.byteLength !== length) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return new Uint8Array(value);
|
||||
}
|
||||
function base64(value: Uint8Array): string { return Buffer.from(value).toString("base64"); }
|
||||
function integer(value: number, name: string, min: number, max: number): number {
|
||||
if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return value;
|
||||
}
|
||||
function integerString(value: unknown, name: string, min: number, max: number): number {
|
||||
if (typeof value !== "string" || !/^(?:0|[1-9][0-9]*)$/.test(value)) throw new Error(`Invalid OMEMO ${name}.`);
|
||||
return integer(Number(value), name, min, max);
|
||||
}
|
||||
function label(value: unknown): string {
|
||||
if (typeof value !== "string" || value.length === 0 || /[\u0000-\u001f\u007f]/u.test(value) || Buffer.byteLength(value, "utf8") > MAX_LABEL_BYTES) {
|
||||
throw new Error("Invalid OMEMO device label.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function validateVersion(value: string): asserts value is OmemoVersion {
|
||||
if (value !== LEGACY_OMEMO && value !== OMEMO_2) throw new Error("Unsupported OMEMO version.");
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
|
||||
import { normalizeBareJid } from "../jid.js";
|
||||
import { LEGACY_OMEMO, OMEMO_2, type OmemoPublishedBundle, type OmemoVersion } from "./engine.js";
|
||||
import { OmemoPepConflictError, OmemoPepPublisher, type OmemoPepAdapter, type OmemoPepItem } from "./pep.js";
|
||||
import { bundleNode, deviceListNode, parseDeviceList, type OmemoDevice } from "./xml.js";
|
||||
|
||||
export const PUBSUB = "http://jabber.org/protocol/pubsub";
|
||||
export const PUBSUB_EVENT = "http://jabber.org/protocol/pubsub#event";
|
||||
export const PUBSUB_OWNER = "http://jabber.org/protocol/pubsub#owner";
|
||||
export const DATA_FORMS = "jabber:x:data";
|
||||
const STANZAS = "urn:ietf:params:xml:ns:xmpp-stanzas";
|
||||
const DEVICE_ITEM = "current";
|
||||
const MAX_BUNDLE_ITEMS = "max";
|
||||
|
||||
export interface OmemoIqCaller { request(stanza: Element): Promise<Element> }
|
||||
|
||||
/** Concrete IQ adapter for the transport-independent publication policy. */
|
||||
export class XmppOmemoPepAdapter implements OmemoPepAdapter {
|
||||
constructor(readonly account: string, readonly iq: OmemoIqCaller) {
|
||||
if (!account.trim()) throw new Error("OMEMO PEP account must not be empty.");
|
||||
}
|
||||
|
||||
async fetchDeviceList(version: OmemoVersion): Promise<OmemoPepItem | undefined> {
|
||||
return await this.#fetch(deviceListNode(version), DEVICE_ITEM);
|
||||
}
|
||||
|
||||
async publishDeviceList(version: OmemoVersion, payload: Element, expectedRevision?: string): Promise<void> {
|
||||
await this.#publish(deviceListNode(version), DEVICE_ITEM, payload, expectedRevision);
|
||||
}
|
||||
|
||||
async fetchBundle(version: OmemoVersion, deviceId: number): Promise<OmemoPepItem | undefined> {
|
||||
return await this.#fetch(bundleNode(version, deviceId), version === OMEMO_2 ? String(deviceId) : DEVICE_ITEM);
|
||||
}
|
||||
|
||||
async publishBundle(version: OmemoVersion, deviceId: number, payload: Element, expectedRevision?: string): Promise<void> {
|
||||
await this.#publish(bundleNode(version, deviceId), version === OMEMO_2 ? String(deviceId) : DEVICE_ITEM, payload, expectedRevision);
|
||||
}
|
||||
|
||||
async retractBundle(version: OmemoVersion, deviceId: number, expectedRevision?: string): Promise<void> {
|
||||
const node = bundleNode(version, deviceId);
|
||||
const itemId = version === OMEMO_2 ? String(deviceId) : DEVICE_ITEM;
|
||||
if (expectedRevision !== undefined) {
|
||||
const current = await this.#fetch(node, itemId);
|
||||
if (current?.revision !== expectedRevision) throw new OmemoPepConflictError();
|
||||
}
|
||||
try {
|
||||
await this.iq.request(xml("iq", { type: "set", to: this.account },
|
||||
xml("pubsub", { xmlns: PUBSUB }, xml("retract", { node }, xml("item", { id: itemId })))));
|
||||
} catch (error) {
|
||||
if (isItemNotFound(error)) return;
|
||||
if (isConflict(error)) throw new OmemoPepConflictError();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async configureOmemo2Nodes(): Promise<void> {
|
||||
await this.#configure(deviceListNode(OMEMO_2), "1");
|
||||
await this.#configure(bundleNode(OMEMO_2, 1), MAX_BUNDLE_ITEMS);
|
||||
}
|
||||
|
||||
async #fetch(node: string, itemId: string): Promise<OmemoPepItem | undefined> {
|
||||
let result: Element;
|
||||
try {
|
||||
result = await this.iq.request(xml("iq", { type: "get", to: this.account },
|
||||
xml("pubsub", { xmlns: PUBSUB }, xml("items", { node }, xml("item", { id: itemId })))));
|
||||
} catch (error) {
|
||||
if (isItemNotFound(error)) return undefined;
|
||||
throw error;
|
||||
}
|
||||
const pubsub = result.getChild("pubsub", PUBSUB);
|
||||
const items = pubsub?.getChild("items", PUBSUB);
|
||||
if (!pubsub || !items || items.attrs.node !== node) throw new Error("Malformed OMEMO PEP fetch response.");
|
||||
const entries = items.getChildren("item", PUBSUB);
|
||||
if (entries.length === 0) return undefined;
|
||||
if (entries.length !== 1 || entries[0]!.attrs.id !== itemId || entries[0]!.getChildElements().length !== 1) {
|
||||
throw new Error("Malformed OMEMO PEP item response.");
|
||||
}
|
||||
return { payload: entries[0]!.getChildElements()[0]!, revision: canonicalRevision(entries[0]!.getChildElements()[0]!) };
|
||||
}
|
||||
|
||||
async #publish(node: string, itemId: string, payload: Element, expectedRevision?: string): Promise<void> {
|
||||
if (expectedRevision !== undefined) {
|
||||
const current = await this.#fetch(node, itemId);
|
||||
if (current?.revision !== expectedRevision) throw new OmemoPepConflictError();
|
||||
}
|
||||
try {
|
||||
await this.iq.request(xml("iq", { type: "set", to: this.account },
|
||||
xml("pubsub", { xmlns: PUBSUB }, xml("publish", { node }, xml("item", { id: itemId }, payload)))));
|
||||
} catch (error) {
|
||||
if (isConflict(error)) throw new OmemoPepConflictError();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async #configure(node: string, maxItems: string): Promise<void> {
|
||||
await this.iq.request(xml("iq", { type: "set", to: this.account },
|
||||
xml("pubsub", { xmlns: PUBSUB_OWNER },
|
||||
xml("configure", { node },
|
||||
xml("x", { xmlns: DATA_FORMS, type: "submit" },
|
||||
field("FORM_TYPE", "http://jabber.org/protocol/pubsub#node_config", "hidden"),
|
||||
field("pubsub#access_model", "open"),
|
||||
field("pubsub#max_items", maxItems))))));
|
||||
}
|
||||
}
|
||||
|
||||
/** Handles PEP device events and restores this process's missing advertisement. */
|
||||
export class OmemoPepSession {
|
||||
readonly #publisher: OmemoPepPublisher;
|
||||
#reannouncing = new Map<OmemoVersion, Promise<void>>();
|
||||
readonly #retired = new Set<OmemoVersion>();
|
||||
readonly #retiring = new Set<OmemoVersion>();
|
||||
constructor(
|
||||
readonly adapter: XmppOmemoPepAdapter,
|
||||
readonly bundles: ReadonlyMap<OmemoVersion, OmemoPublishedBundle>,
|
||||
readonly devices: ReadonlyMap<OmemoVersion, Omit<OmemoDevice, "id">> = new Map(),
|
||||
retired: ReadonlySet<OmemoVersion> = new Set()
|
||||
) {
|
||||
this.#publisher = new OmemoPepPublisher({ adapter });
|
||||
for (const version of retired) this.#retired.add(version);
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
for (const bundle of this.bundles.values()) {
|
||||
if (!this.#retired.has(bundle.version)) await this.#publisher.publish(bundle, this.devices.get(bundle.version));
|
||||
}
|
||||
// Prosody creates PEP nodes on first publish. Configure the OMEMO 2 nodes
|
||||
// only after both payloads exist, while still completing before presence.
|
||||
if (this.bundles.has(OMEMO_2) && !this.#retired.has(OMEMO_2)) await this.adapter.configureOmemo2Nodes();
|
||||
}
|
||||
|
||||
async retire(version: OmemoVersion, deviceId: number): Promise<void> {
|
||||
if (this.#retiring.has(version)) throw new Error("OMEMO device retirement is already in progress.");
|
||||
this.#retired.add(version);
|
||||
this.#retiring.add(version);
|
||||
try {
|
||||
await this.#publisher.retire(version, deviceId);
|
||||
} finally {
|
||||
this.#retiring.delete(version);
|
||||
}
|
||||
}
|
||||
|
||||
async activate(version: OmemoVersion, expectedDeviceId: number): Promise<void> {
|
||||
const bundle = this.bundles.get(version);
|
||||
if (!bundle || bundle.deviceId !== expectedDeviceId) {
|
||||
throw new Error("OMEMO activation target does not match the local bundle.");
|
||||
}
|
||||
await this.#publisher.publish(bundle, this.devices.get(version));
|
||||
if (version === OMEMO_2) await this.adapter.configureOmemo2Nodes();
|
||||
this.#retired.delete(version);
|
||||
}
|
||||
|
||||
async handleEvent(stanza: Element): Promise<boolean> {
|
||||
const event = parseDeviceListEvent(stanza);
|
||||
if (!event) return false;
|
||||
// Only our own PEP service may cause this process to restore its local
|
||||
// advertisement. A contact can publish the same node names on their PEP
|
||||
// service and must not be able to trigger writes to our account.
|
||||
if (normalizeBareJid(String(stanza.attrs.from ?? "")) !== normalizeBareJid(this.adapter.account)) return true;
|
||||
if (this.#retiring.has(event.version) || this.#retired.has(event.version)) return true;
|
||||
const bundle = this.bundles.get(event.version);
|
||||
if (!bundle || event.devices.some((device) => device.id === bundle.deviceId)) return true;
|
||||
const pending = this.#reannouncing.get(event.version);
|
||||
if (pending) { await pending; return true; }
|
||||
const operation = this.#publisher.publish(bundle, this.devices.get(event.version));
|
||||
this.#reannouncing.set(event.version, operation);
|
||||
try { await operation; } finally { this.#reannouncing.delete(event.version); }
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseDeviceListEvent(stanza: Element): { version: OmemoVersion; devices: OmemoDevice[] } | undefined {
|
||||
if (!stanza.is("message") || (stanza.attrs.type !== undefined && stanza.attrs.type !== "headline")) return undefined;
|
||||
const event = stanza.getChild("event", PUBSUB_EVENT);
|
||||
if (!event) return undefined;
|
||||
const items = event.getChild("items", PUBSUB_EVENT);
|
||||
if (!items) return undefined;
|
||||
const version: OmemoVersion | undefined = items.attrs.node === deviceListNode(LEGACY_OMEMO)
|
||||
? LEGACY_OMEMO
|
||||
: items.attrs.node === deviceListNode(OMEMO_2)
|
||||
? OMEMO_2
|
||||
: undefined;
|
||||
if (!version) return undefined;
|
||||
const entries = items.getChildren("item", PUBSUB_EVENT);
|
||||
if (entries.length !== 1 || entries[0]!.attrs.id !== DEVICE_ITEM || entries[0]!.getChildElements().length !== 1) {
|
||||
throw new Error("Malformed OMEMO PEP device-list event.");
|
||||
}
|
||||
return { version, devices: parseDeviceList(version, entries[0]!.getChildElements()[0]!) };
|
||||
}
|
||||
|
||||
function field(name: string, value: string, type?: string): Element {
|
||||
return xml("field", { var: name, ...(type ? { type } : {}) }, xml("value", {}, value));
|
||||
}
|
||||
function canonicalRevision(payload: Element): string { return payload.toString(); }
|
||||
function errorElement(error: unknown): Element | undefined {
|
||||
const stanza = typeof error === "object" && error !== null && "stanza" in error ? (error as { stanza?: unknown }).stanza : undefined;
|
||||
return stanza && typeof stanza === "object" && "getChild" in stanza ? stanza as Element : undefined;
|
||||
}
|
||||
function isItemNotFound(error: unknown): boolean {
|
||||
return errorCondition(error) === "item-not-found" || Boolean(errorElement(error)?.getChild("error")?.getChild("item-not-found", STANZAS));
|
||||
}
|
||||
function isConflict(error: unknown): boolean {
|
||||
return errorCondition(error) === "conflict" || Boolean(errorElement(error)?.getChild("error")?.getChild("conflict", STANZAS));
|
||||
}
|
||||
function errorCondition(error: unknown): string | undefined {
|
||||
return typeof error === "object" && error !== null && "condition" in error && typeof (error as { condition?: unknown }).condition === "string"
|
||||
? (error as { condition: string }).condition
|
||||
: undefined;
|
||||
}
|
||||
+109
-1
@@ -2,6 +2,9 @@ import { createHash, randomUUID } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { client, xml } from "@xmpp/client";
|
||||
import { installDependencyGuards } from "./dep-guards.js";
|
||||
|
||||
installDependencyGuards();
|
||||
import type { Client, Options as XmppClientOptions } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
|
||||
@@ -21,6 +24,8 @@ import {
|
||||
type InboundXmppMessage,
|
||||
type SharedFileMetadata
|
||||
} from "./stanzas.js";
|
||||
import type { OmemoSession } from "./omemo/session.js";
|
||||
import type { OmemoIqCaller } from "./omemo/xmpp-pep.js";
|
||||
|
||||
export interface XmppTransportStatus {
|
||||
connected: boolean;
|
||||
@@ -31,6 +36,11 @@ export interface XmppTransportStatus {
|
||||
lastInboundAt?: number;
|
||||
lastOutboundAt?: number;
|
||||
lastError?: string | undefined;
|
||||
deliveryState?: "healthy" | "degraded" | "blocked";
|
||||
lastDeliveryError?: string | undefined;
|
||||
lastDeliveryFailureAt?: number;
|
||||
excludedDeviceCount?: number;
|
||||
pendingDeviceCount?: number;
|
||||
reconnectAttempts?: number;
|
||||
lastReconnectedAt?: number;
|
||||
streamManagement?: "enabled" | "resumed" | "failed" | "unavailable";
|
||||
@@ -73,6 +83,12 @@ export interface SentXmppMessage {
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface XmppTransportOptions {
|
||||
/** Required only when the explicit account OMEMO switch is enabled. */
|
||||
omemoSession?: OmemoSession;
|
||||
omemoSessionFactory?: (iq: OmemoIqCaller) => OmemoSession;
|
||||
}
|
||||
|
||||
type XmppCredentialsFactory = Extract<
|
||||
NonNullable<XmppClientOptions["credentials"]>,
|
||||
(...args: never[]) => unknown
|
||||
@@ -148,6 +164,7 @@ export class XmppTransport {
|
||||
#stopped = false;
|
||||
#probeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
#probeInFlight = false;
|
||||
readonly #omemoSession: OmemoSession | undefined;
|
||||
readonly #onReconnecting = () => {
|
||||
this.#clearProbeTimer();
|
||||
this.#updateStatus({
|
||||
@@ -160,6 +177,21 @@ export class XmppTransport {
|
||||
this.#updateStatus({ lastReconnectedAt: Date.now() });
|
||||
};
|
||||
readonly #onResumed = () => {
|
||||
if (this.#omemoSession) {
|
||||
this.#updateStatus({ connected: false, phase: "starting", streamManagement: "resumed" });
|
||||
void this.#omemoSession.resume(this.#omemoIo()).then(() => {
|
||||
this.#finishResume();
|
||||
}).catch(async (error) => {
|
||||
const message = `OMEMO recovery after stream resume failed: ${errorText(error, this.config.password)}`;
|
||||
this.#updateStatus({ connected: false, phase: "failed", lastError: message });
|
||||
this.handlers.log.error(`[${this.config.accountId}] ${message}`);
|
||||
await this.#xmpp.stop().catch(() => undefined);
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.#finishResume();
|
||||
};
|
||||
readonly #finishResume = () => {
|
||||
this.#updateStatus({
|
||||
connected: true,
|
||||
phase: "online",
|
||||
@@ -175,8 +207,17 @@ export class XmppTransport {
|
||||
|
||||
constructor(
|
||||
readonly config: XmppConnectionConfig,
|
||||
private readonly handlers: XmppTransportHandlers
|
||||
private readonly handlers: XmppTransportHandlers,
|
||||
private readonly options: XmppTransportOptions = {}
|
||||
) {
|
||||
if (options.omemoSession && options.omemoSessionFactory) {
|
||||
throw new Error("Provide either an OMEMO session or an OMEMO session factory, not both.");
|
||||
}
|
||||
if (Boolean(config.omemo?.enabled) !== Boolean(options.omemoSession || options.omemoSessionFactory)) {
|
||||
throw new Error(config.omemo?.enabled
|
||||
? "XMPP OMEMO is enabled but no assembled OMEMO session was provided."
|
||||
: "An OMEMO session was provided while XMPP OMEMO is disabled.");
|
||||
}
|
||||
this.#xmpp = client({
|
||||
service: config.service,
|
||||
domain: config.domain,
|
||||
@@ -185,6 +226,14 @@ export class XmppTransport {
|
||||
timeout: 15_000
|
||||
});
|
||||
const extensions = this.#extensions();
|
||||
this.#omemoSession = options.omemoSession ?? (
|
||||
options.omemoSessionFactory && extensions.iqCaller
|
||||
? options.omemoSessionFactory(extensions.iqCaller)
|
||||
: undefined
|
||||
);
|
||||
if (options.omemoSessionFactory && !this.#omemoSession) {
|
||||
throw new Error("XMPP OMEMO requires the IQ caller extension.");
|
||||
}
|
||||
if (extensions.reconnect) {
|
||||
extensions.reconnect.delay = config.reconnectDelayMs;
|
||||
extensions.reconnect.on("reconnecting", this.#onReconnecting);
|
||||
@@ -226,6 +275,17 @@ export class XmppTransport {
|
||||
lastError: undefined
|
||||
});
|
||||
handlers.log.info(`[${config.accountId}] XMPP connected as ${boundJid}`);
|
||||
if (this.#omemoSession) {
|
||||
try {
|
||||
await this.#omemoSession.initialize(this.#omemoIo());
|
||||
} catch (error) {
|
||||
const message = `OMEMO initialization failed: ${errorText(error, config.password)}`;
|
||||
this.#updateStatus({ connected: false, phase: "failed", lastError: message });
|
||||
handlers.log.error(`[${config.accountId}] ${message}`);
|
||||
await this.#xmpp.stop().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
}
|
||||
await this.#xmpp.send(xml("presence"));
|
||||
this.#scheduleProbe();
|
||||
});
|
||||
@@ -247,6 +307,10 @@ export class XmppTransport {
|
||||
return { ...this.#status };
|
||||
}
|
||||
|
||||
get omemoSession(): OmemoSession | undefined {
|
||||
return this.#omemoSession;
|
||||
}
|
||||
|
||||
async run(signal: AbortSignal): Promise<void> {
|
||||
const stop = () => {
|
||||
void this.stop();
|
||||
@@ -289,6 +353,7 @@ export class XmppTransport {
|
||||
extensions.streamManagement?.removeListener("resumed", this.#onResumed);
|
||||
extensions.streamManagement?.removeListener("fail", this.#onStreamManagementFail);
|
||||
await this.#xmpp.stop().catch(() => undefined);
|
||||
this.#omemoSession?.close();
|
||||
this.#updateStatus({
|
||||
connected: false,
|
||||
phase: "stopped",
|
||||
@@ -365,6 +430,29 @@ export class XmppTransport {
|
||||
} = {}
|
||||
): Promise<SentXmppMessage> {
|
||||
this.#assertConnected();
|
||||
if (this.#omemoSession) {
|
||||
if (options.oobUrl || options.sharedFile) {
|
||||
throw new Error("OMEMO media messages are not implemented; plaintext fallback is forbidden.");
|
||||
}
|
||||
try {
|
||||
const id = await this.#omemoSession.sendText(to, text);
|
||||
const excluded = this.#omemoSession.excludedDevices ?? [];
|
||||
this.#updateStatus({ lastOutboundAt: Date.now(),
|
||||
deliveryState: excluded.length ? "degraded" : "healthy",
|
||||
excludedDeviceCount: excluded.length,
|
||||
pendingDeviceCount: excluded.filter((item) => item.reason === "undecided").length,
|
||||
lastDeliveryError: undefined });
|
||||
return { id, to };
|
||||
} catch (error) {
|
||||
const excluded = this.#omemoSession.excludedDevices ?? [];
|
||||
this.#updateStatus({ deliveryState: "blocked", lastDeliveryFailureAt: Date.now(),
|
||||
excludedDeviceCount: excluded.length,
|
||||
pendingDeviceCount: excluded.filter((item) => item.reason === "undecided").length,
|
||||
lastDeliveryError: errorText(error, this.config.password) });
|
||||
await this.sendChatState(to, "active").catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const built = buildTextMessage({
|
||||
to,
|
||||
text,
|
||||
@@ -401,6 +489,9 @@ export class XmppTransport {
|
||||
}
|
||||
|
||||
async sendMedia(input: SendMediaInput): Promise<SentXmppMessage> {
|
||||
if (this.#omemoSession) {
|
||||
throw new Error("OMEMO media messages are not implemented; plaintext fallback is forbidden.");
|
||||
}
|
||||
const localPath = localPathFromMediaUrl(input.mediaUrl);
|
||||
if (!localPath) {
|
||||
const url = new URL(input.mediaUrl);
|
||||
@@ -484,6 +575,10 @@ export class XmppTransport {
|
||||
|
||||
async #handleStanza(stanza: Element): Promise<void> {
|
||||
try {
|
||||
if (this.#omemoSession && await this.#omemoSession.handleStanza(stanza)) {
|
||||
this.#updateStatus({ lastInboundAt: Date.now() });
|
||||
return;
|
||||
}
|
||||
const message = parseInboundMessage(stanza, this.config.jid);
|
||||
if (!message) {
|
||||
return;
|
||||
@@ -519,6 +614,19 @@ export class XmppTransport {
|
||||
return this.#xmpp as unknown as XmppClientExtensions;
|
||||
}
|
||||
|
||||
#omemoIo() {
|
||||
return {
|
||||
send: async (stanza: Element) => await this.#xmpp.send(stanza),
|
||||
dispatch: async (message: { id: string; from: string; text: string }) => await this.handlers.onMessage({
|
||||
id: message.id,
|
||||
from: message.from,
|
||||
fromBare: message.from,
|
||||
body: message.text,
|
||||
receiptRequested: false
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
#recordProbe(
|
||||
result: NonNullable<XmppTransportStatus["lastProbeResult"]>,
|
||||
latencyMs?: number
|
||||
|
||||
+11
-1
@@ -32,7 +32,8 @@ describe("XMPP account configuration", () => {
|
||||
jid: "bot@example.org",
|
||||
configured: true,
|
||||
dmPolicy: "allowlist",
|
||||
allowFrom: ["alice@example.org"]
|
||||
allowFrom: ["alice@example.org"],
|
||||
omemo: { enabled: false, profile: "legacy", trustMode: "manual" }
|
||||
});
|
||||
const connection = await resolveXmppConnectionConfig(cfg);
|
||||
expect(connection).toMatchObject({
|
||||
@@ -43,6 +44,15 @@ describe("XMPP account configuration", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("enables OMEMO only through an explicit bounded account policy", async () => {
|
||||
const cfg = { channels: { xmpp: {
|
||||
jid: "bot@example.org", password: "secret",
|
||||
omemo: { enabled: true, profile: "omemo2", trustMode: "tofu" }
|
||||
} } } as unknown as OpenClawConfig;
|
||||
expect(resolveXmppAccount(cfg).omemo).toEqual({ enabled: true, profile: "omemo2", trustMode: "tofu", deliveryPolicy: "strict-all" });
|
||||
expect((await resolveXmppConnectionConfig(cfg)).omemo).toEqual({ enabled: true, profile: "omemo2", trustMode: "tofu", deliveryPolicy: "strict-all" });
|
||||
});
|
||||
|
||||
it("supports named accounts and a configured default", () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
// Regression test for the stale-data parser crash:
|
||||
// socket "data" arriving after parser detach must not throw
|
||||
// "TypeError: Cannot read properties of null (reading 'write')".
|
||||
// The fix ships in the plugin (src/dep-guards.ts prototype wrapper), so it
|
||||
// survives dependency reinstalls by OpenClaw's managed installer.
|
||||
import Connection from "@xmpp/connection";
|
||||
import { installDependencyGuards } from "../src/dep-guards.js";
|
||||
|
||||
const Conn = Connection as unknown as new (domain: string) => any;
|
||||
|
||||
function makeConn(): any {
|
||||
installDependencyGuards();
|
||||
return new Conn("example.com");
|
||||
}
|
||||
|
||||
describe("XMPP stale-data guard (src/dep-guards.ts)", () => {
|
||||
it("ignores socket data after parser detach instead of throwing", () => {
|
||||
const c = makeConn();
|
||||
c.parser = null;
|
||||
expect(() => c._onData(Buffer.from("<stale/>"))).not.toThrow();
|
||||
});
|
||||
|
||||
it("still forwards data to a live parser", () => {
|
||||
const c = makeConn();
|
||||
const seen: string[] = [];
|
||||
c.parser = { write: (s: string) => seen.push(s) } as any;
|
||||
c._onData(Buffer.from("<live/>"));
|
||||
expect(seen).toEqual(["<live/>"]);
|
||||
});
|
||||
|
||||
it("is idempotent and wraps the prototype exactly once", () => {
|
||||
installDependencyGuards();
|
||||
const c = makeConn();
|
||||
const seen: string[] = [];
|
||||
c.parser = { write: (s: string) => seen.push(s) } as any;
|
||||
c._onData(Buffer.from("<x/>"));
|
||||
expect(seen).toEqual(["<x/>"]);
|
||||
expect((Connection.prototype as any).__openclawStaleDataGuardInstalled).toBe(true);
|
||||
});
|
||||
});
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
// Node's built-in type stripper executes this crash fixture directly. The
|
||||
// production build continues to use NodeNext's emitted `.js` specifiers.
|
||||
// @ts-expect-error TypeScript disallows source `.ts` imports without an emit-specific option.
|
||||
const { OmemoTransactionalStore } = await import("../../src/omemo/store.ts");
|
||||
|
||||
const [stateDirectory, direction, crashPoint] = process.argv.slice(2);
|
||||
if (!stateDirectory || !direction || !crashPoint) throw new Error("Missing crash-worker arguments.");
|
||||
|
||||
const store = new OmemoTransactionalStore({
|
||||
stateDirectory,
|
||||
clock: () => 777,
|
||||
faultInjector(point) {
|
||||
if (point === crashPoint) process.kill(process.pid, "SIGKILL");
|
||||
}
|
||||
});
|
||||
|
||||
if (direction === "outbound") {
|
||||
await store.outbound("account", "outbound", "peer", async (view) => {
|
||||
view.set("session", "peer:1", Buffer.from("outbound-ratchet"));
|
||||
return Buffer.from("exact-outbound-ciphertext");
|
||||
});
|
||||
} else if (direction === "inbound") {
|
||||
await store.inbound("account", "inbound", "peer", async (view) => {
|
||||
view.set("session", "peer:1", Buffer.from("inbound-ratchet"));
|
||||
return Buffer.from("pending-inbound-plaintext");
|
||||
});
|
||||
} else {
|
||||
throw new Error(`Unknown direction: ${direction}`);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { handleOmemoOperatorCommand } from "../src/omemo/command.js";
|
||||
import { LEGACY_OMEMO } from "../src/omemo/engine.js";
|
||||
import { registerLiveTransport, resetLiveTransportsForTests } from "../src/transport.js";
|
||||
|
||||
afterEach(() => resetLiveTransportsForTests());
|
||||
|
||||
function context(args: string, senderIsOwner = true) {
|
||||
return { args, senderIsOwner, isAuthorizedSender: true, channel: "webchat", commandBody: `/xmpp-omemo ${args}` } as never;
|
||||
}
|
||||
|
||||
describe("OMEMO operator command", () => {
|
||||
it("offers short approvals only to an authenticated non-XMPP owner", async () => {
|
||||
const reviewPending = vi.fn(async () => [{ address: "peer@example.org.1", fingerprint: "a".repeat(64), firstObservedAt: 1, code: "abcdefghijklmnop" }]);
|
||||
const approveReview = vi.fn(async () => ({ state: "trusted", fingerprint: "a".repeat(64) }));
|
||||
registerLiveTransport("default", { status: { connected: true }, omemoSession: { reviewPending, approveReview, deliveryPolicy: "trusted-devices" } } as never);
|
||||
const owner = { args: "review default", senderIsOwner: true, senderId: "owner", isAuthorizedSender: true, channel: "matrix" };
|
||||
expect((await handleOmemoOperatorCommand(owner as never)).text).toContain("approve default abcdefghijklmnop");
|
||||
expect((await handleOmemoOperatorCommand({ ...owner, args: "approve default abcdefghijklmnop" } as never)).text).toContain("not fingerprint-verified");
|
||||
reviewPending.mockClear(); approveReview.mockClear();
|
||||
for (const args of ["review default", "approve default abcdefghijklmnop"]) {
|
||||
expect((await handleOmemoOperatorCommand({ ...owner, channel: "xmpp", args } as never)).text).toContain("sender-device provenance");
|
||||
await handleOmemoOperatorCommand({ ...owner, senderIsOwner: false, args } as never);
|
||||
}
|
||||
expect(reviewPending).not.toHaveBeenCalled(); expect(approveReview).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a controlled failure for malformed argument input", async () => {
|
||||
const result = await handleOmemoOperatorCommand(context(`list default ${"x".repeat(1025)}`));
|
||||
expect(result.text).toBe("OMEMO operator command failed: Invalid OMEMO operator command arguments.");
|
||||
});
|
||||
|
||||
it("is owner-gated and drives exact trust and local-retirement operations", async () => {
|
||||
const inspectTrust = vi.fn(async () => [{
|
||||
address: "bob@example.org.9",
|
||||
state: "undecided" as const,
|
||||
fingerprint: "aaaaaaaa bbbbbbbb cccccccc dddddddd eeeeeeee ffffffff 00000000 11111111",
|
||||
firstObservedAt: 1,
|
||||
lastObservedAt: 2
|
||||
}]);
|
||||
const transitionTrust = vi.fn(async () => ({
|
||||
state: "verified" as const, fingerprint: "aaaaaaaa bbbbbbbb cccccccc dddddddd eeeeeeee ffffffff 00000000 11111111", firstObservedAt: 1, lastObservedAt: 2
|
||||
}));
|
||||
const retireLocalDevice = vi.fn(async () => undefined);
|
||||
const activateLocalDevice = vi.fn(async () => undefined);
|
||||
registerLiveTransport("default", {
|
||||
status: { connected: true },
|
||||
omemoSession: { inspectTrust, transitionTrust, retireLocalDevice, activateLocalDevice }
|
||||
} as never);
|
||||
|
||||
expect((await handleOmemoOperatorCommand(context("list default", false))).text).toContain("Gateway owner");
|
||||
expect((await handleOmemoOperatorCommand(context("list default"))).text).toContain("bob@example.org.9 undecided");
|
||||
const fingerprint = "aaaaaaaabbbbbbbbccccccccddddddddeeeeeeeeffffffff0000000011111111";
|
||||
await handleOmemoOperatorCommand(context(`trust default bob@example.org.9 undecided ${fingerprint} verified`));
|
||||
expect(transitionTrust).toHaveBeenCalledWith(
|
||||
"bob@example.org.9",
|
||||
{ state: "undecided", fingerprint: "aaaaaaaa bbbbbbbb cccccccc dddddddd eeeeeeee ffffffff 00000000 11111111" },
|
||||
"verified"
|
||||
);
|
||||
await handleOmemoOperatorCommand(context("retire-device default legacy 8123"));
|
||||
expect(retireLocalDevice).toHaveBeenCalledWith(LEGACY_OMEMO, 8123);
|
||||
await handleOmemoOperatorCommand(context("activate-device default legacy 8123"));
|
||||
expect(activateLocalDevice).toHaveBeenCalledWith(LEGACY_OMEMO, 8123);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
LEGACY_OMEMO,
|
||||
OMEMO_2,
|
||||
OmemoEngine,
|
||||
type LibomemoEngineBindings,
|
||||
type OmemoRemoteBundle,
|
||||
type OmemoVersion
|
||||
} from "../src/omemo/engine.js";
|
||||
import { LibomemoStoreAdapter, type LibomemoKeyPair } from "../src/omemo/libomemo-store.js";
|
||||
import { OmemoTransactionalStore } from "../src/omemo/store.js";
|
||||
|
||||
function keyPair(seed: number): LibomemoKeyPair {
|
||||
const pub = new Uint8Array(33);
|
||||
pub[0] = 5;
|
||||
pub.fill(seed & 0xff, 1);
|
||||
const priv = new Uint8Array(32);
|
||||
priv.fill((seed + 1) & 0xff);
|
||||
return { pubKey: pub.buffer, privKey: priv.buffer };
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
let generated = 0;
|
||||
const sessions: Array<{ address: string; version: OmemoVersion }> = [];
|
||||
const bindings: LibomemoEngineBindings = {
|
||||
keyHelper: {
|
||||
async generateIdentityKeyPair() { generated++; return keyPair(240); },
|
||||
generateRegistrationId() { return 8123; },
|
||||
async generatePreKey(id) { generated++; return { keyId: id, keyPair: keyPair(id) }; },
|
||||
async generateSignedPreKey(_identity, id, version) {
|
||||
generated++;
|
||||
const signature = new Uint8Array(64);
|
||||
signature[0] = version === LEGACY_OMEMO ? 1 : 2;
|
||||
signature[1] = id;
|
||||
return {
|
||||
keyId: id,
|
||||
keyPair: keyPair(id),
|
||||
signature: signature.buffer
|
||||
};
|
||||
}
|
||||
},
|
||||
async curvePubKeyToEd25519PubKey(publicKey) { return publicKey.slice(1); },
|
||||
createSessionBuilder(store, address, version) {
|
||||
return {
|
||||
async processPreKey(bundle) {
|
||||
store.isTrustedIdentity(address, bundle.identityKey, 1);
|
||||
store.storeSession(address, JSON.stringify({ version, registrationId: bundle.registrationId }));
|
||||
sessions.push({ address, version });
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
return { bindings, sessions, generated: () => generated };
|
||||
}
|
||||
|
||||
function openStore(directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-engine-"))) {
|
||||
return { directory, store: new OmemoTransactionalStore({ stateDirectory: directory }) };
|
||||
}
|
||||
|
||||
describe("OmemoEngine", () => {
|
||||
it("atomically initializes one stable device and profile-specific bundles", async () => {
|
||||
const { directory, store } = openStore();
|
||||
const state = fixture();
|
||||
const engine = new OmemoEngine({
|
||||
account: "alice@example.org",
|
||||
store,
|
||||
bindings: state.bindings,
|
||||
trustMode: "tofu",
|
||||
preKeyTarget: 4,
|
||||
preKeyLowWatermark: 1,
|
||||
clock: () => 1000
|
||||
});
|
||||
|
||||
const first = await engine.initialize();
|
||||
expect(first[LEGACY_OMEMO].deviceId).toBe(8123);
|
||||
expect(first[LEGACY_OMEMO].identityKey.byteLength).toBe(33);
|
||||
expect(first[OMEMO_2].identityKey.byteLength).toBe(32);
|
||||
expect(new Uint8Array(first[LEGACY_OMEMO].signedPreKey.signature).slice(0, 2)).toEqual(Uint8Array.of(1, 1));
|
||||
expect(new Uint8Array(first[OMEMO_2].signedPreKey.signature).slice(0, 2)).toEqual(Uint8Array.of(2, 6));
|
||||
expect(first[LEGACY_OMEMO].preKeys).toHaveLength(4);
|
||||
expect(first[OMEMO_2].preKeys).toHaveLength(4);
|
||||
expect(first[LEGACY_OMEMO].preKeys[0]?.publicKey.byteLength).toBe(33);
|
||||
expect(first[OMEMO_2].preKeys[0]?.publicKey.byteLength).toBe(32);
|
||||
expect(state.generated()).toBe(11);
|
||||
store.close();
|
||||
|
||||
const reopened = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const restarted = new OmemoEngine({
|
||||
account: "alice@example.org",
|
||||
store: reopened,
|
||||
bindings: state.bindings,
|
||||
trustMode: "tofu",
|
||||
preKeyTarget: 4,
|
||||
preKeyLowWatermark: 1,
|
||||
clock: () => 1000
|
||||
});
|
||||
const second = await restarted.initialize();
|
||||
expect(second).toEqual(first);
|
||||
expect(state.generated()).toBe(11);
|
||||
reopened.close();
|
||||
});
|
||||
|
||||
it("replenishes only at the low watermark and never reuses consumed IDs", async () => {
|
||||
const { store } = openStore();
|
||||
const state = fixture();
|
||||
const options = {
|
||||
account: "alice@example.org", store, bindings: state.bindings, trustMode: "tofu" as const,
|
||||
preKeyTarget: 3, preKeyLowWatermark: 1, clock: () => 1000
|
||||
};
|
||||
const engine = new OmemoEngine(options);
|
||||
const initial = await engine.initialize();
|
||||
const ids = initial[LEGACY_OMEMO].preKeys.map((key) => key.id);
|
||||
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
adapter.removePreKey(ids[0]!);
|
||||
});
|
||||
const aboveWatermark = await engine.maintainKeys();
|
||||
expect(aboveWatermark[LEGACY_OMEMO].preKeys.map((key) => key.id)).toEqual(ids.slice(1));
|
||||
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
adapter.removePreKey(ids[1]!);
|
||||
});
|
||||
const replenished = await engine.maintainKeys();
|
||||
const replenishedIds = replenished[LEGACY_OMEMO].preKeys.map((key) => key.id);
|
||||
expect(replenishedIds).toHaveLength(3);
|
||||
expect(replenishedIds).toContain(ids[2]);
|
||||
expect(Math.min(...replenishedIds.filter((id) => !ids.includes(id)))).toBeGreaterThan(Math.max(...ids));
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("rotates aged signed prekeys while retaining the previous inbound key", async () => {
|
||||
let now = 1000;
|
||||
const { store } = openStore();
|
||||
const state = fixture();
|
||||
const engine = new OmemoEngine({
|
||||
account: "alice@example.org", store, bindings: state.bindings, trustMode: "tofu",
|
||||
preKeyTarget: 2, preKeyLowWatermark: 1, signedPreKeyMaxAgeMs: 100,
|
||||
retainedSignedPreKeys: 2, clock: () => now
|
||||
});
|
||||
const first = await engine.initialize();
|
||||
const oldId = first[LEGACY_OMEMO].signedPreKey.id;
|
||||
now = 1100;
|
||||
const second = await engine.maintainKeys();
|
||||
expect(second[LEGACY_OMEMO].signedPreKey.id).not.toBe(oldId);
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
expect(new LibomemoStoreAdapter(view, { mode: "tofu" }).loadSignedPreKey(oldId)).toBeDefined();
|
||||
});
|
||||
now = 1200;
|
||||
await engine.maintainKeys();
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
expect(new LibomemoStoreAdapter(view, { mode: "tofu" }).loadSignedPreKey(oldId)).toBeUndefined();
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("constructs sessions within the transactional view and persists them", async () => {
|
||||
const { directory, store } = openStore();
|
||||
const state = fixture();
|
||||
const engine = new OmemoEngine({
|
||||
account: "alice@example.org", store, bindings: state.bindings, trustMode: "tofu",
|
||||
preKeyTarget: 2, preKeyLowWatermark: 1
|
||||
});
|
||||
await engine.initialize();
|
||||
const remote: OmemoRemoteBundle = {
|
||||
identityKey: keyPair(90).pubKey,
|
||||
registrationId: 9,
|
||||
signedPreKey: { keyId: 1, publicKey: keyPair(91).pubKey, signature: Uint8Array.of(1).buffer }
|
||||
};
|
||||
await engine.buildSession("bob@example.org.9", LEGACY_OMEMO, remote);
|
||||
expect(state.sessions).toEqual([{ address: "bob@example.org.9", version: LEGACY_OMEMO }]);
|
||||
store.close();
|
||||
|
||||
const reopened = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
await reopened.updateRecords("alice@example.org", (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
expect(adapter.loadSession("bob@example.org.9")).toContain(LEGACY_OMEMO);
|
||||
expect(adapter.trust.get("bob@example.org.9")?.state).toBe("trusted");
|
||||
});
|
||||
reopened.close();
|
||||
});
|
||||
|
||||
it("fails closed on partial local identity state and invalid lifecycle settings", async () => {
|
||||
const { store } = openStore();
|
||||
const state = fixture();
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
new LibomemoStoreAdapter(view, { mode: "tofu" }).put("registrationId", 3);
|
||||
});
|
||||
const engine = new OmemoEngine({
|
||||
account: "alice@example.org", store, bindings: state.bindings, trustMode: "tofu",
|
||||
preKeyTarget: 2, preKeyLowWatermark: 1
|
||||
});
|
||||
await expect(engine.initialize()).rejects.toThrow("Corrupt OMEMO local identity");
|
||||
expect(() => new OmemoEngine({
|
||||
account: "alice@example.org", store, bindings: state.bindings, trustMode: "tofu",
|
||||
preKeyTarget: 2, preKeyLowWatermark: 2
|
||||
})).toThrow("low watermark");
|
||||
store.close();
|
||||
});
|
||||
|
||||
it.each([LEGACY_OMEMO, OMEMO_2] as const)(
|
||||
"builds and uses a real maintained-fork session for %s",
|
||||
async (version) => {
|
||||
const lib = await import("libomemo.js") as Record<string, any>;
|
||||
const bindings: LibomemoEngineBindings = {
|
||||
keyHelper: lib.KeyHelper,
|
||||
curvePubKeyToEd25519PubKey: lib.curvePubKeyToEd25519PubKey,
|
||||
createSessionBuilder: (store, address, profile) => new lib.SessionBuilder(store, address, profile)
|
||||
};
|
||||
const alice = openStore();
|
||||
const bob = openStore();
|
||||
const aliceEngine = new OmemoEngine({
|
||||
account: "alice@example.org", store: alice.store, bindings, trustMode: "tofu",
|
||||
preKeyTarget: 2, preKeyLowWatermark: 1
|
||||
});
|
||||
const bobEngine = new OmemoEngine({
|
||||
account: "bob@example.org", store: bob.store, bindings, trustMode: "tofu",
|
||||
preKeyTarget: 2, preKeyLowWatermark: 1
|
||||
});
|
||||
await aliceEngine.initialize();
|
||||
const bobBundle = (await bobEngine.initialize())[version];
|
||||
const oneTime = bobBundle.preKeys[0]!;
|
||||
await aliceEngine.buildSession("bob@example.org.8123", version, {
|
||||
identityKey: bobBundle.identityKey,
|
||||
registrationId: bobBundle.deviceId,
|
||||
signedPreKey: {
|
||||
keyId: bobBundle.signedPreKey.id,
|
||||
publicKey: bobBundle.signedPreKey.publicKey,
|
||||
signature: bobBundle.signedPreKey.signature
|
||||
},
|
||||
preKey: { keyId: oneTime.id, publicKey: oneTime.publicKey }
|
||||
});
|
||||
|
||||
const encrypted = await alice.store.updateRecords("alice@example.org", async (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
return new lib.SessionCipher(adapter, "bob@example.org.8123", version)
|
||||
.encrypt(new TextEncoder().encode("engine-round-trip").buffer);
|
||||
});
|
||||
const decrypted = await bob.store.updateRecords("bob@example.org", async (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
const cipher = new lib.SessionCipher(adapter, "alice@example.org.8123", version);
|
||||
return cipher.decryptPreKeyWhisperMessage(encrypted.body, "binary");
|
||||
});
|
||||
expect(new TextDecoder().decode(decrypted.plaintext)).toBe("engine-round-trip");
|
||||
const maintained = await bobEngine.maintainKeys();
|
||||
expect(maintained[version].preKeys.map((key) => key.id)).not.toContain(oneTime.id);
|
||||
alice.store.close();
|
||||
bob.store.close();
|
||||
},
|
||||
30_000
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { mkdtempSync, statSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveOmemoStateDirectory } from "../src/omemo/factory.js";
|
||||
|
||||
describe("production OMEMO factory state ownership", () => {
|
||||
it("uses a private, traversal-safe, stable directory for each account", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "openclaw-state-"));
|
||||
const first = resolveOmemoStateDirectory(root, "../../Personal Account");
|
||||
const again = resolveOmemoStateDirectory(root, "../../Personal Account");
|
||||
const other = resolveOmemoStateDirectory(root, "personal-account");
|
||||
|
||||
expect(first).toBe(again);
|
||||
expect(other).not.toBe(first);
|
||||
expect(relative(root, first)).not.toMatch(/^\.\./);
|
||||
expect(first.endsWith("/omemo")).toBe(true);
|
||||
for (let current = first; current !== root; current = dirname(current)) {
|
||||
expect(statSync(current).mode & 0o777).toBe(0o700);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,287 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
formatIdentityFingerprint,
|
||||
LibomemoStoreAdapter,
|
||||
OmemoIdentityChangedError,
|
||||
OmemoTrustConflictError,
|
||||
OmemoTrustError,
|
||||
type LibomemoKeyPair
|
||||
} from "../src/omemo/libomemo-store.js";
|
||||
import { OmemoTransactionalStore } from "../src/omemo/store.js";
|
||||
|
||||
const ACCOUNT = "account";
|
||||
const ADDRESS = "peer@example.test.7";
|
||||
const directories: string[] = [];
|
||||
|
||||
function temporaryState(): string {
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-xmpp-libomemo-"));
|
||||
directories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
|
||||
function bytes(length: number, fill: number): ArrayBuffer {
|
||||
return Uint8Array.from({ length }, (_, index) => index === 0 && length === 33 ? 0x05 : fill).buffer;
|
||||
}
|
||||
|
||||
function keyPair(fill: number): LibomemoKeyPair {
|
||||
return { pubKey: bytes(33, fill), privKey: bytes(32, fill + 1) };
|
||||
}
|
||||
|
||||
function identity(fill: number, modern = false): ArrayBuffer {
|
||||
return bytes(modern ? 32 : 33, fill);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("LibomemoStoreAdapter", () => {
|
||||
it("persists the exact libomemo.js key, session, and initialization callbacks", async () => {
|
||||
const stateDirectory = temporaryState();
|
||||
let store = new OmemoTransactionalStore({ stateDirectory });
|
||||
const localIdentity = keyPair(11);
|
||||
const preKey = keyPair(21);
|
||||
const signedPreKey = keyPair(31);
|
||||
|
||||
await store.updateRecords(ACCOUNT, async (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
callbacks.put("identityKey", localIdentity);
|
||||
callbacks.put("registrationId", 1337);
|
||||
callbacks.storePreKey("04", preKey);
|
||||
callbacks.storeSignedPreKey(5, signedPreKey);
|
||||
callbacks.storeSession(ADDRESS, "serialized-session");
|
||||
callbacks.storeSession("other@example.test.8", "other-session");
|
||||
expect(callbacks.store).toEqual({});
|
||||
});
|
||||
store.close();
|
||||
|
||||
store = new OmemoTransactionalStore({ stateDirectory });
|
||||
await store.updateRecords(ACCOUNT, async (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
expect(new Uint8Array(callbacks.getIdentityKeyPair()!.pubKey)).toEqual(new Uint8Array(localIdentity.pubKey));
|
||||
expect(callbacks.get<number>("registrationId")).toBe(1337);
|
||||
expect(new Uint8Array((await callbacks.loadPreKey("04"))!.keyPair.privKey)).toEqual(
|
||||
new Uint8Array(preKey.privKey)
|
||||
);
|
||||
expect(new Uint8Array(callbacks.loadSignedPreKey(5)!.keyPair.pubKey)).toEqual(
|
||||
new Uint8Array(signedPreKey.pubKey)
|
||||
);
|
||||
expect(callbacks.loadSession(ADDRESS)).toBe("serialized-session");
|
||||
callbacks.removePreKey("04");
|
||||
callbacks.removeSignedPreKey("5");
|
||||
callbacks.removeAllSessions("peer@example.test");
|
||||
expect(await callbacks.loadPreKey("04")).toBeUndefined();
|
||||
expect(callbacks.loadSignedPreKey(5)).toBeUndefined();
|
||||
expect(callbacks.loadSession(ADDRESS)).toBeUndefined();
|
||||
expect(callbacks.loadSession("other@example.test.8")).toBe("other-session");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("commits callback mutations with the exact outbound stanza", async () => {
|
||||
const stateDirectory = temporaryState();
|
||||
let store = new OmemoTransactionalStore({ stateDirectory, clock: () => 40 });
|
||||
|
||||
await store.outbound(ACCOUNT, "message-1", "peer@example.test", async (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu", clock: () => 30 });
|
||||
callbacks.storeSession(ADDRESS, "ratchet-state");
|
||||
return Buffer.from("<encrypted>exact</encrypted>");
|
||||
});
|
||||
store.close();
|
||||
|
||||
store = new OmemoTransactionalStore({ stateDirectory });
|
||||
expect(store.listOutbound(ACCOUNT)[0]?.stanza.toString()).toBe("<encrypted>exact</encrypted>");
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
expect(new LibomemoStoreAdapter(view, { mode: "tofu" }).loadSession(ADDRESS)).toBe("ratchet-state");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("applies TOFU on first sight without claiming verification", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
const remoteIdentity = identity(41);
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu", clock: () => 100 });
|
||||
expect(callbacks.isTrustedIdentity(ADDRESS, remoteIdentity, 1)).toBe(true);
|
||||
expect(callbacks.saveIdentity(ADDRESS, remoteIdentity)).toBe(false);
|
||||
expect(callbacks.trust.get(ADDRESS)).toEqual({
|
||||
state: "trusted",
|
||||
fingerprint: formatIdentityFingerprint(remoteIdentity),
|
||||
firstObservedAt: 100,
|
||||
lastObservedAt: 100
|
||||
});
|
||||
});
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const record = new LibomemoStoreAdapter(view, { mode: "tofu", clock: () => 150 })
|
||||
.trust.observeIdentity(ADDRESS, remoteIdentity);
|
||||
expect(record.state).toBe("trusted");
|
||||
expect(record.lastObservedAt).toBe(150);
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("blocks manual-trust identities until an exact compare-and-set decision", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
const remoteIdentity = identity(51, true);
|
||||
let observedFingerprint = "";
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const record = new LibomemoStoreAdapter(view, { mode: "manual", clock: () => 200 })
|
||||
.trust.observeIdentity(ADDRESS, remoteIdentity);
|
||||
expect(record.state).toBe("undecided");
|
||||
observedFingerprint = record.fingerprint;
|
||||
});
|
||||
|
||||
await expect(store.outbound(ACCOUNT, "blocked", "peer@example.test", async (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "manual", clock: () => 201 });
|
||||
callbacks.isTrustedIdentity(ADDRESS, remoteIdentity, 1);
|
||||
return Buffer.from("must-not-send");
|
||||
})).rejects.toMatchObject({
|
||||
name: "OmemoTrustError",
|
||||
code: "OMEMO_IDENTITY_NOT_TRUSTED",
|
||||
state: "undecided",
|
||||
direction: 1
|
||||
} satisfies Partial<OmemoTrustError>);
|
||||
expect(store.listOutbound(ACCOUNT)).toEqual([]);
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const trust = new LibomemoStoreAdapter(view, { mode: "manual" }).trust;
|
||||
expect(() => trust.transition(ADDRESS, {
|
||||
state: "trusted",
|
||||
fingerprint: observedFingerprint
|
||||
}, "verified")).toThrow(OmemoTrustConflictError);
|
||||
expect(trust.transition(ADDRESS, {
|
||||
state: "undecided",
|
||||
fingerprint: observedFingerprint
|
||||
}, "verified").state).toBe("verified");
|
||||
});
|
||||
|
||||
await store.outbound(ACCOUNT, "allowed", "peer@example.test", async (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "manual", clock: () => 202 });
|
||||
expect(callbacks.isTrustedIdentity(ADDRESS, remoteIdentity, 1)).toBe(true);
|
||||
return Buffer.from("ciphertext");
|
||||
});
|
||||
expect(store.listOutbound(ACCOUNT).map(({ id }) => id)).toEqual(["allowed"]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("hard-fails identity changes without replacing trusted state", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
const originalIdentity = identity(61);
|
||||
const changedIdentity = identity(62);
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
new LibomemoStoreAdapter(view, { mode: "tofu", clock: () => 300 })
|
||||
.trust.observeIdentity(ADDRESS, originalIdentity);
|
||||
});
|
||||
|
||||
await expect(store.outbound(ACCOUNT, "changed", "peer@example.test", async (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu", clock: () => 301 });
|
||||
callbacks.isTrustedIdentity(ADDRESS, changedIdentity, 2);
|
||||
return Buffer.from("must-not-send");
|
||||
})).rejects.toMatchObject({
|
||||
name: "OmemoIdentityChangedError",
|
||||
code: "OMEMO_IDENTITY_CHANGED",
|
||||
previousFingerprint: formatIdentityFingerprint(originalIdentity),
|
||||
observedFingerprint: formatIdentityFingerprint(changedIdentity)
|
||||
} satisfies Partial<OmemoIdentityChangedError>);
|
||||
expect(store.listOutbound(ACCOUNT)).toEqual([]);
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
expect(new Uint8Array(callbacks.loadIdentityKey(ADDRESS)!)).toEqual(new Uint8Array(originalIdentity));
|
||||
expect(callbacks.trust.get(ADDRESS)?.fingerprint).toBe(formatIdentityFingerprint(originalIdentity));
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("requires exact prior trust when accepting a replacement and deletes the old session", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
const originalIdentity = identity(71);
|
||||
const replacementIdentity = identity(72, true);
|
||||
let originalFingerprint = "";
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu", clock: () => 400 });
|
||||
const original = callbacks.trust.observeIdentity(ADDRESS, originalIdentity);
|
||||
originalFingerprint = original.fingerprint;
|
||||
callbacks.storeSession(ADDRESS, "old-ratchet");
|
||||
});
|
||||
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu", clock: () => 500 });
|
||||
expect(() => callbacks.trust.replaceIdentity(ADDRESS, {
|
||||
state: "verified",
|
||||
fingerprint: originalFingerprint
|
||||
}, replacementIdentity, formatIdentityFingerprint(replacementIdentity))).toThrow(OmemoTrustConflictError);
|
||||
expect(() => callbacks.trust.replaceIdentity(ADDRESS, {
|
||||
state: "trusted",
|
||||
fingerprint: originalFingerprint
|
||||
}, replacementIdentity, formatIdentityFingerprint(identity(99)))).toThrow(OmemoTrustConflictError);
|
||||
const replacement = callbacks.trust.replaceIdentity(ADDRESS, {
|
||||
state: "trusted",
|
||||
fingerprint: originalFingerprint
|
||||
}, replacementIdentity, formatIdentityFingerprint(replacementIdentity), "undecided");
|
||||
expect(replacement).toEqual({
|
||||
state: "undecided",
|
||||
fingerprint: formatIdentityFingerprint(replacementIdentity),
|
||||
firstObservedAt: 500,
|
||||
lastObservedAt: 500
|
||||
});
|
||||
expect(callbacks.loadSession(ADDRESS)).toBeUndefined();
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("stages a reviewable replacement candidate without changing identity or trust", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
const originalIdentity = identity(81);
|
||||
const candidateIdentity = identity(82);
|
||||
const originalFingerprint = formatIdentityFingerprint(originalIdentity);
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const trust = new LibomemoStoreAdapter(view, { mode: "manual", clock: () => 600 }).trust;
|
||||
trust.observeIdentity(ADDRESS, originalIdentity);
|
||||
const candidate = trust.stageCandidate(ADDRESS, originalFingerprint, candidateIdentity);
|
||||
expect(candidate.observedFingerprint).toBe(formatIdentityFingerprint(candidateIdentity));
|
||||
expect(trust.get(ADDRESS)?.fingerprint).toBe(originalFingerprint);
|
||||
});
|
||||
await store.updateRecords(ACCOUNT, (view) => {
|
||||
const trust = new LibomemoStoreAdapter(view, { mode: "manual", clock: () => 700 }).trust;
|
||||
const candidate = trust.candidate(ADDRESS)!;
|
||||
expect(candidate.observedAt).toBe(600);
|
||||
trust.replaceIdentity(
|
||||
ADDRESS,
|
||||
{ state: "undecided", fingerprint: originalFingerprint },
|
||||
candidate.identityKey,
|
||||
candidate.observedFingerprint,
|
||||
"verified"
|
||||
);
|
||||
expect(trust.candidate(ADDRESS)).toBeUndefined();
|
||||
expect(trust.get(ADDRESS)?.state).toBe("verified");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("fails closed on malformed callback records and invalid key material", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
await store.updateRecords(ACCOUNT, (view) => view.set("session", ADDRESS, Uint8Array.of(0xff)));
|
||||
await expect(store.updateRecords(ACCOUNT, (view) => {
|
||||
new LibomemoStoreAdapter(view, { mode: "tofu" }).loadSession(ADDRESS);
|
||||
})).rejects.toThrow("Corrupt OMEMO session record encoding");
|
||||
await expect(store.updateRecords(ACCOUNT, (view) => {
|
||||
const callbacks = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
callbacks.put("identityKey", { pubKey: bytes(32, 1), privKey: bytes(32, 2) });
|
||||
})).rejects.toThrow("Invalid OMEMO public key length");
|
||||
await expect(store.updateRecords(ACCOUNT, (view) => {
|
||||
new LibomemoStoreAdapter(view, { mode: "tofu" }).get("arbitrary-key");
|
||||
})).rejects.toThrow("Unsupported libomemo.js generic store key");
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,361 @@
|
||||
import { createDecipheriv, createHmac, hkdfSync } from "node:crypto";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { Element } from "@xmpp/xml";
|
||||
import { parse as parseXml } from "ltx";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { LEGACY_OMEMO, OMEMO_2 } from "../src/omemo/engine.js";
|
||||
import { OmemoInboundCoordinator, OmemoOutboundCoordinator, parseEncryptedEnvelope, serializeEncryptedEnvelope, type OmemoEncryptedEnvelope, type OmemoInboundBindings, type OmemoOutboundBindings } from "../src/omemo/message.js";
|
||||
import { LibomemoStoreAdapter } from "../src/omemo/libomemo-store.js";
|
||||
import { OmemoTransactionalStore } from "../src/omemo/store.js";
|
||||
|
||||
function parse(value: string): Element {
|
||||
return parseXml(value);
|
||||
}
|
||||
function binary(value: Uint8Array): string { return String.fromCharCode(...value); }
|
||||
function fixture() {
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-message-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory, clock: () => 1000 });
|
||||
const encryptedAddresses: string[] = [];
|
||||
const bindings: OmemoOutboundBindings = {
|
||||
createSessionCipher(adapter, address, version) {
|
||||
return { async encrypt(plaintext) {
|
||||
encryptedAddresses.push(address);
|
||||
adapter.storeSession(address, `advanced:${version}:${encryptedAddresses.length}`);
|
||||
return { type: address.endsWith(".9") ? 3 : 1, body: binary(plaintext), ...(version === OMEMO_2 && address.endsWith(".9") ? { kex: true } : {}) };
|
||||
} };
|
||||
}
|
||||
};
|
||||
const coordinator = new OmemoOutboundCoordinator({
|
||||
account: "alice@example.org", localDeviceId: 7, store, bindings, trustMode: "tofu",
|
||||
random: (length) => Uint8Array.from({ length }, (_, index) => index + 1), id: () => "message-1"
|
||||
});
|
||||
return { store, coordinator, encryptedAddresses };
|
||||
}
|
||||
|
||||
describe("OMEMO encrypted-message XML", () => {
|
||||
it.each([LEGACY_OMEMO, OMEMO_2] as const)("round-trips a strict %s envelope", (version) => {
|
||||
const value: OmemoEncryptedEnvelope = {
|
||||
version, senderDeviceId: 7,
|
||||
keyGroups: version === LEGACY_OMEMO
|
||||
? [{ keys: [{ rid: 8, data: Uint8Array.of(1, 2), keyExchange: true }] }]
|
||||
: [{ jid: "bob@example.org", keys: [{ rid: 8, data: Uint8Array.of(1, 2), keyExchange: true }] }],
|
||||
...(version === LEGACY_OMEMO ? { iv: Uint8Array.from({ length: 12 }, () => 3) } : {}),
|
||||
payload: Uint8Array.of(4, 5, 6)
|
||||
};
|
||||
const encoded = serializeEncryptedEnvelope(value);
|
||||
expect(parseEncryptedEnvelope(version, encoded)).toEqual(value);
|
||||
expect(encoded.toString()).toContain(version === LEGACY_OMEMO ? 'prekey="true"' : 'kex="true"');
|
||||
});
|
||||
|
||||
it("rejects wrong structure, noncanonical flags, duplicate recipients and invalid IVs", () => {
|
||||
const duplicate = parse(`<encrypted xmlns="${OMEMO_2}"><header sid="7"><keys jid="bob@example.org"><key rid="8">AQ==</key><key rid="8">Ag==</key></keys></header></encrypted>`);
|
||||
expect(() => parseEncryptedEnvelope(OMEMO_2, duplicate)).toThrow("duplicate recipient");
|
||||
const flag = parse(`<encrypted xmlns="${LEGACY_OMEMO}"><header sid="7"><key rid="8" prekey="1">AQ==</key><iv>AAAAAAAAAAAAAAAA</iv></header></encrypted>`);
|
||||
expect(() => parseEncryptedEnvelope(LEGACY_OMEMO, flag)).toThrow("key-exchange flag");
|
||||
expect(() => serializeEncryptedEnvelope({ version: LEGACY_OMEMO, senderDeviceId: 7, keyGroups: [{ keys: [{ rid: 8, data: Uint8Array.of(1) }] }], iv: Uint8Array.of(1) }))
|
||||
.toThrow("12-byte IV");
|
||||
});
|
||||
});
|
||||
|
||||
describe("OMEMO outbound coordinator", () => {
|
||||
it("rechecks revocation inside the outbound transaction before any cipher mutation", async () => {
|
||||
const { store } = fixture();
|
||||
const key = new Uint8Array(33).fill(7); key[0] = 5;
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "tofu" });
|
||||
const record = adapter.trust.observeIdentity("bob@example.org.8", key.buffer);
|
||||
// Simulate a revocation committed after recipient planning.
|
||||
adapter.trust.transition("bob@example.org.8", record, "distrusted");
|
||||
});
|
||||
const createSessionCipher = vi.fn();
|
||||
const coordinator = new OmemoOutboundCoordinator({ account: "alice@example.org", localDeviceId: 7,
|
||||
store, trustMode: "tofu", requireTrustedTargets: true, bindings: { createSessionCipher } });
|
||||
const send = vi.fn();
|
||||
await expect(coordinator.encryptAndSend({ to: "bob@example.org", text: "must not leak", version: LEGACY_OMEMO,
|
||||
recipients: [{ jid: "bob@example.org", deviceIds: [8] }], send })).rejects.toThrow("distrusted");
|
||||
expect(createSessionCipher).not.toHaveBeenCalled(); expect(send).not.toHaveBeenCalled();
|
||||
expect(store.listOutbound("alice@example.org")).toHaveLength(0);
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("commits exact legacy ciphertext and all ratchets before send, then acknowledges", async () => {
|
||||
const { store, coordinator, encryptedAddresses } = fixture();
|
||||
let committedBeforeSend = false;
|
||||
let sent = "";
|
||||
const result = await coordinator.encryptAndSend({
|
||||
to: "bob@example.org", text: "hello", version: LEGACY_OMEMO,
|
||||
recipients: [{ jid: "bob@example.org", deviceIds: [9, 8] }, { jid: "alice@example.org", deviceIds: [7, 6] }],
|
||||
send: async (stanza) => {
|
||||
const pending = store.listOutbound("alice@example.org");
|
||||
committedBeforeSend = pending.length === 1;
|
||||
sent = stanza.toString();
|
||||
expect(pending[0]!.stanza.toString()).toBe(sent);
|
||||
}
|
||||
});
|
||||
expect(committedBeforeSend).toBe(true);
|
||||
expect(store.listOutbound("alice@example.org")).toEqual([]);
|
||||
expect(result.pending.stanza.toString()).toBe(sent);
|
||||
expect(encryptedAddresses).toEqual(["alice@example.org.6", "bob@example.org.8", "bob@example.org.9"]);
|
||||
const envelope = parseEncryptedEnvelope(LEGACY_OMEMO, parse(sent).getChild("encrypted", LEGACY_OMEMO)!);
|
||||
const material = envelope.keyGroups[0]!.keys[0]!.data;
|
||||
const decipher = createDecipheriv("aes-128-gcm", material.subarray(0, 16), envelope.iv!, { authTagLength: 16 });
|
||||
decipher.setAuthTag(material.subarray(16));
|
||||
expect(Buffer.concat([decipher.update(envelope.payload!), decipher.final()]).toString()).toBe("hello");
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("produces decryptable OMEMO 2 SCE payload and kex grouping", async () => {
|
||||
const { store, coordinator } = fixture();
|
||||
let stanza = "";
|
||||
await coordinator.encryptAndSend({
|
||||
to: "bob@example.org", text: "secret", version: OMEMO_2,
|
||||
recipients: [{ jid: "bob@example.org", deviceIds: [9] }, { jid: "alice@example.org", deviceIds: [6] }],
|
||||
send: async (value) => { stanza = value.toString(); }
|
||||
});
|
||||
const envelope = parseEncryptedEnvelope(OMEMO_2, parse(stanza).getChild("encrypted", OMEMO_2)!);
|
||||
expect(envelope.keyGroups.map((group) => group.jid)).toEqual(["alice@example.org", "bob@example.org"]);
|
||||
expect(envelope.keyGroups[1]!.keys[0]!.keyExchange).toBe(true);
|
||||
const material = envelope.keyGroups[0]!.keys[0]!.data;
|
||||
const key = material.subarray(0, 32);
|
||||
const derived = Buffer.from(hkdfSync("sha256", key, Buffer.alloc(32), "OMEMO Payload", 80));
|
||||
const expectedMac = createHmac("sha256", derived.subarray(32, 64)).update(envelope.payload!).digest().subarray(0, 16);
|
||||
expect(Buffer.from(material.subarray(32))).toEqual(expectedMac);
|
||||
const decipher = createDecipheriv("aes-256-cbc", derived.subarray(0, 32), derived.subarray(64, 80));
|
||||
const plaintext = Buffer.concat([decipher.update(envelope.payload!), decipher.final()]).toString();
|
||||
expect(plaintext).toContain('<envelope xmlns="urn:xmpp:sce:1">');
|
||||
expect(plaintext).toContain('<body xmlns="jabber:client">secret</body>');
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("rolls back every ratchet and emits nothing when one device encryption fails", async () => {
|
||||
const { store } = fixture();
|
||||
const bindings: OmemoOutboundBindings = { createSessionCipher(adapter, address) { return { async encrypt() {
|
||||
adapter.storeSession(address, "advanced");
|
||||
if (address.endsWith(".9")) throw new Error("cipher failure");
|
||||
return { type: 1, body: binary(Uint8Array.of(1)) };
|
||||
} }; } };
|
||||
const coordinator = new OmemoOutboundCoordinator({ account: "alice@example.org", localDeviceId: 7, store, bindings, trustMode: "tofu", id: () => "failed" });
|
||||
const send = vi.fn();
|
||||
await expect(coordinator.encryptAndSend({ to: "bob@example.org", text: "hello", version: LEGACY_OMEMO,
|
||||
recipients: [{ jid: "bob@example.org", deviceIds: [8, 9] }], send })).rejects.toThrow("cipher failure");
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect(store.listOutbound("alice@example.org")).toEqual([]);
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
expect(view.get("session", "bob@example.org.8")).toBeUndefined();
|
||||
expect(view.get("session", "bob@example.org.9")).toBeUndefined();
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("retains committed ciphertext for retry when transport send fails", async () => {
|
||||
const { store, coordinator } = fixture();
|
||||
await expect(coordinator.encryptAndSend({ to: "bob@example.org", text: "hello", version: LEGACY_OMEMO,
|
||||
recipients: [{ jid: "bob@example.org", deviceIds: [8] }], send: async () => { throw new Error("offline"); } }))
|
||||
.rejects.toThrow("offline");
|
||||
expect(store.listOutbound("alice@example.org")).toHaveLength(1);
|
||||
await store.updateRecords("alice@example.org", (view) => {
|
||||
expect(view.get("session", "bob@example.org.8")?.toString()).toContain("advanced");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("OMEMO inbound coordinator", () => {
|
||||
async function encryptedFixture(version: typeof LEGACY_OMEMO | typeof OMEMO_2, keyExchange = false) {
|
||||
const outboundDirectory = mkdtempSync(join(tmpdir(), "openclaw-omemo-inbound-out-"));
|
||||
const outboundStore = new OmemoTransactionalStore({ stateDirectory: outboundDirectory });
|
||||
let stanza!: Element;
|
||||
const outbound = new OmemoOutboundCoordinator({
|
||||
account: "alice@example.org", localDeviceId: 7, store: outboundStore, trustMode: "tofu", id: () => "inbound-1",
|
||||
random: (length) => Uint8Array.from({ length }, (_, index) => index + 1),
|
||||
bindings: { createSessionCipher() { return { async encrypt(value) {
|
||||
return { body: binary(value), type: keyExchange ? 3 : 1, ...(version === OMEMO_2 && keyExchange ? { kex: true } : {}) };
|
||||
} }; } }
|
||||
});
|
||||
await outbound.encryptAndSend({
|
||||
to: "bob@example.org", text: "secret inbound", version,
|
||||
recipients: [{ jid: "bob@example.org", deviceIds: [9] }],
|
||||
send: async (value) => { stanza = parse(value.toString()); stanza.attrs.from = "alice@example.org/phone"; }
|
||||
});
|
||||
outboundStore.close();
|
||||
return stanza;
|
||||
}
|
||||
|
||||
it.each([LEGACY_OMEMO, OMEMO_2] as const)("commits %s ratchet and sealed plaintext before dispatch", async (version) => {
|
||||
const stanza = await encryptedFixture(version, true);
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-inbound-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory, clock: () => 2000 });
|
||||
const order: string[] = [];
|
||||
const refresh = vi.fn(async () => { order.push("refresh"); });
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher(adapter, address, actualVersion) {
|
||||
expect(address).toBe("alice@example.org.7"); expect(actualVersion).toBe(version);
|
||||
return {
|
||||
async decryptWhisperMessage(value) { return decrypt(value); },
|
||||
async decryptPreKeyWhisperMessage(value) { return decrypt(value); }
|
||||
};
|
||||
function decrypt(value: Uint8Array) {
|
||||
adapter.storeSession(address, `advanced:${version}`);
|
||||
return { plaintext: value.slice().buffer };
|
||||
}
|
||||
} };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu", refreshBundle: refresh });
|
||||
const message = await inbound.decryptAndDispatch(stanza, async (value) => {
|
||||
expect(store.listInbound("bob@example.org")).toHaveLength(1);
|
||||
order.push("dispatch"); expect(value.text).toBe("secret inbound");
|
||||
});
|
||||
expect(message?.from).toBe("alice@example.org");
|
||||
expect(order).toEqual(["refresh", "dispatch"]);
|
||||
expect(refresh).toHaveBeenCalledWith(version);
|
||||
expect(store.listInbound("bob@example.org")).toEqual([]);
|
||||
await store.updateRecords("bob@example.org", (view) => expect(view.get("session", "alice@example.org.7")?.toString()).toBe(`advanced:${version}`));
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("accepts the standard xml:lang attribute on an encrypted message", async () => {
|
||||
const stanza = await encryptedFixture(LEGACY_OMEMO);
|
||||
stanza.attrs["xml:lang"] = "en";
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-language-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher() { return {
|
||||
async decryptWhisperMessage(value) { return { plaintext: value.slice().buffer }; },
|
||||
async decryptPreKeyWhisperMessage(value) { return { plaintext: value.slice().buffer }; }
|
||||
}; } };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu" });
|
||||
const message = await inbound.decryptAndDispatch(stanza, async () => undefined);
|
||||
expect(message?.text).toBe("secret inbound");
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("derives a stable replay ID when an encrypted message omits its stanza ID", async () => {
|
||||
const stanza = await encryptedFixture(LEGACY_OMEMO);
|
||||
delete stanza.attrs.id;
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-derived-id-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const decrypt = vi.fn(async (value: Uint8Array) => ({ plaintext: value.slice().buffer }));
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher() { return {
|
||||
decryptWhisperMessage: decrypt, decryptPreKeyWhisperMessage: decrypt
|
||||
}; } };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu" });
|
||||
await expect(inbound.decryptAndDispatch(stanza, async () => { throw new Error("dispatcher offline"); })).rejects.toThrow("dispatcher offline");
|
||||
const [pending] = store.listInbound("bob@example.org");
|
||||
expect(pending?.id).toMatch(/^sha256:[0-9a-f]{64}$/);
|
||||
await expect(inbound.decryptAndDispatch(stanza, async () => undefined)).rejects.toThrow("already pending");
|
||||
expect(decrypt).toHaveBeenCalledOnce();
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("commits payload-free key transport without dispatching a chat message", async () => {
|
||||
const stanza = await encryptedFixture(LEGACY_OMEMO, true);
|
||||
stanza.getChild("encrypted", LEGACY_OMEMO)!.remove(stanza.getChild("encrypted", LEGACY_OMEMO)!.getChild("payload", LEGACY_OMEMO)!);
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-key-transport-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const refresh = vi.fn(async () => undefined);
|
||||
const dispatch = vi.fn(async () => undefined);
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher(adapter, address) { return {
|
||||
async decryptWhisperMessage(value) { adapter.storeSession(address, "advanced"); return { plaintext: value.slice().buffer }; },
|
||||
async decryptPreKeyWhisperMessage(value) { adapter.storeSession(address, "advanced"); return { plaintext: value.slice().buffer }; }
|
||||
}; } };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu", refreshBundle: refresh });
|
||||
expect(await inbound.decryptAndDispatch(stanza, dispatch)).toBeUndefined();
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
expect(refresh).toHaveBeenCalledWith(LEGACY_OMEMO);
|
||||
expect(store.listInbound("bob@example.org")).toEqual([]);
|
||||
await store.updateRecords("bob@example.org", (view) => expect(view.get("session", "alice@example.org.7")?.toString()).toBe("advanced"));
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("recovers a committed payload-free key transport without dispatch", async () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-key-transport-recovery-"));
|
||||
const faulted = new OmemoTransactionalStore({
|
||||
stateDirectory: directory,
|
||||
faultInjector(point) { if (point === "after-commit") throw new Error("crash after commit"); }
|
||||
});
|
||||
await expect(faulted.inbound("bob@example.org", "transport-1", "alice@example.org", async (view) => {
|
||||
view.set("session", "alice@example.org.7", Buffer.from("advanced"));
|
||||
return new Uint8Array();
|
||||
})).rejects.toThrow("crash after commit");
|
||||
faulted.close();
|
||||
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher() { throw new Error("not used"); } };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu" });
|
||||
const dispatch = vi.fn(async () => undefined);
|
||||
expect(await inbound.dispatchPending(dispatch)).toBe(1);
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
expect(store.listInbound("bob@example.org")).toEqual([]);
|
||||
await store.updateRecords("bob@example.org", (view) => expect(view.get("session", "alice@example.org.7")?.toString()).toBe("advanced"));
|
||||
store.close();
|
||||
});
|
||||
|
||||
it.each(["groupchat", "headline", "invalid"])("rejects encrypted %s messages before ratchet use", async (type) => {
|
||||
const stanza = await encryptedFixture(LEGACY_OMEMO);
|
||||
stanza.attrs.type = type;
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-message-type-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const decrypt = vi.fn(async (value: Uint8Array) => ({ plaintext: value.slice().buffer }));
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher() { return {
|
||||
decryptWhisperMessage: decrypt, decryptPreKeyWhisperMessage: decrypt
|
||||
}; } };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu" });
|
||||
await expect(inbound.decryptAndDispatch(stanza, async () => undefined)).rejects.toThrow("Unsupported OMEMO message type");
|
||||
expect(decrypt).not.toHaveBeenCalled();
|
||||
expect(store.listInbound("bob@example.org")).toEqual([]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("retains a sealed delivery on dispatch failure and rejects replay without advancing the ratchet", async () => {
|
||||
const stanza = await encryptedFixture(LEGACY_OMEMO);
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-replay-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const decrypt = vi.fn(async (value: Uint8Array) => ({ plaintext: value.slice().buffer }));
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher() { return { decryptWhisperMessage: decrypt, decryptPreKeyWhisperMessage: decrypt }; } };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu" });
|
||||
await expect(inbound.decryptAndDispatch(stanza, async () => { throw new Error("dispatcher offline"); })).rejects.toThrow("dispatcher offline");
|
||||
expect(store.listInbound("bob@example.org")[0]?.plaintext.toString()).toBe("secret inbound");
|
||||
await expect(inbound.decryptAndDispatch(stanza, async () => undefined)).rejects.toThrow("already pending");
|
||||
expect(decrypt).toHaveBeenCalledOnce();
|
||||
const recovered: string[] = [];
|
||||
expect(await inbound.dispatchPending(async (value) => { recovered.push(value.text); })).toBe(1);
|
||||
expect(recovered).toEqual(["secret inbound"]);
|
||||
expect(store.listInbound("bob@example.org")).toEqual([]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("rolls back ratchet changes and dispatches nothing on authentication failure", async () => {
|
||||
const stanza = await encryptedFixture(OMEMO_2);
|
||||
const encrypted = stanza.getChild("encrypted", OMEMO_2)!;
|
||||
const payload = encrypted.getChild("payload", OMEMO_2)!;
|
||||
payload.children = [Buffer.from("tampered").toString("base64")];
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-auth-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher(adapter, address) { return {
|
||||
async decryptWhisperMessage(value) { adapter.storeSession(address, "must-rollback"); return { plaintext: value.slice().buffer }; },
|
||||
async decryptPreKeyWhisperMessage(value) { return this.decryptWhisperMessage(value, "binary"); }
|
||||
}; } };
|
||||
const dispatch = vi.fn(async () => undefined);
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu" });
|
||||
await expect(inbound.decryptAndDispatch(stanza, dispatch)).rejects.toThrow("authentication failed");
|
||||
expect(dispatch).not.toHaveBeenCalled(); expect(store.listInbound("bob@example.org")).toEqual([]);
|
||||
await store.updateRecords("bob@example.org", (view) => expect(view.get("session", "alice@example.org.7")).toBeUndefined());
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("rejects an OMEMO 2 SCE sender that differs from the authenticated outer sender", async () => {
|
||||
const stanza = await encryptedFixture(OMEMO_2);
|
||||
stanza.attrs.from = "mallory@example.org/laptop";
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-sce-sender-"));
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const bindings: OmemoInboundBindings = { createSessionCipher() { return {
|
||||
async decryptWhisperMessage(value) { return { plaintext: value.slice().buffer }; },
|
||||
async decryptPreKeyWhisperMessage(value) { return { plaintext: value.slice().buffer }; }
|
||||
}; } };
|
||||
const inbound = new OmemoInboundCoordinator({ account: "bob@example.org", localDeviceId: 9, store, bindings, trustMode: "tofu" });
|
||||
await expect(inbound.decryptAndDispatch(stanza, async () => undefined)).rejects.toThrow("SCE sender binding");
|
||||
expect(store.listInbound("bob@example.org")).toEqual([]);
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { formatIdentityFingerprint, LibomemoStoreAdapter } from "../src/omemo/libomemo-store.js";
|
||||
import { OmemoOperator } from "../src/omemo/operator.js";
|
||||
import { OmemoTransactionalStore } from "../src/omemo/store.js";
|
||||
|
||||
const directories: string[] = [];
|
||||
const account = "alice@example.org";
|
||||
const address = "bob@example.org.9";
|
||||
|
||||
function stateDirectory(): string {
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-omemo-operator-"));
|
||||
directories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
|
||||
function identity(fill: number): ArrayBuffer {
|
||||
const value = new Uint8Array(33);
|
||||
value[0] = 5;
|
||||
value.fill(fill, 1);
|
||||
return value.buffer;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("OmemoOperator", () => {
|
||||
it("lists, compare-and-set transitions, and guarded candidate replacement atomically", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: stateDirectory() });
|
||||
const original = identity(3);
|
||||
const replacement = identity(4);
|
||||
const originalFingerprint = formatIdentityFingerprint(original);
|
||||
const replacementFingerprint = formatIdentityFingerprint(replacement);
|
||||
await store.updateRecords(account, (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "manual", clock: () => 10 });
|
||||
adapter.trust.observeIdentity(address, original);
|
||||
adapter.trust.stageCandidate(address, originalFingerprint, replacement);
|
||||
adapter.storeSession(address, "old-session");
|
||||
});
|
||||
const operator = new OmemoOperator(account, store, "manual");
|
||||
expect(await operator.inspectTrust()).toEqual([expect.objectContaining({
|
||||
address,
|
||||
state: "undecided",
|
||||
fingerprint: originalFingerprint,
|
||||
candidate: expect.objectContaining({ observedFingerprint: replacementFingerprint })
|
||||
})]);
|
||||
await expect(operator.transition(address, {
|
||||
state: "trusted", fingerprint: originalFingerprint
|
||||
}, "verified")).rejects.toThrow("changed since it was reviewed");
|
||||
await operator.transition(address, {
|
||||
state: "undecided", fingerprint: originalFingerprint
|
||||
}, "verified");
|
||||
await expect(operator.replaceIdentity(address, {
|
||||
state: "verified", fingerprint: originalFingerprint
|
||||
}, formatIdentityFingerprint(identity(5)), "undecided")).rejects.toThrow("candidate changed");
|
||||
await operator.replaceIdentity(address, {
|
||||
state: "verified", fingerprint: originalFingerprint
|
||||
}, replacementFingerprint, "undecided");
|
||||
await store.updateRecords(account, (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "manual" });
|
||||
expect(adapter.trust.get(address)?.fingerprint).toBe(replacementFingerprint);
|
||||
expect(adapter.trust.candidate(address)).toBeUndefined();
|
||||
expect(adapter.loadSession(address)).toBeUndefined();
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Element } from "@xmpp/xml";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { LEGACY_OMEMO, OMEMO_2, type OmemoPublishedBundle, type OmemoVersion } from "../src/omemo/engine.js";
|
||||
import { OmemoPepConflictError, OmemoPepPublisher, type OmemoPepAdapter, type OmemoPepItem } from "../src/omemo/pep.js";
|
||||
import { parseDeviceList, serializeBundle, serializeDeviceList } from "../src/omemo/xml.js";
|
||||
|
||||
function bytes(length: number, fill: number): ArrayBuffer { return Uint8Array.from({ length }, () => fill).buffer; }
|
||||
function bundle(version: OmemoVersion): OmemoPublishedBundle {
|
||||
const length = version === LEGACY_OMEMO ? 33 : 32;
|
||||
return { version, deviceId: 77, identityKey: bytes(length, 1),
|
||||
signedPreKey: { id: 2, publicKey: bytes(length, 2), signature: bytes(64, 3) },
|
||||
preKeys: [{ id: 3, publicKey: bytes(length, 4) }] };
|
||||
}
|
||||
|
||||
class MemoryPep implements OmemoPepAdapter {
|
||||
devices: OmemoPepItem | undefined;
|
||||
bundles = new Map<string, OmemoPepItem>();
|
||||
devicePublishes = 0;
|
||||
bundlePublishes = 0;
|
||||
bundleRetractions = 0;
|
||||
conflictDeviceOnce = false;
|
||||
conflictBundleOnce = false;
|
||||
async fetchDeviceList(): Promise<OmemoPepItem | undefined> { return this.devices; }
|
||||
async publishDeviceList(_version: OmemoVersion, payload: Element, expected?: string): Promise<void> {
|
||||
this.devicePublishes++;
|
||||
if (this.conflictDeviceOnce) {
|
||||
this.conflictDeviceOnce = false;
|
||||
this.devices = { payload: serializeDeviceList(OMEMO_2, [{ id: 55, label: "Phone", labelSignature: bytes(64, 9) }]), revision: "2" };
|
||||
throw new OmemoPepConflictError();
|
||||
}
|
||||
if (expected !== this.devices?.revision) throw new OmemoPepConflictError();
|
||||
this.devices = { payload, revision: String(Number(expected ?? 0) + 1) };
|
||||
}
|
||||
async fetchBundle(version: OmemoVersion, deviceId: number): Promise<OmemoPepItem | undefined> {
|
||||
return this.bundles.get(`${version}:${deviceId}`);
|
||||
}
|
||||
async publishBundle(version: OmemoVersion, deviceId: number, payload: Element, expected?: string): Promise<void> {
|
||||
this.bundlePublishes++;
|
||||
const key = `${version}:${deviceId}`;
|
||||
if (this.conflictBundleOnce) { this.conflictBundleOnce = false; throw new OmemoPepConflictError(); }
|
||||
if (expected !== this.bundles.get(key)?.revision) throw new OmemoPepConflictError();
|
||||
this.bundles.set(key, { payload, revision: String(Number(expected ?? 0) + 1) });
|
||||
}
|
||||
async retractBundle(version: OmemoVersion, deviceId: number, expected?: string): Promise<void> {
|
||||
this.bundleRetractions++;
|
||||
const key = `${version}:${deviceId}`;
|
||||
if (expected !== this.bundles.get(key)?.revision) throw new OmemoPepConflictError();
|
||||
this.bundles.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
describe("OmemoPepPublisher", () => {
|
||||
it("publishes a bundle before advertising the device and is idempotent", async () => {
|
||||
const adapter = new MemoryPep();
|
||||
const publisher = new OmemoPepPublisher({ adapter });
|
||||
await publisher.publish(bundle(OMEMO_2), { label: "OpenClaw", labelSignature: bytes(64, 8) });
|
||||
expect(adapter.bundlePublishes).toBe(1);
|
||||
expect(adapter.devicePublishes).toBe(1);
|
||||
expect(parseDeviceList(OMEMO_2, adapter.devices!.payload!)).toEqual([{ id: 77, label: "OpenClaw", labelSignature: bytes(64, 8) }]);
|
||||
await publisher.publish(bundle(OMEMO_2), { label: "OpenClaw", labelSignature: bytes(64, 8) });
|
||||
expect(adapter.bundlePublishes).toBe(1);
|
||||
expect(adapter.devicePublishes).toBe(1);
|
||||
});
|
||||
|
||||
it("refetches and preserves a concurrently added device after conflict", async () => {
|
||||
const adapter = new MemoryPep();
|
||||
adapter.devices = { payload: serializeDeviceList(OMEMO_2, [{ id: 10 }]), revision: "1" };
|
||||
adapter.conflictDeviceOnce = true;
|
||||
await new OmemoPepPublisher({ adapter }).publish(bundle(OMEMO_2), { label: "OpenClaw", labelSignature: bytes(64, 8) });
|
||||
expect(adapter.devicePublishes).toBe(2);
|
||||
expect(parseDeviceList(OMEMO_2, adapter.devices!.payload!)).toEqual([
|
||||
{ id: 55, label: "Phone", labelSignature: bytes(64, 9) },
|
||||
{ id: 77, label: "OpenClaw", labelSignature: bytes(64, 8) }
|
||||
]);
|
||||
});
|
||||
|
||||
it("retries bundle conflicts and stops at the bounded attempt limit", async () => {
|
||||
const adapter = new MemoryPep();
|
||||
adapter.conflictBundleOnce = true;
|
||||
await new OmemoPepPublisher({ adapter }).publish(bundle(LEGACY_OMEMO));
|
||||
expect(adapter.bundlePublishes).toBe(2);
|
||||
|
||||
const blocked = new MemoryPep();
|
||||
blocked.publishBundle = async () => { blocked.bundlePublishes++; throw new OmemoPepConflictError(); };
|
||||
await expect(new OmemoPepPublisher({ adapter: blocked, maxAttempts: 2 }).publish(bundle(OMEMO_2)))
|
||||
.rejects.toBeInstanceOf(OmemoPepConflictError);
|
||||
expect(blocked.bundlePublishes).toBe(2);
|
||||
});
|
||||
|
||||
it("does not overwrite a canonically identical existing bundle", async () => {
|
||||
const adapter = new MemoryPep();
|
||||
const value = bundle(OMEMO_2);
|
||||
adapter.bundles.set(`${OMEMO_2}:77`, { payload: serializeBundle(value), revision: "8" });
|
||||
await new OmemoPepPublisher({ adapter }).publish(value);
|
||||
expect(adapter.bundlePublishes).toBe(0);
|
||||
});
|
||||
|
||||
it("accepts a concurrent removal of the selected device before retracting its bundle", async () => {
|
||||
const adapter = new MemoryPep();
|
||||
const value = bundle(OMEMO_2);
|
||||
adapter.devices = {
|
||||
payload: serializeDeviceList(OMEMO_2, [{ id: 11 }, { id: 77 }, { id: 88 }]),
|
||||
revision: "1"
|
||||
};
|
||||
adapter.bundles.set(`${OMEMO_2}:77`, { payload: serializeBundle(value), revision: "4" });
|
||||
adapter.conflictDeviceOnce = true;
|
||||
await new OmemoPepPublisher({ adapter }).retire(OMEMO_2, 77);
|
||||
expect(parseDeviceList(OMEMO_2, adapter.devices!.payload!)).toEqual([
|
||||
{ id: 55, label: "Phone", labelSignature: bytes(64, 9) }
|
||||
]);
|
||||
expect(adapter.devicePublishes).toBe(1);
|
||||
expect(adapter.bundleRetractions).toBe(1);
|
||||
expect(adapter.bundles.has(`${OMEMO_2}:77`)).toBe(false);
|
||||
await new OmemoPepPublisher({ adapter }).retire(OMEMO_2, 77);
|
||||
expect(adapter.bundleRetractions).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { OmemoReviewTickets } from "../src/omemo/review.js";
|
||||
import { registerLiveTransport } from "../src/transport.js";
|
||||
import { registerOmemoAdmin } from "../src/omemo/admin.js";
|
||||
|
||||
const record = { address: "peer@example.org.42", state: "undecided" as const,
|
||||
fingerprint: "a".repeat(64), firstObservedAt: 1, lastObservedAt: 2 };
|
||||
|
||||
describe("OMEMO review capabilities", () => {
|
||||
it("binds single-use approvals to the reviewer, device, fingerprint, state and expiry", () => {
|
||||
let now = 100;
|
||||
const tickets = new OmemoReviewTickets(() => now);
|
||||
const [review] = tickets.issue("owner", [record]);
|
||||
expect(review!.action).toBe("trusted");
|
||||
expect(() => tickets.consume("other", review!.code)).toThrow("mismatched");
|
||||
expect(tickets.consume("owner", review!.code)).toMatchObject({ address: record.address, expected: { state: "undecided", fingerprint: record.fingerprint } });
|
||||
expect(() => tickets.consume("owner", review!.code)).toThrow("Invalid");
|
||||
const [expired] = tickets.issue("owner", [record]);
|
||||
now += 600_000;
|
||||
expect(() => tickets.consume("owner", expired!.code)).toThrow("expired");
|
||||
});
|
||||
|
||||
it("invalidates refreshed reviews and never issues approval for replacement or revoked identities", () => {
|
||||
const tickets = new OmemoReviewTickets();
|
||||
const [first] = tickets.issue("owner", [record]);
|
||||
tickets.issue("owner", []);
|
||||
expect(() => tickets.consume("owner", first!.code)).toThrow();
|
||||
expect(tickets.issue("owner", [
|
||||
{ ...record, state: "retired" }, { ...record, state: "distrusted" },
|
||||
{ ...record, candidate: { previousFingerprint: "a", observedFingerprint: "b", observedAt: 1 } }
|
||||
])).toEqual([]);
|
||||
const [pending] = tickets.issue("owner", [record]);
|
||||
tickets.clear();
|
||||
expect(() => tickets.consume("owner", pending!.code)).toThrow();
|
||||
expect(() => new OmemoReviewTickets().consume("owner", pending!.code)).toThrow();
|
||||
});
|
||||
|
||||
it("registers both admin RPCs with explicit admin scope and denies unauthenticated or read-only callers", async () => {
|
||||
const handlers = new Map<string, any>();
|
||||
registerOmemoAdmin({ registerGatewayMethod: (name: string, handler: unknown, opts: unknown) => {
|
||||
expect(opts).toEqual({ scope: "operator.admin" }); handlers.set(name, handler);
|
||||
} } as never);
|
||||
expect(handlers.size).toBe(2);
|
||||
for (const handler of handlers.values()) {
|
||||
for (const client of [null, { connect: { role: "operator", scopes: ["operator.read"] } }, { connect: { role: "node", scopes: ["operator.admin"] } }]) {
|
||||
const respond = vi.fn();
|
||||
await handler({ client, params: { accountId: "default" }, respond });
|
||||
expect(respond).toHaveBeenCalledWith(false, undefined, expect.objectContaining({ message: expect.stringContaining("operator.admin") }));
|
||||
}
|
||||
}
|
||||
});
|
||||
it("routes authenticated admin reviews and approvals with server-derived principals", async () => {
|
||||
const handlers = new Map<string, any>();
|
||||
registerOmemoAdmin({ registerGatewayMethod: (name: string, handler: unknown) => handlers.set(name, handler) } as never);
|
||||
const reviewPending = vi.fn(async () => []);
|
||||
const approveReview = vi.fn(async () => ({ state: "trusted" }));
|
||||
const unregister = registerLiveTransport("review-test", {
|
||||
status: { connected: true },
|
||||
omemoSession: { deliveryPolicy: "trusted-devices", excludedDevices: [],
|
||||
inspectTrust: async () => [], reviewPending, approveReview }
|
||||
} as never);
|
||||
try {
|
||||
const client = { connect: { role: "operator", scopes: ["operator.admin"] }, authenticatedUserId: "owner", connId: "connection" };
|
||||
const respond = vi.fn();
|
||||
await handlers.get("xmpp.omemo.review")({ client, params: { accountId: "review-test" }, respond });
|
||||
expect(respond).toHaveBeenCalledWith(true, expect.objectContaining({ policy: "trusted-devices" }));
|
||||
const owner = JSON.stringify(["gateway-admin", "user", "owner"]);
|
||||
expect(reviewPending).toHaveBeenCalledWith(owner);
|
||||
await handlers.get("xmpp.omemo.approve")({ client, params: { accountId: "review-test", code: "a".repeat(16) }, respond });
|
||||
expect(approveReview).toHaveBeenCalledWith(owner, "a".repeat(16));
|
||||
approveReview.mockClear();
|
||||
await handlers.get("xmpp.omemo.approve")({ client, params: { accountId: "review-test", code: "a".repeat(16), owner: "forged" }, respond });
|
||||
expect(approveReview).not.toHaveBeenCalled();
|
||||
expect(respond).toHaveBeenLastCalledWith(false, undefined, expect.objectContaining({ message: "Unexpected review arguments." }));
|
||||
} finally { unregister(); }
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,459 @@
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { LEGACY_OMEMO, type LibomemoEngineBindings, type OmemoVersion } from "../src/omemo/engine.js";
|
||||
import { LibomemoStoreAdapter, type LibomemoKeyPair } from "../src/omemo/libomemo-store.js";
|
||||
import type { OmemoInboundBindings, OmemoOutboundBindings } from "../src/omemo/message.js";
|
||||
import { OmemoSession } from "../src/omemo/session.js";
|
||||
import { OmemoTransactionalStore } from "../src/omemo/store.js";
|
||||
import { PUBSUB, XmppOmemoPepAdapter } from "../src/omemo/xmpp-pep.js";
|
||||
|
||||
function pair(seed: number): LibomemoKeyPair {
|
||||
const pub = new Uint8Array(33); pub[0] = 5; pub.fill(seed, 1);
|
||||
const priv = new Uint8Array(32); priv.fill(seed + 1);
|
||||
return { pubKey: pub.buffer, privKey: priv.buffer };
|
||||
}
|
||||
|
||||
function bindings(deviceId: number): LibomemoEngineBindings & OmemoOutboundBindings & OmemoInboundBindings {
|
||||
return {
|
||||
keyHelper: {
|
||||
async generateIdentityKeyPair() { return pair(deviceId); },
|
||||
generateRegistrationId() { return deviceId; },
|
||||
async generatePreKey(keyId) { return { keyId, keyPair: pair((keyId % 200) + 1) }; },
|
||||
async generateSignedPreKey(_identity, keyId, _version) {
|
||||
return { keyId, keyPair: pair((keyId % 200) + 1), signature: new Uint8Array(64).fill(7).buffer };
|
||||
}
|
||||
},
|
||||
async curvePubKeyToEd25519PubKey(publicKey) { return publicKey.slice(1); },
|
||||
createSessionBuilder(store: LibomemoStoreAdapter, address: string, version: OmemoVersion) {
|
||||
return { async processPreKey() { store.storeSession(address, JSON.stringify({ version })); } };
|
||||
},
|
||||
createSessionCipher(_store: LibomemoStoreAdapter, _address: string, _version: OmemoVersion) {
|
||||
return {
|
||||
async encrypt(plaintext: Uint8Array) {
|
||||
return { body: Buffer.from(plaintext).toString("binary"), type: 1 };
|
||||
},
|
||||
async decryptWhisperMessage(ciphertext: Uint8Array) { return { plaintext: Uint8Array.from(ciphertext).buffer }; },
|
||||
async decryptPreKeyWhisperMessage(ciphertext: Uint8Array) { return { plaintext: Uint8Array.from(ciphertext).buffer }; }
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function pepServer() {
|
||||
const items = new Map<string, Element>();
|
||||
const server = {
|
||||
items,
|
||||
failRetractionOnce: false,
|
||||
iq: { request: async (stanza: Element): Promise<Element> => {
|
||||
const owner = String(stanza.attrs.to);
|
||||
const pubsub = stanza.getChild("pubsub", PUBSUB);
|
||||
const get = pubsub?.getChild("items", PUBSUB);
|
||||
if (get) {
|
||||
const node = String(get.attrs.node);
|
||||
const id = String(get.getChild("item", PUBSUB)?.attrs.id);
|
||||
const payload = items.get(`${owner}\0${node}\0${id}`);
|
||||
if (!payload) throw Object.assign(new Error("missing"), { condition: "item-not-found" });
|
||||
return xml("iq", { type: "result" }, xml("pubsub", { xmlns: PUBSUB },
|
||||
xml("items", { node }, xml("item", { id }, payload))));
|
||||
}
|
||||
const publish = pubsub?.getChild("publish", PUBSUB);
|
||||
if (publish) {
|
||||
const node = String(publish.attrs.node);
|
||||
const item = publish.getChild("item", PUBSUB)!;
|
||||
items.set(`${owner}\0${node}\0${String(item.attrs.id)}`, item.getChildElements()[0]!);
|
||||
}
|
||||
const retract = pubsub?.getChild("retract", PUBSUB);
|
||||
if (retract) {
|
||||
if (server.failRetractionOnce) {
|
||||
server.failRetractionOnce = false;
|
||||
throw new Error("injected PEP retraction failure");
|
||||
}
|
||||
const node = String(retract.attrs.node);
|
||||
const id = String(retract.getChild("item", PUBSUB)?.attrs.id);
|
||||
items.delete(`${owner}\0${node}\0${id}`);
|
||||
}
|
||||
return xml("iq", { type: "result" });
|
||||
} }
|
||||
};
|
||||
return server;
|
||||
}
|
||||
|
||||
function open(account: string, deviceId: number, directory: string, server: ReturnType<typeof pepServer>, deliveryPolicy: "strict-all" | "trusted-devices" = "strict-all", trustMode: "manual" | "tofu" = "tofu") {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
const allBindings = bindings(deviceId);
|
||||
return {
|
||||
store,
|
||||
session: new OmemoSession({
|
||||
account, version: LEGACY_OMEMO, trustMode, deliveryPolicy, store,
|
||||
engineBindings: allBindings, outboundBindings: allBindings,
|
||||
inboundBindings: allBindings, pep: new XmppOmemoPepAdapter(account, server.iq)
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
describe("assembled OMEMO session", () => {
|
||||
it("excludes undecided, distrusted, retired and unavailable devices while retaining trusted recipients", async () => {
|
||||
const server = pepServer();
|
||||
const make = (jid: string, id: number, policy: "strict-all" | "trusted-devices" = "strict-all", mode: "manual" | "tofu" = "tofu") =>
|
||||
open(jid, id, mkdtempSync(join(tmpdir(), "omemo-plan-")), server, policy, mode);
|
||||
const alice = make("alice@example.org", 1, "trusted-devices", "manual");
|
||||
const bob = make("bob@example.org", 2);
|
||||
const unknown = make("bob@example.org", 3);
|
||||
const own = make("alice@example.org", 4);
|
||||
let wire: Element | undefined;
|
||||
for (const device of [alice, bob, unknown, own]) await device.session.initialize({ send: async (stanza) => { wire = stanza; }, dispatch: async () => undefined });
|
||||
await expect(alice.session.sendText("bob@example.org", "blocked")).rejects.toThrow("no trusted devices");
|
||||
expect(wire).toBeUndefined();
|
||||
const records = await alice.session.inspectTrust();
|
||||
expect(records).toHaveLength(3); // Discovery continues after undecided devices.
|
||||
const trusted = records.find((record) => record.address === "bob@example.org.2")!;
|
||||
const reviews = await alice.session.reviewPending("owner");
|
||||
const approval = reviews.find((record) => record.address === trusted.address)!;
|
||||
await expect(own.session.approveReview("owner", approval.code)).rejects.toThrow("Invalid");
|
||||
await alice.session.approveReview("owner", approval.code);
|
||||
await expect(alice.session.approveReview("owner", approval.code)).rejects.toThrow("Invalid");
|
||||
for (const state of ["undecided", "distrusted", "retired"] as const) {
|
||||
const current = (await alice.session.inspectTrust()).find((record) => record.address === "bob@example.org.3")!;
|
||||
await alice.session.transitionTrust(current.address, current, state);
|
||||
await alice.session.sendText("bob@example.org", "trusted only");
|
||||
expect(wire!.getChild("body")).toBeUndefined();
|
||||
const keys = wire!.getChild("encrypted", LEGACY_OMEMO)!.getChild("header", LEGACY_OMEMO)!.getChildren("key", LEGACY_OMEMO);
|
||||
expect(keys.map((key) => String(key.attrs.rid))).toEqual(["2"]);
|
||||
expect(alice.session.excludedDevices).toHaveLength(2);
|
||||
}
|
||||
server.items.delete(`bob@example.org\0${LEGACY_OMEMO}.bundles:3\0current`);
|
||||
await alice.session.sendText("bob@example.org", "missing optional bundle");
|
||||
expect(alice.session.excludedDevices).toContainEqual({ address: "bob@example.org.3", reason: "bundle-unavailable" });
|
||||
// Trusting only an own sync device never permits sending to an unknown recipient.
|
||||
const currentBob = (await alice.session.inspectTrust()).find((record) => record.address === trusted.address)!;
|
||||
await alice.session.transitionTrust(currentBob.address, currentBob, "distrusted");
|
||||
const ownRecord = (await alice.session.inspectTrust()).find((record) => record.address === "alice@example.org.4")!;
|
||||
await alice.session.transitionTrust(ownRecord.address, ownRecord, "trusted");
|
||||
await expect(alice.session.sendText("bob@example.org", "must not send")).rejects.toThrow("no trusted devices");
|
||||
for (const device of [alice, bob, unknown, own]) device.session.close();
|
||||
});
|
||||
|
||||
it("rejects stale approval and keeps changed identities and corrupt records as hard failures", async () => {
|
||||
const server = pepServer();
|
||||
const alice = open("alice@example.org", 1, mkdtempSync(join(tmpdir(), "omemo-change-")), server, "trusted-devices", "manual");
|
||||
const bob = open("bob@example.org", 2, mkdtempSync(join(tmpdir(), "omemo-change-")), server);
|
||||
for (const device of [alice, bob]) await device.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
await expect(alice.session.sendText("bob@example.org", "discover")).rejects.toThrow();
|
||||
const [review] = await alice.session.reviewPending("owner");
|
||||
const [record] = await alice.session.inspectTrust();
|
||||
await alice.session.transitionTrust(record!.address, record!, "distrusted");
|
||||
await expect(alice.session.approveReview("owner", review!.code)).rejects.toThrow("changed since");
|
||||
await alice.store.updateRecords("alice@example.org", (view) => {
|
||||
const adapter = new LibomemoStoreAdapter(view, { mode: "manual" });
|
||||
adapter.trust.stageCandidate(record!.address, record!.fingerprint, pair(77).pubKey);
|
||||
});
|
||||
await expect(alice.session.sendText("bob@example.org", "changed")).rejects.toThrow("key changed");
|
||||
await alice.store.updateRecords("alice@example.org", (view) => view.set("trust", record!.address, Buffer.from("bad")));
|
||||
await expect(alice.session.sendText("bob@example.org", "corrupt")).rejects.toThrow();
|
||||
expect(alice.store.listOutbound("alice@example.org")).toHaveLength(0);
|
||||
alice.session.close(); bob.session.close();
|
||||
});
|
||||
|
||||
it("consumes message bodies and encrypted traffic fail-closed before initialization", async () => {
|
||||
const server = pepServer();
|
||||
const value = open("alice@example.org", 99, mkdtempSync(join(tmpdir(), "omemo-starting-")), server);
|
||||
await expect(value.session.handleStanza(
|
||||
xml("message", { from: "bob@example.org/device" }, xml("encrypted", { xmlns: LEGACY_OMEMO }))
|
||||
)).resolves.toBe(true);
|
||||
await expect(value.session.handleStanza(
|
||||
xml("message", { from: "bob@example.org/device" }, xml("body", {}, "plain"))
|
||||
)).resolves.toBe(true);
|
||||
value.store.close();
|
||||
});
|
||||
|
||||
it("delivers real ciphertext only to the trusted device after a second client appears", async () => {
|
||||
const lib = await import("libomemo.js") as Record<string, any>;
|
||||
const real = {
|
||||
keyHelper: lib.KeyHelper, curvePubKeyToEd25519PubKey: lib.curvePubKeyToEd25519PubKey,
|
||||
createSessionBuilder: (store: LibomemoStoreAdapter, address: string, version: OmemoVersion) => new lib.SessionBuilder(store, address, version),
|
||||
createSessionCipher: (store: LibomemoStoreAdapter, address: string, version: OmemoVersion) => new lib.SessionCipher(store, address, version)
|
||||
};
|
||||
const server = pepServer();
|
||||
const make = (account: string, manual = false) => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: mkdtempSync(join(tmpdir(), "omemo-multi-real-")) });
|
||||
return new OmemoSession({ account, version: LEGACY_OMEMO, trustMode: manual ? "manual" : "tofu",
|
||||
deliveryPolicy: "trusted-devices", store, engineBindings: real, outboundBindings: real,
|
||||
inboundBindings: real, pep: new XmppOmemoPepAdapter(account, server.iq) });
|
||||
};
|
||||
const alice = make("alice@example.org", true), bob = make("bob@example.org"), unknown = make("bob@example.org");
|
||||
let wire: Element | undefined;
|
||||
const delivered = vi.fn(async () => undefined), excluded = vi.fn(async () => undefined);
|
||||
await alice.initialize({ send: async (stanza) => { wire = stanza; }, dispatch: async () => undefined });
|
||||
await bob.initialize({ send: async () => undefined, dispatch: delivered });
|
||||
await expect(alice.sendText("bob@example.org", "discover")).rejects.toThrow("no trusted devices");
|
||||
const [record] = await alice.inspectTrust();
|
||||
await alice.transitionTrust(record!.address, record!, "verified");
|
||||
await alice.sendText("bob@example.org", "baseline");
|
||||
wire!.attrs.from = "alice@example.org/client";
|
||||
await bob.handleStanza(wire!);
|
||||
await unknown.initialize({ send: async () => undefined, dispatch: excluded });
|
||||
await alice.sendText("bob@example.org", "still encrypted");
|
||||
expect(wire!.toString()).not.toContain("still encrypted");
|
||||
expect(wire!.getChild("body")).toBeUndefined();
|
||||
wire!.attrs.from = "alice@example.org/client";
|
||||
await bob.handleStanza(wire!);
|
||||
expect(delivered).toHaveBeenLastCalledWith(expect.objectContaining({ text: expect.stringContaining("still encrypted") }));
|
||||
expect(delivered).toHaveBeenLastCalledWith(expect.objectContaining({ text: expect.stringContaining("awaiting approval") }));
|
||||
await expect(unknown.handleStanza(wire!)).rejects.toThrow();
|
||||
expect(excluded).not.toHaveBeenCalled();
|
||||
expect(alice.excludedDevices).toHaveLength(1);
|
||||
await alice.sendText("bob@example.org", "no repeated notice");
|
||||
wire!.attrs.from = "alice@example.org/client";
|
||||
await bob.handleStanza(wire!);
|
||||
expect(delivered).toHaveBeenLastCalledWith(expect.objectContaining({ text: "no repeated notice" }));
|
||||
alice.close(); bob.close(); unknown.close();
|
||||
}, 30_000);
|
||||
|
||||
it("completes a real maintained-fork round trip over mocked XMPP PEP", async () => {
|
||||
const lib = await import("libomemo.js") as Record<string, any>;
|
||||
const real = {
|
||||
keyHelper: lib.KeyHelper,
|
||||
curvePubKeyToEd25519PubKey: lib.curvePubKeyToEd25519PubKey,
|
||||
createSessionBuilder: (store: LibomemoStoreAdapter, address: string, version: OmemoVersion) =>
|
||||
new lib.SessionBuilder(store, address, version),
|
||||
createSessionCipher: (store: LibomemoStoreAdapter, address: string, version: OmemoVersion) =>
|
||||
new lib.SessionCipher(store, address, version)
|
||||
};
|
||||
const server = pepServer();
|
||||
const make = (account: string) => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: mkdtempSync(join(tmpdir(), "omemo-real-")) });
|
||||
return { store, session: new OmemoSession({
|
||||
account, version: LEGACY_OMEMO, trustMode: "tofu", store,
|
||||
engineBindings: real, outboundBindings: real, inboundBindings: real,
|
||||
pep: new XmppOmemoPepAdapter(account, server.iq)
|
||||
}) };
|
||||
};
|
||||
const alice = make("alice@example.org");
|
||||
const bob = make("bob@example.org");
|
||||
let wire: Element | undefined;
|
||||
const delivered = vi.fn(async () => undefined);
|
||||
await alice.session.initialize({ send: async (stanza) => { wire = stanza; }, dispatch: async () => undefined });
|
||||
await bob.session.initialize({ send: async () => undefined, dispatch: delivered });
|
||||
await alice.session.sendText("bob@example.org", "real crypto round trip");
|
||||
wire!.attrs.from = "alice@example.org/openclaw";
|
||||
await bob.session.handleStanza(wire!);
|
||||
expect(delivered).toHaveBeenCalledWith(expect.objectContaining({ text: "real crypto round trip" }));
|
||||
alice.store.close(); bob.store.close();
|
||||
}, 30_000);
|
||||
|
||||
it("exercises a manual-trust legacy activation, retirement, restart, and rollback with real bindings", async () => {
|
||||
const lib = await import("libomemo.js") as Record<string, any>;
|
||||
const real = {
|
||||
keyHelper: lib.KeyHelper,
|
||||
curvePubKeyToEd25519PubKey: lib.curvePubKeyToEd25519PubKey,
|
||||
createSessionBuilder: (store: LibomemoStoreAdapter, address: string, version: OmemoVersion) =>
|
||||
new lib.SessionBuilder(store, address, version),
|
||||
createSessionCipher: (store: LibomemoStoreAdapter, address: string, version: OmemoVersion) =>
|
||||
new lib.SessionCipher(store, address, version)
|
||||
};
|
||||
const server = pepServer();
|
||||
const aliceDirectory = mkdtempSync(join(tmpdir(), "omemo-activation-alice-"));
|
||||
const bobDirectory = mkdtempSync(join(tmpdir(), "omemo-activation-bob-"));
|
||||
const make = (account: string, directory: string) => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: directory });
|
||||
return { store, session: new OmemoSession({
|
||||
account, version: LEGACY_OMEMO, trustMode: "manual", store,
|
||||
engineBindings: real, outboundBindings: real, inboundBindings: real,
|
||||
pep: new XmppOmemoPepAdapter(account, server.iq)
|
||||
}) };
|
||||
};
|
||||
let alice = make("alice@example.org", aliceDirectory);
|
||||
const bob = make("bob@example.org", bobDirectory);
|
||||
const delivered = vi.fn(async () => undefined);
|
||||
let wire: Element | undefined;
|
||||
await alice.session.initialize({ send: async (stanza) => { wire = stanza; }, dispatch: async () => undefined });
|
||||
await bob.session.initialize({ send: async () => undefined, dispatch: delivered });
|
||||
|
||||
await expect(alice.session.sendText("bob@example.org", "activation proof"))
|
||||
.rejects.toThrow("operator review required");
|
||||
const bobIdentity = (await alice.session.inspectTrust())[0]!;
|
||||
expect(bobIdentity).toMatchObject({ state: "undecided" });
|
||||
await alice.session.transitionTrust(
|
||||
bobIdentity.address,
|
||||
{ state: bobIdentity.state, fingerprint: bobIdentity.fingerprint },
|
||||
"verified"
|
||||
);
|
||||
await alice.session.sendText("bob@example.org", "activation proof");
|
||||
wire!.attrs.from = "alice@example.org/openclaw";
|
||||
await expect(bob.session.handleStanza(wire!)).rejects.toThrow("operator review required");
|
||||
// An inbound rejection rolls its transaction back, including identity
|
||||
// observation. Resolve the peer bundle through an outbound attempt so the
|
||||
// manual-trust record is committed for operator review.
|
||||
await expect(bob.session.sendText("alice@example.org", "trust discovery"))
|
||||
.rejects.toThrow("operator review required");
|
||||
const aliceIdentity = (await bob.session.inspectTrust())[0]!;
|
||||
expect(aliceIdentity).toMatchObject({ state: "undecided" });
|
||||
await bob.session.transitionTrust(
|
||||
aliceIdentity.address,
|
||||
{ state: aliceIdentity.state, fingerprint: aliceIdentity.fingerprint },
|
||||
"verified"
|
||||
);
|
||||
await expect(bob.session.handleStanza(wire!)).resolves.toBe(true);
|
||||
expect(delivered).toHaveBeenLastCalledWith(expect.objectContaining({ text: "activation proof" }));
|
||||
expect(alice.store.listOutbound("alice@example.org")).toHaveLength(0);
|
||||
expect(bob.store.listInbound("bob@example.org")).toHaveLength(0);
|
||||
|
||||
const bundleEntry = [...server.items.entries()].find(([key]) =>
|
||||
key.startsWith(`alice@example.org\0${LEGACY_OMEMO}.bundles:`));
|
||||
expect(bundleEntry).toBeDefined();
|
||||
const [bundleKey, originalBundle] = bundleEntry!;
|
||||
const deviceId = Number(bundleKey.match(/\.bundles:(\d+)\0current$/)?.[1]);
|
||||
expect(deviceId).toBeGreaterThan(0);
|
||||
const listKey = [...server.items.keys()].find((key) =>
|
||||
key === `alice@example.org\0${LEGACY_OMEMO}.devicelist\0current`)!;
|
||||
|
||||
await alice.session.retireLocalDevice(LEGACY_OMEMO, deviceId);
|
||||
expect(server.items.has(bundleKey)).toBe(false);
|
||||
expect(server.items.get(listKey)?.toString()).not.toContain(`id="${deviceId}"`);
|
||||
await expect(alice.session.sendText("bob@example.org", "blocked while retired"))
|
||||
.rejects.toThrow("local device is retired");
|
||||
alice.store.close();
|
||||
|
||||
alice = make("alice@example.org", aliceDirectory);
|
||||
await alice.session.initialize({ send: async (stanza) => { wire = stanza; }, dispatch: async () => undefined });
|
||||
expect(server.items.has(bundleKey)).toBe(false);
|
||||
await alice.session.activateLocalDevice(LEGACY_OMEMO, deviceId);
|
||||
expect(server.items.get(bundleKey)?.toString()).toBe(originalBundle.toString());
|
||||
expect(server.items.get(listKey)?.toString()).toContain(`id="${deviceId}"`);
|
||||
await alice.session.sendText("bob@example.org", "rollback proof");
|
||||
wire!.attrs.from = "alice@example.org/openclaw";
|
||||
await expect(bob.session.handleStanza(wire!)).resolves.toBe(true);
|
||||
expect(delivered).toHaveBeenLastCalledWith(expect.objectContaining({ text: "rollback proof" }));
|
||||
expect(alice.store.listOutbound("alice@example.org")).toHaveLength(0);
|
||||
expect(bob.store.listInbound("bob@example.org")).toHaveLength(0);
|
||||
alice.store.close(); bob.store.close();
|
||||
}, 30_000);
|
||||
|
||||
it("publishes, discovers, creates sessions, encrypts and decrypts between two accounts", async () => {
|
||||
const server = pepServer();
|
||||
const alice = open("alice@example.org", 101, mkdtempSync(join(tmpdir(), "omemo-a-")), server);
|
||||
const bob = open("bob@example.org", 202, mkdtempSync(join(tmpdir(), "omemo-b-")), server);
|
||||
const delivered = vi.fn(async () => undefined);
|
||||
let wire: Element | undefined;
|
||||
await alice.session.initialize({ send: async (stanza) => { wire = stanza; }, dispatch: async () => undefined });
|
||||
await bob.session.initialize({ send: async () => undefined, dispatch: delivered });
|
||||
const id = await alice.session.sendText("bob@example.org", "encrypted hello");
|
||||
expect(wire?.toString()).toContain(LEGACY_OMEMO);
|
||||
wire!.attrs.from = "alice@example.org/device";
|
||||
await expect(bob.session.handleStanza(wire!)).resolves.toBe(true);
|
||||
expect(delivered).toHaveBeenCalledWith(expect.objectContaining({ id, from: "alice@example.org", text: "encrypted hello" }));
|
||||
expect(alice.store.listOutbound("alice@example.org")).toHaveLength(0);
|
||||
expect(bob.store.listInbound("bob@example.org")).toHaveLength(0);
|
||||
alice.store.close(); bob.store.close();
|
||||
});
|
||||
|
||||
it("reinitializes safely after a full reconnect and advertises only the configured profile", async () => {
|
||||
const server = pepServer();
|
||||
const value = open("alice@example.org", 212, mkdtempSync(join(tmpdir(), "omemo-reconnect-")), server);
|
||||
const firstSend = vi.fn(async () => undefined);
|
||||
const secondSend = vi.fn(async () => undefined);
|
||||
await value.session.initialize({ send: firstSend, dispatch: async () => undefined });
|
||||
const publishedNodes = [...server.items.keys()];
|
||||
expect(publishedNodes.some((key) => key.includes(LEGACY_OMEMO))).toBe(true);
|
||||
expect(publishedNodes.some((key) => key.includes("urn:xmpp:omemo:2"))).toBe(false);
|
||||
|
||||
await expect(value.session.initialize({ send: secondSend, dispatch: async () => undefined })).resolves.toBeUndefined();
|
||||
value.store.close();
|
||||
});
|
||||
|
||||
it("retires the exact local advertisement, blocks sends, and does not republish on reconnect", async () => {
|
||||
const server = pepServer();
|
||||
const directory = mkdtempSync(join(tmpdir(), "omemo-retire-"));
|
||||
const value = open("alice@example.org", 313, directory, server);
|
||||
await value.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
const bundleKey = [...server.items.keys()].find((key) => key.includes(`${LEGACY_OMEMO}.bundles:313`));
|
||||
const listKey = [...server.items.keys()].find((key) => key.includes(`${LEGACY_OMEMO}.devicelist`));
|
||||
expect(bundleKey).toBeDefined();
|
||||
expect(listKey).toBeDefined();
|
||||
|
||||
await value.session.retireLocalDevice(LEGACY_OMEMO, 313);
|
||||
expect(server.items.has(bundleKey!)).toBe(false);
|
||||
expect(server.items.get(listKey!)?.toString()).not.toContain('id="313"');
|
||||
await expect(value.session.sendText("bob@example.org", "must not send"))
|
||||
.rejects.toThrow("local device is retired");
|
||||
await value.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
expect(server.items.has(bundleKey!)).toBe(false);
|
||||
expect(server.items.get(listKey!)?.toString()).not.toContain('id="313"');
|
||||
value.store.close();
|
||||
|
||||
const restarted = open("alice@example.org", 313, directory, server);
|
||||
await restarted.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
expect(server.items.has(bundleKey!)).toBe(false);
|
||||
await expect(restarted.session.sendText("bob@example.org", "still blocked"))
|
||||
.rejects.toThrow("local device is retired");
|
||||
await restarted.session.activateLocalDevice(LEGACY_OMEMO, 313);
|
||||
expect(server.items.has(bundleKey!)).toBe(true);
|
||||
expect(server.items.get(listKey!)?.toString()).toContain('id="313"');
|
||||
restarted.store.close();
|
||||
});
|
||||
|
||||
it("persists retirement before PEP failure and completes it after restart", async () => {
|
||||
const server = pepServer();
|
||||
const directory = mkdtempSync(join(tmpdir(), "omemo-retire-recovery-"));
|
||||
const first = open("alice@example.org", 314, directory, server);
|
||||
await first.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
const bundleKey = [...server.items.keys()].find((key) => key.includes(`${LEGACY_OMEMO}.bundles:314`))!;
|
||||
server.failRetractionOnce = true;
|
||||
await expect(first.session.retireLocalDevice(LEGACY_OMEMO, 314))
|
||||
.rejects.toThrow("injected PEP retraction failure");
|
||||
expect(server.items.has(bundleKey)).toBe(true);
|
||||
await expect(first.session.sendText("bob@example.org", "blocked after partial retirement"))
|
||||
.rejects.toThrow("local device is retired");
|
||||
first.store.close();
|
||||
|
||||
const restarted = open("alice@example.org", 314, directory, server);
|
||||
await restarted.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
expect(server.items.has(bundleKey)).toBe(false);
|
||||
restarted.store.close();
|
||||
});
|
||||
|
||||
it("replays exact committed ciphertext after restart without advancing the ratchet again", async () => {
|
||||
const server = pepServer();
|
||||
const directory = mkdtempSync(join(tmpdir(), "omemo-restart-"));
|
||||
const first = open("alice@example.org", 303, directory, server);
|
||||
await first.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
await expect(first.session.sendText("alice@example.org", "recover me")).rejects.toThrow("no trusted devices");
|
||||
|
||||
// Add another account device and force a post-commit transport failure.
|
||||
const peer = open("bob@example.org", 404, mkdtempSync(join(tmpdir(), "omemo-peer-")), server);
|
||||
await peer.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
const failing = open("carol@example.org", 505, mkdtempSync(join(tmpdir(), "omemo-c-")), server);
|
||||
await failing.session.initialize({ send: async () => undefined, dispatch: async () => undefined });
|
||||
const originalSend = vi.fn(async () => { throw new Error("offline"); });
|
||||
// A separate account is used because session IO is intentionally immutable.
|
||||
const failedDir = mkdtempSync(join(tmpdir(), "omemo-failed-"));
|
||||
const failed = open("dave@example.org", 606, failedDir, server);
|
||||
await failed.session.initialize({ send: originalSend, dispatch: async () => undefined });
|
||||
await expect(failed.session.sendText("bob@example.org", "recover me")).rejects.toThrow("offline");
|
||||
const committed = failed.store.listOutbound("dave@example.org")[0]!.stanza.toString("utf8");
|
||||
failed.store.close();
|
||||
|
||||
const replayed: string[] = [];
|
||||
const restarted = open("dave@example.org", 606, failedDir, server);
|
||||
await restarted.session.initialize({ send: async (stanza) => { replayed.push(stanza.toString()); }, dispatch: async () => undefined });
|
||||
expect(replayed).toEqual([committed]);
|
||||
expect(restarted.store.listOutbound("dave@example.org")).toHaveLength(0);
|
||||
first.store.close(); peer.store.close(); failing.store.close(); restarted.store.close();
|
||||
});
|
||||
|
||||
it("consumes plaintext bodies while active instead of falling back to plaintext dispatch", async () => {
|
||||
const server = pepServer();
|
||||
const value = open("alice@example.org", 707, mkdtempSync(join(tmpdir(), "omemo-plain-")), server);
|
||||
const dispatch = vi.fn(async () => undefined);
|
||||
await value.session.initialize({ send: async () => undefined, dispatch });
|
||||
await expect(value.session.handleStanza(xml("message", { from: "bob@example.org" }, xml("body", {}, "plain")))).resolves.toBe(true);
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
value.store.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { OmemoTransactionalStore } from "../src/omemo/store.js";
|
||||
|
||||
const directories: string[] = [];
|
||||
|
||||
function temporaryState(): string {
|
||||
const directory = mkdtempSync(join(tmpdir(), "openclaw-xmpp-omemo-"));
|
||||
directories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("OmemoTransactionalStore", () => {
|
||||
it("commits ratchet state and exact outbound stanza together across restart", async () => {
|
||||
const stateDirectory = temporaryState();
|
||||
let store = new OmemoTransactionalStore({ stateDirectory, clock: () => 1234 });
|
||||
await store.outbound("account", "message-1", "peer@example.test", async (view) => {
|
||||
view.set("session", "peer:7", Buffer.from("ratchet-1"));
|
||||
return Buffer.from("<encrypted>exact-ciphertext</encrypted>");
|
||||
});
|
||||
store.close();
|
||||
|
||||
store = new OmemoTransactionalStore({ stateDirectory });
|
||||
expect(store.listOutbound("account")).toEqual([{
|
||||
id: "message-1",
|
||||
recipient: "peer@example.test",
|
||||
stanza: Buffer.from("<encrypted>exact-ciphertext</encrypted>"),
|
||||
createdAt: 1234
|
||||
}]);
|
||||
await store.outbound("account", "message-2", "peer@example.test", async (view) => {
|
||||
expect(view.get("session", "peer:7")?.toString()).toBe("ratchet-1");
|
||||
return Buffer.from("ciphertext-2");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("does not persist callback mutations when crypto fails", async () => {
|
||||
const stateDirectory = temporaryState();
|
||||
const store = new OmemoTransactionalStore({ stateDirectory });
|
||||
await expect(store.outbound("account", "failed", "peer", async (view) => {
|
||||
view.set("identity", "local", Buffer.from("must-not-commit"));
|
||||
throw new Error("crypto failed");
|
||||
})).rejects.toThrow("crypto failed");
|
||||
await store.outbound("account", "passed", "peer", async (view) => {
|
||||
expect(view.get("identity", "local")).toBeUndefined();
|
||||
return Buffer.from("ciphertext");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("commits and rolls back standalone record updates atomically", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
await store.updateRecords("account", (view) => view.set("trust", "peer:7", Buffer.from("trusted")));
|
||||
await expect(store.updateRecords("account", (view) => {
|
||||
view.set("trust", "peer:7", Buffer.from("must-not-commit"));
|
||||
throw new Error("review cancelled");
|
||||
})).rejects.toThrow("review cancelled");
|
||||
await store.updateRecords("account", (view) => {
|
||||
expect(view.get("trust", "peer:7")?.toString()).toBe("trusted");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("does not attempt rollback after a simulated post-commit failure", async () => {
|
||||
const stateDirectory = temporaryState();
|
||||
let store = new OmemoTransactionalStore({
|
||||
stateDirectory,
|
||||
faultInjector(point) {
|
||||
if (point === "after-commit") throw new Error("simulated process exit");
|
||||
}
|
||||
});
|
||||
await expect(store.updateRecords("account", (view) => {
|
||||
view.set("device", "local", Buffer.from("persisted"));
|
||||
})).rejects.toThrow("simulated process exit");
|
||||
store.close();
|
||||
|
||||
store = new OmemoTransactionalStore({ stateDirectory });
|
||||
await store.updateRecords("account", (view) => {
|
||||
expect(view.get("device", "local")?.toString()).toBe("persisted");
|
||||
});
|
||||
store.close();
|
||||
});
|
||||
|
||||
it("encrypts pending inbound plaintext and authenticates it after restart", async () => {
|
||||
const stateDirectory = temporaryState();
|
||||
let store = new OmemoTransactionalStore({ stateDirectory, clock: () => 99 });
|
||||
await store.inbound("account", "in-1", "peer", async (view) => {
|
||||
view.set("session", "peer:7", Buffer.from("advanced"));
|
||||
return Buffer.from("private plaintext");
|
||||
});
|
||||
store.close();
|
||||
expect(readFileSync(join(stateDirectory, "omemo.sqlite")).includes(Buffer.from("private plaintext"))).toBe(false);
|
||||
|
||||
store = new OmemoTransactionalStore({ stateDirectory });
|
||||
expect(store.listInbound("account")[0]?.plaintext.toString()).toBe("private plaintext");
|
||||
store.close();
|
||||
expect(statSync(stateDirectory).mode & 0o777).toBe(0o700);
|
||||
expect(statSync(join(stateDirectory, "omemo.sqlite")).mode & 0o777).toBe(0o600);
|
||||
expect(statSync(join(stateDirectory, "pending-delivery.key")).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it("fails closed when the pending-delivery key is corrupt", () => {
|
||||
const stateDirectory = temporaryState();
|
||||
const store = new OmemoTransactionalStore({ stateDirectory });
|
||||
store.close();
|
||||
writeFileSync(join(stateDirectory, "pending-delivery.key"), Buffer.alloc(3));
|
||||
chmodSync(join(stateDirectory, "pending-delivery.key"), 0o600);
|
||||
expect(() => new OmemoTransactionalStore({ stateDirectory })).toThrow("Invalid OMEMO pending-delivery key length");
|
||||
});
|
||||
|
||||
it("serializes concurrent operations for one database", async () => {
|
||||
const store = new OmemoTransactionalStore({ stateDirectory: temporaryState() });
|
||||
const order: string[] = [];
|
||||
let releaseFirst: (() => void) | undefined;
|
||||
const gate = new Promise<void>((resolve) => { releaseFirst = resolve; });
|
||||
const first = store.outbound("account", "one", "peer", async () => {
|
||||
order.push("one-start");
|
||||
await gate;
|
||||
order.push("one-end");
|
||||
return Buffer.from("one");
|
||||
});
|
||||
const second = store.outbound("account", "two", "peer", async () => {
|
||||
order.push("two");
|
||||
return Buffer.from("two");
|
||||
});
|
||||
await Promise.resolve();
|
||||
releaseFirst?.();
|
||||
await Promise.all([first, second]);
|
||||
expect(order).toEqual(["one-start", "one-end", "two"]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
for (const direction of ["outbound", "inbound"] as const) {
|
||||
for (const crashPoint of ["before-commit", "after-commit"] as const) {
|
||||
it(`survives SIGKILL ${crashPoint} for ${direction}`, () => {
|
||||
const stateDirectory = temporaryState();
|
||||
const worker = join(process.cwd(), "test", "fixtures", "omemo-crash-worker.ts");
|
||||
const result = spawnSync(process.execPath, ["--experimental-transform-types", worker, stateDirectory, direction, crashPoint], {
|
||||
encoding: "utf8",
|
||||
timeout: 10_000
|
||||
});
|
||||
expect(result.signal).toBe("SIGKILL");
|
||||
|
||||
const store = new OmemoTransactionalStore({ stateDirectory });
|
||||
store.integrityCheck();
|
||||
const committed = crashPoint === "after-commit";
|
||||
expect(store.listOutbound("account")).toHaveLength(direction === "outbound" && committed ? 1 : 0);
|
||||
expect(store.listInbound("account")).toHaveLength(direction === "inbound" && committed ? 1 : 0);
|
||||
store.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { xml } from "@xmpp/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { LEGACY_OMEMO, OMEMO_2, type OmemoPublishedBundle } from "../src/omemo/engine.js";
|
||||
import {
|
||||
bundleNode,
|
||||
deviceListNode,
|
||||
parseBundle,
|
||||
parseDeviceList,
|
||||
serializeBundle,
|
||||
serializeDeviceList
|
||||
} from "../src/omemo/xml.js";
|
||||
|
||||
function bytes(length: number, fill: number): ArrayBuffer {
|
||||
return Uint8Array.from({ length }, () => fill).buffer;
|
||||
}
|
||||
|
||||
function bundle(version: typeof LEGACY_OMEMO | typeof OMEMO_2): OmemoPublishedBundle {
|
||||
const keyBytes = version === LEGACY_OMEMO ? 33 : 32;
|
||||
return {
|
||||
version,
|
||||
deviceId: 1234,
|
||||
identityKey: bytes(keyBytes, 1),
|
||||
signedPreKey: { id: 7, publicKey: bytes(keyBytes, 2), signature: bytes(64, 3) },
|
||||
preKeys: [{ id: 10, publicKey: bytes(keyBytes, 4) }, { id: 9, publicKey: bytes(keyBytes, 5) }]
|
||||
};
|
||||
}
|
||||
|
||||
describe("OMEMO XML codecs", () => {
|
||||
it.each([LEGACY_OMEMO, OMEMO_2] as const)("round trips strict %s device lists", (version) => {
|
||||
const labelled = version === OMEMO_2 ? { id: 10, label: "Laptop", labelSignature: bytes(64, 8) } : { id: 10 };
|
||||
const payload = serializeDeviceList(version, [{ id: 20 }, labelled]);
|
||||
expect(parseDeviceList(version, payload)).toEqual([...([labelled, { id: 20 }] as const)]);
|
||||
expect(payload.toString()).toContain(version === LEGACY_OMEMO ? "<list" : "<devices");
|
||||
});
|
||||
|
||||
it.each([LEGACY_OMEMO, OMEMO_2] as const)("round trips strict %s bundles", (version) => {
|
||||
const payload = serializeBundle(bundle(version));
|
||||
const parsed = parseBundle(version, 1234, payload, () => 0);
|
||||
expect(parsed.registrationId).toBe(1234);
|
||||
expect(parsed.identityKey).toEqual(bundle(version).identityKey);
|
||||
expect(parsed.signedPreKey).toEqual({
|
||||
keyId: 7,
|
||||
publicKey: bundle(version).signedPreKey.publicKey,
|
||||
signature: bundle(version).signedPreKey.signature
|
||||
});
|
||||
expect(parsed.preKey).toEqual({ keyId: 9, publicKey: bytes(version === LEGACY_OMEMO ? 33 : 32, 5) });
|
||||
});
|
||||
|
||||
it("uses the profile-specific PEP node names", () => {
|
||||
expect(deviceListNode(LEGACY_OMEMO)).toBe("eu.siacs.conversations.axolotl.devicelist");
|
||||
expect(deviceListNode(OMEMO_2)).toBe("urn:xmpp:omemo:2:devices");
|
||||
expect(bundleNode(LEGACY_OMEMO, 1234)).toBe("eu.siacs.conversations.axolotl.bundles:1234");
|
||||
expect(bundleNode(OMEMO_2, 1234)).toBe("urn:xmpp:omemo:2:bundles");
|
||||
});
|
||||
|
||||
it("fails closed on namespace, duplicates, unknown children, attributes, and noncanonical base64", () => {
|
||||
expect(() => parseDeviceList(OMEMO_2, xml("devices", { xmlns: LEGACY_OMEMO }))).toThrow("Expected OMEMO devices");
|
||||
expect(() => parseDeviceList(OMEMO_2, xml("devices", { xmlns: OMEMO_2 },
|
||||
xml("device", { id: "1" }), xml("device", { id: "1" })))).toThrow("duplicate device ID");
|
||||
expect(() => parseDeviceList(OMEMO_2, xml("devices", { xmlns: OMEMO_2 },
|
||||
xml("device", { id: "1", mystery: "x" })))).toThrow("Unexpected OMEMO XML attribute");
|
||||
|
||||
const valid = bundle(OMEMO_2);
|
||||
const malformed = serializeBundle(valid);
|
||||
malformed.c("unknown");
|
||||
expect(() => parseBundle(OMEMO_2, 1234, malformed)).toThrow("Malformed OMEMO bundle structure");
|
||||
|
||||
const invalidBase64 = serializeBundle(valid);
|
||||
invalidBase64.getChild("ik", OMEMO_2)!.children = ["AQ=="];
|
||||
expect(() => parseBundle(OMEMO_2, 1234, invalidBase64)).toThrow("Invalid OMEMO identity key");
|
||||
});
|
||||
|
||||
it("rejects empty prekey sets, duplicate key IDs, oversized labels, and invalid device IDs", () => {
|
||||
expect(() => serializeBundle({ ...bundle(OMEMO_2), preKeys: [] })).toThrow("no one-time prekeys");
|
||||
const duplicate = bundle(OMEMO_2);
|
||||
duplicate.preKeys = [duplicate.preKeys[0]!, duplicate.preKeys[0]!];
|
||||
expect(() => serializeBundle(duplicate)).toThrow("duplicate prekey ID");
|
||||
expect(() => serializeDeviceList(OMEMO_2, [{ id: 1, label: "x".repeat(129), labelSignature: bytes(64, 1) }])).toThrow("Invalid OMEMO device label");
|
||||
expect(() => serializeDeviceList(OMEMO_2, [{ id: 1, label: "unsigned" }])).toThrow("label signature");
|
||||
expect(() => bundleNode(LEGACY_OMEMO, 0)).toThrow("Invalid OMEMO device ID");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { LEGACY_OMEMO, OMEMO_2, type OmemoPublishedBundle } from "../src/omemo/engine.js";
|
||||
import { serializeBundle, serializeDeviceList } from "../src/omemo/xml.js";
|
||||
import { DATA_FORMS, OmemoPepSession, PUBSUB, PUBSUB_EVENT, PUBSUB_OWNER, XmppOmemoPepAdapter, parseDeviceListEvent } from "../src/omemo/xmpp-pep.js";
|
||||
import { OmemoPepConflictError } from "../src/omemo/pep.js";
|
||||
|
||||
function bytes(length: number, fill: number): ArrayBuffer { return Uint8Array.from({ length }, () => fill).buffer; }
|
||||
function bundle(version: typeof LEGACY_OMEMO | typeof OMEMO_2, deviceId = 77): OmemoPublishedBundle {
|
||||
const length = version === LEGACY_OMEMO ? 33 : 32;
|
||||
return { version, deviceId, identityKey: bytes(length, 1), signedPreKey: { id: 2, publicKey: bytes(length, 2), signature: bytes(64, 3) }, preKeys: [{ id: 3, publicKey: bytes(length, 4) }] };
|
||||
}
|
||||
function result(node: string, id: string, payload?: Element): Element {
|
||||
return xml("iq", { type: "result" }, xml("pubsub", { xmlns: PUBSUB },
|
||||
xml("items", { node }, ...(payload ? [xml("item", { id }, payload)] : []))));
|
||||
}
|
||||
function event(version: typeof LEGACY_OMEMO | typeof OMEMO_2, devices: number[], from = "bot@example.org"): Element {
|
||||
const payload = serializeDeviceList(version, devices.map((id) => ({ id })));
|
||||
return xml("message", { type: "headline", from }, xml("event", { xmlns: PUBSUB_EVENT },
|
||||
xml("items", { node: version === LEGACY_OMEMO ? `${version}.devicelist` : `${version}:devices` },
|
||||
xml("item", { id: "current" }, payload))));
|
||||
}
|
||||
|
||||
describe("XMPP OMEMO PEP boundary", () => {
|
||||
it("constructs profile-specific item IQs and strictly parses responses", async () => {
|
||||
const value = bundle(OMEMO_2);
|
||||
const request = vi.fn(async (stanza: Element): Promise<Element> => {
|
||||
const items = stanza.getChild("pubsub", PUBSUB)?.getChild("items", PUBSUB);
|
||||
return result(String(items!.attrs.node), String(items!.getChild("item", PUBSUB)!.attrs.id), serializeBundle(value));
|
||||
});
|
||||
const adapter = new XmppOmemoPepAdapter("bot@example.org", { request });
|
||||
const fetched = await adapter.fetchBundle(OMEMO_2, 77);
|
||||
expect(fetched?.payload?.toString()).toBe(serializeBundle(value).toString());
|
||||
const iq = request.mock.calls[0]![0];
|
||||
expect(iq.attrs).toMatchObject({ type: "get", to: "bot@example.org" });
|
||||
expect(iq.toString()).toContain('node="urn:xmpp:omemo:2:bundles"');
|
||||
expect(iq.toString()).toContain('<item id="77"/>');
|
||||
|
||||
request.mockResolvedValueOnce(result("wrong", "77", serializeBundle(value)));
|
||||
await expect(adapter.fetchBundle(OMEMO_2, 77)).rejects.toThrow("Malformed OMEMO PEP fetch response");
|
||||
});
|
||||
|
||||
it("maps the exact @xmpp IQ error contract to missing items and publication conflicts", async () => {
|
||||
const missing = Object.assign(new Error("item-not-found"), { condition: "item-not-found" });
|
||||
const conflict = Object.assign(new Error("conflict"), { condition: "conflict" });
|
||||
const request = vi.fn<(stanza: Element) => Promise<Element>>()
|
||||
.mockRejectedValueOnce(missing)
|
||||
.mockResolvedValueOnce(result(`${OMEMO_2}:devices`, "current", serializeDeviceList(OMEMO_2, [{ id: 4 }])))
|
||||
.mockRejectedValueOnce(conflict);
|
||||
const adapter = new XmppOmemoPepAdapter("bot@example.org", { request });
|
||||
await expect(adapter.fetchDeviceList(OMEMO_2)).resolves.toBeUndefined();
|
||||
await expect(adapter.publishDeviceList(OMEMO_2, serializeDeviceList(OMEMO_2, [{ id: 5 }]), serializeDeviceList(OMEMO_2, [{ id: 4 }]).toString()))
|
||||
.rejects.toBeInstanceOf(OmemoPepConflictError);
|
||||
});
|
||||
|
||||
it("retracts the exact profile bundle item after a revision check", async () => {
|
||||
const value = bundle(OMEMO_2);
|
||||
const request = vi.fn<(stanza: Element) => Promise<Element>>()
|
||||
.mockResolvedValueOnce(result(`${OMEMO_2}:bundles`, "77", serializeBundle(value)))
|
||||
.mockResolvedValueOnce(xml("iq", { type: "result" }));
|
||||
const adapter = new XmppOmemoPepAdapter("bot@example.org", { request });
|
||||
await adapter.retractBundle(OMEMO_2, 77, serializeBundle(value).toString());
|
||||
const retract = request.mock.calls[1]![0].getChild("pubsub", PUBSUB)?.getChild("retract", PUBSUB);
|
||||
expect(retract?.attrs.node).toBe(`${OMEMO_2}:bundles`);
|
||||
expect(retract?.getChild("item", PUBSUB)?.attrs.id).toBe("77");
|
||||
});
|
||||
|
||||
it("configures OMEMO 2 nodes for open access and retained bundle items", async () => {
|
||||
const request = vi.fn(async (_stanza: Element): Promise<Element> => xml("iq", { type: "result" }));
|
||||
await new XmppOmemoPepAdapter("bot@example.org", { request }).configureOmemo2Nodes();
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
for (const call of request.mock.calls) {
|
||||
const configure = call[0].getChild("pubsub", PUBSUB_OWNER)?.getChild("configure", PUBSUB_OWNER);
|
||||
const form = configure?.getChild("x", DATA_FORMS);
|
||||
expect(call[0].attrs.type).toBe("set");
|
||||
expect(form?.attrs.type).toBe("submit");
|
||||
expect(form?.toString()).toContain("pubsub#access_model");
|
||||
expect(form?.toString()).toContain("open");
|
||||
}
|
||||
expect(request.mock.calls[0]![0].toString()).toContain("pubsub#max_items");
|
||||
expect(request.mock.calls[0]![0].toString()).toContain("<value>1</value>");
|
||||
expect(request.mock.calls[1]![0].toString()).toContain("<value>max</value>");
|
||||
});
|
||||
|
||||
it("publishes fresh PEP nodes before configuring them", async () => {
|
||||
const requests: Element[] = [];
|
||||
const existing = new Set<string>();
|
||||
const adapter = new XmppOmemoPepAdapter("bot@example.org", { request: async (stanza) => {
|
||||
requests.push(stanza);
|
||||
const pubsub = stanza.getChild("pubsub", PUBSUB);
|
||||
const items = pubsub?.getChild("items", PUBSUB);
|
||||
if (items) {
|
||||
const node = String(items.attrs.node);
|
||||
if (!existing.has(node)) throw Object.assign(new Error("Node not found"), { condition: "item-not-found" });
|
||||
return result(node, String(items.getChild("item", PUBSUB)!.attrs.id));
|
||||
}
|
||||
const publish = pubsub?.getChild("publish", PUBSUB);
|
||||
if (publish) existing.add(String(publish.attrs.node));
|
||||
const configure = stanza.getChild("pubsub", PUBSUB_OWNER)?.getChild("configure", PUBSUB_OWNER);
|
||||
if (configure && !existing.has(String(configure.attrs.node))) {
|
||||
throw Object.assign(new Error("Node not found"), { condition: "item-not-found" });
|
||||
}
|
||||
return xml("iq", { type: "result" });
|
||||
} });
|
||||
const session = new OmemoPepSession(adapter, new Map([
|
||||
[LEGACY_OMEMO, bundle(LEGACY_OMEMO, 76)],
|
||||
[OMEMO_2, bundle(OMEMO_2, 77)]
|
||||
]));
|
||||
|
||||
await expect(session.initialize()).resolves.toBeUndefined();
|
||||
const firstConfigure = requests.findIndex((iq) => iq.getChild("pubsub", PUBSUB_OWNER)?.getChild("configure", PUBSUB_OWNER));
|
||||
const lastPublish = requests.findLastIndex((iq) => iq.getChild("pubsub", PUBSUB)?.getChild("publish", PUBSUB));
|
||||
expect(firstConfigure).toBeGreaterThan(lastPublish);
|
||||
});
|
||||
|
||||
it("parses only strict headline device events", () => {
|
||||
expect(parseDeviceListEvent(event(LEGACY_OMEMO, [8, 4]))).toEqual({ version: LEGACY_OMEMO, devices: [{ id: 4 }, { id: 8 }] });
|
||||
expect(parseDeviceListEvent(xml("message", { type: "chat" }))).toBeUndefined();
|
||||
const malformed = event(OMEMO_2, [4]);
|
||||
malformed.getChild("event", PUBSUB_EVENT)!.getChild("items", PUBSUB_EVENT)!.getChild("item", PUBSUB_EVENT)!.attrs.id = "wrong";
|
||||
expect(() => parseDeviceListEvent(malformed)).toThrow("Malformed OMEMO PEP device-list event");
|
||||
});
|
||||
|
||||
it("reannounces a missing self device once and ignores present or unrelated events", async () => {
|
||||
const own = bundle(LEGACY_OMEMO);
|
||||
const requests: Element[] = [];
|
||||
const adapter = new XmppOmemoPepAdapter("bot@example.org", { request: async (stanza) => {
|
||||
requests.push(stanza);
|
||||
const items = stanza.getChild("pubsub", PUBSUB)?.getChild("items", PUBSUB);
|
||||
if (items) return result(String(items.attrs.node), String(items.getChild("item", PUBSUB)!.attrs.id));
|
||||
return xml("iq", { type: "result" });
|
||||
} });
|
||||
const session = new OmemoPepSession(adapter, new Map([[LEGACY_OMEMO, own]]));
|
||||
await expect(session.handleEvent(event(LEGACY_OMEMO, [12]))).resolves.toBe(true);
|
||||
const publishes = requests.filter((iq) => iq.getChild("pubsub", PUBSUB)?.getChild("publish", PUBSUB));
|
||||
expect(publishes).toHaveLength(2);
|
||||
expect(publishes[0]!.toString()).toContain(`${LEGACY_OMEMO}.bundles:77`);
|
||||
expect(publishes[1]!.toString()).toContain(`${LEGACY_OMEMO}.devicelist`);
|
||||
const before = requests.length;
|
||||
await session.handleEvent(event(LEGACY_OMEMO, [12], "mallory@example.org"));
|
||||
await session.handleEvent(event(LEGACY_OMEMO, [77]));
|
||||
await expect(session.handleEvent(xml("message", { type: "headline" }))).resolves.toBe(false);
|
||||
expect(requests).toHaveLength(before);
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,22 @@ describe("OpenClaw plugin contract", () => {
|
||||
expect(xmppPlugin.outbound?.textChunkLimit).toBe(DEFAULT_TEXT_CHUNK_LIMIT);
|
||||
});
|
||||
|
||||
it("registers the owner-gated OMEMO operator command with the full runtime", () => {
|
||||
const registerChannel = vi.fn();
|
||||
const registerCommand = vi.fn();
|
||||
const registerGatewayMethod = vi.fn();
|
||||
pluginEntry.register({ registrationMode: "full", registerChannel, registerCommand, registerGatewayMethod } as never);
|
||||
expect(registerChannel).toHaveBeenCalledWith({ plugin: xmppPlugin });
|
||||
expect(registerGatewayMethod).toHaveBeenCalledWith("xmpp.omemo.review", expect.any(Function), { scope: "operator.admin" });
|
||||
expect(registerGatewayMethod).toHaveBeenCalledWith("xmpp.omemo.approve", expect.any(Function), { scope: "operator.admin" });
|
||||
expect(registerCommand).toHaveBeenCalledWith(expect.objectContaining({
|
||||
name: "xmpp-omemo",
|
||||
requireAuth: true,
|
||||
requiredScopes: ["operator.admin"],
|
||||
exposeSenderIsOwner: true
|
||||
}));
|
||||
});
|
||||
|
||||
it("provides the chunker required by OpenClaw's message delivery path", () => {
|
||||
const chunker = xmppPlugin.outbound?.chunker;
|
||||
expect(chunker).toBeTypeOf("function");
|
||||
@@ -128,12 +144,18 @@ describe("OpenClaw plugin contract", () => {
|
||||
id: string;
|
||||
channels: string[];
|
||||
activation: { onStartup: boolean };
|
||||
doctorContract: { stateMigrations: unknown[] };
|
||||
channelConfigs: {
|
||||
xmpp: {
|
||||
schema: {
|
||||
properties: Record<string, unknown>;
|
||||
definitions: {
|
||||
account: { properties: Record<string, unknown> };
|
||||
secretInput: {
|
||||
anyOf: Array<{
|
||||
properties?: { source?: { enum?: string[] } };
|
||||
}>;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -142,6 +164,11 @@ describe("OpenClaw plugin contract", () => {
|
||||
expect(manifest.id).toBe("xmpp");
|
||||
expect(manifest.channels).toEqual(["xmpp"]);
|
||||
expect(manifest.activation.onStartup).toBe(false);
|
||||
expect(manifest.doctorContract.stateMigrations).toEqual([]);
|
||||
expect(
|
||||
manifest.channelConfigs.xmpp.schema.definitions.secretInput.anyOf
|
||||
.flatMap((entry) => entry.properties?.source?.enum ?? [])
|
||||
).toContain("store");
|
||||
const expectedTextChunkLimitSchema = {
|
||||
type: "integer",
|
||||
minimum: 1,
|
||||
@@ -154,5 +181,12 @@ describe("OpenClaw plugin contract", () => {
|
||||
manifest.channelConfigs.xmpp.schema.definitions.account.properties
|
||||
.textChunkLimit
|
||||
).toEqual(expectedTextChunkLimitSchema);
|
||||
expect(manifest.channelConfigs.xmpp.schema.properties.omemo).toMatchObject({
|
||||
type: "object",
|
||||
additionalProperties: false
|
||||
});
|
||||
expect(manifest.channelConfigs.xmpp.schema.definitions.account.properties.omemo).toEqual(
|
||||
manifest.channelConfigs.xmpp.schema.properties.omemo
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -34,13 +34,13 @@ const config: XmppConnectionConfig = {
|
||||
healthProbeTimeoutMs: 5_000, reconnectDelayMs: 2_000
|
||||
};
|
||||
|
||||
function create() {
|
||||
function create(omemoSession?: { initialize(io: unknown): Promise<void>; resume(io: unknown): Promise<void>; handleStanza(stanza: unknown): Promise<boolean>; sendText(to: string, text: string): Promise<string>; close(): void }) {
|
||||
const statuses: any[] = [];
|
||||
const transport = new XmppTransport(config, {
|
||||
const transport = new XmppTransport(omemoSession ? { ...config, omemo: { enabled: true, profile: "legacy", trustMode: "manual" } } : config, {
|
||||
onMessage: async () => undefined,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
|
||||
});
|
||||
}, omemoSession ? { omemoSession: omemoSession as never } : {});
|
||||
return { transport, statuses, client: mock.clients.at(-1)! };
|
||||
}
|
||||
|
||||
@@ -48,6 +48,31 @@ describe("XMPP health and recovery lifecycle", () => {
|
||||
beforeEach(() => { vi.useFakeTimers(); mock.request.mockReset(); mock.clients.length = 0; });
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("keeps delivery failure separate from successful ping and clears it only on successful send", async () => {
|
||||
const session = { initialize: vi.fn(async () => undefined), resume: vi.fn(async () => undefined),
|
||||
handleStanza: vi.fn(async () => false), close: vi.fn(),
|
||||
excludedDevices: [{ address: "alice@example.org.3", reason: "undecided" }],
|
||||
sendText: vi.fn<() => Promise<string>>().mockRejectedValueOnce(new Error("no trusted devices")).mockResolvedValue("ok") };
|
||||
const { transport, client } = create(session);
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await expect(transport.sendText("alice@example.org", "secret")).rejects.toThrow("no trusted devices");
|
||||
expect(transport.status).toMatchObject({ connected: true, deliveryState: "blocked", pendingDeviceCount: 1, lastDeliveryError: "no trusted devices" });
|
||||
expect(client.send.mock.calls.some(([stanza]: any[]) => stanza.getChild("active"))).toBe(true);
|
||||
mock.request.mockResolvedValueOnce({});
|
||||
await transport.probe();
|
||||
expect(transport.status.deliveryState).toBe("blocked");
|
||||
expect(transport.status.lastDeliveryError).toBe("no trusted devices");
|
||||
await transport.sendText("alice@example.org", "new reply");
|
||||
expect(transport.status).toMatchObject({ deliveryState: "degraded", excludedDeviceCount: 1 });
|
||||
expect(transport.status.lastDeliveryError).toBeUndefined();
|
||||
session.excludedDevices = [];
|
||||
await transport.sendText("alice@example.org", "fully recovered");
|
||||
expect(transport.status.deliveryState).toBe("healthy");
|
||||
controller.abort(); await running;
|
||||
});
|
||||
|
||||
it("correlates one bounded probe and records success", async () => {
|
||||
mock.request.mockResolvedValueOnce({});
|
||||
const { transport, client } = create();
|
||||
@@ -92,4 +117,103 @@ describe("XMPP health and recovery lifecycle", () => {
|
||||
expect(client.streamManagement.listenerCount("resumed")).toBe(0);
|
||||
expect(transport.status.phase).toBe("stopped");
|
||||
});
|
||||
|
||||
it("initializes explicitly injected OMEMO PEP before presence and consumes its events", async () => {
|
||||
const order: string[] = [];
|
||||
const session = {
|
||||
initialize: vi.fn(async () => { order.push("omemo"); }),
|
||||
resume: vi.fn(async () => { order.push("recover"); }),
|
||||
handleStanza: vi.fn(async () => true),
|
||||
sendText: vi.fn(async () => "encrypted"),
|
||||
close: vi.fn()
|
||||
};
|
||||
const { transport, client } = create(session);
|
||||
client.send.mockImplementation(async () => { order.push("presence"); });
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(order).toEqual(["omemo", "presence"]);
|
||||
client.emit("online", { toString: () => "bot@example.org/openclaw" });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(order).toEqual(["omemo", "presence", "omemo", "presence"]);
|
||||
expect(transport.status.phase).toBe("online");
|
||||
client.reconnect.emit("reconnecting");
|
||||
client.streamManagement.emit("resumed");
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(order).toEqual(["omemo", "presence", "omemo", "presence", "recover"]);
|
||||
expect(transport.status).toMatchObject({ connected: true, phase: "online", streamManagement: "resumed" });
|
||||
client.emit("stanza", (await import("@xmpp/client")).xml("message", { type: "headline" }));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(session.handleStanza).toHaveBeenCalledOnce();
|
||||
controller.abort();
|
||||
await running;
|
||||
});
|
||||
|
||||
it("routes text through the assembled OMEMO session and rejects switch/session mismatches", async () => {
|
||||
const session = {
|
||||
initialize: vi.fn(async () => undefined),
|
||||
resume: vi.fn(async () => undefined),
|
||||
handleStanza: vi.fn(async () => false),
|
||||
sendText: vi.fn(async () => "encrypted-id"),
|
||||
close: vi.fn()
|
||||
};
|
||||
const { transport } = create(session);
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await expect(transport.sendText("alice@example.org", "secret")).resolves.toEqual({
|
||||
id: "encrypted-id", to: "alice@example.org"
|
||||
});
|
||||
expect(session.sendText).toHaveBeenCalledWith("alice@example.org", "secret");
|
||||
controller.abort();
|
||||
await running;
|
||||
|
||||
expect(() => new XmppTransport({ ...config, omemo: { enabled: true, profile: "legacy", trustMode: "manual" } }, {
|
||||
onMessage: async () => undefined, onStatus: () => undefined,
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
|
||||
})).toThrow("no assembled OMEMO session");
|
||||
});
|
||||
|
||||
it("constructs the production session from the client's IQ caller and closes it on stop", async () => {
|
||||
const session = {
|
||||
initialize: vi.fn(async () => undefined),
|
||||
resume: vi.fn(async () => undefined),
|
||||
handleStanza: vi.fn(async () => false),
|
||||
sendText: vi.fn(async () => "encrypted-id"),
|
||||
close: vi.fn()
|
||||
};
|
||||
const factory = vi.fn(() => session as never);
|
||||
const transport = new XmppTransport({
|
||||
...config, omemo: { enabled: true, profile: "legacy", trustMode: "manual" }
|
||||
}, {
|
||||
onMessage: async () => undefined, onStatus: () => undefined,
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
|
||||
}, { omemoSessionFactory: factory });
|
||||
expect(factory).toHaveBeenCalledWith(mock.clients.at(-1)!.iqCaller);
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
controller.abort();
|
||||
await running;
|
||||
expect(session.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("fails closed before presence when explicit OMEMO PEP initialization fails", async () => {
|
||||
const session = {
|
||||
initialize: vi.fn(async () => { throw new Error("denied"); }),
|
||||
resume: vi.fn(async () => undefined),
|
||||
handleStanza: vi.fn(async () => false),
|
||||
sendText: vi.fn(async () => "encrypted"),
|
||||
close: vi.fn()
|
||||
};
|
||||
const { transport, client } = create(session);
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(client.send).not.toHaveBeenCalled();
|
||||
expect(transport.status).toMatchObject({ connected: false, phase: "failed" });
|
||||
expect(transport.status.lastError).toContain("OMEMO initialization failed");
|
||||
controller.abort();
|
||||
await running;
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user