feat(rbac): add multi-use share-link invitations for invite_only mode (#1504)

* feat(rbac): add multi-use share-link invitations for invite_only mode

When the auth.registration_mode toggle flips to invite_only, the public
/auth/register endpoint returns 403 — but until now there was no
channel for unregistered users to actually join a tenant. The existing
invitation table required a registered invitee, so new emails could
not enter the system at all.

This change introduces a share-link model:

- Owner generates a multi-use registration link with a per-tenant role
- Recipient opens the link, registers with their own email, and is
  added to the tenant on the same request
- Token is stored in plaintext (not hashed) so the management UI can
  re-display the URL on demand without a "copy now or revoke" trap.
  Threat model is bounded by 7-day TTL, revocability, and the fact
  that all the link grants is membership in one tenant.
- accepted_count tracks how many users joined through the link so the
  Owner can tell whether a link is fresh or has already been spread

Per-user invitations (registered email -> in-app inbox accept) are
unchanged. Share-link rows use empty invitee_user_id as discriminator;
the partial unique index on (tenant_id, invitee_user_id) was relaxed
to skip empty values so multiple share links can coexist per tenant.

Frontend reuses Login.vue for /register?token=xxx instead of a
parallel page, and adds icon-only revoke / remove actions plus a
distinct "active" status tag for share-link rows.

Migration 000054 adds the token column, the accepted_count column,
and the relaxed pending unique index in a single step.

* feat(auth): update invitation token handling and add rate limiting

- Refactor the invitation token retrieval to use POST instead of GET, enhancing security by preventing the plaintext token from appearing in logs and browser history.
- Update the API endpoint from `/auth/invitations/:token` to `/auth/invitations/lookup` to reflect the new method.
- Introduce a rate limiter for unauthenticated share-link endpoints to mitigate brute-force attacks and abuse, ensuring a maximum of 30 requests per minute per IP.
- Adjust the registration flow to maintain user experience while securing the invitation process.
This commit is contained in:
lyingbug
2026-05-27 19:42:01 +08:00
committed by GitHub
parent 6220667517
commit 3611a8607d
24 changed files with 1687 additions and 47 deletions
@@ -38,6 +38,11 @@ func NewTenantInvitationRepository(db *gorm.DB) interfaces.TenantInvitationRepos
// service layer treats any insert error containing the index name
// (idx_tenant_invitations_unique_pending) as the conflict sentinel —
// see invitationService.Create.
//
// Share-link rows (invitee_user_id == "") skip the pre-check: the
// partial unique index on (tenant_id, invitee_user_id) deliberately
// excludes empty values so multiple share links can coexist on a
// tenant; pre-checking would falsely reject every additional one.
func (r *tenantInvitationRepository) Create(
ctx context.Context,
inv *types.TenantInvitation,
@@ -46,18 +51,20 @@ func (r *tenantInvitationRepository) Create(
inv.Status = types.TenantInvitationStatusPending
}
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var probe types.TenantInvitation
err := tx.
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
inv.TenantID, inv.InviteeUserID, types.TenantInvitationStatusPending).
First(&probe).Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
// fallthrough — clean to insert.
case err != nil:
return err
default:
return ErrPendingInvitationExists
if inv.InviteeUserID != "" {
var probe types.TenantInvitation
err := tx.
Where("tenant_id = ? AND invitee_user_id = ? AND status = ?",
inv.TenantID, inv.InviteeUserID, types.TenantInvitationStatusPending).
First(&probe).Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
// fallthrough — clean to insert.
case err != nil:
return err
default:
return ErrPendingInvitationExists
}
}
return tx.Create(inv).Error
})
@@ -101,6 +108,31 @@ func (r *tenantInvitationRepository) GetPendingByPair(
return &inv, nil
}
// GetActiveByToken returns the share-link row matching token, or
// (nil, nil) if none. Empty token returns (nil, nil) defensively so
// a malformed caller doesn't accidentally match the legacy "" sentinel
// rows that have token=”.
func (r *tenantInvitationRepository) GetActiveByToken(
ctx context.Context,
token string,
) (*types.TenantInvitation, error) {
if token == "" {
return nil, nil
}
var inv types.TenantInvitation
err := r.db.WithContext(ctx).
Where("token = ? AND status = ?",
token, types.TenantInvitationStatusPending).
First(&inv).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
return nil, err
}
return &inv, nil
}
// listQuery centralises the "newest-first" ordering and includeTerminal
// filter so ListByTenant / ListByInvitee stay short.
func (r *tenantInvitationRepository) listQuery(includeTerminal bool) *gorm.DB {
@@ -255,3 +287,27 @@ func (r *tenantInvitationRepository) SweepExpired(
}
return res.RowsAffected, nil
}
// IncrementAcceptedCount bumps accepted_count by 1 for the given row.
// Implemented as a single UPDATE expression so concurrent accepts
// don't race on a read-modify-write loop. We deliberately don't gate
// on status='pending' here: AcceptByToken is the only caller, and
// share-link rows stay pending across accepts — so the gate would
// reject zero rows in steady state but introduce a subtle ordering
// dependency on MarkStatusIfPending for per-user accepts.
func (r *tenantInvitationRepository) IncrementAcceptedCount(
ctx context.Context,
id uint64,
) error {
res := r.db.WithContext(ctx).
Model(&types.TenantInvitation{}).
Where("id = ?", id).
UpdateColumn("accepted_count", gorm.Expr("accepted_count + 1"))
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
@@ -2,10 +2,13 @@ package service
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"os"
"strconv"
"strings"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
@@ -43,6 +46,14 @@ var (
// caller is not the invitee. Owner-driven Revoke is gated at the
// route layer so this error only surfaces on the /me/ paths.
ErrInvitationForbidden = errors.New("only the invitee can accept or decline this invitation")
// ErrInvitationTokenInvalid is returned by LookupByToken /
// AcceptByToken when the supplied plaintext token does not match
// any active share-link row. The handler maps this to 410 Gone.
// We deliberately collapse "unknown" / "expired" / "revoked" into
// a single sentinel so an attacker can't probe which slots used
// to exist.
ErrInvitationTokenInvalid = errors.New("invitation token is invalid or has been revoked")
)
// defaultInvitationTTL is the lifetime of a pending invitation before
@@ -74,10 +85,10 @@ func invitationTTL() time.Duration {
// tenantInvitationService implements interfaces.TenantInvitationService.
type tenantInvitationService struct {
repo interfaces.TenantInvitationRepository
memberSvc interfaces.TenantMemberService
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
now func() time.Time // injection seam for tests
repo interfaces.TenantInvitationRepository
memberSvc interfaces.TenantMemberService
audit interfaces.AuditLogService // optional; nil ⇒ no audit, business ops still succeed
now func() time.Time // injection seam for tests
}
// NewTenantInvitationService wires the dependencies. memberSvc is
@@ -428,3 +439,147 @@ func (s *tenantInvitationService) CountPendingByInvitee(
s.sweep(ctx)
return s.repo.CountPendingByInvitee(ctx, inviteeUserID)
}
// invitationTokenBytes is the raw entropy length for share-link
// tokens before base64url encoding. 32 bytes -> 256 bits, well above
// the 128-bit floor for unguessable opaque tokens.
const invitationTokenBytes = 32
// generateShareLinkToken returns a freshly-randomised plaintext token
// (base64url, no padding) for a new share-link invitation.
func generateShareLinkToken() (string, error) {
buf := make([]byte, invitationTokenBytes)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(buf), nil
}
// CreateShareLink issues a multi-use share-link invitation. The token
// is generated server-side and persisted plaintext on the row so the
// management UI can re-display it on demand. Per-user invitation
// constraints (already-member, duplicate-pending) do NOT apply here:
// share-link rows have no specific invitee, multiple can coexist on
// the same tenant, and consumption is non-destructive (see
// AcceptByToken).
func (s *tenantInvitationService) CreateShareLink(
ctx context.Context,
tenantID uint64,
role types.TenantRole,
invitedBy *string,
message string,
) (*types.TenantInvitation, string, error) {
if !role.IsValid() {
return nil, "", ErrInvalidTenantRole
}
token, err := generateShareLinkToken()
if err != nil {
return nil, "", err
}
now := s.now()
inv := &types.TenantInvitation{
TenantID: tenantID,
InviteeUserID: "", // share-link rows have no specific invitee
Token: token,
InvitedBy: invitedBy,
Role: role,
Status: types.TenantInvitationStatusPending,
Message: message,
ExpiresAt: now.Add(invitationTTL()),
}
if err := s.repo.Create(ctx, inv); err != nil {
return nil, "", err
}
s.emitAudit(ctx, &types.AuditLog{
TenantID: tenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionInvitationSent,
TargetType: "tenant_invitation",
TargetID: strconv.FormatUint(inv.ID, 10),
// TargetUserID intentionally empty — share-link has no invitee yet.
Outcome: types.AuditOutcomeSuccess,
Details: detailsFor(inv.ID, role),
})
return inv, token, nil
}
// LookupByToken resolves a plaintext share-link token to its row.
// Sweeps overdue rows first so an expired link is reflected as
// expired rather than letting the registration page accept it for a
// few extra seconds. Multi-use semantics: a successful lookup does
// not consume or modify the row.
func (s *tenantInvitationService) LookupByToken(
ctx context.Context,
plainToken string,
) (*types.TenantInvitation, error) {
plainToken = strings.TrimSpace(plainToken)
if plainToken == "" {
return nil, ErrInvitationTokenInvalid
}
s.sweep(ctx)
inv, err := s.repo.GetActiveByToken(ctx, plainToken)
if err != nil {
return nil, err
}
if inv == nil {
return nil, ErrInvitationTokenInvalid
}
if inv.IsExpired(s.now()) {
return nil, ErrInvitationTokenInvalid
}
return inv, nil
}
// AcceptByToken adds newUserID to the share-link's tenant + role.
// Unlike Accept, the invitation row itself is NOT mutated — share-link
// rows stay pending across uses. Idempotent: an existing membership
// is returned untouched (callers shouldn't see role downgrade just
// because they clicked the same link twice from different devices).
func (s *tenantInvitationService) AcceptByToken(
ctx context.Context,
plainToken string,
newUserID string,
) (*types.TenantMember, error) {
if newUserID == "" {
return nil, errors.New("newUserID is required")
}
inv, err := s.LookupByToken(ctx, plainToken)
if err != nil {
return nil, err
}
member, err := s.memberSvc.AddMember(ctx, newUserID, inv.TenantID, inv.Role, inv.InvitedBy)
if err != nil {
if errors.Is(err, ErrMembershipAlreadyExists) {
existing, getErr := s.memberSvc.GetMembership(ctx, newUserID, inv.TenantID)
if getErr == nil && existing != nil {
return existing, nil
}
}
logger.Errorf(ctx,
"share-link %d accept failed for user %s: %v",
inv.ID, newUserID, err)
return nil, err
}
// Bump usage counter so the management UI can show "N 人已加入".
// Best-effort: a failure here doesn't undo the membership the user
// just earned — log and move on. The counter is for display only;
// audit log + tenant_members rows are the authoritative trail.
if incErr := s.repo.IncrementAcceptedCount(ctx, inv.ID); incErr != nil {
logger.Warnf(ctx,
"share-link %d accepted_count bump failed (membership still created): %v",
inv.ID, incErr)
}
s.emitAudit(ctx, &types.AuditLog{
TenantID: inv.TenantID,
ActorUserID: auditActor(ctx),
ActorRole: auditActorRole(ctx),
Action: types.AuditActionInvitationAccepted,
TargetType: "tenant_invitation",
TargetID: strconv.FormatUint(inv.ID, 10),
TargetUserID: newUserID,
Outcome: types.AuditOutcomeSuccess,
Details: detailsFor(inv.ID, inv.Role),
})
return member, nil
}
@@ -66,6 +66,22 @@ func (r *fakeInvitationRepo) GetPendingByPair(
return nil, nil
}
func (r *fakeInvitationRepo) GetActiveByToken(
ctx context.Context, token string,
) (*types.TenantInvitation, error) {
if token == "" {
return nil, nil
}
for _, e := range r.rows {
if e.Token == token &&
e.Status == types.TenantInvitationStatusPending {
cp := *e
return &cp, nil
}
}
return nil, nil
}
func (r *fakeInvitationRepo) filteredTenantRows(
tenantID uint64, includeTerminal bool,
) []*types.TenantInvitation {
@@ -179,6 +195,19 @@ func (r *fakeInvitationRepo) SweepExpired(
return n, nil
}
func (r *fakeInvitationRepo) IncrementAcceptedCount(
ctx context.Context, id uint64,
) error {
for _, e := range r.rows {
if e.ID == id {
e.AcceptedCount++
e.UpdatedAt = time.Now()
return nil
}
}
return gormErrRecordNotFound
}
var _ interfaces.TenantInvitationRepository = (*fakeInvitationRepo)(nil)
// newInvitationSvc returns a service wired against in-memory fakes for
@@ -395,3 +424,131 @@ func TestInvitationService_CountPending(t *testing.T) {
t.Fatalf("want 1 pending after decline, got %d", n)
}
}
// --- share-link tests ---------------------------------------------------
func TestInvitationService_CreateShareLink_PersistsToken(t *testing.T) {
svc, repo, _ := newInvitationSvc()
inv, plain, err := svc.CreateShareLink(
context.Background(), 1, types.TenantRoleContributor, nil, "")
if err != nil {
t.Fatalf("create-share-link: %v", err)
}
if plain == "" {
t.Fatalf("plain token must be returned for the URL")
}
row, _ := repo.GetByID(context.Background(), inv.ID)
if row == nil {
t.Fatalf("row missing")
}
if row.Token != plain {
t.Fatalf("DB must store plaintext token (multi-use, short-lived), got %q vs %q", row.Token, plain)
}
if row.InviteeUserID != "" {
t.Fatalf("share-link rows must have empty invitee_user_id, got %q", row.InviteeUserID)
}
if row.Status != types.TenantInvitationStatusPending {
t.Fatalf("status must be pending, got %s", row.Status)
}
}
func TestInvitationService_CreateShareLink_RejectsInvalidRole(t *testing.T) {
svc, _, _ := newInvitationSvc()
_, _, err := svc.CreateShareLink(
context.Background(), 1, types.TenantRole("magician"), nil, "")
if !errors.Is(err, ErrInvalidTenantRole) {
t.Fatalf("want ErrInvalidTenantRole, got %v", err)
}
}
func TestInvitationService_LookupByToken_RejectsUnknownToken(t *testing.T) {
svc, _, _ := newInvitationSvc()
if _, err := svc.LookupByToken(context.Background(), "nonexistent"); !errors.Is(err, ErrInvitationTokenInvalid) {
t.Fatalf("want ErrInvitationTokenInvalid, got %v", err)
}
}
func TestInvitationService_LookupByToken_RejectsExpired(t *testing.T) {
svc, repo, _ := newInvitationSvc()
_, plain, err := svc.CreateShareLink(context.Background(), 1, types.TenantRoleViewer, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
for _, r := range repo.rows {
r.ExpiresAt = time.Now().Add(-time.Hour)
}
if _, err := svc.LookupByToken(context.Background(), plain); !errors.Is(err, ErrInvitationTokenInvalid) {
t.Fatalf("expired token must reject, got %v", err)
}
}
func TestInvitationService_AcceptByToken_HappyPath(t *testing.T) {
svc, repo, memberSvc := newInvitationSvc()
ctx := context.Background()
_, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleAdmin, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
mb, err := svc.AcceptByToken(ctx, plain, "u-alice")
if err != nil {
t.Fatalf("accept-by-token: %v", err)
}
if mb == nil || mb.UserID != "u-alice" || mb.Role != types.TenantRoleAdmin {
t.Fatalf("unexpected membership: %+v", mb)
}
if got, _ := memberSvc.GetMembership(ctx, "u-alice", 1); got == nil {
t.Fatalf("membership row missing")
}
// Multi-use: row stays pending.
rows, _ := repo.ListByTenant(ctx, 1, true)
if len(rows) == 0 || rows[0].Status != types.TenantInvitationStatusPending {
t.Fatalf("share-link row must remain pending after accept, got %+v", rows)
}
}
func TestInvitationService_AcceptByToken_AllowsMultipleUsers(t *testing.T) {
svc, _, memberSvc := newInvitationSvc()
ctx := context.Background()
_, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleViewer, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
if _, err := svc.AcceptByToken(ctx, plain, "u-alice"); err != nil {
t.Fatalf("accept alice: %v", err)
}
if _, err := svc.AcceptByToken(ctx, plain, "u-bob"); err != nil {
t.Fatalf("accept bob: %v", err)
}
a, _ := memberSvc.GetMembership(ctx, "u-alice", 1)
b, _ := memberSvc.GetMembership(ctx, "u-bob", 1)
if a == nil || b == nil {
t.Fatalf("both users should have membership: alice=%v bob=%v", a, b)
}
}
func TestInvitationService_AcceptByToken_RevokedTokenRejected(t *testing.T) {
svc, _, _ := newInvitationSvc()
ctx := context.Background()
inv, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleViewer, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
if err := svc.Revoke(ctx, inv.ID); err != nil {
t.Fatalf("revoke: %v", err)
}
if _, err := svc.AcceptByToken(ctx, plain, "u-alice"); !errors.Is(err, ErrInvitationTokenInvalid) {
t.Fatalf("revoked token must reject, got %v", err)
}
}
func TestInvitationService_AcceptByToken_RequiresUserID(t *testing.T) {
svc, _, _ := newInvitationSvc()
ctx := context.Background()
_, plain, err := svc.CreateShareLink(ctx, 1, types.TenantRoleViewer, nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
if _, err := svc.AcceptByToken(ctx, plain, ""); err == nil {
t.Fatalf("empty user id must be rejected")
}
}
+6
View File
@@ -33,6 +33,12 @@ type Config struct {
PromptTemplates *PromptTemplatesConfig `yaml:"prompt_templates" json:"prompt_templates"`
IM *IMConfig `yaml:"im" json:"im"`
Agent *AgentConfig `yaml:"agent" json:"agent"`
// FrontendBaseURL is the externally-visible origin of the SPA, used
// to compose absolute share-link URLs. Empty falls back to a host-
// relative URL ("/register?token=…") which the SPA then resolves
// against window.location.origin — fine for typical single-origin
// deployments. Sourced from FRONTEND_BASE_URL env at startup.
FrontendBaseURL string `yaml:"frontend_base_url" json:"frontend_base_url"`
}
// AgentConfig represents the global agent settings.
+7
View File
@@ -27,6 +27,11 @@ type AuthHandler struct {
tenantService interfaces.TenantService
configInfo *config.Config
systemSettingSvc interfaces.SystemSettingService
// invitationSvc is required for the share-link registration path
// (POST /auth/register-by-invite). When nil — e.g. legacy test
// fixtures — the share-link endpoints respond 503 rather than
// blocking the rest of the auth surface.
invitationSvc interfaces.TenantInvitationService
}
// NewAuthHandler creates a new auth handler instance with the provided services
@@ -44,6 +49,7 @@ type AuthHandler struct {
func NewAuthHandler(configInfo *config.Config,
userService interfaces.UserService, tenantService interfaces.TenantService,
systemSettingSvc interfaces.SystemSettingService,
invitationSvc interfaces.TenantInvitationService,
) *AuthHandler {
// Boot-time guard: a nil-or-empty Auth section silently disables the
// invite_only gate (see Register below). Emit a loud one-shot log
@@ -60,6 +66,7 @@ func NewAuthHandler(configInfo *config.Config,
userService: userService,
tenantService: tenantService,
systemSettingSvc: systemSettingSvc,
invitationSvc: invitationSvc,
}
}
+216
View File
@@ -0,0 +1,216 @@
package handler
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// registerByInviteRequest is the body for /auth/register-by-invite.
//
// Email is collected from the invitee themselves: share-link rows have
// no specific invitee, so we cannot pre-bind any address. The token
// IS the authorisation; the email is whatever account the invitee
// wants to register.
type registerByInviteRequest struct {
Token string `json:"token" binding:"required"`
Email string `json:"email" binding:"required,email"`
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required,min=6"`
}
// invitationLookupResponse is the public projection of a share-link
// row returned by /auth/invitations/lookup. Kept narrow on purpose:
// just enough for the registration page to render context ("X invited
// you to Y") without exposing inviter audit fields.
type invitationLookupResponse struct {
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name,omitempty"`
Role types.TenantRole `json:"role"`
ExpiresAt string `json:"expires_at"`
}
// invitationLookupRequest carries the token in the request body
// instead of the URL path: GET /auth/invitations/:token would have
// landed the plaintext token in access logs, browser history, and
// tracing spans. POST + body keeps the token out of those surfaces
// at the cost of "this endpoint reads, why is it POST" — worth it
// because the token is the sole authorisation for registration.
type invitationLookupRequest struct {
Token string `json:"token" binding:"required"`
}
// LookupInvitationByToken godoc
// @Summary 解析共享邀请链接 token
// @Description 根据邀请链接中的 token 返回邀请上下文(租户名 / 角色 / 过期时间),
// @Description 供注册页展示。无认证;token 无效或被撤销返回 410。
// @Description 使用 POST + body 而非 GET + path,避免 token 落入访问日志 / 浏览器历史 / tracing。
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body invitationLookupRequest true "邀请 token"
// @Success 200 {object} invitationLookupResponse
// @Failure 410 {object} errors.AppError "链接无效或已撤销"
// @Router /auth/invitations/lookup [post]
func (h *AuthHandler) LookupInvitationByToken(c *gin.Context) {
ctx := c.Request.Context()
if h.invitationSvc == nil {
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
return
}
var req invitationLookupRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("token is required").WithDetails(err.Error()))
return
}
token := strings.TrimSpace(req.Token)
if token == "" {
c.Error(apperrors.NewValidationError("token is required"))
return
}
inv, err := h.invitationSvc.LookupByToken(ctx, token)
if err != nil {
// Collapse "unknown / expired / revoked" into 410 to avoid
// leaking which slot a stolen token used to occupy.
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is invalid or has been revoked",
HTTPCode: http.StatusGone,
})
return
}
resp := invitationLookupResponse{
TenantID: inv.TenantID,
Role: inv.Role,
ExpiresAt: inv.ExpiresAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
}
if tenant, terr := h.tenantService.GetTenantByID(ctx, inv.TenantID); terr == nil && tenant != nil {
resp.TenantName = tenant.Name
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": resp,
})
}
// RegisterByInvite godoc
// @Summary 使用共享链接注册
// @Description 通过 Owner 生成的共享邀请链接 token 完成注册,绕过 invite_only 模式拦截。
// @Description 注册者自填邮箱(与 token 不绑定);注册成功后自动加入对应租户。
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body registerByInviteRequest true "邀请注册请求"
// @Success 201 {object} types.LoginResponse
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 409 {object} errors.AppError "邮箱已注册"
// @Failure 410 {object} errors.AppError "链接无效或已撤销"
// @Router /auth/register-by-invite [post]
//
// RegisterByInvite is intentionally NOT subject to the invite_only gate:
// the gate suppresses public registration, while this endpoint requires
// a valid token issued by an Owner. The token IS the authorisation.
func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
ctx := c.Request.Context()
if h.invitationSvc == nil {
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
return
}
var req registerByInviteRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("Invalid registration parameters").WithDetails(err.Error()))
return
}
req.Token = strings.TrimSpace(req.Token)
req.Email = strings.TrimSpace(strings.ToLower(req.Email))
req.Username = strings.TrimSpace(req.Username)
// Password is intentionally NOT sanitized: SanitizeForLog strips
// \n, \r, \t and control chars to make a string safe to write into
// a log line — applying it to a real password would silently
// rewrite the stored credential and lock the user out. Passwords
// must never be logged, so they don't need that defence here.
if req.Token == "" || req.Email == "" || req.Username == "" || req.Password == "" {
c.Error(apperrors.NewValidationError("token, email, username and password are required"))
return
}
inv, err := h.invitationSvc.LookupByToken(ctx, req.Token)
if err != nil {
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is invalid or has been revoked",
HTTPCode: http.StatusGone,
})
return
}
// If the email already has an account we shouldn't quietly succeed
// here: register would fail with a duplicate-email error, but the
// share-link flow is "create new account + join tenant", not "join
// my existing account". Surface 409 so the SPA can prompt them to
// log in instead, and the invitation can be applied to their
// existing account via /me/invitations once we wire that path.
if existing, _ := h.userService.GetUserByEmail(ctx, req.Email); existing != nil {
c.Error(apperrors.NewConflictError(
"this email already has an account; please log in to join the workspace"))
return
}
user, err := h.userService.Register(ctx, &types.RegisterRequest{
Username: req.Username,
Email: req.Email,
Password: req.Password,
})
if err != nil {
logger.Errorf(ctx, "register-by-invite: user create failed for %s: %v",
secutils.SanitizeForLog(req.Email), err)
c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
if _, err := h.invitationSvc.AcceptByToken(ctx, req.Token, user.ID); err != nil {
// Race: link was revoked between Lookup and Accept. The user
// account is created either way — they can still log in.
logger.Errorf(ctx, "register-by-invite: accept failed for user %s: %v", user.ID, err)
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is no longer valid; please log in to your new account",
HTTPCode: http.StatusGone,
})
return
}
accessToken, refreshToken, err := h.userService.GenerateTokens(ctx, user)
if err != nil {
logger.Errorf(ctx, "register-by-invite: token generation failed for user %s: %v", user.ID, err)
c.Error(apperrors.NewInternalServerError("token generation failed").WithDetails(err.Error()))
return
}
tenant, _ := h.tenantService.GetTenantByID(ctx, inv.TenantID)
c.JSON(http.StatusCreated, &types.LoginResponse{
Success: true,
Message: "Registration successful",
User: user,
ActiveTenant: tenant,
Memberships: []types.Membership{{
TenantID: inv.TenantID,
TenantName: tenantNameOrEmpty(tenant),
Role: inv.Role,
}},
Token: accessToken,
RefreshToken: refreshToken,
})
}
@@ -89,7 +89,7 @@ func TestRegister_InviteOnlyRejects(t *testing.T) {
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeInviteOnly},
}, us, nil, nil)
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusForbidden {
@@ -114,7 +114,7 @@ func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeSelfServe},
}, us, nil, nil)
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
@@ -135,7 +135,7 @@ func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil)
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
+36 -2
View File
@@ -10,6 +10,7 @@ import (
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -26,20 +27,24 @@ type TenantInvitationHandler struct {
invitationService interfaces.TenantInvitationService
userService interfaces.UserService
tenantService interfaces.TenantService
configInfo *config.Config
}
// NewTenantInvitationHandler wires the dependencies. tenantService is
// used to hydrate tenant names in the inbox view so the invitee sees
// "join Foo Workspace" instead of a raw numeric tenant id.
// "join Foo Workspace" instead of a raw numeric tenant id. configInfo
// supplies FrontendBaseURL for share-link URL composition.
func NewTenantInvitationHandler(
invitationService interfaces.TenantInvitationService,
userService interfaces.UserService,
tenantService interfaces.TenantService,
configInfo *config.Config,
) *TenantInvitationHandler {
return &TenantInvitationHandler{
invitationService: invitationService,
userService: userService,
tenantService: tenantService,
configInfo: configInfo,
}
}
@@ -73,6 +78,11 @@ func parseInvitationIDFromPath(c *gin.Context) (uint64, bool) {
// name are filled best-effort: a missing row degrades to the bare id
// rather than dropping the response. usersByID and tenantsByID let the
// caller batch the lookups when projecting a list.
//
// Share-link rows (InviteeUserID == "") get the IsShareLink flag set
// so the SPA can render them differently. invite_url is NOT populated
// here — projectInvitationWithLink layers it on for the management
// view that needs the copy-link affordance.
func projectInvitation(
inv *types.TenantInvitation,
usersByID map[string]*types.User,
@@ -89,6 +99,8 @@ func projectInvitation(
ExpiresAt: inv.ExpiresAt,
RespondedAt: inv.RespondedAt,
CreatedAt: inv.CreatedAt,
IsShareLink: inv.InviteeUserID == "",
AcceptedCount: inv.AcceptedCount,
}
if u, ok := usersByID[inv.InviteeUserID]; ok && u != nil {
resp.InviteeEmail = u.Email
@@ -106,6 +118,26 @@ func projectInvitation(
return resp
}
// projectInvitationWithLink layers invite_url on top of projectInvitation
// for share-link rows that are still pending. The Owner-facing list and
// the create response go through here so a "copy link" button can sit
// on every active row — Owners can dispatch the link on demand without
// the "copy now or revoke" pressure.
//
// The /me/invitations inbox path does NOT use this helper: per-user
// invitees don't have a token to copy.
func (h *TenantInvitationHandler) projectInvitationWithLink(
inv *types.TenantInvitation,
usersByID map[string]*types.User,
tenantsByID map[uint64]*types.Tenant,
) types.TenantInvitationResponse {
resp := projectInvitation(inv, usersByID, tenantsByID)
if inv.Status == types.TenantInvitationStatusPending && inv.Token != "" {
resp.InviteURL = buildInviteRegisterURL(h.configInfo, inv.Token)
}
return resp
}
// hydrateUsers batches GetUsersByIDs over the (invitee, inviter) pairs.
// Best-effort: a transient lookup failure logs and returns an empty
// map so the projection falls back to ids.
@@ -191,7 +223,9 @@ func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
for _, inv := range rows {
// Within the tenant view we don't bother hydrating tenant name
// (the caller already knows the tenant). Pass an empty map.
resp = append(resp, projectInvitation(inv, usersByID, nil))
// Use ...WithLink so management UI can re-display invite_url
// for pending share-link rows (re-copy without revoking).
resp = append(resp, h.projectInvitationWithLink(inv, usersByID, nil))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
+105
View File
@@ -0,0 +1,105 @@
package handler
import (
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
)
// frontendBaseURLFor returns the externally-visible SPA origin used to
// compose absolute share-link URLs. Lookup order:
// 1. config.FrontendBaseURL (set in YAML or via ${FRONTEND_BASE_URL})
// 2. FRONTEND_BASE_URL env at request time (so an operator can roll
// the value out without restarting the server)
// 3. empty — handler emits a host-relative URL ("/register?token=…")
// and the SPA resolves it against the current origin.
//
// Trailing slashes are stripped so callers can append "/register?…"
// cleanly.
func frontendBaseURLFor(cfg *config.Config) string {
candidate := ""
if cfg != nil {
candidate = strings.TrimSpace(cfg.FrontendBaseURL)
}
if candidate == "" {
candidate = strings.TrimSpace(os.Getenv("FRONTEND_BASE_URL"))
}
return strings.TrimRight(candidate, "/")
}
// buildInviteRegisterURL composes the registration URL Owners hand
// to invitees. Plaintext token is URL-safe by construction (base64url)
// so no extra escaping is required.
func buildInviteRegisterURL(cfg *config.Config, plainToken string) string {
if plainToken == "" {
return ""
}
return frontendBaseURLFor(cfg) + "/register?token=" + plainToken
}
// createInviteLinkRequest is the body for POST /tenants/:id/invite-links.
// Only role + optional message — share-link rows have no specific
// invitee, so the Owner just picks "what role does the holder get".
type createInviteLinkRequest struct {
Role types.TenantRole `json:"role" binding:"required"`
Message string `json:"message"`
}
// CreateInviteLink godoc
// @Summary 生成共享邀请链接
// @Description 生成一条多次使用的共享邀请链接:谁拿到链接谁就能注册并加入当前租户。
// @Description 链接持续有效,直到过期或被撤销。
// @Tags 租户邀请
// @Accept json
// @Produce json
// @Param id path string true "租户 ID"
// @Param request body createInviteLinkRequest true "共享链接配置"
// @Success 201 {object} map[string]interface{}
// @Security Bearer
// @Router /tenants/{id}/invite-links [post]
func (h *TenantInvitationHandler) CreateInviteLink(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
var req createInviteLinkRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("invalid request body").WithDetails(err.Error()))
return
}
if !req.Role.IsValid() {
c.Error(apperrors.NewValidationError("role must be one of owner/admin/contributor/viewer"))
return
}
caller, _ := types.UserIDFromContext(ctx)
var invitedBy *string
if caller != "" && !types.IsSyntheticUserID(caller) {
invitedBy = &caller
}
inv, _, err := h.invitationService.CreateShareLink(ctx, tenantID, req.Role, invitedBy, req.Message)
if err != nil {
logger.Errorf(ctx, "CreateShareLink failed: tenant=%d err=%v", tenantID, err)
c.Error(apperrors.NewInternalServerError("failed to create share link").WithDetails(err.Error()))
return
}
usersByID := map[string]*types.User{}
if invitedBy != nil {
if iu, lookupErr := h.userService.GetUserByID(ctx, *invitedBy); lookupErr == nil && iu != nil {
usersByID[iu.ID] = iu
}
}
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": h.projectInvitationWithLink(inv, usersByID, nil),
})
}
@@ -0,0 +1,135 @@
package middleware
import (
"net/http"
"sync"
"time"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/gin-gonic/gin"
)
// auth_public_ratelimit.go — sliding-window IP rate limiter for the
// unauthenticated share-link endpoints (/auth/invitations/lookup and
// /auth/register-by-invite). Both surfaces accept a plaintext token
// from the request and either reveal tenant context (lookup) or
// create an account (register-by-invite); without a limiter an
// attacker can brute-force token guesses and hammer registration.
//
// The token is 256-bit so guessing the space is infeasible regardless,
// but the limiter still narrows the abuse window for partial-token
// leaks (e.g. via referrer / clipboard managers / accidental commits)
// and bounds the noise this endpoint can add to the user-create path.
//
// Local in-memory only — fine for typical deployments since both
// endpoints handle low absolute volumes; if/when WeKnora horizontally
// scales the auth surface, swap to the Redis-backed limiter in
// internal/im/ratelimit.go (kept lowercase / package-private today).
// publicAuthRateLimitWindow is the rolling window length per IP.
const publicAuthRateLimitWindow = 60 * time.Second
// publicAuthRateLimitMax is the request budget per IP per window for
// each endpoint instance. 30/min comfortably covers a real user
// retrying a failed registration while clamping enumeration
// throughput to ~half a request per second.
const publicAuthRateLimitMax = 30
// publicAuthRateLimitCleanupInterval bounds map growth from one-off
// IPs that never come back.
const publicAuthRateLimitCleanupInterval = 2 * time.Minute
type ipBucket struct {
mu sync.Mutex
timestamps []time.Time
}
type ipRateLimiter struct {
window time.Duration
max int
buckets sync.Map // string (IP) -> *ipBucket
}
func newIPRateLimiter(window time.Duration, max int) *ipRateLimiter {
l := &ipRateLimiter{window: window, max: max}
go l.cleanupLoop()
return l
}
// allow returns true if the IP is within budget for the current
// window. Empty IP (proxy stripped X-Forwarded-For) is treated as a
// shared bucket — slightly over-restrictive vs. dropping the limit
// entirely, which would let a misconfigured proxy bypass the gate.
func (l *ipRateLimiter) allow(ip string) bool {
if ip == "" {
ip = "_unknown_"
}
now := time.Now()
cutoff := now.Add(-l.window)
val, _ := l.buckets.LoadOrStore(ip, &ipBucket{})
b := val.(*ipBucket)
b.mu.Lock()
defer b.mu.Unlock()
kept := b.timestamps[:0]
for _, t := range b.timestamps {
if t.After(cutoff) {
kept = append(kept, t)
}
}
b.timestamps = kept
if len(b.timestamps) >= l.max {
return false
}
b.timestamps = append(b.timestamps, now)
return true
}
func (l *ipRateLimiter) cleanupLoop() {
t := time.NewTicker(publicAuthRateLimitCleanupInterval)
defer t.Stop()
for range t.C {
cutoff := time.Now().Add(-l.window)
l.buckets.Range(func(k, v any) bool {
b := v.(*ipBucket)
b.mu.Lock()
drop := len(b.timestamps) == 0 ||
b.timestamps[len(b.timestamps)-1].Before(cutoff)
b.mu.Unlock()
if drop {
l.buckets.Delete(k)
}
return true
})
}
}
// publicAuthLimiter — package-singleton so each route registration
// shares a single bucket map per process. Each route still gets its
// own Gin handler that calls into this same limiter; per-route
// isolation isn't important here (real users don't hit both
// endpoints in the same window) but the shared state makes total
// budget per IP intuitive: 30/min across all share-link surfaces.
var publicAuthLimiter = newIPRateLimiter(
publicAuthRateLimitWindow, publicAuthRateLimitMax)
// PublicAuthRateLimit returns a Gin middleware that rate-limits the
// unauthenticated share-link endpoints by client IP. 429 is mapped
// through the project's AppError type so it flows through the same
// error middleware as the rest of the auth surface.
func PublicAuthRateLimit() gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
if !publicAuthLimiter.allow(ip) {
c.Error(&apperrors.AppError{
Code: apperrors.ErrTooManyRequests,
Message: "too many requests; please retry shortly",
HTTPCode: http.StatusTooManyRequests,
})
c.Abort()
return
}
c.Next()
}
}
+13
View File
@@ -565,6 +565,11 @@ func RegisterTenantRoutes(
tenantByID.GET("/invitations", g.Viewer(), invitationHandler.ListTenantInvitations)
tenantByID.POST("/invitations", g.Owner(), invitationHandler.CreateInvitation)
tenantByID.DELETE("/invitations/:inv_id", g.Owner(), invitationHandler.RevokeInvitation)
// Share-link create lives under /invite-links so the URL
// reads as "create a link" rather than another flavour
// of /invitations; the underlying row still lives in the
// tenant_invitations table and shows up in the GET above.
tenantByID.POST("/invite-links", g.Owner(), invitationHandler.CreateInviteLink)
}
// Audit log feed (PR 6 of #1303). Admin+ so denied-action
@@ -650,6 +655,14 @@ func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.T
// RegisterAuthRoutes registers authentication routes
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
r.POST("/auth/register", handler.Register)
// Share-link surfaces are unauthenticated and accept a plaintext
// token from the caller; rate-limit by IP to bound brute-force /
// enumeration / abuse traffic. Limiter is shared across both
// endpoints (see middleware/auth_public_ratelimit.go) so total
// budget per IP is intuitive.
publicAuthRL := middleware.PublicAuthRateLimit()
r.POST("/auth/register-by-invite", publicAuthRL, handler.RegisterByInvite)
r.POST("/auth/invitations/lookup", publicAuthRL, handler.LookupInvitationByToken)
r.POST("/auth/login", handler.Login)
r.POST("/auth/auto-setup", handler.AutoSetup)
r.GET("/auth/config", handler.GetAuthConfig)
@@ -26,6 +26,14 @@ type TenantInvitationRepository interface {
// they hit the unique index.
GetPendingByPair(ctx context.Context, tenantID uint64, inviteeUserID string) (*types.TenantInvitation, error)
// GetActiveByToken looks up the share-link row matching the
// supplied plaintext token. Returns (nil, nil) if no row matches
// or the row is no longer pending. "Active" rather than "pending
// for a single user" because share-link rows are multi-use:
// AcceptByToken does NOT consume them, only Revoke or expiry
// removes them from circulation.
GetActiveByToken(ctx context.Context, token string) (*types.TenantInvitation, error)
// ListByTenant returns invitations for the tenant ordered by
// id DESC (newest first). includeTerminal controls whether
// non-pending rows (accepted/declined/revoked/expired) are
@@ -71,4 +79,10 @@ type TenantInvitationRepository interface {
// events (we don't — the volume could be high and the audit-log
// table already records the original invitation_sent rows).
SweepExpired(ctx context.Context, now time.Time) (int64, error)
// IncrementAcceptedCount atomically bumps accepted_count by 1.
// Used by AcceptByToken so the management UI can show "N 人已通过
// 此链接加入" for share-link rows. Per-user invitations also call
// this on accept; the count just caps at 1 there.
IncrementAcceptedCount(ctx context.Context, id uint64) error
}
@@ -64,4 +64,34 @@ type TenantInvitationService interface {
// after running the lazy sweep, so the inbox badge can poll a
// lightweight endpoint without paginating the full list.
CountPendingByInvitee(ctx context.Context, inviteeUserID string) (int64, error)
// CreateShareLink generates a multi-use share-link invitation for
// the tenant. The plaintext token is persisted on the row and also
// returned for the handler to compose the registration URL — the
// token stays available via list/get for as long as the row is
// pending so Owners can re-share without "copy now or lose it"
// pressure. Multiple share-link rows can coexist on the same
// tenant (different roles, or just multiple campaigns).
CreateShareLink(
ctx context.Context,
tenantID uint64,
role types.TenantRole,
invitedBy *string,
message string,
) (inv *types.TenantInvitation, plainToken string, err error)
// LookupByToken resolves a plaintext token to its active share-link
// row. Returns ErrInvitationTokenInvalid for unknown / expired /
// revoked tokens to avoid leaking which tokens used to exist. The
// row is NOT consumed; the same token can be looked up arbitrarily
// many times until it expires or the Owner revokes it.
LookupByToken(ctx context.Context, plainToken string) (*types.TenantInvitation, error)
// AcceptByToken creates a tenant_members row binding newUserID to
// the share-link's tenant + role. Unlike Accept, this does NOT flip
// the invitation row into a terminal state — share-link rows stay
// pending so subsequent invitees can also register through the
// same link. Idempotent: if the user already has membership, the
// existing row is returned.
AcceptByToken(ctx context.Context, plainToken string, newUserID string) (*types.TenantMember, error)
}
+36 -3
View File
@@ -64,9 +64,22 @@ type TenantInvitation struct {
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
// TenantID references tenants.id.
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
// InviteeUserID references users.id (always a registered user; the
// handler resolves the email to a User row before insertion).
InviteeUserID string `json:"invitee_user_id" gorm:"type:varchar(36);not null;index"`
// InviteeUserID references users.id when this row represents a
// per-user invitation (Owner picked a registered email). For
// share-link rows the field is the empty-string sentinel — there
// is no specific invitee yet; whoever holds the link can register.
// The (tenant_id, invitee_user_id) partial unique index in
// migration 000054 was relaxed to skip empty values so multiple
// share-link rows can coexist per tenant.
InviteeUserID string `json:"invitee_user_id" gorm:"type:varchar(36);not null;default:'';index"`
// Token holds the plaintext registration token for share-link
// rows. Empty for per-user invitations (those use the in-app
// inbox, not a URL). Stored plaintext so the management UI can
// re-display the link on demand — the threat model is bounded by
// short TTL, revocability, and the fact that all the link grants
// is membership in this one tenant. Excluded from JSON to keep
// the wire shape small; handlers emit invite_url instead.
Token string `json:"-" gorm:"column:token;type:varchar(64);not null;default:'';index"`
// InvitedBy records the user id that issued this invitation. NULL
// for invitations created via service-internal / synthetic actors
// (mirrors the same treatment TenantMember.InvitedBy gets).
@@ -87,6 +100,13 @@ type TenantInvitation struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
// AcceptedCount counts how many users have completed registration
// through this invitation. Per-user invitations cap out at 1 (and
// the row flips to accepted in the same step). Share-link rows can
// accumulate many — this is what the management UI surfaces as the
// "已加入 N 人" caption so Owners can see whether a link is fresh
// or has already been used widely.
AcceptedCount int `json:"accepted_count" gorm:"column:accepted_count;not null;default:0"`
}
// TableName binds TenantInvitation to the tenant_invitations table.
@@ -122,4 +142,17 @@ type TenantInvitationResponse struct {
ExpiresAt time.Time `json:"expires_at"`
RespondedAt *time.Time `json:"responded_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
// InviteURL is set on share-link rows that are still pending.
// Composed by the handler from FrontendBaseURL + the row's plaintext
// token, so the management UI can render a "copy link" button per
// row without ever exposing the raw token through the JSON wire.
InviteURL string `json:"invite_url,omitempty"`
// IsShareLink is a convenience flag so the SPA doesn't have to
// special-case "invitee_user_id == ''" everywhere when distinguishing
// share-link rows from per-user invitations.
IsShareLink bool `json:"is_share_link,omitempty"`
// AcceptedCount mirrors TenantInvitation.AcceptedCount. Surfaced
// for share-link rows so the management UI can show "N 人已通过此
// 链接加入"; informational only for per-user invitations.
AcceptedCount int `json:"accepted_count,omitempty"`
}