@syrix/client 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +75 -2
- package/examples/echo-bot.js +27 -0
- package/examples/group-admin-bot.js +75 -0
- package/index.d.ts +82 -0
- package/package.json +43 -4
- package/src/crypto.js +86 -0
- package/src/index.js +368 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,76 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @syrix/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official SYRIX CHAT library for bots and programs (Node.js 20+).
|
|
4
|
+
Your program becomes a **linked device** of a SYRIX account: it shows a **QR code** and a **pairing code**,
|
|
5
|
+
the phone scans or types it, then the program sends and receives **end-to-end encrypted** messages.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @syrix/client
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import { SyrixClient } from '@syrix/client';
|
|
13
|
+
|
|
14
|
+
const client = new SyrixClient({ server: 'https://YOUR-SYRIX-SERVER', name: 'Shop assistant' });
|
|
15
|
+
|
|
16
|
+
client.on('qr', (qr) => { /* printed in the terminal by default; render it yourself if you want */ });
|
|
17
|
+
client.on('pairing_code', (code) => console.log('Pairing code:', code)); // e.g. 7U4X-8EJE
|
|
18
|
+
client.on('waiting_approval', () => console.log('Tap Allow on the phone'));
|
|
19
|
+
client.on('ready', ({ user }) => console.log('Linked to @' + user.username));
|
|
20
|
+
client.on('message', async (m) => {
|
|
21
|
+
if (m.text === '!ping') await m.reply('pong');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
await client.connect(); // first run: QR + pairing code. Next runs: the saved session in authDir.
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Link it from the phone
|
|
28
|
+
|
|
29
|
+
1. Run the program. The terminal shows a QR code and an 8-character pairing code (valid 3 minutes, renewed automatically).
|
|
30
|
+
2. Phone: **Settings > Linked devices > Link a program or device**.
|
|
31
|
+
3. Scan the QR code, or open the **Code** tab and type the pairing code.
|
|
32
|
+
4. Check the name, then tap **Allow**. The program prints `ready`.
|
|
33
|
+
|
|
34
|
+
The session is saved in `authDir`: the next starts need no QR code.
|
|
35
|
+
|
|
36
|
+
## Options
|
|
37
|
+
|
|
38
|
+
| Option | Default | |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `server` | required | Your SYRIX address |
|
|
41
|
+
| `name` | `Bot` | Device name shown in Settings > Linked devices |
|
|
42
|
+
| `authDir` | `./.syrix-auth` | Session and encryption key. Keep it private: it is a signed-in device |
|
|
43
|
+
| `printQr` | `true` | Print the QR code and the pairing code in the terminal |
|
|
44
|
+
| `ignoreOwnMessages` | `false` | Skip what the account owner writes from the phone (`m.fromMe`). The bot's own replies are always skipped |
|
|
45
|
+
| `syncHistory` | `false` | Receive the chat history from the phone (`history` event) |
|
|
46
|
+
|
|
47
|
+
## API
|
|
48
|
+
|
|
49
|
+
Events: `qr`, `pairing_code`, `waiting_approval`, `ready`, `message`, `history`, `undecryptable`, `logged_out`, `error`.
|
|
50
|
+
|
|
51
|
+
Methods: `connect()`, `requestPairing()`, `sendText(conversationId, text, { replyTo })`, `chats()`, `chat(id)`, `downloadMedia(pointer)`, `logout()`, `close()`.
|
|
52
|
+
|
|
53
|
+
Groups (the linked account must be an admin): `promote(groupId, userId)`, `demote(groupId, userId)`, `kick(groupId, userId)`, `addMembers(groupId, userIds)`, `mute(groupId, userId, hours)`, `unmute(groupId, userId)`, `isAdmin(groupId, userId)`, `userByUsername(name)`, `leaveGroup(groupId)`.
|
|
54
|
+
|
|
55
|
+
A message also has `mentions` (user ids) and `quoted` (`{ id, senderId }` of the replied message), to know who a command is about.
|
|
56
|
+
|
|
57
|
+
`connect({ phoneCode })` still accepts the 6-digit code from *Settings > Linked devices > Show my connection code*.
|
|
58
|
+
|
|
59
|
+
A linked device has the same access as the web app. The owner sees it in Settings > Linked devices and can log it out at any time.
|
|
60
|
+
|
|
61
|
+
Examples: [`examples/echo-bot.js`](examples/echo-bot.js), [`examples/group-admin-bot.js`](examples/group-admin-bot.js) (`!promote`, `!demote`, `!kick`, `!mute`, `!unmute`, `!admins`).
|
|
62
|
+
|
|
63
|
+
## Publishing (maintainers)
|
|
64
|
+
|
|
65
|
+
The package is published on npm by GitHub Actions (`.github/workflows/publish-sdk.yml`):
|
|
66
|
+
|
|
67
|
+
1. Once: create the npm organisation `syrix` (npmjs.com › Add organization), make an **Automation** access
|
|
68
|
+
token, and save it in the GitHub repository as the secret `NPM_TOKEN` (Settings › Secrets and variables › Actions).
|
|
69
|
+
2. For each release: raise `version` in `package.json`, commit, then push a tag `sdk-v<version>` (or run the workflow by hand in GitHub: Actions › Publish @syrix/client › Run workflow):
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
git tag sdk-v1.1.0 && git push origin sdk-v1.1.0
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The workflow runs the tests, checks that the tag matches `package.json`, and publishes. By hand instead:
|
|
76
|
+
`cd sdk/syrix-client && npm test && npm publish` (an npm account that owns the `syrix` scope).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Example: a small shop assistant running as a linked device. Run:
|
|
2
|
+
// SYRIX_SERVER=https://your-syrix-server node examples/echo-bot.js
|
|
3
|
+
// The terminal shows a QR code and a pairing code. Phone: Settings > Linked devices > Link a program or device,
|
|
4
|
+
// scan or type the code, then tap Allow.
|
|
5
|
+
import { SyrixClient } from '../src/index.js';
|
|
6
|
+
|
|
7
|
+
const bot = new SyrixClient({
|
|
8
|
+
server: process.env.SYRIX_SERVER ?? 'http://localhost:5173',
|
|
9
|
+
name: process.env.SYRIX_BOT_NAME ?? 'Assistant',
|
|
10
|
+
authDir: process.env.SYRIX_AUTH_DIR ?? '.syrix-auth',
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
bot.on('ready', ({ user }) => console.log(`Linked to @${user.username}`));
|
|
14
|
+
bot.on('logged_out', (why) => { console.log(`Disconnected (${why}). Run again to link.`); process.exit(1); });
|
|
15
|
+
|
|
16
|
+
const HOURS = 'Ouvert du lundi au samedi, 8 h - 18 h.';
|
|
17
|
+
|
|
18
|
+
bot.on('message', async (m) => {
|
|
19
|
+
const text = m.text.trim().toLowerCase();
|
|
20
|
+
if (text === '!ping') return m.reply('pong 🏓');
|
|
21
|
+
if (text === '!heures' || text === '!hours') return m.reply(HOURS);
|
|
22
|
+
if (text === '!aide' || text === '!help') return m.reply('Commandes : !ping, !heures, !aide');
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
bot.on('waiting_approval', () => console.log('Tap Allow on the phone.'));
|
|
26
|
+
|
|
27
|
+
await bot.connect();
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Example: group admin commands. Run:
|
|
2
|
+
// SYRIX_SERVER=https://your-syrix-server node examples/group-admin-bot.js
|
|
3
|
+
// The linked account must be an admin of the group. Only group admins can use the commands.
|
|
4
|
+
// Target a member by replying to their message, by mentioning them, or with their @username:
|
|
5
|
+
// !promote @alice !demote @alice !kick @alice !mute @alice 24 !unmute @alice !admins
|
|
6
|
+
import { SyrixClient } from '../src/index.js';
|
|
7
|
+
|
|
8
|
+
const bot = new SyrixClient({
|
|
9
|
+
server: process.env.SYRIX_SERVER ?? 'http://localhost:5173',
|
|
10
|
+
name: process.env.SYRIX_BOT_NAME ?? 'Admin',
|
|
11
|
+
authDir: process.env.SYRIX_AUTH_DIR ?? '.syrix-auth',
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
bot.on('ready', ({ user }) => console.log(`Linked to @${user.username}`));
|
|
15
|
+
bot.on('logged_out', (why) => { console.log(`Disconnected (${why}). Run again to link.`); process.exit(1); });
|
|
16
|
+
bot.on('waiting_approval', () => console.log('Tap Allow on the phone.'));
|
|
17
|
+
|
|
18
|
+
// The member a command is about: replied-to message, then mention, then @username.
|
|
19
|
+
async function target(m, args) {
|
|
20
|
+
if (m.quoted?.senderId) return m.quoted.senderId;
|
|
21
|
+
if (m.mentions.length) return m.mentions[0];
|
|
22
|
+
const name = args.find((a) => a.startsWith('@'));
|
|
23
|
+
if (!name) return null;
|
|
24
|
+
return (await bot.userByUsername(name))?.id ?? null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const ERRORS = {
|
|
28
|
+
admin_required: "Le compte du bot n'est pas admin de ce groupe.",
|
|
29
|
+
forbidden: 'Action refusée.',
|
|
30
|
+
not_member: "Cette personne n'est pas dans le groupe.",
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const ACTIONS = {
|
|
34
|
+
promote: [(g, u) => bot.promote(g, u), 'est maintenant admin.'],
|
|
35
|
+
demote: [(g, u) => bot.demote(g, u), "n'est plus admin."],
|
|
36
|
+
kick: [(g, u) => bot.kick(g, u), 'a été retiré du groupe.'],
|
|
37
|
+
unmute: [(g, u) => bot.unmute(g, u), 'peut de nouveau écrire.'],
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
bot.on('message', async (m) => {
|
|
41
|
+
const [cmd, ...args] = m.text.trim().split(/\s+/);
|
|
42
|
+
if (!cmd?.startsWith('!')) return;
|
|
43
|
+
const name = cmd.slice(1).toLowerCase();
|
|
44
|
+
if (!['promote', 'demote', 'kick', 'mute', 'unmute', 'admins', 'help'].includes(name)) return;
|
|
45
|
+
|
|
46
|
+
const chat = await bot.chat(m.conversationId);
|
|
47
|
+
if (chat.type !== 'group') return m.reply('Cette commande marche seulement dans un groupe.');
|
|
48
|
+
if (name === 'help') return m.reply('Commandes : !promote, !demote, !kick, !mute [1|24|168], !unmute, !admins');
|
|
49
|
+
if (name === 'admins') return m.reply(`Admins : ${chat.participants.filter((p) => chat.admins.includes(p.id)).map((p) => '@' + p.username).join(', ')}`);
|
|
50
|
+
|
|
51
|
+
// Only admins may give orders to the bot.
|
|
52
|
+
if (!chat.admins.includes(m.senderId)) return m.reply('Réservé aux admins du groupe.');
|
|
53
|
+
|
|
54
|
+
const userId = await target(m, args);
|
|
55
|
+
if (!userId) return m.reply(`Indique la personne : réponds à son message ou écris !${name} @pseudo`);
|
|
56
|
+
if (userId === bot.user.id) return m.reply('Je ne peux pas faire ça sur moi-même.');
|
|
57
|
+
if (userId === chat.owner_id && name !== 'promote') return m.reply('Impossible : c\'est le créateur du groupe.');
|
|
58
|
+
const who = chat.participants.find((p) => p.id === userId);
|
|
59
|
+
const label = who ? '@' + who.username : 'Cette personne';
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
if (name === 'mute') {
|
|
63
|
+
const hours = [1, 24, 168].includes(Number(args.at(-1))) ? Number(args.at(-1)) : 1;
|
|
64
|
+
await bot.mute(m.conversationId, userId, hours);
|
|
65
|
+
return m.reply(`${label} ne peut plus écrire pendant ${hours} h.`);
|
|
66
|
+
}
|
|
67
|
+
const [run, done] = ACTIONS[name];
|
|
68
|
+
await run(m.conversationId, userId);
|
|
69
|
+
return m.reply(`${label} ${done}`);
|
|
70
|
+
} catch (err) {
|
|
71
|
+
return m.reply(ERRORS[err.code] ?? `Erreur : ${err.code ?? err.message}`);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
await bot.connect();
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
|
|
3
|
+
export interface SyrixClientOptions {
|
|
4
|
+
/** Address of the SYRIX server, e.g. https://your-syrix-server */
|
|
5
|
+
server: string;
|
|
6
|
+
/** Device name shown in Settings > Linked devices. Max 40 characters. */
|
|
7
|
+
name?: string;
|
|
8
|
+
/** Folder that keeps the session and the encryption key. Default: ./.syrix-auth (keep it private). */
|
|
9
|
+
authDir?: string;
|
|
10
|
+
/** Print the QR code, the pairing code and short instructions in the terminal. Default: true. */
|
|
11
|
+
printQr?: boolean;
|
|
12
|
+
/** Skip what the account owner writes from the phone (m.fromMe). The bot's own replies are always skipped. Default: false. */
|
|
13
|
+
ignoreOwnMessages?: boolean;
|
|
14
|
+
/** Receive the chat history from the phone after linking ('history' event). Default: false. */
|
|
15
|
+
syncHistory?: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface MediaPointer { url: string; key: string; iv: string; sha256: string; mime: string; size: number }
|
|
19
|
+
|
|
20
|
+
export interface SyrixMessage {
|
|
21
|
+
id: string;
|
|
22
|
+
conversationId: string;
|
|
23
|
+
senderId: string;
|
|
24
|
+
sender: { id: string; username: string; full_name: string; photo_url: string | null } | null;
|
|
25
|
+
fromMe: boolean;
|
|
26
|
+
text: string;
|
|
27
|
+
/** text, image, video, voice, audio, file, location, poll… */
|
|
28
|
+
type: string;
|
|
29
|
+
fileName: string | null;
|
|
30
|
+
media: MediaPointer | null;
|
|
31
|
+
/** User ids mentioned in a group message. */
|
|
32
|
+
mentions: string[];
|
|
33
|
+
/** The message this one replies to. */
|
|
34
|
+
quoted: { id: string; senderId: string } | null;
|
|
35
|
+
createdAt: string;
|
|
36
|
+
reply(text: string): Promise<unknown>;
|
|
37
|
+
/** Decrypted attachment bytes. */
|
|
38
|
+
download(): Promise<Buffer>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export declare class SyrixClient extends EventEmitter {
|
|
42
|
+
constructor(opts: SyrixClientOptions);
|
|
43
|
+
user: { id: string; username: string } | null;
|
|
44
|
+
/**
|
|
45
|
+
* Links as a device if needed, then listens. By default the program shows a QR code and a pairing code
|
|
46
|
+
* (events 'qr' and 'pairing_code', printed in the terminal); the phone scans or types it and taps Allow.
|
|
47
|
+
* `phoneCode`: the other direction, the 6-digit code shown by the phone.
|
|
48
|
+
*/
|
|
49
|
+
connect(opts?: { phoneCode?: string }): Promise<this>;
|
|
50
|
+
/** Shows a QR code and a pairing code until the phone links this program (renewed every 3 minutes). */
|
|
51
|
+
requestPairing(opts?: { attempts?: number }): Promise<{ linkId: string }>;
|
|
52
|
+
sendText(conversationId: string, text: string, opts?: { replyTo?: string | null }): Promise<unknown>;
|
|
53
|
+
chats(): Promise<Array<{ id: string; type: string; name?: string }>>;
|
|
54
|
+
downloadMedia(pointer: MediaPointer): Promise<Buffer>;
|
|
55
|
+
/** Chat details: type, name, owner_id, admins, participants, participant_ids… */
|
|
56
|
+
chat(conversationId: string): Promise<{ id: string; type: string; name?: string; owner_id: string | null; admins: string[]; participant_ids: string[]; participants: Array<{ id: string; username: string; full_name: string }> }>;
|
|
57
|
+
isAdmin(groupId: string, userId: string): Promise<boolean>;
|
|
58
|
+
userByUsername(username: string): Promise<{ id: string; username: string } | null>;
|
|
59
|
+
/** Group admin actions: the linked account must be an admin of the group. */
|
|
60
|
+
promote(groupId: string, userId: string): Promise<unknown>;
|
|
61
|
+
demote(groupId: string, userId: string): Promise<unknown>;
|
|
62
|
+
kick(groupId: string, userId: string): Promise<unknown>;
|
|
63
|
+
addMembers(groupId: string, userIds: string | string[]): Promise<unknown>;
|
|
64
|
+
/** hours: 1, 24, 168, or null (until lifted). */
|
|
65
|
+
mute(groupId: string, userId: string, hours?: 1 | 24 | 168 | null): Promise<unknown>;
|
|
66
|
+
unmute(groupId: string, userId: string): Promise<unknown>;
|
|
67
|
+
leaveGroup(groupId: string): Promise<unknown>;
|
|
68
|
+
/** Logs this device out of the account and deletes its local session and key. */
|
|
69
|
+
logout(): Promise<void>;
|
|
70
|
+
close(): Promise<void>;
|
|
71
|
+
|
|
72
|
+
on(event: 'message', fn: (m: SyrixMessage) => void): this;
|
|
73
|
+
on(event: 'qr', fn: (qr: string) => void): this;
|
|
74
|
+
on(event: 'pairing_code', fn: (code: string) => void): this;
|
|
75
|
+
on(event: 'waiting_approval', fn: () => void): this;
|
|
76
|
+
on(event: 'history', fn: (items: Array<[string, { t: string; mt?: string | null }]>) => void): this;
|
|
77
|
+
on(event: 'ready', fn: (info: { user: { id: string; username: string } }) => void): this;
|
|
78
|
+
on(event: 'logged_out', fn: (reason?: string) => void): this;
|
|
79
|
+
on(event: 'undecryptable', fn: (info: { id: string; conversationId: string }) => void): this;
|
|
80
|
+
on(event: 'error', fn: (err: Error) => void): this;
|
|
81
|
+
}
|
|
82
|
+
export default SyrixClient;
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syrix/client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Official SYRIX CHAT library: link a bot or a program to a SYRIX account with a QR code or a pairing code (like a linked device), with end-to-end encryption.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./index.d.ts",
|
|
11
|
+
"default": "./src/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"LICENSE",
|
|
16
|
+
"README.md",
|
|
17
|
+
"examples",
|
|
18
|
+
"index.d.ts",
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"test": "node --test test/*.test.js"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"qrcode": "^1.5.4",
|
|
29
|
+
"socket.io-client": "^4.8.1"
|
|
30
|
+
},
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"keywords": [
|
|
33
|
+
"syrix",
|
|
34
|
+
"syrix-chat",
|
|
35
|
+
"bot",
|
|
36
|
+
"messaging",
|
|
37
|
+
"e2ee",
|
|
38
|
+
"linked-device",
|
|
39
|
+
"qr",
|
|
40
|
+
"pairing-code"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/crypto.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// End-to-end encryption, byte-for-byte compatible with the SYRIX apps (src/lib/e2ee/crypto.ts).
|
|
2
|
+
// Envelope v1: AES-256-GCM content with a random key; for each recipient device the key is wrapped with
|
|
3
|
+
// AES-256-GCM under HKDF-SHA-256(ECDH-P256(sender device, recipient device)).
|
|
4
|
+
const subtle = globalThis.crypto.subtle;
|
|
5
|
+
const enc = new TextEncoder();
|
|
6
|
+
const dec = new TextDecoder();
|
|
7
|
+
const ECDH = { name: 'ECDH', namedCurve: 'P-256' };
|
|
8
|
+
|
|
9
|
+
export const toB64 = (buf) => Buffer.from(buf instanceof Uint8Array ? buf : new Uint8Array(buf)).toString('base64');
|
|
10
|
+
export const fromB64 = (b64) => new Uint8Array(Buffer.from(b64.replace(/-/g, '+').replace(/_/g, '/'), 'base64'));
|
|
11
|
+
export const randomBytes = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
|
|
12
|
+
export const randomId = () => toB64(randomBytes(16)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
13
|
+
|
|
14
|
+
/** Key pair for this bot's device. Exportable so it can be saved in the auth folder. */
|
|
15
|
+
export async function generateIdentity() {
|
|
16
|
+
const pair = await subtle.generateKey(ECDH, true, ['deriveBits']);
|
|
17
|
+
return {
|
|
18
|
+
privateJwk: await subtle.exportKey('jwk', pair.privateKey),
|
|
19
|
+
publicKey: toB64(await subtle.exportKey('raw', pair.publicKey)),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export const importPrivate = (jwk) => subtle.importKey('jwk', jwk, ECDH, false, ['deriveBits']);
|
|
23
|
+
const importPublic = (b64) => subtle.importKey('raw', fromB64(b64), ECDH, true, []);
|
|
24
|
+
|
|
25
|
+
const wrapKeyFor = async (myPrivate, theirPublic, salt, info) => {
|
|
26
|
+
const bits = await subtle.deriveBits({ name: 'ECDH', public: await importPublic(theirPublic) }, myPrivate, 256);
|
|
27
|
+
const hk = await subtle.importKey('raw', bits, 'HKDF', false, ['deriveKey']);
|
|
28
|
+
return subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt, info: enc.encode(info) }, hk, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
29
|
+
};
|
|
30
|
+
const contentAad = (conversationId, senderId, senderDevice) => enc.encode(`syrix-e2ee-v1|${conversationId}|${senderId}|${senderDevice}`);
|
|
31
|
+
const wrapInfo = (conversationId, senderDevice, recipientDevice) => `syrix-wrap-v1|${conversationId}|${senderDevice}|${recipientDevice}`;
|
|
32
|
+
|
|
33
|
+
export async function seal(content, ctx, recipients) {
|
|
34
|
+
const keyBytes = randomBytes(32);
|
|
35
|
+
const key = await subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt']);
|
|
36
|
+
const iv = randomBytes(12);
|
|
37
|
+
const salt = randomBytes(16);
|
|
38
|
+
const ct = await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: contentAad(ctx.conversationId, ctx.senderId, ctx.senderDevice) }, key, enc.encode(JSON.stringify(content)));
|
|
39
|
+
const keys = {};
|
|
40
|
+
await Promise.all(recipients.map(async (r) => {
|
|
41
|
+
const wk = await wrapKeyFor(ctx.privateKey, r.publicKey, salt, wrapInfo(ctx.conversationId, ctx.senderDevice, r.deviceId));
|
|
42
|
+
const wiv = randomBytes(12);
|
|
43
|
+
keys[r.deviceId] = { iv: toB64(wiv), wk: toB64(await subtle.encrypt({ name: 'AES-GCM', iv: wiv }, wk, keyBytes)) };
|
|
44
|
+
}));
|
|
45
|
+
keyBytes.fill(0);
|
|
46
|
+
return { v: 1, sd: ctx.senderDevice, salt: toB64(salt), iv: toB64(iv), ct: toB64(ct), keys };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function open(env, ctx) {
|
|
50
|
+
const mine = env.keys?.[ctx.myDevice];
|
|
51
|
+
if (!mine) throw new Error('no_key_for_device');
|
|
52
|
+
const wk = await wrapKeyFor(ctx.privateKey, ctx.senderPublicKey, fromB64(env.salt), wrapInfo(ctx.conversationId, env.sd, ctx.myDevice));
|
|
53
|
+
const keyBytes = new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: fromB64(mine.iv) }, wk, fromB64(mine.wk)));
|
|
54
|
+
const key = await subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['decrypt']);
|
|
55
|
+
keyBytes.fill(0);
|
|
56
|
+
const pt = await subtle.decrypt({ name: 'AES-GCM', iv: fromB64(env.iv), additionalData: contentAad(ctx.conversationId, ctx.senderId, env.sd) }, key, fromB64(env.ct));
|
|
57
|
+
return JSON.parse(dec.decode(pt));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Attachments are encrypted with their own key, carried inside the message. */
|
|
61
|
+
export async function decryptBlob(cipher, p) {
|
|
62
|
+
if (p.sha256) {
|
|
63
|
+
const digest = toB64(await subtle.digest('SHA-256', cipher));
|
|
64
|
+
if (digest !== p.sha256) throw new Error('attachment_tampered');
|
|
65
|
+
}
|
|
66
|
+
const key = await subtle.importKey('raw', fromB64(p.key), 'AES-GCM', false, ['decrypt']);
|
|
67
|
+
return Buffer.from(await subtle.decrypt({ name: 'AES-GCM', iv: fromB64(p.iv) }, key, cipher));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One-time key pair for receiving the history from the phone (same as the web app's QR code key). */
|
|
71
|
+
export async function ephemeralPair() {
|
|
72
|
+
const pair = await subtle.generateKey(ECDH, false, ['deriveBits']);
|
|
73
|
+
return { privateKey: pair.privateKey, publicKey: toB64(await subtle.exportKey('raw', pair.publicKey)) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Decrypts the history archive sent by the phone (ECDH + HKDF, AES-256-GCM, gzip), as src/lib/e2ee/history.ts. */
|
|
77
|
+
export async function openHistory(cipher, h, privateKey, linkId, userId) {
|
|
78
|
+
const pub = await importPublic(h.pub);
|
|
79
|
+
const bits = await subtle.deriveBits({ name: 'ECDH', public: pub }, privateKey, 256);
|
|
80
|
+
const hk = await subtle.importKey('raw', bits, 'HKDF', false, ['deriveKey']);
|
|
81
|
+
const key = await subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: fromB64(h.salt), info: enc.encode('syrix-link-history-v1') }, hk, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
|
|
82
|
+
const plain = new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: fromB64(h.iv), additionalData: enc.encode(`syrix-history-v1|link:${linkId}|${userId}`) }, key, cipher));
|
|
83
|
+
const body = plain.subarray(1);
|
|
84
|
+
const raw = plain[0] === 1 ? new Uint8Array(await new Response(new Blob([body]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()) : body;
|
|
85
|
+
return JSON.parse(dec.decode(raw));
|
|
86
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { io } from 'socket.io-client';
|
|
5
|
+
import { decryptBlob, ephemeralPair, generateIdentity, importPrivate, open, openHistory, randomId, seal } from './crypto.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* SYRIX CHAT client: links a program to a SYRIX account as a linked device, exactly like the web app.
|
|
9
|
+
*
|
|
10
|
+
* const client = new SyrixClient({ server: 'https://your-syrix-server', name: 'Assistant boutique' });
|
|
11
|
+
* client.on('message', async (m) => { if (!m.fromMe) await m.reply('Bonjour !'); });
|
|
12
|
+
* client.on('qr', (qr) => …); // or let the library print it in the terminal
|
|
13
|
+
* client.on('pairing_code', (code) => …); // ABCD-EFGH, to type on the phone
|
|
14
|
+
* await client.connect(); // phone: Settings > Linked devices > Link a program or device > scan / type the code
|
|
15
|
+
*
|
|
16
|
+
* The device has its own end-to-end encryption key. Its session and key are kept in `authDir` (keep it private).
|
|
17
|
+
*/
|
|
18
|
+
export class SyrixClient extends EventEmitter {
|
|
19
|
+
constructor(opts = {}) {
|
|
20
|
+
super();
|
|
21
|
+
if (!opts.server) throw new Error('server is required, e.g. https://your-syrix-server');
|
|
22
|
+
this.server = opts.server.replace(/\/+$/, '');
|
|
23
|
+
this.name = (opts.name || 'Bot').slice(0, 40);
|
|
24
|
+
this.authDir = opts.authDir || path.resolve('.syrix-auth');
|
|
25
|
+
this.printQr = opts.printQr !== false;
|
|
26
|
+
// Like Baileys: what the account owner writes from the phone reaches the bot too (m.fromMe = true), so
|
|
27
|
+
// they can test commands in any chat. The bot's own replies are always skipped (sent by this device).
|
|
28
|
+
this.ignoreOwnMessages = opts.ignoreOwnMessages === true;
|
|
29
|
+
this.syncHistory = opts.syncHistory === true;
|
|
30
|
+
this.identity = null;
|
|
31
|
+
this.session = null;
|
|
32
|
+
this.user = null;
|
|
33
|
+
this.socket = null;
|
|
34
|
+
this.peerKeys = new Map();
|
|
35
|
+
this.privateKey = null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// ---------- storage ----------
|
|
39
|
+
file(name) { return path.join(this.authDir, name); }
|
|
40
|
+
async readJson(name) {
|
|
41
|
+
try { return JSON.parse(await readFile(this.file(name), 'utf8')); } catch { return null; }
|
|
42
|
+
}
|
|
43
|
+
async writeJson(name, value) {
|
|
44
|
+
await mkdir(this.authDir, { recursive: true, mode: 0o700 });
|
|
45
|
+
await writeFile(this.file(name), JSON.stringify(value, null, 1), { mode: 0o600 });
|
|
46
|
+
await chmod(this.file(name), 0o600).catch(() => undefined);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ---------- HTTP ----------
|
|
50
|
+
async request(method, url, body, { auth = true, retry = true } = {}) {
|
|
51
|
+
const headers = { 'content-type': 'application/json', 'user-agent': `syrix-client/1.1 (${this.name})` };
|
|
52
|
+
if (auth && this.session) headers.authorization = `Bearer ${this.session.accessToken}`;
|
|
53
|
+
const res = await fetch(this.server + url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
54
|
+
const data = await res.json().catch(() => ({}));
|
|
55
|
+
if (res.status === 401 && auth && retry && this.session?.refreshToken) {
|
|
56
|
+
await this.refresh();
|
|
57
|
+
return this.request(method, url, body, { auth, retry: false });
|
|
58
|
+
}
|
|
59
|
+
if (!res.ok) {
|
|
60
|
+
const err = new Error(data?.error?.code || `http_${res.status}`);
|
|
61
|
+
err.status = res.status;
|
|
62
|
+
err.code = data?.error?.code;
|
|
63
|
+
err.details = data?.error?.details;
|
|
64
|
+
throw err;
|
|
65
|
+
}
|
|
66
|
+
return data;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async refresh() {
|
|
70
|
+
const r = await this.request('POST', '/api/auth/refresh', { refreshToken: this.session.refreshToken }, { auth: false, retry: false }).catch((err) => {
|
|
71
|
+
if (err.status === 401) this.emit('logged_out', err.code);
|
|
72
|
+
throw err;
|
|
73
|
+
});
|
|
74
|
+
this.session = { ...this.session, accessToken: r.session.accessToken, refreshToken: r.session.refreshToken };
|
|
75
|
+
await this.writeJson('session.json', this.session);
|
|
76
|
+
if (this.socket) this.socket.auth = { token: this.session.accessToken };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---------- linking ----------
|
|
80
|
+
async ensureIdentity() {
|
|
81
|
+
this.identity = await this.readJson('identity.json');
|
|
82
|
+
if (!this.identity) {
|
|
83
|
+
const id = await generateIdentity();
|
|
84
|
+
this.identity = { deviceId: randomId(), ...id };
|
|
85
|
+
await this.writeJson('identity.json', this.identity);
|
|
86
|
+
}
|
|
87
|
+
this.privateKey = await importPrivate(this.identity.privateJwk);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Links the device (if needed), registers its encryption key and starts listening. */
|
|
91
|
+
async connect({ pairingCode, phoneCode } = {}) {
|
|
92
|
+
await this.ensureIdentity();
|
|
93
|
+
this.session = await this.readJson('session.json');
|
|
94
|
+
if (this.session) {
|
|
95
|
+
try {
|
|
96
|
+
this.user = (await this.request('GET', '/api/auth/me')).user;
|
|
97
|
+
} catch (err) {
|
|
98
|
+
if (err.status !== 401 && err.status !== 403) throw err;
|
|
99
|
+
await this.logoutLocal();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
let link = null;
|
|
103
|
+
if (!this.session) {
|
|
104
|
+
// Default: this program shows a QR code and a pairing code; the phone scans or types it.
|
|
105
|
+
// phoneCode (6 digits shown by the phone) is the other direction, kept for scripts.
|
|
106
|
+
const fromPhone = phoneCode || (pairingCode && /^\d{3}\s?-?\d{3}$/.test(String(pairingCode)) ? pairingCode : null);
|
|
107
|
+
link = fromPhone ? await this.linkWithCode(fromPhone) : await this.requestPairing();
|
|
108
|
+
this.user = (await this.request('GET', '/api/auth/me')).user;
|
|
109
|
+
}
|
|
110
|
+
await this.request('POST', '/api/e2ee/devices', { deviceId: this.identity.deviceId, publicKey: this.identity.publicKey, label: `${this.name} · SYRIX Library` });
|
|
111
|
+
await this.listen();
|
|
112
|
+
this.emit('ready', { user: this.user });
|
|
113
|
+
if (link && this.syncHistory) void this.receiveHistory(link).catch((err) => this.emit('error', err));
|
|
114
|
+
return this;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Linking: the phone shows a 6-digit code (Settings > Linked devices > Show my connection code). The program
|
|
119
|
+
* sends it with a one-time key, then waits until the person taps Allow on the phone.
|
|
120
|
+
*/
|
|
121
|
+
async linkWithCode(code) {
|
|
122
|
+
const eph = await ephemeralPair();
|
|
123
|
+
const j = await this.request('POST', '/api/auth/link/join', { code: String(code), publicKey: eph.publicKey, label: `${this.name} · SYRIX Library` }, { auth: false });
|
|
124
|
+
this.emit('waiting_approval');
|
|
125
|
+
if (this.printQr) process.stdout.write('SYRIX: tap Allow on your phone to finish linking.\n');
|
|
126
|
+
const until = Date.now() + j.expiresIn * 1000;
|
|
127
|
+
while (Date.now() < until) {
|
|
128
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
129
|
+
const p = await this.request('POST', `/api/auth/link/join/${j.joinId}/poll`, { token: j.joinToken }, { auth: false }).catch((err) => {
|
|
130
|
+
if (err.code === 'link_denied' || err.code === 'link_expired') throw err;
|
|
131
|
+
return { status: 'pending' };
|
|
132
|
+
});
|
|
133
|
+
if (p.status === 'approved') {
|
|
134
|
+
this.session = { accessToken: p.session.accessToken, refreshToken: p.session.refreshToken };
|
|
135
|
+
await this.writeJson('session.json', this.session);
|
|
136
|
+
return { linkId: p.linkId, privateKey: eph.privateKey };
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
throw Object.assign(new Error('link_expired'), { code: 'link_expired' });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Pairing shown by this program (like WhatsApp libraries): a QR code and an 8-character pairing code, renewed
|
|
144
|
+
* every 3 minutes until the phone scans or types one ('qr' and 'pairing_code' events; printed in the terminal
|
|
145
|
+
* unless printQr is false). Resolves when the person taps Allow on the phone.
|
|
146
|
+
*/
|
|
147
|
+
async requestPairing({ attempts = 10 } = {}) {
|
|
148
|
+
for (let round = 0; round < attempts; round++) {
|
|
149
|
+
const eph = await ephemeralPair();
|
|
150
|
+
const r = await this.request('POST', '/api/auth/link/request', { publicKey: eph.publicKey, label: `${this.name} · SYRIX Library` }, { auth: false });
|
|
151
|
+
this.emit('qr', r.qr);
|
|
152
|
+
this.emit('pairing_code', r.pairingCode);
|
|
153
|
+
if (this.printQr) await this.printPairing(r.qr, r.pairingCode);
|
|
154
|
+
const until = Date.now() + r.expiresIn * 1000;
|
|
155
|
+
let scanned = false;
|
|
156
|
+
while (Date.now() < until) {
|
|
157
|
+
await new Promise((res) => setTimeout(res, 1500));
|
|
158
|
+
const p = await this.request('POST', `/api/auth/link/request/${r.requestId}/poll`, { token: r.token }, { auth: false }).catch((err) => {
|
|
159
|
+
if (err.code === 'link_denied') throw err;
|
|
160
|
+
if (err.code === 'link_expired') return { status: 'expired' };
|
|
161
|
+
return { status: 'pending' };
|
|
162
|
+
});
|
|
163
|
+
if (p.status === 'expired') break;
|
|
164
|
+
if (p.status === 'scanned' && !scanned) {
|
|
165
|
+
scanned = true;
|
|
166
|
+
this.emit('waiting_approval');
|
|
167
|
+
if (this.printQr) process.stdout.write('SYRIX: tap Allow on your phone to finish linking.\n');
|
|
168
|
+
}
|
|
169
|
+
if (p.status === 'approved') {
|
|
170
|
+
this.session = { accessToken: p.session.accessToken, refreshToken: p.session.refreshToken };
|
|
171
|
+
await this.writeJson('session.json', this.session);
|
|
172
|
+
return { linkId: p.linkId, privateKey: eph.privateKey };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// Expired without a scan: a fresh QR code and pairing code.
|
|
176
|
+
}
|
|
177
|
+
throw Object.assign(new Error('link_expired'), { code: 'link_expired' });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** QR code drawn with characters in the terminal, plus the pairing code. */
|
|
181
|
+
async printPairing(qr, code) {
|
|
182
|
+
let art = '';
|
|
183
|
+
try {
|
|
184
|
+
const QR = (await import('qrcode')).default;
|
|
185
|
+
art = await QR.toString(qr, { type: 'terminal', small: true });
|
|
186
|
+
} catch {
|
|
187
|
+
art = '';
|
|
188
|
+
}
|
|
189
|
+
process.stdout.write(`\n${art}\nSYRIX: on your phone open Settings > Linked devices > Link a program or device,\nthen scan this QR code or type the pairing code: ${code}\n\n`);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Asks for the phone's 6-digit code in the terminal (when no code was given). */
|
|
193
|
+
async promptCode() {
|
|
194
|
+
if (!process.stdin.isTTY) throw new Error('pairing code required: connect({ pairingCode }) or SYRIX_PAIRING_CODE');
|
|
195
|
+
const { createInterface } = await import('node:readline/promises');
|
|
196
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
197
|
+
try {
|
|
198
|
+
return (await rl.question('SYRIX: on your phone open Settings > Linked devices > Show my connection code, then type the 6-digit code: ')).trim();
|
|
199
|
+
} finally {
|
|
200
|
+
rl.close();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The phone sends the chat history encrypted to this device; emitted as 'history' ([messageId, content] pairs). */
|
|
205
|
+
async receiveHistory({ linkId, privateKey }) {
|
|
206
|
+
for (let i = 0; i < 200; i++) {
|
|
207
|
+
const r = await this.request('GET', `/api/e2ee/link/${linkId}/history`);
|
|
208
|
+
if (r.history) {
|
|
209
|
+
const res = await fetch(r.history.url.startsWith('/') ? this.server + r.history.url : r.history.url);
|
|
210
|
+
const archive = await openHistory(await res.arrayBuffer(), r.history, privateKey, linkId, this.user.id);
|
|
211
|
+
this.emit('history', archive.items);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
await new Promise((res2) => setTimeout(res2, 3000));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Logs this device out of the account (removes its key and session) and deletes the local files. */
|
|
219
|
+
async logout() {
|
|
220
|
+
await this.request('DELETE', `/api/e2ee/devices/${this.identity.deviceId}`).catch(() => undefined);
|
|
221
|
+
await this.request('POST', '/api/auth/logout').catch(() => undefined);
|
|
222
|
+
await this.logoutLocal();
|
|
223
|
+
}
|
|
224
|
+
async logoutLocal() {
|
|
225
|
+
this.socket?.close();
|
|
226
|
+
this.socket = null;
|
|
227
|
+
this.session = null;
|
|
228
|
+
await rm(this.file('session.json'), { force: true });
|
|
229
|
+
await rm(this.file('identity.json'), { force: true });
|
|
230
|
+
await this.ensureIdentity();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ---------- realtime ----------
|
|
234
|
+
async listen() {
|
|
235
|
+
this.socket?.close();
|
|
236
|
+
this.socket = io(this.server, { auth: { token: this.session.accessToken }, transports: ['websocket'], reconnection: true });
|
|
237
|
+
this.socket.on('connect_error', async (err) => {
|
|
238
|
+
if (String(err?.message) === 'unauthorized') await this.refresh().catch(() => this.emit('logged_out', 'session_revoked'));
|
|
239
|
+
});
|
|
240
|
+
this.socket.on('session:revoked', async () => {
|
|
241
|
+
this.emit('logged_out', 'session_revoked');
|
|
242
|
+
await this.logoutLocal();
|
|
243
|
+
});
|
|
244
|
+
this.socket.on('message:new', (raw) => void this.handle(raw).catch((err) => this.emit('error', err)));
|
|
245
|
+
await new Promise((resolve, reject) => {
|
|
246
|
+
const t = setTimeout(() => reject(new Error('socket_timeout')), 15000);
|
|
247
|
+
this.socket.once('connect', () => { clearTimeout(t); resolve(); });
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async peerKey(userId, deviceId) {
|
|
252
|
+
const k = `${userId}:${deviceId}`;
|
|
253
|
+
if (!this.peerKeys.has(k)) this.peerKeys.set(k, (await this.request('GET', `/api/e2ee/keys/${userId}/${deviceId}`)).publicKey);
|
|
254
|
+
return this.peerKeys.get(k);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async decrypt(raw) {
|
|
258
|
+
if (!raw.e2ee) return { t: raw.text ?? '', mt: raw.media_type ?? null, mu: raw.media_url ?? null };
|
|
259
|
+
const senderPublicKey = raw.sender_id === this.user.id && raw.e2ee.sd === this.identity.deviceId ? this.identity.publicKey : await this.peerKey(raw.sender_id, raw.e2ee.sd);
|
|
260
|
+
return open(raw.e2ee, { conversationId: raw.conversation_id, senderId: raw.sender_id, myDevice: this.identity.deviceId, privateKey: this.privateKey, senderPublicKey });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async handle(raw) {
|
|
264
|
+
if (!raw || raw.type === 'system') return;
|
|
265
|
+
const fromMe = raw.sender_id === this.user.id;
|
|
266
|
+
if (fromMe && raw.e2ee?.sd === this.identity.deviceId) return; // sent by this device
|
|
267
|
+
if (fromMe && this.ignoreOwnMessages) return;
|
|
268
|
+
let content;
|
|
269
|
+
try {
|
|
270
|
+
content = await this.decrypt(raw);
|
|
271
|
+
} catch {
|
|
272
|
+
this.emit('undecryptable', { id: raw.id, conversationId: raw.conversation_id });
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
const message = {
|
|
276
|
+
id: raw.id,
|
|
277
|
+
conversationId: raw.conversation_id,
|
|
278
|
+
senderId: raw.sender_id,
|
|
279
|
+
sender: raw.sender ?? null,
|
|
280
|
+
fromMe,
|
|
281
|
+
text: content.t ?? '',
|
|
282
|
+
type: content.mt ?? 'text',
|
|
283
|
+
fileName: content.fn ?? null,
|
|
284
|
+
media: content.m ?? null,
|
|
285
|
+
mentions: raw.mentions ?? [],
|
|
286
|
+
quoted: raw.reply_to ? { id: raw.reply_to.id, senderId: raw.reply_to.sender_id } : null,
|
|
287
|
+
createdAt: raw.created_at,
|
|
288
|
+
reply: (text) => this.sendText(raw.conversation_id, text, { replyTo: raw.id }),
|
|
289
|
+
download: () => this.downloadMedia(content.m),
|
|
290
|
+
};
|
|
291
|
+
this.emit('message', message);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Decrypts an attachment of a received message (photo, voice note, file) into a Buffer. */
|
|
295
|
+
async downloadMedia(pointer) {
|
|
296
|
+
if (!pointer) throw new Error('no_media');
|
|
297
|
+
const res = await fetch(pointer.url.startsWith('/') ? this.server + pointer.url : pointer.url);
|
|
298
|
+
if (!res.ok) throw new Error(`download_failed_${res.status}`);
|
|
299
|
+
return decryptBlob(await res.arrayBuffer(), pointer);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ---------- sending ----------
|
|
303
|
+
/** Lists the account's chats. */
|
|
304
|
+
async chats() {
|
|
305
|
+
return (await this.request('GET', '/api/chat/conversations')).conversations;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async sendText(conversationId, text, { replyTo = null } = {}) {
|
|
309
|
+
if (typeof text !== 'string' || !text.trim()) throw new Error('empty_text');
|
|
310
|
+
const clientId = globalThis.crypto.randomUUID();
|
|
311
|
+
const keys = await this.request('GET', `/api/e2ee/conversations/${conversationId}/devices`);
|
|
312
|
+
if (!keys.e2ee) {
|
|
313
|
+
return (await this.request('POST', `/api/chat/conversations/${conversationId}/messages`, { clientId, text, replyTo })).message;
|
|
314
|
+
}
|
|
315
|
+
const content = { v: 1, t: text, mt: null, fn: null, m: null, mu: null };
|
|
316
|
+
const send = async (devices) => {
|
|
317
|
+
const recipients = Object.values(devices).flat();
|
|
318
|
+
if (!recipients.some((d) => d.deviceId === this.identity.deviceId)) recipients.push({ deviceId: this.identity.deviceId, publicKey: this.identity.publicKey });
|
|
319
|
+
const env = await seal(content, { conversationId, senderId: this.user.id, senderDevice: this.identity.deviceId, privateKey: this.privateKey }, recipients);
|
|
320
|
+
return (await this.request('POST', `/api/chat/conversations/${conversationId}/messages`, { clientId, text: '', replyTo, e2ee: env })).message;
|
|
321
|
+
};
|
|
322
|
+
try {
|
|
323
|
+
return await send(keys.devices);
|
|
324
|
+
} catch (err) {
|
|
325
|
+
// Someone added or removed a device in the meantime: encrypt again for the current list.
|
|
326
|
+
if (err.code === 'e2ee_devices_changed' && err.details?.devices) return send(err.details.devices);
|
|
327
|
+
throw err;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ---------- groups (the linked account must be an admin of the group) ----------
|
|
332
|
+
/** Details of a chat: type, name, owner_id, admins, participant_ids... */
|
|
333
|
+
async chat(conversationId) {
|
|
334
|
+
return (await this.request('GET', `/api/chat/conversations/${conversationId}`)).conversation;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** True when the user is the owner or an admin of the group. */
|
|
338
|
+
async isAdmin(groupId, userId) {
|
|
339
|
+
const c = await this.chat(groupId);
|
|
340
|
+
return c.type === 'group' && (c.admins ?? []).includes(userId);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Finds a user by username (with or without @); null when not found. */
|
|
344
|
+
async userByUsername(username) {
|
|
345
|
+
try {
|
|
346
|
+
return (await this.request('GET', `/api/users/by-username/${encodeURIComponent(String(username).replace(/^@/, ''))}`)).profile;
|
|
347
|
+
} catch (err) {
|
|
348
|
+
if (err.status === 404) return null;
|
|
349
|
+
throw err;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
promote(groupId, userId) { return this.request('PUT', `/api/chat/groups/${groupId}/admins/${userId}`); }
|
|
354
|
+
demote(groupId, userId) { return this.request('DELETE', `/api/chat/groups/${groupId}/admins/${userId}`); }
|
|
355
|
+
kick(groupId, userId) { return this.request('DELETE', `/api/chat/groups/${groupId}/members/${userId}`); }
|
|
356
|
+
addMembers(groupId, userIds) { return this.request('POST', `/api/chat/groups/${groupId}/members`, { userIds: [].concat(userIds) }); }
|
|
357
|
+
/** Stops a member from writing for 1, 24 or 168 hours (null: until lifted). */
|
|
358
|
+
mute(groupId, userId, hours = 1) { return this.request('PUT', `/api/chat/groups/${groupId}/restricted/${userId}`, { hours }); }
|
|
359
|
+
unmute(groupId, userId) { return this.request('DELETE', `/api/chat/groups/${groupId}/restricted/${userId}`); }
|
|
360
|
+
leaveGroup(groupId) { return this.request('POST', `/api/chat/groups/${groupId}/leave`); }
|
|
361
|
+
|
|
362
|
+
async close() {
|
|
363
|
+
this.socket?.close();
|
|
364
|
+
this.socket = null;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export default SyrixClient;
|