128 lines
6.7 KiB
Python
128 lines
6.7 KiB
Python
"""Device-authenticated outbound messages. Recipient and OAuth links are server-owned."""
|
|
import hashlib
|
|
import json
|
|
import time
|
|
import uuid
|
|
from urllib.parse import urlencode
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from fastapi.responses import JSONResponse
|
|
from pydantic import BaseModel, ConfigDict, Field
|
|
|
|
from .common import no_cache, rate_limit
|
|
from .crypto import canonical
|
|
from .store import INTEGRITY_ERRORS
|
|
from .work_api import device_owner
|
|
|
|
|
|
class Notification(BaseModel):
|
|
model_config = ConfigDict(extra='forbid')
|
|
host_id: str = Field(pattern=r'^[a-f0-9]{32}$')
|
|
proof: dict
|
|
request_id: str = Field(pattern=r'^[A-Za-z0-9_-]{8,100}$')
|
|
binding_owner: str = Field(min_length=1, max_length=128)
|
|
kind: str = Field(pattern=r'^(text|notice|authorization)$')
|
|
title: str = Field(default='', max_length=80)
|
|
text: str = Field(default='', max_length=2000)
|
|
oauth_state: str = Field(default='', max_length=100)
|
|
|
|
|
|
def router(settings, redis, store, platform, oauth):
|
|
routes = APIRouter()
|
|
store.db.execute('''CREATE TABLE IF NOT EXISTS notifications(
|
|
host_id TEXT NOT NULL, request_id TEXT NOT NULL, owner TEXT NOT NULL,
|
|
request_hash TEXT NOT NULL, status TEXT NOT NULL, message_id TEXT NOT NULL,
|
|
created DOUBLE PRECISION NOT NULL, PRIMARY KEY(host_id,request_id))''')
|
|
if not settings.database_url:
|
|
store.db.commit()
|
|
|
|
@routes.post('/device/notifications')
|
|
async def notify(body: Notification):
|
|
if not settings.feishu_enabled:
|
|
raise HTTPException(503, 'platform disabled')
|
|
payload = body.model_dump(exclude={'host_id', 'proof'})
|
|
owner = await device_owner(settings, redis, store, body.host_id, body.proof,
|
|
'work-notify-v1', payload)
|
|
if body.binding_owner != owner:
|
|
raise HTTPException(403, 'local binding is stale; pair the client again')
|
|
digest = hashlib.sha256(canonical(payload)).hexdigest()
|
|
previous = store.db.execute('SELECT * FROM notifications WHERE host_id=? AND request_id=?',
|
|
(body.host_id, body.request_id)).fetchone()
|
|
if previous:
|
|
return duplicate(dict(previous), owner, digest)
|
|
await rate_limit(redis, 'notify-device:' + body.host_id, 10)
|
|
await rate_limit(redis, 'notify-owner:' + owner, 10)
|
|
|
|
if body.kind == 'authorization':
|
|
if body.text or body.title or not body.oauth_state:
|
|
raise HTTPException(422, 'authorization requires only a pending OAuth state')
|
|
oauth.prune()
|
|
item = oauth.pending.get(body.oauth_state)
|
|
if (not settings.oauth_enabled or not item or item.status != 'waiting'
|
|
or item.owner != owner or item.host_id != body.host_id):
|
|
raise HTTPException(403, 'active device-owned authorization required')
|
|
params = {'app_id': settings.feishu_app_id,
|
|
'redirect_uri': settings.public_url.rstrip('/') + '/oauth/cb',
|
|
'state': body.oauth_state}
|
|
if settings.feishu_oauth_scopes:
|
|
params['scope'] = settings.feishu_oauth_scopes
|
|
url = settings.feishu_authorize_url + '?' + urlencode(params)
|
|
if not url.startswith('https://'):
|
|
raise HTTPException(503, 'HTTPS authorization URL required')
|
|
content = {'config': {'wide_screen_mode': True},
|
|
'header': {'title': {'tag': 'plain_text', 'content': '海能Work 用户授权'}},
|
|
'elements': [
|
|
{'tag': 'div', 'text': {'tag': 'plain_text', 'content': '本机海诺需要本人授权。请使用与电脑绑定一致的账号完成授权;链接短时有效,过期请重新发起。'}},
|
|
{'tag': 'action', 'actions': [{'tag': 'button', 'type': 'primary',
|
|
'text': {'tag': 'plain_text', 'content': '前往授权'}, 'url': url}]}]}
|
|
msg_type = 'interactive'
|
|
else:
|
|
if body.oauth_state or not body.text.strip():
|
|
raise HTTPException(422, 'notification text required; OAuth state is not allowed')
|
|
if body.kind == 'text':
|
|
if body.title:
|
|
raise HTTPException(422, 'text messages do not accept title')
|
|
msg_type, content = 'text', {'text': body.text}
|
|
else:
|
|
msg_type = 'interactive'
|
|
content = {'header': {'title': {'tag': 'plain_text', 'content': body.title or '海诺通知'}},
|
|
'elements': [{'tag': 'div', 'text': {'tag': 'plain_text', 'content': body.text}}]}
|
|
try:
|
|
with store.db:
|
|
store.db.execute('INSERT INTO notifications VALUES(?,?,?,?,?,?,?)',
|
|
(body.host_id, body.request_id, owner, digest, 'inflight', '', time.time()))
|
|
except INTEGRITY_ERRORS:
|
|
row = store.db.execute('SELECT * FROM notifications WHERE host_id=? AND request_id=?',
|
|
(body.host_id, body.request_id)).fetchone()
|
|
return duplicate(dict(row), owner, digest)
|
|
status, message_id = 'unknown', ''
|
|
try:
|
|
# Complete credential acquisition before the last synchronous binding check.
|
|
token = await platform.tenant_token()
|
|
device = store.device(body.host_id)
|
|
if not device or device['revoked'] or device['owner'] != owner:
|
|
status = 'binding_changed'
|
|
else:
|
|
delivery_id = uuid.uuid5(uuid.NAMESPACE_URL, body.host_id + ':' + body.request_id).hex
|
|
result = await platform.send(owner, msg_type, content, delivery_id, token=token)
|
|
message_id = result.get('message_id', '')
|
|
status = 'sent' if message_id else 'unknown'
|
|
except Exception:
|
|
# A timeout may follow successful delivery. Do not retry or expose upstream secrets.
|
|
status = 'unknown'
|
|
with store.db:
|
|
store.db.execute('UPDATE notifications SET status=?,message_id=? WHERE host_id=? AND request_id=?',
|
|
(status, message_id, body.host_id, body.request_id))
|
|
store.audit(owner, 'device_notification', body.request_id, status)
|
|
return no_cache(JSONResponse({'status': status, 'request_id': body.request_id,
|
|
'message_id': message_id}))
|
|
|
|
return routes
|
|
|
|
|
|
def duplicate(row, owner, digest):
|
|
if row['owner'] != owner or row['request_hash'] != digest:
|
|
raise HTTPException(409, 'request_id reused across owner or content')
|
|
return no_cache(JSONResponse({'status': 'duplicate', 'previous_status': row['status'],
|
|
'request_id': row['request_id'], 'message_id': row['message_id']}))
|