From 5eb45b30686cb6d6858c1cfb3dcbb97633fc69dd Mon Sep 17 00:00:00 2001 From: pplulee Date: Wed, 9 Sep 2026 17:18:06 +0800 Subject: [PATCH 1/5] feat: display times in each party's timezone Co-authored-by: Cursor --- .../src/components/ui/ActivityTimeline.tsx | 4 ++- frontend/src/lib/formatTime.ts | 30 +++++++++++++++++++ frontend/src/pages/ItemPages.tsx | 4 ++- frontend/src/pages/PaymentPartyPage.tsx | 5 ++-- .../src/pages/parties/PartyMyItemsPage.tsx | 4 ++- frontend/src/pages/parties/PartyShowPage.tsx | 3 +- internal/httpapi/items.go | 9 +++--- 7 files changed, 49 insertions(+), 10 deletions(-) create mode 100644 frontend/src/lib/formatTime.ts diff --git a/frontend/src/components/ui/ActivityTimeline.tsx b/frontend/src/components/ui/ActivityTimeline.tsx index 9f68f68..ed6ec63 100644 --- a/frontend/src/components/ui/ActivityTimeline.tsx +++ b/frontend/src/components/ui/ActivityTimeline.tsx @@ -1,6 +1,7 @@ import {useNavigate} from 'react-router-dom'; import {Flex, Tag, Timeline, Typography} from 'antd'; import {formatMoney, parseAmount} from '@/lib/formatMoney'; +import {formatPartyTime} from '@/lib/formatTime'; import {EmptyState} from './EmptyState'; export type ActivityItem = { @@ -11,6 +12,7 @@ export type ActivityItem = { created_at?: string; party_id: number; party_name: string; + timezone?: string; currency_symbol: string; type: 'initiated' | 'assigned'; counterparty_name: string; @@ -75,7 +77,7 @@ export function ActivityTimeline({items}: ActivityTimelineProps) { {title} · {it.party_name} - {it.created_at ? ` · ${it.created_at}` : ''} + {it.created_at ? ` · ${formatPartyTime(it.created_at, it.timezone)}` : ''} diff --git a/frontend/src/lib/formatTime.ts b/frontend/src/lib/formatTime.ts new file mode 100644 index 0000000..d2e7e51 --- /dev/null +++ b/frontend/src/lib/formatTime.ts @@ -0,0 +1,30 @@ +const DEFAULT_TZ = 'Asia/Shanghai'; + +function part(parts: Intl.DateTimeFormatPart[], type: Intl.DateTimeFormatPartTypes): string { + return parts.find((p) => p.type === type)?.value ?? ''; +} + +export function formatPartyTime(value?: string | null, timezone?: string | null): string { + if (!value) return ''; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return value; + + const zones = [timezone?.trim(), DEFAULT_TZ].filter((z): z is string => !!z); + for (const timeZone of zones) { + try { + const parts = new Intl.DateTimeFormat('en-CA', { + timeZone, + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + hourCycle: 'h23', + }).formatToParts(date); + return `${part(parts, 'year')}-${part(parts, 'month')}-${part(parts, 'day')} ${part(parts, 'hour')}:${part(parts, 'minute')}`; + } catch { + // invalid IANA timezone — try fallback + } + } + return value; +} diff --git a/frontend/src/pages/ItemPages.tsx b/frontend/src/pages/ItemPages.tsx index 7f489c4..7d576d9 100644 --- a/frontend/src/pages/ItemPages.tsx +++ b/frontend/src/pages/ItemPages.tsx @@ -4,6 +4,7 @@ import {Alert, Badge, Button, message, Popconfirm, Space, Tabs} from 'antd'; import {AccountBookOutlined, DeleteOutlined, PlusOutlined} from '@ant-design/icons'; import {apiDelete, apiJson, apiPostForm} from '@/api/client'; import {formatMoney} from '@/lib/formatMoney'; +import {formatPartyTime} from '@/lib/formatTime'; import {EmptyState, EntityCard, LedgerList, PageShell, SectionTitle, SummaryStrip, SurfaceCard,} from '@/components/ui'; type PartyRow = { @@ -123,6 +124,7 @@ export function ItemPartyPage() { const [err, setErr] = useState(null); const [party, setParty] = useState<{ name?: string; + timezone?: string; currency_symbol?: string; is_archived?: boolean; } | null>(null); @@ -296,7 +298,7 @@ export function ItemPartyPage() { return { id: it.id, title: it.description || '(无描述)', - meta: `付款方:${it.payer_name} · 发起方:${it.initiator_name}${it.created_at ? ` · ${it.created_at}` : ''}`, + meta: `付款方:${it.payer_name} · 发起方:${it.initiator_name}${it.created_at ? ` · ${formatPartyTime(it.created_at, party?.timezone)}` : ''}`, amount: formatMoney(sym, it.amount), paid, action: diff --git a/frontend/src/pages/PaymentPartyPage.tsx b/frontend/src/pages/PaymentPartyPage.tsx index 9cebc82..db1dec4 100644 --- a/frontend/src/pages/PaymentPartyPage.tsx +++ b/frontend/src/pages/PaymentPartyPage.tsx @@ -3,6 +3,7 @@ import {useParams} from 'react-router-dom'; import {WalletOutlined} from '@ant-design/icons'; import {apiJson} from '@/api/client'; import {formatMoney} from '@/lib/formatMoney'; +import {formatPartyTime} from '@/lib/formatTime'; import {EmptyState, LedgerList, PageShell, SectionTitle, SummaryStrip, SurfaceCard} from '@/components/ui'; type Item = { id: number; username: string; description: string; amount: string | number; created_at?: string }; @@ -12,7 +13,7 @@ export function PaymentPartyPage() { const partyId = Number(partyIdParam); const [loading, setLoading] = useState(true); const [err, setErr] = useState(null); - const [party, setParty] = useState<{ name?: string; description?: string; currency_symbol?: string } | null>(null); + const [party, setParty] = useState<{ name?: string; description?: string; timezone?: string; currency_symbol?: string } | null>(null); const [items, setItems] = useState([]); const [total, setTotal] = useState(''); @@ -60,7 +61,7 @@ export function PaymentPartyPage() { rows={items.map((it) => ({ id: it.id, title: it.description || '(无描述)', - meta: `发起方:${it.username}${it.created_at ? ` · ${it.created_at}` : ''}`, + meta: `发起方:${it.username}${it.created_at ? ` · ${formatPartyTime(it.created_at, party?.timezone)}` : ''}`, amount: formatMoney(sym, it.amount), }))} empty={} diff --git a/frontend/src/pages/parties/PartyMyItemsPage.tsx b/frontend/src/pages/parties/PartyMyItemsPage.tsx index 5440dfd..142762d 100644 --- a/frontend/src/pages/parties/PartyMyItemsPage.tsx +++ b/frontend/src/pages/parties/PartyMyItemsPage.tsx @@ -4,6 +4,7 @@ import {Alert, Badge, Button, Col, Row, Space, Tabs, message} from 'antd'; import {AccountBookOutlined, PlusOutlined, WalletOutlined} from '@ant-design/icons'; import {apiJson, apiPostForm} from '@/api/client'; import {formatMoney} from '@/lib/formatMoney'; +import {formatPartyTime} from '@/lib/formatTime'; import {EmptyState, LedgerList, PageShell, StatCard, SurfaceCard} from '@/components/ui'; type FilterKey = 'all' | 'my_initiated' | 'my_payment'; @@ -35,6 +36,7 @@ export function PartyMyItemsPage() { const [err, setErr] = useState(null); const [party, setParty] = useState<{ name?: string; + timezone?: string; currency_symbol?: string; is_archived?: boolean; } | null>(null); @@ -206,7 +208,7 @@ export function PartyMyItemsPage() { return { id: it.id, title: it.description || '(无描述)', - meta: `${metaText}${it.created_at ? ` · ${it.created_at}` : ''}`, + meta: `${metaText}${it.created_at ? ` · ${formatPartyTime(it.created_at, party?.timezone)}` : ''}`, amount: formatMoney(sym, it.amount), paid, action: markBtn diff --git a/frontend/src/pages/parties/PartyShowPage.tsx b/frontend/src/pages/parties/PartyShowPage.tsx index c6a0dcd..c97fcc0 100644 --- a/frontend/src/pages/parties/PartyShowPage.tsx +++ b/frontend/src/pages/parties/PartyShowPage.tsx @@ -20,6 +20,7 @@ import { } from '@ant-design/icons'; import {apiDelete, apiFetch, apiJson, downloadAuthenticated} from '@/api/client'; import {formatMoney, parseAmount} from '@/lib/formatMoney'; +import {formatPartyTime} from '@/lib/formatTime'; import {buildPartyInviteUrl} from '@/lib/partyInvite'; import {EmptyState, LedgerList, PageShell, StatCard, SurfaceCard} from '@/components/ui'; @@ -494,7 +495,7 @@ export function PartyShowPage() { {username} {m.joined_at ? ( - {m.joined_at} + {formatPartyTime(m.joined_at, party?.timezone)} ) : null} diff --git a/internal/httpapi/items.go b/internal/httpapi/items.go index 56ea7ae..db44cd0 100644 --- a/internal/httpapi/items.go +++ b/internal/httpapi/items.go @@ -328,10 +328,11 @@ WHERE pm.user_id=? AND (i.userid=? OR i.initiator=?)`, h.table("item"), h.table( PartyID uint64 `json:"party_id"` PartyName string `json:"party_name"` BaseCurrency string + Timezone string DebtorName string InitiatorName string } - activityQuery := fmt.Sprintf(`SELECT i.id,i.description,i.amount,i.paid,i.created_at,i.initiator,i.userid,p.id party_id,p.name party_name,p.base_currency,du.username debtor_name,iu.username initiator_name + activityQuery := fmt.Sprintf(`SELECT i.id,i.description,i.amount,i.paid,i.created_at,i.initiator,i.userid,p.id party_id,p.name party_name,p.base_currency,p.timezone,du.username debtor_name,iu.username initiator_name FROM %s i JOIN %s p ON i.party_id=p.id JOIN %s pm ON i.party_id=pm.party_id JOIN %s du ON i.userid=du.id JOIN %s iu ON i.initiator=iu.id WHERE pm.user_id=? AND (i.initiator=? OR i.userid=?) AND NOT(i.initiator=? AND i.userid=?) @@ -351,7 +352,7 @@ ORDER BY i.created_at DESC LIMIT 20`, h.table("item"), h.table("party"), h.table counterparty = row.DebtorName typeName = "initiated" } - recentActivity = append(recentActivity, gin.H{"id": row.ID, "description": row.Description, "amount": row.Amount, "paid": row.Paid, "created_at": row.CreatedAt, "party_id": row.PartyID, "party_name": row.PartyName, "currency_symbol": h.currencySymbol(c, row.BaseCurrency), "type": typeName, "counterparty_name": counterparty}) + recentActivity = append(recentActivity, gin.H{"id": row.ID, "description": row.Description, "amount": row.Amount, "paid": row.Paid, "created_at": row.CreatedAt, "party_id": row.PartyID, "party_name": row.PartyName, "timezone": row.Timezone, "currency_symbol": h.currencySymbol(c, row.BaseCurrency), "type": typeName, "counterparty_name": counterparty}) } var defaultCurrency model.Currency if h.db.WithContext(c).Table(h.table("currencies")).Where("is_default=1 AND is_active=1").First(&defaultCurrency).Error != nil { @@ -556,7 +557,7 @@ func (h *Handler) partyItemList(c *gin.Context) { } items = append(items, gin.H{"id": row.ID, "description": row.Description, "amount": row.Amount, "paid": boolInt(row.Paid), "created_at": row.CreatedAt, "userid": row.UserID, "initiator": row.Initiator, "payer_name": row.PayerName, "initiator_name": row.InitiatorName, "is_my_initiation": mineInitiated, "is_my_payment": minePayment}) } - c.JSON(http.StatusOK, gin.H{"ret": 1, "data": gin.H{"party": gin.H{"id": party.ID, "name": party.Name, "description": stringValue(party.Description), "currency_symbol": h.currencySymbol(c, party.BaseCurrency), "is_archived": party.ArchivedAt != nil}, "isOwner": party.OwnerID == user.ID, "items": items, "stats": gin.H{"total": stat.total, "unpaid": stat.unpaid, "my_initiated": stat.myInitiated, "my_payment": stat.myPayment, "total_amount": stat.totalAmount.String(), "unpaid_amount": stat.unpaidAmount.String(), "my_initiated_amount": stat.myInitiatedAmount.String(), "my_initiated_unpaid": stat.myInitiatedOpen.String(), "my_payment_amount": stat.myPaymentAmount.String()}}}) + c.JSON(http.StatusOK, gin.H{"ret": 1, "data": gin.H{"party": gin.H{"id": party.ID, "name": party.Name, "description": stringValue(party.Description), "timezone": party.Timezone, "currency_symbol": h.currencySymbol(c, party.BaseCurrency), "is_archived": party.ArchivedAt != nil}, "isOwner": party.OwnerID == user.ID, "items": items, "stats": gin.H{"total": stat.total, "unpaid": stat.unpaid, "my_initiated": stat.myInitiated, "my_payment": stat.myPayment, "total_amount": stat.totalAmount.String(), "unpaid_amount": stat.unpaidAmount.String(), "my_initiated_amount": stat.myInitiatedAmount.String(), "my_initiated_unpaid": stat.myInitiatedOpen.String(), "my_payment_amount": stat.myPaymentAmount.String()}}}) } func (h *Handler) paymentByParty(c *gin.Context) { @@ -586,7 +587,7 @@ func (h *Handler) paymentByParty(c *gin.Context) { } total += amount } - partyView := gin.H{"id": party.ID, "name": party.Name, "description": stringValue(party.Description), "base_currency": party.BaseCurrency, "currency_symbol": h.currencySymbol(c, party.BaseCurrency)} + partyView := gin.H{"id": party.ID, "name": party.Name, "description": stringValue(party.Description), "timezone": party.Timezone, "base_currency": party.BaseCurrency, "currency_symbol": h.currencySymbol(c, party.BaseCurrency)} c.JSON(http.StatusOK, gin.H{"ret": 1, "data": gin.H{"party": partyView, "items": items, "totalAmount": total.String()}}) } From 39e153b94454daab43b118065f4ecde02d0b995c Mon Sep 17 00:00:00 2001 From: pplulee Date: Wed, 9 Sep 2026 18:45:58 +0800 Subject: [PATCH 2/5] feat: add PAT-authenticated OpenAPI and stateless MCP Co-authored-by: Cursor --- cmd/server/main.go | 2 +- frontend/src/pages/ProfilePage.tsx | 130 +++++++++ go.mod | 7 + go.sum | 16 ++ internal/auth/apitoken.go | 117 ++++++++ internal/httpapi/auth.go | 15 +- internal/httpapi/docs.go | 22 ++ internal/httpapi/mcp.go | 192 +++++++++++++ internal/httpapi/middleware.go | 35 ++- internal/httpapi/openapi.json | 176 ++++++++++++ internal/httpapi/router_test.go | 6 + internal/httpapi/swagger.html | 21 ++ internal/httpapi/tokens.go | 66 +++++ internal/httpapi/v1.go | 173 +++++++++++ internal/ledger/ledger.go | 441 +++++++++++++++++++++++++++++ internal/migrate/migrate.go | 13 + internal/migrate/migrate_test.go | 2 +- internal/model/model.go | 15 + 18 files changed, 1445 insertions(+), 4 deletions(-) create mode 100644 internal/auth/apitoken.go create mode 100644 internal/httpapi/docs.go create mode 100644 internal/httpapi/mcp.go create mode 100644 internal/httpapi/openapi.json create mode 100644 internal/httpapi/swagger.html create mode 100644 internal/httpapi/tokens.go create mode 100644 internal/httpapi/v1.go create mode 100644 internal/ledger/ledger.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 2647aeb..f887d3d 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -107,7 +107,7 @@ func run(ctx context.Context) error { server.Engine().StaticFile("/favicon.ico", "public/favicon.ico") server.Engine().StaticFile("/robots.txt", "public/robots.txt") server.Engine().NoRoute(func(c *gin.Context) { - if strings.HasPrefix(c.Request.URL.Path, "/api/") { + if strings.HasPrefix(c.Request.URL.Path, "/api/") || c.Request.URL.Path == "/mcp" { c.JSON(http.StatusNotFound, gin.H{"ret": 0, "msg": "接口不存在"}) return } diff --git a/frontend/src/pages/ProfilePage.tsx b/frontend/src/pages/ProfilePage.tsx index bc95d4c..4c36401 100644 --- a/frontend/src/pages/ProfilePage.tsx +++ b/frontend/src/pages/ProfilePage.tsx @@ -3,6 +3,7 @@ import {useNavigate} from 'react-router-dom'; import {Avatar, Button, Card, Col, Flex, Form, Input, message, Modal, QRCode, Row, Tag, Typography,} from 'antd'; import { DeleteOutlined, + ApiOutlined, KeyOutlined, LockOutlined, MobileOutlined, @@ -18,6 +19,15 @@ import {PageShell, SurfaceCard} from '@/components/ui'; type Device = { id: number; name?: string }; +type APITokenRow = { + id: number; + name: string; + token_prefix: string; + expires_at?: string | null; + last_used_at?: string | null; + created_at?: string; +}; + type SecurityBlockProps = { icon: ReactNode; iconClass: string; @@ -99,6 +109,10 @@ export function ProfilePage() { const [profileSaving, setProfileSaving] = useState(false); const [pwdForm] = Form.useForm(); const [profileForm] = Form.useForm(); + const [tokenForm] = Form.useForm(); + const [tokens, setTokens] = useState([]); + const [tokenSaving, setTokenSaving] = useState(false); + const [createdToken, setCreatedToken] = useState(null); const load = useCallback(async () => { setLoading(true); @@ -122,6 +136,15 @@ export function ProfilePage() { setTotp(data.data?.totp_devices || []); setFido(data.data?.fido_devices || []); if (u) profileForm.setFieldsValue({username: u.username}); + try { + const tokenRes = await apiJson<{ + ret: number; + data?: {tokens?: APITokenRow[]}; + }>('/user/tokens'); + if (tokenRes.ret === 1) setTokens(tokenRes.data?.tokens || []); + } catch { + setTokens([]); + } setLoading(false); }, [nav, profileForm]); @@ -277,6 +300,43 @@ export function ProfilePage() { }); }; + const createToken = async (v: {name: string; expires_at?: string}) => { + setTokenSaving(true); + try { + const res = await apiPostJson('/user/tokens', { + name: v.name.trim(), + expires_at: v.expires_at ? `${v.expires_at}T23:59:59Z` : '', + }); + const out = (await res.json()) as {ret: number; msg?: string; data?: {token?: string}}; + if (out.ret !== 1) { + message.error(out.msg || '创建失败'); + return; + } + tokenForm.resetFields(); + setCreatedToken(out.data?.token || null); + await load(); + } finally { + setTokenSaving(false); + } + }; + + const revokeToken = (row: APITokenRow) => { + Modal.confirm({ + title: `撤销令牌「${row.name}」?`, + content: '撤销后使用该令牌的 OpenAPI / MCP 请求会立即失败。', + okType: 'danger', + onOk: async () => { + const res = await apiDelete(`/user/tokens/${row.id}`); + const out = (await res.json()) as {ret: number; msg?: string}; + if (out.ret !== 1) message.error(out.msg || '失败'); + else { + message.success('已撤销'); + await load(); + } + }, + }); + }; + const initial = user?.username?.charAt(0)?.toUpperCase() || '?'; return ( @@ -453,6 +513,76 @@ export function ProfilePage() { + + + API 访问令牌 + + } + > + + 用于 OpenAPI 与 MCP。明文只显示一次。MCP 地址: + {`${window.location.origin}/mcp`} + ,文档: + + Swagger + + {' / '} + + openapi.json + + 。请求头:Authorization: Bearer bbs_… + +
+ + + + + + + + + +
+ {tokens.length === 0 ? ( + 还没有令牌 + ) : ( +
    + {tokens.map((row) => ( +
  • + + {row.name} · {row.token_prefix}…{row.expires_at ? ` · 过期 ${row.expires_at}` : ''} + {row.last_used_at ? ` · 最近使用 ${row.last_used_at}` : ''} + + +
  • + ))} +
+ )} +
+ + setCreatedToken(null)} + footer={ + + } + > + 此明文不会再次显示。 + + {createdToken} + + + 64 { + name = name[:64] + } + var active int64 + if err := s.db.WithContext(ctx).Table(s.table()).Where("user_id = ? AND revoked_at IS NULL", userID).Count(&active).Error; err != nil { + return "", model.APIToken{}, err + } + if active >= MaxAPITokensPerUser { + return "", model.APIToken{}, ErrAPITokenLimit + } + secret := make([]byte, APITokenSecretBytes) + if _, err := rand.Read(secret); err != nil { + return "", model.APIToken{}, err + } + plain = APITokenPrefix + hex.EncodeToString(secret) + row = model.APIToken{ + UserID: userID, + Name: name, + TokenHash: tokenHash(plain), + TokenPrefix: plain[:apiTokenPrefixLen], + ExpiresAt: expiresAt, + CreatedAt: s.now(), + CreatedIP: stringPtr(ip), + } + if err := s.db.WithContext(ctx).Table(s.table()).Create(&row).Error; err != nil { + return "", model.APIToken{}, err + } + return plain, row, nil +} + +func (s *APITokenService) Revoke(ctx context.Context, userID, tokenID uint64) error { + now := s.now() + res := s.db.WithContext(ctx).Table(s.table()).Where("id = ? AND user_id = ? AND revoked_at IS NULL", tokenID, userID).Update("revoked_at", now) + if res.Error != nil { + return res.Error + } + if res.RowsAffected != 1 { + return ErrAPITokenInvalid + } + return nil +} + +func (s *APITokenService) Lookup(ctx context.Context, plain string) (model.User, error) { + plain = strings.TrimSpace(plain) + if !strings.HasPrefix(plain, APITokenPrefix) { + return model.User{}, ErrAPITokenInvalid + } + var row model.APIToken + if err := s.db.WithContext(ctx).Table(s.table()).Where("token_hash = ?", tokenHash(plain)).First(&row).Error; err != nil { + return model.User{}, ErrAPITokenInvalid + } + now := s.now() + if row.RevokedAt != nil || (row.ExpiresAt != nil && !row.ExpiresAt.After(now)) { + return model.User{}, ErrAPITokenInvalid + } + var user model.User + if err := s.db.WithContext(ctx).Table(s.tablePrefix+"user").First(&user, row.UserID).Error; err != nil || !user.Enable { + return model.User{}, ErrAPITokenInvalid + } + go s.touch(row.ID) + return user, nil +} + +func (s *APITokenService) touch(id uint64) { + now := s.now() + _ = s.db.Table(s.table()).Where("id = ?", id).Update("last_used_at", now).Error +} + +func (s *APITokenService) table() string { return s.tablePrefix + "api_tokens" } diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go index 70521e2..2a04a50 100644 --- a/internal/httpapi/auth.go +++ b/internal/httpapi/auth.go @@ -24,6 +24,7 @@ import ( "github.com/SideCloudGroup/BetterBillSplitter/internal/appconfig" "github.com/SideCloudGroup/BetterBillSplitter/internal/auth" "github.com/SideCloudGroup/BetterBillSplitter/internal/currency" + "github.com/SideCloudGroup/BetterBillSplitter/internal/ledger" "github.com/SideCloudGroup/BetterBillSplitter/internal/model" ) @@ -32,6 +33,8 @@ var usernamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) type Handler struct { db *gorm.DB tokens *auth.TokenService + apiTokens *auth.APITokenService + ledger *ledger.Service tickets *auth.TicketStore challenges *auth.ChallengeStore captchas *auth.CaptchaStore @@ -43,7 +46,12 @@ type Handler struct { } func NewHandler(db *gorm.DB, tokens *auth.TokenService, exchange *currency.Service, cfg appconfig.Config) *Handler { - return &Handler{db: db, tokens: tokens, tickets: auth.NewTicketStore(), challenges: auth.NewChallengeStore(), captchas: auth.NewCaptchaStore(), webSessions: auth.NewWebAuthnSessionStore(), httpClient: &http.Client{Timeout: 8 * time.Second}, exchange: exchange, cfg: cfg, tablePrefix: cfg.Database.TablePrefix} + return &Handler{ + db: db, tokens: tokens, apiTokens: auth.NewAPITokenService(db, cfg.Database.TablePrefix), + ledger: ledger.New(db, cfg.Database.TablePrefix, exchange), tickets: auth.NewTicketStore(), + challenges: auth.NewChallengeStore(), captchas: auth.NewCaptchaStore(), webSessions: auth.NewWebAuthnSessionStore(), + httpClient: &http.Client{Timeout: 8 * time.Second}, exchange: exchange, cfg: cfg, tablePrefix: cfg.Database.TablePrefix, + } } func (h *Handler) Register(engine *gin.Engine) { @@ -73,11 +81,16 @@ func (h *Handler) Register(engine *gin.Engine) { userGroup.GET("/fido_reg", h.fidoRegisterChallenge) userGroup.POST("/fido_reg", h.fidoRegisterVerify) userGroup.DELETE("/fido_reg/:id", h.fidoDelete) + userGroup.GET("/tokens", h.listAPITokens) + userGroup.POST("/tokens", h.createAPIToken) + userGroup.DELETE("/tokens/:id", h.revokeAPIToken) h.registerPartyRoutes(userGroup) h.registerItemRoutes(userGroup) engine.GET("/api/party/invite/:code", h.previewInvite) h.registerAdminRoutes(engine) + h.registerV1Routes(engine) + h.registerMCP(engine) } func (h *Handler) bootstrap(c *gin.Context) { diff --git a/internal/httpapi/docs.go b/internal/httpapi/docs.go new file mode 100644 index 0000000..e0cb2d1 --- /dev/null +++ b/internal/httpapi/docs.go @@ -0,0 +1,22 @@ +package httpapi + +import ( + _ "embed" + "net/http" + + "github.com/gin-gonic/gin" +) + +//go:embed openapi.json +var openAPISpec []byte + +//go:embed swagger.html +var swaggerHTML []byte + +func (h *Handler) serveOpenAPI(c *gin.Context) { + c.Data(http.StatusOK, "application/json; charset=utf-8", openAPISpec) +} + +func (h *Handler) serveSwagger(c *gin.Context) { + c.Data(http.StatusOK, "text/html; charset=utf-8", swaggerHTML) +} diff --git a/internal/httpapi/mcp.go b/internal/httpapi/mcp.go new file mode 100644 index 0000000..0ea0572 --- /dev/null +++ b/internal/httpapi/mcp.go @@ -0,0 +1,192 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/SideCloudGroup/BetterBillSplitter/internal/ledger" + "github.com/SideCloudGroup/BetterBillSplitter/internal/model" +) + +const mcpProtocolVersion = "2026-07-28" + +type partyIDArgs struct { + PartyID uint64 `json:"party_id" jsonschema:"派对ID"` +} + +type createItemArgs struct { + PartyID uint64 `json:"party_id" jsonschema:"派对ID"` + Description string `json:"description" jsonschema:"账目描述"` + Currency string `json:"currency" jsonschema:"货币代码如cny"` + Amount string `json:"amount,omitempty" jsonschema:"均摊时每人金额"` + UserIDs []uint64 `json:"user_ids,omitempty" jsonschema:"均摊付款人用户ID列表"` + Splits []ledger.SplitInput `json:"splits,omitempty" jsonschema:"按人指定金额"` +} + +type updatePaidArgs struct { + ID uint64 `json:"id" jsonschema:"账目ID"` + Paid bool `json:"paid" jsonschema:"是否已付"` +} + +func (h *Handler) registerMCP(engine *gin.Engine) { + server := mcp.NewServer(&mcp.Implementation{Name: "better-bill-splitter", Version: "2.0.0"}, &mcp.ServerOptions{ + Instructions: "BetterBillSplitter 派对分账。使用 PAT Bearer 鉴权。只支持 MCP 协议 2026-07-28,无 session。", + Capabilities: &mcp.ServerCapabilities{}, + }) + h.addMCPTools(server) + inner := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { + return server + }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true}) + engine.Any("/mcp", h.PATRequired(), gin.WrapH(mcpProtocolGate{next: inner})) +} + +func (h *Handler) addMCPTools(server *mcp.Server) { + mcp.AddTool(server, &mcp.Tool{Name: "get_me", Description: "当前 PAT 对应用户"}, func(ctx context.Context, _ *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, ledger.UserView, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, ledger.UserView{}, err + } + return nil, h.ledger.Me(ctx, user), nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "list_parties", Description: "列出当前用户加入或拥有的派对"}, func(ctx context.Context, _ *mcp.CallToolRequest, _ struct{}) (*mcp.CallToolResult, map[string]any, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, nil, err + } + rows, err := h.ledger.ListParties(ctx, user) + if err != nil { + return nil, nil, err + } + return nil, map[string]any{"parties": rows}, nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "get_party", Description: "获取派对详情"}, func(ctx context.Context, _ *mcp.CallToolRequest, in partyIDArgs) (*mcp.CallToolResult, map[string]any, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, nil, err + } + row, err := h.ledger.GetParty(ctx, user, in.PartyID) + if err != nil { + return nil, nil, err + } + return nil, map[string]any{"party": row}, nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "list_members", Description: "列出派对成员"}, func(ctx context.Context, _ *mcp.CallToolRequest, in partyIDArgs) (*mcp.CallToolResult, map[string]any, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, nil, err + } + rows, err := h.ledger.ListMembers(ctx, user, in.PartyID) + if err != nil { + return nil, nil, err + } + return nil, map[string]any{"members": rows}, nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "list_items", Description: "列出派对全部账目"}, func(ctx context.Context, _ *mcp.CallToolRequest, in partyIDArgs) (*mcp.CallToolResult, map[string]any, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, nil, err + } + rows, err := h.ledger.ListItems(ctx, user, in.PartyID) + if err != nil { + return nil, nil, err + } + return nil, map[string]any{"items": rows}, nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "create_item", Description: "在派对中创建分账账目。可按 user_ids+amount 均摊,或用 splits 指定每人金额。"}, func(ctx context.Context, _ *mcp.CallToolRequest, in createItemArgs) (*mcp.CallToolResult, map[string]any, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, nil, err + } + count, err := h.ledger.CreateItem(ctx, user, in.PartyID, ledger.CreateItemInput{ + Description: in.Description, Currency: in.Currency, Amount: in.Amount, UserIDs: in.UserIDs, Splits: in.Splits, + }) + if err != nil { + return nil, nil, err + } + return nil, map[string]any{"count": count}, nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "update_item_paid", Description: "由收款发起方标记账目已付或未付"}, func(ctx context.Context, _ *mcp.CallToolRequest, in updatePaidArgs) (*mcp.CallToolResult, map[string]any, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, nil, err + } + if err := h.ledger.UpdateItemPaid(ctx, user, in.ID, in.Paid); err != nil { + return nil, nil, err + } + return nil, map[string]any{"paid": in.Paid}, nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "list_payments", Description: "列出当前用户在该派对的待付款"}, func(ctx context.Context, _ *mcp.CallToolRequest, in partyIDArgs) (*mcp.CallToolResult, map[string]any, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, nil, err + } + rows, total, err := h.ledger.ListPayments(ctx, user, in.PartyID) + if err != nil { + return nil, nil, err + } + return nil, map[string]any{"items": rows, "total_amount": total}, nil + }) + mcp.AddTool(server, &mcp.Tool{Name: "get_settlement", Description: "计算派对未结清账目的最优支付方案"}, func(ctx context.Context, _ *mcp.CallToolRequest, in partyIDArgs) (*mcp.CallToolResult, ledger.SettlementView, error) { + user, err := requireMCPUser(ctx) + if err != nil { + return nil, ledger.SettlementView{}, err + } + row, err := h.ledger.GetSettlement(ctx, user, in.PartyID) + if err != nil { + return nil, ledger.SettlementView{}, err + } + return nil, row, nil + }) +} + +func requireMCPUser(ctx context.Context) (model.User, error) { + user, ok := userFromContext(ctx) + if !ok { + return model.User{}, &ledger.Error{Status: 401, Message: "未授权"} + } + return user, nil +} + +type mcpProtocolGate struct { + next http.Handler +} + +func (g mcpProtocolGate) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Mcp-Session-Id") != "" { + http.Error(w, "MCP sessions are not supported", http.StatusBadRequest) + return + } + if ver := r.Header.Get("MCP-Protocol-Version"); ver != "" && ver != mcpProtocolVersion { + http.Error(w, "unsupported MCP protocol version", http.StatusBadRequest) + return + } + if r.Method == http.MethodPost && r.Body != nil { + body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20)) + _ = r.Body.Close() + if err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + var probe struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + } + if json.Unmarshal(body, &probe) == nil && probe.Method == "initialize" { + id := probe.ID + if len(id) == 0 { + id = []byte("null") + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(id) + `,"error":{"code":-32022,"message":"Unsupported protocol version; use 2026-07-28"}}`)) + return + } + } + g.next.ServeHTTP(w, r) +} diff --git a/internal/httpapi/middleware.go b/internal/httpapi/middleware.go index d6da3ee..29f4b28 100644 --- a/internal/httpapi/middleware.go +++ b/internal/httpapi/middleware.go @@ -1,6 +1,7 @@ package httpapi import ( + "context" "net/http" "strings" @@ -11,6 +12,8 @@ import ( const userContextKey = "authenticated_user" +type requestUserKey struct{} + func (h *Handler) AuthRequired() gin.HandlerFunc { return func(c *gin.Context) { header := c.GetHeader("Authorization") @@ -28,11 +31,41 @@ func (h *Handler) AuthRequired() gin.HandlerFunc { c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"ok": false, "error": "用户不可用"}) return } - c.Set(userContextKey, user) + setRequestUser(c, user) + c.Next() + } +} + +func (h *Handler) PATRequired() gin.HandlerFunc { + return func(c *gin.Context) { + header := c.GetHeader("Authorization") + if !strings.HasPrefix(header, "Bearer ") { + c.Header("WWW-Authenticate", `Bearer realm="BetterBillSplitter"`) + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"ok": false, "error": "未授权"}) + return + } + plain := strings.TrimSpace(strings.TrimPrefix(header, "Bearer ")) + user, err := h.apiTokens.Lookup(c, plain) + if err != nil { + c.Header("WWW-Authenticate", `Bearer realm="BetterBillSplitter"`) + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"ok": false, "error": "令牌无效或已过期"}) + return + } + setRequestUser(c, user) c.Next() } } +func setRequestUser(c *gin.Context, user model.User) { + c.Set(userContextKey, user) + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), requestUserKey{}, user)) +} + +func userFromContext(ctx context.Context) (model.User, bool) { + user, ok := ctx.Value(requestUserKey{}).(model.User) + return user, ok +} + func (h *Handler) AdminRequired() gin.HandlerFunc { return func(c *gin.Context) { user, ok := currentUser(c) diff --git a/internal/httpapi/openapi.json b/internal/httpapi/openapi.json new file mode 100644 index 0000000..3147b36 --- /dev/null +++ b/internal/httpapi/openapi.json @@ -0,0 +1,176 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "BetterBillSplitter API", + "version": "1.0.0", + "description": "使用账户页创建的 Bearer PAT(bbs_ 前缀)访问。不接受浏览器登录 JWT。" + }, + "servers": [{ "url": "/" }], + "security": [{ "bearerAuth": [] }], + "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "PAT", + "description": "账户页创建的 API 令牌" + } + }, + "schemas": { + "Error": { + "type": "object", + "properties": { + "ok": { "type": "boolean", "example": false }, + "error": { "type": "string" } + } + }, + "Party": { + "type": "object", + "properties": { + "id": { "type": "integer" }, + "name": { "type": "string" }, + "description": { "type": "string" }, + "timezone": { "type": "string" }, + "base_currency": { "type": "string" }, + "supported_currencies": { "type": "array", "items": { "type": "string" } }, + "archived": { "type": "boolean" }, + "role": { "type": "string", "enum": ["owner", "member"] }, + "owner_id": { "type": "integer" } + } + }, + "Member": { + "type": "object", + "properties": { + "id": { "type": "integer" }, + "username": { "type": "string" }, + "joined_at": { "type": "string", "format": "date-time" }, + "is_owner": { "type": "boolean" } + } + }, + "Item": { + "type": "object", + "properties": { + "id": { "type": "integer" }, + "description": { "type": "string" }, + "amount": { "type": "string" }, + "paid": { "type": "boolean" }, + "created_at": { "type": "string", "format": "date-time" }, + "payer_id": { "type": "integer" }, + "payer_name": { "type": "string" }, + "initiator_id": { "type": "integer" }, + "initiator_name": { "type": "string" } + } + }, + "CreateItem": { + "type": "object", + "required": ["description", "currency"], + "properties": { + "description": { "type": "string" }, + "currency": { "type": "string", "description": "货币代码,如 cny" }, + "amount": { "type": "string", "description": "均摊时每人金额" }, + "user_ids": { "type": "array", "items": { "type": "integer" } }, + "splits": { + "type": "array", + "items": { + "type": "object", + "required": ["user_id", "amount"], + "properties": { + "user_id": { "type": "integer" }, + "amount": { "type": "string" } + } + } + } + } + } + } + }, + "paths": { + "/api/v1/me": { + "get": { + "summary": "当前用户", + "operationId": "getMe", + "responses": { + "200": { "description": "OK" }, + "401": { "description": "未授权", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } } + } + } + }, + "/api/v1/parties": { + "get": { + "summary": "列出派对", + "operationId": "listParties", + "responses": { "200": { "description": "OK" }, "401": { "description": "未授权" } } + } + }, + "/api/v1/parties/{partyId}": { + "get": { + "summary": "派对详情", + "operationId": "getParty", + "parameters": [{ "name": "partyId", "in": "path", "required": true, "schema": { "type": "integer" } }], + "responses": { "200": { "description": "OK" }, "403": { "description": "非成员" }, "404": { "description": "不存在" } } + } + }, + "/api/v1/parties/{partyId}/members": { + "get": { + "summary": "派对成员", + "operationId": "listMembers", + "parameters": [{ "name": "partyId", "in": "path", "required": true, "schema": { "type": "integer" } }], + "responses": { "200": { "description": "OK" } } + } + }, + "/api/v1/parties/{partyId}/items": { + "get": { + "summary": "派对账目", + "operationId": "listItems", + "parameters": [{ "name": "partyId", "in": "path", "required": true, "schema": { "type": "integer" } }], + "responses": { "200": { "description": "OK" } } + }, + "post": { + "summary": "创建分账", + "operationId": "createItem", + "parameters": [{ "name": "partyId", "in": "path", "required": true, "schema": { "type": "integer" } }], + "requestBody": { + "required": true, + "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateItem" } } } + }, + "responses": { "200": { "description": "OK" }, "400": { "description": "参数错误" } } + } + }, + "/api/v1/parties/{partyId}/payments": { + "get": { + "summary": "当前用户待付款", + "operationId": "listPayments", + "parameters": [{ "name": "partyId", "in": "path", "required": true, "schema": { "type": "integer" } }], + "responses": { "200": { "description": "OK" } } + } + }, + "/api/v1/parties/{partyId}/settlement": { + "get": { + "summary": "最优支付方案", + "operationId": "getSettlement", + "parameters": [{ "name": "partyId", "in": "path", "required": true, "schema": { "type": "integer" } }], + "responses": { "200": { "description": "OK" } } + } + }, + "/api/v1/items/{id}": { + "patch": { + "summary": "标记已付/未付(仅发起方)", + "operationId": "updateItemPaid", + "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "integer" } }], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["paid"], + "properties": { "paid": { "type": "boolean" } } + } + } + } + }, + "responses": { "200": { "description": "OK" }, "404": { "description": "未找到" } } + } + } + } +} diff --git a/internal/httpapi/router_test.go b/internal/httpapi/router_test.go index 336ec53..18cc8b0 100644 --- a/internal/httpapi/router_test.go +++ b/internal/httpapi/router_test.go @@ -54,6 +54,7 @@ func TestRegisterAllRoutesDoesNotConflict(t *testing.T) { "GET /api/user/webauthn_reg", "POST /api/user/webauthn_reg", "DELETE /api/user/webauthn_reg/:id", "GET /api/user/totp_reg", "POST /api/user/totp_reg", "DELETE /api/user/totp_reg", "GET /api/user/fido_reg", "POST /api/user/fido_reg", "DELETE /api/user/fido_reg/:id", + "GET /api/user/tokens", "POST /api/user/tokens", "DELETE /api/user/tokens/:id", "GET /api/user/party/create", "GET /api/user/party/join", "POST /api/user/party/join", "GET /api/user/party/:partyId/users", "GET /api/user/party/:partyId/info", "GET /api/user/party/:partyId/edit", "POST /api/user/party/:partyId/update", @@ -71,6 +72,11 @@ func TestRegisterAllRoutesDoesNotConflict(t *testing.T) { "POST /api/admin/currency/add", "GET /api/admin/currency/edit-form", "POST /api/admin/currency/edit", "DELETE /api/admin/currency/delete", "GET /api/admin/currencies", "GET /api/admin/setting", "POST /api/admin/setting", + "GET /api/v1/openapi.json", "GET /api/v1/docs", "GET /api/v1/me", "GET /api/v1/parties", + "GET /api/v1/parties/:partyId", "GET /api/v1/parties/:partyId/members", + "GET /api/v1/parties/:partyId/items", "POST /api/v1/parties/:partyId/items", + "GET /api/v1/parties/:partyId/payments", "GET /api/v1/parties/:partyId/settlement", + "PATCH /api/v1/items/:id", "POST /mcp", "GET /mcp", "DELETE /mcp", "PUT /mcp", "PATCH /mcp", "HEAD /mcp", "OPTIONS /mcp", } for _, route := range expected { if !routes[route] { diff --git a/internal/httpapi/swagger.html b/internal/httpapi/swagger.html new file mode 100644 index 0000000..9a3dc04 --- /dev/null +++ b/internal/httpapi/swagger.html @@ -0,0 +1,21 @@ + + + + + + BetterBillSplitter API + + + + +
+ + + + diff --git a/internal/httpapi/tokens.go b/internal/httpapi/tokens.go new file mode 100644 index 0000000..68bd8ad --- /dev/null +++ b/internal/httpapi/tokens.go @@ -0,0 +1,66 @@ +package httpapi + +import ( + "errors" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "github.com/SideCloudGroup/BetterBillSplitter/internal/auth" +) + +func (h *Handler) listAPITokens(c *gin.Context) { + user, _ := currentUser(c) + rows, err := h.apiTokens.List(c, user.ID) + if err != nil { + legacyServiceError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"ret": 1, "data": gin.H{"tokens": rows, "mcp_url": "/mcp", "openapi_url": "/api/v1/openapi.json", "docs_url": "/api/v1/docs"}}) +} + +func (h *Handler) createAPIToken(c *gin.Context) { + user, _ := currentUser(c) + var input struct { + Name string `json:"name" form:"name"` + ExpiresAt string `json:"expires_at" form:"expires_at"` + } + _ = c.ShouldBind(&input) + var expires *time.Time + if raw := strings.TrimSpace(input.ExpiresAt); raw != "" { + parsed, err := time.Parse(time.RFC3339, raw) + if err != nil { + parsed, err = time.Parse("2006-01-02", raw) + } + if err != nil { + legacyError(c, "过期时间格式无效") + return + } + expires = &parsed + } + plain, row, err := h.apiTokens.Create(c, user.ID, input.Name, c.ClientIP(), expires) + if errors.Is(err, auth.ErrAPITokenLimit) { + legacyError(c, "令牌数量已达上限") + return + } + if err != nil { + legacyError(c, err.Error()) + return + } + c.JSON(http.StatusOK, gin.H{"ret": 1, "msg": "令牌已创建,请立即复制保存", "data": gin.H{"id": row.ID, "name": row.Name, "token": plain, "token_prefix": row.TokenPrefix, "expires_at": row.ExpiresAt, "created_at": row.CreatedAt}}) +} + +func (h *Handler) revokeAPIToken(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parseID(c, "id") + if !ok { + return + } + if err := h.apiTokens.Revoke(c, user.ID, id); err != nil { + legacyError(c, "令牌不存在或已撤销") + return + } + c.JSON(http.StatusOK, gin.H{"ret": 1, "msg": "已撤销"}) +} diff --git a/internal/httpapi/v1.go b/internal/httpapi/v1.go new file mode 100644 index 0000000..31f5884 --- /dev/null +++ b/internal/httpapi/v1.go @@ -0,0 +1,173 @@ +package httpapi + +import ( + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + + "github.com/SideCloudGroup/BetterBillSplitter/internal/ledger" +) + +func (h *Handler) registerV1Routes(engine *gin.Engine) { + engine.GET("/api/v1/openapi.json", h.serveOpenAPI) + engine.GET("/api/v1/docs", h.serveSwagger) + group := engine.Group("/api/v1", h.PATRequired()) + group.GET("/me", h.v1Me) + group.GET("/parties", h.v1ListParties) + group.GET("/parties/:partyId", h.v1GetParty) + group.GET("/parties/:partyId/members", h.v1ListMembers) + group.GET("/parties/:partyId/items", h.v1ListItems) + group.POST("/parties/:partyId/items", h.v1CreateItem) + group.GET("/parties/:partyId/payments", h.v1ListPayments) + group.GET("/parties/:partyId/settlement", h.v1GetSettlement) + group.PATCH("/items/:id", h.v1UpdateItem) +} + +func v1OK(c *gin.Context, data any) { + c.JSON(http.StatusOK, gin.H{"ok": true, "data": data}) +} + +func v1Fail(c *gin.Context, err error) { + if e := ledger.AsError(err); e != nil { + c.JSON(e.Status, gin.H{"ok": false, "error": e.Message}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"ok": false, "error": err.Error()}) +} + +func (h *Handler) v1Me(c *gin.Context) { + user, _ := currentUser(c) + v1OK(c, h.ledger.Me(c, user)) +} + +func (h *Handler) v1ListParties(c *gin.Context) { + user, _ := currentUser(c) + rows, err := h.ledger.ListParties(c, user) + if err != nil { + v1Fail(c, err) + return + } + v1OK(c, gin.H{"parties": rows}) +} + +func (h *Handler) v1GetParty(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parsePathID(c.Param("partyId")) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "ID无效"}) + return + } + row, err := h.ledger.GetParty(c, user, id) + if err != nil { + v1Fail(c, err) + return + } + v1OK(c, gin.H{"party": row}) +} + +func (h *Handler) v1ListMembers(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parsePathID(c.Param("partyId")) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "ID无效"}) + return + } + rows, err := h.ledger.ListMembers(c, user, id) + if err != nil { + v1Fail(c, err) + return + } + v1OK(c, gin.H{"members": rows}) +} + +func (h *Handler) v1ListItems(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parsePathID(c.Param("partyId")) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "ID无效"}) + return + } + rows, err := h.ledger.ListItems(c, user, id) + if err != nil { + v1Fail(c, err) + return + } + v1OK(c, gin.H{"items": rows}) +} + +func (h *Handler) v1CreateItem(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parsePathID(c.Param("partyId")) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "ID无效"}) + return + } + var input ledger.CreateItemInput + if err := c.ShouldBindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "请求格式错误"}) + return + } + count, err := h.ledger.CreateItem(c, user, id, input) + if err != nil { + v1Fail(c, err) + return + } + v1OK(c, gin.H{"count": count}) +} + +func (h *Handler) v1ListPayments(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parsePathID(c.Param("partyId")) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "ID无效"}) + return + } + rows, total, err := h.ledger.ListPayments(c, user, id) + if err != nil { + v1Fail(c, err) + return + } + v1OK(c, gin.H{"items": rows, "total_amount": total}) +} + +func (h *Handler) v1GetSettlement(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parsePathID(c.Param("partyId")) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "ID无效"}) + return + } + row, err := h.ledger.GetSettlement(c, user, id) + if err != nil { + v1Fail(c, err) + return + } + v1OK(c, row) +} + +func (h *Handler) v1UpdateItem(c *gin.Context) { + user, _ := currentUser(c) + id, ok := parsePathID(c.Param("id")) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "ID无效"}) + return + } + var input struct { + Paid *bool `json:"paid"` + } + if err := c.ShouldBindJSON(&input); err != nil || input.Paid == nil { + c.JSON(http.StatusBadRequest, gin.H{"ok": false, "error": "请提供 paid"}) + return + } + if err := h.ledger.UpdateItemPaid(c, user, id, *input.Paid); err != nil { + v1Fail(c, err) + return + } + v1OK(c, gin.H{"paid": *input.Paid}) +} + +func parsePathID(value string) (uint64, bool) { + id, err := strconv.ParseUint(value, 10, 64) + return id, err == nil && id > 0 +} diff --git a/internal/ledger/ledger.go b/internal/ledger/ledger.go new file mode 100644 index 0000000..7da3ac2 --- /dev/null +++ b/internal/ledger/ledger.go @@ -0,0 +1,441 @@ +package ledger + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "gorm.io/gorm" + + "github.com/SideCloudGroup/BetterBillSplitter/internal/currency" + "github.com/SideCloudGroup/BetterBillSplitter/internal/model" + "github.com/SideCloudGroup/BetterBillSplitter/internal/money" + "github.com/SideCloudGroup/BetterBillSplitter/internal/settlement" +) + +type Error struct { + Status int + Message string +} + +func (e *Error) Error() string { return e.Message } + +func errBad(msg string) error { return &Error{Status: 400, Message: msg} } +func errForbidden(msg string) error { return &Error{Status: 403, Message: msg} } +func errNotFound(msg string) error { return &Error{Status: 404, Message: msg} } + +func AsError(err error) *Error { + var e *Error + if errors.As(err, &e) { + return e + } + return nil +} + +type Service struct { + db *gorm.DB + prefix string + exchange *currency.Service +} + +func New(db *gorm.DB, prefix string, exchange *currency.Service) *Service { + return &Service{db: db, prefix: prefix, exchange: exchange} +} + +func (s *Service) table(name string) string { return s.prefix + name } + +type UserView struct { + ID uint64 `json:"id"` + Username string `json:"username"` +} + +type PartyView struct { + ID uint64 `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Timezone string `json:"timezone"` + BaseCurrency string `json:"base_currency"` + Currencies []string `json:"supported_currencies"` + Archived bool `json:"archived"` + Role string `json:"role"` + OwnerID uint64 `json:"owner_id"` +} + +type MemberView struct { + ID uint64 `json:"id"` + Username string `json:"username"` + JoinedAt time.Time `json:"joined_at"` + IsOwner bool `json:"is_owner"` +} + +type ItemView struct { + ID uint64 `json:"id"` + Description string `json:"description"` + Amount string `json:"amount"` + Paid bool `json:"paid"` + CreatedAt time.Time `json:"created_at"` + PayerID uint64 `json:"payer_id"` + PayerName string `json:"payer_name"` + InitiatorID uint64 `json:"initiator_id"` + InitiatorName string `json:"initiator_name"` +} + +type SplitInput struct { + UserID uint64 `json:"user_id" jsonschema:"付款人用户ID"` + Amount string `json:"amount" jsonschema:"金额"` +} + +type CreateItemInput struct { + Description string `json:"description"` + Currency string `json:"currency"` + Amount string `json:"amount"` + UserIDs []uint64 `json:"user_ids"` + Splits []SplitInput `json:"splits"` +} + +type SettlementView struct { + BestPayAll map[string]map[string]string `json:"best_pay_all"` + BestPayFinal map[string]map[string]string `json:"best_pay_final"` + UserStat map[string]UserStat `json:"user_stat"` +} + +type UserStat struct { + In string `json:"in"` + Out string `json:"out"` +} + +func (s *Service) Me(_ context.Context, user model.User) UserView { + return UserView{ID: user.ID, Username: user.Username} +} + +func (s *Service) ListParties(ctx context.Context, user model.User) ([]PartyView, error) { + var owned, joined []model.Party + if err := s.db.WithContext(ctx).Table(s.table("party")).Where("owner_id = ?", user.ID).Order("updated_at DESC").Find(&owned).Error; err != nil { + return nil, err + } + join := fmt.Sprintf("JOIN %s pm ON %s.id = pm.party_id", s.table("party_member"), s.table("party")) + if err := s.db.WithContext(ctx).Table(s.table("party")).Joins(join).Where("pm.user_id = ? AND "+s.table("party")+".owner_id <> ?", user.ID, user.ID).Select(s.table("party") + ".*").Order(s.table("party") + ".updated_at DESC").Find(&joined).Error; err != nil { + return nil, err + } + out := make([]PartyView, 0, len(owned)+len(joined)) + for _, p := range owned { + out = append(out, partyView(p, "owner")) + } + for _, p := range joined { + out = append(out, partyView(p, "member")) + } + return out, nil +} + +func (s *Service) GetParty(ctx context.Context, user model.User, partyID uint64) (PartyView, error) { + party, err := s.memberParty(ctx, user.ID, partyID) + if err != nil { + return PartyView{}, err + } + role := "member" + if party.OwnerID == user.ID { + role = "owner" + } + return partyView(party, role), nil +} + +func (s *Service) ListMembers(ctx context.Context, user model.User, partyID uint64) ([]MemberView, error) { + party, err := s.memberParty(ctx, user.ID, partyID) + if err != nil { + return nil, err + } + var rows []struct { + ID uint64 + Username string + JoinedAt time.Time `gorm:"column:joined_at"` + } + query := fmt.Sprintf("SELECT u.id, u.username, pm.joined_at FROM %s pm JOIN %s u ON pm.user_id=u.id WHERE pm.party_id=? ORDER BY pm.id", s.table("party_member"), s.table("user")) + if err := s.db.WithContext(ctx).Raw(query, party.ID).Scan(&rows).Error; err != nil { + return nil, err + } + out := make([]MemberView, 0, len(rows)) + for _, row := range rows { + out = append(out, MemberView{ID: row.ID, Username: row.Username, JoinedAt: row.JoinedAt, IsOwner: row.ID == party.OwnerID}) + } + return out, nil +} + +func (s *Service) ListItems(ctx context.Context, user model.User, partyID uint64) ([]ItemView, error) { + party, err := s.memberParty(ctx, user.ID, partyID) + if err != nil { + return nil, err + } + var rows []ItemView + query := fmt.Sprintf("SELECT i.id,i.description,i.amount,i.paid,i.created_at,i.userid payer_id,p.username payer_name,i.initiator initiator_id,iu.username initiator_name FROM %s i JOIN %s p ON i.userid=p.id JOIN %s iu ON i.initiator=iu.id WHERE i.party_id=? ORDER BY i.created_at DESC", s.table("item"), s.table("user"), s.table("user")) + if err := s.db.WithContext(ctx).Raw(query, party.ID).Scan(&rows).Error; err != nil { + return nil, err + } + if rows == nil { + rows = []ItemView{} + } + return rows, nil +} + +func (s *Service) ListPayments(ctx context.Context, user model.User, partyID uint64) ([]ItemView, string, error) { + party, err := s.memberParty(ctx, user.ID, partyID) + if err != nil { + return nil, "", err + } + var rows []ItemView + query := fmt.Sprintf("SELECT i.id,i.description,i.amount,i.paid,i.created_at,i.userid payer_id,u.username payer_name,i.initiator initiator_id,iu.username initiator_name FROM %s i JOIN %s iu ON i.initiator=iu.id JOIN %s u ON i.userid=u.id WHERE i.party_id=? AND i.userid=? AND i.paid=0 ORDER BY i.created_at DESC", s.table("item"), s.table("user"), s.table("user")) + if err := s.db.WithContext(ctx).Raw(query, party.ID, user.ID).Scan(&rows).Error; err != nil { + return nil, "", err + } + var total money.Amount + for _, row := range rows { + amount, err := money.Parse(row.Amount) + if err != nil { + return nil, "", err + } + total += amount + } + if rows == nil { + rows = []ItemView{} + } + return rows, total.String(), nil +} + +func (s *Service) CreateItem(ctx context.Context, user model.User, partyID uint64, input CreateItemInput) (int, error) { + party, err := s.memberParty(ctx, user.ID, partyID) + if err != nil { + return 0, err + } + if party.ArchivedAt != nil { + return 0, errForbidden("该派对已归档,无法添加收款项") + } + description := strings.TrimSpace(input.Description) + unit := strings.ToLower(strings.TrimSpace(input.Currency)) + if description == "" { + return 0, errBad("描述不能为空") + } + if unit == "" { + return 0, errBad("货币不能为空") + } + supported := decodeCurrencies(party) + okUnit := false + for _, code := range supported { + if strings.ToLower(code) == unit { + okUnit = true + break + } + } + if !okUnit { + return 0, errBad("该派对不支持此货币") + } + type allocation struct { + userID uint64 + amount string + } + allocations := make([]allocation, 0) + if len(input.Splits) > 0 { + seen := map[uint64]bool{} + for index, split := range input.Splits { + amount, err := money.Parse(split.Amount) + if split.UserID == 0 { + return 0, errBad(fmt.Sprintf("分摊第 %d 项用户无效", index+1)) + } + if err != nil || amount <= 0 { + return 0, errBad(fmt.Sprintf("分摊第 %d 项金额必须大于 0", index+1)) + } + if seen[split.UserID] { + return 0, errBad("同一用户不能重复分摊") + } + seen[split.UserID] = true + allocations = append(allocations, allocation{split.UserID, amount.String()}) + } + } else { + if len(input.UserIDs) == 0 { + return 0, errBad("用户不能为空") + } + amount, err := money.Parse(input.Amount) + if err != nil || amount <= 0 { + return 0, errBad("金额必须大于 0") + } + seen := map[uint64]bool{} + for _, userID := range input.UserIDs { + if userID == 0 || seen[userID] { + return 0, errBad("用户无效或重复") + } + seen[userID] = true + allocations = append(allocations, allocation{userID, amount.String()}) + } + } + memberIDs := make([]uint64, 0, len(allocations)) + for _, a := range allocations { + memberIDs = append(memberIDs, a.userID) + } + var memberCount int64 + s.db.WithContext(ctx).Table(s.table("party_member")).Where("party_id = ? AND user_id IN ?", party.ID, memberIDs).Count(&memberCount) + if memberCount != int64(len(memberIDs)) { + return 0, errBad("包含不属于该派对的用户") + } + if unit != strings.ToLower(party.BaseCurrency) { + if s.exchange == nil { + return 0, errBad("无法获取该货币的汇率信息") + } + rates, err := s.exchange.Rates(ctx, party.BaseCurrency) + if err != nil || rates[unit] == "" { + return 0, errBad("无法获取该货币的汇率信息") + } + for index := range allocations { + converted, err := money.ConvertToBaseCurrency(allocations[index].amount, rates[unit]) + if err != nil || converted <= 0 { + return 0, errBad("无法获取该货币的汇率信息") + } + allocations[index].amount = converted.String() + } + } + location, _ := time.LoadLocation(party.Timezone) + createdAt := time.Now() + if location != nil { + createdAt = createdAt.In(location) + } + err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + for _, a := range allocations { + id := party.ID + item := model.Item{UserID: a.userID, Description: description, CreatedAt: createdAt, Amount: a.amount, Paid: a.userID == user.ID, Initiator: user.ID, PartyID: &id} + if err := tx.Table(s.table("item")).Create(&item).Error; err != nil { + return err + } + } + return nil + }) + if err != nil { + return 0, err + } + return len(allocations), nil +} + +func (s *Service) UpdateItemPaid(ctx context.Context, user model.User, itemID uint64, paid bool) error { + var item model.Item + if err := s.db.WithContext(ctx).Table(s.table("item")).Where("id = ? AND initiator = ?", itemID, user.ID).First(&item).Error; err != nil { + return errNotFound("未找到指定项目") + } + if item.PartyID == nil { + return errForbidden("您不是该派对的成员") + } + if !s.isMember(ctx, *item.PartyID, user.ID) { + return errForbidden("您不是该派对的成员") + } + var party model.Party + if s.db.WithContext(ctx).Table(s.table("party")).First(&party, *item.PartyID).Error == nil && party.ArchivedAt != nil { + return errForbidden("该派对已归档,无法修改支付状态") + } + return s.db.WithContext(ctx).Table(s.table("item")).Where("id = ?", itemID).Update("paid", paid).Error +} + +func (s *Service) GetSettlement(ctx context.Context, user model.User, partyID uint64) (SettlementView, error) { + if _, err := s.memberParty(ctx, user.ID, partyID); err != nil { + return SettlementView{}, err + } + var memberRows []struct { + ID uint64 + Username string + } + query := fmt.Sprintf("SELECT u.id,u.username FROM %s pm JOIN %s u ON pm.user_id=u.id WHERE pm.party_id=? ORDER BY pm.id", s.table("party_member"), s.table("user")) + if err := s.db.WithContext(ctx).Raw(query, partyID).Scan(&memberRows).Error; err != nil { + return SettlementView{}, err + } + users := make([]settlement.User, 0, len(memberRows)) + for _, row := range memberRows { + users = append(users, settlement.User{ID: int64(row.ID), Username: row.Username}) + } + var itemRows []struct { + UserID uint64 `gorm:"column:userid"` + Initiator uint64 + Amount string + } + if err := s.db.WithContext(ctx).Table(s.table("item")).Select("userid, initiator, amount").Where("party_id = ? AND paid = 0", partyID).Order("id").Scan(&itemRows).Error; err != nil { + return SettlementView{}, err + } + items := make([]settlement.Item, 0, len(itemRows)) + inTotals := make(map[int64]money.Amount) + outTotals := make(map[int64]money.Amount) + for _, row := range itemRows { + amount, err := money.Parse(row.Amount) + if err != nil { + return SettlementView{}, err + } + inTotals[int64(row.Initiator)] += amount + outTotals[int64(row.UserID)] += amount + items = append(items, settlement.Item{UserID: int64(row.UserID), Initiator: int64(row.Initiator), Amount: row.Amount}) + } + stats := make(map[string]UserStat, len(users)) + for _, u := range users { + stats[u.Username] = UserStat{In: inTotals[u.ID].String(), Out: outTotals[u.ID].String()} + } + unpaid, err := settlement.AggregateUnpaid(items) + if err != nil { + return SettlementView{}, err + } + optimized, stage1 := settlement.Compute(unpaid, users) + return SettlementView{BestPayAll: debtsMap(stage1), BestPayFinal: debtsMap(optimized), UserStat: stats}, nil +} + +func (s *Service) memberParty(ctx context.Context, userID, partyID uint64) (model.Party, error) { + var party model.Party + if partyID == 0 || s.db.WithContext(ctx).Table(s.table("party")).First(&party, partyID).Error != nil { + return party, errNotFound("派对不存在") + } + if !s.isMember(ctx, party.ID, userID) { + return party, errForbidden("您不是该派对的成员") + } + return party, nil +} + +func (s *Service) isMember(ctx context.Context, partyID, userID uint64) bool { + var count int64 + s.db.WithContext(ctx).Table(s.table("party_member")).Where("party_id = ? AND user_id = ?", partyID, userID).Count(&count) + return count > 0 +} + +func partyView(p model.Party, role string) PartyView { + desc := "" + if p.Description != nil { + desc = *p.Description + } + return PartyView{ + ID: p.ID, Name: p.Name, Description: desc, Timezone: p.Timezone, + BaseCurrency: p.BaseCurrency, Currencies: decodeCurrencies(p), + Archived: p.ArchivedAt != nil, Role: role, OwnerID: p.OwnerID, + } +} + +func decodeCurrencies(party model.Party) []string { + result := []string{party.BaseCurrency} + if party.SupportedCurrencies != nil { + var decoded []string + if json.Unmarshal([]byte(*party.SupportedCurrencies), &decoded) == nil && len(decoded) > 0 { + result = decoded + } + } + found := false + for _, code := range result { + if code == party.BaseCurrency { + found = true + } + } + if !found { + result = append(result, party.BaseCurrency) + } + return result +} + +func debtsMap(debts settlement.Debts) map[string]map[string]string { + result := make(map[string]map[string]string, len(debts)) + for debtor, creditors := range debts { + result[debtor] = make(map[string]string, len(creditors)) + for creditor, amount := range creditors { + result[debtor][creditor] = amount.String() + } + } + return result +} diff --git a/internal/migrate/migrate.go b/internal/migrate/migrate.go index 5966477..728d71f 100644 --- a/internal/migrate/migrate.go +++ b/internal/migrate/migrate.go @@ -227,5 +227,18 @@ ALTER TABLE %s ADD KEY idx_mfa_userid_type (userid, type), ADD KEY idx_mfa_rawid ALTER TABLE %s ADD KEY idx_item_party_paid (party_id, paid), ADD KEY idx_item_party_userid_paid (party_id, userid, paid), ADD KEY idx_item_party_initiator_paid (party_id, initiator, paid), ADD KEY idx_item_userid_paid (userid, paid), ADD KEY idx_item_initiator_paid (initiator, paid), ADD KEY idx_item_created_at (created_at); ALTER TABLE %s ADD KEY idx_party_owner_archived (owner_id, archived_at), ADD KEY idx_party_base_currency (base_currency); ALTER TABLE %s ADD KEY idx_refresh_user_revoked (user_id, revoked_at), ADD KEY idx_refresh_expires_at (expires_at)`, table("user"), table("setting"), quote("key"), table("mfa_credential"), table("item"), table("party"), table("refresh_tokens")))}, + {20260909120000, "CreateAPITokensTable", []string{fmt.Sprintf(`CREATE TABLE %s ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + user_id INT NOT NULL, + name VARCHAR(64) NOT NULL, + token_hash VARCHAR(64) NOT NULL, + token_prefix VARCHAR(16) NOT NULL, + expires_at DATETIME NULL, + revoked_at DATETIME NULL, + last_used_at DATETIME NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + created_ip VARCHAR(45) NULL, + KEY user_id (user_id), UNIQUE KEY token_hash (token_hash), KEY idx_api_token_user_revoked (user_id, revoked_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`, table("api_tokens"))}}, } } diff --git a/internal/migrate/migrate_test.go b/internal/migrate/migrate_test.go index a605c0a..40bd1a4 100644 --- a/internal/migrate/migrate_test.go +++ b/internal/migrate/migrate_test.go @@ -13,7 +13,7 @@ func TestLegacyVersionsMatchPHPFilenames(t *testing.T) { 20240512222608, 20241002123454, 20241008220049, 20250108084543, 20250819200000, 20250819200001, 20250819200002, 20250819200003, 20250820000000, 20250820122215, 20260518120000, 20260518140000, - 20260519050950, + 20260519050950, 20260909120000, } got := legacyMigrations("") if len(got) != len(want) { diff --git a/internal/model/model.go b/internal/model/model.go index 0f77c1f..aabc292 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -26,6 +26,21 @@ type RefreshToken struct { func (RefreshToken) TableName() string { return "refresh_tokens" } +type APIToken struct { + ID uint64 `gorm:"primaryKey" json:"id"` + UserID uint64 `gorm:"column:user_id" json:"user_id"` + Name string `json:"name"` + TokenHash string `gorm:"column:token_hash" json:"-"` + TokenPrefix string `gorm:"column:token_prefix" json:"token_prefix"` + ExpiresAt *time.Time `gorm:"column:expires_at" json:"expires_at"` + RevokedAt *time.Time `gorm:"column:revoked_at" json:"revoked_at"` + LastUsedAt *time.Time `gorm:"column:last_used_at" json:"last_used_at"` + CreatedAt time.Time `gorm:"column:created_at" json:"created_at"` + CreatedIP *string `gorm:"column:created_ip" json:"-"` +} + +func (APIToken) TableName() string { return "api_tokens" } + type Setting struct { ID uint64 `gorm:"primaryKey"` Key string `gorm:"column:key"` From 2cba70eb0b83cd51eae2c7114ac3d7b8799205bb Mon Sep 17 00:00:00 2001 From: pplulee Date: Wed, 9 Sep 2026 18:54:23 +0800 Subject: [PATCH 3/5] fix: bump grpc for CVE-2026-84304 and cancel overlapping CI Co-authored-by: Cursor --- .github/workflows/docker.yml | 2 +- .github/workflows/go-tests.yml | 2 +- go.mod | 20 +++++++-------- go.sum | 46 ++++++++++++++++++---------------- 4 files changed, 36 insertions(+), 34 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index b5ace92..f149970 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -15,7 +15,7 @@ env: IMAGE_NAME: ${{ github.repository }} concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: diff --git a/.github/workflows/go-tests.yml b/.github/workflows/go-tests.yml index 3d71767..bf2c33a 100644 --- a/.github/workflows/go-tests.yml +++ b/.github/workflows/go-tests.yml @@ -6,7 +6,7 @@ on: pull_request: concurrency: - group: go-tests-${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: diff --git a/go.mod b/go.mod index a862166..a869200 100644 --- a/go.mod +++ b/go.mod @@ -88,30 +88,30 @@ require ( github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.65.0 // indirect - go.opentelemetry.io/otel v1.42.0 // indirect + go.opentelemetry.io/otel v1.44.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.40.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.40.0 // indirect go.opentelemetry.io/otel/exporters/prometheus v0.62.0 // indirect - go.opentelemetry.io/otel/metric v1.42.0 // indirect - go.opentelemetry.io/otel/sdk v1.42.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect - go.opentelemetry.io/otel/trace v1.42.0 // indirect + go.opentelemetry.io/otel/metric v1.44.0 // indirect + go.opentelemetry.io/otel/sdk v1.44.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect + go.opentelemetry.io/otel/trace v1.44.0 // indirect go.opentelemetry.io/proto/otlp v1.9.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/arch v0.23.0 // indirect golang.org/x/crypto v0.52.0 // indirect - golang.org/x/net v0.54.0 // indirect - golang.org/x/oauth2 v0.35.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.20.0 // indirect golang.org/x/sys v0.45.0 // indirect golang.org/x/text v0.37.0 // indirect golang.org/x/time v0.15.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 // indirect - google.golang.org/grpc v1.79.3 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/grpc v1.83.1 // indirect google.golang.org/protobuf v1.36.11 // indirect gorm.io/driver/postgres v1.5.11 // indirect ) diff --git a/go.sum b/go.sum index b02d12d..efc9b9e 100644 --- a/go.sum +++ b/go.sum @@ -210,8 +210,8 @@ go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0. go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.65.0/go.mod h1:0Q5ocj6h/+C6KYq8cnl4tDFVd4I1HBdsJ440aeagHos= go.opentelemetry.io/contrib/propagators/b3 v1.40.0 h1:xariChe8OOVF3rNlfzGFgQc61npQmXhzZj/i82mxMfg= go.opentelemetry.io/contrib/propagators/b3 v1.40.0/go.mod h1:72WvbdxbOfXaELEQfonFfOL6osvcVjI7uJEE8C2nkrs= -go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho= -go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.40.0 h1:NOyNnS19BF2SUDApbOKbDtWZ0IK7b8FJ2uAGdIWOGb0= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.40.0/go.mod h1:VL6EgVikRLcJa9ftukrHu/ZkkhFBSo1lzvdBC9CF1ss= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 h1:QKdN8ly8zEMrByybbQgv8cWBcdAarwmIPZ6FThrWXJs= @@ -222,14 +222,16 @@ go.opentelemetry.io/otel/exporters/prometheus v0.62.0 h1:krvC4JMfIOVdEuNPTtQ0ZjC go.opentelemetry.io/otel/exporters/prometheus v0.62.0/go.mod h1:fgOE6FM/swEnsVQCqCnbOfRV4tOnWPg7bVeo4izBuhQ= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.40.0 h1:MzfofMZN8ulNqobCmCAVbqVL5syHw+eB2qPRkCMA/fQ= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.40.0/go.mod h1:E73G9UFtKRXrxhBsHtG00TB5WxX57lpsQzogDkqBTz8= -go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4= -go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI= -go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo= -go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts= -go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA= -go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc= -go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY= -go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA= +go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A= go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= @@ -256,10 +258,10 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w= -golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ= -golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= -golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -298,14 +300,14 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c= golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= -gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= -google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 h1:merA0rdPeUV3YIIfHHcH4qBkiQAc1nfCKSI7lB4cV2M= -google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409/go.mod h1:fl8J1IvUjCilwZzQowmw2b7HQB2eAuYBabMXzWurF+I= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 h1:H86B94AW+VfJWDqFeEbBPhEtHzJwJfTbgE2lZa54ZAQ= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= -google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= -google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y= +google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 62123e5e9410be68abe30c014042d0432a156e66 Mon Sep 17 00:00:00 2001 From: pplulee Date: Wed, 9 Sep 2026 19:01:05 +0800 Subject: [PATCH 4/5] fix: accept legacy MCP initialize handshake without sessions Co-authored-by: Cursor --- internal/httpapi/mcp.go | 47 ++--------------------------------------- 1 file changed, 2 insertions(+), 45 deletions(-) diff --git a/internal/httpapi/mcp.go b/internal/httpapi/mcp.go index 0ea0572..cb376e7 100644 --- a/internal/httpapi/mcp.go +++ b/internal/httpapi/mcp.go @@ -1,10 +1,7 @@ package httpapi import ( - "bytes" "context" - "encoding/json" - "io" "net/http" "github.com/gin-gonic/gin" @@ -14,8 +11,6 @@ import ( "github.com/SideCloudGroup/BetterBillSplitter/internal/model" ) -const mcpProtocolVersion = "2026-07-28" - type partyIDArgs struct { PartyID uint64 `json:"party_id" jsonschema:"派对ID"` } @@ -36,14 +31,14 @@ type updatePaidArgs struct { func (h *Handler) registerMCP(engine *gin.Engine) { server := mcp.NewServer(&mcp.Implementation{Name: "better-bill-splitter", Version: "2.0.0"}, &mcp.ServerOptions{ - Instructions: "BetterBillSplitter 派对分账。使用 PAT Bearer 鉴权。只支持 MCP 协议 2026-07-28,无 session。", + Instructions: "BetterBillSplitter 派对分账。使用 PAT Bearer 鉴权。Streamable HTTP 无状态:兼容 2026-07-28 与带 initialize 的旧协议,不维持 MCP session。", Capabilities: &mcp.ServerCapabilities{}, }) h.addMCPTools(server) inner := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true}) - engine.Any("/mcp", h.PATRequired(), gin.WrapH(mcpProtocolGate{next: inner})) + engine.Any("/mcp", h.PATRequired(), gin.WrapH(inner)) } func (h *Handler) addMCPTools(server *mcp.Server) { @@ -152,41 +147,3 @@ func requireMCPUser(ctx context.Context) (model.User, error) { } return user, nil } - -type mcpProtocolGate struct { - next http.Handler -} - -func (g mcpProtocolGate) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Mcp-Session-Id") != "" { - http.Error(w, "MCP sessions are not supported", http.StatusBadRequest) - return - } - if ver := r.Header.Get("MCP-Protocol-Version"); ver != "" && ver != mcpProtocolVersion { - http.Error(w, "unsupported MCP protocol version", http.StatusBadRequest) - return - } - if r.Method == http.MethodPost && r.Body != nil { - body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20)) - _ = r.Body.Close() - if err != nil { - http.Error(w, "invalid request body", http.StatusBadRequest) - return - } - r.Body = io.NopCloser(bytes.NewReader(body)) - var probe struct { - ID json.RawMessage `json:"id"` - Method string `json:"method"` - } - if json.Unmarshal(body, &probe) == nil && probe.Method == "initialize" { - id := probe.ID - if len(id) == 0 { - id = []byte("null") - } - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(id) + `,"error":{"code":-32022,"message":"Unsupported protocol version; use 2026-07-28"}}`)) - return - } - } - g.next.ServeHTTP(w, r) -} From 365815a48697c875019ff469ec12f35eee8a61a2 Mon Sep 17 00:00:00 2001 From: pplulee Date: Wed, 9 Sep 2026 19:25:55 +0800 Subject: [PATCH 5/5] feat: polish API token management UI Co-authored-by: Cursor --- frontend/src/lib/formatTime.ts | 4 + frontend/src/pages/ProfilePage.tsx | 176 ++++++++++++++++++++++------- 2 files changed, 137 insertions(+), 43 deletions(-) diff --git a/frontend/src/lib/formatTime.ts b/frontend/src/lib/formatTime.ts index d2e7e51..b0584e3 100644 --- a/frontend/src/lib/formatTime.ts +++ b/frontend/src/lib/formatTime.ts @@ -28,3 +28,7 @@ export function formatPartyTime(value?: string | null, timezone?: string | null) } return value; } + +export function formatLocalTime(value?: string | null): string { + return formatPartyTime(value, Intl.DateTimeFormat().resolvedOptions().timeZone); +} diff --git a/frontend/src/pages/ProfilePage.tsx b/frontend/src/pages/ProfilePage.tsx index 4c36401..8d21695 100644 --- a/frontend/src/pages/ProfilePage.tsx +++ b/frontend/src/pages/ProfilePage.tsx @@ -1,9 +1,10 @@ import {type ReactNode, useCallback, useEffect, useState} from 'react'; import {useNavigate} from 'react-router-dom'; -import {Avatar, Button, Card, Col, Flex, Form, Input, message, Modal, QRCode, Row, Tag, Typography,} from 'antd'; +import {Avatar, Button, Card, Col, DatePicker, Flex, Form, Input, message, Modal, QRCode, Row, Space, Table, Tag, Typography,} from 'antd'; import { DeleteOutlined, ApiOutlined, + BookOutlined, KeyOutlined, LockOutlined, MobileOutlined, @@ -15,6 +16,7 @@ import { import {type PublicKeyCredentialCreationOptionsJSON, startRegistration} from '@simplewebauthn/browser'; import {apiDelete, apiFetch, apiJson, apiPostForm, apiPostJson} from '@/api/client'; import {useAuth} from '@/context/AuthContext'; +import {formatLocalTime} from '@/lib/formatTime'; import {PageShell, SurfaceCard} from '@/components/ui'; type Device = { id: number; name?: string }; @@ -113,6 +115,8 @@ export function ProfilePage() { const [tokens, setTokens] = useState([]); const [tokenSaving, setTokenSaving] = useState(false); const [createdToken, setCreatedToken] = useState(null); + const [createTokenOpen, setCreateTokenOpen] = useState(false); + const [docsOpen, setDocsOpen] = useState(false); const load = useCallback(async () => { setLoading(true); @@ -300,12 +304,12 @@ export function ProfilePage() { }); }; - const createToken = async (v: {name: string; expires_at?: string}) => { + const createToken = async (v: {name: string; expires_at?: {endOf: (unit: 'day') => {toISOString: () => string}}}) => { setTokenSaving(true); try { const res = await apiPostJson('/user/tokens', { name: v.name.trim(), - expires_at: v.expires_at ? `${v.expires_at}T23:59:59Z` : '', + expires_at: v.expires_at ? v.expires_at.endOf('day').toISOString() : '', }); const out = (await res.json()) as {ret: number; msg?: string; data?: {token?: string}}; if (out.ret !== 1) { @@ -313,6 +317,7 @@ export function ProfilePage() { return; } tokenForm.resetFields(); + setCreateTokenOpen(false); setCreatedToken(out.data?.token || null); await load(); } finally { @@ -338,6 +343,22 @@ export function ProfilePage() { }; const initial = user?.username?.charAt(0)?.toUpperCase() || '?'; + const origin = typeof window !== 'undefined' ? window.location.origin : ''; + const mcpUrl = `${origin}/mcp`; + const openapiUrl = `${origin}/api/v1/openapi.json`; + const swaggerUrl = `${origin}/api/v1/docs`; + const mcpConfig = JSON.stringify( + { + mcpServers: { + 'better-bill-splitter': { + url: mcpUrl, + headers: {Authorization: 'Bearer bbs_你的令牌'}, + }, + }, + }, + null, + 2, + ); return ( @@ -521,52 +542,121 @@ export function ProfilePage() { API 访问令牌 } - > - - 用于 OpenAPI 与 MCP。明文只显示一次。MCP 地址: - {`${window.location.origin}/mcp`} - ,文档: - - Swagger - - {' / '} - - openapi.json - - 。请求头:Authorization: Bearer bbs_… - -
- - - - - - - - + - -
- {tokens.length === 0 ? ( - 还没有令牌 - ) : ( -
    - {tokens.map((row) => ( -
  • - - {row.name} · {row.token_prefix}…{row.expires_at ? ` · 过期 ${row.expires_at}` : ''} - {row.last_used_at ? ` · 最近使用 ${row.last_used_at}` : ''} - - -
  • - ))} -
- )} + ), + }, + ]} + /> + setCreateTokenOpen(false)} + footer={null} + destroyOnHidden + > +
+ + + + + + + +
+
+ + setDocsOpen(false)} + footer={null} + width={560} + > + + 使用 Bearer PAT 调用 OpenAPI 或 MCP,不要使用浏览器登录 JWT。明文令牌只在创建时显示一次。 + + MCP 地址 + + {mcpUrl} + + 鉴权请求头 + + Authorization: Bearer bbs_… + + + + + + MCP 客户端配置示例 + +
{mcpConfig}
+
+ + 复制配置 + +
+