@rhizogrip/spore-plugin-teams 0.0.0-stage → 0.2.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 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
@@ -0,0 +1,2 @@
1
+ spore-plugin-teams
2
+ Copyright 2026 Christophe Le Bars <clb@toort.net>
package/README.md CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # @rhizogrip/spore-plugin-teams
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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**, made in the Azure portal with *Single Tenant*
22
+ as its type and a new Microsoft App ID — Microsoft no longer makes multi-tenant bots, and the
23
+ service asks your tenant for its token. Its app registration in Entra ID gives the bot file its
24
+ `app` (the Microsoft App ID), its `tenant`, and a client secret — the secret's value, kept in
25
+ `environment` under the variable `secret` names. The Azure Bot's messaging endpoint is a public
26
+ HTTPS address of yours, which your proxy forwards to `listen` — a loopback address: the service
27
+ never faces the internet itself. With nginx, a path per bot:
28
+
29
+ ```nginx
30
+ location = /ops/api/messages { proxy_pass http://127.0.0.1:3978/api/messages; }
31
+ ```
32
+
33
+ Turn on the Azure Bot's Microsoft Teams channel. Then a Teams app for the bot, in the Teams
34
+ Developer Portal: under App features, a bot with the Microsoft App ID, in the personal and team
35
+ scopes. A manifest of version 1.25 or later with the team scope must say
36
+ `"supportsChannelFeatures": "tier1"`, or Teams refuses the package; it lets the app into private
37
+ and shared channels too, which the service does not serve yet, so leave it out of those. Publish
38
+ it to your organization and approve it in the Teams admin center, under Manage apps: an app
39
+ uploaded for one person can stay blocked by the tenant's app policies.
40
+
41
+ Every activity is checked before it is read: a token Microsoft signed for this app id, with a key
42
+ it endorses for Teams, for the `serviceUrl` the activity names. One that fails is answered 401 and
43
+ logged with what failed. An activity from another tenant than the bot's is dropped and logged.
44
+
45
+ `spore service define` first runs the service's checks (`--check`), which ask Microsoft for the
46
+ bot's token: a wrong app id, tenant or secret is refused there, with exit status 2.
47
+
48
+ ## People and channels
49
+
50
+ ```json
51
+ { "app": "…", "tenant": "…", "secret": "${OPS_TEAMS_SECRET}", "listen": "127.0.0.1:3978",
52
+ "people": { "3f2b…-object-id": "triage", "8a41…-object-id": { "spore": "ledger", "details": true } },
53
+ "channels": { "19:a1b2…@thread.tacv2": { "spores": ["triage"], "people": ["3f2b…-object-id", "*"] } } }
54
+ ```
55
+
56
+ `people` is each person's personal chat with the bot, by their Entra object id, and the spore it
57
+ reaches. `channels` is each standard channel by its id — in the channel's link, `19:…@thread.tacv2`
58
+ — with its one spore and `people`, who may address it there: object ids, or `"*"` for everyone in
59
+ the channel, written out. A channel has one spore: the bot speaks there as itself, so a second spore
60
+ is a second bot. `details` shows the calls themselves in the `working…` message rather than their
61
+ kinds. The file is read on every message, so a person or a channel is added by editing a line.
62
+
63
+ A bot that serves people who should see their answers and not the machinery takes `"brief": true`
64
+ beside `people` and `channels`: each conversation is then told its spore's state and its answers,
65
+ and nothing of how it runs. `/status` says `working`, `idle`, `paused` or how many messages wait —
66
+ never the model, the spend, the turns or the limits; an answer comes without how the turn ended, a
67
+ turn with none says `no answer this time` and the log says why; a limit reached shows as `wrapping
68
+ up`; and `/extend` is not offered, since what a turn may spend is yours. A person or a channel takes
69
+ `"brief"` as well, `false` to be told everything in a brief bot; `details` is refused beside it.
70
+
71
+ Someone not in the file gets silence, and the log gets the line to add:
72
+
73
+ ```
74
+ refused Alice Martin (3f2b…) — to allow them, add "3f2b…": "<a spore>" to the people of …/teams/ops.json
75
+ ```
76
+
77
+ which is also how you learn object ids: start with `"people": {}` and write to the bot.
78
+
79
+ ## A turn
80
+
81
+ In a personal chat, anything written reaches the spore. In a channel, a message reaches it when
82
+ it mentions the bot, and the mention is not part of what the spore is told; the spore is told who
83
+ wrote and where. The bot posts `working…` and shows what kind of call runs as it runs; the answer
84
+ is a new message — in a channel, in the thread of the message it answers — and `working…` is then
85
+ removed, or marked `answered below` where Teams will not remove it; in a channel thread, Teams shows
86
+ `This message has been deleted.` where it was. The answer is sent as Teams
87
+ markdown. What the turn left in `data/out/` is named, one line a file: files do not cross yet,
88
+ either way.
89
+
90
+ ```
91
+ /status what the spore is doing, its turns and what they cost, and the running turn's limits
92
+ /stop end the turn it is running, and set aside what you sent that it had not read
93
+ /wrap [10m] ask the running turn to wrap up, now or in a while
94
+ /extend wall 30m give it more — wall, cost or rounds — up to the extend.<limit> its spore.cmk grants
95
+ ```
96
+
97
+ In a channel, after the mention; there `/stop`, `/wrap` and `/extend` are for the people the
98
+ channel lists by id, not everyone `"*"` lets talk.
99
+
100
+ ## Turns nobody in Teams started
101
+
102
+ A schedule, a job or a webhook starts a turn no one in Teams asked for. Its answer goes to the
103
+ spore's `replyTo` in `config.json`: `teams:<bot>/<object id>` for a person — the bot opens a
104
+ personal chat with them if they never wrote to it — or `teams:<bot>/<channel id>`, a new post in
105
+ the channel. A place this bot's file does not route to the spore is refused, and the log says why.
106
+
107
+ ## What it guarantees
108
+
109
+ - **A message reaches its spore once,** under `teams:<conversation id>:<activity id>` as its
110
+ `requestId`, and Microsoft's delivery is answered only once the spore has it: one Microsoft sends
111
+ again is not said twice.
112
+ - **A finished turn reaches its conversation at least once.** What it owes a conversation is an
113
+ entry in the spore's outbox, settled only once Teams took it; one the service was posting when it
114
+ stopped is posted again opening with `(this may repeat an earlier message)`. One Teams refuses is
115
+ settled refused with Teams' reason; a rate limit is waited out, as long as Teams says.
116
+ - **An answer never waits behind progress.** Under a rate limit the `working…` edits are dropped.
117
+
118
+ ## Not yet
119
+
120
+ Group chats (logged and left), private and shared channels, files in either direction, and a bot
121
+ serving tenants other than its own.
122
+
123
+ ## What it keeps
124
+
125
+ `$XDG_STATE_HOME/spore/teams/<bot>/state.json`, mode 0600: where it stands in each spore, the
126
+ `working…` messages waiting for an answer, each person's chat with the bot and each channel's
127
+ service address, as Teams last gave them.
128
+
129
+ 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.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.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.23.0"
32
+ },
33
+ "scripts": {
34
+ "test": "vitest run"
35
+ },
36
+ "spore": {
37
+ "works": "^1.23.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,258 @@
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', 'brief']
12
+ const CHANNEL_FIELDS = ['spores', 'people', 'details', 'brief']
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 flags = (path, kind, id, entry) => {
26
+ for (const name of ['details', 'brief']) {
27
+ if (entry[name] !== undefined && typeof entry[name] !== 'boolean') throw invalid(path, `has a ${kind} ${id} whose ${name} is not true or false`)
28
+ }
29
+ }
30
+
31
+ const strays = (path, kind, id, entry, takes) => {
32
+ const extra = Object.keys(entry).filter(key => !takes.includes(key))
33
+ if (!extra.length) return
34
+ const bots = extra.filter(key => FIELDS.includes(key))
35
+ 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` : ''}`)
36
+ }
37
+
38
+ /** Where the service listens, `<loopback host>:<port>`: the operator's proxy is what faces Microsoft. */
39
+ export function listenOf (raw, path) {
40
+ const found = /^(.+):(\d+)$/.exec(raw.listen ?? '')
41
+ const host = found?.[1].replace(/^\[(.*)\]$/, '$1')
42
+ if (!found || !LOOPBACK.has(host) || Number(found[2]) > 65535) {
43
+ 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')
44
+ }
45
+ return { host, port: Number(found[2]) }
46
+ }
47
+
48
+ /**
49
+ * The bot's app and tenant, where it listens, and its routing: `people`, each person's personal
50
+ * chat by their Entra object id — `"<spore>"` or `{ "spore", "details", "brief" }` — and `channels`,
51
+ * each standard channel by its id, with its one spore and who may address it there: object ids, or
52
+ * `*` for everyone in the channel. `details` shows the calls themselves rather than their kinds;
53
+ * `brief` is the bot's own, for this conversation.
54
+ */
55
+ function routes (raw, path) {
56
+ for (const field of ['app', 'tenant']) {
57
+ 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'}`)
58
+ }
59
+ listenOf(raw, path)
60
+ if (raw.people === undefined && raw.channels === undefined) {
61
+ 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`)
62
+ }
63
+ const entries = (field) => {
64
+ const value = raw[field] ?? {}
65
+ if (!record(value)) throw invalid(path, `has ${field} that is not { "<id>": … }`)
66
+ return Object.entries(value)
67
+ }
68
+ const table = new Map()
69
+ for (const [person, entry] of entries('people')) {
70
+ 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')
71
+ if (record(entry)) {
72
+ strays(path, 'person', person, entry, PERSON_FIELDS)
73
+ flags(path, 'person', person, entry)
74
+ }
75
+ const spore = record(entry) ? entry.spore : entry
76
+ 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 }')
77
+ table.set(person, { spores: [spore], details: record(entry) && entry.details === true, show: null, brief: record(entry) ? entry.brief ?? null : null, people: null, overhear: false })
78
+ }
79
+ for (const [channel, entry] of entries('channels')) {
80
+ 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')
81
+ if (!record(entry)) throw invalid(path, `has a channel ${channel} that is not { "spores": [...], "people": [...] }`)
82
+ strays(path, 'channel', channel, entry, CHANNEL_FIELDS)
83
+ flags(path, 'channel', channel, entry)
84
+ 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`)
85
+ 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')
86
+ if (!Array.isArray(entry.people) || !entry.people.every(who => who === '*' || (typeof who === 'string' && PERSON.test(who)))) {
87
+ 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')
88
+ }
89
+ table.set(channel, { spores: entry.spores, details: entry.details === true, show: null, brief: entry.brief ?? null, people: entry.people, overhear: false })
90
+ }
91
+ return table
92
+ }
93
+
94
+ 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'
95
+ const EXTEND = '/extend wall 30m gives it more, as far as its spore.cmk allows'
96
+
97
+ export const TEAMS = {
98
+ kind: 'teams',
99
+ label: 'Teams',
100
+ noun: 'conversation',
101
+ fields: FIELDS,
102
+ credentials: ['secret'],
103
+ stateFields: ['chats', 'channels'],
104
+ sourceVariables: [],
105
+ refusals: ['TEAMS_REFUSED', 'TEAMS_LISTEN_REFUSED'],
106
+ example: SHAPE,
107
+ routes,
108
+ routeOf: (conversation) => conversation.split(THREAD)[0],
109
+ usage: { help: `${HELP}; ${EXTEND}.`, briefHelp: `${HELP}.`, extend: '/extend wall 30m, /extend cost 1.50 or /extend rounds 20' },
110
+ limits: { message: 40000, file: 0, editEveryMs: 2500, typingEveryMs: 4000 },
111
+ can: { upload: false, remove: true, react: false, typing: false, reply: true },
112
+ reactions: null,
113
+ showShared: 'working',
114
+ hint (err, { file }) {
115
+ if (err.type === 'TEAMS_NO_BOT') return `mkdir -p ${file.slice(0, file.lastIndexOf('/'))} — then ${file} as ${SHAPE}`
116
+ 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'
117
+ if (err.type === 'TEAMS_LISTEN_REFUSED') return `another process holds that address — change listen in ${file}`
118
+ return null
119
+ },
120
+ refusal: (message, botFile) => message.shared
121
+ ? `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}`
122
+ : `refused ${message.person.name} (${message.person.id}) — to allow them, add "${message.person.id}": "<a spore>" to the people of ${botFile}`
123
+ }
124
+
125
+ const ENTITIES = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': '\'', '&nbsp;': ' ' }
126
+
127
+ /** Teams' markup made plain: the bot's own mention gone, anyone else's as `@name`, tags dropped. */
128
+ const plain = (html, own) => html
129
+ .replace(/<at[^>]*>(.*?)<\/at>/gis, (whole, name) => own.includes(whole) ? '' : `@${name}`)
130
+ .replace(/<br\s*\/?>|<\/p>/gi, '\n')
131
+ .replace(/<[^>]+>/g, '')
132
+ .replace(/&(amp|lt|gt|quot|#39|nbsp);/g, (entity) => ENTITIES[entity])
133
+ .replace(/\n{3,}/g, '\n\n')
134
+ .trim()
135
+
136
+ /**
137
+ * A message activity as the relay takes it, or null for none it takes: one in a personal chat
138
+ * reaches the person's spore; one in a channel reaches the channel's when it mentions the bot,
139
+ * and names no spore otherwise.
140
+ */
141
+ export function normalize (activity) {
142
+ const personal = activity.conversation.conversationType === 'personal'
143
+ const own = (activity.entities ?? []).filter(entity => entity.type === 'mention' && entity.mentioned?.id === activity.recipient.id).map(entity => entity.text)
144
+ const text = plain(activity.text ?? '', own) || null
145
+ const command = text?.match(COMMAND)
146
+ const channel = activity.channelData?.channel
147
+ return {
148
+ id: `${activity.conversation.id}:${activity.id}`,
149
+ conversation: personal ? activity.from.aadObjectId : activity.conversation.id,
150
+ message: activity.id,
151
+ person: { id: activity.from.aadObjectId, name: activity.from.name, groups: [] },
152
+ spore: null,
153
+ where: personal ? 'a personal chat in Teams' : channel?.name ? `the Teams channel "${channel.name}"` : 'a Teams channel',
154
+ shared: !personal,
155
+ text,
156
+ command: command ? { verb: command[1].toLowerCase(), args: command[2] ?? '' } : null,
157
+ addresses: personal || own.length ? null : [],
158
+ files: (activity.attachments ?? []).filter(attachment => attachment.contentType !== 'text/html').length
159
+ }
160
+ }
161
+
162
+ const tenantOf = (activity) => activity.conversation?.tenantId ?? activity.channelData?.tenant?.id
163
+
164
+ /**
165
+ * The live adapter. `receive({ onActivity, signal, log })` is the transport — the listener, or a
166
+ * test's — and hands over each activity already checked. A post to a person goes to the chat they
167
+ * have with the bot, made when there is none yet; to a channel thread, into the thread; to a
168
+ * channel, as a new post. A note is `<conversation id> <activity id>`, where the post went.
169
+ */
170
+ export function createAdapter ({ connector, receive, app, tenant }) {
171
+ let kept = null
172
+ let save = null
173
+
174
+ /** What came with an activity that says where to answer: the person's chat, or the channel's service. */
175
+ const remember = (activity) => {
176
+ const { serviceUrl } = activity
177
+ if (activity.conversation.conversationType === 'personal' && activity.from.aadObjectId) {
178
+ const was = kept.chats[activity.from.aadObjectId]
179
+ if (was?.conversation === activity.conversation.id && was.serviceUrl === serviceUrl) return
180
+ kept.chats[activity.from.aadObjectId] = { conversation: activity.conversation.id, serviceUrl }
181
+ save()
182
+ } else if (activity.channelData?.channel?.id) {
183
+ const channel = activity.channelData.channel.id
184
+ if (kept.channels[channel]?.serviceUrl === serviceUrl) return
185
+ kept.channels[channel] = { serviceUrl }
186
+ save()
187
+ }
188
+ }
189
+
190
+ const serviceOf = (conversation) => conversation.startsWith('19:')
191
+ ? kept.channels[conversation.split(THREAD)[0]]?.serviceUrl ?? SERVICE_URL
192
+ : kept.chats[conversation]?.serviceUrl ?? SERVICE_URL
193
+
194
+ const chatOf = async (person) => {
195
+ if (!kept.chats[person]) {
196
+ const made = await connector.create(SERVICE_URL, { bot: { id: `28:${app}` }, members: [{ id: person }], channelData: { tenant: { id: tenant } }, isGroup: false })
197
+ kept.chats[person] = { conversation: made.id, serviceUrl: SERVICE_URL }
198
+ save()
199
+ }
200
+ return kept.chats[person].conversation
201
+ }
202
+
203
+ const placeOf = (note) => {
204
+ const at = note.lastIndexOf(' ')
205
+ return { conversation: note.slice(0, at), id: note.slice(at + 1) }
206
+ }
207
+
208
+ const activity = (text, { markdown = false, answering = null } = {}) => ({
209
+ type: 'message',
210
+ text,
211
+ textFormat: markdown ? 'markdown' : 'plain',
212
+ ...(answering === null ? {} : { replyToId: answering })
213
+ })
214
+
215
+ return {
216
+ ...TEAMS,
217
+
218
+ restore (state, persist) {
219
+ kept = state
220
+ save = persist
221
+ },
222
+
223
+ listen: ({ onMessage, signal, log }) => receive({
224
+ signal,
225
+ log,
226
+ onActivity: async (one) => {
227
+ if (tenantOf(one) !== tenant) return log(`dropped an activity from tenant ${tenantOf(one)}: this bot serves ${tenant}`)
228
+ remember(one)
229
+ if (one.type !== 'message') return
230
+ if (one.conversation.conversationType === 'groupChat') return log(`group chat ${one.conversation.id}: group chats are not served yet`)
231
+ if (!one.from?.aadObjectId) return log(`a message in ${one.conversation.id} from ${one.from?.name ?? 'someone'} with no Entra object id, not taken`)
232
+ await onMessage(normalize(one))
233
+ }
234
+ }),
235
+
236
+ post: async (conversation, text, { answering = null, markdown = false } = {}) => {
237
+ if (!conversation.startsWith('19:')) {
238
+ const chat = await chatOf(conversation)
239
+ return `${chat} ${await connector.send(serviceOf(conversation), chat, activity(text, { markdown, answering }))}`
240
+ }
241
+ if (conversation.includes(THREAD)) {
242
+ return `${conversation} ${await connector.send(serviceOf(conversation), conversation, activity(text, { markdown, answering }))}`
243
+ }
244
+ const made = await connector.create(serviceOf(conversation), { isGroup: true, channelData: { channel: { id: conversation }, tenant: { id: tenant } }, activity: activity(text, { markdown }) })
245
+ return `${made.id} ${made.activityId}`
246
+ },
247
+
248
+ edit: async (conversation, note, text) => {
249
+ const where = placeOf(note)
250
+ await connector.update(serviceOf(conversation), where.conversation, where.id, { ...activity(text), id: where.id })
251
+ },
252
+
253
+ remove: async (conversation, note) => {
254
+ const where = placeOf(note)
255
+ await connector.remove(serviceOf(conversation), where.conversation, where.id)
256
+ }
257
+ }
258
+ }
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
+ }