Initial public source prerelease
This commit is contained in:
commit
93a00d9919
42 files changed
+13859
No files matched your search
@@ -0,0 +1,6 @@
|
||||
* text=auto eol=lf
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.webp binary
|
||||
@@ -0,0 +1,29 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
matrix:
|
||||
node:
|
||||
- "22.22.3"
|
||||
- "24"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run verify
|
||||
- run: npm audit --omit=dev
|
||||
@@ -0,0 +1,8 @@
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
backups/
|
||||
*.bak.*
|
||||
*.tgz
|
||||
.env
|
||||
*.log
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
# Pre-adoption baseline
|
||||
|
||||
Captured: 2026-08-09
|
||||
|
||||
Git commit: `11db813a292a1215f59032b36617251c8553ccbd`
|
||||
|
||||
This commit is the immutable boundary between the independently developed
|
||||
direct-message prototype and any later work informed by external XMPP
|
||||
implementations. It was committed before any external source was copied or
|
||||
closely adapted into this repository.
|
||||
|
||||
## Toolchain
|
||||
|
||||
- OpenClaw CLI: `2026.7.1-2` (`0790d9f`)
|
||||
- OpenClaw package and plugin SDK: `2026.7.1`
|
||||
- Node.js: `22.23.2`
|
||||
- npm: `10.9.8`
|
||||
- `@xmpp/client`: `0.14.0`
|
||||
- `@xmpp/xml`: `0.14.0`
|
||||
- TypeScript: `5.9.3`
|
||||
- Vitest: `4.0.18`
|
||||
- Prosody: `13.0.1`, reported by an authenticated XEP-0092 query
|
||||
|
||||
The Android XMPP client used in the successful live path returned an IQ error
|
||||
to a single XEP-0092 query to its bare JID. Its exact version therefore remains
|
||||
an explicit evidence gap rather than being guessed; no further client probe was
|
||||
made.
|
||||
|
||||
## Verification
|
||||
|
||||
`npm run verify` completed successfully from the baseline tree:
|
||||
|
||||
- TypeScript type-check passed.
|
||||
- Seven test files passed, containing 18 tests.
|
||||
- The production build passed.
|
||||
- `npm pack --dry-run` passed with 51 files.
|
||||
- The dry-run tarball was 82.6 kB (350.3 kB unpacked), with SHA-1
|
||||
`78e42c14a74b02a06defda039ed2a64fb788eca2`.
|
||||
|
||||
The generated runtime entry points for the transport and channel were
|
||||
byte-for-byte identical to the installed live plugin at capture time. The live
|
||||
Gateway configuration was hashed before this work and was not edited.
|
||||
|
||||
## Privacy and package review
|
||||
|
||||
The source tree and packed artefact were scanned for private domains, real
|
||||
JIDs, home/root paths, private-key headers, common cloud-key formats, and
|
||||
plausible assigned credentials. No deployment-specific or secret material was
|
||||
found. Example values such as `bot@example.org`, `owner@example.org`,
|
||||
`use-an-app-password`, and the test-only string `secret` are deliberate
|
||||
fixtures.
|
||||
|
||||
Ignored generated content is limited to `node_modules/`, `dist/`, coverage,
|
||||
tarballs, environment files, and logs. The packed file list was reviewed
|
||||
explicitly during verification.
|
||||
|
||||
## External-source boundary
|
||||
|
||||
The relevant ProcessOne branch was rechecked at
|
||||
`a6adb95b35c183a81eef3afcef17071e9b647673`, and OpenClaw PR 9741 at
|
||||
`8a4bc4314ae39f8c5693051dc7bf604ddda0a6c9`. A SHA-256 comparison found no
|
||||
identical non-generated file between that XMPP extension and this baseline.
|
||||
The provenance classification and future update rules are in
|
||||
[`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md).
|
||||
|
||||
## Reproduction
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run verify
|
||||
git status --short
|
||||
```
|
||||
|
||||
The package remains private until the separate public-release gates in
|
||||
`PROJECT.md` are approved.
|
||||
@@ -0,0 +1,76 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.2-beta.2 - 2026-09-10
|
||||
|
||||
- Add a bounded, configurable XEP-0199 probe on the existing authenticated
|
||||
connection, recording attempts, success, latency, failure state, and
|
||||
unsupported-server results while cleaning up every plugin-owned timer and
|
||||
listener on disconnect or stop.
|
||||
- Surface explicit starting, online, degraded, reconnecting, failed, and
|
||||
stopped phases together with xmpp.js reconnect attempts and XEP-0198 resume
|
||||
or full-rebind outcomes.
|
||||
- Add secure interactive multi-account onboarding with verified TLS, SRV or
|
||||
explicit secure endpoints, environment SecretRefs, explicit direct-message
|
||||
policy, normalized bare-JID allowlists, optional probing, connection
|
||||
validation before save, and no MUC prompts.
|
||||
- Expand deterministic coverage for probe concurrency and timeout, lifecycle
|
||||
listener cleanup, secure onboarding, bounded health configuration,
|
||||
malformed upload slots, failed uploads, HTTPS enforcement, and validated
|
||||
media-reader enforcement.
|
||||
|
||||
## 0.1.2-beta.1 - 2026-09-09
|
||||
|
||||
- Keep the development lockfile source-only and constrain Vitest resolution so
|
||||
the packed plugin installs cleanly through OpenClaw's production-only npm
|
||||
installer without resolving a conflicting development peer graph.
|
||||
- Forward the XEP-0363 `Authorization`, `Cookie`, and `Expires` slot headers
|
||||
required by authenticated HTTP PUT endpoints, while stripping CR/LF,
|
||||
retaining repeated values in order, rejecting every other slot header, and
|
||||
excluding authenticated uploads from debug HTTP capture.
|
||||
- Test the full Gateway account-start path to prove that unavailable TLS is
|
||||
refused before credentials or stanzas are sent, and that an env-backed
|
||||
SecretRef resolves through authenticated startup and clean shutdown without
|
||||
replacing the source configuration with plaintext.
|
||||
- Complete live interoperability against a second server implementation,
|
||||
ejabberd 26.7.0, covering verified TLS, SASL, resource binding, presence,
|
||||
bidirectional direct messages, receipts, chat states, replies, and shutdown.
|
||||
- Correlate XEP-0184 receipts with the sender's message `id`, while continuing
|
||||
to use a server-added XEP-0359 `stanza-id` as the stable deduplication key.
|
||||
|
||||
## 0.1.1 - 2026-09-05
|
||||
|
||||
- Publish the reviewed one-commit prerelease source on canonical SDF Gitea and
|
||||
a clearly labelled one-way GitHub mirror, while keeping package publication
|
||||
disabled pending the remaining release gates.
|
||||
- License the project as GNU GPL version 3 or later.
|
||||
- Record SDF Gitea as the canonical source and issue tracker, with GitHub
|
||||
reserved for a clearly labelled one-way mirror.
|
||||
- Name Eric (`soilDNRA`) as the initial maintainer and select GitHub Private
|
||||
Vulnerability Reporting on the future mirror for confidential reports.
|
||||
- Migrate the canonical project to the OpenClaw 2026.8.2 SDK, replacing the
|
||||
removed root SDK and deprecated broad runtime barrels with focused public
|
||||
imports while preserving guarded uploads and root-bounded local media reads.
|
||||
- Advertise the native XMPP `send` action to OpenClaw's shared message tool so
|
||||
structured text and media sends use the channel's validated outbound media
|
||||
reader and XEP-0363 uploader directly.
|
||||
- Present outbound media as XEP-0447 inline file shares with XEP-0446 file
|
||||
metadata, XEP-0300 SHA-256 integrity hashes for local uploads, and XEP-0428
|
||||
fallback indication while retaining XEP-0066 for older clients. Use the
|
||||
media URL alone as the fallback body, sending any caption as a preceding
|
||||
text stanza, for inline rendering in Conversations.
|
||||
- Request XEP-0363 upload slots through the full IQ API so responses whose
|
||||
`<slot/>` name differs from the `<request/>` name are parsed correctly.
|
||||
- Recover harmless whole-line Markdown wrappers around legacy `MEDIA:`
|
||||
directives in direct-message replies, while leaving inline prose, fenced
|
||||
examples, and unsafe media sources untouched.
|
||||
- Update the prerelease test toolchain to patched Vitest and nanoid releases;
|
||||
both production-only and full dependency audits now report no known
|
||||
vulnerabilities.
|
||||
|
||||
## 0.1.0 - 2026-08-13
|
||||
|
||||
- Initial native OpenClaw XMPP direct-message channel.
|
||||
- Multi-account configuration, TLS transport, pairing/allowlist ingress, typing
|
||||
states, delivery receipts, stanza deduplication, and XEP-0363 uploads.
|
||||
- Configurable outbound text chunking with a conservative 4,000-character
|
||||
default, including direct replies to inbound XMPP messages.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Contributing
|
||||
|
||||
The canonical repository and public issue tracker are hosted at
|
||||
<https://git.sdf.org/erici/openclaw-xmpp>. Any GitHub repository for this
|
||||
project is a one-way mirror for visibility and OpenClaw review.
|
||||
|
||||
Requirements: Node.js 22.22.3 or newer and npm.
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run verify
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Keep transport code independent from OpenClaw where practical and cover stanza
|
||||
normalization, access decisions, deduplication, and outbound metadata with
|
||||
offline tests. Tests must not contact public XMPP services.
|
||||
|
||||
Changes to authentication, TLS, access policy, session routing, local media
|
||||
roots, uploads, redirects, DNS/IP validation, or logging require focused
|
||||
negative tests as well as the normal success case. Do not weaken a fail-closed
|
||||
path to make a test or server pass.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
+1135
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,229 @@
|
||||
# OpenClaw XMPP
|
||||
|
||||
A native XMPP direct-message channel plugin for OpenClaw. It runs inside the
|
||||
OpenClaw Gateway and uses OpenClaw's normal routing, sessions, commands,
|
||||
delivery pipeline, pairing store, and status surfaces.
|
||||
|
||||
The canonical source repository is
|
||||
[SDF Gitea](https://git.sdf.org/erici/openclaw-xmpp). The
|
||||
[`soilDNRA/openclaw-xmpp`](https://github.com/soilDNRA/openclaw-xmpp) repository
|
||||
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. Its reviewed source is public for inspection and
|
||||
early testing, but the npm package remains marked `private` and there is no
|
||||
ClawHub or stable package release. Those distribution steps remain gated on
|
||||
the remaining beta-release checks and separate owner approval. Core
|
||||
interoperability has been exercised against both Prosody and ejabberd, and
|
||||
with Conversations and Gajim clients.
|
||||
|
||||
The durable project goal, status, decisions, and roadmap are maintained in
|
||||
[`PROJECT.md`](./PROJECT.md).
|
||||
|
||||
## Supported
|
||||
|
||||
- XMPP direct chats over verified TLS
|
||||
- Multiple named accounts
|
||||
- Bare-JID allowlists and OpenClaw pairing
|
||||
- Per-sender OpenClaw session routing
|
||||
- XEP-0085 chat states
|
||||
- XEP-0184 delivery receipts
|
||||
- XEP-0203 delayed-delivery timestamps
|
||||
- XEP-0359 origin/stanza IDs for deduplication
|
||||
- XEP-0363 HTTP upload for outbound local media
|
||||
- XEP-0447/XEP-0446 inline file sharing with MIME type, name, size, and
|
||||
XEP-0300 SHA-256 integrity metadata for uploaded local media
|
||||
- XEP-0066 out-of-band URL fallback for uploaded media
|
||||
- Structured OpenClaw message-tool sends using `media`, `mediaUrl`, `path`, or
|
||||
`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.
|
||||
|
||||
## Development
|
||||
|
||||
Development, issues, and release tags belong on the canonical SDF Gitea
|
||||
repository. The GitHub copy is a visibility and upstream-review mirror, not a
|
||||
second source of truth.
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run verify
|
||||
```
|
||||
|
||||
Package-shape validation:
|
||||
|
||||
```bash
|
||||
npm pack --dry-run
|
||||
```
|
||||
|
||||
Installing a packed artefact changes the active OpenClaw installation. Follow
|
||||
the release checklist and preserve a known-good rollback package before doing
|
||||
that on a live Gateway.
|
||||
|
||||
## Compatibility
|
||||
|
||||
- Node.js 22.22.3 or newer is required.
|
||||
- OpenClaw 2026.8.2 is the minimum supported Gateway and plugin API version.
|
||||
- CI runs the pinned OpenClaw 2026.8.2 baseline on Node.js 22.22.3 and Node.js
|
||||
24.
|
||||
- Before each release, the packed artefact must also pass loader and live
|
||||
smoke tests against the current stable OpenClaw release. A lower-bound
|
||||
version range is not a promise of compatibility with an untested future SDK.
|
||||
|
||||
## Configuration
|
||||
|
||||
Environment variables provide a minimal single-account setup:
|
||||
|
||||
```bash
|
||||
export XMPP_JID='bot@example.org'
|
||||
export XMPP_PASSWORD='use-an-app-password'
|
||||
```
|
||||
|
||||
Equivalent OpenClaw configuration:
|
||||
|
||||
```json
|
||||
{
|
||||
"channels": {
|
||||
"xmpp": {
|
||||
"enabled": true,
|
||||
"jid": "bot@example.org",
|
||||
"password": {
|
||||
"source": "env",
|
||||
"provider": "default",
|
||||
"id": "XMPP_PASSWORD"
|
||||
},
|
||||
"resource": "openclaw",
|
||||
"textChunkLimit": 4000,
|
||||
"dmPolicy": "pairing",
|
||||
"allowFrom": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For named accounts:
|
||||
|
||||
```json
|
||||
{
|
||||
"channels": {
|
||||
"xmpp": {
|
||||
"defaultAccount": "personal",
|
||||
"accounts": {
|
||||
"personal": {
|
||||
"enabled": true,
|
||||
"jid": "bot@example.org",
|
||||
"password": {
|
||||
"source": "env",
|
||||
"provider": "default",
|
||||
"id": "XMPP_PASSWORD"
|
||||
},
|
||||
"dmPolicy": "allowlist",
|
||||
"allowFrom": [
|
||||
"owner@example.org"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`allowFrom` entries are normalized to bare JIDs. `"*"` is accepted only when
|
||||
`dmPolicy` is `"open"`.
|
||||
|
||||
Long replies are split at paragraph boundaries where practical. Set
|
||||
`textChunkLimit` on the channel or an individual named account to change the
|
||||
maximum outbound message size; the default is 4,000 characters. A smaller
|
||||
value can improve compatibility with clients that truncate very long message
|
||||
bodies.
|
||||
|
||||
If normal DNS SRV discovery is unavailable, configure `service` or
|
||||
`websocketUrl`. Explicit `xmpp:` services must negotiate STARTTLS; `xmpps:`
|
||||
uses direct TLS, and WebSocket connections must use `wss:`. The plugin closes
|
||||
the connection before sending presence or messages if transport security is
|
||||
not active.
|
||||
|
||||
### Session continuity
|
||||
|
||||
XMPP uses OpenClaw's core session routing and lifecycle; the plugin does not
|
||||
silently impose its own reset schedule. For a personal conversational account,
|
||||
`session.dmScope: "per-channel-peer"` keeps each XMPP peer isolated while
|
||||
preserving a stable conversation binding. OpenClaw 2026.9.2 defaults to no
|
||||
automatic reset when no reset policy is configured, and compaction bounds the
|
||||
active model context as a conversation grows. Send `/new` or `/reset` when you
|
||||
deliberately want a fresh conversation; verify the default for other OpenClaw
|
||||
versions before relying on it.
|
||||
|
||||
Operators who want to make the no-automatic-reset choice explicit can use:
|
||||
|
||||
```json
|
||||
{
|
||||
"session": {
|
||||
"dmScope": "per-channel-peer",
|
||||
"resetByChannel": {
|
||||
"xmpp": { "mode": "none" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Automatic `daily` or `idle` reset policies are optional operator choices and
|
||||
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.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This project's roadmap has been informed by Mickaël Rémond and ProcessOne's
|
||||
earlier OpenClaw XMPP implementation, particularly its work on active health
|
||||
probing, reconnect visibility, onboarding, reactions, replies/threads, and
|
||||
MUC. Their implementation and maintenance offer are important prior work, and
|
||||
we gratefully credit them even where this project uses a fresh implementation.
|
||||
|
||||
Exact reviewed revisions, source paths, licence information, and the boundary
|
||||
between influence and adapted source are recorded in
|
||||
[`THIRD_PARTY_NOTICES.md`](./THIRD_PARTY_NOTICES.md).
|
||||
|
||||
## Licence
|
||||
|
||||
OpenClaw XMPP is free software licensed under the GNU General Public License,
|
||||
version 3 or (at your option) any later version. See [`LICENSE`](./LICENSE).
|
||||
|
||||
## Security
|
||||
|
||||
Please use the private reporting route described in
|
||||
[`SECURITY.md`](./SECURITY.md). Do not put credentials, private JIDs, message
|
||||
contents, server addresses, or exploit details in a public issue.
|
||||
|
||||
## Release checklist
|
||||
|
||||
- The licence is `GPL-3.0-or-later`; Eric is the initial maintainer. The
|
||||
reviewed source prerelease is public, but keep `private: true` until the
|
||||
package-release gates pass and package publication is separately approved.
|
||||
- Keep the SDF repository, issue tracker, and homepage metadata canonical.
|
||||
GitHub Private Vulnerability Reporting is enabled on the labelled mirror.
|
||||
- Run `npm run verify` on the minimum supported Node/OpenClaw versions.
|
||||
- Install the packed tarball using `npm-pack:` and inspect the loaded runtime.
|
||||
- Run live tests against at least two XMPP servers and clients.
|
||||
- Verify STARTTLS/direct TLS certificate failures are fail-closed.
|
||||
- Verify pairing, allowlist, reconnect, receipt, delayed stanza, and upload
|
||||
behavior.
|
||||
- Review the packed file list for secrets and machine-specific paths.
|
||||
- Require separate explicit owner approval for release tags, ClawHub
|
||||
publication, npm publication, and standard-installer inclusion.
|
||||
|
||||
Interactive OpenClaw channel setup now supports named accounts without
|
||||
hand-editing JSON. It requires a password environment-variable name and saves
|
||||
that reference as a SecretRef; the resolved password is never written to the
|
||||
configuration or displayed. Setup requires an explicit direct-message policy,
|
||||
refuses insecure WebSockets, explains explicit-host certificate verification,
|
||||
and validates TLS, authentication, and resource binding before returning a
|
||||
configuration to be saved.
|
||||
|
||||
XEP-0199 health probing is enabled conservatively by default (every 300
|
||||
seconds with a 15-second timeout). Set `healthProbe: false` to disable it, or
|
||||
use `healthProbeIntervalSeconds`, `healthProbeTimeoutSeconds`, and
|
||||
`reconnectDelaySeconds` within the manifest bounds. Channel status reports
|
||||
probe health, reconnect attempts, and XEP-0198 resume/full-rebind outcomes.
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# Security policy
|
||||
|
||||
## 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
|
||||
or newer and Node.js 22.22.3 or newer. Security fixes are made on the latest
|
||||
prerelease source only.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
The initial maintainer is Eric, using the GitHub account
|
||||
[`soilDNRA`](https://github.com/soilDNRA).
|
||||
|
||||
Private vulnerability reports will use GitHub Private Vulnerability Reporting
|
||||
on the labelled one-way mirror:
|
||||
|
||||
<https://github.com/soilDNRA/openclaw-xmpp/security/advisories/new>
|
||||
|
||||
Private Vulnerability Reporting is enabled on the mirror and the endpoint was
|
||||
verified before source publication. A GitHub account is required to submit a
|
||||
private report. Do not open a public issue containing credentials, private
|
||||
JIDs, message contents, server addresses, or exploit details.
|
||||
|
||||
The canonical source and public issue tracker remain on SDF Gitea. GitHub is
|
||||
used for confidential vulnerability coordination, not as a second source of
|
||||
truth.
|
||||
|
||||
Include the plugin, OpenClaw, Node.js, XMPP server, and client versions; the
|
||||
affected configuration surface; reproduction steps; and whether the issue can
|
||||
expose credentials, bypass access control, cross session boundaries, or reach
|
||||
private network or filesystem resources. Redact secrets and personal data.
|
||||
|
||||
## Security model
|
||||
|
||||
- TLS certificate verification is never disabled by plugin configuration.
|
||||
- Credentials support OpenClaw `SecretInput` values and environment variables.
|
||||
- Direct messages default to pairing and can be restricted to bare JIDs.
|
||||
- Group chats and MUC invitations are ignored.
|
||||
- Inbound message IDs are deduplicated before agent dispatch.
|
||||
- Errors and status output do not expose passwords or message bodies.
|
||||
- Local media uploads are restricted to approved roots and a size limit.
|
||||
Remote media references must be HTTPS and pass DNS/IP safety checks; upload
|
||||
slot redirects and headers are restricted.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Third-party notices and provenance
|
||||
|
||||
This file is both an attribution record and a source-provenance ledger. Update
|
||||
it in the same commit whenever source, tests, fixtures, or substantial text are
|
||||
copied or closely adapted from another project.
|
||||
|
||||
## Pre-adoption baseline
|
||||
|
||||
Commit `11db813a292a1215f59032b36617251c8553ccbd` contains the independently
|
||||
developed local implementation as it existed before selective adoption work.
|
||||
No code from the external implementation recorded below was intentionally
|
||||
copied or closely adapted into that commit.
|
||||
|
||||
## Influential earlier XMPP work
|
||||
|
||||
Mickaël Rémond of ProcessOne authored an earlier OpenClaw XMPP extension and
|
||||
offered ProcessOne's XMPP expertise and maintenance help. Its health-probe,
|
||||
reconnect-observability, onboarding, reaction, reply/thread, and MUC product
|
||||
ideas informed this project's comparative review and roadmap. We gratefully
|
||||
credit Rémond and ProcessOne for that work, including where this project later
|
||||
uses a fresh implementation rather than their source.
|
||||
|
||||
- Project: ProcessOne fork of OpenClaw, `xmpp-support` branch
|
||||
- Pull request: <https://github.com/openclaw/openclaw/pull/9741>
|
||||
- Branch: <https://github.com/processone/openclaw/tree/xmpp-support/extensions/xmpp>
|
||||
- Author of the reviewed 17-commit XMPP history: Mickaël Rémond
|
||||
- Licence: MIT, inherited from the parent OpenClaw repository
|
||||
- Reviewed PR head: `8a4bc4314ae39f8c5693051dc7bf604ddda0a6c9`
|
||||
- Reviewed branch head: `a6adb95b35c183a81eef3afcef17071e9b647673`
|
||||
- Upstream licence: <https://github.com/processone/openclaw/blob/xmpp-support/LICENSE>
|
||||
|
||||
## Provenance ledger
|
||||
|
||||
| Subject | Upstream source path and commits | Local destination | Classification |
|
||||
| --- | --- | --- | --- |
|
||||
| Overall extension and onboarding | `extensions/xmpp/**`, introduced at `a78b3e9ac2d718c48b225f5c1f03fe645ff99265`; especially `src/onboarding.ts` and `src/config-schema.ts` | `PROJECT.md`, README acknowledgement; no baseline source destination | Design and comparative-review influence; independently written local baseline |
|
||||
| Active health probing | `src/probe.ts`, `src/channel.ts`, and `src/client.ts`; evolution at `09fd0822c70768c11d0dcae8fd67f19ca30322e4`, `4a092fdaa6d679f8df212196101a3825dd83c3e4`, `5722097c679bf8cdadb8b4d00023ca0cdabc46be`, `bf20f91fb6259abff763155fe6efaccc891cbbd1`, and `a6adb95b35c183a81eef3afcef17071e9b647673` | None yet | Planned fresh implementation; no code carried into the baseline |
|
||||
| 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 |
|
||||
|
||||
## Rule for later adaptation
|
||||
|
||||
For each future copied or closely adapted contribution, add the exact upstream
|
||||
commit and source path, the local destination path, the author/project, and the
|
||||
applicable licence notice before merging it. Preserve the upstream MIT notice
|
||||
verbatim when it applies. Independently reimplemented ideas still receive
|
||||
plain-language credit, but must not be described as copied code.
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
defineChannelPluginEntry
|
||||
} from "openclaw/plugin-sdk/channel-core";
|
||||
|
||||
import { xmppPlugin } from "./src/channel.js";
|
||||
import { setXmppPluginRuntime } from "./src/inbound.js";
|
||||
|
||||
const xmppPluginEntry: ReturnType<
|
||||
typeof defineChannelPluginEntry<typeof xmppPlugin>
|
||||
> = defineChannelPluginEntry({
|
||||
id: "xmpp",
|
||||
name: "XMPP",
|
||||
description: "Native XMPP direct-message channel for OpenClaw.",
|
||||
plugin: xmppPlugin,
|
||||
setRuntime: setXmppPluginRuntime,
|
||||
configSchema: {
|
||||
schema: {
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export default xmppPluginEntry;
|
||||
|
||||
export { xmppPlugin } from "./src/channel.js";
|
||||
@@ -0,0 +1,292 @@
|
||||
{
|
||||
"id": "xmpp",
|
||||
"name": "XMPP",
|
||||
"description": "Native XMPP direct-message channel for OpenClaw.",
|
||||
"version": "0.1.2-beta.2",
|
||||
"activation": {
|
||||
"onStartup": false
|
||||
},
|
||||
"channels": [
|
||||
"xmpp"
|
||||
],
|
||||
"channelEnvVars": {
|
||||
"xmpp": [
|
||||
"XMPP_JID",
|
||||
"XMPP_PASSWORD",
|
||||
"XMPP_SERVICE",
|
||||
"XMPP_WEBSOCKET_URL"
|
||||
]
|
||||
},
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {}
|
||||
},
|
||||
"channelConfigs": {
|
||||
"xmpp": {
|
||||
"schema": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"defaultAccount": {
|
||||
"type": "string"
|
||||
},
|
||||
"jid": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"$ref": "#/definitions/secretInput"
|
||||
},
|
||||
"resource": {
|
||||
"type": "string"
|
||||
},
|
||||
"service": {
|
||||
"type": "string"
|
||||
},
|
||||
"websocketUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"dmPolicy": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"pairing",
|
||||
"allowlist",
|
||||
"open",
|
||||
"disabled"
|
||||
]
|
||||
},
|
||||
"allowFrom": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"sendReceipts": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"requestReceipts": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"sendChatStates": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"textChunkLimit": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 100000
|
||||
},
|
||||
"mediaMaxMb": {
|
||||
"type": "number",
|
||||
"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 },
|
||||
"dm": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"sessionScope": {
|
||||
"type": "string",
|
||||
"enum": ["per-user", "per-channel-peer", "per-account-channel-peer"]
|
||||
},
|
||||
"threadReplies": {
|
||||
"type": "string",
|
||||
"enum": ["off", "inbound", "always"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"threadBindings": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"idleHours": { "type": "number", "minimum": 0 },
|
||||
"maxAgeHours": { "type": "number", "minimum": 0 },
|
||||
"spawnSessions": { "type": "boolean" }
|
||||
}
|
||||
},
|
||||
"accounts": {
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9][a-z0-9_-]{0,63}$"
|
||||
},
|
||||
"additionalProperties": {
|
||||
"$ref": "#/definitions/account"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"secretInput": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"source",
|
||||
"provider",
|
||||
"id"
|
||||
],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"env",
|
||||
"file",
|
||||
"exec"
|
||||
]
|
||||
},
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_-]{0,63}$"
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"account": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"jid": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"$ref": "#/definitions/secretInput"
|
||||
},
|
||||
"resource": {
|
||||
"type": "string"
|
||||
},
|
||||
"service": {
|
||||
"type": "string"
|
||||
},
|
||||
"websocketUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"dmPolicy": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"pairing",
|
||||
"allowlist",
|
||||
"open",
|
||||
"disabled"
|
||||
]
|
||||
},
|
||||
"allowFrom": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"sendReceipts": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"requestReceipts": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"sendChatStates": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"textChunkLimit": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 100000
|
||||
},
|
||||
"mediaMaxMb": {
|
||||
"type": "number",
|
||||
"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 },
|
||||
"dm": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"sessionScope": {
|
||||
"type": "string",
|
||||
"enum": ["per-user", "per-channel-peer", "per-account-channel-peer"]
|
||||
},
|
||||
"threadReplies": {
|
||||
"type": "string",
|
||||
"enum": ["off", "inbound", "always"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"threadBindings": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"idleHours": { "type": "number", "minimum": 0 },
|
||||
"maxAgeHours": { "type": "number", "minimum": 0 },
|
||||
"spawnSessions": { "type": "boolean" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"uiHints": {
|
||||
"dm.sessionScope": {
|
||||
"label": "XMPP DM Session Scope",
|
||||
"help": "Controls how direct messages from the same peer are routed to OpenClaw sessions (per-channel-peer recommended for continuity)."
|
||||
},
|
||||
"dm.threadReplies": {
|
||||
"label": "XMPP Thread Replies",
|
||||
"help": "How inbound replies are presented to the model."
|
||||
},
|
||||
"threadBindings.enabled": {
|
||||
"label": "XMPP Thread Bindings Enabled"
|
||||
},
|
||||
"jid": {
|
||||
"label": "XMPP JID",
|
||||
"placeholder": "bot@example.org"
|
||||
},
|
||||
"password": {
|
||||
"label": "Password",
|
||||
"sensitive": true
|
||||
},
|
||||
"service": {
|
||||
"label": "XMPP service",
|
||||
"placeholder": "xmpps://xmpp.example.org:5223"
|
||||
},
|
||||
"websocketUrl": {
|
||||
"label": "WebSocket URL",
|
||||
"placeholder": "wss://xmpp.example.org/xmpp-websocket"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Allowed bare JIDs"
|
||||
},
|
||||
"textChunkLimit": {
|
||||
"label": "Outbound text chunk size",
|
||||
"help": "Maximum characters per outbound message (default: 4000)."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+7292
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"name": "openclaw-xmpp",
|
||||
"version": "0.1.2-beta.2",
|
||||
"description": "Native XMPP direct-message channel plugin for OpenClaw.",
|
||||
"keywords": [
|
||||
"openclaw",
|
||||
"xmpp",
|
||||
"jabber",
|
||||
"channel",
|
||||
"plugin"
|
||||
],
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"license": "GPL-3.0-or-later",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://git.sdf.org/erici/openclaw-xmpp.git"
|
||||
},
|
||||
"homepage": "https://git.sdf.org/erici/openclaw-xmpp",
|
||||
"bugs": {
|
||||
"url": "https://git.sdf.org/erici/openclaw-xmpp/issues"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.22.3"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"clean": "node scripts/clean.mjs",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"pack:check": "npm pack --dry-run",
|
||||
"verify": "npm run clean && npm run typecheck && npm test && npm run build && npm run pack:check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@openclaw/fs-safe": "0.5.6",
|
||||
"@xmpp/client": "0.14.0",
|
||||
"@xmpp/xml": "0.14.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"openclaw": ">=2026.8.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"openclaw": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "24.10.1",
|
||||
"@types/xmpp__client": "0.14.1",
|
||||
"@types/xmpp__xml": "0.13.5",
|
||||
"openclaw": "2026.8.2",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "4.1.11"
|
||||
},
|
||||
"overrides": {
|
||||
"nanoid": "3.3.18",
|
||||
"vitest": "4.1.11"
|
||||
},
|
||||
"openclaw": {
|
||||
"extensions": [
|
||||
"./dist/index.js"
|
||||
],
|
||||
"setupEntry": "./dist/setup-entry.js",
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.8.2",
|
||||
"minGatewayVersion": "2026.8.2"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.8.2",
|
||||
"pluginSdkVersion": "2026.8.2"
|
||||
},
|
||||
"runtimeExtensions": [
|
||||
"./dist/index.js"
|
||||
],
|
||||
"runtimeSetupEntry": "./dist/setup-entry.js"
|
||||
},
|
||||
"files": [
|
||||
"dist/**",
|
||||
"openclaw.plugin.json",
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"THIRD_PARTY_NOTICES.md",
|
||||
"SECURITY.md",
|
||||
"CONTRIBUTING.md",
|
||||
"CHANGELOG.md"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
|
||||
await Promise.all([
|
||||
rm(new URL("../dist", import.meta.url), { recursive: true, force: true }),
|
||||
rm(new URL("../coverage", import.meta.url), { recursive: true, force: true })
|
||||
]);
|
||||
@@ -0,0 +1,6 @@
|
||||
import { defineSetupPluginEntry } from "openclaw/plugin-sdk/channel-core";
|
||||
|
||||
import { xmppPlugin } from "./src/channel.js";
|
||||
|
||||
export default defineSetupPluginEntry(xmppPlugin);
|
||||
export { xmppPlugin };
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
import {
|
||||
createChatChannelPlugin,
|
||||
type ChannelPlugin,
|
||||
type OpenClawConfig
|
||||
} from "openclaw/plugin-sdk/channel-core";
|
||||
import {
|
||||
createMessageReceiptFromOutboundResults,
|
||||
defineChannelMessageAdapter
|
||||
} from "openclaw/plugin-sdk/channel-outbound";
|
||||
import { chunkTextForOutbound } from "openclaw/plugin-sdk/text-chunking";
|
||||
import { extractToolSend } from "openclaw/plugin-sdk/tool-send";
|
||||
|
||||
import {
|
||||
listXmppAccountIds,
|
||||
resolveDefaultXmppAccountId,
|
||||
resolveXmppAccount,
|
||||
resolveXmppConnectionConfig,
|
||||
setXmppAccountEnabled,
|
||||
type ResolvedXmppAccount
|
||||
} from "./config.js";
|
||||
import { DEFAULT_TEXT_CHUNK_LIMIT } from "./constants.js";
|
||||
import {
|
||||
getXmppPluginRuntime,
|
||||
handleInboundXmppMessage,
|
||||
} from "./inbound.js";
|
||||
import { normalizeBareJid, normalizeXmppTarget } from "./jid.js";
|
||||
import {
|
||||
getLiveTransport,
|
||||
registerLiveTransport,
|
||||
XmppTransport,
|
||||
type XmppTransportStatus
|
||||
} from "./transport.js";
|
||||
import { xmppSetupWizard } from "./setup.js";
|
||||
|
||||
function resolveAccountId(cfg: OpenClawConfig, accountId?: string | null): string {
|
||||
return accountId ?? resolveDefaultXmppAccountId(cfg);
|
||||
}
|
||||
|
||||
function requireTransport(
|
||||
cfg: OpenClawConfig,
|
||||
accountId?: string | null
|
||||
): XmppTransport {
|
||||
const resolvedId = resolveAccountId(cfg, accountId);
|
||||
const transport = getLiveTransport(resolvedId);
|
||||
if (!transport) {
|
||||
throw new Error(`XMPP account "${resolvedId}" is not connected.`);
|
||||
}
|
||||
return transport;
|
||||
}
|
||||
|
||||
function normalizeTargetOrThrow(value: string): string {
|
||||
const target = normalizeXmppTarget(value);
|
||||
if (!target) {
|
||||
throw new Error("Expected an XMPP target such as user@example.org.");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
async function sendText(params: {
|
||||
cfg: OpenClawConfig;
|
||||
to: string;
|
||||
text: string;
|
||||
accountId?: string | null;
|
||||
}): Promise<{ channel: "xmpp"; messageId: string; toJid: string }> {
|
||||
const to = normalizeTargetOrThrow(params.to);
|
||||
const sent = await requireTransport(params.cfg, params.accountId).sendText(
|
||||
to,
|
||||
params.text
|
||||
);
|
||||
return { channel: "xmpp", messageId: sent.id, toJid: to };
|
||||
}
|
||||
|
||||
async function sendMedia(params: {
|
||||
cfg: OpenClawConfig;
|
||||
to: string;
|
||||
text: string;
|
||||
mediaUrl: string;
|
||||
accountId?: string | null;
|
||||
mediaReadFile?: (filePath: string) => Promise<Buffer>;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<{ channel: "xmpp"; messageId: string; toJid: string }> {
|
||||
const to = normalizeTargetOrThrow(params.to);
|
||||
const sent = await requireTransport(params.cfg, params.accountId).sendMedia({
|
||||
to,
|
||||
text: params.text,
|
||||
mediaUrl: params.mediaUrl,
|
||||
...(params.mediaReadFile ? { mediaReadFile: params.mediaReadFile } : {}),
|
||||
...(params.signal ? { signal: params.signal } : {})
|
||||
});
|
||||
return { channel: "xmpp", messageId: sent.id, toJid: to };
|
||||
}
|
||||
|
||||
const xmppMessageAdapter = defineChannelMessageAdapter({
|
||||
id: "xmpp",
|
||||
durableFinal: {
|
||||
capabilities: {
|
||||
text: true,
|
||||
media: true
|
||||
}
|
||||
},
|
||||
receive: {
|
||||
defaultAckPolicy: "after_agent_dispatch",
|
||||
supportedAckPolicies: ["after_agent_dispatch"]
|
||||
},
|
||||
send: {
|
||||
text: async (ctx) => {
|
||||
const result = await sendText({
|
||||
cfg: ctx.cfg,
|
||||
to: ctx.to,
|
||||
text: ctx.text,
|
||||
...(ctx.accountId !== undefined ? { accountId: ctx.accountId } : {})
|
||||
});
|
||||
return {
|
||||
messageId: result.messageId,
|
||||
receipt: createMessageReceiptFromOutboundResults({
|
||||
results: [result],
|
||||
kind: "text",
|
||||
...(ctx.replyToId ? { replyToId: ctx.replyToId } : {})
|
||||
})
|
||||
};
|
||||
},
|
||||
media: async (ctx) => {
|
||||
const result = await sendMedia({
|
||||
cfg: ctx.cfg,
|
||||
to: ctx.to,
|
||||
text: ctx.text,
|
||||
mediaUrl: ctx.mediaUrl,
|
||||
...(ctx.accountId !== undefined ? { accountId: ctx.accountId } : {}),
|
||||
...(ctx.mediaAccess?.readFile
|
||||
? { mediaReadFile: ctx.mediaAccess.readFile }
|
||||
: ctx.mediaReadFile
|
||||
? { mediaReadFile: ctx.mediaReadFile }
|
||||
: {}),
|
||||
...(ctx.signal ? { signal: ctx.signal } : {})
|
||||
});
|
||||
return {
|
||||
messageId: result.messageId,
|
||||
receipt: createMessageReceiptFromOutboundResults({
|
||||
results: [result],
|
||||
kind: "media",
|
||||
...(ctx.replyToId ? { replyToId: ctx.replyToId } : {})
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const outbound = {
|
||||
deliveryMode: "direct" as const,
|
||||
chunker: chunkTextForOutbound,
|
||||
textChunkLimit: DEFAULT_TEXT_CHUNK_LIMIT,
|
||||
chunkerMode: "text" as const,
|
||||
resolveTarget: ({ to }: { to?: string }) => {
|
||||
const normalized = to ? normalizeXmppTarget(to) : undefined;
|
||||
return normalized
|
||||
? { ok: true as const, to: normalized }
|
||||
: {
|
||||
ok: false as const,
|
||||
error: new Error("Expected an XMPP target such as user@example.org.")
|
||||
};
|
||||
},
|
||||
sendText: async (ctx: {
|
||||
cfg: OpenClawConfig;
|
||||
to: string;
|
||||
text: string;
|
||||
accountId?: string | null;
|
||||
}) => await sendText(ctx),
|
||||
sendMedia: async (ctx: {
|
||||
cfg: OpenClawConfig;
|
||||
to: string;
|
||||
text: string;
|
||||
mediaUrl?: string;
|
||||
accountId?: string | null;
|
||||
mediaAccess?: { readFile?: (filePath: string) => Promise<Buffer> };
|
||||
mediaReadFile?: (filePath: string) => Promise<Buffer>;
|
||||
}) => {
|
||||
if (!ctx.mediaUrl) {
|
||||
throw new Error("XMPP media send requires mediaUrl.");
|
||||
}
|
||||
return await sendMedia({
|
||||
cfg: ctx.cfg,
|
||||
to: ctx.to,
|
||||
text: ctx.text,
|
||||
mediaUrl: ctx.mediaUrl,
|
||||
...(ctx.accountId !== undefined ? { accountId: ctx.accountId } : {}),
|
||||
...(ctx.mediaAccess?.readFile
|
||||
? { mediaReadFile: ctx.mediaAccess.readFile }
|
||||
: ctx.mediaReadFile
|
||||
? { mediaReadFile: ctx.mediaReadFile }
|
||||
: {})
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const xmppMessageActions = {
|
||||
describeMessageTool: ({ cfg, accountId }: {
|
||||
cfg: OpenClawConfig;
|
||||
accountId?: string | null;
|
||||
}) => {
|
||||
const account = resolveXmppAccount(cfg, accountId);
|
||||
return account.enabled && account.configured
|
||||
? { actions: ["send" as const], capabilities: [] }
|
||||
: { actions: [], capabilities: [] };
|
||||
},
|
||||
supportsAction: ({ action }: { action: string }) => action === "send",
|
||||
extractToolSend: ({ args }: { args: Record<string, unknown> }) =>
|
||||
extractToolSend(args, "send")
|
||||
};
|
||||
|
||||
function statusSnapshot(
|
||||
account: ResolvedXmppAccount,
|
||||
status?: XmppTransportStatus
|
||||
) {
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
...(account.name ? { name: account.name } : {}),
|
||||
enabled: account.enabled,
|
||||
configured: account.configured,
|
||||
running: Boolean(status),
|
||||
connected: status?.connected ?? false,
|
||||
...(status?.boundJid ? { bot: { jid: status.boundJid } } : {}),
|
||||
...(status?.lastConnectedAt
|
||||
? { lastConnectedAt: status.lastConnectedAt }
|
||||
: {}),
|
||||
...(status?.lastDisconnectedAt
|
||||
? { lastDisconnect: { at: status.lastDisconnectedAt } }
|
||||
: {}),
|
||||
...(status?.lastInboundAt ? { lastInboundAt: status.lastInboundAt } : {}),
|
||||
...(status?.lastOutboundAt
|
||||
? { lastOutboundAt: status.lastOutboundAt }
|
||||
: {}),
|
||||
...(status?.lastError ? { lastError: status.lastError } : {}),
|
||||
...(status?.phase ? { phase: status.phase } : {}),
|
||||
...(status?.reconnectAttempts !== undefined
|
||||
? { reconnectAttempts: status.reconnectAttempts }
|
||||
: {}),
|
||||
...(status?.lastReconnectedAt
|
||||
? { lastReconnectedAt: status.lastReconnectedAt }
|
||||
: {}),
|
||||
...(status?.streamManagement
|
||||
? { streamManagement: status.streamManagement }
|
||||
: {}),
|
||||
...(status?.lastProbeAt ? { lastProbeAt: status.lastProbeAt } : {}),
|
||||
...(status?.lastProbeSuccessAt
|
||||
? { lastProbeSuccessAt: status.lastProbeSuccessAt }
|
||||
: {}),
|
||||
...(status?.lastProbeLatencyMs !== undefined
|
||||
? { lastProbeLatencyMs: status.lastProbeLatencyMs }
|
||||
: {}),
|
||||
...(status?.probeFailures !== undefined
|
||||
? { probeFailures: status.probeFailures }
|
||||
: {}),
|
||||
...(status?.lastProbeResult
|
||||
? { lastProbeResult: status.lastProbeResult }
|
||||
: {}),
|
||||
dmPolicy: account.dmPolicy,
|
||||
allowFrom: account.allowFrom
|
||||
};
|
||||
}
|
||||
|
||||
const basePlugin: Omit<
|
||||
ChannelPlugin<ResolvedXmppAccount>,
|
||||
"security" | "pairing" | "outbound"
|
||||
> = {
|
||||
id: "xmpp",
|
||||
meta: {
|
||||
id: "xmpp",
|
||||
label: "XMPP",
|
||||
selectionLabel: "XMPP (plugin)",
|
||||
docsPath: "/channels/xmpp",
|
||||
docsLabel: "xmpp",
|
||||
blurb: "Open-standard federated direct messaging.",
|
||||
order: 75,
|
||||
markdownCapable: false,
|
||||
quickstartAllowFrom: true
|
||||
},
|
||||
capabilities: {
|
||||
chatTypes: ["direct"],
|
||||
media: true
|
||||
},
|
||||
reload: {
|
||||
configPrefixes: ["channels.xmpp"]
|
||||
},
|
||||
config: {
|
||||
listAccountIds: listXmppAccountIds,
|
||||
resolveAccount: resolveXmppAccount,
|
||||
defaultAccountId: resolveDefaultXmppAccountId,
|
||||
setAccountEnabled: ({ cfg, accountId, enabled }) =>
|
||||
setXmppAccountEnabled(cfg, accountId, enabled),
|
||||
isEnabled: (account) => account.enabled,
|
||||
isConfigured: (account) => account.configured,
|
||||
disabledReason: () => "XMPP account is disabled.",
|
||||
unconfiguredReason: () => "XMPP JID or password is not configured.",
|
||||
describeAccount: (account) => statusSnapshot(account),
|
||||
resolveAllowFrom: ({ cfg, accountId }) =>
|
||||
resolveXmppAccount(cfg, accountId).allowFrom,
|
||||
formatAllowFrom: ({ allowFrom }) =>
|
||||
allowFrom
|
||||
.map((entry) => normalizeBareJid(String(entry)))
|
||||
.filter((entry): entry is string => Boolean(entry)),
|
||||
hasConfiguredState: ({ cfg }) =>
|
||||
listXmppAccountIds(cfg).some(
|
||||
(accountId) => resolveXmppAccount(cfg, accountId).configured
|
||||
)
|
||||
},
|
||||
setupWizard: xmppSetupWizard,
|
||||
messaging: {
|
||||
defaultMarkdownTableMode: "bullets",
|
||||
targetPrefixes: ["xmpp"],
|
||||
normalizeTarget: normalizeXmppTarget,
|
||||
targetResolver: {
|
||||
looksLikeId: (raw) => Boolean(normalizeXmppTarget(raw)),
|
||||
hint: "<user@example.org>"
|
||||
}
|
||||
},
|
||||
message: xmppMessageAdapter,
|
||||
actions: xmppMessageActions,
|
||||
status: {
|
||||
defaultRuntime: {
|
||||
accountId: "default",
|
||||
running: false,
|
||||
connected: false
|
||||
},
|
||||
buildAccountSnapshot: ({ account, runtime }) => ({
|
||||
...statusSnapshot(
|
||||
account,
|
||||
runtime
|
||||
? ({
|
||||
...runtime,
|
||||
connected: runtime.connected ?? false,
|
||||
phase: (runtime as { phase?: XmppTransportStatus["phase"] }).phase
|
||||
?? (runtime.connected ? "online" : "stopped")
|
||||
} as XmppTransportStatus)
|
||||
: undefined
|
||||
)
|
||||
})
|
||||
},
|
||||
gateway: {
|
||||
startAccount: async (ctx) => {
|
||||
if (!ctx.channelRuntime) {
|
||||
throw new Error("OpenClaw channel runtime is unavailable.");
|
||||
}
|
||||
const connection = await resolveXmppConnectionConfig(
|
||||
ctx.cfg,
|
||||
ctx.accountId
|
||||
);
|
||||
const pluginRuntime = getXmppPluginRuntime();
|
||||
let transport!: XmppTransport;
|
||||
transport = new XmppTransport(connection, {
|
||||
log: ctx.log ?? {
|
||||
info: ctx.runtime.log,
|
||||
warn: ctx.runtime.log,
|
||||
error: ctx.runtime.error
|
||||
},
|
||||
onStatus: (next) => {
|
||||
ctx.setStatus(statusSnapshot(ctx.account, next));
|
||||
},
|
||||
onMessage: async (message) => {
|
||||
await handleInboundXmppMessage({
|
||||
cfg: ctx.cfg,
|
||||
account: connection,
|
||||
transport,
|
||||
runtime: pluginRuntime,
|
||||
message,
|
||||
log: ctx.log ?? {
|
||||
info: ctx.runtime.log,
|
||||
warn: ctx.runtime.log,
|
||||
error: ctx.runtime.error
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
const unregister = registerLiveTransport(ctx.accountId, transport);
|
||||
ctx.setStatus(statusSnapshot(ctx.account, transport.status));
|
||||
try {
|
||||
await transport.run(ctx.abortSignal);
|
||||
} finally {
|
||||
unregister();
|
||||
}
|
||||
},
|
||||
stopAccount: async (ctx) => {
|
||||
await getLiveTransport(ctx.accountId)?.stop();
|
||||
}
|
||||
},
|
||||
heartbeat: {
|
||||
checkReady: async ({ cfg, accountId }) => {
|
||||
const resolvedId = resolveAccountId(cfg, accountId);
|
||||
const transport = getLiveTransport(resolvedId);
|
||||
if (!transport?.status.connected) {
|
||||
return { ok: false, reason: "not connected" };
|
||||
}
|
||||
if (!transport.config.healthProbe) {
|
||||
return { ok: true, reason: "connected; health probe disabled" };
|
||||
}
|
||||
const result = await transport.probe();
|
||||
return result === undefined || result === "success" || result === "unsupported"
|
||||
? { ok: true, reason: result === "success" ? "probe succeeded" : result === "unsupported" ? "connected; server does not support XEP-0199" : "connected; health probe in progress" }
|
||||
: { ok: false, reason: `health probe ${result ?? "already running"}` };
|
||||
},
|
||||
sendTyping: async ({ cfg, to, accountId }) => {
|
||||
await requireTransport(cfg, accountId).sendChatState(
|
||||
normalizeTargetOrThrow(to),
|
||||
"composing"
|
||||
);
|
||||
},
|
||||
clearTyping: async ({ cfg, to, accountId }) => {
|
||||
await requireTransport(cfg, accountId).sendChatState(
|
||||
normalizeTargetOrThrow(to),
|
||||
"active"
|
||||
);
|
||||
}
|
||||
},
|
||||
doctor: {
|
||||
dmAllowFromMode: "topOrNested",
|
||||
groupModel: "sender",
|
||||
groupAllowFromFallbackToAllowFrom: false,
|
||||
warnOnEmptyGroupSenderAllowlist: false
|
||||
}
|
||||
};
|
||||
|
||||
export const xmppPlugin = createChatChannelPlugin({
|
||||
base: basePlugin,
|
||||
security: {
|
||||
dm: {
|
||||
channelKey: "xmpp",
|
||||
resolvePolicy: (account) => account.dmPolicy,
|
||||
resolveAllowFrom: (account) => account.allowFrom,
|
||||
defaultPolicy: "pairing",
|
||||
normalizeEntry: (raw) => normalizeBareJid(raw) ?? raw.trim()
|
||||
},
|
||||
collectWarnings: ({ account }) => {
|
||||
const warnings: string[] = [];
|
||||
if (account.dmPolicy === "open") {
|
||||
warnings.push(
|
||||
`XMPP account "${account.accountId}" accepts direct messages from anyone.`
|
||||
);
|
||||
}
|
||||
if (!account.enabled || !account.configured) {
|
||||
return warnings;
|
||||
}
|
||||
if (account.service?.startsWith("ws:")) {
|
||||
warnings.push("Insecure XMPP WebSocket URLs are not supported.");
|
||||
}
|
||||
return warnings;
|
||||
}
|
||||
},
|
||||
pairing: {
|
||||
text: {
|
||||
idLabel: "XMPP JID",
|
||||
message: "Your XMPP account has been approved for OpenClaw.",
|
||||
normalizeAllowEntry: (raw) => normalizeBareJid(raw) ?? raw.trim(),
|
||||
notify: async ({ cfg, id, accountId, message }) => {
|
||||
await requireTransport(cfg, accountId).sendText(
|
||||
normalizeTargetOrThrow(id),
|
||||
message
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
outbound
|
||||
});
|
||||
+351
@@ -0,0 +1,351 @@
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
import type { SecretInput } from "openclaw/plugin-sdk/secret-input";
|
||||
import {
|
||||
hasConfiguredSecretInput,
|
||||
resolveConfiguredSecretInputString
|
||||
} from "openclaw/plugin-sdk/secret-input-runtime";
|
||||
|
||||
import {
|
||||
DEFAULT_ACCOUNT_ID,
|
||||
DEFAULT_MEDIA_MAX_MB,
|
||||
DEFAULT_RESOURCE
|
||||
} from "./constants.js";
|
||||
import {
|
||||
jidDomain,
|
||||
jidLocalpart,
|
||||
normalizeBareJid
|
||||
} from "./jid.js";
|
||||
|
||||
export type XmppDmPolicy = "pairing" | "allowlist" | "open" | "disabled";
|
||||
|
||||
export type XmppDmSessionScope = "per-user" | "per-channel-peer" | "per-account-channel-peer";
|
||||
export type XmppThreadReplies = "off" | "inbound" | "always";
|
||||
|
||||
export interface XmppDmConfig {
|
||||
sessionScope?: XmppDmSessionScope;
|
||||
threadReplies?: XmppThreadReplies;
|
||||
}
|
||||
|
||||
export interface XmppThreadBindingsConfig {
|
||||
enabled?: boolean;
|
||||
idleHours?: number;
|
||||
maxAgeHours?: number;
|
||||
spawnSessions?: boolean;
|
||||
}
|
||||
|
||||
export interface XmppAccountConfig {
|
||||
enabled?: boolean;
|
||||
name?: string;
|
||||
jid?: string;
|
||||
password?: SecretInput;
|
||||
resource?: string;
|
||||
service?: string;
|
||||
websocketUrl?: string;
|
||||
dmPolicy?: XmppDmPolicy;
|
||||
allowFrom?: string[];
|
||||
sendReceipts?: boolean;
|
||||
requestReceipts?: boolean;
|
||||
sendChatStates?: boolean;
|
||||
textChunkLimit?: number;
|
||||
mediaMaxMb?: number;
|
||||
healthProbe?: boolean;
|
||||
healthProbeIntervalSeconds?: number;
|
||||
healthProbeTimeoutSeconds?: number;
|
||||
reconnectDelaySeconds?: number;
|
||||
dm?: XmppDmConfig;
|
||||
threadBindings?: XmppThreadBindingsConfig;
|
||||
}
|
||||
|
||||
export interface XmppChannelConfig extends XmppAccountConfig {
|
||||
defaultAccount?: string;
|
||||
accounts?: Record<string, XmppAccountConfig>;
|
||||
}
|
||||
|
||||
export interface ResolvedXmppAccount {
|
||||
accountId: string;
|
||||
name?: string;
|
||||
enabled: boolean;
|
||||
configured: boolean;
|
||||
jid?: string;
|
||||
password?: SecretInput;
|
||||
resource: string;
|
||||
service?: string;
|
||||
websocketUrl?: string;
|
||||
dmPolicy: XmppDmPolicy;
|
||||
allowFrom: string[];
|
||||
sendReceipts: boolean;
|
||||
requestReceipts: boolean;
|
||||
sendChatStates: boolean;
|
||||
mediaMaxMb: number;
|
||||
healthProbe: boolean;
|
||||
healthProbeIntervalSeconds: number;
|
||||
healthProbeTimeoutSeconds: number;
|
||||
reconnectDelaySeconds: number;
|
||||
dm?: XmppDmConfig;
|
||||
threadBindings?: XmppThreadBindingsConfig;
|
||||
}
|
||||
|
||||
export interface XmppConnectionConfig {
|
||||
accountId: string;
|
||||
jid: string;
|
||||
domain: string;
|
||||
username: string;
|
||||
password: string;
|
||||
resource: string;
|
||||
service: string;
|
||||
dmPolicy: XmppDmPolicy;
|
||||
allowFrom: string[];
|
||||
sendReceipts: boolean;
|
||||
requestReceipts: boolean;
|
||||
sendChatStates: boolean;
|
||||
mediaMaxBytes: number;
|
||||
healthProbe: boolean;
|
||||
healthProbeIntervalMs: number;
|
||||
healthProbeTimeoutMs: number;
|
||||
reconnectDelayMs: number;
|
||||
}
|
||||
|
||||
type ConfigWithChannels = OpenClawConfig & {
|
||||
channels?: OpenClawConfig["channels"] & {
|
||||
xmpp?: XmppChannelConfig;
|
||||
};
|
||||
};
|
||||
|
||||
function cleanString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed || undefined;
|
||||
}
|
||||
|
||||
function boundedNumber(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
minimum: number,
|
||||
maximum: number
|
||||
): number {
|
||||
return typeof value === "number" && Number.isFinite(value)
|
||||
? Math.max(minimum, Math.min(maximum, value))
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function channelConfig(cfg: OpenClawConfig): XmppChannelConfig {
|
||||
return (cfg as ConfigWithChannels).channels?.xmpp ?? {};
|
||||
}
|
||||
|
||||
function normalizeAccountId(value: string | null | undefined): string {
|
||||
const normalized = cleanString(value)?.toLowerCase();
|
||||
return normalized || DEFAULT_ACCOUNT_ID;
|
||||
}
|
||||
|
||||
function envAccountPrefix(accountId: string): string {
|
||||
if (accountId === DEFAULT_ACCOUNT_ID) {
|
||||
return "XMPP";
|
||||
}
|
||||
return `XMPP_${accountId.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}`;
|
||||
}
|
||||
|
||||
function envValue(accountId: string, key: string): string | undefined {
|
||||
return cleanString(process.env[`${envAccountPrefix(accountId)}_${key}`]);
|
||||
}
|
||||
|
||||
function accountEntry(cfg: OpenClawConfig, accountId: string): XmppAccountConfig {
|
||||
const section = channelConfig(cfg);
|
||||
if (section.accounts?.[accountId]) {
|
||||
return {
|
||||
...section,
|
||||
accounts: undefined,
|
||||
defaultAccount: undefined,
|
||||
...section.accounts[accountId]
|
||||
} as XmppAccountConfig;
|
||||
}
|
||||
return section;
|
||||
}
|
||||
|
||||
export function listXmppAccountIds(cfg: OpenClawConfig): string[] {
|
||||
const section = channelConfig(cfg);
|
||||
const ids = Object.keys(section.accounts ?? {}).map(normalizeAccountId);
|
||||
if (ids.length > 0) {
|
||||
return [...new Set(ids)].sort();
|
||||
}
|
||||
if (
|
||||
cleanString(section.jid) ||
|
||||
cleanString(process.env.XMPP_JID) ||
|
||||
hasConfiguredSecretInput(section.password)
|
||||
) {
|
||||
return [DEFAULT_ACCOUNT_ID];
|
||||
}
|
||||
return [DEFAULT_ACCOUNT_ID];
|
||||
}
|
||||
|
||||
export function resolveDefaultXmppAccountId(cfg: OpenClawConfig): string {
|
||||
const section = channelConfig(cfg);
|
||||
const configuredDefault = normalizeAccountId(section.defaultAccount);
|
||||
const ids = listXmppAccountIds(cfg);
|
||||
if (section.defaultAccount && ids.includes(configuredDefault)) {
|
||||
return configuredDefault;
|
||||
}
|
||||
return ids[0] ?? DEFAULT_ACCOUNT_ID;
|
||||
}
|
||||
|
||||
export function resolveXmppAccount(
|
||||
cfg: OpenClawConfig,
|
||||
requestedAccountId?: string | null
|
||||
): ResolvedXmppAccount {
|
||||
const accountId = requestedAccountId
|
||||
? normalizeAccountId(requestedAccountId)
|
||||
: resolveDefaultXmppAccountId(cfg);
|
||||
const raw = accountEntry(cfg, accountId);
|
||||
const jidValue = normalizeBareJid(raw.jid ?? envValue(accountId, "JID") ?? "");
|
||||
const password = raw.password ?? envValue(accountId, "PASSWORD");
|
||||
const websocketUrl =
|
||||
cleanString(raw.websocketUrl) ?? envValue(accountId, "WEBSOCKET_URL");
|
||||
const service = cleanString(raw.service) ?? envValue(accountId, "SERVICE");
|
||||
const allowFrom = (raw.allowFrom ?? [])
|
||||
.map((entry) => normalizeBareJid(entry))
|
||||
.filter((entry): entry is string => Boolean(entry));
|
||||
const name = cleanString(raw.name);
|
||||
|
||||
return {
|
||||
accountId,
|
||||
...(name ? { name } : {}),
|
||||
enabled: raw.enabled !== false,
|
||||
configured: Boolean(jidValue && hasConfiguredSecretInput(password)),
|
||||
...(jidValue ? { jid: jidValue } : {}),
|
||||
...(password !== undefined ? { password } : {}),
|
||||
resource: cleanString(raw.resource) ?? DEFAULT_RESOURCE,
|
||||
...(service ? { service } : {}),
|
||||
...(websocketUrl ? { websocketUrl } : {}),
|
||||
dmPolicy: raw.dmPolicy ?? "pairing",
|
||||
allowFrom,
|
||||
sendReceipts: raw.sendReceipts !== false,
|
||||
requestReceipts: raw.requestReceipts !== false,
|
||||
sendChatStates: raw.sendChatStates !== false,
|
||||
mediaMaxMb:
|
||||
typeof raw.mediaMaxMb === "number" && Number.isFinite(raw.mediaMaxMb)
|
||||
? Math.max(1, Math.min(100, raw.mediaMaxMb))
|
||||
: DEFAULT_MEDIA_MAX_MB,
|
||||
healthProbe: raw.healthProbe !== false,
|
||||
healthProbeIntervalSeconds: boundedNumber(
|
||||
raw.healthProbeIntervalSeconds,
|
||||
300,
|
||||
30,
|
||||
3600
|
||||
),
|
||||
healthProbeTimeoutSeconds: boundedNumber(
|
||||
raw.healthProbeTimeoutSeconds,
|
||||
15,
|
||||
5,
|
||||
60
|
||||
),
|
||||
reconnectDelaySeconds: boundedNumber(
|
||||
raw.reconnectDelaySeconds,
|
||||
1,
|
||||
1,
|
||||
60
|
||||
),
|
||||
...(raw.dm ? { dm: raw.dm } : {}),
|
||||
...(raw.threadBindings ? { threadBindings: raw.threadBindings } : {})
|
||||
};
|
||||
}
|
||||
|
||||
function validateService(account: ResolvedXmppAccount): string {
|
||||
if (!account.jid) {
|
||||
throw new Error("XMPP JID is not configured.");
|
||||
}
|
||||
if (account.websocketUrl) {
|
||||
const url = new URL(account.websocketUrl);
|
||||
if (url.protocol !== "wss:") {
|
||||
throw new Error("XMPP WebSocket URLs must use wss:.");
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
if (account.service) {
|
||||
if (!account.service.includes("://")) {
|
||||
return account.service;
|
||||
}
|
||||
const url = new URL(account.service);
|
||||
if (!["xmpp:", "xmpps:", "wss:"].includes(url.protocol)) {
|
||||
throw new Error("XMPP service must use xmpp:, xmpps:, or wss:.");
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
return jidDomain(account.jid);
|
||||
}
|
||||
|
||||
export async function resolveXmppConnectionConfig(
|
||||
cfg: OpenClawConfig,
|
||||
requestedAccountId?: string | null,
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): Promise<XmppConnectionConfig> {
|
||||
const account = resolveXmppAccount(cfg, requestedAccountId);
|
||||
if (!account.enabled) {
|
||||
throw new Error(`XMPP account "${account.accountId}" is disabled.`);
|
||||
}
|
||||
if (!account.jid || !account.password) {
|
||||
throw new Error(`XMPP account "${account.accountId}" is not configured.`);
|
||||
}
|
||||
if (account.allowFrom.includes("*") && account.dmPolicy !== "open") {
|
||||
throw new Error(
|
||||
`XMPP account "${account.accountId}" uses allowFrom "*" but dmPolicy is not "open".`
|
||||
);
|
||||
}
|
||||
const passwordPath =
|
||||
account.accountId === DEFAULT_ACCOUNT_ID
|
||||
? "channels.xmpp.password"
|
||||
: `channels.xmpp.accounts.${account.accountId}.password`;
|
||||
const resolved = await resolveConfiguredSecretInputString({
|
||||
config: cfg,
|
||||
env,
|
||||
value: account.password,
|
||||
path: passwordPath,
|
||||
unresolvedReasonStyle: "detailed"
|
||||
});
|
||||
const password = cleanString(resolved.value);
|
||||
if (!password) {
|
||||
throw new Error(
|
||||
resolved.unresolvedRefReason ??
|
||||
`XMPP password for account "${account.accountId}" could not be resolved.`
|
||||
);
|
||||
}
|
||||
return {
|
||||
accountId: account.accountId,
|
||||
jid: account.jid,
|
||||
domain: jidDomain(account.jid),
|
||||
username: jidLocalpart(account.jid),
|
||||
password,
|
||||
resource: account.resource,
|
||||
service: validateService(account),
|
||||
dmPolicy: account.dmPolicy,
|
||||
allowFrom: account.allowFrom,
|
||||
sendReceipts: account.sendReceipts,
|
||||
requestReceipts: account.requestReceipts,
|
||||
sendChatStates: account.sendChatStates,
|
||||
mediaMaxBytes: Math.floor(account.mediaMaxMb * 1024 * 1024),
|
||||
healthProbe: account.healthProbe,
|
||||
healthProbeIntervalMs: Math.floor(account.healthProbeIntervalSeconds * 1000),
|
||||
healthProbeTimeoutMs: Math.floor(account.healthProbeTimeoutSeconds * 1000),
|
||||
reconnectDelayMs: Math.floor(account.reconnectDelaySeconds * 1000)
|
||||
};
|
||||
}
|
||||
|
||||
export function setXmppAccountEnabled(
|
||||
cfg: OpenClawConfig,
|
||||
accountId: string,
|
||||
enabled: boolean
|
||||
): OpenClawConfig {
|
||||
const next = structuredClone(cfg) as ConfigWithChannels;
|
||||
next.channels ??= {};
|
||||
const section = (next.channels.xmpp ??= {});
|
||||
if (accountId === DEFAULT_ACCOUNT_ID && !section.accounts) {
|
||||
section.enabled = enabled;
|
||||
return next;
|
||||
}
|
||||
section.accounts ??= {};
|
||||
section.accounts[accountId] = {
|
||||
...section.accounts[accountId],
|
||||
enabled
|
||||
};
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export const CHANNEL_ID = "xmpp" as const;
|
||||
export const DEFAULT_ACCOUNT_ID = "default";
|
||||
export const DEFAULT_RESOURCE = "openclaw";
|
||||
export const DEFAULT_MEDIA_MAX_MB = 25;
|
||||
export const DEFAULT_TEXT_CHUNK_LIMIT = 4_000;
|
||||
export const DEFAULT_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
export const DEFAULT_DEDUPE_MAX_ENTRIES = 10_000;
|
||||
|
||||
export const NS = {
|
||||
chatStates: "http://jabber.org/protocol/chatstates",
|
||||
delay: "urn:xmpp:delay",
|
||||
discoInfo: "http://jabber.org/protocol/disco#info",
|
||||
discoItems: "http://jabber.org/protocol/disco#items",
|
||||
fallback: "urn:xmpp:fallback:0",
|
||||
fileMetadata: "urn:xmpp:file:metadata:0",
|
||||
hashes: "urn:xmpp:hashes:2",
|
||||
httpUpload: "urn:xmpp:http:upload:0",
|
||||
oob: "jabber:x:oob",
|
||||
receipts: "urn:xmpp:receipts",
|
||||
sfs: "urn:xmpp:sfs:0",
|
||||
sid: "urn:xmpp:sid:0",
|
||||
urlData: "http://jabber.org/protocol/url-data"
|
||||
} as const;
|
||||
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
DEFAULT_DEDUPE_MAX_ENTRIES,
|
||||
DEFAULT_DEDUPE_TTL_MS
|
||||
} from "./constants.js";
|
||||
|
||||
export class ExpiringDedupe {
|
||||
readonly #entries = new Map<string, number>();
|
||||
|
||||
constructor(
|
||||
private readonly ttlMs = DEFAULT_DEDUPE_TTL_MS,
|
||||
private readonly maxEntries = DEFAULT_DEDUPE_MAX_ENTRIES,
|
||||
private readonly now: () => number = Date.now
|
||||
) {}
|
||||
|
||||
seen(key: string): boolean {
|
||||
const current = this.now();
|
||||
this.prune(current);
|
||||
const expiresAt = this.#entries.get(key);
|
||||
if (expiresAt !== undefined && expiresAt > current) {
|
||||
return true;
|
||||
}
|
||||
this.#entries.delete(key);
|
||||
this.#entries.set(key, current + this.ttlMs);
|
||||
this.#enforceLimit();
|
||||
return false;
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.#entries.size;
|
||||
}
|
||||
|
||||
prune(current = this.now()): void {
|
||||
for (const [key, expiresAt] of this.#entries) {
|
||||
if (expiresAt > current) {
|
||||
continue;
|
||||
}
|
||||
this.#entries.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
#enforceLimit(): void {
|
||||
while (this.#entries.size > this.maxEntries) {
|
||||
const oldest = this.#entries.keys().next().value as string | undefined;
|
||||
if (oldest === undefined) {
|
||||
break;
|
||||
}
|
||||
this.#entries.delete(oldest);
|
||||
}
|
||||
}
|
||||
}
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
import { readLocalFileFromRoots } from "@openclaw/fs-safe/advanced";
|
||||
import type { PluginRuntime } from "openclaw/plugin-sdk/channel-core";
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
import {
|
||||
dispatchInboundDirectDmWithRuntime
|
||||
} from "openclaw/plugin-sdk/channel-inbound";
|
||||
import {
|
||||
chunkTextWithMode,
|
||||
resolveChunkMode,
|
||||
resolveTextChunkLimit
|
||||
} from "openclaw/plugin-sdk/reply-chunking";
|
||||
import {
|
||||
createChannelIngressResolver,
|
||||
defineStableChannelIngressIdentity
|
||||
} from "openclaw/plugin-sdk/channel-ingress-runtime";
|
||||
import {
|
||||
getAgentScopedMediaLocalRootsForSources
|
||||
} from "openclaw/plugin-sdk/media-local-roots";
|
||||
|
||||
import type { XmppConnectionConfig, XmppDmConfig, XmppThreadBindingsConfig } from "./config.js";
|
||||
import { CHANNEL_ID, DEFAULT_TEXT_CHUNK_LIMIT } from "./constants.js";
|
||||
import { normalizeBareJid } from "./jid.js";
|
||||
import type { InboundXmppMessage } from "./stanzas.js";
|
||||
import type { XmppTransport } from "./transport.js";
|
||||
|
||||
export type XmppInboundRuntime = PluginRuntime;
|
||||
|
||||
let xmppPluginRuntime: PluginRuntime | undefined;
|
||||
|
||||
export function setXmppPluginRuntime(runtime: PluginRuntime): void {
|
||||
xmppPluginRuntime = runtime;
|
||||
}
|
||||
|
||||
export function getXmppPluginRuntime(): PluginRuntime {
|
||||
if (!xmppPluginRuntime) {
|
||||
throw new Error("OpenClaw plugin runtime is unavailable for XMPP.");
|
||||
}
|
||||
return xmppPluginRuntime;
|
||||
}
|
||||
|
||||
export function chunkXmppReplyText(params: {
|
||||
cfg: OpenClawConfig;
|
||||
accountId: string;
|
||||
text: string;
|
||||
}): string[] {
|
||||
const limit = resolveTextChunkLimit(
|
||||
params.cfg,
|
||||
CHANNEL_ID,
|
||||
params.accountId,
|
||||
{ fallbackLimit: DEFAULT_TEXT_CHUNK_LIMIT }
|
||||
);
|
||||
const mode = resolveChunkMode(params.cfg, CHANNEL_ID, params.accountId);
|
||||
return chunkTextWithMode(params.text, limit, mode);
|
||||
}
|
||||
|
||||
const MARKDOWN_MEDIA_LINE_WRAPPERS = [
|
||||
["**", "**"],
|
||||
["__", "__"],
|
||||
["~~", "~~"],
|
||||
["`", "`"],
|
||||
["*", "*"],
|
||||
["_", "_"]
|
||||
] as const;
|
||||
|
||||
function markdownFenceMarker(line: string):
|
||||
| { marker: "`" | "~"; length: number }
|
||||
| undefined {
|
||||
const stripped = line.trimStart();
|
||||
if (!stripped.startsWith("`") && !stripped.startsWith("~")) {
|
||||
return undefined;
|
||||
}
|
||||
const marker = stripped[0] as "`" | "~";
|
||||
let length = 0;
|
||||
while (stripped[length] === marker) {
|
||||
length += 1;
|
||||
}
|
||||
return length >= 3 ? { marker, length } : undefined;
|
||||
}
|
||||
|
||||
function unwrapMatchingQuote(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
const first = trimmed[0];
|
||||
if (
|
||||
trimmed.length >= 2 &&
|
||||
first === trimmed.at(-1) &&
|
||||
(first === "`" || first === "\"" || first === "'")
|
||||
) {
|
||||
return trimmed.slice(1, -1).trim();
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function unwrapMarkdownMediaDirectiveLine(line: string): string | undefined {
|
||||
let candidate = line.trim();
|
||||
let unwrapped = false;
|
||||
for (let depth = 0; depth < 4; depth += 1) {
|
||||
for (const [opener, closer] of MARKDOWN_MEDIA_LINE_WRAPPERS) {
|
||||
if (
|
||||
candidate.startsWith(opener) &&
|
||||
candidate.endsWith(closer) &&
|
||||
candidate.length > opener.length + closer.length
|
||||
) {
|
||||
candidate = candidate.slice(opener.length, -closer.length).trim();
|
||||
unwrapped = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (unwrapped && candidate.toUpperCase().startsWith("MEDIA:")) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isRecoverableMediaSource(source: string): boolean {
|
||||
if (source.startsWith("/") || source.startsWith("file://")) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(source);
|
||||
return parsed.protocol === "https:" && !parsed.username && !parsed.password;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function recoverMarkdownWrappedMediaDirectives(text: string): {
|
||||
text: string;
|
||||
mediaSources: string[];
|
||||
} {
|
||||
const keptLines: string[] = [];
|
||||
const mediaSources: string[] = [];
|
||||
let fence: { marker: "`" | "~"; length: number } | undefined;
|
||||
|
||||
for (const line of text.split("\n")) {
|
||||
const marker = markdownFenceMarker(line);
|
||||
if (marker) {
|
||||
if (!fence) {
|
||||
fence = marker;
|
||||
} else if (marker.marker === fence.marker && marker.length >= fence.length) {
|
||||
fence = undefined;
|
||||
}
|
||||
keptLines.push(line);
|
||||
continue;
|
||||
}
|
||||
if (fence) {
|
||||
keptLines.push(line);
|
||||
continue;
|
||||
}
|
||||
const directive = unwrapMarkdownMediaDirectiveLine(line);
|
||||
const source = directive
|
||||
? unwrapMatchingQuote(directive.slice("MEDIA:".length))
|
||||
: "";
|
||||
if (!source || !isRecoverableMediaSource(source)) {
|
||||
keptLines.push(line);
|
||||
continue;
|
||||
}
|
||||
mediaSources.push(source);
|
||||
}
|
||||
|
||||
return {
|
||||
text: keptLines.join("\n").trim(),
|
||||
mediaSources
|
||||
};
|
||||
}
|
||||
|
||||
const xmppIngressIdentity = defineStableChannelIngressIdentity({
|
||||
kind: "plugin:xmpp-jid",
|
||||
normalize: (value) => normalizeBareJid(value),
|
||||
isWildcardEntry: (value) => value.trim() === "*",
|
||||
entryIdPrefix: "xmpp-jid"
|
||||
});
|
||||
|
||||
const pairingReplyAt = new Map<string, number>();
|
||||
const PAIRING_REPLY_COOLDOWN_MS = 5 * 60 * 1000;
|
||||
|
||||
function shouldSendPairingReply(key: string, now = Date.now()): boolean {
|
||||
const previous = pairingReplyAt.get(key) ?? 0;
|
||||
if (now - previous < PAIRING_REPLY_COOLDOWN_MS) {
|
||||
return false;
|
||||
}
|
||||
pairingReplyAt.set(key, now);
|
||||
return true;
|
||||
}
|
||||
|
||||
function commandAuthorized(
|
||||
sender: string,
|
||||
effectiveAllowFrom: readonly string[]
|
||||
): boolean {
|
||||
const normalized = normalizeBareJid(sender);
|
||||
if (!normalized) {
|
||||
return false;
|
||||
}
|
||||
return effectiveAllowFrom
|
||||
.filter((entry) => entry !== "*")
|
||||
.some((entry) => normalizeBareJid(entry) === normalized);
|
||||
}
|
||||
|
||||
function mediaReader(params: {
|
||||
cfg: OpenClawConfig;
|
||||
agentId: string;
|
||||
mediaSources: readonly string[];
|
||||
}): (path: string) => Promise<Buffer> {
|
||||
const roots = getAgentScopedMediaLocalRootsForSources({
|
||||
cfg: params.cfg,
|
||||
agentId: params.agentId,
|
||||
mediaSources: params.mediaSources
|
||||
});
|
||||
return async (path) => {
|
||||
const result = await readLocalFileFromRoots({
|
||||
filePath: path,
|
||||
roots,
|
||||
label: "XMPP outbound media",
|
||||
symlinks: "follow-within-root",
|
||||
hardlinks: "allow",
|
||||
maxBytes: 100 * 1024 * 1024
|
||||
});
|
||||
if (!result) {
|
||||
throw new Error("XMPP outbound media is outside approved local roots.");
|
||||
}
|
||||
return result.buffer;
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleInboundXmppMessage(params: {
|
||||
cfg: OpenClawConfig;
|
||||
account: XmppConnectionConfig;
|
||||
transport: XmppTransport;
|
||||
runtime: XmppInboundRuntime;
|
||||
message: InboundXmppMessage;
|
||||
log: {
|
||||
info(message: string): void;
|
||||
warn(message: string): void;
|
||||
error(message: string): void;
|
||||
debug?(message: string): void;
|
||||
};
|
||||
}): Promise<void> {
|
||||
const { account, message, transport, runtime } = params;
|
||||
const access = await createChannelIngressResolver({
|
||||
channelId: "xmpp",
|
||||
accountId: account.accountId,
|
||||
identity: xmppIngressIdentity,
|
||||
useDefaultPairingStore: true,
|
||||
defaultDmPolicy: "pairing"
|
||||
}).message({
|
||||
subject: { stableId: message.fromBare },
|
||||
conversation: { kind: "direct", id: message.fromBare },
|
||||
event: { kind: "message", authMode: "inbound", mayPair: true },
|
||||
dmPolicy: account.dmPolicy,
|
||||
groupPolicy: "disabled",
|
||||
allowFrom: account.allowFrom,
|
||||
command: false
|
||||
});
|
||||
|
||||
if (access.ingress.decision !== "allow") {
|
||||
if (access.ingress.admission === "pairing-required") {
|
||||
const pairingKey = `${account.accountId}\u0000${message.fromBare}`;
|
||||
const pairing = await runtime.channel.pairing.upsertPairingRequest({
|
||||
channel: "xmpp",
|
||||
id: message.fromBare,
|
||||
accountId: account.accountId,
|
||||
meta: { jid: message.fromBare }
|
||||
});
|
||||
if (shouldSendPairingReply(pairingKey)) {
|
||||
const text = runtime.channel.pairing.buildPairingReply({
|
||||
channel: "xmpp",
|
||||
idLine: `Your XMPP JID: ${message.fromBare}`,
|
||||
code: pairing.code
|
||||
});
|
||||
await transport.sendText(
|
||||
message.from,
|
||||
pairing.created
|
||||
? text
|
||||
: `${text}\n\nPairing request is still pending approval.`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
params.log.warn(
|
||||
`[${account.accountId}] blocked XMPP DM from ${message.fromBare} (${access.ingress.reasonCode})`
|
||||
);
|
||||
}
|
||||
if (message.receiptRequested && message.receiptId) {
|
||||
await transport.sendReceipt(message.from, message.receiptId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const peer = { kind: "direct" as const, id: message.fromBare };
|
||||
const route = runtime.channel.routing.resolveAgentRoute({
|
||||
cfg: params.cfg,
|
||||
channel: "xmpp",
|
||||
accountId: account.accountId,
|
||||
peer
|
||||
});
|
||||
await transport.sendChatState(message.from, "composing").catch(() => undefined);
|
||||
try {
|
||||
await dispatchInboundDirectDmWithRuntime({
|
||||
cfg: params.cfg,
|
||||
runtime,
|
||||
channel: "xmpp",
|
||||
channelLabel: "XMPP",
|
||||
accountId: account.accountId,
|
||||
peer,
|
||||
senderId: message.fromBare,
|
||||
senderAddress: `xmpp:${message.fromBare}`,
|
||||
recipientAddress: `xmpp:${account.jid}`,
|
||||
conversationLabel: message.fromBare,
|
||||
rawBody: message.body,
|
||||
bodyForAgent: message.body,
|
||||
commandBody: message.body,
|
||||
messageId: message.id,
|
||||
...(message.timestamp ? { timestamp: message.timestamp } : {}),
|
||||
commandAuthorized: commandAuthorized(
|
||||
message.fromBare,
|
||||
access.senderAccess.effectiveAllowFrom
|
||||
),
|
||||
provider: "xmpp",
|
||||
surface: "xmpp",
|
||||
originatingChannel: "xmpp",
|
||||
originatingTo: message.fromBare,
|
||||
extraContext: {
|
||||
NativeDirectUserId: message.fromBare,
|
||||
XMPPFullJid: message.from
|
||||
},
|
||||
deliver: async (payload) => {
|
||||
const recovered = recoverMarkdownWrappedMediaDirectives(
|
||||
payload.text ?? ""
|
||||
);
|
||||
const mediaUrls = [...new Set([
|
||||
...(payload.mediaUrls ?? []),
|
||||
...(payload.mediaUrl ? [payload.mediaUrl] : []),
|
||||
...recovered.mediaSources
|
||||
].filter(Boolean))];
|
||||
const text = recovered.text;
|
||||
if (mediaUrls.length === 0) {
|
||||
const chunks = chunkXmppReplyText({
|
||||
cfg: params.cfg,
|
||||
accountId: account.accountId,
|
||||
text
|
||||
});
|
||||
if (chunks.length > 1) {
|
||||
params.log.info(
|
||||
`[${account.accountId}] split ${text.length}-character XMPP reply into ${chunks.length} messages`
|
||||
);
|
||||
}
|
||||
for (const chunk of chunks) {
|
||||
await transport.sendText(message.from, chunk);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const readFile = mediaReader({
|
||||
cfg: params.cfg,
|
||||
agentId: route.agentId,
|
||||
mediaSources: mediaUrls
|
||||
});
|
||||
for (const [index, mediaUrl] of mediaUrls.entries()) {
|
||||
await transport.sendMedia({
|
||||
to: message.from,
|
||||
text: index === 0 ? text : "",
|
||||
mediaUrl,
|
||||
mediaReadFile: readFile
|
||||
});
|
||||
}
|
||||
},
|
||||
onRecordError: (error) => {
|
||||
params.log.warn(
|
||||
`[${account.accountId}] failed to record XMPP inbound session: ${String(
|
||||
error
|
||||
)}`
|
||||
);
|
||||
},
|
||||
onDispatchError: (error, info) => {
|
||||
params.log.error(
|
||||
`[${account.accountId}] XMPP ${info.kind} reply failed: ${String(error)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
if (message.receiptRequested && message.receiptId) {
|
||||
await transport.sendReceipt(message.from, message.receiptId);
|
||||
}
|
||||
} finally {
|
||||
await transport.sendChatState(message.from, "active").catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function resetInboundStateForTests(): void {
|
||||
pairingReplyAt.clear();
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import { jid } from "@xmpp/client";
|
||||
|
||||
const TARGET_PREFIX = /^(?:xmpp:)/i;
|
||||
|
||||
export function normalizeBareJid(value: string): string | undefined {
|
||||
const raw = value.trim().replace(TARGET_PREFIX, "");
|
||||
if (!raw || raw === "*") {
|
||||
return raw || undefined;
|
||||
}
|
||||
try {
|
||||
const parsed = jid(raw);
|
||||
if (!parsed.local || !parsed.domain) {
|
||||
return undefined;
|
||||
}
|
||||
return `${parsed.getLocal(true)}@${parsed.domain.toLowerCase()}`;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeFullJid(value: string): string | undefined {
|
||||
const raw = value.trim().replace(TARGET_PREFIX, "");
|
||||
if (!raw) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const parsed = jid(raw);
|
||||
if (!parsed.local || !parsed.domain) {
|
||||
return undefined;
|
||||
}
|
||||
const bare = `${parsed.getLocal(true)}@${parsed.domain.toLowerCase()}`;
|
||||
return parsed.resource ? `${bare}/${parsed.resource}` : bare;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function jidDomain(value: string): string {
|
||||
const normalized = normalizeBareJid(value);
|
||||
if (!normalized || normalized === "*") {
|
||||
throw new Error("A valid XMPP JID is required.");
|
||||
}
|
||||
return normalized.slice(normalized.indexOf("@") + 1);
|
||||
}
|
||||
|
||||
export function jidLocalpart(value: string): string {
|
||||
const normalized = normalizeBareJid(value);
|
||||
if (!normalized || normalized === "*") {
|
||||
throw new Error("A valid XMPP JID is required.");
|
||||
}
|
||||
return normalized.slice(0, normalized.indexOf("@"));
|
||||
}
|
||||
|
||||
export function normalizeXmppTarget(raw: string): string | undefined {
|
||||
const normalized = normalizeBareJid(raw);
|
||||
return normalized && normalized !== "*" ? normalized : undefined;
|
||||
}
|
||||
|
||||
export function matchesAllowFrom(sender: string, entries: readonly string[]): boolean {
|
||||
const normalizedSender = normalizeBareJid(sender);
|
||||
if (!normalizedSender) {
|
||||
return false;
|
||||
}
|
||||
return entries.some((entry) => {
|
||||
const normalizedEntry = normalizeBareJid(String(entry));
|
||||
return normalizedEntry === "*" || normalizedEntry === normalizedSender;
|
||||
});
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
import { basename } from "node:path";
|
||||
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Client } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
|
||||
|
||||
import { NS } from "./constants.js";
|
||||
|
||||
export interface UploadSlot {
|
||||
putUrl: string;
|
||||
getUrl: string;
|
||||
headers: Array<[name: string, value: string]>;
|
||||
}
|
||||
|
||||
// XEP-0363 permits only these slot-provided headers on the HTTP PUT.
|
||||
const ALLOWED_UPLOAD_HEADERS = new Map([
|
||||
["authorization", "Authorization"],
|
||||
["cookie", "Cookie"],
|
||||
["expires", "Expires"]
|
||||
]);
|
||||
|
||||
function elementChildren(element: Element, name: string, xmlns?: string): Element[] {
|
||||
return element.getChildren(name, xmlns);
|
||||
}
|
||||
|
||||
export async function discoverUploadService(
|
||||
xmpp: Client,
|
||||
domain: string
|
||||
): Promise<string> {
|
||||
const items = await xmpp.iqCaller.get(
|
||||
xml("query", { xmlns: NS.discoItems }),
|
||||
domain,
|
||||
15_000
|
||||
);
|
||||
const candidates = items
|
||||
? elementChildren(items, "item")
|
||||
.map((item) => String(item.attrs.jid ?? ""))
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
for (const candidate of candidates) {
|
||||
const info = await xmpp.iqCaller
|
||||
.get(xml("query", { xmlns: NS.discoInfo }), candidate, 15_000)
|
||||
.catch(() => undefined);
|
||||
const supportsUpload = info
|
||||
?.getChildren("feature")
|
||||
.some((feature: Element) => feature.attrs.var === NS.httpUpload);
|
||||
if (supportsUpload) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
throw new Error("The XMPP server did not advertise an XEP-0363 upload service.");
|
||||
}
|
||||
|
||||
export async function requestUploadSlot(params: {
|
||||
xmpp: Client;
|
||||
serviceJid: string;
|
||||
filename: string;
|
||||
size: number;
|
||||
contentType: string;
|
||||
}): Promise<UploadSlot> {
|
||||
// XEP-0363 replies to <request/> with a differently named <slot/> child.
|
||||
// iqCaller.get() can only return a response child with the same name as the
|
||||
// request, so use the full IQ request API and select <slot/> explicitly.
|
||||
const response = await params.xmpp.iqCaller.request(
|
||||
xml(
|
||||
"iq",
|
||||
{ type: "get", to: params.serviceJid },
|
||||
xml("request", {
|
||||
xmlns: NS.httpUpload,
|
||||
filename: params.filename,
|
||||
size: String(params.size),
|
||||
"content-type": params.contentType
|
||||
})
|
||||
),
|
||||
20_000
|
||||
);
|
||||
const slot =
|
||||
response?.getChild("slot", NS.httpUpload) ?? response?.getChild("slot");
|
||||
const put = slot?.getChild("put", NS.httpUpload) ?? slot?.getChild("put");
|
||||
const get = slot?.getChild("get", NS.httpUpload) ?? slot?.getChild("get");
|
||||
const putUrl = String(put?.attrs.url ?? "");
|
||||
const getUrl = String(get?.attrs.url ?? "");
|
||||
if (!putUrl || !getUrl) {
|
||||
throw new Error("The XMPP upload service returned an invalid slot.");
|
||||
}
|
||||
const headers: UploadSlot["headers"] = [];
|
||||
for (const header of put?.getChildren("header") ?? []) {
|
||||
const rawName = String(header.attrs.name ?? "");
|
||||
const name = rawName.replace(/[\r\n]/g, "").trim().toLowerCase();
|
||||
const allowedName = ALLOWED_UPLOAD_HEADERS.get(name);
|
||||
if (!allowedName) {
|
||||
continue;
|
||||
}
|
||||
const value = header.text().replace(/[\r\n]/g, "");
|
||||
headers.push([allowedName, value]);
|
||||
}
|
||||
return { putUrl, getUrl, headers };
|
||||
}
|
||||
|
||||
export async function uploadBuffer(params: {
|
||||
slot: UploadSlot;
|
||||
buffer: Buffer;
|
||||
contentType: string;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<string> {
|
||||
const headers = new Headers();
|
||||
for (const [name, value] of params.slot.headers) {
|
||||
headers.append(name, value);
|
||||
}
|
||||
headers.set("content-type", params.contentType);
|
||||
headers.set("content-length", String(params.buffer.byteLength));
|
||||
|
||||
const guarded = await fetchWithSsrFGuard({
|
||||
url: params.slot.putUrl,
|
||||
requireHttps: true,
|
||||
maxRedirects: 0,
|
||||
timeoutMs: 60_000,
|
||||
capture: false,
|
||||
...(params.signal ? { signal: params.signal } : {}),
|
||||
init: {
|
||||
method: "PUT",
|
||||
headers,
|
||||
body: new Uint8Array(params.buffer)
|
||||
},
|
||||
auditContext: "xmpp-xep0363-upload"
|
||||
});
|
||||
try {
|
||||
if (!guarded.response.ok) {
|
||||
throw new Error(
|
||||
`XMPP upload failed with HTTP ${guarded.response.status}.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await guarded.release();
|
||||
}
|
||||
const downloadUrl = new URL(params.slot.getUrl);
|
||||
if (downloadUrl.protocol !== "https:") {
|
||||
throw new Error("The XMPP upload service returned a non-HTTPS download URL.");
|
||||
}
|
||||
return downloadUrl.toString();
|
||||
}
|
||||
|
||||
export function safeUploadFilename(filePath: string): string {
|
||||
const value = basename(filePath).replace(/[^A-Za-z0-9._-]+/g, "_");
|
||||
return value || "attachment";
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
import type {
|
||||
ChannelSetupWizardAdapter,
|
||||
WizardPrompter
|
||||
} from "openclaw/plugin-sdk/setup";
|
||||
|
||||
import {
|
||||
listXmppAccountIds,
|
||||
resolveXmppAccount,
|
||||
resolveXmppConnectionConfig,
|
||||
type XmppAccountConfig,
|
||||
type XmppDmPolicy
|
||||
} from "./config.js";
|
||||
import { normalizeBareJid } from "./jid.js";
|
||||
import { XmppTransport } from "./transport.js";
|
||||
|
||||
type XmppConfig = OpenClawConfig & {
|
||||
channels?: OpenClawConfig["channels"] & {
|
||||
xmpp?: XmppAccountConfig & {
|
||||
defaultAccount?: string;
|
||||
accounts?: Record<string, XmppAccountConfig>;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
function normalizeAccountId(value: string): string | undefined {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
return /^[a-z0-9][a-z0-9_-]{0,63}$/.test(normalized)
|
||||
? normalized
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function applyXmppSetupAccount(params: {
|
||||
cfg: OpenClawConfig;
|
||||
accountId: string;
|
||||
account: XmppAccountConfig;
|
||||
}): OpenClawConfig {
|
||||
const next = structuredClone(params.cfg) as XmppConfig;
|
||||
next.channels ??= {};
|
||||
const channel = (next.channels.xmpp ??= {});
|
||||
channel.accounts ??= {};
|
||||
channel.accounts[params.accountId] = params.account;
|
||||
channel.defaultAccount ??= params.accountId;
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function validateXmppSetupConnection(
|
||||
cfg: OpenClawConfig,
|
||||
accountId: string
|
||||
): Promise<void> {
|
||||
const connection = await resolveXmppConnectionConfig(cfg, accountId);
|
||||
const controller = new AbortController();
|
||||
let resolveOnline!: () => void;
|
||||
let rejectOnline!: (error: Error) => void;
|
||||
const online = new Promise<void>((resolve, reject) => {
|
||||
resolveOnline = resolve;
|
||||
rejectOnline = reject;
|
||||
});
|
||||
const transport = new XmppTransport(connection, {
|
||||
onMessage: async () => undefined,
|
||||
onStatus: (status) => {
|
||||
if (status.connected) resolveOnline();
|
||||
if (status.phase === "failed" && status.lastError) {
|
||||
rejectOnline(new Error(status.lastError));
|
||||
}
|
||||
},
|
||||
log: { info: () => undefined, warn: () => undefined, error: () => undefined }
|
||||
});
|
||||
const running = transport.run(controller.signal);
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
online,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => reject(new Error("XMPP connection validation timed out.")), 20_000);
|
||||
timeout.unref?.();
|
||||
})
|
||||
]);
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
controller.abort();
|
||||
await running.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function promptAccountId(
|
||||
prompter: WizardPrompter,
|
||||
cfg: OpenClawConfig,
|
||||
shouldPrompt: boolean
|
||||
): Promise<string> {
|
||||
if (!shouldPrompt) return "default";
|
||||
const existing = listXmppAccountIds(cfg).filter(
|
||||
(id) => resolveXmppAccount(cfg, id).configured
|
||||
);
|
||||
return await prompter.text({
|
||||
message: existing.length
|
||||
? `Account id (existing: ${existing.join(", ")})`
|
||||
: "Account id",
|
||||
initialValue: existing[0] ?? "default",
|
||||
validate: (value) => normalizeAccountId(value) ? undefined : "Use letters, numbers, _ or -, beginning with a letter or number."
|
||||
}).then((value) => normalizeAccountId(value) ?? "default");
|
||||
}
|
||||
|
||||
export async function configureXmppInteractive(
|
||||
params: {
|
||||
cfg: OpenClawConfig;
|
||||
prompter: WizardPrompter;
|
||||
shouldPromptAccountIds: boolean;
|
||||
},
|
||||
validateConnection: (cfg: OpenClawConfig, accountId: string) => Promise<void> = validateXmppSetupConnection
|
||||
): Promise<{ cfg: OpenClawConfig; accountId: string; completion: "configured" }> {
|
||||
const { prompter } = params;
|
||||
const accountId = await promptAccountId(prompter, params.cfg, params.shouldPromptAccountIds);
|
||||
const current = resolveXmppAccount(params.cfg, accountId);
|
||||
await prompter.note(
|
||||
"XMPP setup requires verified TLS. Passwords are referenced from an environment SecretRef and are never written into configuration. Group-chat options remain unavailable until the MUC security gate is complete.",
|
||||
"Secure XMPP setup"
|
||||
);
|
||||
const jid = await prompter.text({
|
||||
message: "Bot JID",
|
||||
...(current.jid ? { initialValue: current.jid } : {}),
|
||||
placeholder: "bot@example.org",
|
||||
validate: (value) => normalizeBareJid(value) ? undefined : "Enter a valid bare XMPP JID."
|
||||
}).then((value) => normalizeBareJid(value)!);
|
||||
const resource = await prompter.text({
|
||||
message: "Resource",
|
||||
initialValue: current.resource || "openclaw",
|
||||
validate: (value) => value.trim() ? undefined : "Resource is required."
|
||||
});
|
||||
const endpoint = await prompter.text({
|
||||
message: "Secure service endpoint (leave blank for domain/SRV discovery)",
|
||||
initialValue: current.websocketUrl ?? current.service ?? "",
|
||||
placeholder: "wss://xmpp.example.org/xmpp-websocket",
|
||||
validate: (value) => {
|
||||
if (!value.trim()) return undefined;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return ["xmpp:", "xmpps:", "wss:"].includes(url.protocol)
|
||||
? undefined
|
||||
: "Use xmpp:, xmpps:, or wss:. Insecure ws: is refused.";
|
||||
} catch {
|
||||
return "Enter a complete secure endpoint URL or leave blank.";
|
||||
}
|
||||
}
|
||||
});
|
||||
if (endpoint.trim()) {
|
||||
await prompter.note(
|
||||
"The TLS certificate must be valid for the explicit endpoint hostname; changing the host does not disable certificate-name verification.",
|
||||
"Certificate verification"
|
||||
);
|
||||
}
|
||||
const secretEnv = await prompter.text({
|
||||
message: "Environment variable containing the XMPP password",
|
||||
placeholder: accountId === "default" ? "XMPP_PASSWORD" : `XMPP_${accountId.toUpperCase()}_PASSWORD`,
|
||||
validate: (value) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(value.trim())
|
||||
? undefined
|
||||
: "Enter a valid environment variable name."
|
||||
});
|
||||
const dmPolicy = await prompter.select<XmppDmPolicy>({
|
||||
message: "Direct-message access policy",
|
||||
options: [
|
||||
{ value: "pairing", label: "Pairing", hint: "Approve new contacts explicitly" },
|
||||
{ value: "allowlist", label: "Allowlist", hint: "Only listed bare JIDs" },
|
||||
{ value: "disabled", label: "Disabled", hint: "Reject direct messages" }
|
||||
],
|
||||
initialValue: current.dmPolicy === "open" ? "pairing" : current.dmPolicy
|
||||
});
|
||||
let allowFrom: string[] = [];
|
||||
if (dmPolicy === "allowlist") {
|
||||
const raw = await prompter.text({
|
||||
message: "Allowed bare JIDs (comma-separated)",
|
||||
initialValue: current.allowFrom.join(", "),
|
||||
validate: (value) => value.split(",").every((item) => normalizeBareJid(item))
|
||||
? undefined
|
||||
: "Every entry must be a valid bare XMPP JID."
|
||||
});
|
||||
allowFrom = [...new Set(raw.split(",").map((item) => normalizeBareJid(item)).filter((item): item is string => Boolean(item)))];
|
||||
}
|
||||
const healthProbe = await prompter.confirm({
|
||||
message: "Enable conservative XEP-0199 health probes?",
|
||||
initialValue: current.healthProbe
|
||||
});
|
||||
await prompter.note(
|
||||
`Account: ${accountId}\nJID: ${jid}\nEndpoint: ${endpoint.trim() || "domain/SRV discovery"}\nDM policy: ${dmPolicy}${allowFrom.length ? ` (${allowFrom.join(", ")})` : ""}\nHealth probe: ${healthProbe ? "enabled" : "disabled"}`,
|
||||
"Effective XMPP configuration"
|
||||
);
|
||||
const account: XmppAccountConfig = {
|
||||
enabled: true,
|
||||
jid,
|
||||
resource: resource.trim(),
|
||||
password: { source: "env", provider: "default", id: secretEnv.trim() },
|
||||
dmPolicy,
|
||||
allowFrom,
|
||||
healthProbe,
|
||||
...(endpoint.trim().startsWith("wss:")
|
||||
? { websocketUrl: endpoint.trim() }
|
||||
: endpoint.trim()
|
||||
? { service: endpoint.trim() }
|
||||
: {})
|
||||
};
|
||||
const next = applyXmppSetupAccount({ cfg: params.cfg, accountId, account });
|
||||
const progress = prompter.progress("Validating TLS, authentication, and resource binding");
|
||||
try {
|
||||
await validateConnection(next, accountId);
|
||||
progress.stop("XMPP connection validated securely.");
|
||||
} catch (error) {
|
||||
progress.stop("XMPP validation failed; no configuration was saved.");
|
||||
throw new Error(`XMPP setup validation failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
return { cfg: next, accountId, completion: "configured" };
|
||||
}
|
||||
|
||||
export const xmppSetupWizard: ChannelSetupWizardAdapter = {
|
||||
channel: "xmpp",
|
||||
getStatus: async ({ cfg }) => {
|
||||
const configured = listXmppAccountIds(cfg).some((id) => resolveXmppAccount(cfg, id).configured);
|
||||
return {
|
||||
channel: "xmpp",
|
||||
configured,
|
||||
statusLines: [configured ? "XMPP is configured." : "XMPP is not configured."],
|
||||
selectionHint: "Secure federated direct messaging"
|
||||
};
|
||||
},
|
||||
configure: async (ctx) => await configureXmppInteractive(ctx),
|
||||
configureInteractive: async (ctx) => await configureXmppInteractive(ctx),
|
||||
disable: (cfg) => {
|
||||
const next = structuredClone(cfg) as XmppConfig;
|
||||
if (next.channels?.xmpp) next.channels.xmpp.enabled = false;
|
||||
return next;
|
||||
}
|
||||
};
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
|
||||
import { NS } from "./constants.js";
|
||||
import { normalizeBareJid, normalizeFullJid } from "./jid.js";
|
||||
|
||||
export interface InboundXmppMessage {
|
||||
id: string;
|
||||
from: string;
|
||||
fromBare: string;
|
||||
to?: string;
|
||||
body: string;
|
||||
timestamp?: number;
|
||||
receiptRequested: boolean;
|
||||
receiptId?: string;
|
||||
}
|
||||
|
||||
export interface SharedFileMetadata {
|
||||
url: string;
|
||||
name: string;
|
||||
mediaType: string;
|
||||
size?: number;
|
||||
sha256?: string;
|
||||
}
|
||||
|
||||
export function parseInboundMessage(
|
||||
stanza: Element,
|
||||
ownBareJid: string
|
||||
): InboundXmppMessage | undefined {
|
||||
if (!stanza.is("message")) {
|
||||
return undefined;
|
||||
}
|
||||
const type = stanza.attrs.type ?? "normal";
|
||||
if (type === "groupchat" || type === "error" || type === "headline") {
|
||||
return undefined;
|
||||
}
|
||||
const body = stanza.getChildText("body")?.trim();
|
||||
if (!body) {
|
||||
return undefined;
|
||||
}
|
||||
const from = normalizeFullJid(String(stanza.attrs.from ?? ""));
|
||||
const fromBare = from ? normalizeBareJid(from) : undefined;
|
||||
if (!from || !fromBare || fromBare === normalizeBareJid(ownBareJid)) {
|
||||
return undefined;
|
||||
}
|
||||
const to = normalizeFullJid(String(stanza.attrs.to ?? ""));
|
||||
const stanzaId = stanza
|
||||
.getChildren("stanza-id", NS.sid)
|
||||
.map((entry) => entry.attrs.id)
|
||||
.find((id): id is string => typeof id === "string" && id.length > 0);
|
||||
const originId = stanza.getChild("origin-id", NS.sid)?.attrs.id;
|
||||
const attrId =
|
||||
typeof stanza.attrs.id === "string" && stanza.attrs.id
|
||||
? stanza.attrs.id
|
||||
: undefined;
|
||||
const id = stanzaId ?? originId ?? attrId ?? randomUUID();
|
||||
const delayStamp = stanza.getChild("delay", NS.delay)?.attrs.stamp;
|
||||
const parsedDelay =
|
||||
typeof delayStamp === "string" ? Date.parse(delayStamp) : Number.NaN;
|
||||
|
||||
return {
|
||||
id,
|
||||
from,
|
||||
fromBare,
|
||||
...(to ? { to } : {}),
|
||||
body,
|
||||
...(Number.isFinite(parsedDelay) ? { timestamp: parsedDelay } : {}),
|
||||
receiptRequested: Boolean(stanza.getChild("request", NS.receipts)),
|
||||
...(attrId ? { receiptId: attrId } : {})
|
||||
};
|
||||
}
|
||||
|
||||
export function buildTextMessage(params: {
|
||||
to: string;
|
||||
text: string;
|
||||
id?: string;
|
||||
requestReceipt?: boolean;
|
||||
oobUrl?: string;
|
||||
sharedFile?: SharedFileMetadata;
|
||||
}): { id: string; stanza: Element } {
|
||||
const id = params.id ?? randomUUID();
|
||||
const children: Element[] = [
|
||||
xml("body", {}, params.text),
|
||||
xml("origin-id", { xmlns: NS.sid, id })
|
||||
];
|
||||
if (params.requestReceipt) {
|
||||
children.push(xml("request", { xmlns: NS.receipts }));
|
||||
}
|
||||
if (params.oobUrl) {
|
||||
children.push(
|
||||
xml(
|
||||
"x",
|
||||
{ xmlns: NS.oob },
|
||||
xml("url", {}, params.oobUrl),
|
||||
xml("desc", {}, params.text)
|
||||
)
|
||||
);
|
||||
}
|
||||
if (params.sharedFile) {
|
||||
const metadataChildren: Element[] = [
|
||||
xml(
|
||||
"media-type",
|
||||
{ xmlns: NS.fileMetadata },
|
||||
params.sharedFile.mediaType
|
||||
),
|
||||
xml("name", { xmlns: NS.fileMetadata }, params.sharedFile.name)
|
||||
];
|
||||
if (params.sharedFile.size !== undefined) {
|
||||
metadataChildren.push(
|
||||
xml("size", { xmlns: NS.fileMetadata }, String(params.sharedFile.size))
|
||||
);
|
||||
}
|
||||
if (params.sharedFile.sha256) {
|
||||
metadataChildren.push(
|
||||
xml(
|
||||
"hash",
|
||||
{ xmlns: NS.hashes, algo: "sha-256" },
|
||||
params.sharedFile.sha256
|
||||
)
|
||||
);
|
||||
}
|
||||
children.push(
|
||||
xml(
|
||||
"file-sharing",
|
||||
{ xmlns: NS.sfs, disposition: "inline" },
|
||||
xml("file", { xmlns: NS.fileMetadata }, ...metadataChildren),
|
||||
xml(
|
||||
"sources",
|
||||
{ xmlns: NS.sfs },
|
||||
xml("url-data", {
|
||||
xmlns: NS.urlData,
|
||||
target: params.sharedFile.url
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
if (params.text === params.sharedFile.url) {
|
||||
children.push(
|
||||
xml(
|
||||
"fallback",
|
||||
{ xmlns: NS.fallback, for: NS.sfs },
|
||||
xml("body", {})
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
id,
|
||||
stanza: xml("message", { to: params.to, type: "chat", id }, ...children)
|
||||
};
|
||||
}
|
||||
|
||||
export function buildReceipt(params: {
|
||||
to: string;
|
||||
id: string;
|
||||
}): Element {
|
||||
return xml(
|
||||
"message",
|
||||
{ to: params.to, type: "chat" },
|
||||
xml("received", { xmlns: NS.receipts, id: params.id })
|
||||
);
|
||||
}
|
||||
|
||||
export function buildChatState(params: {
|
||||
to: string;
|
||||
state: "active" | "composing" | "paused" | "inactive" | "gone";
|
||||
}): Element {
|
||||
return xml(
|
||||
"message",
|
||||
{ to: params.to, type: "chat" },
|
||||
xml(params.state, { xmlns: NS.chatStates })
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { client, xml } from "@xmpp/client";
|
||||
import type { Client, Options as XmppClientOptions } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
|
||||
import type { XmppConnectionConfig } from "./config.js";
|
||||
import { ExpiringDedupe } from "./dedupe.js";
|
||||
import {
|
||||
discoverUploadService,
|
||||
requestUploadSlot,
|
||||
safeUploadFilename,
|
||||
uploadBuffer
|
||||
} from "./media.js";
|
||||
import {
|
||||
buildChatState,
|
||||
buildReceipt,
|
||||
buildTextMessage,
|
||||
parseInboundMessage,
|
||||
type InboundXmppMessage,
|
||||
type SharedFileMetadata
|
||||
} from "./stanzas.js";
|
||||
|
||||
export interface XmppTransportStatus {
|
||||
connected: boolean;
|
||||
phase: "starting" | "online" | "degraded" | "reconnecting" | "stopped" | "failed";
|
||||
boundJid?: string;
|
||||
lastConnectedAt?: number;
|
||||
lastDisconnectedAt?: number;
|
||||
lastInboundAt?: number;
|
||||
lastOutboundAt?: number;
|
||||
lastError?: string | undefined;
|
||||
reconnectAttempts?: number;
|
||||
lastReconnectedAt?: number;
|
||||
streamManagement?: "enabled" | "resumed" | "failed" | "unavailable";
|
||||
lastProbeAt?: number;
|
||||
lastProbeSuccessAt?: number;
|
||||
lastProbeLatencyMs?: number;
|
||||
probeFailures?: number;
|
||||
lastProbeResult?: "success" | "timeout" | "unsupported" | "aborted" | "error";
|
||||
}
|
||||
|
||||
export interface XmppTransportHandlers {
|
||||
onMessage(message: InboundXmppMessage): Promise<void>;
|
||||
onStatus(status: XmppTransportStatus): void;
|
||||
log: {
|
||||
info(message: string): void;
|
||||
warn(message: string): void;
|
||||
error(message: string): void;
|
||||
debug?(message: string): void;
|
||||
};
|
||||
}
|
||||
|
||||
interface XmppClientExtensions {
|
||||
reconnect?: { delay: number; on(event: string, listener: () => void): void; removeListener(event: string, listener: () => void): void };
|
||||
streamManagement?: { enabled?: boolean; on(event: string, listener: (...args: unknown[]) => void): void; removeListener(event: string, listener: (...args: unknown[]) => void): void };
|
||||
iqCaller?: { request(stanza: Element, timeout?: number): Promise<Element> };
|
||||
}
|
||||
|
||||
export interface SendMediaInput {
|
||||
to: string;
|
||||
text: string;
|
||||
mediaUrl: string;
|
||||
mediaReadFile?: (filePath: string) => Promise<Buffer>;
|
||||
contentType?: string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface SentXmppMessage {
|
||||
id: string;
|
||||
to: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
type XmppCredentialsFactory = Extract<
|
||||
NonNullable<XmppClientOptions["credentials"]>,
|
||||
(...args: never[]) => unknown
|
||||
>;
|
||||
|
||||
function errorText(error: unknown, password?: string): string {
|
||||
const raw = error instanceof Error ? error.message : String(error);
|
||||
const sanitized = password ? raw.split(password).join("[redacted]") : raw;
|
||||
return sanitized.replace(/\s+/g, " ").slice(0, 500);
|
||||
}
|
||||
|
||||
function localPathFromMediaUrl(mediaUrl: string): string | undefined {
|
||||
try {
|
||||
const parsed = new URL(mediaUrl);
|
||||
if (parsed.protocol === "file:") {
|
||||
return fileURLToPath(parsed);
|
||||
}
|
||||
return undefined;
|
||||
} catch {
|
||||
return mediaUrl.startsWith("/") ? mediaUrl : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function inferContentType(filePath: string): string {
|
||||
const lower = filePath.toLowerCase();
|
||||
if (lower.endsWith(".png")) return "image/png";
|
||||
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
|
||||
if (lower.endsWith(".gif")) return "image/gif";
|
||||
if (lower.endsWith(".webp")) return "image/webp";
|
||||
if (lower.endsWith(".svg")) return "image/svg+xml";
|
||||
if (lower.endsWith(".pdf")) return "application/pdf";
|
||||
if (lower.endsWith(".mp3")) return "audio/mpeg";
|
||||
if (lower.endsWith(".ogg") || lower.endsWith(".opus")) return "audio/ogg";
|
||||
if (lower.endsWith(".mp4")) return "video/mp4";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
function remoteFilename(url: URL): string {
|
||||
try {
|
||||
return safeUploadFilename(decodeURIComponent(url.pathname));
|
||||
} catch {
|
||||
return safeUploadFilename(url.pathname);
|
||||
}
|
||||
}
|
||||
|
||||
export function createTlsRequiredCredentials(
|
||||
config: Pick<XmppConnectionConfig, "username" | "password">
|
||||
): XmppCredentialsFactory {
|
||||
return async (authenticate, mechanisms, _fast, entity) => {
|
||||
if (!entity.isSecure()) {
|
||||
throw new Error("XMPP TLS is required before authentication.");
|
||||
}
|
||||
const mechanism = mechanisms.find((candidate) => candidate !== "ANONYMOUS");
|
||||
if (!mechanism) {
|
||||
throw new Error("The XMPP server offered no supported authenticated SASL mechanism.");
|
||||
}
|
||||
await authenticate(
|
||||
{
|
||||
username: config.username,
|
||||
password: config.password
|
||||
},
|
||||
mechanism,
|
||||
xml("user-agent", { id: randomUUID() })
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export class XmppTransport {
|
||||
readonly #xmpp: Client;
|
||||
readonly #dedupe = new ExpiringDedupe();
|
||||
#status: XmppTransportStatus = { connected: false, phase: "starting" };
|
||||
#uploadService: string | undefined;
|
||||
#stopped = false;
|
||||
#probeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
#probeInFlight = false;
|
||||
readonly #onReconnecting = () => {
|
||||
this.#clearProbeTimer();
|
||||
this.#updateStatus({
|
||||
connected: false,
|
||||
phase: "reconnecting",
|
||||
reconnectAttempts: (this.#status.reconnectAttempts ?? 0) + 1
|
||||
});
|
||||
};
|
||||
readonly #onReconnected = () => {
|
||||
this.#updateStatus({ lastReconnectedAt: Date.now() });
|
||||
};
|
||||
readonly #onResumed = () => {
|
||||
this.#updateStatus({
|
||||
connected: true,
|
||||
phase: "online",
|
||||
lastReconnectedAt: Date.now(),
|
||||
streamManagement: "resumed",
|
||||
lastError: undefined
|
||||
});
|
||||
this.#scheduleProbe();
|
||||
};
|
||||
readonly #onStreamManagementFail = () => {
|
||||
this.#updateStatus({ streamManagement: "failed" });
|
||||
};
|
||||
|
||||
constructor(
|
||||
readonly config: XmppConnectionConfig,
|
||||
private readonly handlers: XmppTransportHandlers
|
||||
) {
|
||||
this.#xmpp = client({
|
||||
service: config.service,
|
||||
domain: config.domain,
|
||||
resource: config.resource,
|
||||
credentials: createTlsRequiredCredentials(config),
|
||||
timeout: 15_000
|
||||
});
|
||||
const extensions = this.#extensions();
|
||||
if (extensions.reconnect) {
|
||||
extensions.reconnect.delay = config.reconnectDelayMs;
|
||||
extensions.reconnect.on("reconnecting", this.#onReconnecting);
|
||||
extensions.reconnect.on("reconnected", this.#onReconnected);
|
||||
}
|
||||
if (extensions.streamManagement) {
|
||||
extensions.streamManagement.on("resumed", this.#onResumed);
|
||||
extensions.streamManagement.on("fail", this.#onStreamManagementFail);
|
||||
}
|
||||
this.#xmpp.on("error", (error) => {
|
||||
const message = errorText(error, config.password);
|
||||
this.#updateStatus({ lastError: message });
|
||||
handlers.log.error(`[${config.accountId}] XMPP error: ${message}`);
|
||||
});
|
||||
this.#xmpp.on("status", (status) => {
|
||||
handlers.log.debug?.(`[${config.accountId}] XMPP status: ${status}`);
|
||||
});
|
||||
this.#xmpp.on("online", async (address) => {
|
||||
if (!this.#xmpp.isSecure()) {
|
||||
const message = "XMPP connection did not negotiate TLS; closing.";
|
||||
this.#updateStatus({ connected: false, lastError: message });
|
||||
handlers.log.error(`[${config.accountId}] ${message}`);
|
||||
await this.#xmpp.stop().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
const boundJid = address.toString();
|
||||
const recoveredWithFullBind = (this.#status.reconnectAttempts ?? 0) > 0;
|
||||
this.#updateStatus({
|
||||
connected: true,
|
||||
phase: "online",
|
||||
boundJid,
|
||||
lastConnectedAt: Date.now(),
|
||||
reconnectAttempts: 0,
|
||||
streamManagement: recoveredWithFullBind
|
||||
? "failed"
|
||||
: extensions.streamManagement?.enabled
|
||||
? "enabled"
|
||||
: "unavailable",
|
||||
lastError: undefined
|
||||
});
|
||||
handlers.log.info(`[${config.accountId}] XMPP connected as ${boundJid}`);
|
||||
await this.#xmpp.send(xml("presence"));
|
||||
this.#scheduleProbe();
|
||||
});
|
||||
this.#xmpp.on("disconnect", () => {
|
||||
this.#clearProbeTimer();
|
||||
this.#uploadService = undefined;
|
||||
this.#updateStatus({
|
||||
connected: false,
|
||||
phase: this.#stopped ? "stopped" : "reconnecting",
|
||||
lastDisconnectedAt: Date.now()
|
||||
});
|
||||
});
|
||||
this.#xmpp.on("stanza", (stanza) => {
|
||||
void this.#handleStanza(stanza);
|
||||
});
|
||||
}
|
||||
|
||||
get status(): XmppTransportStatus {
|
||||
return { ...this.#status };
|
||||
}
|
||||
|
||||
async run(signal: AbortSignal): Promise<void> {
|
||||
const stop = () => {
|
||||
void this.stop();
|
||||
};
|
||||
signal.addEventListener("abort", stop, { once: true });
|
||||
try {
|
||||
try {
|
||||
await this.#xmpp.start();
|
||||
} catch (error) {
|
||||
this.#updateStatus({
|
||||
connected: false,
|
||||
phase: "failed",
|
||||
lastError: errorText(error, this.config.password)
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
if (!this.#xmpp.isSecure()) {
|
||||
throw new Error("XMPP TLS negotiation was required but did not succeed.");
|
||||
}
|
||||
if (!signal.aborted) {
|
||||
await new Promise<void>((resolve) => {
|
||||
signal.addEventListener("abort", () => resolve(), { once: true });
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener("abort", stop);
|
||||
await this.stop();
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.#stopped) {
|
||||
return;
|
||||
}
|
||||
this.#stopped = true;
|
||||
this.#clearProbeTimer();
|
||||
const extensions = this.#extensions();
|
||||
extensions.reconnect?.removeListener("reconnecting", this.#onReconnecting);
|
||||
extensions.reconnect?.removeListener("reconnected", this.#onReconnected);
|
||||
extensions.streamManagement?.removeListener("resumed", this.#onResumed);
|
||||
extensions.streamManagement?.removeListener("fail", this.#onStreamManagementFail);
|
||||
await this.#xmpp.stop().catch(() => undefined);
|
||||
this.#updateStatus({
|
||||
connected: false,
|
||||
phase: "stopped",
|
||||
lastDisconnectedAt: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
async probe(signal?: AbortSignal): Promise<XmppTransportStatus["lastProbeResult"]> {
|
||||
if (!this.config.healthProbe || this.#probeInFlight) {
|
||||
return this.#status.lastProbeResult;
|
||||
}
|
||||
this.#assertConnected();
|
||||
const extensions = this.#extensions();
|
||||
if (!extensions.iqCaller) {
|
||||
this.#recordProbe("unsupported");
|
||||
return "unsupported";
|
||||
}
|
||||
this.#probeInFlight = true;
|
||||
const startedAt = Date.now();
|
||||
this.#updateStatus({ lastProbeAt: startedAt });
|
||||
let timedOut = false;
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
let onAbort: (() => void) | undefined;
|
||||
try {
|
||||
const races: Promise<unknown>[] = [
|
||||
extensions.iqCaller.request(
|
||||
xml("iq", { type: "get", to: this.config.domain },
|
||||
xml("ping", { xmlns: "urn:xmpp:ping" }))
|
||||
, this.config.healthProbeTimeoutMs
|
||||
),
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
reject(new Error("XMPP health probe timed out."));
|
||||
}, this.config.healthProbeTimeoutMs);
|
||||
timeout.unref?.();
|
||||
})
|
||||
];
|
||||
if (signal) {
|
||||
races.push(new Promise<never>((_resolve, reject) => {
|
||||
onAbort = () => reject(signal.reason ?? new Error("XMPP health probe aborted."));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
}));
|
||||
}
|
||||
await Promise.race(races);
|
||||
this.#recordProbe("success", Date.now() - startedAt);
|
||||
return "success";
|
||||
} catch (error) {
|
||||
const text = errorText(error, this.config.password).toLowerCase();
|
||||
const result = signal?.aborted
|
||||
? "aborted"
|
||||
: timedOut || text.includes("timeout")
|
||||
? "timeout"
|
||||
: /service-unavailable|feature-not-implemented|item-not-found/.test(text)
|
||||
? "unsupported"
|
||||
: "error";
|
||||
this.#recordProbe(result);
|
||||
return result;
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
if (signal && onAbort) signal.removeEventListener("abort", onAbort);
|
||||
this.#probeInFlight = false;
|
||||
this.#scheduleProbe();
|
||||
}
|
||||
}
|
||||
|
||||
async sendText(
|
||||
to: string,
|
||||
text: string,
|
||||
options: {
|
||||
requestReceipt?: boolean;
|
||||
oobUrl?: string;
|
||||
sharedFile?: SharedFileMetadata;
|
||||
} = {}
|
||||
): Promise<SentXmppMessage> {
|
||||
this.#assertConnected();
|
||||
const built = buildTextMessage({
|
||||
to,
|
||||
text,
|
||||
requestReceipt:
|
||||
options.requestReceipt ?? this.config.requestReceipts,
|
||||
...(options.oobUrl ? { oobUrl: options.oobUrl } : {}),
|
||||
...(options.sharedFile ? { sharedFile: options.sharedFile } : {})
|
||||
});
|
||||
await this.#xmpp.send(built.stanza);
|
||||
this.#updateStatus({ lastOutboundAt: Date.now() });
|
||||
return {
|
||||
id: built.id,
|
||||
to,
|
||||
...(options.oobUrl ? { url: options.oobUrl } : {})
|
||||
};
|
||||
}
|
||||
|
||||
async sendReceipt(to: string, id: string): Promise<void> {
|
||||
if (!this.config.sendReceipts || !this.#status.connected) {
|
||||
return;
|
||||
}
|
||||
await this.#xmpp.send(buildReceipt({ to, id }));
|
||||
this.#updateStatus({ lastOutboundAt: Date.now() });
|
||||
}
|
||||
|
||||
async sendChatState(
|
||||
to: string,
|
||||
state: "active" | "composing" | "paused" | "inactive" | "gone"
|
||||
): Promise<void> {
|
||||
if (!this.config.sendChatStates || !this.#status.connected) {
|
||||
return;
|
||||
}
|
||||
await this.#xmpp.send(buildChatState({ to, state }));
|
||||
}
|
||||
|
||||
async sendMedia(input: SendMediaInput): Promise<SentXmppMessage> {
|
||||
const localPath = localPathFromMediaUrl(input.mediaUrl);
|
||||
if (!localPath) {
|
||||
const url = new URL(input.mediaUrl);
|
||||
if (url.protocol !== "https:") {
|
||||
throw new Error("XMPP outbound media must be a local file or HTTPS URL.");
|
||||
}
|
||||
const name = remoteFilename(url);
|
||||
return await this.#sendInlineMedia({
|
||||
to: input.to,
|
||||
caption: input.text,
|
||||
sharedFile: {
|
||||
url: url.toString(),
|
||||
name,
|
||||
mediaType: input.contentType ?? inferContentType(name)
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!input.mediaReadFile) {
|
||||
throw new Error(
|
||||
"OpenClaw did not provide a validated media reader for the local file."
|
||||
);
|
||||
}
|
||||
const buffer = await input.mediaReadFile(localPath);
|
||||
if (buffer.byteLength > this.config.mediaMaxBytes) {
|
||||
throw new Error(
|
||||
`XMPP media exceeds the configured ${Math.floor(
|
||||
this.config.mediaMaxBytes / 1024 / 1024
|
||||
)} MB limit.`
|
||||
);
|
||||
}
|
||||
const service =
|
||||
this.#uploadService ??
|
||||
(this.#uploadService = await discoverUploadService(
|
||||
this.#xmpp,
|
||||
this.config.domain
|
||||
));
|
||||
const contentType = input.contentType ?? inferContentType(localPath);
|
||||
const slot = await requestUploadSlot({
|
||||
xmpp: this.#xmpp,
|
||||
serviceJid: service,
|
||||
filename: safeUploadFilename(localPath),
|
||||
size: buffer.byteLength,
|
||||
contentType
|
||||
});
|
||||
const downloadUrl = await uploadBuffer({
|
||||
slot,
|
||||
buffer,
|
||||
contentType,
|
||||
...(input.signal ? { signal: input.signal } : {})
|
||||
});
|
||||
const name = safeUploadFilename(localPath);
|
||||
return await this.#sendInlineMedia({
|
||||
to: input.to,
|
||||
caption: input.text,
|
||||
sharedFile: {
|
||||
url: downloadUrl,
|
||||
name,
|
||||
mediaType: contentType,
|
||||
size: buffer.byteLength,
|
||||
sha256: createHash("sha256").update(buffer).digest("base64")
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async #sendInlineMedia(params: {
|
||||
to: string;
|
||||
caption: string;
|
||||
sharedFile: SharedFileMetadata;
|
||||
}): Promise<SentXmppMessage> {
|
||||
const caption = params.caption.trim();
|
||||
if (caption && caption !== params.sharedFile.url) {
|
||||
await this.sendText(params.to, caption);
|
||||
}
|
||||
// Conversations renders XEP-0447 files inline when the ordinary body is
|
||||
// the source URL and XEP-0428 marks that body as compatibility fallback.
|
||||
return await this.sendText(params.to, params.sharedFile.url, {
|
||||
oobUrl: params.sharedFile.url,
|
||||
sharedFile: params.sharedFile
|
||||
});
|
||||
}
|
||||
|
||||
async #handleStanza(stanza: Element): Promise<void> {
|
||||
try {
|
||||
const message = parseInboundMessage(stanza, this.config.jid);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
const dedupeKey = `${message.fromBare}\u0000${message.id}`;
|
||||
if (this.#dedupe.seen(dedupeKey)) {
|
||||
this.handlers.log.debug?.(
|
||||
`[${this.config.accountId}] dropped duplicate XMPP message ${message.id}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.#updateStatus({ lastInboundAt: Date.now() });
|
||||
await this.handlers.onMessage(message);
|
||||
} catch (error) {
|
||||
this.handlers.log.error(
|
||||
`[${this.config.accountId}] inbound XMPP handling failed: ${errorText(
|
||||
error,
|
||||
this.config.password
|
||||
)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#assertConnected(): void {
|
||||
if (!this.#status.connected || this.#xmpp.status !== "online") {
|
||||
throw new Error(
|
||||
`XMPP account "${this.config.accountId}" is not connected.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#extensions(): XmppClientExtensions {
|
||||
return this.#xmpp as unknown as XmppClientExtensions;
|
||||
}
|
||||
|
||||
#recordProbe(
|
||||
result: NonNullable<XmppTransportStatus["lastProbeResult"]>,
|
||||
latencyMs?: number
|
||||
): void {
|
||||
const successful = result === "success";
|
||||
const unsupported = result === "unsupported";
|
||||
this.#updateStatus({
|
||||
lastProbeResult: result,
|
||||
...(successful ? {
|
||||
lastProbeSuccessAt: Date.now(),
|
||||
...(latencyMs !== undefined ? { lastProbeLatencyMs: latencyMs } : {})
|
||||
} : {}),
|
||||
probeFailures: successful || unsupported ? 0 : (this.#status.probeFailures ?? 0) + 1,
|
||||
phase: successful || unsupported
|
||||
? "online"
|
||||
: (this.#status.probeFailures ?? 0) + 1 >= 3
|
||||
? "degraded"
|
||||
: this.#status.phase
|
||||
});
|
||||
}
|
||||
|
||||
#scheduleProbe(): void {
|
||||
this.#clearProbeTimer();
|
||||
if (!this.config.healthProbe || this.#stopped || !this.#status.connected) {
|
||||
return;
|
||||
}
|
||||
this.#probeTimer = setTimeout(() => {
|
||||
void this.probe().catch((error) => {
|
||||
this.handlers.log.warn(
|
||||
`[${this.config.accountId}] XMPP health probe failed: ${errorText(error, this.config.password)}`
|
||||
);
|
||||
});
|
||||
}, this.config.healthProbeIntervalMs);
|
||||
this.#probeTimer.unref?.();
|
||||
}
|
||||
|
||||
#clearProbeTimer(): void {
|
||||
if (this.#probeTimer) {
|
||||
clearTimeout(this.#probeTimer);
|
||||
this.#probeTimer = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
#updateStatus(patch: Partial<XmppTransportStatus>): void {
|
||||
this.#status = { ...this.#status, ...patch };
|
||||
if (patch.lastError === undefined && "lastError" in patch) {
|
||||
delete this.#status.lastError;
|
||||
}
|
||||
this.handlers.onStatus(this.status);
|
||||
}
|
||||
}
|
||||
|
||||
const liveTransports = new Map<string, XmppTransport>();
|
||||
|
||||
export function registerLiveTransport(
|
||||
accountId: string,
|
||||
transport: XmppTransport
|
||||
): () => void {
|
||||
liveTransports.set(accountId, transport);
|
||||
return () => {
|
||||
if (liveTransports.get(accountId) === transport) {
|
||||
liveTransports.delete(accountId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function getLiveTransport(accountId: string): XmppTransport | undefined {
|
||||
return liveTransports.get(accountId);
|
||||
}
|
||||
|
||||
export function resetLiveTransportsForTests(): void {
|
||||
liveTransports.clear();
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
listXmppAccountIds,
|
||||
resolveDefaultXmppAccountId,
|
||||
resolveXmppAccount,
|
||||
resolveXmppConnectionConfig
|
||||
} from "../src/config.js";
|
||||
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
describe("XMPP account configuration", () => {
|
||||
it("resolves a safe single account without exposing the password in snapshots", async () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
jid: "Bot@Example.ORG",
|
||||
password: "secret",
|
||||
dmPolicy: "allowlist",
|
||||
allowFrom: ["Alice@Example.ORG/phone"]
|
||||
}
|
||||
}
|
||||
} as unknown as OpenClawConfig;
|
||||
const account = resolveXmppAccount(cfg);
|
||||
expect(account).toMatchObject({
|
||||
accountId: "default",
|
||||
jid: "bot@example.org",
|
||||
configured: true,
|
||||
dmPolicy: "allowlist",
|
||||
allowFrom: ["alice@example.org"]
|
||||
});
|
||||
const connection = await resolveXmppConnectionConfig(cfg);
|
||||
expect(connection).toMatchObject({
|
||||
domain: "example.org",
|
||||
username: "bot",
|
||||
password: "secret",
|
||||
service: "example.org"
|
||||
});
|
||||
});
|
||||
|
||||
it("supports named accounts and a configured default", () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
defaultAccount: "work",
|
||||
accounts: {
|
||||
personal: { jid: "me@example.org", password: "one" },
|
||||
work: { jid: "me@example.net", password: "two" }
|
||||
}
|
||||
}
|
||||
}
|
||||
} as unknown as OpenClawConfig;
|
||||
expect(listXmppAccountIds(cfg)).toEqual(["personal", "work"]);
|
||||
expect(resolveDefaultXmppAccountId(cfg)).toBe("work");
|
||||
expect(resolveXmppAccount(cfg).jid).toBe("me@example.net");
|
||||
});
|
||||
|
||||
it("accepts environment setup and rejects insecure WebSockets", async () => {
|
||||
process.env.XMPP_JID = "bot@example.org";
|
||||
process.env.XMPP_PASSWORD = "secret";
|
||||
const envCfg = {} as OpenClawConfig;
|
||||
expect(resolveXmppAccount(envCfg).configured).toBe(true);
|
||||
|
||||
const badCfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
jid: "bot@example.org",
|
||||
password: "secret",
|
||||
websocketUrl: "ws://example.org/xmpp"
|
||||
}
|
||||
}
|
||||
} as unknown as OpenClawConfig;
|
||||
await expect(resolveXmppConnectionConfig(badCfg)).rejects.toThrow(
|
||||
/must use wss/
|
||||
);
|
||||
});
|
||||
|
||||
it("requires dmPolicy open for a wildcard allowlist", async () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
jid: "bot@example.org",
|
||||
password: "secret",
|
||||
dmPolicy: "allowlist",
|
||||
allowFrom: ["*"]
|
||||
}
|
||||
}
|
||||
} as unknown as OpenClawConfig;
|
||||
await expect(resolveXmppConnectionConfig(cfg)).rejects.toThrow(
|
||||
/dmPolicy is not "open"/
|
||||
);
|
||||
});
|
||||
|
||||
it("applies conservative bounded probe and reconnect defaults", async () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
jid: "bot@example.org",
|
||||
password: "secret",
|
||||
healthProbeIntervalSeconds: 1,
|
||||
healthProbeTimeoutSeconds: 999,
|
||||
reconnectDelaySeconds: 0
|
||||
}
|
||||
}
|
||||
} as unknown as OpenClawConfig;
|
||||
expect(resolveXmppAccount(cfg)).toMatchObject({
|
||||
healthProbe: true,
|
||||
healthProbeIntervalSeconds: 30,
|
||||
healthProbeTimeoutSeconds: 60,
|
||||
reconnectDelaySeconds: 1
|
||||
});
|
||||
expect(await resolveXmppConnectionConfig(cfg)).toMatchObject({
|
||||
healthProbe: true,
|
||||
healthProbeIntervalMs: 30_000,
|
||||
healthProbeTimeoutMs: 60_000,
|
||||
reconnectDelayMs: 1_000
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ExpiringDedupe } from "../src/dedupe.js";
|
||||
|
||||
describe("ExpiringDedupe", () => {
|
||||
it("recognizes duplicates until the TTL expires", () => {
|
||||
let now = 1_000;
|
||||
const dedupe = new ExpiringDedupe(100, 10, () => now);
|
||||
expect(dedupe.seen("a")).toBe(false);
|
||||
expect(dedupe.seen("a")).toBe(true);
|
||||
now = 1_101;
|
||||
expect(dedupe.seen("a")).toBe(false);
|
||||
});
|
||||
|
||||
it("evicts oldest entries at the configured limit", () => {
|
||||
const dedupe = new ExpiringDedupe(1_000, 2, () => 1_000);
|
||||
dedupe.seen("a");
|
||||
dedupe.seen("b");
|
||||
dedupe.seen("c");
|
||||
expect(dedupe.size).toBe(2);
|
||||
expect(dedupe.seen("a")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
|
||||
const xmppMock = vi.hoisted(() => ({
|
||||
secure: true,
|
||||
clients: [] as Array<{
|
||||
start: ReturnType<typeof vi.fn>;
|
||||
stop: ReturnType<typeof vi.fn>;
|
||||
send: ReturnType<typeof vi.fn>;
|
||||
authenticate: ReturnType<typeof vi.fn>;
|
||||
}>
|
||||
}));
|
||||
|
||||
vi.mock("@xmpp/client", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@xmpp/client")>();
|
||||
|
||||
return {
|
||||
...actual,
|
||||
client: (options: {
|
||||
credentials: (
|
||||
authenticate: ReturnType<typeof vi.fn>,
|
||||
mechanisms: string[],
|
||||
fast: null,
|
||||
entity: { isSecure(): boolean }
|
||||
) => Promise<void>;
|
||||
}) => {
|
||||
const events = new EventEmitter();
|
||||
const authenticate = vi.fn(async () => undefined);
|
||||
const fake = Object.assign(events, {
|
||||
isSecure: () => xmppMock.secure,
|
||||
authenticate,
|
||||
send: vi.fn(async () => undefined),
|
||||
stop: vi.fn(async () => undefined),
|
||||
start: vi.fn(async () => {
|
||||
await options.credentials(
|
||||
authenticate,
|
||||
["SCRAM-SHA-1", "PLAIN"],
|
||||
null,
|
||||
{ isSecure: () => xmppMock.secure }
|
||||
);
|
||||
events.emit("online", { toString: () => "bot@example.org/openclaw" });
|
||||
})
|
||||
});
|
||||
xmppMock.clients.push(fake);
|
||||
return fake;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
import { xmppPlugin } from "../src/channel.js";
|
||||
import { resolveXmppAccount } from "../src/config.js";
|
||||
import { setXmppPluginRuntime } from "../src/inbound.js";
|
||||
|
||||
function gatewayContext(cfg: OpenClawConfig, abortSignal: AbortSignal) {
|
||||
return {
|
||||
cfg,
|
||||
accountId: "default",
|
||||
account: resolveXmppAccount(cfg, "default"),
|
||||
abortSignal,
|
||||
channelRuntime: {},
|
||||
setStatus: vi.fn(),
|
||||
runtime: { log: vi.fn(), error: vi.fn() },
|
||||
log: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe("Gateway security gates", () => {
|
||||
beforeEach(() => {
|
||||
setXmppPluginRuntime({} as never);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
xmppMock.clients.length = 0;
|
||||
xmppMock.secure = true;
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("refuses Gateway startup before sending credentials when TLS is unavailable", async () => {
|
||||
xmppMock.secure = false;
|
||||
const cfg = {
|
||||
channels: { xmpp: { jid: "bot@example.org", password: "test-only-secret" } }
|
||||
} as unknown as OpenClawConfig;
|
||||
const controller = new AbortController();
|
||||
const startAccount = xmppPlugin.gateway?.startAccount;
|
||||
|
||||
await expect(
|
||||
startAccount?.(gatewayContext(cfg, controller.signal) as never)
|
||||
).rejects.toThrow(/TLS is required before authentication/);
|
||||
|
||||
const client = xmppMock.clients[0];
|
||||
expect(client).toBeDefined();
|
||||
expect(client?.authenticate).not.toHaveBeenCalled();
|
||||
expect(client?.send).not.toHaveBeenCalled();
|
||||
expect(client?.stop).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("starts a complete Gateway account using an env SecretRef", async () => {
|
||||
vi.stubEnv("XMPP_GATEWAY_TEST_PASSWORD", "resolved-test-only-secret");
|
||||
const cfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
jid: "bot@example.org",
|
||||
password: {
|
||||
source: "env",
|
||||
provider: "default",
|
||||
id: "XMPP_GATEWAY_TEST_PASSWORD"
|
||||
}
|
||||
}
|
||||
}
|
||||
} as unknown as OpenClawConfig;
|
||||
const controller = new AbortController();
|
||||
const ctx = gatewayContext(cfg, controller.signal);
|
||||
const startAccount = xmppPlugin.gateway?.startAccount;
|
||||
|
||||
expect(typeof cfg.channels?.xmpp?.password).toBe("object");
|
||||
const running = startAccount?.(ctx as never);
|
||||
await vi.waitFor(() => {
|
||||
expect(xmppMock.clients[0]?.authenticate).toHaveBeenCalledWith(
|
||||
{
|
||||
username: "bot",
|
||||
password: "resolved-test-only-secret"
|
||||
},
|
||||
"SCRAM-SHA-1",
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(ctx.setStatus).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
accountId: "default",
|
||||
running: true,
|
||||
connected: true
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
controller.abort();
|
||||
await running;
|
||||
expect(xmppMock.clients[0]?.stop).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
|
||||
import {
|
||||
chunkXmppReplyText,
|
||||
recoverMarkdownWrappedMediaDirectives
|
||||
} from "../src/inbound.js";
|
||||
|
||||
describe("XMPP inbound runtime wiring", () => {
|
||||
it("splits long direct-DM replies with the configured XMPP limit", () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
textChunkLimit: 4_000
|
||||
}
|
||||
}
|
||||
} as OpenClawConfig;
|
||||
const text = `${"A".repeat(3_500)}\n\n${"B".repeat(3_000)} END OF TEST`;
|
||||
|
||||
const chunks = chunkXmppReplyText({
|
||||
cfg,
|
||||
accountId: "default",
|
||||
text
|
||||
});
|
||||
|
||||
expect(chunks).toHaveLength(2);
|
||||
expect(chunks.every((chunk) => chunk.length <= 4_000)).toBe(true);
|
||||
expect(chunks.at(-1)).toContain("END OF TEST");
|
||||
});
|
||||
|
||||
it("uses the conservative XMPP default when no override is configured", () => {
|
||||
const chunks = chunkXmppReplyText({
|
||||
cfg: { channels: { xmpp: { enabled: true } } } as OpenClawConfig,
|
||||
accountId: "default",
|
||||
text: "X".repeat(6_482)
|
||||
});
|
||||
|
||||
expect(chunks.map((chunk) => chunk.length)).toEqual([4_000, 2_482]);
|
||||
});
|
||||
|
||||
it("uses an account-level XMPP chunk limit for direct-DM replies", () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
textChunkLimit: 4_000,
|
||||
accounts: {
|
||||
personal: { textChunkLimit: 2_000 }
|
||||
}
|
||||
}
|
||||
}
|
||||
} as OpenClawConfig;
|
||||
|
||||
const chunks = chunkXmppReplyText({
|
||||
cfg,
|
||||
accountId: "personal",
|
||||
text: "X".repeat(4_500)
|
||||
});
|
||||
|
||||
expect(chunks).toHaveLength(3);
|
||||
expect(chunks.every((chunk) => chunk.length <= 2_000)).toBe(true);
|
||||
});
|
||||
|
||||
it("recovers whole-line Markdown-wrapped MEDIA directives", () => {
|
||||
const source = "/home/example/.openclaw/media/plot with spaces.png";
|
||||
const wrappers = ["**{}**", "__{}__", "~~{}~~", "`{}`", "*{}*", "_{}_"];
|
||||
|
||||
for (const wrapper of wrappers) {
|
||||
const raw = wrapper.replace("{}", `MEDIA:${source}`);
|
||||
expect(recoverMarkdownWrappedMediaDirectives(raw)).toEqual({
|
||||
text: "",
|
||||
mediaSources: [source]
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("recovers nested wrappers and preserves the caption", () => {
|
||||
const source = "https://upload.example.org/plot.png";
|
||||
|
||||
expect(
|
||||
recoverMarkdownWrappedMediaDirectives(
|
||||
`Plot attached.\n**\`MEDIA:${source}\`**`
|
||||
)
|
||||
).toEqual({
|
||||
text: "Plot attached.",
|
||||
mediaSources: [source]
|
||||
});
|
||||
});
|
||||
|
||||
it("does not recover inline prose, plain directives, or fenced examples", () => {
|
||||
const source = "https://upload.example.org/plot.png";
|
||||
const raw = [
|
||||
`Here is the file: **MEDIA:${source}**`,
|
||||
`MEDIA:${source}`,
|
||||
"```text",
|
||||
`**MEDIA:${source}**`,
|
||||
"```"
|
||||
].join("\n");
|
||||
|
||||
expect(recoverMarkdownWrappedMediaDirectives(raw)).toEqual({
|
||||
text: raw,
|
||||
mediaSources: []
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects wrapped unsupported or credential-bearing media sources", () => {
|
||||
const raw = [
|
||||
"**MEDIA:http://upload.example.org/plot.png**",
|
||||
"**MEDIA:https://user:secret@upload.example.org/plot.png**",
|
||||
"**MEDIA:relative/plot.png**"
|
||||
].join("\n");
|
||||
|
||||
expect(recoverMarkdownWrappedMediaDirectives(raw)).toEqual({
|
||||
text: raw,
|
||||
mediaSources: []
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
matchesAllowFrom,
|
||||
normalizeBareJid,
|
||||
normalizeFullJid,
|
||||
normalizeXmppTarget
|
||||
} from "../src/jid.js";
|
||||
|
||||
describe("JID normalization", () => {
|
||||
it("normalizes case, resources, and target prefixes", () => {
|
||||
expect(normalizeBareJid(" Alice@Example.ORG/Phone ")).toBe(
|
||||
"alice@example.org"
|
||||
);
|
||||
expect(normalizeFullJid("xmpp:Alice@Example.ORG/Phone")).toBe(
|
||||
"alice@example.org/Phone"
|
||||
);
|
||||
expect(normalizeXmppTarget("xmpp:Alice@Example.ORG")).toBe(
|
||||
"alice@example.org"
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects non-JID targets", () => {
|
||||
expect(normalizeBareJid("not-a-jid")).toBeUndefined();
|
||||
expect(normalizeXmppTarget("*")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("matches bare JID allowlists and wildcard entries", () => {
|
||||
expect(
|
||||
matchesAllowFrom("Alice@Example.ORG/Phone", ["alice@example.org"])
|
||||
).toBe(true);
|
||||
expect(matchesAllowFrom("alice@example.org", ["*"])).toBe(true);
|
||||
expect(matchesAllowFrom("mallory@example.org", ["alice@example.org"])).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { xml } from "@xmpp/client";
|
||||
import type { Element } from "@xmpp/xml";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { NS } from "../src/constants.js";
|
||||
import { requestUploadSlot, uploadBuffer } from "../src/media.js";
|
||||
|
||||
const { fetchWithSsrFGuard } = vi.hoisted(() => ({
|
||||
fetchWithSsrFGuard: vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock("openclaw/plugin-sdk/ssrf-runtime", () => ({
|
||||
fetchWithSsrFGuard
|
||||
}));
|
||||
|
||||
describe("XEP-0363 upload slots", () => {
|
||||
it("reads the differently named slot child from the full IQ result", async () => {
|
||||
const response = xml(
|
||||
"iq",
|
||||
{ type: "result", id: "upload-1" },
|
||||
xml(
|
||||
"slot",
|
||||
{ xmlns: NS.httpUpload },
|
||||
xml(
|
||||
"put",
|
||||
{ url: "https://upload.example.org/put" },
|
||||
xml("header", { name: "Expires" }, "60"),
|
||||
xml("header", { name: "Authori\nzation" }, "Bearer\r\n first"),
|
||||
xml("header", { name: "authorization" }, "Bearer second"),
|
||||
xml("header", { name: "Cookie" }, "session=one\n"),
|
||||
xml("header", { name: "cookie" }, "theme=dark"),
|
||||
xml("header", { name: "X-Not-Allowed" }, "ignored"),
|
||||
xml("header", { name: "Proxy-Authorization" }, "ignored")
|
||||
),
|
||||
xml("get", { url: "https://upload.example.org/get/plot.png" })
|
||||
)
|
||||
);
|
||||
const request = vi.fn(async (_stanza: Element, _timeout: number) => response);
|
||||
|
||||
const slot = await requestUploadSlot({
|
||||
xmpp: { iqCaller: { request } } as never,
|
||||
serviceJid: "upload.example.org",
|
||||
filename: "plot.png",
|
||||
size: 1234,
|
||||
contentType: "image/png"
|
||||
});
|
||||
|
||||
expect(request).toHaveBeenCalledOnce();
|
||||
const [stanza, timeout] = request.mock.calls[0] ?? [];
|
||||
expect(stanza?.attrs).toMatchObject({
|
||||
type: "get",
|
||||
to: "upload.example.org"
|
||||
});
|
||||
expect(stanza?.getChild("request", NS.httpUpload)?.attrs).toMatchObject({
|
||||
filename: "plot.png",
|
||||
size: "1234",
|
||||
"content-type": "image/png"
|
||||
});
|
||||
expect(timeout).toBe(20_000);
|
||||
expect(slot).toEqual({
|
||||
putUrl: "https://upload.example.org/put",
|
||||
getUrl: "https://upload.example.org/get/plot.png",
|
||||
headers: [
|
||||
["Expires", "60"],
|
||||
["Authorization", "Bearer first"],
|
||||
["Authorization", "Bearer second"],
|
||||
["Cookie", "session=one"],
|
||||
["Cookie", "theme=dark"]
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
it("copies allowed headers into the PUT in repeated-value order", async () => {
|
||||
const release = vi.fn(async () => undefined);
|
||||
fetchWithSsrFGuard.mockResolvedValueOnce({
|
||||
response: new Response(null, { status: 201 }),
|
||||
release
|
||||
});
|
||||
|
||||
await expect(
|
||||
uploadBuffer({
|
||||
slot: {
|
||||
putUrl: "https://upload.example.org/put",
|
||||
getUrl: "https://upload.example.org/get/plot.png",
|
||||
headers: [
|
||||
["Authorization", "Bearer first"],
|
||||
["Authorization", "Bearer second"],
|
||||
["Cookie", "session=one"],
|
||||
["Cookie", "theme=dark"],
|
||||
["Expires", "60"]
|
||||
]
|
||||
},
|
||||
buffer: Buffer.from("png"),
|
||||
contentType: "image/png"
|
||||
})
|
||||
).resolves.toBe("https://upload.example.org/get/plot.png");
|
||||
|
||||
expect(fetchWithSsrFGuard).toHaveBeenCalledOnce();
|
||||
const request = fetchWithSsrFGuard.mock.calls[0]?.[0];
|
||||
expect(request).toMatchObject({
|
||||
url: "https://upload.example.org/put",
|
||||
requireHttps: true,
|
||||
maxRedirects: 0,
|
||||
capture: false,
|
||||
init: {
|
||||
method: "PUT",
|
||||
body: new Uint8Array(Buffer.from("png"))
|
||||
}
|
||||
});
|
||||
expect(request?.init?.headers).toBeInstanceOf(Headers);
|
||||
const headers = request?.init?.headers as Headers;
|
||||
expect(headers.get("authorization")).toBe("Bearer first, Bearer second");
|
||||
expect(headers.get("cookie")).toBe("session=one; theme=dark");
|
||||
expect(headers.get("expires")).toBe("60");
|
||||
expect(headers.get("content-type")).toBe("image/png");
|
||||
expect(headers.get("content-length")).toBe("3");
|
||||
expect(release).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects malformed slots and non-HTTPS download URLs", async () => {
|
||||
const request = vi.fn(async () => xml("iq", { type: "result" }, xml("slot", { xmlns: NS.httpUpload })));
|
||||
await expect(requestUploadSlot({
|
||||
xmpp: { iqCaller: { request } } as never,
|
||||
serviceJid: "upload.example.org",
|
||||
filename: "plot.png",
|
||||
size: 3,
|
||||
contentType: "image/png"
|
||||
})).rejects.toThrow(/invalid slot/);
|
||||
|
||||
const release = vi.fn(async () => undefined);
|
||||
fetchWithSsrFGuard.mockResolvedValueOnce({ response: new Response(null, { status: 201 }), release });
|
||||
await expect(uploadBuffer({
|
||||
slot: { putUrl: "https://upload.example.org/put", getUrl: "http://upload.example.org/file", headers: [] },
|
||||
buffer: Buffer.from("png"),
|
||||
contentType: "image/png"
|
||||
})).rejects.toThrow(/non-HTTPS download URL/);
|
||||
expect(release).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("releases guarded responses when upload fails", async () => {
|
||||
const release = vi.fn(async () => undefined);
|
||||
fetchWithSsrFGuard.mockResolvedValueOnce({ response: new Response(null, { status: 401 }), release });
|
||||
await expect(uploadBuffer({
|
||||
slot: { putUrl: "https://upload.example.org/put", getUrl: "https://upload.example.org/file", headers: [] },
|
||||
buffer: Buffer.from("png"),
|
||||
contentType: "image/png"
|
||||
})).rejects.toThrow(/HTTP 401/);
|
||||
expect(release).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
|
||||
import pluginEntry from "../index.js";
|
||||
import { xmppPlugin } from "../src/channel.js";
|
||||
import { DEFAULT_TEXT_CHUNK_LIMIT } from "../src/constants.js";
|
||||
import { registerLiveTransport } from "../src/transport.js";
|
||||
|
||||
const configuredXmpp = {
|
||||
channels: {
|
||||
xmpp: {
|
||||
jid: "bot@example.org",
|
||||
password: "secret"
|
||||
}
|
||||
}
|
||||
} as unknown as OpenClawConfig;
|
||||
|
||||
describe("OpenClaw plugin contract", () => {
|
||||
it("registers one native direct-message channel", () => {
|
||||
expect(pluginEntry.id).toBe("xmpp");
|
||||
expect(pluginEntry.setChannelRuntime).toBeTypeOf("function");
|
||||
expect(xmppPlugin.id).toBe("xmpp");
|
||||
expect(xmppPlugin.capabilities.chatTypes).toEqual(["direct"]);
|
||||
expect(xmppPlugin.gateway?.startAccount).toBeTypeOf("function");
|
||||
expect(xmppPlugin.message?.send?.text).toBeTypeOf("function");
|
||||
expect(xmppPlugin.message?.send?.media).toBeTypeOf("function");
|
||||
expect(xmppPlugin.message?.receive?.defaultAckPolicy).toBe(
|
||||
"after_agent_dispatch"
|
||||
);
|
||||
expect(xmppPlugin.outbound?.chunker).toBeTypeOf("function");
|
||||
expect(xmppPlugin.outbound?.textChunkLimit).toBe(DEFAULT_TEXT_CHUNK_LIMIT);
|
||||
});
|
||||
|
||||
it("provides the chunker required by OpenClaw's message delivery path", () => {
|
||||
const chunker = xmppPlugin.outbound?.chunker;
|
||||
expect(chunker).toBeTypeOf("function");
|
||||
|
||||
const chunks = chunker?.("X".repeat(6_482), DEFAULT_TEXT_CHUNK_LIMIT);
|
||||
|
||||
expect(chunks?.map((chunk) => chunk.length)).toEqual([4_000, 2_482]);
|
||||
});
|
||||
|
||||
it("advertises structured message-tool sends for configured accounts", () => {
|
||||
expect(
|
||||
xmppPlugin.actions?.describeMessageTool({
|
||||
cfg: configuredXmpp,
|
||||
accountId: "default"
|
||||
})
|
||||
).toEqual({ actions: ["send"], capabilities: [] });
|
||||
expect(
|
||||
xmppPlugin.actions?.extractToolSend?.({
|
||||
args: {
|
||||
action: "send",
|
||||
to: "alice@example.org",
|
||||
accountId: "default"
|
||||
}
|
||||
})
|
||||
).toEqual({
|
||||
to: "alice@example.org",
|
||||
accountId: "default",
|
||||
threadId: undefined
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards structured media payloads to the native XMPP uploader", async () => {
|
||||
const readFile = vi.fn(async () => Buffer.from("image"));
|
||||
const sendMedia = vi.fn(async () => ({
|
||||
id: "xmpp-media-1",
|
||||
to: "alice@example.org",
|
||||
url: "https://upload.example.org/plot.png"
|
||||
}));
|
||||
const unregister = registerLiveTransport("default", {
|
||||
sendMedia
|
||||
} as never);
|
||||
|
||||
try {
|
||||
const result = await xmppPlugin.message?.send?.media?.({
|
||||
cfg: configuredXmpp,
|
||||
to: "alice@example.org",
|
||||
text: "Plot attached.",
|
||||
mediaUrl: "/tmp/plot.png",
|
||||
accountId: "default",
|
||||
mediaAccess: { readFile }
|
||||
} as never);
|
||||
|
||||
expect(sendMedia).toHaveBeenCalledWith({
|
||||
to: "alice@example.org",
|
||||
text: "Plot attached.",
|
||||
mediaUrl: "/tmp/plot.png",
|
||||
mediaReadFile: readFile
|
||||
});
|
||||
expect(result?.messageId).toBe("xmpp-media-1");
|
||||
} finally {
|
||||
unregister();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the public package free of installation-specific identifiers", async () => {
|
||||
const root = resolve(import.meta.dirname, "..");
|
||||
const files = [
|
||||
"README.md",
|
||||
"SECURITY.md",
|
||||
"CONTRIBUTING.md",
|
||||
"openclaw.plugin.json",
|
||||
"package.json",
|
||||
"package-lock.json"
|
||||
];
|
||||
const contents = (
|
||||
await Promise.all(
|
||||
files.map((file) => readFile(resolve(root, file), "utf8"))
|
||||
)
|
||||
).join("\n");
|
||||
expect(contents).not.toMatch(
|
||||
/(?:private\.example|\/home\/local-owner|Local Owner|legacy-xmpp-bridge|Local Agent)/i
|
||||
);
|
||||
});
|
||||
|
||||
it("ships a manifest aligned with the runtime id and channel", async () => {
|
||||
const manifest = JSON.parse(
|
||||
await readFile(
|
||||
resolve(import.meta.dirname, "../openclaw.plugin.json"),
|
||||
"utf8"
|
||||
)
|
||||
) as {
|
||||
id: string;
|
||||
channels: string[];
|
||||
activation: { onStartup: boolean };
|
||||
channelConfigs: {
|
||||
xmpp: {
|
||||
schema: {
|
||||
properties: Record<string, unknown>;
|
||||
definitions: {
|
||||
account: { properties: Record<string, unknown> };
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
expect(manifest.id).toBe("xmpp");
|
||||
expect(manifest.channels).toEqual(["xmpp"]);
|
||||
expect(manifest.activation.onStartup).toBe(false);
|
||||
const expectedTextChunkLimitSchema = {
|
||||
type: "integer",
|
||||
minimum: 1,
|
||||
maximum: 100000
|
||||
};
|
||||
expect(
|
||||
manifest.channelConfigs.xmpp.schema.properties.textChunkLimit
|
||||
).toEqual(expectedTextChunkLimitSchema);
|
||||
expect(
|
||||
manifest.channelConfigs.xmpp.schema.definitions.account.properties
|
||||
.textChunkLimit
|
||||
).toEqual(expectedTextChunkLimitSchema);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
|
||||
import { applyXmppSetupAccount, configureXmppInteractive } from "../src/setup.js";
|
||||
|
||||
function prompter(values: {
|
||||
texts: string[];
|
||||
policy?: "pairing" | "allowlist" | "disabled";
|
||||
healthProbe?: boolean;
|
||||
}) {
|
||||
const texts = [...values.texts];
|
||||
return {
|
||||
note: vi.fn(async () => undefined),
|
||||
text: vi.fn(async () => texts.shift() ?? ""),
|
||||
select: vi.fn(async () => values.policy ?? "pairing"),
|
||||
confirm: vi.fn(async () => values.healthProbe ?? true),
|
||||
progress: vi.fn(() => ({ update: vi.fn(), stop: vi.fn() })),
|
||||
intro: vi.fn(async () => undefined),
|
||||
outro: vi.fn(async () => undefined),
|
||||
plain: vi.fn(async () => undefined),
|
||||
multiselect: vi.fn(async () => [])
|
||||
};
|
||||
}
|
||||
|
||||
describe("secure XMPP onboarding", () => {
|
||||
it("adds named accounts without replacing an existing account", () => {
|
||||
const first = applyXmppSetupAccount({
|
||||
cfg: {} as OpenClawConfig,
|
||||
accountId: "personal",
|
||||
account: { jid: "me@example.org", password: { source: "env", provider: "default", id: "XMPP_PERSONAL_PASSWORD" } }
|
||||
});
|
||||
const second = applyXmppSetupAccount({
|
||||
cfg: first,
|
||||
accountId: "work",
|
||||
account: { jid: "me@example.net", password: { source: "env", provider: "default", id: "XMPP_WORK_PASSWORD" } }
|
||||
}) as never as { channels: { xmpp: { accounts: Record<string, unknown> } } };
|
||||
expect(Object.keys(second.channels.xmpp.accounts)).toEqual(["personal", "work"]);
|
||||
});
|
||||
|
||||
it("records only a SecretRef, normalizes allowlists, and validates before returning", async () => {
|
||||
const prompts = prompter({
|
||||
texts: [
|
||||
"work",
|
||||
"Bot@Example.ORG/device",
|
||||
"openclaw",
|
||||
"wss://xmpp.example.org/ws",
|
||||
"XMPP_WORK_PASSWORD",
|
||||
"Alice@Example.ORG/phone, bob@example.org"
|
||||
],
|
||||
policy: "allowlist"
|
||||
});
|
||||
const validate = vi.fn(async () => undefined);
|
||||
const result = await configureXmppInteractive(
|
||||
{ cfg: {} as OpenClawConfig, prompter: prompts as never, shouldPromptAccountIds: true },
|
||||
validate
|
||||
);
|
||||
const account = (result.cfg as never as { channels: { xmpp: { accounts: Record<string, Record<string, unknown>> } } }).channels.xmpp.accounts.work;
|
||||
expect(account).toMatchObject({
|
||||
jid: "bot@example.org",
|
||||
websocketUrl: "wss://xmpp.example.org/ws",
|
||||
dmPolicy: "allowlist",
|
||||
allowFrom: ["alice@example.org", "bob@example.org"],
|
||||
password: { source: "env", provider: "default", id: "XMPP_WORK_PASSWORD" }
|
||||
});
|
||||
expect(JSON.stringify(result.cfg)).not.toContain("secret");
|
||||
expect(validate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("returns no configuration when connection validation fails", async () => {
|
||||
const prompts = prompter({
|
||||
texts: ["bot@example.org", "openclaw", "", "XMPP_PASSWORD"],
|
||||
policy: "disabled",
|
||||
healthProbe: false
|
||||
});
|
||||
await expect(configureXmppInteractive(
|
||||
{ cfg: {} as OpenClawConfig, prompter: prompts as never, shouldPromptAccountIds: false },
|
||||
async () => { throw new Error("TLS certificate rejected"); }
|
||||
)).rejects.toThrow(/TLS certificate rejected/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import { xml } from "@xmpp/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { NS } from "../src/constants.js";
|
||||
import {
|
||||
buildChatState,
|
||||
buildReceipt,
|
||||
buildTextMessage,
|
||||
parseInboundMessage
|
||||
} from "../src/stanzas.js";
|
||||
|
||||
describe("XMPP stanza mapping", () => {
|
||||
it("parses direct messages with stanza ids, delays, and receipt requests", () => {
|
||||
const stanza = xml(
|
||||
"message",
|
||||
{
|
||||
from: "alice@example.org/phone",
|
||||
to: "bot@example.org/openclaw",
|
||||
type: "chat",
|
||||
id: "client-id"
|
||||
},
|
||||
xml("body", {}, " hello "),
|
||||
xml("stanza-id", {
|
||||
xmlns: NS.sid,
|
||||
by: "example.org",
|
||||
id: "server-id"
|
||||
}),
|
||||
xml("delay", {
|
||||
xmlns: NS.delay,
|
||||
stamp: "2026-07-30T10:00:00Z"
|
||||
}),
|
||||
xml("request", { xmlns: NS.receipts })
|
||||
);
|
||||
expect(parseInboundMessage(stanza, "bot@example.org")).toEqual({
|
||||
id: "server-id",
|
||||
from: "alice@example.org/phone",
|
||||
fromBare: "alice@example.org",
|
||||
to: "bot@example.org/openclaw",
|
||||
body: "hello",
|
||||
timestamp: Date.parse("2026-07-30T10:00:00Z"),
|
||||
receiptRequested: true,
|
||||
receiptId: "client-id"
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the sender id separate from the server stanza id for receipts", () => {
|
||||
const parsed = parseInboundMessage(
|
||||
xml(
|
||||
"message",
|
||||
{ from: "alice@example.org/phone", id: "sender-id" },
|
||||
xml("body", {}, "hello"),
|
||||
xml("stanza-id", { xmlns: NS.sid, by: "example.org", id: "archive-id" }),
|
||||
xml("request", { xmlns: NS.receipts })
|
||||
),
|
||||
"bot@example.org"
|
||||
);
|
||||
|
||||
expect(parsed?.id).toBe("archive-id");
|
||||
expect(parsed?.receiptId).toBe("sender-id");
|
||||
});
|
||||
|
||||
it("ignores groupchat, empty, receipt-only, and self messages", () => {
|
||||
expect(
|
||||
parseInboundMessage(
|
||||
xml(
|
||||
"message",
|
||||
{ type: "groupchat", from: "room@example.org/alice" },
|
||||
xml("body", {}, "hello")
|
||||
),
|
||||
"bot@example.org"
|
||||
)
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
parseInboundMessage(
|
||||
xml(
|
||||
"message",
|
||||
{ type: "chat", from: "alice@example.org" },
|
||||
xml("received", { xmlns: NS.receipts, id: "x" })
|
||||
),
|
||||
"bot@example.org"
|
||||
)
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
parseInboundMessage(
|
||||
xml(
|
||||
"message",
|
||||
{ type: "chat", from: "bot@example.org/other" },
|
||||
xml("body", {}, "loop")
|
||||
),
|
||||
"bot@example.org"
|
||||
)
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("builds origin ids, receipt requests, OOB URLs, receipts, and chat states", () => {
|
||||
const sent = buildTextMessage({
|
||||
to: "alice@example.org",
|
||||
text: "photo",
|
||||
id: "out-1",
|
||||
requestReceipt: true,
|
||||
oobUrl: "https://upload.example.org/photo.png"
|
||||
});
|
||||
expect(sent.id).toBe("out-1");
|
||||
expect(sent.stanza.getChildText("body")).toBe("photo");
|
||||
expect(sent.stanza.getChild("origin-id", NS.sid)?.attrs.id).toBe("out-1");
|
||||
expect(sent.stanza.getChild("request", NS.receipts)).toBeTruthy();
|
||||
expect(
|
||||
sent.stanza
|
||||
.getChild("x", NS.oob)
|
||||
?.getChildText("url")
|
||||
).toBe("https://upload.example.org/photo.png");
|
||||
|
||||
expect(
|
||||
buildReceipt({ to: "alice@example.org", id: "in-1" })
|
||||
.getChild("received", NS.receipts)
|
||||
?.attrs.id
|
||||
).toBe("in-1");
|
||||
expect(
|
||||
buildChatState({ to: "alice@example.org", state: "composing" }).getChild(
|
||||
"composing",
|
||||
NS.chatStates
|
||||
)
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("builds XEP-0447 inline file sharing with XEP-0446 metadata", () => {
|
||||
const url = "https://upload.example.org/plot.png";
|
||||
const sent = buildTextMessage({
|
||||
to: "alice@example.org",
|
||||
text: url,
|
||||
id: "media-1",
|
||||
oobUrl: url,
|
||||
sharedFile: {
|
||||
url,
|
||||
name: "plot.png",
|
||||
mediaType: "image/png",
|
||||
size: 1234,
|
||||
sha256: "c2hhMjU2"
|
||||
}
|
||||
});
|
||||
const sharing = sent.stanza.getChild("file-sharing", NS.sfs);
|
||||
expect(sharing?.attrs.disposition).toBe("inline");
|
||||
const file = sharing?.getChild("file", NS.fileMetadata);
|
||||
expect(file?.getChildText("media-type")).toBe("image/png");
|
||||
expect(file?.getChildText("name")).toBe("plot.png");
|
||||
expect(file?.getChildText("size")).toBe("1234");
|
||||
const hash = file?.getChild("hash", NS.hashes);
|
||||
expect(hash?.attrs.algo).toBe("sha-256");
|
||||
expect(hash?.text()).toBe("c2hhMjU2");
|
||||
expect(
|
||||
sharing
|
||||
?.getChild("sources", NS.sfs)
|
||||
?.getChild("url-data", NS.urlData)?.attrs.target
|
||||
).toBe(url);
|
||||
expect(
|
||||
sent.stanza.getChild("fallback", NS.fallback)?.attrs.for
|
||||
).toBe(NS.sfs);
|
||||
});
|
||||
|
||||
it("preserves a real caption without marking it as fallback text", () => {
|
||||
const sent = buildTextMessage({
|
||||
to: "alice@example.org",
|
||||
text: "Here is the plot.",
|
||||
sharedFile: {
|
||||
url: "https://upload.example.org/plot.png",
|
||||
name: "plot.png",
|
||||
mediaType: "image/png"
|
||||
}
|
||||
});
|
||||
expect(sent.stanza.getChildText("body")).toBe("Here is the plot.");
|
||||
expect(sent.stanza.getChild("file-sharing", NS.sfs)).toBeTruthy();
|
||||
expect(sent.stanza.getChild("fallback", NS.fallback)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mock = vi.hoisted(() => ({ clients: [] as any[], request: vi.fn() }));
|
||||
|
||||
vi.mock("@xmpp/client", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@xmpp/client")>();
|
||||
return {
|
||||
...actual,
|
||||
client: () => {
|
||||
const entity = new EventEmitter() as any;
|
||||
entity.status = "online";
|
||||
entity.isSecure = () => true;
|
||||
entity.send = vi.fn(async () => undefined);
|
||||
entity.start = vi.fn(async () => entity.emit("online", { toString: () => "bot@example.org/openclaw" }));
|
||||
entity.stop = vi.fn(async () => { entity.status = "offline"; entity.emit("offline"); });
|
||||
entity.iqCaller = { request: mock.request };
|
||||
entity.reconnect = Object.assign(new EventEmitter(), { delay: 1000 });
|
||||
entity.streamManagement = Object.assign(new EventEmitter(), { enabled: true });
|
||||
mock.clients.push(entity);
|
||||
return entity;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
import type { XmppConnectionConfig } from "../src/config.js";
|
||||
import { XmppTransport } from "../src/transport.js";
|
||||
|
||||
const config: XmppConnectionConfig = {
|
||||
accountId: "default", jid: "bot@example.org", domain: "example.org", username: "bot",
|
||||
password: "test-only", resource: "openclaw", service: "example.org", dmPolicy: "disabled",
|
||||
allowFrom: [], sendReceipts: true, requestReceipts: true, sendChatStates: true,
|
||||
mediaMaxBytes: 1024, healthProbe: true, healthProbeIntervalMs: 300_000,
|
||||
healthProbeTimeoutMs: 5_000, reconnectDelayMs: 2_000
|
||||
};
|
||||
|
||||
function create() {
|
||||
const statuses: any[] = [];
|
||||
const transport = new XmppTransport(config, {
|
||||
onMessage: async () => undefined,
|
||||
onStatus: (status) => statuses.push(status),
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
|
||||
});
|
||||
return { transport, statuses, client: mock.clients.at(-1)! };
|
||||
}
|
||||
|
||||
describe("XMPP health and recovery lifecycle", () => {
|
||||
beforeEach(() => { vi.useFakeTimers(); mock.request.mockReset(); mock.clients.length = 0; });
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("correlates one bounded probe and records success", async () => {
|
||||
mock.request.mockResolvedValueOnce({});
|
||||
const { transport, client } = create();
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await expect(transport.probe()).resolves.toBe("success");
|
||||
expect(mock.request).toHaveBeenCalledOnce();
|
||||
expect(transport.status.lastProbeSuccessAt).toBeTypeOf("number");
|
||||
expect(client.reconnect.delay).toBe(2_000);
|
||||
controller.abort();
|
||||
await running;
|
||||
});
|
||||
|
||||
it("allows only one outstanding probe and records a timeout", async () => {
|
||||
mock.request.mockReturnValue(new Promise(() => undefined));
|
||||
const { transport } = create();
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
const first = transport.probe();
|
||||
expect(await transport.probe()).toBeUndefined();
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await expect(first).resolves.toBe("timeout");
|
||||
expect(mock.request).toHaveBeenCalledOnce();
|
||||
controller.abort();
|
||||
await running;
|
||||
});
|
||||
|
||||
it("surfaces reconnect and XEP-0198 resume state and removes listeners on stop", async () => {
|
||||
const { transport, client } = create();
|
||||
const controller = new AbortController();
|
||||
const running = transport.run(controller.signal);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
client.reconnect.emit("reconnecting");
|
||||
expect(transport.status).toMatchObject({ phase: "reconnecting", reconnectAttempts: 1 });
|
||||
client.streamManagement.emit("resumed");
|
||||
expect(transport.status).toMatchObject({ phase: "online", streamManagement: "resumed" });
|
||||
controller.abort();
|
||||
await running;
|
||||
expect(client.reconnect.listenerCount("reconnecting")).toBe(0);
|
||||
expect(client.streamManagement.listenerCount("resumed")).toBe(0);
|
||||
expect(transport.status.phase).toBe("stopped");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { XmppConnectionConfig } from "../src/config.js";
|
||||
import { XmppTransport } from "../src/transport.js";
|
||||
|
||||
const config: XmppConnectionConfig = {
|
||||
accountId: "default",
|
||||
jid: "bot@example.org",
|
||||
domain: "example.org",
|
||||
username: "bot",
|
||||
password: "secret",
|
||||
resource: "openclaw",
|
||||
service: "xmpp://example.org:5222",
|
||||
dmPolicy: "allowlist",
|
||||
allowFrom: ["alice@example.org"],
|
||||
sendReceipts: true,
|
||||
requestReceipts: true,
|
||||
sendChatStates: true,
|
||||
mediaMaxBytes: 10 * 1024 * 1024,
|
||||
healthProbe: false,
|
||||
healthProbeIntervalMs: 300_000,
|
||||
healthProbeTimeoutMs: 15_000,
|
||||
reconnectDelayMs: 1_000
|
||||
};
|
||||
|
||||
function transport() {
|
||||
return new XmppTransport(config, {
|
||||
onMessage: vi.fn(async () => undefined),
|
||||
onStatus: vi.fn(),
|
||||
log: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn()
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
describe("XMPP inline media delivery", () => {
|
||||
it("refuses local media unless OpenClaw provides its validated reader", async () => {
|
||||
const xmpp = transport();
|
||||
await expect(xmpp.sendMedia({
|
||||
to: "alice@example.org",
|
||||
text: "",
|
||||
mediaUrl: "/outside/unchecked.png"
|
||||
})).rejects.toThrow(/validated media reader/);
|
||||
});
|
||||
it("sends a caption first and a URL-only fallback media stanza second", async () => {
|
||||
const xmpp = transport();
|
||||
const sendText = vi
|
||||
.spyOn(xmpp, "sendText")
|
||||
.mockImplementation(async (to, _text, options = {}) => ({
|
||||
id: options.sharedFile ? "media-1" : "caption-1",
|
||||
to,
|
||||
...(options.oobUrl ? { url: options.oobUrl } : {})
|
||||
}));
|
||||
const url = "https://upload.example.org/plot.png";
|
||||
|
||||
const sent = await xmpp.sendMedia({
|
||||
to: "alice@example.org",
|
||||
text: "Here is the plot.",
|
||||
mediaUrl: url,
|
||||
contentType: "image/png"
|
||||
});
|
||||
|
||||
expect(sendText).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"alice@example.org",
|
||||
"Here is the plot."
|
||||
);
|
||||
expect(sendText).toHaveBeenNthCalledWith(2, "alice@example.org", url, {
|
||||
oobUrl: url,
|
||||
sharedFile: {
|
||||
url,
|
||||
name: "plot.png",
|
||||
mediaType: "image/png"
|
||||
}
|
||||
});
|
||||
expect(sent).toMatchObject({ id: "media-1", url });
|
||||
});
|
||||
|
||||
it("does not duplicate an empty or URL-valued caption", async () => {
|
||||
for (const caption of ["", "https://upload.example.org/plot.png"]) {
|
||||
const xmpp = transport();
|
||||
const sendText = vi
|
||||
.spyOn(xmpp, "sendText")
|
||||
.mockResolvedValue({ id: "media-1", to: "alice@example.org" });
|
||||
const url = "https://upload.example.org/plot.png";
|
||||
|
||||
await xmpp.sendMedia({
|
||||
to: "alice@example.org",
|
||||
text: caption,
|
||||
mediaUrl: url,
|
||||
contentType: "image/png"
|
||||
});
|
||||
|
||||
expect(sendText).toHaveBeenCalledOnce();
|
||||
expect(sendText).toHaveBeenCalledWith(
|
||||
"alice@example.org",
|
||||
url,
|
||||
expect.objectContaining({ oobUrl: url })
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTlsRequiredCredentials } from "../src/transport.js";
|
||||
|
||||
describe("XMPP transport authentication", () => {
|
||||
it("does not offer credentials before TLS is active", async () => {
|
||||
const authenticate = vi.fn();
|
||||
const credentials = createTlsRequiredCredentials({
|
||||
username: "bot",
|
||||
password: "secret"
|
||||
});
|
||||
await expect(
|
||||
credentials(
|
||||
authenticate,
|
||||
["PLAIN"],
|
||||
null,
|
||||
{ isSecure: () => false } as never
|
||||
)
|
||||
).rejects.toThrow(/TLS is required before authentication/);
|
||||
expect(authenticate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("authenticates after TLS and excludes ANONYMOUS", async () => {
|
||||
const authenticate = vi.fn(async () => undefined);
|
||||
const credentials = createTlsRequiredCredentials({
|
||||
username: "bot",
|
||||
password: "secret"
|
||||
});
|
||||
await credentials(
|
||||
authenticate,
|
||||
["ANONYMOUS", "SCRAM-SHA-1", "PLAIN"],
|
||||
null,
|
||||
{ isSecure: () => true } as never
|
||||
);
|
||||
expect(authenticate).toHaveBeenCalledOnce();
|
||||
expect(authenticate).toHaveBeenCalledWith(
|
||||
{
|
||||
username: "bot",
|
||||
password: "secret"
|
||||
},
|
||||
"SCRAM-SHA-1",
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": ".",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"exclude": [
|
||||
"test/**",
|
||||
"dist/**"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"types": [
|
||||
"node",
|
||||
"vitest/globals"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"index.ts",
|
||||
"setup-entry.ts",
|
||||
"src/**/*.ts",
|
||||
"test/**/*.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
coverage: {
|
||||
enabled: false
|
||||
},
|
||||
include: ["test/**/*.test.ts"],
|
||||
testTimeout: 10_000
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user