first commit

This commit is contained in:
Myk
2025-07-31 23:47:20 +03:00
commit 2186b278a0
5149 changed files with 537218 additions and 0 deletions

View File

@@ -0,0 +1,89 @@
# Matrix-Rust-SDK Node.js Bindings
## 0.3.0-beta.1 - 2024-11-18
- Update matrix-rust-sdk dependency.
- The SignedCurve25519 algorithm is no longer supported.
## 0.2.0-beta.1 - 2024-06-11
- Support Node.JS 22, drop support for 16, 19.
- Update matrix-rust-sdk dependency.
- `RoomId` no longer has a `localpart` property.
## 0.1.0-beta.12 - 2024-02-01
- Add prebuilt library support for 390x. [#32](https://github.com/matrix-org/matrix-rust-sdk-crypto-nodejs/pull/32)
## 0.1.0-beta.11 - 2023-09-05
- Add `export_room_keys_for_session`. [#26](https://github.com/matrix-org/matrix-rust-sdk-crypto-nodejs/pull/26)
## 0.1.0-beta.10 - 2023-08-11
- Return `ToDeviceRequest` objects from `OlmMachine.share_room_key`. [#15](https://github.com/matrix-org/matrix-rust-sdk-crypto-nodejs/pull/15)
- Added documentation for the release process. [#21](https://github.com/matrix-org/matrix-rust-sdk-crypto-nodejs/pull/21)
## 0.1.0-beta.9 - 2023-08-02
- Update URL & tag in pre-built download script. [#13](https://github.com/matrix-org/matrix-rust-sdk-crypto-nodejs/pull/13)
## 0.1.0-beta.8 - 2023-08-01
- Don't skip downloading the native library when installing from npm.
## 0.1.0-beta.7 - 2023-08-01
- Expose bindings for secure key backup. [#7](https://github.com/matrix-org/matrix-rust-sdk-crypto-nodejs/pull/7)
## 0.1.0-beta.6 - 2023-04-26
- Update supported Node.js versions. [#1822](https://github.com/matrix-org/matrix-rust-sdk/pull/1822)
- Various bug fixes and improvements.
## 0.1.0-beta.5 - 2023-04-24
- Build Node bindings against Ubuntu 20.04. [#1819](https://github.com/matrix-org/matrix-rust-sdk/pull/1819)
- Various bug fixes and improvements.
## 0.1.0-beta.4 - 2023-04-14
- Support a new sqlite storage type. [#1521](https://github.com/matrix-org/matrix-rust-sdk/pull/1521)
- Various bug fixes and improvements.
## 0.1.0-beta.3 - 2022-11-03
- [Fix the pre-built downloading script for Node.js 19.](https://github.com/matrix-org/matrix-rust-sdk/pull/1164)
## 0.1.0-beta.2 - 2022-09-28
## 0.1.0-beta.1 - 2022-07-14
- Fixing broken download link, [#842](https://github.com/matrix-org/matrix-rust-sdk/issues/842)
## 0.1.0-beta.0 - 2022-07-12
Welcome to the first release of `matrix-sdk-crypto-nodejs`. This is a
Node.js binding for the Rust `matrix-sdk-crypto` library. This is a
no-network-IO implementation of a state machine, named `OlmMachine`,
that handles E2EE (End-to-End Encryption) for Matrix clients.
The goal of this binding is _not_ to cover the entirety of the
`matrix-sdk-crypto` API, but only what's required to build Matrix bots
or Matrix bridges (i.e. to connect different networks together via the
Matrix protocol).
This project replaces and deprecates a previous project, with the same
name and same goals, inside [the `matrix-rust-sdk-bindings`
repository](https://github.com/matrix-org/matrix-rust-sdk-bindings),
with the NPM package name `@turt2live/matrix-sdk-crypto-nodejs`. The
The new official package name is
`@matrix-org/matrix-sdk-crypto-nodejs`.
Note: All bindings are now part of [the `matrix-rust-sdk`
repository](https://github.com/matrix-org/matrix-rust-sdk) (see the
`bindings/` root directory).
[A documentation is available inside the new
`matrix-sdk-crypto-nodejs`
project](https://github.com/matrix-org/matrix-rust-sdk/tree/0bde5ccf38f8cda3865297a2d12ddcdaf4b80ca7/bindings/matrix-sdk-crypto-nodejs).

View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,225 @@
# `matrix-sdk-crypto-nodejs`
Welcome to the [Node.js] binding for the Rust [`matrix-sdk-crypto`]
library! This binding is part of the [`matrix-rust-sdk`] project,
which is a library implementation of a [Matrix] client-server.
`matrix-sdk-crypto-nodejs` is a no-network-IO implementation of a
state machine, named `OlmMachine`, that handles E2EE ([End-to-End
Encryption](https://en.wikipedia.org/wiki/End-to-end_encryption)) for
[Matrix] clients.
## Usage
Just add the latest release to your `package.json`:
```sh
$ npm install --save @matrix-org/matrix-sdk-crypto-nodejs
```
When installing, NPM will download the corresponding prebuilt Rust library for your current host system. The following are supported:
<table>
<thead>
<tr>
<th>Platform</th>
<th>Architecture</th>
<th>Triple</th>
<th>Prebuilt available</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="6">Linux</td>
<td rowspan="2"><code>aarch</code></td>
<td><code>aarch64-unknown-linux-gnu</code></td>
<td></td>
</tr>
<tr>
<td><code>arm-unknown-linux-gnueabihf</code></td>
<td></td>
</tr>
<tr>
<td rowspan="3"><code>amd</code></td>
<td><code>x86_64-unknown-linux-gnu</code></td>
<td></td>
</tr>
<tr>
<td><code>x86_64-unknown-linux-musl</code></td>
<td></td>
</tr>
<tr>
<td><code>i686-unknown-linux-gnu</code></td>
<td></td>
</tr>
<tr>
<td rowspan="1"><code>s390x</code></td>
<td><code>s390x-unknown-linux-gnu</code></td>
<td></td>
</tr>
<tr>
<td rowspan="2">macOS</td>
<td><code>aarch</code></td>
<td><code>arch64-apple-darwin</code></td>
<td></td>
</tr>
<tr>
<td><code>amd</code></td>
<td><code>x86_64-apple-darwin</code></td>
<td></td>
</tr>
<tr>
<td rowspan="3">Windows</td>
<td><code>aarch</code></td>
<td><code>aarch64-pc-windows-msvc</code></td>
<td></td>
</tr>
<tr>
<td rowspan="2"><code>amd</code></td>
<td><code>x86_64-pc-windows-msvc</code></td>
<td></td>
</tr>
<tr>
<td><code>i686-pc-windows-msvc</code></td>
<td></td>
</tr>
</tbody>
</table>
## Development
This Node.js binding is written in [Rust]. To build this binding, you
need to install the Rust compiler, see [the Install Rust
Page](https://www.rust-lang.org/tools/install). Then, the workflow is
pretty classical by using [npm], see [the Downloading and installing
Node.js and npm
Page](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
The binding is compatible with, and tested against, the Node.js
versions that are in “current”, “active” or “maintenance” states,
according to [the Node.js Releases
Page](https://nodejs.org/en/about/releases/), _and_ which are
compatible with [NAPI v6 (Node.js
API)](https://nodejs.org/api/n-api.html#node-api-version-matrix). It
means that this binding will work with the following versions:
18.0.0, 20.0.0 and 22.0.0.
Once the Rust compiler, Node.js and npm are installed, you can run the
following commands:
```sh
$ npm install --ignore-scripts
$ npm run build
$ npm run test
```
An `index.js`, `index.d.ts` and a `*.node` files should be
generated. At the same level of those files, you can edit a file and
try this:
```javascript
const { OlmMachine } = require("./index.js");
// Let's see what we can do.
```
The `OlmMachine` state machine works in a push/pull manner:
- You push state changes and events retrieved from a Matrix homeserver
`/sync` response, into the state machine,
- You pull requests that you will need to send back to the homeserver
out of the state machine.
```javascript
const { OlmMachine, UserId, DeviceId, RoomId, DeviceLists } = require("./index.js");
async function main() {
// Define a user ID.
const alice = new UserId("@alice:example.org");
// Define a device ID.
const device = new DeviceId("DEVICEID");
// Let's create the `OlmMachine` state machine.
const machine = await OlmMachine.initialize(alice, device);
// Let's pretend we have received changes and events from a
// `/sync` endpoint of a Matrix homeserver, …
const toDeviceEvents = "[]"; // JSON-encoded list of events
const changedDevices = new DeviceLists();
const oneTimeKeyCounts = {};
const unusedFallbackKeys = [];
// … and push them into the state machine.
const decryptedToDevice = await machine.receiveSyncChanges(
toDeviceEvents,
changedDevices,
oneTimeKeyCounts,
unusedFallbackKeys,
);
// Now, let's pull requests that we need to send out to the Matrix
// homeserver.
const outgoingRequests = await machine.outgoingRequests();
// To complete the workflow, send the requests here out and call
// `machine.markRequestAsSent`.
}
main();
```
### With tracing (experimental)
If you want to enable [tracing](https://tracing.rs), i.e. to get the
logs, you should re-compile the extension with the `tracing` feature
turned on:
```sh
$ npm run build -- --features tracing
```
Now, you can use the `MATRIX_LOG` environment variable to tweak the log filtering, such as:
```sh
$ MATRIX_LOG=debug npm run test
```
See
[`tracing-subscriber`](https://tracing.rs/tracing_subscriber/index.html)
to learn more about the `RUST_LOG`/`MATRIX_LOG` environment variable.
#### Using tracing in dependent projects
To enable tracing in client applications that import these bindings, here's how to do it in
a local development environment:
- In this directory, run `npm link` to make your local build of the bindings available to
other Node projects on your system
- In your client app's source directory, run `npm link @matrix-org/matrix-sdk-crypto-nodejs`
to make it use your trace-enabled local build of the bindings
- In your client app's source code, add a call to `initTracing` near startup time
- Run your app with the `MATRIX_LOG` environment variable set to the desired log level
Either `npm link` command may be substituted with `yarn link`.
## Documentation
[The documentation can be found
online](https://matrix-org.github.io/matrix-rust-sdk-crypto-nodejs/).
To generate the documentation locally, please run the following
command:
```sh
$ npm run doc
```
The documentation is generated in the `./docs` directory.
[Node.js]: https://nodejs.org/
[`matrix-sdk-crypto`]: https://github.com/matrix-org/matrix-rust-sdk/tree/main/crates/matrix-sdk-crypto
[`matrix-rust-sdk`]: https://github.com/matrix-org/matrix-rust-sdk
[Matrix]: https://matrix.org/
[Rust]: https://www.rust-lang.org/
[npm]: https://www.npmjs.com/

View File

@@ -0,0 +1,15 @@
# Steps for releasing `matrix-rust-sdk-crypto-nodejs`
1. Create a new branch, named `release-v<version>`.
2. Update `CHANGELOG.md` and `git add` ready for commit on the next step.
3. Run `yarn version` to bump the version number, commit, and create a tag.
4. Push the branch, but not yet the tag.
5. Create a PR to approve the changes.
6. Once approved:
1. Update the git tag to the new head of the branch, if necessary.
2. Push the git tag (`git push origin tag v<version>`). Doing so triggers
the github actions workflow which builds and publishes to npm, and
creates a draft GH release.
3. Merge the PR. (Prefer a genuine merge rather than a squash so that
the tagged commit is included in the history.)
7. Update the release on github and publish.

View File

@@ -0,0 +1,128 @@
const { HttpsProxyAgent } = require("https-proxy-agent");
const { DownloaderHelper } = require("node-downloader-helper");
const { version } = require("./package.json");
// Get the platform and architecture based on environment variables,
// falling back to the current platform and architecture
const platform = process.env.npm_config_target_platform || process.env.npm_config_platform || process.platform;
const arch = process.env.npm_config_target_arch || process.env.npm_config_arch || process.arch;
const DOWNLOADS_BASE_URL = "https://github.com/matrix-org/matrix-rust-sdk-crypto-nodejs/releases/download";
const CURRENT_VERSION = `v${version}`;
const byteHelper = function (value) {
if (value === 0) {
return "0 b";
}
const units = ["b", "kB", "MB", "GB", "TB"];
const number = Math.floor(Math.log(value) / Math.log(1024));
return (value / Math.pow(1024, Math.floor(number))).toFixed(1) + " " + units[number];
};
function download_lib(libname) {
let startTime = new Date();
const url = `${DOWNLOADS_BASE_URL}/${CURRENT_VERSION}/${libname}`;
console.info(`Downloading lib ${libname} from ${url}`);
const dl = new DownloaderHelper(url, __dirname, {
override: true,
});
const proxy = process.env.https_proxy ?? process.env.HTTPS_PROXY;
if (proxy) {
const proxyAgent = new HttpsProxyAgent(proxy);
dl.updateOptions({
httpsRequestOptions: { agent: proxyAgent },
});
}
dl.on("end", () => console.info("Download Completed"));
dl.on("error", (err) => console.info("Download Failed", err));
dl.on("progress", (stats) => {
const progress = stats.progress.toFixed(1);
const speed = byteHelper(stats.speed);
const downloaded = byteHelper(stats.downloaded);
const total = byteHelper(stats.total);
// print every one second (`progress.throttled` can be used instead)
const currentTime = new Date();
const elaspsedTime = currentTime - startTime;
if (elaspsedTime > 1000) {
startTime = currentTime;
console.info(`${speed}/s - ${progress}% [${downloaded}/${total}]`);
}
});
dl.start().catch((err) => console.error(err));
}
function isMusl() {
// For Node 10
if (!process.report || typeof process.report.getReport !== "function") {
try {
return readFileSync("/usr/bin/ldd", "utf8").includes("musl");
} catch (e) {
return true;
}
} else {
const { glibcVersionRuntime } = process.report.getReport().header;
return !glibcVersionRuntime;
}
}
switch (platform) {
case "win32":
switch (arch) {
case "x64":
download_lib("matrix-sdk-crypto.win32-x64-msvc.node");
break;
case "ia32":
download_lib("matrix-sdk-crypto.win32-ia32-msvc.node");
break;
case "arm64":
download_lib("matrix-sdk-crypto.win32-arm64-msvc.node");
break;
default:
throw new Error(`Unsupported architecture on Windows: ${arch}`);
}
break;
case "darwin":
switch (arch) {
case "x64":
download_lib("matrix-sdk-crypto.darwin-x64.node");
break;
case "arm64":
download_lib("matrix-sdk-crypto.darwin-arm64.node");
break;
default:
throw new Error(`Unsupported architecture on macOS: ${arch}`);
}
break;
case "linux":
switch (arch) {
case "x64":
if (isMusl()) {
download_lib("matrix-sdk-crypto.linux-x64-musl.node");
} else {
download_lib("matrix-sdk-crypto.linux-x64-gnu.node");
}
break;
case "arm64":
if (isMusl()) {
throw new Error("Linux for arm64 musl isn't support at the moment");
} else {
download_lib("matrix-sdk-crypto.linux-arm64-gnu.node");
}
break;
case "arm":
download_lib("matrix-sdk-crypto.linux-arm-gnueabihf.node");
break;
case "s390x":
download_lib("matrix-sdk-crypto.linux-s390x-gnu.node");
break;
default:
throw new Error(`Unsupported architecture on Linux: ${arch}`);
}
break;
default:
throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`);
}

View File

@@ -0,0 +1,991 @@
/* tslint:disable */
/* eslint-disable */
/* auto-generated by NAPI-RS */
/**
* An encryption algorithm to be used to encrypt messages sent to a
* room.
*/
export const enum EncryptionAlgorithm {
/** Olm version 1 using Curve25519, AES-256, and SHA-256. */
OlmV1Curve25519AesSha2 = 0,
/** Megolm version 1 using AES-256 and SHA-256. */
MegolmV1AesSha2 = 1
}
/**
* Take a look at [`matrix_sdk_common::deserialized_responses::ShieldState`]
* for more info.
*/
export const enum ShieldColor {
Red = 0,
Grey = 1,
None = 2
}
/**
* Take a look at
* [`matrix_sdk_common::deserialized_responses::ShieldStateCode`]
* for more info.
*/
export const enum ShieldStateCode {
/** Not enough information available to check the authenticity. */
AuthenticityNotGuaranteed = 0,
/** The sending device isn't yet known by the Client. */
UnknownDevice = 1,
/** The sending device hasn't been verified by the sender. */
UnsignedDevice = 2,
/** The sender hasn't been verified by the Client's user. */
UnverifiedIdentity = 3,
/** An unencrypted event in an encrypted room. */
SentInClear = 4,
/** The sender was previously verified but changed their identity. */
VerificationViolation = 5,
None = 6
}
/** Who can see a room's history. */
export const enum HistoryVisibility {
/**
* Previous events are accessible to newly joined members from
* the point they were invited onwards.
*
* Events stop being accessible when the member's state changes
* to something other than *invite* or *join*.
*/
Invited = 0,
/**
* Previous events are accessible to newly joined members from
* the point they joined the room onwards.
*
* Events stop being accessible when the member's state changes
* to something other than *join*.
*/
Joined = 1,
/**
* Previous events are always accessible to newly joined members.
*
* All events in the room are accessible, even those sent when
* the member was not a part of the room.
*/
Shared = 2,
/**
* All events while this is the `HistoryVisibility` value may be
* shared by any participating homeserver with anyone, regardless
* of whether they have ever joined the room.
*/
WorldReadable = 3
}
/** The basic key algorithm names in the specification. */
export const enum DeviceKeyAlgorithmName {
/** The Ed25519 signature algorithm. */
Ed25519 = 0,
/** The Curve25519 ECDH algorithm. */
Curve25519 = 1,
/** An unknown device key algorithm. */
Unknown = 2
}
/** Represents the type of store an `OlmMachine` can use. */
export const enum StoreType {
/** Use `matrix-sdk-sqlite`. */
Sqlite = 0
}
/** Represent the type of a request. */
export const enum RequestType {
/** Represents a `KeysUploadRequest`. */
KeysUpload = 0,
/** Represents a `KeysQueryRequest`. */
KeysQuery = 1,
/** Represents a `KeysClaimRequest`. */
KeysClaim = 2,
/** Represents a `ToDeviceRequest`. */
ToDevice = 3,
/** Represents a `SignatureUploadRequest`. */
SignatureUpload = 4,
/** Represents a `RoomMessageRequest`. */
RoomMessage = 5,
/** Represents a `KeysBackupRequest`. */
KeysBackup = 6
}
/** The result of a signature check. */
export const enum SignatureState {
/** The signature is missing. */
Missing = 0,
/** The signature is invalid. */
Invalid = 1,
/**
* The signature is valid but the device or user identity that created the
* signature is not trusted.
*/
ValidButNotTrusted = 2,
/**
* The signature is valid and the device or user identity that created the
* signature is trusted.
*/
ValidAndTrusted = 3
}
/** Get the versions of the Rust libraries we are using. */
export declare function getVersions(): Versions
/**
* A type to encrypt and to decrypt anything that can fit in an
* `Uint8Array`, usually big buffer.
*/
export declare class Attachment {
/**
* Encrypt the content of the `Uint8Array`.
*
* It produces an `EncryptedAttachment`, which can be used to
* retrieve the media encryption information, or the encrypted
* data.
*/
static encrypt(array: Uint8Array): EncryptedAttachment
/**
* Decrypt an `EncryptedAttachment`.
*
* The encrypted attachment can be created manually, or from the
* `encrypt` method.
*
* **Warning**: The encrypted attachment can be used only
* **once**! The encrypted data will still be present, but the
* media encryption info (which contain secrets) will be
* destroyed. It is still possible to get a JSON-encoded backup
* by calling `EncryptedAttachment.mediaEncryptionInfo`.
*/
static decrypt(attachment: EncryptedAttachment): Uint8Array
}
/** An encrypted attachment, usually created from `Attachment.encrypt`. */
export declare class EncryptedAttachment {
/** The actual encrypted data. */
encryptedData: Uint8Array
/**
* Create a new encrypted attachment manually.
*
* It needs encrypted data, stored in an `Uint8Array`, and a
* [media encryption
* information](https://docs.rs/matrix-sdk-crypto/latest/matrix_sdk_crypto/struct.MediaEncryptionInfo.html),
* as a JSON-encoded string.
*
* The media encryption information aren't stored as a string:
* they are parsed, validated and fully deserialized.
*
* See [the specification to learn
* more](https://spec.matrix.org/unstable/client-server-api/#extensions-to-mroommessage-msgtypes).
*/
constructor(encryptedData: Uint8Array, mediaEncryptionInfo: string)
/**
* Return the media encryption info as a JSON-encoded string. The
* structure is fully valid.
*
* If the media encryption info have been consumed already, it
* will return `null`.
*/
get mediaEncryptionInfo(): string | null
/**
* Check whether the media encryption info has been consumed by
* `Attachment.decrypt` already.
*/
get hasMediaEncryptionInfoBeenConsumed(): boolean
}
/** The private part of the backup key, the one used for recovery. */
export declare class BackupDecryptionKey {
/** Create a new random [`BackupDecryptionKey`]. */
static createRandomKey(): BackupDecryptionKey
/** Try to create a [`BackupDecryptionKey`] from a base 64 encoded string. */
static fromBase64(key: string): BackupDecryptionKey
/** Convert the recovery key to a base 64 encoded string. */
toBase64(): string
/** Get the public part of the backup key. */
get megolmV1PublicKey(): MegolmV1BackupKey
/**
* Try to decrypt a message that was encrypted using the public part of the
* backup key.
*/
decryptV1(ephemeralKey: string, mac: string, ciphertext: string): string
}
/** The public part of the backup key. */
export declare class MegolmV1BackupKey {
/** The actual base64 encoded public key. */
get publicKeyBase64(): string
/** Get the full name of the backup algorithm this backup key supports. */
get algorithm(): string
}
/** Struct holding the number of room keys we have. */
export declare class RoomKeyCounts {
/** The total number of room keys. */
total: number
/** The number of backed up room keys. */
backedUp: number
}
/** Stored versions of the backup keys. */
export declare class BackupKeys {
/** The key used to decrypt backed up room keys, encoded as base64 */
decryptionKeyBase64?: string
/** The version that we are using for backups. */
backupVersion?: string
}
/**
* Settings for an encrypted room.
*
* This determines the algorithm and rotation periods of a group
* session.
*/
export declare class EncryptionSettings {
/** The encryption algorithm that should be used in the room. */
algorithm: EncryptionAlgorithm
/**
* How long the session should be used before changing it,
* expressed in microseconds.
*/
rotationPeriod: bigint
/** How many messages should be sent before changing the session. */
rotationPeriodMessages: bigint
/**
* The history visibility of the room when the session was
* created.
*/
historyVisibility: HistoryVisibility
/**
* Should untrusted devices receive the room key, or should they be
* excluded from the conversation.
*/
onlyAllowTrustedDevices: boolean
/**
* Should keys be shared with a verified user with an unverified device
* or when a verified user has replaced their identity. Otherwise
* keys are shared with unsigned devices as normal.
*/
errorOnVerifiedUserProblem: boolean
/** Create a new `EncryptionSettings` with default values. */
constructor()
}
/**
* Take a look at [`matrix_sdk_common::deserialized_responses::ShieldState`]
* for more info.
*/
export declare class ShieldState {
color: ShieldColor
code: ShieldStateCode
message?: string
}
/**
* A Matrix [user ID].
*
* [user ID]: https://spec.matrix.org/v1.2/appendices/#user-identifiers
*/
export declare class UserId {
/** Parse/validate and create a new `UserId`. */
constructor(id: string)
/** Returns the user's localpart. */
get localpart(): string
/** Returns the server name of the user ID. */
get serverName(): ServerName
/**
* Whether this user ID is a historical one.
*
* A historical user ID is one that doesn't conform to the latest
* specification of the user ID grammar but is still accepted
* because it was previously allowed.
*/
isHistorical(): boolean
/** Return the user ID as a string. */
toString(): string
}
/**
* A Matrix device ID.
*
* Device identifiers in Matrix are completely opaque character
* sequences. This type is provided simply for its semantic value.
*/
export declare class DeviceId {
/** Create a new `DeviceId`. */
constructor(id: string)
/** Return the device ID as a string. */
toString(): string
}
/**
* A Matrix device key ID.
*
* A key algorithm and a device ID, combined with a :.
*/
export declare class DeviceKeyId {
/** Parse/validate and create a new `DeviceKeyId`. */
constructor(id: string)
/** Returns key algorithm of the device key ID. */
get algorithm(): DeviceKeyAlgorithm
/** Returns device ID of the device key ID. */
get deviceId(): DeviceId
/** Return the device key ID as a string. */
toString(): string
}
/** The basic key algorithms in the specification. */
export declare class DeviceKeyAlgorithm {
/**
* Read the device key algorithm's name. If the name is
* `Unknown`, one may be interested by the `to_string` method to
* read the original name.
*/
get name(): DeviceKeyAlgorithmName
/** Return the device key algorithm as a string. */
toString(): string
}
/**
* A Matrix [room ID].
*
* [room ID]: https://spec.matrix.org/v1.2/appendices/#room-ids-and-event-ids
*/
export declare class RoomId {
/** Parse/validate and create a new `RoomId`. */
constructor(id: string)
/** Return the room ID as a string. */
toString(): string
/** Returns the server name of the room ID. */
get serverName(): ServerName
}
/**
* A Matrix-spec compliant [server name].
*
* It consists of a host and an optional port (separated by a colon if
* present).
*
* [server name]: https://spec.matrix.org/v1.2/appendices/#server-name
*/
export declare class ServerName {
/** Parse/validate and create a new `ServerName`. */
constructor(name: string)
/**
* Returns the host of the server name.
*
* That is: Return the part of the server before `:<port>` or the
* full server name if there is no port.
*/
get host(): string
/** Returns the port of the server name if any. */
get port(): number | null
/**
* Returns true if and only if the server name is an IPv4 or IPv6
* address.
*/
isIpLiteral(): boolean
}
/**
* State machine implementation of the Olm/Megolm encryption protocol
* used for Matrix end to end encryption.
*/
export declare class OlmMachine {
/**
* Create a new `OlmMachine` asynchronously.
*
* The persistence of the encryption keys and all the inner
* objects are controlled by the `store_path` argument.
*
* # Arguments
*
* * `user_id`, the unique ID of the user that owns this machine.
* * `device_id`, the unique id of the device that owns this machine.
* * `store_path`, the path to a directory where the state of the machine
* should be persisted; if not set, the created machine will keep the
* encryption keys only in memory, and once the object is dropped, the
* keys will be lost.
* * `store_passphrase`, the passphrase that should be used to encrypt the
* data at rest in the store. **Warning**, if no passphrase is given, the
* store and all its data will remain unencrypted. This argument is
* ignored if `store_path` is not set.
*/
static initialize(userId: UserId, deviceId: DeviceId, storePath?: string | undefined | null, storePassphrase?: string | undefined | null, storeType?: StoreType | undefined | null): Promise<OlmMachine>
/**
* It's not possible to construct an `OlmMachine` with its
* constructor because building an `OlmMachine` is
* asynchronous. Please use the `finalize` method.
*/
constructor()
/** The unique user ID that owns this `OlmMachine` instance. */
get userId(): UserId
/** The unique device ID that identifies this `OlmMachine`. */
get deviceId(): DeviceId
/** Get the public parts of our Olm identity keys. */
get identityKeys(): IdentityKeys
/**
* Handle a to-device and one-time key counts from a sync response.
*
* This will decrypt and handle to-device events returning the
* decrypted versions of them, as a JSON-encoded string.
*
* To decrypt an event from the room timeline, please use
* `decrypt_room_event`.
*
* # Arguments
*
* * `to_device_events`, the to-device events of the current sync response.
* * `changed_devices`, the list of devices that changed in this sync
* response.
* * `one_time_keys_count`, the current one-time keys counts that the sync
* response returned.
*/
receiveSyncChanges(toDeviceEvents: string, changedDevices: DeviceLists, oneTimeKeyCounts: Record<string, number>, unusedFallbackKeys: Array<string>): Promise<string>
/**
* Get the outgoing requests that need to be sent out.
*
* This returns a list of `KeysUploadRequest`, or
* `KeysQueryRequest`, or `KeysClaimRequest`, or
* `ToDeviceRequest`, or `SignatureUploadRequest`, or
* `RoomMessageRequest`. Those requests
* need to be sent out to the server and the responses need to be
* passed back to the state machine using `mark_request_as_sent`.
*/
outgoingRequests(): Promise<Array<KeysUploadRequest | KeysQueryRequest | KeysClaimRequest | ToDeviceRequest | SignatureUploadRequest | RoomMessageRequest>>
/**
* Mark the request with the given request ID as sent.
*
* # Arguments
*
* * `request_id`, the unique ID of the request that was sent out. This is
* needed to couple the response with the now sent out request.
* * `request_type`, the request type associated to the request ID.
* * `response`, the response that was received from the server after the
* outgoing request was sent out.
*/
markRequestAsSent(requestId: string, requestType: RequestType, response: string): Promise<boolean>
/**
* Get the a key claiming request for the user/device pairs that
* we are missing Olm sessions for.
*
* Returns `null` if no key claiming request needs to be sent
* out.
*
* Sessions need to be established between devices so group
* sessions for a room can be shared with them.
*
* This should be called every time a group session needs to be
* shared as well as between sync calls. After a sync some
* devices may request room keys without us having a valid Olm
* session with them, making it impossible to server the room key
* request, thus its necessary to check for missing sessions
* between sync as well.
*
* Note: Care should be taken that only one such request at a
* time is in flight, e.g. using a lock.
*
* The response of a successful key claiming requests needs to be
* passed to the `OlmMachine` with the `mark_request_as_sent`.
*
* # Arguments
*
* * `users`, the list of users that we should check if we lack a session
* with one of their devices. This can be an empty array or `null` when
* calling this method between sync requests.
*/
getMissingSessions(users?: Array<UserId> | undefined | null): Promise<KeysClaimRequest | null>
/**
* Update the tracked users.
*
* This will mark users that werent seen before for a key query
* and tracking.
*
* If the user is already known to the Olm machine it will not be
* considered for a key query.
*
* # Arguments
*
* * `users`, an array over user IDs that should be marked for tracking.
*/
updateTrackedUsers(users: Array<UserId>): Promise<void>
/**
* Get to-device requests to share a room key with users in a room.
*
* # Arguments
*
* * `room_id`, the room ID of the room where the room key will be used.
* * `users`, the list of users that should receive the room key.
* * `encryption_settings`, the encryption settings.
*/
shareRoomKey(roomId: RoomId, users: Array<UserId>, encryptionSettings: EncryptionSettings): Promise<Array<ToDeviceRequest>>
/**
* Encrypt a JSON-encoded content for the given room.
*
* # Arguments
*
* * `room_id`, the ID of the room for which the message should be
* encrypted.
* * `event_type`, the plaintext type of the event.
* * `content`, the JSON-encoded content of the message that should be
* encrypted.
*/
encryptRoomEvent(roomId: RoomId, eventType: string, content: string): Promise<string>
/**
* Decrypt an event from a room timeline.
*
* # Arguments
*
* * `event`, the event that should be decrypted.
* * `room_id`, the ID of the room where the event was sent to.
*/
decryptRoomEvent(event: string, roomId: RoomId): Promise<DecryptedRoomEvent>
/**
* Get the status of the private cross signing keys.
*
* This can be used to check which private cross signing keys we
* have stored locally.
*/
crossSigningStatus(): Promise<CrossSigningStatus>
/**
* Create a new cross signing identity and get the upload request
* to push the new public keys to the server.
*
* Warning: This will delete any existing cross signing keys that
* might exist on the server and thus will reset the trust
* between all the devices.
*
* Uploading these keys will require user interactive auth.
*
* # Arguments
*
* * `reset`, whether the method should create a new identity or use the
* existing one during the request. If set to true, the request will
* attempt to upload a new identity. If set to false, the request will
* attempt to upload the existing identity. Since the uploading process
* requires user interactive authentication, which involves sending out
* the same request multiple times, setting this argument to false
* enables you to reuse the same request.
*/
bootstrapCrossSigning(reset: boolean): Promise<void>
/**
* Sign the given message using our device key and if available
* cross-signing master key.
*/
sign(message: string): Promise<Signatures>
/**
* Store the backup decryption key in the crypto store.
*
* This is useful if the client wants to support gossiping of the backup
* key.
*/
saveBackupDecryptionKey(decryptionKey: BackupDecryptionKey, version: string): Promise<void>
/** Get the backup keys we have saved in our store. */
getBackupKeys(): Promise<BackupKeys>
/**
* Check if the given backup has been verified by us or by another of our
* devices that we trust.
*
* The `backup_info` should be a stringified JSON object with the following
* format:
*
* ```json
* {
* "algorithm": "m.megolm_backup.v1.curve25519-aes-sha2",
* "auth_data": {
* "public_key":"XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM",
* "signatures": {}
* }
* }
* ```
*/
verifyBackup(backupInfo: string): Promise<SignatureVerification>
/**
* Activate the given backup key to be used with the given backup version.
*
* **Warning**: The caller needs to make sure that the given `BackupKey` is
* trusted, otherwise we might be encrypting room keys that a malicious
* party could decrypt.
*
* The [`OlmMachine::verify_backup`] method can be used to do so.
*/
enableBackupV1(publicKeyBase64: string, version: string): Promise<void>
/**
* Are we able to encrypt room keys.
*
* This returns true if we have an active `BackupKey` and backup version
* registered with the state machine.
*/
isBackupEnabled(): Promise<boolean>
/**
* Disable and reset our backup state.
*
* This will remove any pending backup request, remove the backup key and
* reset the backup state of each room key we have.
*/
disableBackup(): Promise<void>
/**
* Encrypt a batch of room keys and return a request that needs to be sent
* out to backup the room keys.
*/
backupRoomKeys(): Promise<KeysBackupRequest | null>
/**
* Export room keys in unencrypted format for a given session_id.
* This currently exports a json blob.
*/
exportRoomKeysForSession(roomId: string, sessionId: string): Promise<string>
/** Get the number of backed up room keys and the total number of room keys. */
roomKeyCounts(): Promise<RoomKeyCounts>
/**
* Shut down the `OlmMachine`.
*
* The `OlmMachine` cannot be used after this method has been called,
* otherwise it will panic.
*
* All associated resources will be closed too, like the crypto storage
* connections.
*
* # Safety
*
* The caller is responsible to **not** use any objects that came from this
* `OlmMachine` after this `close` method has been called.
*/
close(): void
}
/**
* Struct representing the state of our private cross signing keys,
* it shows which private cross signing keys we have locally stored.
*/
export declare class CrossSigningStatus {
/** Do we have the master key. */
get hasMaster(): boolean
/**
* Do we have the self signing key, this one is necessary to sign
* our own devices.
*/
get hasSelfSigning(): boolean
/**
* Do we have the user signing key, this one is necessary to sign
* other users.
*/
get hasUserSigning(): boolean
}
/**
* Data for a request to the `/keys/upload` API endpoint
* ([specification]).
*
* Publishes end-to-end encryption keys for the device.
*
* [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysupload
*/
export declare class KeysUploadRequest {
/** The request ID. */
readonly id: string
/**
* A JSON-encoded string containing the rest of the payload: `device_keys`,
* `one_time_keys`, `fallback_keys`.
*
* It represents the body of the HTTP request.
*/
readonly body: string
/** Get its request type. */
get type(): RequestType
}
/**
* Data for a request to the `/keys/query` API endpoint
* ([specification]).
*
* Returns the current devices and identity keys for the given users.
*
* [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysquery
*/
export declare class KeysQueryRequest {
/** The request ID. */
readonly id: string
/**
* A JSON-encoded object of form:
*
* ```json
* {"timeout": …, "device_keys": …}
* ```
*/
readonly body: string
/** Get its request type. */
get type(): RequestType
}
/**
* Data for a request to the `/keys/claim` API endpoint
* ([specification]).
*
* Claims one-time keys that can be used to establish 1-to-1 E2EE
* sessions.
*
* [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keysclaim
*/
export declare class KeysClaimRequest {
/** The request ID. */
readonly id: string
/**
* A JSON-encoded object of form:
*
* ```json
* {"timeout": …, "one_time_keys": …}
* ```
*/
readonly body: string
/** Get its request type. */
get type(): RequestType
}
/**
* Data for a request to the `/sendToDevice` API endpoint
* ([specification]).
*
* Send an event to a single device or to a group of devices.
*
* [specification]: https://spec.matrix.org/unstable/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid
*/
export declare class ToDeviceRequest {
/** The request ID. */
readonly id: string
/** A string representing the type of event being sent to each devices. */
readonly eventType: string
/**
* A string representing a request identifier unique to the access token
* used to send the request.
*/
readonly txnId: string
/**
* A JSON-encoded string containing the rest of the payload: `messages`.
*
* It represents the body of the HTTP request.
*/
readonly body: string
/** Get its request type. */
get type(): RequestType
}
/**
* Data for a request to the `/keys/signatures/upload` API endpoint
* ([specification]).
*
* Publishes cross-signing signatures for the user.
*
* [specification]: https://spec.matrix.org/unstable/client-server-api/#post_matrixclientv3keyssignaturesupload
*/
export declare class SignatureUploadRequest {
/** The request ID. */
readonly id: string
/**
* A JSON-encoded string containing the rest of the payload: `signed_keys`.
*
* It represents the body of the HTTP request.
*/
readonly body: string
/** Get its request type. */
get type(): RequestType
}
/**
* A customized owned request type for sending out room messages
* ([specification]).
*
* [specification]: https://spec.matrix.org/unstable/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid
*/
export declare class RoomMessageRequest {
/** The request ID. */
readonly id: string
/** A string representing the room to send the event to. */
readonly roomId: string
/**
* A string representing the transaction ID for this event.
*
* Clients should generate an ID unique across requests with the same
* access token; it will be used by the server to ensure idempotency of
* requests.
*/
readonly txnId: string
/** A string representing the type of event to be sent. */
readonly eventType: string
/** A JSON-encoded string containing the message's content. */
readonly body: string
/** Get its request type. */
get type(): RequestType
}
/**
* A request that will back up a batch of room keys to the server
* ([specification]).
*
* [specification]: https://spec.matrix.org/unstable/client-server-api/#put_matrixclientv3room_keyskeys
*/
export declare class KeysBackupRequest {
/** The request ID. */
readonly id: string
/**
* A JSON-encoded string containing the rest of the payload: `rooms`.
*
* It represents the body of the HTTP request.
*/
readonly body: string
/** Get its request type. */
get type(): RequestType
}
/** A decrypted room event. */
export declare class DecryptedRoomEvent {
/** The JSON-encoded decrypted event. */
readonly event: string
/**
* The user ID of the event sender, note this is untrusted data
* unless the `verification_state` is as well trusted.
*/
get sender(): UserId | null
/**
* The device ID of the device that sent us the event, note this
* is untrusted data unless `verification_state` is as well
* trusted.
*/
get senderDevice(): DeviceId | null
/**
* The Curve25519 key of the device that created the megolm
* decryption key originally.
*/
get senderCurve25519Key(): string | null
/**
* The signing Ed25519 key that have created the megolm key that
* was used to decrypt this session.
*/
get senderClaimedEd25519Key(): string | null
/**
* Chain of Curve25519 keys through which this session was
* forwarded, via `m.forwarded_room_key` events.
*/
get forwardingCurve25519KeyChain(): Array<string>
/**
* The verification state of the device that sent us the event,
* note this is the state of the device at the time of
* decryption. It may change in the future if a device gets
* verified or deleted.
*/
shieldState(strict: boolean): ShieldState | null
}
/** Information on E2E device updates. */
export declare class DeviceLists {
/** Create an empty `DeviceLists`. */
constructor(changed?: Array<UserId> | undefined | null, left?: Array<UserId> | undefined | null)
/** Returns true if there are no device list updates. */
isEmpty(): boolean
/**
* List of users who have updated their device identity keys or
* who now share an encrypted room with the client since the
* previous sync.
*/
get changed(): Array<UserId>
/**
* List of users who no longer share encrypted rooms since the
* previous sync response.
*/
get left(): Array<UserId>
}
export declare class Signatures {
/** Creates a new, empty, signatures collection. */
constructor()
/**
* Add the given signature from the given signer and the given key ID to
* the collection.
*/
addSignature(signer: UserId, keyId: DeviceKeyId, signature: Ed25519Signature): MaybeSignature | null
/**
* Try to find an Ed25519 signature from the given signer with
* the given key ID.
*/
getSignature(signer: UserId, keyId: DeviceKeyId): Ed25519Signature | null
/** Get the map of signatures that belong to the given user. */
get(signer: UserId): Record<string, MaybeSignature> | null
/** Remove all the signatures we currently hold. */
clear(): void
/**
* Do we hold any signatures or is our collection completely
* empty.
*/
get isEmpty(): boolean
/** How many signatures do we currently hold. */
get count(): bigint
/** Get the json with all signatures */
asJSON(): string
}
/**
* Represents a potentially decoded signature (but not a validated
* one).
*/
export declare class Signature {
/** Get the Ed25519 signature, if this is one. */
get ed25519(): Ed25519Signature | null
/** Convert the signature to a base64 encoded string. */
toBase64(): string
}
/**
* Represents a signature that is either valid _or_ that could not be
* decoded.
*/
export declare class MaybeSignature {
/** Check whether the signature has been successfully decoded. */
get isValid(): boolean
/** Check whether the signature could not be successfully decoded. */
get isInvalid(): boolean
/** The signature, if successfully decoded. */
get signature(): Signature | null
/**
* The base64 encoded string that is claimed to contain a
* signature but could not be decoded, if any.
*/
get invalidSignatureSource(): string | null
}
/** The result of a signature verification of a signed JSON object. */
export declare class SignatureVerification {
/**
* Give the backup signature state from the current device.
* See SignatureState for values
*/
get deviceState(): SignatureState
/**
* Give the backup signature state from the current user identity.
* See SignatureState for values
*/
get userState(): SignatureState
/**
* Is the result considered to be trusted?
*
* This tells us if the result has a valid signature from any of the
* following:
*
* * Our own device
* * Our own user identity, provided the identity is trusted as well
* * Any of our own devices, provided the device is trusted as well
*/
trusted(): boolean
}
/** An Ed25519 public key, used to verify digital signatures. */
export declare class Ed25519PublicKey {
/** The number of bytes an Ed25519 public key has. */
get length(): number
/**
* Serialize an Ed25519 public key to an unpadded base64
* representation.
*/
toBase64(): string
}
/**
* An Ed25519 digital signature, can be used to verify the
* authenticity of a message.
*/
export declare class Ed25519Signature {
/**
* Try to create an Ed25519 signature from an unpadded base64
* representation.
*/
constructor(signature: string)
/**
* Serialize a Ed25519 signature to an unpadded base64
* representation.
*/
toBase64(): string
}
/** A Curve25519 public key. */
export declare class Curve25519PublicKey {
/** The number of bytes a Curve25519 public key has. */
get length(): number
/**
* Serialize an Curve25519 public key to an unpadded base64
* representation.
*/
toBase64(): string
}
/** Struct holding the two public identity keys of an account. */
export declare class IdentityKeys {
/** The Ed25519 public key, used for signing. */
get ed25519(): Ed25519PublicKey
/** The Curve25519 public key, used for establish shared secrets. */
get curve25519(): Curve25519PublicKey
}
/** Object containing the versions of the Rust libraries we are using. */
export declare class Versions {
/** The version of the vodozemac crate. */
vodozemac: string
/** The version of the matrix-sdk-crypto crate. */
matrixSdkCrypto: string
}

View File

@@ -0,0 +1,357 @@
/* tslint:disable */
/* eslint-disable */
/* prettier-ignore */
/* auto-generated by NAPI-RS */
const { existsSync, readFileSync } = require('fs')
const { join } = require('path')
const { platform, arch } = process
let nativeBinding = null
let localFileExisted = false
let loadError = null
function isMusl() {
// For Node 10
if (!process.report || typeof process.report.getReport !== 'function') {
try {
const lddPath = require('child_process').execSync('which ldd').toString().trim()
return readFileSync(lddPath, 'utf8').includes('musl')
} catch (e) {
return true
}
} else {
const { glibcVersionRuntime } = process.report.getReport().header
return !glibcVersionRuntime
}
}
switch (platform) {
case 'android':
switch (arch) {
case 'arm64':
localFileExisted = existsSync(join(__dirname, 'matrix-sdk-crypto.android-arm64.node'))
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.android-arm64.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-android-arm64')
}
} catch (e) {
loadError = e
}
break
case 'arm':
localFileExisted = existsSync(join(__dirname, 'matrix-sdk-crypto.android-arm-eabi.node'))
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.android-arm-eabi.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-android-arm-eabi')
}
} catch (e) {
loadError = e
}
break
default:
throw new Error(`Unsupported architecture on Android ${arch}`)
}
break
case 'win32':
switch (arch) {
case 'x64':
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.win32-x64-msvc.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.win32-x64-msvc.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-win32-x64-msvc')
}
} catch (e) {
loadError = e
}
break
case 'ia32':
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.win32-ia32-msvc.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.win32-ia32-msvc.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-win32-ia32-msvc')
}
} catch (e) {
loadError = e
}
break
case 'arm64':
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.win32-arm64-msvc.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.win32-arm64-msvc.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-win32-arm64-msvc')
}
} catch (e) {
loadError = e
}
break
default:
throw new Error(`Unsupported architecture on Windows: ${arch}`)
}
break
case 'darwin':
localFileExisted = existsSync(join(__dirname, 'matrix-sdk-crypto.darwin-universal.node'))
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.darwin-universal.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-darwin-universal')
}
break
} catch {}
switch (arch) {
case 'x64':
localFileExisted = existsSync(join(__dirname, 'matrix-sdk-crypto.darwin-x64.node'))
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.darwin-x64.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-darwin-x64')
}
} catch (e) {
loadError = e
}
break
case 'arm64':
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.darwin-arm64.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.darwin-arm64.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-darwin-arm64')
}
} catch (e) {
loadError = e
}
break
default:
throw new Error(`Unsupported architecture on macOS: ${arch}`)
}
break
case 'freebsd':
if (arch !== 'x64') {
throw new Error(`Unsupported architecture on FreeBSD: ${arch}`)
}
localFileExisted = existsSync(join(__dirname, 'matrix-sdk-crypto.freebsd-x64.node'))
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.freebsd-x64.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-freebsd-x64')
}
} catch (e) {
loadError = e
}
break
case 'linux':
switch (arch) {
case 'x64':
if (isMusl()) {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-x64-musl.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-x64-musl.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-x64-musl')
}
} catch (e) {
loadError = e
}
} else {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-x64-gnu.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-x64-gnu.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-x64-gnu')
}
} catch (e) {
loadError = e
}
}
break
case 'arm64':
if (isMusl()) {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-arm64-musl.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-arm64-musl.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-arm64-musl')
}
} catch (e) {
loadError = e
}
} else {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-arm64-gnu.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-arm64-gnu.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-arm64-gnu')
}
} catch (e) {
loadError = e
}
}
break
case 'arm':
if (isMusl()) {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-arm-musleabihf.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-arm-musleabihf.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-arm-musleabihf')
}
} catch (e) {
loadError = e
}
} else {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-arm-gnueabihf.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-arm-gnueabihf.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-arm-gnueabihf')
}
} catch (e) {
loadError = e
}
}
break
case 'riscv64':
if (isMusl()) {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-riscv64-musl.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-riscv64-musl.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-riscv64-musl')
}
} catch (e) {
loadError = e
}
} else {
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-riscv64-gnu.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-riscv64-gnu.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-riscv64-gnu')
}
} catch (e) {
loadError = e
}
}
break
case 's390x':
localFileExisted = existsSync(
join(__dirname, 'matrix-sdk-crypto.linux-s390x-gnu.node')
)
try {
if (localFileExisted) {
nativeBinding = require('./matrix-sdk-crypto.linux-s390x-gnu.node')
} else {
nativeBinding = require('@matrix-org/matrix-sdk-crypto-nodejs-linux-s390x-gnu')
}
} catch (e) {
loadError = e
}
break
default:
throw new Error(`Unsupported architecture on Linux: ${arch}`)
}
break
default:
throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`)
}
if (!nativeBinding) {
if (loadError) {
throw loadError
}
throw new Error(`Failed to load native binding`)
}
const { Attachment, EncryptedAttachment, BackupDecryptionKey, MegolmV1BackupKey, RoomKeyCounts, BackupKeys, EncryptionAlgorithm, EncryptionSettings, ShieldColor, ShieldStateCode, ShieldState, HistoryVisibility, UserId, DeviceId, DeviceKeyId, DeviceKeyAlgorithm, DeviceKeyAlgorithmName, RoomId, ServerName, StoreType, OlmMachine, CrossSigningStatus, KeysUploadRequest, KeysQueryRequest, KeysClaimRequest, ToDeviceRequest, SignatureUploadRequest, RoomMessageRequest, KeysBackupRequest, RequestType, DecryptedRoomEvent, DeviceLists, Signatures, Signature, MaybeSignature, SignatureVerification, SignatureState, Ed25519PublicKey, Ed25519Signature, Curve25519PublicKey, IdentityKeys, Versions, getVersions } = nativeBinding
module.exports.Attachment = Attachment
module.exports.EncryptedAttachment = EncryptedAttachment
module.exports.BackupDecryptionKey = BackupDecryptionKey
module.exports.MegolmV1BackupKey = MegolmV1BackupKey
module.exports.RoomKeyCounts = RoomKeyCounts
module.exports.BackupKeys = BackupKeys
module.exports.EncryptionAlgorithm = EncryptionAlgorithm
module.exports.EncryptionSettings = EncryptionSettings
module.exports.ShieldColor = ShieldColor
module.exports.ShieldStateCode = ShieldStateCode
module.exports.ShieldState = ShieldState
module.exports.HistoryVisibility = HistoryVisibility
module.exports.UserId = UserId
module.exports.DeviceId = DeviceId
module.exports.DeviceKeyId = DeviceKeyId
module.exports.DeviceKeyAlgorithm = DeviceKeyAlgorithm
module.exports.DeviceKeyAlgorithmName = DeviceKeyAlgorithmName
module.exports.RoomId = RoomId
module.exports.ServerName = ServerName
module.exports.StoreType = StoreType
module.exports.OlmMachine = OlmMachine
module.exports.CrossSigningStatus = CrossSigningStatus
module.exports.KeysUploadRequest = KeysUploadRequest
module.exports.KeysQueryRequest = KeysQueryRequest
module.exports.KeysClaimRequest = KeysClaimRequest
module.exports.ToDeviceRequest = ToDeviceRequest
module.exports.SignatureUploadRequest = SignatureUploadRequest
module.exports.RoomMessageRequest = RoomMessageRequest
module.exports.KeysBackupRequest = KeysBackupRequest
module.exports.RequestType = RequestType
module.exports.DecryptedRoomEvent = DecryptedRoomEvent
module.exports.DeviceLists = DeviceLists
module.exports.Signatures = Signatures
module.exports.Signature = Signature
module.exports.MaybeSignature = MaybeSignature
module.exports.SignatureVerification = SignatureVerification
module.exports.SignatureState = SignatureState
module.exports.Ed25519PublicKey = Ed25519PublicKey
module.exports.Ed25519Signature = Ed25519Signature
module.exports.Curve25519PublicKey = Curve25519PublicKey
module.exports.IdentityKeys = IdentityKeys
module.exports.Versions = Versions
module.exports.getVersions = getVersions

View File

@@ -0,0 +1,39 @@
{
"name": "@matrix-org/matrix-sdk-crypto-nodejs",
"version": "0.3.0-beta.1",
"main": "index.js",
"types": "index.d.ts",
"napi": {
"name": "matrix-sdk-crypto",
"triples": {
"additional": [
"aarch64-apple-darwin"
]
}
},
"license": "Apache-2.0",
"devDependencies": {
"@napi-rs/cli": "^2.18.4",
"jest": "^29.7.0",
"prettier": "^3.3.3",
"typedoc": "^0.26.11",
"typescript": "^5.6.3",
"yargs-parser": "~21.1.1"
},
"engines": {
"node": ">= 18"
},
"scripts": {
"lint": "prettier --check .",
"release-build": "napi build --platform --release --strip",
"build": "napi build --platform",
"postinstall": "node download-lib.js",
"test": "jest --verbose --testTimeout 10000",
"doc": "typedoc --tsconfig ."
},
"dependencies": {
"https-proxy-agent": "^7.0.5",
"node-downloader-helper": "^2.1.9"
},
"packageManager": "yarn@1.22.19+sha512.ff4579ab459bb25aa7c0ff75b62acebe576f6084b36aa842971cf250a5d8c6cd3bc9420b22ce63c7f93a0857bc6ef29291db39c3e7a23aab5adfd5a4dd6c5d71"
}