@rhizogrip/spore-plugin-teams 0.0.0-stage → 0.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 +202 -0
- package/NOTICE +2 -0
- package/README.md +106 -2
- package/bin/spore-teams.js +25 -0
- package/package.json +67 -4
- package/src/adapter.js +250 -0
- package/src/api.js +54 -0
- package/src/auth.js +107 -0
- package/src/server.js +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,107 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rhizogrip/spore-plugin-teams
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A service that puts your spores in Microsoft Teams: a person's personal chat with the bot reaches
|
|
4
|
+
their spore, and a channel reaches its spore when someone there mentions the bot. It runs on the
|
|
5
|
+
machine the spores are on, once per bot, as a systemd user unit. It gives spores nothing, so it
|
|
6
|
+
needs no `spore plugin allow`: `spore service` offers it once it is installed.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm i -g @rhizogrip/spore-plugin-teams
|
|
10
|
+
echo 'OPS_TEAMS_SECRET=…' >> ~/.config/spore/environment # the app registration's client secret; it never reaches a spore
|
|
11
|
+
mkdir -p ~/.config/spore/teams
|
|
12
|
+
cat > ~/.config/spore/teams/ops.json <<'JSON'
|
|
13
|
+
{ "app": "<app id>", "tenant": "<tenant id>", "secret": "${OPS_TEAMS_SECRET}",
|
|
14
|
+
"listen": "127.0.0.1:3978", "people": {} }
|
|
15
|
+
JSON
|
|
16
|
+
spore service define teams@ops && spore service start teams@ops
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## The bot
|
|
20
|
+
|
|
21
|
+
Teams reaches a bot through Azure: an **Azure Bot**, single-tenant, whose app registration in
|
|
22
|
+
Entra ID gives the bot file its `app` (the Microsoft App ID), its `tenant`, and a client secret,
|
|
23
|
+
kept in `environment` under the variable `secret` names. The Azure Bot's messaging endpoint is a
|
|
24
|
+
public HTTPS address of yours ending in `/api/messages`, which your proxy forwards to `listen` —
|
|
25
|
+
a loopback address: the service never faces the internet itself. Turn on the Azure Bot's Teams
|
|
26
|
+
channel, and install a Teams app for the bot in your tenant with the personal and team scopes.
|
|
27
|
+
|
|
28
|
+
Every activity is checked before it is read: a token Microsoft signed for this app id, with a key
|
|
29
|
+
it endorses for Teams, for the `serviceUrl` the activity names. One that fails is answered 401 and
|
|
30
|
+
logged with what failed. An activity from another tenant than the bot's is dropped and logged.
|
|
31
|
+
|
|
32
|
+
`spore service define` first runs the service's checks (`--check`), which ask Microsoft for the
|
|
33
|
+
bot's token: a wrong app id, tenant or secret is refused there, with exit status 2.
|
|
34
|
+
|
|
35
|
+
## People and channels
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
{ "app": "…", "tenant": "…", "secret": "${OPS_TEAMS_SECRET}", "listen": "127.0.0.1:3978",
|
|
39
|
+
"people": { "3f2b…-object-id": "triage", "8a41…-object-id": { "spore": "ledger", "details": true } },
|
|
40
|
+
"channels": { "19:a1b2…@thread.tacv2": { "spores": ["triage"], "people": ["3f2b…-object-id", "*"] } } }
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`people` is each person's personal chat with the bot, by their Entra object id, and the spore it
|
|
44
|
+
reaches. `channels` is each standard channel by its id — in the channel's link, `19:…@thread.tacv2`
|
|
45
|
+
— with its one spore and `people`, who may address it there: object ids, or `"*"` for everyone in
|
|
46
|
+
the channel, written out. A channel has one spore: the bot speaks there as itself, so a second spore
|
|
47
|
+
is a second bot. `details` shows the calls themselves in the `working…` message rather than their
|
|
48
|
+
kinds. The file is read on every message, so a person or a channel is added by editing a line.
|
|
49
|
+
|
|
50
|
+
Someone not in the file gets silence, and the log gets the line to add:
|
|
51
|
+
|
|
52
|
+
```
|
|
53
|
+
refused Alice Martin (3f2b…) — to allow them, add "3f2b…": "<a spore>" to the people of …/teams/ops.json
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
which is also how you learn object ids: start with `"people": {}` and write to the bot.
|
|
57
|
+
|
|
58
|
+
## A turn
|
|
59
|
+
|
|
60
|
+
In a personal chat, anything written reaches the spore. In a channel, a message reaches it when
|
|
61
|
+
it mentions the bot, and the mention is not part of what the spore is told; the spore is told who
|
|
62
|
+
wrote and where. The bot posts `working…` and shows what kind of call runs as it runs; the answer
|
|
63
|
+
is a new message — in a channel, in the thread of the message it answers — and `working…` is then
|
|
64
|
+
removed, or marked `answered below` where Teams will not remove it. The answer is sent as Teams
|
|
65
|
+
markdown. What the turn left in `data/out/` is named, one line a file: files do not cross yet,
|
|
66
|
+
either way.
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
/status what the spore is doing, its turns and what they cost, and the running turn's limits
|
|
70
|
+
/stop end the turn it is running, and set aside what you sent that it had not read
|
|
71
|
+
/wrap [10m] ask the running turn to wrap up, now or in a while
|
|
72
|
+
/extend wall 30m give it more — wall, cost or rounds — up to the extend.<limit> its spore.cmk grants
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
In a channel, after the mention; there `/stop`, `/wrap` and `/extend` are for the people the
|
|
76
|
+
channel lists by id, not everyone `"*"` lets talk.
|
|
77
|
+
|
|
78
|
+
## Turns nobody in Teams started
|
|
79
|
+
|
|
80
|
+
A schedule, a job or a webhook starts a turn no one in Teams asked for. Its answer goes to the
|
|
81
|
+
spore's `replyTo` in `config.json`: `teams:<bot>/<object id>` for a person — the bot opens a
|
|
82
|
+
personal chat with them if they never wrote to it — or `teams:<bot>/<channel id>`, a new post in
|
|
83
|
+
the channel. A place this bot's file does not route to the spore is refused, and the log says why.
|
|
84
|
+
|
|
85
|
+
## What it guarantees
|
|
86
|
+
|
|
87
|
+
- **A message reaches its spore once,** under `teams:<conversation id>:<activity id>` as its
|
|
88
|
+
`requestId`, and Microsoft's delivery is answered only once the spore has it: one Microsoft sends
|
|
89
|
+
again is not said twice.
|
|
90
|
+
- **A finished turn reaches its conversation at least once.** What it owes a conversation is an
|
|
91
|
+
entry in the spore's outbox, settled only once Teams took it; one the service was posting when it
|
|
92
|
+
stopped is posted again opening with `(this may repeat an earlier message)`. One Teams refuses is
|
|
93
|
+
settled refused with Teams' reason; a rate limit is waited out, as long as Teams says.
|
|
94
|
+
- **An answer never waits behind progress.** Under a rate limit the `working…` edits are dropped.
|
|
95
|
+
|
|
96
|
+
## Not yet
|
|
97
|
+
|
|
98
|
+
Group chats (logged and left), private and shared channels, files in either direction, and a bot
|
|
99
|
+
serving tenants other than its own.
|
|
100
|
+
|
|
101
|
+
## What it keeps
|
|
102
|
+
|
|
103
|
+
`$XDG_STATE_HOME/spore/teams/<bot>/state.json`, mode 0600: where it stands in each spore, the
|
|
104
|
+
`working…` messages waiting for an answer, each person's chat with the bot and each channel's
|
|
105
|
+
service address, as Teams last gave them.
|
|
106
|
+
|
|
107
|
+
It imports `@rhizogrip/spore`, declared as a peer.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { dirname, resolve } from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
|
|
5
|
+
import { readBot, runService } from '@rhizogrip/spore/relay'
|
|
6
|
+
|
|
7
|
+
import { createConnector } from '../src/api.js'
|
|
8
|
+
import { createToken, createVerifier } from '../src/auth.js'
|
|
9
|
+
import { TEAMS, createAdapter, listenOf } from '../src/adapter.js'
|
|
10
|
+
import { serve } from '../src/server.js'
|
|
11
|
+
|
|
12
|
+
await runService({
|
|
13
|
+
spec: TEAMS,
|
|
14
|
+
program: 'spore-teams',
|
|
15
|
+
root: resolve(dirname(fileURLToPath(import.meta.url)), '..'),
|
|
16
|
+
open: async ({ file, credentials }) => {
|
|
17
|
+
const { app, tenant, ...raw } = readBot(TEAMS, file)
|
|
18
|
+
const { host, port } = listenOf(raw, file)
|
|
19
|
+
const token = createToken({ app, tenant, secret: credentials.secret })
|
|
20
|
+
await token()
|
|
21
|
+
const verify = createVerifier({ app })
|
|
22
|
+
const receive = ({ onActivity, signal, log }) => serve({ host, port, verify, onActivity, signal, log })
|
|
23
|
+
return { adapter: createAdapter({ connector: createConnector({ token }), receive, app, tenant }), who: `app ${app} on ${host}:${port}` }
|
|
24
|
+
}
|
|
25
|
+
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rhizogrip/spore-plugin-teams",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Microsoft Teams for spores: a bot of yours in personal chats and channels, each reaching its spore, run as a service",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Christophe Le Bars",
|
|
7
|
+
"email": "clb@toort.net"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/RHIZOGRIP/spore.git",
|
|
13
|
+
"directory": "plugins/teams"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=24"
|
|
17
|
+
},
|
|
18
|
+
"os": [
|
|
19
|
+
"linux"
|
|
20
|
+
],
|
|
21
|
+
"cpu": [
|
|
22
|
+
"x64"
|
|
23
|
+
],
|
|
24
|
+
"files": [
|
|
25
|
+
"bin/",
|
|
26
|
+
"src/",
|
|
27
|
+
"README.md",
|
|
28
|
+
"NOTICE"
|
|
29
|
+
],
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@rhizogrip/spore": "^1.22.0"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"test": "vitest run"
|
|
35
|
+
},
|
|
36
|
+
"spore": {
|
|
37
|
+
"works": "^1.22.0",
|
|
38
|
+
"services": {
|
|
39
|
+
"teams": {
|
|
40
|
+
"what": "a bot of yours in Microsoft Teams, each personal chat and channel reaching its spore",
|
|
41
|
+
"program": "./bin/spore-teams.js",
|
|
42
|
+
"instances": {
|
|
43
|
+
"dir": "teams",
|
|
44
|
+
"ext": ".json",
|
|
45
|
+
"called": "bot"
|
|
46
|
+
},
|
|
47
|
+
"check": [
|
|
48
|
+
"--check"
|
|
49
|
+
]
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"release-it": {
|
|
54
|
+
"git": {
|
|
55
|
+
"requireBranch": "main",
|
|
56
|
+
"commitMessage": "release: plugin-teams v${version}",
|
|
57
|
+
"tagName": "plugin-teams-v${version}",
|
|
58
|
+
"requireUpstream": false,
|
|
59
|
+
"push": true
|
|
60
|
+
},
|
|
61
|
+
"npm": {
|
|
62
|
+
"publish": false
|
|
63
|
+
},
|
|
64
|
+
"github": {
|
|
65
|
+
"release": false
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"license": "Apache-2.0"
|
|
69
|
+
}
|
package/src/adapter.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Microsoft Teams for the relay (`@rhizogrip/spore/relay`): the bot file, the activities the Bot
|
|
3
|
+
* Connector delivers, and the Bot Connector calls that answer them. A person's personal chat with
|
|
4
|
+
* the bot is a conversation keyed by their Entra object id; a channel's is a thread in it,
|
|
5
|
+
* `<channel id>;messageid=<root>`, routed by its channel.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { SporeError } from '@rhizogrip/spore'
|
|
9
|
+
|
|
10
|
+
const FIELDS = ['app', 'tenant', 'secret', 'listen', 'people', 'channels']
|
|
11
|
+
const PERSON_FIELDS = ['spore', 'details']
|
|
12
|
+
const CHANNEL_FIELDS = ['spores', 'people', 'details']
|
|
13
|
+
const PERSON = /^[0-9a-f][0-9a-f-]*$/i
|
|
14
|
+
const CHANNEL = /^19:[^\s;]+@thread\.[a-z0-9]+$/i
|
|
15
|
+
const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost'])
|
|
16
|
+
const THREAD = ';messageid='
|
|
17
|
+
const COMMAND = /^\/([a-z]+)(?:\s+(.+))?$/is
|
|
18
|
+
const SERVICE_URL = 'https://smba.trafficmanager.net/teams/'
|
|
19
|
+
const SHAPE = '{ "app": "<app id>", "tenant": "<tenant id>", "secret": "${OPS_TEAMS_SECRET}", "listen": "127.0.0.1:3978", "people": { "<object id>": "<spore>" }, "channels": { "<channel id>": { "spores": ["<spore>"], "people": ["<object id>"] } } }' // eslint-disable-line no-template-curly-in-string
|
|
20
|
+
|
|
21
|
+
const invalid = (path, problem, detail = `a bot is ${SHAPE}`) => new SporeError(`${path} ${problem}`, { type: 'TEAMS_BOT_INVALID', detail })
|
|
22
|
+
|
|
23
|
+
const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
24
|
+
|
|
25
|
+
const strays = (path, kind, id, entry, takes) => {
|
|
26
|
+
const extra = Object.keys(entry).filter(key => !takes.includes(key))
|
|
27
|
+
if (!extra.length) return
|
|
28
|
+
const bots = extra.filter(key => FIELDS.includes(key))
|
|
29
|
+
throw invalid(path, `gives ${kind} ${id} ${extra.join(', ')}, which a ${kind} does not take`, `a ${kind} takes ${takes.join(', ')}${bots.length ? `; ${bots.join(', ')} is the bot's, beside people and channels` : ''}`)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Where the service listens, `<loopback host>:<port>`: the operator's proxy is what faces Microsoft. */
|
|
33
|
+
export function listenOf (raw, path) {
|
|
34
|
+
const found = /^(.+):(\d+)$/.exec(raw.listen ?? '')
|
|
35
|
+
const host = found?.[1].replace(/^\[(.*)\]$/, '$1')
|
|
36
|
+
if (!found || !LOOPBACK.has(host) || Number(found[2]) > 65535) {
|
|
37
|
+
throw invalid(path, `listens on ${JSON.stringify(raw.listen)}`, 'listen is a loopback address and a port, as 127.0.0.1:3978 — a proxy of yours gives it the public HTTPS address the Azure Bot names')
|
|
38
|
+
}
|
|
39
|
+
return { host, port: Number(found[2]) }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The bot's app and tenant, where it listens, and its routing: `people`, each person's personal
|
|
44
|
+
* chat by their Entra object id — `"<spore>"` or `{ "spore", "details" }` — and `channels`, each
|
|
45
|
+
* standard channel by its id, with its one spore and who may address it there: object ids, or `*`
|
|
46
|
+
* for everyone in the channel. `details` shows the calls themselves rather than their kinds.
|
|
47
|
+
*/
|
|
48
|
+
function routes (raw, path) {
|
|
49
|
+
for (const field of ['app', 'tenant']) {
|
|
50
|
+
if (typeof raw[field] !== 'string' || !raw[field]) throw invalid(path, `has no ${field}`, `${field} is the Azure Bot's ${field === 'app' ? 'Microsoft App ID' : 'app tenant ID'}`)
|
|
51
|
+
}
|
|
52
|
+
listenOf(raw, path)
|
|
53
|
+
if (raw.people === undefined && raw.channels === undefined) {
|
|
54
|
+
throw invalid(path, 'has no people and no channels', `a bot is ${SHAPE} — "people": {} while you learn the ids: the log names everyone it refuses`)
|
|
55
|
+
}
|
|
56
|
+
const entries = (field) => {
|
|
57
|
+
const value = raw[field] ?? {}
|
|
58
|
+
if (!record(value)) throw invalid(path, `has ${field} that is not { "<id>": … }`)
|
|
59
|
+
return Object.entries(value)
|
|
60
|
+
}
|
|
61
|
+
const table = new Map()
|
|
62
|
+
for (const [person, entry] of entries('people')) {
|
|
63
|
+
if (!PERSON.test(person)) throw invalid(path, `names "${person}" among its people, which is not an Entra object id`, 'a person is their object id in Entra ID; a channel\'s id begins 19: and goes under channels')
|
|
64
|
+
if (record(entry)) {
|
|
65
|
+
strays(path, 'person', person, entry, PERSON_FIELDS)
|
|
66
|
+
if (entry.details !== undefined && typeof entry.details !== 'boolean') throw invalid(path, `has a person ${person} whose details is not true or false`)
|
|
67
|
+
}
|
|
68
|
+
const spore = record(entry) ? entry.spore : entry
|
|
69
|
+
if (typeof spore !== 'string' || !spore) throw invalid(path, `maps person ${person} to something that is not a spore`, 'each person is their object id against the name of the spore they reach, or { "spore": "<name>", "details": true }')
|
|
70
|
+
table.set(person, { spores: [spore], details: record(entry) && entry.details === true, show: null, people: null, overhear: false })
|
|
71
|
+
}
|
|
72
|
+
for (const [channel, entry] of entries('channels')) {
|
|
73
|
+
if (!CHANNEL.test(channel)) throw invalid(path, `names "${channel}" among its channels, which is not a channel id`, 'a channel id is 19:…@thread.tacv2, from the channel\'s link in Teams')
|
|
74
|
+
if (!record(entry)) throw invalid(path, `has a channel ${channel} that is not { "spores": [...], "people": [...] }`)
|
|
75
|
+
strays(path, 'channel', channel, entry, CHANNEL_FIELDS)
|
|
76
|
+
if (entry.details !== undefined && typeof entry.details !== 'boolean') throw invalid(path, `has a channel ${channel} whose details is not true or false`)
|
|
77
|
+
if (!Array.isArray(entry.spores) || !entry.spores.length || !entry.spores.every(spore => typeof spore === 'string' && spore)) throw invalid(path, `has a channel ${channel} with no spores`)
|
|
78
|
+
if (entry.spores.length > 1) throw invalid(path, `gives channel ${channel} ${entry.spores.length} spores`, 'a bot speaks in a channel as itself, so a channel has one spore — a second spore there is a second bot')
|
|
79
|
+
if (!Array.isArray(entry.people) || !entry.people.every(who => who === '*' || (typeof who === 'string' && PERSON.test(who)))) {
|
|
80
|
+
throw invalid(path, `has a channel ${channel} whose people are not object ids or *`, 'people is who may address its spore — ["<object id>", …], or ["*"] for everyone in the channel, written out')
|
|
81
|
+
}
|
|
82
|
+
table.set(channel, { spores: entry.spores, details: entry.details === true, show: null, people: entry.people, overhear: false })
|
|
83
|
+
}
|
|
84
|
+
return table
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const HELP = 'Anything you write to me in a personal chat goes to the spore; in a channel, mention me. /status says what it is doing; /stop ends the turn it is running and sets aside what you sent that it had not read; /wrap [10m] asks it to wrap up; /extend wall 30m gives it more, as far as its spore.cmk allows.'
|
|
88
|
+
|
|
89
|
+
export const TEAMS = {
|
|
90
|
+
kind: 'teams',
|
|
91
|
+
label: 'Teams',
|
|
92
|
+
noun: 'conversation',
|
|
93
|
+
fields: FIELDS,
|
|
94
|
+
credentials: ['secret'],
|
|
95
|
+
stateFields: ['chats', 'channels'],
|
|
96
|
+
sourceVariables: [],
|
|
97
|
+
refusals: ['TEAMS_REFUSED', 'TEAMS_LISTEN_REFUSED'],
|
|
98
|
+
example: SHAPE,
|
|
99
|
+
routes,
|
|
100
|
+
routeOf: (conversation) => conversation.split(THREAD)[0],
|
|
101
|
+
usage: { help: HELP, extend: '/extend wall 30m, /extend cost 1.50 or /extend rounds 20' },
|
|
102
|
+
limits: { message: 40000, file: 0, editEveryMs: 2500, typingEveryMs: 4000 },
|
|
103
|
+
can: { upload: false, remove: true, react: false, typing: false, reply: true },
|
|
104
|
+
reactions: null,
|
|
105
|
+
showShared: 'working',
|
|
106
|
+
hint (err, { file }) {
|
|
107
|
+
if (err.type === 'TEAMS_NO_BOT') return `mkdir -p ${file.slice(0, file.lastIndexOf('/'))} — then ${file} as ${SHAPE}`
|
|
108
|
+
if (err.type === 'TEAMS_REFUSED') return 'the app id, its tenant and a client secret come from the Azure Bot\'s app registration in Entra ID; the secret goes in environment beside config.json'
|
|
109
|
+
if (err.type === 'TEAMS_LISTEN_REFUSED') return `another process holds that address — change listen in ${file}`
|
|
110
|
+
return null
|
|
111
|
+
},
|
|
112
|
+
refusal: (message, botFile) => message.shared
|
|
113
|
+
? `refused ${message.where}, ${message.conversation.split(THREAD)[0]} — to allow it, add "${message.conversation.split(THREAD)[0]}": { "spores": ["<a spore>"], "people": ["${message.person.id}"] } to the channels of ${botFile}`
|
|
114
|
+
: `refused ${message.person.name} (${message.person.id}) — to allow them, add "${message.person.id}": "<a spore>" to the people of ${botFile}`
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', ''': '\'', ' ': ' ' }
|
|
118
|
+
|
|
119
|
+
/** Teams' markup made plain: the bot's own mention gone, anyone else's as `@name`, tags dropped. */
|
|
120
|
+
const plain = (html, own) => html
|
|
121
|
+
.replace(/<at[^>]*>(.*?)<\/at>/gis, (whole, name) => own.includes(whole) ? '' : `@${name}`)
|
|
122
|
+
.replace(/<br\s*\/?>|<\/p>/gi, '\n')
|
|
123
|
+
.replace(/<[^>]+>/g, '')
|
|
124
|
+
.replace(/&(amp|lt|gt|quot|#39|nbsp);/g, (entity) => ENTITIES[entity])
|
|
125
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
126
|
+
.trim()
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* A message activity as the relay takes it, or null for none it takes: one in a personal chat
|
|
130
|
+
* reaches the person's spore; one in a channel reaches the channel's when it mentions the bot,
|
|
131
|
+
* and names no spore otherwise.
|
|
132
|
+
*/
|
|
133
|
+
export function normalize (activity) {
|
|
134
|
+
const personal = activity.conversation.conversationType === 'personal'
|
|
135
|
+
const own = (activity.entities ?? []).filter(entity => entity.type === 'mention' && entity.mentioned?.id === activity.recipient.id).map(entity => entity.text)
|
|
136
|
+
const text = plain(activity.text ?? '', own) || null
|
|
137
|
+
const command = text?.match(COMMAND)
|
|
138
|
+
const channel = activity.channelData?.channel
|
|
139
|
+
return {
|
|
140
|
+
id: `${activity.conversation.id}:${activity.id}`,
|
|
141
|
+
conversation: personal ? activity.from.aadObjectId : activity.conversation.id,
|
|
142
|
+
message: activity.id,
|
|
143
|
+
person: { id: activity.from.aadObjectId, name: activity.from.name, groups: [] },
|
|
144
|
+
spore: null,
|
|
145
|
+
where: personal ? 'a personal chat in Teams' : channel?.name ? `the Teams channel "${channel.name}"` : 'a Teams channel',
|
|
146
|
+
shared: !personal,
|
|
147
|
+
text,
|
|
148
|
+
command: command ? { verb: command[1].toLowerCase(), args: command[2] ?? '' } : null,
|
|
149
|
+
addresses: personal || own.length ? null : [],
|
|
150
|
+
files: (activity.attachments ?? []).filter(attachment => attachment.contentType !== 'text/html').length
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const tenantOf = (activity) => activity.conversation?.tenantId ?? activity.channelData?.tenant?.id
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The live adapter. `receive({ onActivity, signal, log })` is the transport — the listener, or a
|
|
158
|
+
* test's — and hands over each activity already checked. A post to a person goes to the chat they
|
|
159
|
+
* have with the bot, made when there is none yet; to a channel thread, into the thread; to a
|
|
160
|
+
* channel, as a new post. A note is `<conversation id> <activity id>`, where the post went.
|
|
161
|
+
*/
|
|
162
|
+
export function createAdapter ({ connector, receive, app, tenant }) {
|
|
163
|
+
let kept = null
|
|
164
|
+
let save = null
|
|
165
|
+
|
|
166
|
+
/** What came with an activity that says where to answer: the person's chat, or the channel's service. */
|
|
167
|
+
const remember = (activity) => {
|
|
168
|
+
const { serviceUrl } = activity
|
|
169
|
+
if (activity.conversation.conversationType === 'personal' && activity.from.aadObjectId) {
|
|
170
|
+
const was = kept.chats[activity.from.aadObjectId]
|
|
171
|
+
if (was?.conversation === activity.conversation.id && was.serviceUrl === serviceUrl) return
|
|
172
|
+
kept.chats[activity.from.aadObjectId] = { conversation: activity.conversation.id, serviceUrl }
|
|
173
|
+
save()
|
|
174
|
+
} else if (activity.channelData?.channel?.id) {
|
|
175
|
+
const channel = activity.channelData.channel.id
|
|
176
|
+
if (kept.channels[channel]?.serviceUrl === serviceUrl) return
|
|
177
|
+
kept.channels[channel] = { serviceUrl }
|
|
178
|
+
save()
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const serviceOf = (conversation) => conversation.startsWith('19:')
|
|
183
|
+
? kept.channels[conversation.split(THREAD)[0]]?.serviceUrl ?? SERVICE_URL
|
|
184
|
+
: kept.chats[conversation]?.serviceUrl ?? SERVICE_URL
|
|
185
|
+
|
|
186
|
+
const chatOf = async (person) => {
|
|
187
|
+
if (!kept.chats[person]) {
|
|
188
|
+
const made = await connector.create(SERVICE_URL, { bot: { id: `28:${app}` }, members: [{ id: person }], channelData: { tenant: { id: tenant } }, isGroup: false })
|
|
189
|
+
kept.chats[person] = { conversation: made.id, serviceUrl: SERVICE_URL }
|
|
190
|
+
save()
|
|
191
|
+
}
|
|
192
|
+
return kept.chats[person].conversation
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const placeOf = (note) => {
|
|
196
|
+
const at = note.lastIndexOf(' ')
|
|
197
|
+
return { conversation: note.slice(0, at), id: note.slice(at + 1) }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const activity = (text, { markdown = false, answering = null } = {}) => ({
|
|
201
|
+
type: 'message',
|
|
202
|
+
text,
|
|
203
|
+
textFormat: markdown ? 'markdown' : 'plain',
|
|
204
|
+
...(answering === null ? {} : { replyToId: answering })
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
...TEAMS,
|
|
209
|
+
|
|
210
|
+
restore (state, persist) {
|
|
211
|
+
kept = state
|
|
212
|
+
save = persist
|
|
213
|
+
},
|
|
214
|
+
|
|
215
|
+
listen: ({ onMessage, signal, log }) => receive({
|
|
216
|
+
signal,
|
|
217
|
+
log,
|
|
218
|
+
onActivity: async (one) => {
|
|
219
|
+
if (tenantOf(one) !== tenant) return log(`dropped an activity from tenant ${tenantOf(one)}: this bot serves ${tenant}`)
|
|
220
|
+
remember(one)
|
|
221
|
+
if (one.type !== 'message') return
|
|
222
|
+
if (one.conversation.conversationType === 'groupChat') return log(`group chat ${one.conversation.id}: group chats are not served yet`)
|
|
223
|
+
if (!one.from?.aadObjectId) return log(`a message in ${one.conversation.id} from ${one.from?.name ?? 'someone'} with no Entra object id, not taken`)
|
|
224
|
+
await onMessage(normalize(one))
|
|
225
|
+
}
|
|
226
|
+
}),
|
|
227
|
+
|
|
228
|
+
post: async (conversation, text, { answering = null, markdown = false } = {}) => {
|
|
229
|
+
if (!conversation.startsWith('19:')) {
|
|
230
|
+
const chat = await chatOf(conversation)
|
|
231
|
+
return `${chat} ${await connector.send(serviceOf(conversation), chat, activity(text, { markdown, answering }))}`
|
|
232
|
+
}
|
|
233
|
+
if (conversation.includes(THREAD)) {
|
|
234
|
+
return `${conversation} ${await connector.send(serviceOf(conversation), conversation, activity(text, { markdown, answering }))}`
|
|
235
|
+
}
|
|
236
|
+
const made = await connector.create(serviceOf(conversation), { isGroup: true, channelData: { channel: { id: conversation }, tenant: { id: tenant } }, activity: activity(text, { markdown }) })
|
|
237
|
+
return `${made.id} ${made.activityId}`
|
|
238
|
+
},
|
|
239
|
+
|
|
240
|
+
edit: async (conversation, note, text) => {
|
|
241
|
+
const where = placeOf(note)
|
|
242
|
+
await connector.update(serviceOf(conversation), where.conversation, where.id, { ...activity(text), id: where.id })
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
remove: async (conversation, note) => {
|
|
246
|
+
const where = placeOf(note)
|
|
247
|
+
await connector.remove(serviceOf(conversation), where.conversation, where.id)
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
package/src/api.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Bot Connector's REST API, as the service uses it. Every failure is a `TEAMS_FAILED`,
|
|
3
|
+
* `retryable` for what Microsoft asks a bot to try again — 412, 429, 502, 503, 504, and a request
|
|
4
|
+
* that never reached it — with `context.status`, `context.code` and `context.retryAfter` (seconds,
|
|
5
|
+
* when Microsoft said how long to wait).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { SporeError } from '@rhizogrip/spore'
|
|
9
|
+
|
|
10
|
+
const RETRYABLE = new Set([412, 429, 502, 503, 504])
|
|
11
|
+
|
|
12
|
+
const base = (serviceUrl) => serviceUrl.endsWith('/') ? serviceUrl : `${serviceUrl}/`
|
|
13
|
+
|
|
14
|
+
export function createConnector ({ token, fetchImpl = fetch }) {
|
|
15
|
+
const call = async (method, url, body) => {
|
|
16
|
+
const bearer = await token()
|
|
17
|
+
let response
|
|
18
|
+
try {
|
|
19
|
+
response = await fetchImpl(url, {
|
|
20
|
+
method,
|
|
21
|
+
headers: { authorization: `Bearer ${bearer}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
22
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
23
|
+
signal: AbortSignal.timeout(60_000)
|
|
24
|
+
})
|
|
25
|
+
} catch (err) {
|
|
26
|
+
throw new SporeError(`teams ${method} failed`, { type: 'TEAMS_FAILED', detail: err.message, retryable: true, context: { status: null, code: null, retryAfter: null } })
|
|
27
|
+
}
|
|
28
|
+
const answer = await response.json().catch(() => null)
|
|
29
|
+
if (!response.ok) {
|
|
30
|
+
const after = Number(response.headers.get('retry-after'))
|
|
31
|
+
throw new SporeError(`teams ${method} failed`, {
|
|
32
|
+
type: 'TEAMS_FAILED',
|
|
33
|
+
detail: answer?.error?.message ?? answer?.message ?? `HTTP ${response.status}`,
|
|
34
|
+
retryable: RETRYABLE.has(response.status),
|
|
35
|
+
context: { status: response.status, code: answer?.error?.code ?? null, retryAfter: Number.isFinite(after) && after > 0 ? after : null }
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
return answer
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const activities = (serviceUrl, conversation) => `${base(serviceUrl)}v3/conversations/${encodeURIComponent(conversation)}/activities`
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
/** An activity into a conversation; answers its id. */
|
|
45
|
+
send: async (serviceUrl, conversation, activity) => (await call('POST', activities(serviceUrl, conversation), activity)).id,
|
|
46
|
+
|
|
47
|
+
update: (serviceUrl, conversation, id, activity) => call('PUT', `${activities(serviceUrl, conversation)}/${encodeURIComponent(id)}`, activity),
|
|
48
|
+
|
|
49
|
+
remove: (serviceUrl, conversation, id) => call('DELETE', `${activities(serviceUrl, conversation)}/${encodeURIComponent(id)}`),
|
|
50
|
+
|
|
51
|
+
/** A conversation made — a person's chat with the bot, or a new post in a channel: `{ id, activityId }`. */
|
|
52
|
+
create: (serviceUrl, body) => call('POST', `${base(serviceUrl)}v3/conversations`, body)
|
|
53
|
+
}
|
|
54
|
+
}
|
package/src/auth.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A bot's identity with Microsoft, both ways: the token it sends the Bot Connector, from its
|
|
3
|
+
* tenant's authority, and the check of the token the Bot Connector sends with each activity. A
|
|
4
|
+
* failure to reach Microsoft is a `TEAMS_FAILED`, retryable; Microsoft refusing the bot's app id or
|
|
5
|
+
* secret is a `TEAMS_REFUSED`, which a service cannot get past by waiting.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { createPublicKey, verify } from 'node:crypto'
|
|
9
|
+
|
|
10
|
+
import { SporeError } from '@rhizogrip/spore'
|
|
11
|
+
|
|
12
|
+
const AUTHORITY = 'https://login.microsoftonline.com'
|
|
13
|
+
const OPENID = 'https://login.botframework.com/v1/.well-known/openidconfiguration'
|
|
14
|
+
const ISSUER = 'https://api.botframework.com'
|
|
15
|
+
const SCOPE = 'https://api.botframework.com/.default'
|
|
16
|
+
const SKEW_S = 300
|
|
17
|
+
const KEYS_EVERY_MS = 24 * 60 * 60 * 1000
|
|
18
|
+
const UNKNOWN_KEY_EVERY_MS = 60 * 1000
|
|
19
|
+
|
|
20
|
+
const unreachable = (what, err) => new SporeError(`${what} failed`, { type: 'TEAMS_FAILED', detail: err.message, retryable: true, context: { status: null, retryAfter: null } })
|
|
21
|
+
|
|
22
|
+
/** The bot's bearer token for the Bot Connector, asked of its tenant and kept until shortly before it expires. */
|
|
23
|
+
export function createToken ({ app, tenant, secret, fetchImpl = fetch, now = Date.now, authority = AUTHORITY }) {
|
|
24
|
+
let held = null
|
|
25
|
+
return async () => {
|
|
26
|
+
if (held && held.until > now()) return held.token
|
|
27
|
+
let response
|
|
28
|
+
try {
|
|
29
|
+
response = await fetchImpl(`${authority}/${encodeURIComponent(tenant)}/oauth2/v2.0/token`, {
|
|
30
|
+
method: 'POST',
|
|
31
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
32
|
+
body: new URLSearchParams({ grant_type: 'client_credentials', client_id: app, client_secret: secret, scope: SCOPE }),
|
|
33
|
+
signal: AbortSignal.timeout(30_000)
|
|
34
|
+
})
|
|
35
|
+
} catch (err) {
|
|
36
|
+
throw unreachable('asking Microsoft for a token', err)
|
|
37
|
+
}
|
|
38
|
+
const answer = await response.json().catch(() => null)
|
|
39
|
+
if (!response.ok || typeof answer?.access_token !== 'string') {
|
|
40
|
+
throw new SporeError('Microsoft gave the bot no token', {
|
|
41
|
+
type: response.status >= 500 ? 'TEAMS_FAILED' : 'TEAMS_REFUSED',
|
|
42
|
+
detail: answer?.error_description?.split('\r\n')[0] ?? `HTTP ${response.status}`,
|
|
43
|
+
retryable: response.status >= 500,
|
|
44
|
+
context: { status: response.status, retryAfter: null }
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
held = { token: answer.access_token, until: now() + (answer.expires_in - SKEW_S) * 1000 }
|
|
48
|
+
return held.token
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const decoded = (part) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
|
|
53
|
+
|
|
54
|
+
const sameService = (one, other) => typeof one === 'string' && typeof other === 'string' &&
|
|
55
|
+
one.toLowerCase().replace(/\/+$/, '') === other.toLowerCase().replace(/\/+$/, '')
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The check of an activity's `Authorization`: a JWT Microsoft signed with RS256, by a key it
|
|
59
|
+
* publishes and endorses for the activity's channel, issued by the Bot Connector for this app id,
|
|
60
|
+
* in its time, for the `serviceUrl` the activity names. Answers null when it holds, else why not.
|
|
61
|
+
* The keys are read from Microsoft's OpenID metadata, again each day and when a token names one
|
|
62
|
+
* they do not hold.
|
|
63
|
+
*/
|
|
64
|
+
export function createVerifier ({ app, fetchImpl = fetch, now = Date.now, openid = OPENID }) {
|
|
65
|
+
let keys = null
|
|
66
|
+
const load = async () => {
|
|
67
|
+
try {
|
|
68
|
+
const config = await (await fetchImpl(openid, { signal: AbortSignal.timeout(30_000) })).json()
|
|
69
|
+
const set = await (await fetchImpl(config.jwks_uri, { signal: AbortSignal.timeout(30_000) })).json()
|
|
70
|
+
keys = { at: now(), byKid: new Map(set.keys.map(key => [key.kid, key])) }
|
|
71
|
+
} catch (err) {
|
|
72
|
+
throw unreachable('reading the keys Microsoft signs activities with', err)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const keyOf = async (kid) => {
|
|
76
|
+
if (!keys || now() - keys.at > KEYS_EVERY_MS) await load()
|
|
77
|
+
if (!keys.byKid.has(kid) && now() - keys.at > UNKNOWN_KEY_EVERY_MS) await load()
|
|
78
|
+
return keys.byKid.get(kid) ?? null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return async (authorization, activity) => {
|
|
82
|
+
const token = /^Bearer (\S+)$/.exec(authorization ?? '')?.[1]
|
|
83
|
+
if (!token) return 'it carries no bearer token'
|
|
84
|
+
const parts = token.split('.')
|
|
85
|
+
let header, claims
|
|
86
|
+
try {
|
|
87
|
+
if (parts.length !== 3) throw new Error('three parts')
|
|
88
|
+
header = decoded(parts[0])
|
|
89
|
+
claims = decoded(parts[1])
|
|
90
|
+
} catch {
|
|
91
|
+
return 'its token is not a JWT'
|
|
92
|
+
}
|
|
93
|
+
if (header.alg !== 'RS256') return `its token is signed with ${header.alg}, not RS256`
|
|
94
|
+
const jwk = await keyOf(header.kid)
|
|
95
|
+
if (!jwk) return `its token names key ${header.kid}, which Microsoft does not publish`
|
|
96
|
+
if (!(jwk.endorsements ?? []).includes(activity.channelId)) return `key ${header.kid} is not endorsed for ${activity.channelId}`
|
|
97
|
+
const key = createPublicKey({ key: { kty: jwk.kty, n: jwk.n, e: jwk.e }, format: 'jwk' })
|
|
98
|
+
if (!verify('RSA-SHA256', Buffer.from(`${parts[0]}.${parts[1]}`), key, Buffer.from(parts[2], 'base64url'))) return 'its token\'s signature does not hold'
|
|
99
|
+
if (claims.iss !== ISSUER) return `its token was issued by ${claims.iss}`
|
|
100
|
+
if (claims.aud !== app) return `its token is for ${claims.aud}, not this bot`
|
|
101
|
+
const at = now() / 1000
|
|
102
|
+
if (typeof claims.exp !== 'number' || claims.exp + SKEW_S < at) return 'its token has expired'
|
|
103
|
+
if (typeof claims.nbf === 'number' && claims.nbf - SKEW_S > at) return 'its token is not valid yet'
|
|
104
|
+
if (!sameService(claims.serviceurl, activity.serviceUrl)) return 'its token is for another serviceUrl than the activity names'
|
|
105
|
+
return null
|
|
106
|
+
}
|
|
107
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the Bot Connector delivers: `POST /api/messages` on a loopback address, which the
|
|
3
|
+
* operator's proxy makes the bot's public HTTPS endpoint. An activity is checked before it is
|
|
4
|
+
* read, and answered 200 only once `onActivity` has it, so one the service could not take is
|
|
5
|
+
* delivered again.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { createServer } from 'node:http'
|
|
9
|
+
|
|
10
|
+
import { SporeError } from '@rhizogrip/spore'
|
|
11
|
+
|
|
12
|
+
const PATH = '/api/messages'
|
|
13
|
+
const MOST_BYTES = 1024 * 1024
|
|
14
|
+
|
|
15
|
+
const bodyOf = (request) => new Promise((resolve, reject) => {
|
|
16
|
+
const chunks = []
|
|
17
|
+
let bytes = 0
|
|
18
|
+
request.on('data', (chunk) => {
|
|
19
|
+
bytes += chunk.length
|
|
20
|
+
if (bytes <= MOST_BYTES) chunks.push(chunk)
|
|
21
|
+
})
|
|
22
|
+
request.on('end', () => bytes > MOST_BYTES ? reject(Object.assign(new Error('too large'), { status: 413 })) : resolve(Buffer.concat(chunks).toString('utf8')))
|
|
23
|
+
request.on('error', reject)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
/** Serves until `signal` aborts, telling `listening` the port once it listens. */
|
|
27
|
+
export function serve ({ host, port, verify, onActivity, signal, log, listening = () => {} }) {
|
|
28
|
+
const server = createServer(async (request, response) => {
|
|
29
|
+
const answer = (status) => response.writeHead(status).end()
|
|
30
|
+
if (request.method !== 'POST' || request.url !== PATH) return answer(404)
|
|
31
|
+
let activity
|
|
32
|
+
try {
|
|
33
|
+
activity = JSON.parse(await bodyOf(request))
|
|
34
|
+
} catch (err) {
|
|
35
|
+
return answer(err.status ?? 400)
|
|
36
|
+
}
|
|
37
|
+
let refused
|
|
38
|
+
try {
|
|
39
|
+
refused = await verify(request.headers.authorization, activity)
|
|
40
|
+
} catch (err) {
|
|
41
|
+
log(`could not check an activity — ${err.message}${err.detail ? ` — ${err.detail}` : ''}`)
|
|
42
|
+
return answer(503)
|
|
43
|
+
}
|
|
44
|
+
if (refused) {
|
|
45
|
+
log(`refused an activity: ${refused}`)
|
|
46
|
+
return answer(401)
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
await onActivity(activity)
|
|
50
|
+
} catch (err) {
|
|
51
|
+
log(`activity ${activity.id} not taken — ${err.message}${err.detail ? ` — ${err.detail}` : ''}`)
|
|
52
|
+
return answer(500)
|
|
53
|
+
}
|
|
54
|
+
answer(200)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
return new Promise((resolve, reject) => {
|
|
58
|
+
server.once('error', (err) => reject(new SporeError(`cannot listen on ${host}:${port}`, { type: 'TEAMS_LISTEN_REFUSED', detail: err.message })))
|
|
59
|
+
server.listen(port, host, () => {
|
|
60
|
+
listening(server.address().port)
|
|
61
|
+
signal.addEventListener('abort', () => server.close(() => resolve()), { once: true })
|
|
62
|
+
if (signal.aborted) server.close(() => resolve())
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
}
|