mybridge-connect 0.1.0__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.
- mybridge_connect-0.1.0/.gitignore +11 -0
- mybridge_connect-0.1.0/PKG-INFO +273 -0
- mybridge_connect-0.1.0/README.md +250 -0
- mybridge_connect-0.1.0/pyproject.toml +43 -0
- mybridge_connect-0.1.0/src/mybridge_connect/__init__.py +24 -0
- mybridge_connect-0.1.0/src/mybridge_connect/_base.py +364 -0
- mybridge_connect-0.1.0/src/mybridge_connect/async_client.py +168 -0
- mybridge_connect-0.1.0/src/mybridge_connect/client.py +167 -0
- mybridge_connect-0.1.0/src/mybridge_connect/errors.py +38 -0
- mybridge_connect-0.1.0/src/mybridge_connect/pkce.py +32 -0
- mybridge_connect-0.1.0/src/mybridge_connect/py.typed +0 -0
- mybridge_connect-0.1.0/src/mybridge_connect/types.py +175 -0
- mybridge_connect-0.1.0/src/mybridge_connect/webhooks.py +91 -0
- mybridge_connect-0.1.0/tests/__init__.py +0 -0
- mybridge_connect-0.1.0/tests/conftest.py +92 -0
- mybridge_connect-0.1.0/tests/test_async.py +68 -0
- mybridge_connect-0.1.0/tests/test_meet.py +145 -0
- mybridge_connect-0.1.0/tests/test_oauth.py +158 -0
- mybridge_connect-0.1.0/tests/test_pkce_and_authorize.py +86 -0
- mybridge_connect-0.1.0/tests/test_webhooks.py +66 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mybridge-connect
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for myBridge Connect: Sign in with myBridge (OAuth 2 / OpenID Connect) and myBridge Meet for partner apps.
|
|
5
|
+
Author: myBridge
|
|
6
|
+
License: Proprietary
|
|
7
|
+
Keywords: meet,mybridge,oauth2,oidc,openid-connect,sdk
|
|
8
|
+
Classifier: Framework :: AsyncIO
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: anyio>=4; extra == 'dev'
|
|
20
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# mybridge-connect (Python)
|
|
25
|
+
|
|
26
|
+
Python SDK for **myBridge Connect**:
|
|
27
|
+
|
|
28
|
+
- **Sign in with myBridge**: myBridge is an OAuth 2 / OpenID Connect provider (like "Sign in with Google").
|
|
29
|
+
- **myBridge Meet for partner apps**: create Meet meetings for a person who connected their account, get join
|
|
30
|
+
links, and receive webhooks when a meeting starts, ends or is cancelled.
|
|
31
|
+
|
|
32
|
+
Sync (`MyBridgeClient`, on `httpx.Client`) and async (`AsyncMyBridgeClient`, on `httpx.AsyncClient`) clients with
|
|
33
|
+
the same methods. Python 3.10+, one dependency: `httpx`.
|
|
34
|
+
|
|
35
|
+
| Environment | API base |
|
|
36
|
+
|---|---|
|
|
37
|
+
| `production` | `https://api.mybridge.me` |
|
|
38
|
+
| `staging` | `https://api.bybk.org` (try everything here first, with test accounts) |
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install mybridge-connect # once published
|
|
44
|
+
pip install -e path/to/sdks/python # from this repository
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Configure
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from mybridge_connect import AsyncMyBridgeClient
|
|
51
|
+
|
|
52
|
+
mybridge = AsyncMyBridgeClient(
|
|
53
|
+
client_id=settings.MYBRIDGE_CLIENT_ID,
|
|
54
|
+
client_secret=settings.MYBRIDGE_CLIENT_SECRET, # leave out for a public (browser / phone) app using PKCE
|
|
55
|
+
redirect_uri="https://learning.example.com/auth/mybridge/callback",
|
|
56
|
+
environment="staging", # or "production"; or base_url="http://localhost:8000"
|
|
57
|
+
)
|
|
58
|
+
# MyBridgeClient(...) is the same, synchronous. Close with `await mybridge.aclose()` / `client.close()`,
|
|
59
|
+
# or use them as (async) context managers. Pass http_client=... to reuse your own httpx client.
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`client_auth_method="basic"` (default) sends the secret to `/oauth/token` with HTTP Basic; `"body"` sends
|
|
63
|
+
`client_id` / `client_secret` as form fields.
|
|
64
|
+
|
|
65
|
+
## Sign in with myBridge (FastAPI)
|
|
66
|
+
|
|
67
|
+
Scopes: `openid` (`sub`, the person's permanent myBridge uuid), `profile`, `email`, `phone`, `meet` (Meet API).
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
71
|
+
from fastapi.responses import RedirectResponse
|
|
72
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
73
|
+
|
|
74
|
+
from mybridge_connect import AsyncMyBridgeClient, MyBridgeError
|
|
75
|
+
|
|
76
|
+
app = FastAPI()
|
|
77
|
+
app.add_middleware(SessionMiddleware, secret_key="change-me")
|
|
78
|
+
mybridge = AsyncMyBridgeClient(client_id="...", client_secret="...",
|
|
79
|
+
redirect_uri="https://learning.example.com/auth/mybridge/callback",
|
|
80
|
+
environment="staging")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@app.get("/auth/mybridge/login")
|
|
84
|
+
async def login(request: Request):
|
|
85
|
+
# makes state, a PKCE verifier (S256) and, with openid, a nonce
|
|
86
|
+
auth = mybridge.prepare_authorization(["openid", "profile", "email", "meet"])
|
|
87
|
+
request.session["mybridge"] = {"state": auth.state, "verifier": auth.code_verifier, "nonce": auth.nonce}
|
|
88
|
+
return RedirectResponse(auth.url)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@app.get("/auth/mybridge/callback")
|
|
92
|
+
async def callback(request: Request, code: str | None = None, state: str | None = None,
|
|
93
|
+
error: str | None = None):
|
|
94
|
+
saved = request.session.pop("mybridge", None)
|
|
95
|
+
if not saved or state != saved["state"]:
|
|
96
|
+
raise HTTPException(400, "Bad state")
|
|
97
|
+
if error: # e.g. access_denied: the person said no
|
|
98
|
+
return RedirectResponse("/login?declined=1")
|
|
99
|
+
try:
|
|
100
|
+
tokens = await mybridge.exchange_code(code, code_verifier=saved["verifier"])
|
|
101
|
+
except MyBridgeError as exc: # e.g. invalid_grant: code expired or already used
|
|
102
|
+
raise HTTPException(400, exc.message)
|
|
103
|
+
|
|
104
|
+
user = await mybridge.get_userinfo(tokens.access_token) # {"sub", "name", "email", ...}
|
|
105
|
+
# Link on user["sub"] (never on email). Store tokens.refresh_token if you need access later.
|
|
106
|
+
await save_tokens(user["sub"], tokens.access_token, tokens.refresh_token, tokens.expires_at)
|
|
107
|
+
return RedirectResponse("/")
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Building the URL yourself instead:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from mybridge_connect import create_code_verifier, code_challenge_s256, create_state
|
|
114
|
+
|
|
115
|
+
verifier, state = create_code_verifier(), create_state()
|
|
116
|
+
url = mybridge.build_authorize_url(["openid", "email"], state, nonce=create_state(),
|
|
117
|
+
code_challenge=code_challenge_s256(verifier))
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
PKCE is required for public apps and optional for confidential ones (which prove themselves with the secret); using
|
|
121
|
+
it anyway is recommended.
|
|
122
|
+
|
|
123
|
+
### Tokens: store, refresh, revoke
|
|
124
|
+
|
|
125
|
+
The access token lasts **1 hour**; the refresh token **90 days**, and it is **rotated on every use**: each refresh
|
|
126
|
+
returns a new refresh token and the old one stops working. Always save the new one.
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
async def access_token_for(user_id: str) -> str:
|
|
130
|
+
row = await load_tokens(user_id)
|
|
131
|
+
if row.expires_at - 60 > time.time():
|
|
132
|
+
return row.access_token
|
|
133
|
+
tokens = await mybridge.refresh_tokens(row.refresh_token)
|
|
134
|
+
# save BOTH, replacing the old refresh token, before using the access token
|
|
135
|
+
await save_tokens(user_id, tokens.access_token, tokens.refresh_token, tokens.expires_at)
|
|
136
|
+
return tokens.access_token
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
If two workers may refresh the same person at once, serialise it (a row lock or a per-user lock): the second
|
|
140
|
+
refresh with the old token fails with `MyBridgeError(code="invalid_grant")`, and the person has to sign in again.
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
await mybridge.revoke_token(row.refresh_token, token_type_hint="refresh_token") # unlink / sign out
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Who is it?
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
info = await mybridge.get_userinfo(access_token) # OpenID claims for the granted scopes
|
|
150
|
+
me = await mybridge.get_me(access_token) # {"id", "name", "email"} (scope profile or email)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The ID token (`tokens.id_token`) is a signed JWT (RS256). This SDK does not verify JWTs; either rely on
|
|
154
|
+
`get_userinfo` (simplest), or verify it with a JWT library against `await mybridge.get_jwks()` (issuer
|
|
155
|
+
`mybridge.issuer`, audience your client id, and check `nonce`). `get_openid_configuration()` returns discovery.
|
|
156
|
+
|
|
157
|
+
## myBridge Meet (scope `meet`)
|
|
158
|
+
|
|
159
|
+
The meeting belongs to the person who connected (e.g. the teacher): it appears in their myBridge calendar and they
|
|
160
|
+
host it. Your app only sees the meetings it created.
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from datetime import datetime, timezone
|
|
164
|
+
|
|
165
|
+
token = await access_token_for(teacher_id)
|
|
166
|
+
|
|
167
|
+
meeting = await mybridge.create_meeting(
|
|
168
|
+
token, "Algebra - live class",
|
|
169
|
+
start_at=datetime(2026, 12, 1, 15, 0, tzinfo=timezone.utc), # None (default) = now
|
|
170
|
+
duration_minutes=90,
|
|
171
|
+
external_ref="class-123", # your own id
|
|
172
|
+
timezone="Africa/Lagos",
|
|
173
|
+
waiting_room=False,
|
|
174
|
+
)
|
|
175
|
+
meeting["id"], meeting["status"], meeting["host_url"], meeting["guest_url"]
|
|
176
|
+
|
|
177
|
+
meetings = await mybridge.list_meetings(token, external_ref="class-123")
|
|
178
|
+
meeting = await mybridge.get_meeting(token, meeting["id"])
|
|
179
|
+
meeting = await mybridge.update_meeting(token, meeting["id"], title="Algebra II", duration_minutes=60)
|
|
180
|
+
|
|
181
|
+
meeting = await mybridge.invite_to_meeting(
|
|
182
|
+
token, meeting["id"],
|
|
183
|
+
[{"email": "ada@example.com", "name": "Ada"}, "bob@example.com"],
|
|
184
|
+
notify=False, # True: myBridge emails them; otherwise show the links yourself
|
|
185
|
+
)
|
|
186
|
+
for invite in meeting["invites"]: # people without a myBridge account: personal links
|
|
187
|
+
print(invite["email"], invite["join_url"])
|
|
188
|
+
for member in meeting["members"]: # people with an account: join signed in
|
|
189
|
+
print(member["name"], member["join_url"])
|
|
190
|
+
|
|
191
|
+
await mybridge.cancel_meeting(token, meeting["id"]) # 204; idempotent; reads as "cancelled" afterwards
|
|
192
|
+
|
|
193
|
+
status = await mybridge.health() # {"status": "ok" | "degraded", "checks": {...}}; no token needed
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`status` is `scheduled`, `live`, `ended` or `cancelled`. Limit: 50 invites per meeting. Changing or inviting to a
|
|
197
|
+
cancelled meeting raises `MyBridgeError(409, "meeting_cancelled", ...)`.
|
|
198
|
+
|
|
199
|
+
## Account check (server-to-server)
|
|
200
|
+
|
|
201
|
+
For apps allowed to check accounts (e.g. to *offer* linking at sign-up; never to merge). Uses the client id and
|
|
202
|
+
secret; 120 calls a minute per app.
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
exists = await mybridge.check_account(email="ada@example.com")
|
|
206
|
+
exists = await mybridge.check_account(phone="+2348012345678") # E.164
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## Webhooks
|
|
210
|
+
|
|
211
|
+
myBridge POSTs `{"id", "type", "created_at", "data"}` to your webhook URL, signed with your webhook secret.
|
|
212
|
+
Types: `meeting.started`, `meeting.ended`, `meeting.cancelled` (data: the meeting) and `connection.revoked`
|
|
213
|
+
(data: `{"user_id", "revoked_at"}`). Verify against the **raw** body:
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
from fastapi import Request, Response
|
|
217
|
+
from mybridge_connect import SIGNATURE_HEADER, WebhookVerificationError, verify_webhook
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@app.post("/v1/webhooks/mybridge")
|
|
221
|
+
async def mybridge_webhook(request: Request):
|
|
222
|
+
raw = await request.body() # the exact bytes; don't use a parsed JSON model here
|
|
223
|
+
try:
|
|
224
|
+
event = verify_webhook(raw, request.headers.get(SIGNATURE_HEADER), settings.MYBRIDGE_WEBHOOK_SECRET)
|
|
225
|
+
except WebhookVerificationError:
|
|
226
|
+
return Response(status_code=400)
|
|
227
|
+
|
|
228
|
+
if await already_processed(event["id"]): # deliveries can repeat (retries): dedupe on the event id
|
|
229
|
+
return Response(status_code=200)
|
|
230
|
+
if event["type"] == "meeting.ended":
|
|
231
|
+
await mark_class_ended(event["data"]["external_ref"])
|
|
232
|
+
elif event["type"] == "connection.revoked":
|
|
233
|
+
await forget_tokens(event["data"]["user_id"])
|
|
234
|
+
return Response(status_code=200)
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
The signature header is `MyBridge-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`; `verify_webhook`
|
|
238
|
+
compares in constant time and refuses timestamps more than 300 s off (`tolerance_seconds=`). Answer quickly with a
|
|
239
|
+
2xx; a 5xx or 429 is retried with backoff (up to 6 times). `compute_signature(raw, secret, timestamp)` builds a
|
|
240
|
+
header for your own tests.
|
|
241
|
+
|
|
242
|
+
## Errors
|
|
243
|
+
|
|
244
|
+
Every call raises `MyBridgeError` for an error answer:
|
|
245
|
+
|
|
246
|
+
```python
|
|
247
|
+
from mybridge_connect import MyBridgeError
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
await mybridge.get_meeting(token, "abc-def")
|
|
251
|
+
except MyBridgeError as exc:
|
|
252
|
+
exc.status # 404
|
|
253
|
+
exc.code # "not_found"
|
|
254
|
+
exc.message # "Meeting not found."
|
|
255
|
+
exc.fields # per-field messages on a 400 validation error, else None
|
|
256
|
+
exc.body # the decoded JSON body
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
Partner API codes: `invalid_request`, `invalid_token` (refresh the token), `insufficient_scope` (ask for the scope
|
|
260
|
+
again), `not_found`, `conflict` / `meeting_cancelled`, `rate_limited`. OAuth codes (from `/oauth/...`) are the
|
|
261
|
+
standard ones: `invalid_grant`, `invalid_client`, `invalid_request`, ... Network failures surface as
|
|
262
|
+
`httpx.TransportError` (e.g. `httpx.TimeoutException`).
|
|
263
|
+
|
|
264
|
+
## Development
|
|
265
|
+
|
|
266
|
+
```bash
|
|
267
|
+
cd sdks/python
|
|
268
|
+
uv venv .venv && uv pip install -e '.[dev]' # or: python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
|
|
269
|
+
.venv/bin/pytest
|
|
270
|
+
.venv/bin/mypy # strict type check of src/
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Tests mock HTTP with `httpx.MockTransport`; they never call a real server.
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# mybridge-connect (Python)
|
|
2
|
+
|
|
3
|
+
Python SDK for **myBridge Connect**:
|
|
4
|
+
|
|
5
|
+
- **Sign in with myBridge**: myBridge is an OAuth 2 / OpenID Connect provider (like "Sign in with Google").
|
|
6
|
+
- **myBridge Meet for partner apps**: create Meet meetings for a person who connected their account, get join
|
|
7
|
+
links, and receive webhooks when a meeting starts, ends or is cancelled.
|
|
8
|
+
|
|
9
|
+
Sync (`MyBridgeClient`, on `httpx.Client`) and async (`AsyncMyBridgeClient`, on `httpx.AsyncClient`) clients with
|
|
10
|
+
the same methods. Python 3.10+, one dependency: `httpx`.
|
|
11
|
+
|
|
12
|
+
| Environment | API base |
|
|
13
|
+
|---|---|
|
|
14
|
+
| `production` | `https://api.mybridge.me` |
|
|
15
|
+
| `staging` | `https://api.bybk.org` (try everything here first, with test accounts) |
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install mybridge-connect # once published
|
|
21
|
+
pip install -e path/to/sdks/python # from this repository
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Configure
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from mybridge_connect import AsyncMyBridgeClient
|
|
28
|
+
|
|
29
|
+
mybridge = AsyncMyBridgeClient(
|
|
30
|
+
client_id=settings.MYBRIDGE_CLIENT_ID,
|
|
31
|
+
client_secret=settings.MYBRIDGE_CLIENT_SECRET, # leave out for a public (browser / phone) app using PKCE
|
|
32
|
+
redirect_uri="https://learning.example.com/auth/mybridge/callback",
|
|
33
|
+
environment="staging", # or "production"; or base_url="http://localhost:8000"
|
|
34
|
+
)
|
|
35
|
+
# MyBridgeClient(...) is the same, synchronous. Close with `await mybridge.aclose()` / `client.close()`,
|
|
36
|
+
# or use them as (async) context managers. Pass http_client=... to reuse your own httpx client.
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`client_auth_method="basic"` (default) sends the secret to `/oauth/token` with HTTP Basic; `"body"` sends
|
|
40
|
+
`client_id` / `client_secret` as form fields.
|
|
41
|
+
|
|
42
|
+
## Sign in with myBridge (FastAPI)
|
|
43
|
+
|
|
44
|
+
Scopes: `openid` (`sub`, the person's permanent myBridge uuid), `profile`, `email`, `phone`, `meet` (Meet API).
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
48
|
+
from fastapi.responses import RedirectResponse
|
|
49
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
50
|
+
|
|
51
|
+
from mybridge_connect import AsyncMyBridgeClient, MyBridgeError
|
|
52
|
+
|
|
53
|
+
app = FastAPI()
|
|
54
|
+
app.add_middleware(SessionMiddleware, secret_key="change-me")
|
|
55
|
+
mybridge = AsyncMyBridgeClient(client_id="...", client_secret="...",
|
|
56
|
+
redirect_uri="https://learning.example.com/auth/mybridge/callback",
|
|
57
|
+
environment="staging")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@app.get("/auth/mybridge/login")
|
|
61
|
+
async def login(request: Request):
|
|
62
|
+
# makes state, a PKCE verifier (S256) and, with openid, a nonce
|
|
63
|
+
auth = mybridge.prepare_authorization(["openid", "profile", "email", "meet"])
|
|
64
|
+
request.session["mybridge"] = {"state": auth.state, "verifier": auth.code_verifier, "nonce": auth.nonce}
|
|
65
|
+
return RedirectResponse(auth.url)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@app.get("/auth/mybridge/callback")
|
|
69
|
+
async def callback(request: Request, code: str | None = None, state: str | None = None,
|
|
70
|
+
error: str | None = None):
|
|
71
|
+
saved = request.session.pop("mybridge", None)
|
|
72
|
+
if not saved or state != saved["state"]:
|
|
73
|
+
raise HTTPException(400, "Bad state")
|
|
74
|
+
if error: # e.g. access_denied: the person said no
|
|
75
|
+
return RedirectResponse("/login?declined=1")
|
|
76
|
+
try:
|
|
77
|
+
tokens = await mybridge.exchange_code(code, code_verifier=saved["verifier"])
|
|
78
|
+
except MyBridgeError as exc: # e.g. invalid_grant: code expired or already used
|
|
79
|
+
raise HTTPException(400, exc.message)
|
|
80
|
+
|
|
81
|
+
user = await mybridge.get_userinfo(tokens.access_token) # {"sub", "name", "email", ...}
|
|
82
|
+
# Link on user["sub"] (never on email). Store tokens.refresh_token if you need access later.
|
|
83
|
+
await save_tokens(user["sub"], tokens.access_token, tokens.refresh_token, tokens.expires_at)
|
|
84
|
+
return RedirectResponse("/")
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Building the URL yourself instead:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from mybridge_connect import create_code_verifier, code_challenge_s256, create_state
|
|
91
|
+
|
|
92
|
+
verifier, state = create_code_verifier(), create_state()
|
|
93
|
+
url = mybridge.build_authorize_url(["openid", "email"], state, nonce=create_state(),
|
|
94
|
+
code_challenge=code_challenge_s256(verifier))
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
PKCE is required for public apps and optional for confidential ones (which prove themselves with the secret); using
|
|
98
|
+
it anyway is recommended.
|
|
99
|
+
|
|
100
|
+
### Tokens: store, refresh, revoke
|
|
101
|
+
|
|
102
|
+
The access token lasts **1 hour**; the refresh token **90 days**, and it is **rotated on every use**: each refresh
|
|
103
|
+
returns a new refresh token and the old one stops working. Always save the new one.
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
async def access_token_for(user_id: str) -> str:
|
|
107
|
+
row = await load_tokens(user_id)
|
|
108
|
+
if row.expires_at - 60 > time.time():
|
|
109
|
+
return row.access_token
|
|
110
|
+
tokens = await mybridge.refresh_tokens(row.refresh_token)
|
|
111
|
+
# save BOTH, replacing the old refresh token, before using the access token
|
|
112
|
+
await save_tokens(user_id, tokens.access_token, tokens.refresh_token, tokens.expires_at)
|
|
113
|
+
return tokens.access_token
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
If two workers may refresh the same person at once, serialise it (a row lock or a per-user lock): the second
|
|
117
|
+
refresh with the old token fails with `MyBridgeError(code="invalid_grant")`, and the person has to sign in again.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
await mybridge.revoke_token(row.refresh_token, token_type_hint="refresh_token") # unlink / sign out
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Who is it?
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
info = await mybridge.get_userinfo(access_token) # OpenID claims for the granted scopes
|
|
127
|
+
me = await mybridge.get_me(access_token) # {"id", "name", "email"} (scope profile or email)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The ID token (`tokens.id_token`) is a signed JWT (RS256). This SDK does not verify JWTs; either rely on
|
|
131
|
+
`get_userinfo` (simplest), or verify it with a JWT library against `await mybridge.get_jwks()` (issuer
|
|
132
|
+
`mybridge.issuer`, audience your client id, and check `nonce`). `get_openid_configuration()` returns discovery.
|
|
133
|
+
|
|
134
|
+
## myBridge Meet (scope `meet`)
|
|
135
|
+
|
|
136
|
+
The meeting belongs to the person who connected (e.g. the teacher): it appears in their myBridge calendar and they
|
|
137
|
+
host it. Your app only sees the meetings it created.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from datetime import datetime, timezone
|
|
141
|
+
|
|
142
|
+
token = await access_token_for(teacher_id)
|
|
143
|
+
|
|
144
|
+
meeting = await mybridge.create_meeting(
|
|
145
|
+
token, "Algebra - live class",
|
|
146
|
+
start_at=datetime(2026, 12, 1, 15, 0, tzinfo=timezone.utc), # None (default) = now
|
|
147
|
+
duration_minutes=90,
|
|
148
|
+
external_ref="class-123", # your own id
|
|
149
|
+
timezone="Africa/Lagos",
|
|
150
|
+
waiting_room=False,
|
|
151
|
+
)
|
|
152
|
+
meeting["id"], meeting["status"], meeting["host_url"], meeting["guest_url"]
|
|
153
|
+
|
|
154
|
+
meetings = await mybridge.list_meetings(token, external_ref="class-123")
|
|
155
|
+
meeting = await mybridge.get_meeting(token, meeting["id"])
|
|
156
|
+
meeting = await mybridge.update_meeting(token, meeting["id"], title="Algebra II", duration_minutes=60)
|
|
157
|
+
|
|
158
|
+
meeting = await mybridge.invite_to_meeting(
|
|
159
|
+
token, meeting["id"],
|
|
160
|
+
[{"email": "ada@example.com", "name": "Ada"}, "bob@example.com"],
|
|
161
|
+
notify=False, # True: myBridge emails them; otherwise show the links yourself
|
|
162
|
+
)
|
|
163
|
+
for invite in meeting["invites"]: # people without a myBridge account: personal links
|
|
164
|
+
print(invite["email"], invite["join_url"])
|
|
165
|
+
for member in meeting["members"]: # people with an account: join signed in
|
|
166
|
+
print(member["name"], member["join_url"])
|
|
167
|
+
|
|
168
|
+
await mybridge.cancel_meeting(token, meeting["id"]) # 204; idempotent; reads as "cancelled" afterwards
|
|
169
|
+
|
|
170
|
+
status = await mybridge.health() # {"status": "ok" | "degraded", "checks": {...}}; no token needed
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`status` is `scheduled`, `live`, `ended` or `cancelled`. Limit: 50 invites per meeting. Changing or inviting to a
|
|
174
|
+
cancelled meeting raises `MyBridgeError(409, "meeting_cancelled", ...)`.
|
|
175
|
+
|
|
176
|
+
## Account check (server-to-server)
|
|
177
|
+
|
|
178
|
+
For apps allowed to check accounts (e.g. to *offer* linking at sign-up; never to merge). Uses the client id and
|
|
179
|
+
secret; 120 calls a minute per app.
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
exists = await mybridge.check_account(email="ada@example.com")
|
|
183
|
+
exists = await mybridge.check_account(phone="+2348012345678") # E.164
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
## Webhooks
|
|
187
|
+
|
|
188
|
+
myBridge POSTs `{"id", "type", "created_at", "data"}` to your webhook URL, signed with your webhook secret.
|
|
189
|
+
Types: `meeting.started`, `meeting.ended`, `meeting.cancelled` (data: the meeting) and `connection.revoked`
|
|
190
|
+
(data: `{"user_id", "revoked_at"}`). Verify against the **raw** body:
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
from fastapi import Request, Response
|
|
194
|
+
from mybridge_connect import SIGNATURE_HEADER, WebhookVerificationError, verify_webhook
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@app.post("/v1/webhooks/mybridge")
|
|
198
|
+
async def mybridge_webhook(request: Request):
|
|
199
|
+
raw = await request.body() # the exact bytes; don't use a parsed JSON model here
|
|
200
|
+
try:
|
|
201
|
+
event = verify_webhook(raw, request.headers.get(SIGNATURE_HEADER), settings.MYBRIDGE_WEBHOOK_SECRET)
|
|
202
|
+
except WebhookVerificationError:
|
|
203
|
+
return Response(status_code=400)
|
|
204
|
+
|
|
205
|
+
if await already_processed(event["id"]): # deliveries can repeat (retries): dedupe on the event id
|
|
206
|
+
return Response(status_code=200)
|
|
207
|
+
if event["type"] == "meeting.ended":
|
|
208
|
+
await mark_class_ended(event["data"]["external_ref"])
|
|
209
|
+
elif event["type"] == "connection.revoked":
|
|
210
|
+
await forget_tokens(event["data"]["user_id"])
|
|
211
|
+
return Response(status_code=200)
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
The signature header is `MyBridge-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`; `verify_webhook`
|
|
215
|
+
compares in constant time and refuses timestamps more than 300 s off (`tolerance_seconds=`). Answer quickly with a
|
|
216
|
+
2xx; a 5xx or 429 is retried with backoff (up to 6 times). `compute_signature(raw, secret, timestamp)` builds a
|
|
217
|
+
header for your own tests.
|
|
218
|
+
|
|
219
|
+
## Errors
|
|
220
|
+
|
|
221
|
+
Every call raises `MyBridgeError` for an error answer:
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
from mybridge_connect import MyBridgeError
|
|
225
|
+
|
|
226
|
+
try:
|
|
227
|
+
await mybridge.get_meeting(token, "abc-def")
|
|
228
|
+
except MyBridgeError as exc:
|
|
229
|
+
exc.status # 404
|
|
230
|
+
exc.code # "not_found"
|
|
231
|
+
exc.message # "Meeting not found."
|
|
232
|
+
exc.fields # per-field messages on a 400 validation error, else None
|
|
233
|
+
exc.body # the decoded JSON body
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Partner API codes: `invalid_request`, `invalid_token` (refresh the token), `insufficient_scope` (ask for the scope
|
|
237
|
+
again), `not_found`, `conflict` / `meeting_cancelled`, `rate_limited`. OAuth codes (from `/oauth/...`) are the
|
|
238
|
+
standard ones: `invalid_grant`, `invalid_client`, `invalid_request`, ... Network failures surface as
|
|
239
|
+
`httpx.TransportError` (e.g. `httpx.TimeoutException`).
|
|
240
|
+
|
|
241
|
+
## Development
|
|
242
|
+
|
|
243
|
+
```bash
|
|
244
|
+
cd sdks/python
|
|
245
|
+
uv venv .venv && uv pip install -e '.[dev]' # or: python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
|
|
246
|
+
.venv/bin/pytest
|
|
247
|
+
.venv/bin/mypy # strict type check of src/
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
Tests mock HTTP with `httpx.MockTransport`; they never call a real server.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.21"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mybridge-connect"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK for myBridge Connect: Sign in with myBridge (OAuth 2 / OpenID Connect) and myBridge Meet for partner apps."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "Proprietary" }
|
|
12
|
+
authors = [{ name = "myBridge" }]
|
|
13
|
+
keywords = ["mybridge", "oauth2", "openid-connect", "oidc", "meet", "sdk"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Framework :: AsyncIO",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["httpx>=0.27"]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = [
|
|
28
|
+
"pytest>=8",
|
|
29
|
+
"anyio>=4",
|
|
30
|
+
"mypy>=1.10",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build.targets.wheel]
|
|
34
|
+
packages = ["src/mybridge_connect"]
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
testpaths = ["tests"]
|
|
38
|
+
addopts = "-ra"
|
|
39
|
+
|
|
40
|
+
[tool.mypy]
|
|
41
|
+
strict = true
|
|
42
|
+
python_version = "3.10"
|
|
43
|
+
files = ["src"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""myBridge Connect: Sign in with myBridge (OAuth 2 / OpenID Connect) and myBridge Meet for partner apps.
|
|
2
|
+
|
|
3
|
+
from mybridge_connect import MyBridgeClient, AsyncMyBridgeClient, verify_webhook, MyBridgeError
|
|
4
|
+
"""
|
|
5
|
+
from ._base import ENVIRONMENTS, UNSET, ClientAuthMethod, Environment
|
|
6
|
+
from .async_client import AsyncMyBridgeClient
|
|
7
|
+
from .client import MyBridgeClient
|
|
8
|
+
from .errors import MyBridgeError, WebhookVerificationError
|
|
9
|
+
from .pkce import code_challenge_s256, create_code_verifier, create_state
|
|
10
|
+
from .types import (AuthorizationRequest, ConnectionRevokedData, Guest, HealthStatus, Invite, Me, Meeting,
|
|
11
|
+
MeetingStatus, Member, Scope, TokenSet, UserInfo, WebhookEvent, WebhookEventType)
|
|
12
|
+
from .webhooks import SIGNATURE_HEADER, compute_signature, verify_webhook
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"MyBridgeClient", "AsyncMyBridgeClient", "MyBridgeError", "WebhookVerificationError",
|
|
18
|
+
"create_code_verifier", "code_challenge_s256", "create_state",
|
|
19
|
+
"verify_webhook", "compute_signature", "SIGNATURE_HEADER",
|
|
20
|
+
"ENVIRONMENTS", "Environment", "ClientAuthMethod", "UNSET",
|
|
21
|
+
"TokenSet", "AuthorizationRequest", "UserInfo", "Me", "Meeting", "MeetingStatus", "Invite", "Member", "Guest",
|
|
22
|
+
"HealthStatus", "WebhookEvent", "WebhookEventType", "ConnectionRevokedData", "Scope",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|