fusion-channel 0.1.8__tar.gz
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.
- fusion_channel-0.1.8/LICENSE +201 -0
- fusion_channel-0.1.8/PKG-INFO +236 -0
- fusion_channel-0.1.8/README.md +198 -0
- fusion_channel-0.1.8/pyproject.toml +90 -0
- fusion_channel-0.1.8/setup.cfg +4 -0
- fusion_channel-0.1.8/src/fusion_channel/__init__.py +83 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/__init__.py +76 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/aliyun_sms.py +141 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/dingtalk_robot.py +144 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/email_imap.py +214 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/feishu_app.py +293 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/gmail_api.py +358 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/graph_mail.py +282 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/slack_app.py +218 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/telegram_bot.py +198 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/tencent_sms.py +159 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/twilio_sms.py +167 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/wecom_app.py +252 -0
- fusion_channel-0.1.8/src/fusion_channel/adapters/whatsapp_cloud.py +185 -0
- fusion_channel-0.1.8/src/fusion_channel/capabilities.py +171 -0
- fusion_channel-0.1.8/src/fusion_channel/cards.py +185 -0
- fusion_channel-0.1.8/src/fusion_channel/cli.py +85 -0
- fusion_channel-0.1.8/src/fusion_channel/config.py +117 -0
- fusion_channel-0.1.8/src/fusion_channel/credentials.py +196 -0
- fusion_channel-0.1.8/src/fusion_channel/fastapi.py +105 -0
- fusion_channel-0.1.8/src/fusion_channel/hooks.py +77 -0
- fusion_channel-0.1.8/src/fusion_channel/identity.py +75 -0
- fusion_channel-0.1.8/src/fusion_channel/models.py +185 -0
- fusion_channel-0.1.8/src/fusion_channel/outbox.py +187 -0
- fusion_channel-0.1.8/src/fusion_channel/registry.py +449 -0
- fusion_channel-0.1.8/src/fusion_channel/spi.py +141 -0
- fusion_channel-0.1.8/src/fusion_channel/storage.py +336 -0
- fusion_channel-0.1.8/src/fusion_channel/verify.py +211 -0
- fusion_channel-0.1.8/src/fusion_channel.egg-info/PKG-INFO +236 -0
- fusion_channel-0.1.8/src/fusion_channel.egg-info/SOURCES.txt +52 -0
- fusion_channel-0.1.8/src/fusion_channel.egg-info/dependency_links.txt +1 -0
- fusion_channel-0.1.8/src/fusion_channel.egg-info/entry_points.txt +2 -0
- fusion_channel-0.1.8/src/fusion_channel.egg-info/requires.txt +17 -0
- fusion_channel-0.1.8/src/fusion_channel.egg-info/top_level.txt +1 -0
- fusion_channel-0.1.8/tests/test_cards_matrix.py +191 -0
- fusion_channel-0.1.8/tests/test_cli.py +97 -0
- fusion_channel-0.1.8/tests/test_credentials_config.py +153 -0
- fusion_channel-0.1.8/tests/test_e2e_approval.py +397 -0
- fusion_channel-0.1.8/tests/test_email_adapter.py +273 -0
- fusion_channel-0.1.8/tests/test_gmail_api.py +401 -0
- fusion_channel-0.1.8/tests/test_graph_mail.py +346 -0
- fusion_channel-0.1.8/tests/test_hardening.py +374 -0
- fusion_channel-0.1.8/tests/test_integration_email.py +128 -0
- fusion_channel-0.1.8/tests/test_integration_feishu.py +30 -0
- fusion_channel-0.1.8/tests/test_outbox.py +166 -0
- fusion_channel-0.1.8/tests/test_registry_inbound.py +331 -0
- fusion_channel-0.1.8/tests/test_review_fixes.py +546 -0
- fusion_channel-0.1.8/tests/test_sms_adapters.py +283 -0
- fusion_channel-0.1.8/tests/test_verify_signatures.py +124 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated, in writing by the copyright owner, as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Support. While redistributing the Work or
|
|
166
|
+
Derivative Works thereof, You may choose to offer, and charge a
|
|
167
|
+
fee for, acceptance of support, warranty, indemnity, or other
|
|
168
|
+
liability obligations and/or rights consistent with this License.
|
|
169
|
+
However, in accepting such obligations, You may act only on Your
|
|
170
|
+
own behalf and on Your sole responsibility, not on behalf of any
|
|
171
|
+
other Contributor, and only if You agree to indemnify, defend,
|
|
172
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
173
|
+
or claims asserted against, such Contributor by reason of your
|
|
174
|
+
accepting any such warranty or support.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 dahai80
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
200
|
+
implied. See the License for the specific language governing
|
|
201
|
+
permissions and limitations under the License.
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fusion-channel
|
|
3
|
+
Version: 0.1.8
|
|
4
|
+
Summary: Fusion-Channel — unified messaging channel access layer for the Fusion ecosystem (webhook verification, outbox, dedup, cards, identity mapping)
|
|
5
|
+
Author: dahai80
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/dahai80/fusion-channel
|
|
8
|
+
Project-URL: Repository, https://github.com/dahai80/fusion-channel
|
|
9
|
+
Project-URL: Issues, https://github.com/dahai80/fusion-channel/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/dahai80/fusion-channel/releases
|
|
11
|
+
Keywords: messaging,sms,im,webhook,twilio,feishu,dingtalk,slack,wecom,telegram,whatsapp,email,imap,gmail,microsoft-graph,outbox
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Communications
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: httpx<1.0,>=0.27.0
|
|
23
|
+
Requires-Dist: pydantic>=2.0.0
|
|
24
|
+
Requires-Dist: cryptography>=42.0.0
|
|
25
|
+
Requires-Dist: aiosqlite>=0.20.0
|
|
26
|
+
Requires-Dist: PyYAML>=6.0
|
|
27
|
+
Provides-Extra: fastapi
|
|
28
|
+
Requires-Dist: fastapi>=0.110.0; extra == "fastapi"
|
|
29
|
+
Requires-Dist: uvicorn[standard]>=0.29.0; extra == "fastapi"
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
32
|
+
Requires-Dist: pytest-asyncio>=1.0.0; extra == "test"
|
|
33
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == "test"
|
|
34
|
+
Requires-Dist: fastapi>=0.110.0; extra == "test"
|
|
35
|
+
Requires-Dist: httpx>=0.27.0; extra == "test"
|
|
36
|
+
Requires-Dist: ruff>=0.5.0; extra == "test"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# fusion-channel
|
|
40
|
+
|
|
41
|
+
[](https://github.com/dahai80/fusion-channel/actions/workflows/ci.yml)
|
|
42
|
+
|
|
43
|
+
Unified messaging channel access layer for the Fusion ecosystem ("一核九端"). One library gives any Fusion application the ability to **receive, send, join groups, be @-mentioned, and push approval buttons** across SMS and IM providers — with verification, dedup, outbox retry, rate limiting, archiving, and identity mapping built in.
|
|
44
|
+
|
|
45
|
+
> Status: v0.1.7 — M1–M3 scope landed (core abstractions + 12 first-batch adapters, including pull-mode email). The M4 bridge service is intentionally **not** built yet (library-first per the PRD); M5 ecosystem adoption happens inside consumer projects.
|
|
46
|
+
|
|
47
|
+
## Why
|
|
48
|
+
|
|
49
|
+
Fusion has 48 sub-projects; every human-facing one eventually needs an IM channel. Each provider's details differ wildly — Twilio HMAC-SHA1 form signing, Feishu AES-CBC encrypted events + challenge handshake, DingTalk HMAC-SHA256 signing, Slack request signatures, WhatsApp `X-Hub-Signature-256`, WeCom AES + SHA1 callbacks. Getting any of these wrong means "anyone can forge the owner's commands". fusion-channel centralizes them once.
|
|
50
|
+
|
|
51
|
+
Design source: the PRD at `architecture/fusion-channel-prd-1025.md` and the production-verified ai-family SMS pipeline (verification / dedup / reject-archive / outbox backoff), ported behavior-equivalent.
|
|
52
|
+
|
|
53
|
+
## Install
|
|
54
|
+
|
|
55
|
+
Requires Python >= 3.12 (the workspace pins `.python-version` to 3.12).
|
|
56
|
+
|
|
57
|
+
Requires Python >= 3.12 (the workspace pins `.python-version` to 3.12).
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
# From PyPI (published on v-tags via GitHub Actions Trusted Publishing):
|
|
61
|
+
pip install fusion-channel # add ",fastapi" extras for the webhook router
|
|
62
|
+
|
|
63
|
+
# From Homebrew (dahai80/homebrew-tap; installs into an isolated venv, exposes the CLI):
|
|
64
|
+
brew tap dahai80/fusion-channel https://github.com/dahai80/homebrew-tap
|
|
65
|
+
brew install fusion-channel
|
|
66
|
+
|
|
67
|
+
# Development (in-tree editable install with the test stack):
|
|
68
|
+
cd /Users/dahai/fusion && source .venv/bin/activate
|
|
69
|
+
pip install -e ".[test]"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
After a Homebrew (or any CLI-enabled) install, a diagnostics CLI is available:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
fusion-channel version # print version
|
|
76
|
+
fusion-channel check-config channels.yaml # validate a config + credentials at load
|
|
77
|
+
fusion-channel test-connection channels.yaml ops_dingtalk # run a channel's test_connection
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Supported channels (first batch)
|
|
81
|
+
|
|
82
|
+
| Adapter | Channel | Verify scheme | Cards | Groups |
|
|
83
|
+
|---------|---------|---------------|-------|--------|
|
|
84
|
+
| `twilio_sms` | SMS (Twilio) | HMAC-SHA1 `X-Twilio-Signature` | fallback text | – |
|
|
85
|
+
| `aliyun_sms` | SMS (Aliyun) | callback HMAC (optional) | – | – |
|
|
86
|
+
| `tencent_sms` | SMS (Tencent Cloud) | callback HMAC (optional) | – | – |
|
|
87
|
+
| `wecom_app` | WeCom self-built app | SHA1 signature + AES-256-CBC | partial (textcard) | ✅ |
|
|
88
|
+
| `feishu_app` | Feishu/Lark app | Encrypt Key AES + verification token | full | ✅ |
|
|
89
|
+
| `dingtalk_robot` | DingTalk group robot | HMAC-SHA256 signing (required) | full (ActionCard) | ✅ |
|
|
90
|
+
| `slack_app` | Slack Events API | `X-Slack-Signature` HMAC-SHA256 | full (Block Kit) | ✅ |
|
|
91
|
+
| `whatsapp_cloud` | WhatsApp Cloud API | `X-Hub-Signature-256` | fallback text | – |
|
|
92
|
+
| `telegram_bot` | Telegram Bot API | secret-token header | full (inline keyboard) | ✅ |
|
|
93
|
+
| `email_imap` | Email (IMAP/SMTP) | transport auth (TLS + login) | fallback text | – |
|
|
94
|
+
| `graph_mail` | Microsoft 365 / Exchange Online (Graph API, OAuth2 client credentials) | transport auth (OAuth2 + TLS) | fallback text | – |
|
|
95
|
+
| `gmail_api` | Gmail / Google Workspace (Gmail API, OAuth2 refresh token) | transport auth (OAuth2 + TLS) | fallback text | – |
|
|
96
|
+
|
|
97
|
+
**Compliance red line:** no personal-WeChat reverse-engineered protocols. Official APIs only.
|
|
98
|
+
|
|
99
|
+
## Quick start
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from fusion_channel import ChannelRegistry, ApprovalCard, CardAction
|
|
103
|
+
from fusion_channel.credentials import AESGCMCredentialProvider
|
|
104
|
+
from fusion_channel.storage import SqliteStore
|
|
105
|
+
|
|
106
|
+
store = SqliteStore("channel.db")
|
|
107
|
+
await store.init()
|
|
108
|
+
registry = ChannelRegistry.from_config(
|
|
109
|
+
"channels.yaml", # PRD §4.3 data-driven config
|
|
110
|
+
credentials=AESGCMCredentialProvider("data/secrets"),
|
|
111
|
+
store=store,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# --- inbound: FastAPI webhook in one line ---
|
|
115
|
+
from fusion_channel.fastapi import build_channel_router
|
|
116
|
+
|
|
117
|
+
app.include_router(build_channel_router(registry)) # POST /webhook/{channel_id}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# --- handlers: card buttons and text commands converge here ---
|
|
121
|
+
async def on_interaction(interaction):
|
|
122
|
+
code = interaction.payload.get("code") or interaction.payload.get("value") or ""
|
|
123
|
+
print("approval", code, interaction.action) # one state machine, all channels
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
registry.on_interaction(on_interaction)
|
|
127
|
+
registry.register_command("approve", ["同意", "approve"], code_required=True)
|
|
128
|
+
registry.register_command("reject", ["拒绝", "reject"], code_required=True)
|
|
129
|
+
registry.on_message(lambda env: print(env.channel_id, env.text))
|
|
130
|
+
|
|
131
|
+
# --- outbound: outbox semantics, card degradation automatic ---
|
|
132
|
+
await registry.send(
|
|
133
|
+
"family_twilio",
|
|
134
|
+
{"type": "direct", "id": "+15550000001->+15550000000"},
|
|
135
|
+
card=ApprovalCard(
|
|
136
|
+
title="审批 AP-123456",
|
|
137
|
+
code="AP-123456",
|
|
138
|
+
body="New caregiver profile",
|
|
139
|
+
actions=[CardAction(action="approve", label="同意"), CardAction(action="reject", label="拒绝")],
|
|
140
|
+
),
|
|
141
|
+
)
|
|
142
|
+
sent = await registry.outbox.flush_once() # or run_loop() in background
|
|
143
|
+
|
|
144
|
+
# --- identity: external id -> fusion-identity account ---
|
|
145
|
+
user = registry.identify("family_twilio", "+15550000001")
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Full runnable example: `examples/approve_bot.py` with `examples/channels.yaml`. Wiring a consumer service (outbox worker lifecycle, delivery-status receipts, Postgres-backed store, credential isolation): `docs/consumer-integration.md`.
|
|
149
|
+
|
|
150
|
+
## Architecture
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
ChannelRegistry ── ChannelAdapter(SPI) ── 12 provider adapters
|
|
154
|
+
│ │
|
|
155
|
+
IdentityMapper SignatureVerifier (per-channel policy)
|
|
156
|
+
│ │
|
|
157
|
+
CredentialProvider DedupGuard / ReplayGuard
|
|
158
|
+
│ │
|
|
159
|
+
ArchiveHook OutboxSender (backoff retry / token bucket / degradation)
|
|
160
|
+
│
|
|
161
|
+
AuditHook CardRenderer (per CAN_CARDS degradation)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Non-negotiable rules baked into the library (PRD §4.2 / §7.1):
|
|
165
|
+
|
|
166
|
+
1. **Verification is mandatory at the SPI level** — an adapter class that does not implement `verify_request` cannot be registered (`ConfigError`).
|
|
167
|
+
2. **Archive-first** — inbound messages are persisted with the raw payload before business processing; duplicates are counted, never dropped.
|
|
168
|
+
3. **Rejected requests are archived too** (`RejectedEnvelope`) so attacks and lost messages are auditable.
|
|
169
|
+
4. **Outbox pattern** — send intents enqueue first; the flush loop retries with `[30, 120, 600]`s backoff, 3 attempts max, then fires `on_permanent_failure` (the ai-family alert pattern). Records are CAS-claimed (`pending` → `sending` lease) so two workers never double-send; a crashed worker's lease expires and the record requeues; pending records older than 24h fail permanently.
|
|
170
|
+
5. **Degradation is rendering, not business logic** — consumers always ask for a card; `CAN_CARDS=none` channels get the fallback text ("回复 同意 AP-123456"), and the reply parses back into the same `Interaction`.
|
|
171
|
+
6. **Credentials never live in the library** — `CredentialProvider` interface with an AES-256-GCM file-backed default (0600 key, atomic writes); reads through it return masked values.
|
|
172
|
+
7. **Fail closed** — verification/parse exceptions on attacker input reject-archive and return 4xx (never 500); webhook bodies over 1 MiB get 413; adapter error strings are secret-redacted before they reach logs or `SendResult`.
|
|
173
|
+
8. **Identity gate** — set `require_bound_identity: true` on a channel to dispatch interactions (card buttons + text commands) only for senders present in `identity_bindings`; unbound senders get 403 `identity_not_bound` plus an audit event.
|
|
174
|
+
|
|
175
|
+
Config details:
|
|
176
|
+
|
|
177
|
+
- **Credential refs**: each credential value may be `env:VAR_NAME` (read from the environment), a `CredentialProvider` key, or a plain literal (used as-is when no provider entry matches).
|
|
178
|
+
- **Archive modes**: `inbound.archive: full` (default, raw payload kept) / `metadata-only` (content and raw payload stripped at archive time; handlers still see the full envelope) / `off` (dedup record only).
|
|
179
|
+
- **Replay windows**: Slack / DingTalk / WeCom signatures older than 300s are rejected.
|
|
180
|
+
|
|
181
|
+
## Group & bot capabilities
|
|
182
|
+
|
|
183
|
+
- Conversation types: `direct` / `group` / `broadcast`.
|
|
184
|
+
- Watched-group allowlist (`groups:` in config) — unlisted groups are archived and ignored.
|
|
185
|
+
- `mentions_required: true` gates group messages on @bot.
|
|
186
|
+
- `group_ops()` on CAN_GROUP adapters: `list()` / `info()` / `broadcast()`; raises `CapabilityNotSupported` elsewhere so consumers can fall back to per-direct sends.
|
|
187
|
+
|
|
188
|
+
## Pull-mode channels (email)
|
|
189
|
+
|
|
190
|
+
Webhook channels get requests pushed; `email_imap` pulls instead. Adapters that override `ChannelAdapter.poll()` fetch their own messages (IMAP `UNSEEN`, batch-limited) and return them as raw requests — the registry runs each through the exact same `handle_inbound` pipeline (dedup, archive, commands, identity gate). There is no webhook signature to verify; TLS + account login are the trust boundary, and email `verify_request` always passes (logged). MIME handling stays thin: `text/plain` extraction plus attachment `MediaRef`s, `In-Reply-To` mapped to `conversation.thread_id`. Outbound goes through the same outbox (SMTP + STARTTLS); set the subject via `meta={"subject": ...}` or it defaults to the first line of the text.
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
await registry.poll() # one-shot: fetch + dispatch
|
|
194
|
+
registry.start_polling(interval=60) # background worker; close() cancels it
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`graph_mail` is the Microsoft 365 / Exchange Online variant: M365 has basic auth disabled, so IMAP password login cannot connect. It polls the same way via Microsoft Graph with OAuth2 client credentials (`tenant_id` / `client_id` / `client_secret` / `mailbox`; register an Entra ID app with the `Mail.ReadWrite` application permission on the shared mailbox). Config keys: `folder` (default `INBOX`), `poll_batch_limit` (default 20). Unread messages are fetched as full MIME, then marked read so re-poll dedup matches `email_imap` semantics; Graph attachment refs land in `MediaRef` and consumers can pull real bytes with `adapter.download_attachment(graph_message_id, attachment_id)` — the document-pipeline path for emailed PDFs. Outbound uses `POST /users/{mailbox}/sendMail`; subject rules match `email_imap`.
|
|
198
|
+
|
|
199
|
+
`gmail_api` is the Gmail / Google Workspace variant, also pull-mode with OAuth2 (`client_id` / `client_secret` / `refresh_token` / `user_id`; a Google Cloud OAuth client with the `gmail.readonly` + `gmail.send` scopes — service accounts with domain-wide delegation work through the same refresh-token contract). Config keys: `label_ids` (default `INBOX, UNREAD`), `query` (optional Gmail search filter), `poll_batch_limit` (default 25), `history_id` (seed for incremental sync), `draft_mode` (send creates a draft instead of sending — the human-approval path). Polling uses `historyId` incremental sync when a previous poll recorded one, falling back to the full label list when the history window has expired; messages are fetched `format=full` (attachment ids live in the payload parts), then have `UNREAD` stripped via `modifyLabels` so re-poll dedup matches `email_imap` semantics. 429 quota responses back off to the next poll cycle instead of crashing the loop. `threadId` and `In-Reply-To` both surface on the envelope (`conversation.thread_id` + `raw.gmail_thread_id`); attachment bytes come via `adapter.download_attachment(gmail_message_id, attachment_id)`. Outbound uses `POST .../messages/send` (or `drafts/create` in draft mode); subject rules match `email_imap`.
|
|
200
|
+
|
|
201
|
+
## Capability matrix
|
|
202
|
+
|
|
203
|
+
Every adapter declares `ChannelCapabilities` (CAN_RECEIVE / CAN_SEND / CAN_GROUP / CAN_BOT / CAN_MENTION / CAN_CARDS / CAN_MEDIA / CAN_RECEIPT / CAN_THREADS) — see `src/fusion_channel/capabilities.py`. Consumers branch on capabilities, never on adapter identity. Config `capabilities_override` tweaks per channel instance.
|
|
204
|
+
|
|
205
|
+
## Relationship to other Fusion components
|
|
206
|
+
|
|
207
|
+
- **fusion-core**: same in-tree distribution mode (`pip install -e`); no reverse dependency.
|
|
208
|
+
- **fusion-identity**: `IdentityMapper` maps external ids to identity accounts; RBAC stays in fusion-identity (`assert_bound_identity()` provides the two-factor primitive for sensitive commands).
|
|
209
|
+
- **fusion-gateway**: deliberately does **not** use its connector framework (no IM concepts, no verification, no background model).
|
|
210
|
+
- **ai-family**: first consumer + code donor (verification/dedup/outbox/secret-store semantics ported). Its switch-over is tracked in its own repo (PRD §11).
|
|
211
|
+
|
|
212
|
+
## Development
|
|
213
|
+
|
|
214
|
+
```bash
|
|
215
|
+
source /Users/dahai/fusion/.venv/bin/activate
|
|
216
|
+
pytest tests/ # 196 tests: crypto vectors, webhook E2E, outbox, matrix, hardening, email
|
|
217
|
+
pytest tests/test_e2e_approval.py -v # cross-channel approval acceptance
|
|
218
|
+
ruff check . && ruff format --check . # lint
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Test coverage highlights:
|
|
222
|
+
|
|
223
|
+
- Real signature vectors for every channel (including Feishu/WeCom AES-CBC round-trips, Slack replay-window rejection, DingTalk ms-timestamp handling, Aliyun RFC3986 percent-encoding).
|
|
224
|
+
- FastAPI TestClient E2E: signed webhook → verify → parse → dedup → archive → handler; bad signature → 403 + reject archive; duplicate → 200, no redispatch; internal errors → reject-archive + 400, never 500.
|
|
225
|
+
- GET handshakes: WeCom `echostr` URL verification and WhatsApp `hub.challenge` echo (token-checked), via the router's GET route.
|
|
226
|
+
- Delivery receipts (Twilio `MessageStatus`, WhatsApp `statuses`) are archived as receipts, never dispatched as messages; challenge retries always re-echo (never deduped).
|
|
227
|
+
- Cross-channel approval acceptance: the same `AP-123456` decision arrives via SMS text, Slack Block Kit button, DingTalk signed command, Telegram inline keyboard, WhatsApp text, WeCom encrypted callback, Feishu group mention, and Feishu card button callback — one handler, one state machine.
|
|
228
|
+
- Outbound E2E via `httpx.MockTransport`: Twilio/Feishu/Slack provider payload shapes asserted; `test_connection()` smoke-tested per adapter (DingTalk's is static — a robot send always lands in a real group).
|
|
229
|
+
- Email (`email_imap`): MIME parse (text extraction, attachments, In-Reply-To threading), SMTP send with subject/In-Reply-To headers, fake-transport E2E through `registry.poll()` including dedup on re-poll, fetch-error isolation, card-fallback outbox send, polling worker lifecycle.
|
|
230
|
+
- Microsoft 365 (`graph_mail`): mocked Graph HTTP via `httpx.MockTransport` — OAuth2 client-credentials token fetch + caching + 401 refresh, unread list → MIME fetch → mark-read verified, Graph attachment refs into `MediaRef`, `download_attachment()` bytes, registry poll dispatch + dedup on re-poll, mark-read-failure dedup fallback, `sendMail` payload shape, credentials-missing and provider-error paths.
|
|
231
|
+
- Gmail (`gmail_api`): mocked Gmail HTTP via `httpx.MockTransport` — OAuth2 refresh-token token fetch + caching + 401 refresh, label list → `format=full` fetch → `modifyLabels` UNREAD-strip verified, historyId incremental sync + 404 gap fallback to full list, 429 backoff on list and per-message fetch, `threadId`/`In-Reply-To` threading, `download_attachment()` bytes, registry poll dispatch + dedup on re-poll, label-strip-failure dedup fallback, `messages.send` raw MIME shape, `drafts.create` draft mode, credentials-missing and provider-error paths.
|
|
232
|
+
- Live provider calls require sandbox credentials and are marked `integration` (excluded by default): Feishu tenant-token handshake; QQ Mail real IMAP/SMTP E2E (login + poll + dedup on the live INBOX, SMTP send-to-self with loopback receive, env-based credentials `FUSION_CHANNEL_QQ_EMAIL` / `FUSION_CHANNEL_QQ_AUTH_CODE`).
|
|
233
|
+
|
|
234
|
+
## License
|
|
235
|
+
|
|
236
|
+
Apache-2.0
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
# fusion-channel
|
|
2
|
+
|
|
3
|
+
[](https://github.com/dahai80/fusion-channel/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
Unified messaging channel access layer for the Fusion ecosystem ("一核九端"). One library gives any Fusion application the ability to **receive, send, join groups, be @-mentioned, and push approval buttons** across SMS and IM providers — with verification, dedup, outbox retry, rate limiting, archiving, and identity mapping built in.
|
|
6
|
+
|
|
7
|
+
> Status: v0.1.7 — M1–M3 scope landed (core abstractions + 12 first-batch adapters, including pull-mode email). The M4 bridge service is intentionally **not** built yet (library-first per the PRD); M5 ecosystem adoption happens inside consumer projects.
|
|
8
|
+
|
|
9
|
+
## Why
|
|
10
|
+
|
|
11
|
+
Fusion has 48 sub-projects; every human-facing one eventually needs an IM channel. Each provider's details differ wildly — Twilio HMAC-SHA1 form signing, Feishu AES-CBC encrypted events + challenge handshake, DingTalk HMAC-SHA256 signing, Slack request signatures, WhatsApp `X-Hub-Signature-256`, WeCom AES + SHA1 callbacks. Getting any of these wrong means "anyone can forge the owner's commands". fusion-channel centralizes them once.
|
|
12
|
+
|
|
13
|
+
Design source: the PRD at `architecture/fusion-channel-prd-1025.md` and the production-verified ai-family SMS pipeline (verification / dedup / reject-archive / outbox backoff), ported behavior-equivalent.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
Requires Python >= 3.12 (the workspace pins `.python-version` to 3.12).
|
|
18
|
+
|
|
19
|
+
Requires Python >= 3.12 (the workspace pins `.python-version` to 3.12).
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
# From PyPI (published on v-tags via GitHub Actions Trusted Publishing):
|
|
23
|
+
pip install fusion-channel # add ",fastapi" extras for the webhook router
|
|
24
|
+
|
|
25
|
+
# From Homebrew (dahai80/homebrew-tap; installs into an isolated venv, exposes the CLI):
|
|
26
|
+
brew tap dahai80/fusion-channel https://github.com/dahai80/homebrew-tap
|
|
27
|
+
brew install fusion-channel
|
|
28
|
+
|
|
29
|
+
# Development (in-tree editable install with the test stack):
|
|
30
|
+
cd /Users/dahai/fusion && source .venv/bin/activate
|
|
31
|
+
pip install -e ".[test]"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
After a Homebrew (or any CLI-enabled) install, a diagnostics CLI is available:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
fusion-channel version # print version
|
|
38
|
+
fusion-channel check-config channels.yaml # validate a config + credentials at load
|
|
39
|
+
fusion-channel test-connection channels.yaml ops_dingtalk # run a channel's test_connection
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Supported channels (first batch)
|
|
43
|
+
|
|
44
|
+
| Adapter | Channel | Verify scheme | Cards | Groups |
|
|
45
|
+
|---------|---------|---------------|-------|--------|
|
|
46
|
+
| `twilio_sms` | SMS (Twilio) | HMAC-SHA1 `X-Twilio-Signature` | fallback text | – |
|
|
47
|
+
| `aliyun_sms` | SMS (Aliyun) | callback HMAC (optional) | – | – |
|
|
48
|
+
| `tencent_sms` | SMS (Tencent Cloud) | callback HMAC (optional) | – | – |
|
|
49
|
+
| `wecom_app` | WeCom self-built app | SHA1 signature + AES-256-CBC | partial (textcard) | ✅ |
|
|
50
|
+
| `feishu_app` | Feishu/Lark app | Encrypt Key AES + verification token | full | ✅ |
|
|
51
|
+
| `dingtalk_robot` | DingTalk group robot | HMAC-SHA256 signing (required) | full (ActionCard) | ✅ |
|
|
52
|
+
| `slack_app` | Slack Events API | `X-Slack-Signature` HMAC-SHA256 | full (Block Kit) | ✅ |
|
|
53
|
+
| `whatsapp_cloud` | WhatsApp Cloud API | `X-Hub-Signature-256` | fallback text | – |
|
|
54
|
+
| `telegram_bot` | Telegram Bot API | secret-token header | full (inline keyboard) | ✅ |
|
|
55
|
+
| `email_imap` | Email (IMAP/SMTP) | transport auth (TLS + login) | fallback text | – |
|
|
56
|
+
| `graph_mail` | Microsoft 365 / Exchange Online (Graph API, OAuth2 client credentials) | transport auth (OAuth2 + TLS) | fallback text | – |
|
|
57
|
+
| `gmail_api` | Gmail / Google Workspace (Gmail API, OAuth2 refresh token) | transport auth (OAuth2 + TLS) | fallback text | – |
|
|
58
|
+
|
|
59
|
+
**Compliance red line:** no personal-WeChat reverse-engineered protocols. Official APIs only.
|
|
60
|
+
|
|
61
|
+
## Quick start
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from fusion_channel import ChannelRegistry, ApprovalCard, CardAction
|
|
65
|
+
from fusion_channel.credentials import AESGCMCredentialProvider
|
|
66
|
+
from fusion_channel.storage import SqliteStore
|
|
67
|
+
|
|
68
|
+
store = SqliteStore("channel.db")
|
|
69
|
+
await store.init()
|
|
70
|
+
registry = ChannelRegistry.from_config(
|
|
71
|
+
"channels.yaml", # PRD §4.3 data-driven config
|
|
72
|
+
credentials=AESGCMCredentialProvider("data/secrets"),
|
|
73
|
+
store=store,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# --- inbound: FastAPI webhook in one line ---
|
|
77
|
+
from fusion_channel.fastapi import build_channel_router
|
|
78
|
+
|
|
79
|
+
app.include_router(build_channel_router(registry)) # POST /webhook/{channel_id}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# --- handlers: card buttons and text commands converge here ---
|
|
83
|
+
async def on_interaction(interaction):
|
|
84
|
+
code = interaction.payload.get("code") or interaction.payload.get("value") or ""
|
|
85
|
+
print("approval", code, interaction.action) # one state machine, all channels
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
registry.on_interaction(on_interaction)
|
|
89
|
+
registry.register_command("approve", ["同意", "approve"], code_required=True)
|
|
90
|
+
registry.register_command("reject", ["拒绝", "reject"], code_required=True)
|
|
91
|
+
registry.on_message(lambda env: print(env.channel_id, env.text))
|
|
92
|
+
|
|
93
|
+
# --- outbound: outbox semantics, card degradation automatic ---
|
|
94
|
+
await registry.send(
|
|
95
|
+
"family_twilio",
|
|
96
|
+
{"type": "direct", "id": "+15550000001->+15550000000"},
|
|
97
|
+
card=ApprovalCard(
|
|
98
|
+
title="审批 AP-123456",
|
|
99
|
+
code="AP-123456",
|
|
100
|
+
body="New caregiver profile",
|
|
101
|
+
actions=[CardAction(action="approve", label="同意"), CardAction(action="reject", label="拒绝")],
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
sent = await registry.outbox.flush_once() # or run_loop() in background
|
|
105
|
+
|
|
106
|
+
# --- identity: external id -> fusion-identity account ---
|
|
107
|
+
user = registry.identify("family_twilio", "+15550000001")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Full runnable example: `examples/approve_bot.py` with `examples/channels.yaml`. Wiring a consumer service (outbox worker lifecycle, delivery-status receipts, Postgres-backed store, credential isolation): `docs/consumer-integration.md`.
|
|
111
|
+
|
|
112
|
+
## Architecture
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
ChannelRegistry ── ChannelAdapter(SPI) ── 12 provider adapters
|
|
116
|
+
│ │
|
|
117
|
+
IdentityMapper SignatureVerifier (per-channel policy)
|
|
118
|
+
│ │
|
|
119
|
+
CredentialProvider DedupGuard / ReplayGuard
|
|
120
|
+
│ │
|
|
121
|
+
ArchiveHook OutboxSender (backoff retry / token bucket / degradation)
|
|
122
|
+
│
|
|
123
|
+
AuditHook CardRenderer (per CAN_CARDS degradation)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Non-negotiable rules baked into the library (PRD §4.2 / §7.1):
|
|
127
|
+
|
|
128
|
+
1. **Verification is mandatory at the SPI level** — an adapter class that does not implement `verify_request` cannot be registered (`ConfigError`).
|
|
129
|
+
2. **Archive-first** — inbound messages are persisted with the raw payload before business processing; duplicates are counted, never dropped.
|
|
130
|
+
3. **Rejected requests are archived too** (`RejectedEnvelope`) so attacks and lost messages are auditable.
|
|
131
|
+
4. **Outbox pattern** — send intents enqueue first; the flush loop retries with `[30, 120, 600]`s backoff, 3 attempts max, then fires `on_permanent_failure` (the ai-family alert pattern). Records are CAS-claimed (`pending` → `sending` lease) so two workers never double-send; a crashed worker's lease expires and the record requeues; pending records older than 24h fail permanently.
|
|
132
|
+
5. **Degradation is rendering, not business logic** — consumers always ask for a card; `CAN_CARDS=none` channels get the fallback text ("回复 同意 AP-123456"), and the reply parses back into the same `Interaction`.
|
|
133
|
+
6. **Credentials never live in the library** — `CredentialProvider` interface with an AES-256-GCM file-backed default (0600 key, atomic writes); reads through it return masked values.
|
|
134
|
+
7. **Fail closed** — verification/parse exceptions on attacker input reject-archive and return 4xx (never 500); webhook bodies over 1 MiB get 413; adapter error strings are secret-redacted before they reach logs or `SendResult`.
|
|
135
|
+
8. **Identity gate** — set `require_bound_identity: true` on a channel to dispatch interactions (card buttons + text commands) only for senders present in `identity_bindings`; unbound senders get 403 `identity_not_bound` plus an audit event.
|
|
136
|
+
|
|
137
|
+
Config details:
|
|
138
|
+
|
|
139
|
+
- **Credential refs**: each credential value may be `env:VAR_NAME` (read from the environment), a `CredentialProvider` key, or a plain literal (used as-is when no provider entry matches).
|
|
140
|
+
- **Archive modes**: `inbound.archive: full` (default, raw payload kept) / `metadata-only` (content and raw payload stripped at archive time; handlers still see the full envelope) / `off` (dedup record only).
|
|
141
|
+
- **Replay windows**: Slack / DingTalk / WeCom signatures older than 300s are rejected.
|
|
142
|
+
|
|
143
|
+
## Group & bot capabilities
|
|
144
|
+
|
|
145
|
+
- Conversation types: `direct` / `group` / `broadcast`.
|
|
146
|
+
- Watched-group allowlist (`groups:` in config) — unlisted groups are archived and ignored.
|
|
147
|
+
- `mentions_required: true` gates group messages on @bot.
|
|
148
|
+
- `group_ops()` on CAN_GROUP adapters: `list()` / `info()` / `broadcast()`; raises `CapabilityNotSupported` elsewhere so consumers can fall back to per-direct sends.
|
|
149
|
+
|
|
150
|
+
## Pull-mode channels (email)
|
|
151
|
+
|
|
152
|
+
Webhook channels get requests pushed; `email_imap` pulls instead. Adapters that override `ChannelAdapter.poll()` fetch their own messages (IMAP `UNSEEN`, batch-limited) and return them as raw requests — the registry runs each through the exact same `handle_inbound` pipeline (dedup, archive, commands, identity gate). There is no webhook signature to verify; TLS + account login are the trust boundary, and email `verify_request` always passes (logged). MIME handling stays thin: `text/plain` extraction plus attachment `MediaRef`s, `In-Reply-To` mapped to `conversation.thread_id`. Outbound goes through the same outbox (SMTP + STARTTLS); set the subject via `meta={"subject": ...}` or it defaults to the first line of the text.
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
await registry.poll() # one-shot: fetch + dispatch
|
|
156
|
+
registry.start_polling(interval=60) # background worker; close() cancels it
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
`graph_mail` is the Microsoft 365 / Exchange Online variant: M365 has basic auth disabled, so IMAP password login cannot connect. It polls the same way via Microsoft Graph with OAuth2 client credentials (`tenant_id` / `client_id` / `client_secret` / `mailbox`; register an Entra ID app with the `Mail.ReadWrite` application permission on the shared mailbox). Config keys: `folder` (default `INBOX`), `poll_batch_limit` (default 20). Unread messages are fetched as full MIME, then marked read so re-poll dedup matches `email_imap` semantics; Graph attachment refs land in `MediaRef` and consumers can pull real bytes with `adapter.download_attachment(graph_message_id, attachment_id)` — the document-pipeline path for emailed PDFs. Outbound uses `POST /users/{mailbox}/sendMail`; subject rules match `email_imap`.
|
|
160
|
+
|
|
161
|
+
`gmail_api` is the Gmail / Google Workspace variant, also pull-mode with OAuth2 (`client_id` / `client_secret` / `refresh_token` / `user_id`; a Google Cloud OAuth client with the `gmail.readonly` + `gmail.send` scopes — service accounts with domain-wide delegation work through the same refresh-token contract). Config keys: `label_ids` (default `INBOX, UNREAD`), `query` (optional Gmail search filter), `poll_batch_limit` (default 25), `history_id` (seed for incremental sync), `draft_mode` (send creates a draft instead of sending — the human-approval path). Polling uses `historyId` incremental sync when a previous poll recorded one, falling back to the full label list when the history window has expired; messages are fetched `format=full` (attachment ids live in the payload parts), then have `UNREAD` stripped via `modifyLabels` so re-poll dedup matches `email_imap` semantics. 429 quota responses back off to the next poll cycle instead of crashing the loop. `threadId` and `In-Reply-To` both surface on the envelope (`conversation.thread_id` + `raw.gmail_thread_id`); attachment bytes come via `adapter.download_attachment(gmail_message_id, attachment_id)`. Outbound uses `POST .../messages/send` (or `drafts/create` in draft mode); subject rules match `email_imap`.
|
|
162
|
+
|
|
163
|
+
## Capability matrix
|
|
164
|
+
|
|
165
|
+
Every adapter declares `ChannelCapabilities` (CAN_RECEIVE / CAN_SEND / CAN_GROUP / CAN_BOT / CAN_MENTION / CAN_CARDS / CAN_MEDIA / CAN_RECEIPT / CAN_THREADS) — see `src/fusion_channel/capabilities.py`. Consumers branch on capabilities, never on adapter identity. Config `capabilities_override` tweaks per channel instance.
|
|
166
|
+
|
|
167
|
+
## Relationship to other Fusion components
|
|
168
|
+
|
|
169
|
+
- **fusion-core**: same in-tree distribution mode (`pip install -e`); no reverse dependency.
|
|
170
|
+
- **fusion-identity**: `IdentityMapper` maps external ids to identity accounts; RBAC stays in fusion-identity (`assert_bound_identity()` provides the two-factor primitive for sensitive commands).
|
|
171
|
+
- **fusion-gateway**: deliberately does **not** use its connector framework (no IM concepts, no verification, no background model).
|
|
172
|
+
- **ai-family**: first consumer + code donor (verification/dedup/outbox/secret-store semantics ported). Its switch-over is tracked in its own repo (PRD §11).
|
|
173
|
+
|
|
174
|
+
## Development
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
source /Users/dahai/fusion/.venv/bin/activate
|
|
178
|
+
pytest tests/ # 196 tests: crypto vectors, webhook E2E, outbox, matrix, hardening, email
|
|
179
|
+
pytest tests/test_e2e_approval.py -v # cross-channel approval acceptance
|
|
180
|
+
ruff check . && ruff format --check . # lint
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Test coverage highlights:
|
|
184
|
+
|
|
185
|
+
- Real signature vectors for every channel (including Feishu/WeCom AES-CBC round-trips, Slack replay-window rejection, DingTalk ms-timestamp handling, Aliyun RFC3986 percent-encoding).
|
|
186
|
+
- FastAPI TestClient E2E: signed webhook → verify → parse → dedup → archive → handler; bad signature → 403 + reject archive; duplicate → 200, no redispatch; internal errors → reject-archive + 400, never 500.
|
|
187
|
+
- GET handshakes: WeCom `echostr` URL verification and WhatsApp `hub.challenge` echo (token-checked), via the router's GET route.
|
|
188
|
+
- Delivery receipts (Twilio `MessageStatus`, WhatsApp `statuses`) are archived as receipts, never dispatched as messages; challenge retries always re-echo (never deduped).
|
|
189
|
+
- Cross-channel approval acceptance: the same `AP-123456` decision arrives via SMS text, Slack Block Kit button, DingTalk signed command, Telegram inline keyboard, WhatsApp text, WeCom encrypted callback, Feishu group mention, and Feishu card button callback — one handler, one state machine.
|
|
190
|
+
- Outbound E2E via `httpx.MockTransport`: Twilio/Feishu/Slack provider payload shapes asserted; `test_connection()` smoke-tested per adapter (DingTalk's is static — a robot send always lands in a real group).
|
|
191
|
+
- Email (`email_imap`): MIME parse (text extraction, attachments, In-Reply-To threading), SMTP send with subject/In-Reply-To headers, fake-transport E2E through `registry.poll()` including dedup on re-poll, fetch-error isolation, card-fallback outbox send, polling worker lifecycle.
|
|
192
|
+
- Microsoft 365 (`graph_mail`): mocked Graph HTTP via `httpx.MockTransport` — OAuth2 client-credentials token fetch + caching + 401 refresh, unread list → MIME fetch → mark-read verified, Graph attachment refs into `MediaRef`, `download_attachment()` bytes, registry poll dispatch + dedup on re-poll, mark-read-failure dedup fallback, `sendMail` payload shape, credentials-missing and provider-error paths.
|
|
193
|
+
- Gmail (`gmail_api`): mocked Gmail HTTP via `httpx.MockTransport` — OAuth2 refresh-token token fetch + caching + 401 refresh, label list → `format=full` fetch → `modifyLabels` UNREAD-strip verified, historyId incremental sync + 404 gap fallback to full list, 429 backoff on list and per-message fetch, `threadId`/`In-Reply-To` threading, `download_attachment()` bytes, registry poll dispatch + dedup on re-poll, label-strip-failure dedup fallback, `messages.send` raw MIME shape, `drafts.create` draft mode, credentials-missing and provider-error paths.
|
|
194
|
+
- Live provider calls require sandbox credentials and are marked `integration` (excluded by default): Feishu tenant-token handshake; QQ Mail real IMAP/SMTP E2E (login + poll + dedup on the live INBOX, SMTP send-to-self with loopback receive, env-based credentials `FUSION_CHANNEL_QQ_EMAIL` / `FUSION_CHANNEL_QQ_AUTH_CODE`).
|
|
195
|
+
|
|
196
|
+
## License
|
|
197
|
+
|
|
198
|
+
Apache-2.0
|