Add device-bound robot notifications and automatic OAuth cards
This commit is contained in:
@@ -144,6 +144,7 @@ def create_app(settings=None, redis=None, platform=None):
|
||||
broker = Broker(s, r, store)
|
||||
oauth = OAuth(s, r, f)
|
||||
oauth.store = store
|
||||
from .notifications import router as notification_router
|
||||
background = set()
|
||||
|
||||
def spawn(coro):
|
||||
@@ -185,6 +186,7 @@ def create_app(settings=None, redis=None, platform=None):
|
||||
app = FastAPI(title="Hainuo B1 connector", lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||
app.add_middleware(BodyLimitMiddleware, max_body=s.max_body)
|
||||
app.include_router(oauth.router)
|
||||
app.include_router(notification_router(s, r, store, f, oauth))
|
||||
from .web_session import WebSessions
|
||||
web_sessions = WebSessions(s, r, store, broker, f)
|
||||
app.include_router(web_sessions.router)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Explicit local notification CLI; never accepts a recipient or arbitrary card JSON."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from .work_client import WorkClient, WorkError
|
||||
from .notification_client import push
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--directory', type=Path, required=True)
|
||||
parser.add_argument('--url', required=True)
|
||||
parser.add_argument('--request-id', required=True)
|
||||
parser.add_argument('--kind', choices=['text', 'notice', 'authorization'], default='text')
|
||||
parser.add_argument('--text', default='')
|
||||
parser.add_argument('--title', default='')
|
||||
args = parser.parse_args()
|
||||
client = WorkClient(args.directory, args.url)
|
||||
try:
|
||||
if args.kind == 'authorization':
|
||||
client.authorize() # Auto-pushes once; claim secret and OAuth URL are not printed.
|
||||
result = {'status': client.read(client.pending).get('notification_status', 'unknown')}
|
||||
else:
|
||||
result = push(client, request_id=args.request_id, kind=args.kind,
|
||||
text=args.text, title=args.title)
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
except WorkError as error:
|
||||
parser.exit(1, str(error) + '\n')
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Small add-on compatible with existing WorkClient; never stores or sends recipient IDs."""
|
||||
import hashlib
|
||||
import httpx
|
||||
|
||||
|
||||
def push(client, *, request_id, kind='text', text='', title='', oauth_state=''):
|
||||
from .work_client import WorkError
|
||||
payload = {'request_id': request_id, 'kind': kind, 'text': text,
|
||||
'title': title, 'oauth_state': oauth_state, 'binding_owner': client.owner}
|
||||
try:
|
||||
response = client.http.post('/device/notifications', json={
|
||||
**payload, 'host_id': client.config['host_id'],
|
||||
'proof': client.proof('work-notify-v1', payload)})
|
||||
except httpx.HTTPError:
|
||||
raise WorkError('通知发送状态未知;未自动重试。请核对机器人消息,勿换新request_id重发。') from None
|
||||
if response.status_code != 200:
|
||||
raise WorkError(f'通知请求失败(HTTP {response.status_code}),未自动重试。')
|
||||
return response.json()
|
||||
|
||||
|
||||
def notify_authorization(client, data):
|
||||
"""Best effort once per local OAuth transaction. Local authorization remains usable."""
|
||||
from .work_client import atomic_secret, WorkError
|
||||
if data.get('notification_attempted'):
|
||||
return
|
||||
data['notification_attempted'] = True
|
||||
data['notification_status'] = 'unknown'
|
||||
atomic_secret(client.pending, data)
|
||||
try:
|
||||
result = push(client, request_id='oauth_' + hashlib.sha256(data['state'].encode()).hexdigest(),
|
||||
kind='authorization', oauth_state=data['state'])
|
||||
data['notification_status'] = result.get('previous_status', result['status'])
|
||||
except (WorkError, ValueError):
|
||||
# Older ECS returns 404; direct user authorization URL remains the fallback.
|
||||
data['notification_status'] = 'unconfirmed'
|
||||
atomic_secret(client.pending, data)
|
||||
|
||||
|
||||
def register_notification_tool(directory):
|
||||
import json
|
||||
import os
|
||||
from tools.registry import registry
|
||||
import toolsets
|
||||
name = 'work_notification'
|
||||
description = '按用户要求向本机绑定用户的Work机器人私聊发送文本或通知卡片;不能指定其他收件人。request_id须稳定,状态未知不得换ID重试。'
|
||||
parameters = {'type': 'object', 'additionalProperties': False,
|
||||
'properties': {'request_id': {'type':'string'}, 'kind': {'type':'string', 'enum':['text','notice']},
|
||||
'text': {'type':'string'}, 'title': {'type':'string'}},
|
||||
'required': ['request_id','text']}
|
||||
def handle(args, **kwargs):
|
||||
from .work_client import WorkClient, WorkError
|
||||
client = None
|
||||
try:
|
||||
if set(args) - {'request_id','kind','text','title'}:
|
||||
raise WorkError('不支持指定收件人或自定义卡片。')
|
||||
client = WorkClient(directory, os.environ.get('HN_WORK_RELAY_URL','https://10.77.76.13'))
|
||||
return json.dumps(push(client, **args), ensure_ascii=False)
|
||||
except WorkError as error:
|
||||
return json.dumps({'status':'unconfirmed','message':str(error)},ensure_ascii=False)
|
||||
except Exception:
|
||||
return json.dumps({'status':'unknown','message':'通知状态未确认,未自动重试。'},ensure_ascii=False)
|
||||
finally:
|
||||
if client:client.close()
|
||||
registry.register(name=name,toolset='hainuo_work',schema={'name':name,'description':description,'parameters':parameters},
|
||||
handler=handle,description=description)
|
||||
if name not in toolsets.TOOLSETS['hainuo_work']['tools']:
|
||||
toolsets.TOOLSETS['hainuo_work']['tools'].append(name)
|
||||
if name not in toolsets._HERMES_CORE_TOOLS:
|
||||
toolsets._HERMES_CORE_TOOLS.append(name)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""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']}))
|
||||
@@ -20,6 +20,7 @@ class Transaction:
|
||||
status: str = "waiting"
|
||||
result: dict | None = None
|
||||
owner: str = ""
|
||||
host_id: str = ""
|
||||
|
||||
|
||||
class Empty(BaseModel):
|
||||
@@ -72,7 +73,8 @@ class OAuth:
|
||||
if len(self.pending) >= self.settings.max_pending:
|
||||
raise HTTPException(503, "too many pending transactions")
|
||||
state, secret = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
|
||||
self.pending[state] = Transaction(hashlib.sha256(secret.encode()).hexdigest(), time.monotonic() + 600, owner=owner)
|
||||
self.pending[state] = Transaction(hashlib.sha256(secret.encode()).hexdigest(), time.monotonic() + 600,
|
||||
owner=owner, host_id=body.host_id)
|
||||
redirect = self.settings.public_url.rstrip("/") + "/oauth/cb"
|
||||
parameters = {"app_id": self.settings.feishu_app_id, "redirect_uri": redirect, "state": state}
|
||||
if self.settings.feishu_oauth_scopes:
|
||||
|
||||
@@ -90,3 +90,12 @@ class Feishu:
|
||||
await self._json("POST", f"/open-apis/im/v1/messages/{message_id}/reply",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
json={"msg_type": "text", "content": json.dumps({"text": text}, ensure_ascii=False)})
|
||||
|
||||
async def send(self, owner, msg_type, content, delivery_id, *, token=None):
|
||||
token = token or await self.tenant_token()
|
||||
data = await self._json('POST', '/open-apis/im/v1/messages',
|
||||
params={'receive_id_type': 'open_id'},
|
||||
headers={'Authorization': 'Bearer ' + token},
|
||||
json={'receive_id': owner, 'msg_type': msg_type,
|
||||
'content': json.dumps(content, ensure_ascii=False), 'uuid': delivery_id})
|
||||
return data.get('data', {})
|
||||
|
||||
@@ -58,6 +58,8 @@ class WorkClient:
|
||||
if self.pending.exists():
|
||||
data = self.read(self.pending)
|
||||
if data.get("owner") == self.owner and data["deadline"] > time.time():
|
||||
from .notification_client import notify_authorization
|
||||
notify_authorization(self, data)
|
||||
return data["authorization_url"]
|
||||
response = self.http.post("/oauth/start", json={"host_id": self.config["host_id"],
|
||||
"proof": self.proof("work-oauth-v1", {})})
|
||||
@@ -68,6 +70,8 @@ class WorkClient:
|
||||
raise WorkError("授权地址必须使用HTTPS。")
|
||||
data.update(owner=self.owner, deadline=time.time() + data["expires_in"])
|
||||
atomic_secret(self.pending, data)
|
||||
from .notification_client import notify_authorization
|
||||
notify_authorization(self, data)
|
||||
return data["authorization_url"]
|
||||
|
||||
def save_tokens(self, data):
|
||||
|
||||
@@ -115,6 +115,10 @@ def register(directory):
|
||||
toolsets._HERMES_CORE_TOOLS.append(name)
|
||||
|
||||
|
||||
from .notification_client import register_notification_tool
|
||||
register_notification_tool(directory)
|
||||
|
||||
|
||||
def calendar(client, args):
|
||||
from urllib.parse import quote
|
||||
action = args["action"]
|
||||
|
||||
Reference in New Issue
Block a user