Skip to content

Add direct email invites with pending rows and flexible-claim join #833

Open

Description

@HMarzban

Parent

#823

What to build

Add direct email invitations (DocumentEmailInvite) supporting instant grants for existing verified accounts, domain-separated dpe_ fragment invitations with flexible-claim mismatch prompts for unregistered recipients, manager-only Pending rows (Resend / Cancel), and the two-stage Add people email-chip composer.

1. Prisma Schema, Worker Signing & MX Validation (apps/hocuspocus.server, packages/email-templates)

  • Add DocumentEmailInvite model (onDelete: Cascade to DocumentMetadata.documentId):
    • id String @id @default(uuid()), documentId String, email String (normalized lowercase), role DocumentRole (all 4 roles full | edit | comment | view), invitedBy String, note String?, expiresAt DateTime (14d TTL), acceptedAt DateTime?, acceptedByUserId String?, revokedAt DateTime?, createdAt DateTime @default(now()).
    • Partial unique index: UNIQUE ("documentId", "email") WHERE "acceptedAt" IS NULL AND "revokedAt" IS NULL.
    • Add FK relation (onDelete: SetNull) from DocumentGrant.emailInviteId to DocumentEmailInvite.id.
  • Shared email validator: Extract validateEmailAddress(email) (using HOUSE_EMAIL_REGEX + resolveMx with bounded 2s timeout) from src/api/email.ts into src/lib/email/validateEmail.ts for reuse across /api/email/validate and email invites.
  • Worker-derived HMAC & email template (packages/email-templates, hocuspocus-worker):
    • Require INVITE_LINK_SECRET (>= 32 chars) in hocuspocus-worker env.schema.ts as well as rest-api.
    • BullMQ EmailJobData passes { inviteId, recipientEmail, documentId, role, note } ONLY — derive dpe_<inviteId>.<base64url(hmacSha256("dpe:" + inviteId, INVITE_LINK_SECRET))> inside buildEmailMessage (never store raw tokens in BullMQ or DLQ payloads). Add a clean invitation template under packages/email-templates/templates/.

2. Backend Endpoints (src/modules/document-sharing/, OpenAPI covered)

  • POST /api/documents/:documentId/invites/email — Owner or Full access.
    • Fail-closed budgets: 20/hr per caller, max 20 emails per request (returning per-address result status), max 50 open pending invites per document. Validates each address with validateEmailAddress and skips inviter's own email.
    • Looks up non-deleted, non-anonymous public.users case-insensitively by email:
      • Account exists: immediately creates/updates DocumentGrant + Supabase document_access_grants mirror (instant-grant); queues direct document link email when notify = true.
      • No account matches: creates DocumentEmailInvite (14d TTL) and requires email delivery carrying /invite#dpe_… (even if optional notify checkbox was unchecked for existing users).
  • POST /api/documents/:documentId/invites/email/:inviteId/resend & DELETE .../invites/email/:inviteId:
    • Resend: 1 / 5 min cooldown per invite; extends expiresAt = now() + 14 days and queues email. Cancel: stamps revokedAt = now().
  • POST /api/documents/invites/preview & redeem (dpe_ extension to #829):
    • preview: returns invited email (display/mismatch check), role, note, emailMismatch: boolean.
    • redeem: accepts { token, confirmMismatch?: boolean }; if caller's email differs from invite.email and !confirmMismatch, returns structured mismatch challenge; once confirmed (confirmMismatch: true or exact match), consumes invite atomically (acceptedAt, acceptedByUserId) inside pg_advisory_xact_lock, grants DocumentGrant + Supabase mirror, and redirects to document.

3. Webapp Two-Stage Compose, Pending Rows & Mismatch Screen (apps/webapp)

  • Two-stage Add people view (SharePopover 'compose' & 'share' BottomSheet 'addPeople'):
    • Overview renders compact button "Add people by email…" opening the dedicated compose view: multi-email chip field (Enter or , commits chip; Backspace pops last chip; invalid format highlighted), Role picker (Full access–Can view), optional message textarea, "Notify people by email" checkbox, Cancel, and sole btn-primary Send invite.
  • Manager-only Pending rows (People with access):
    • Active header count People with access · N counts Owner + active grants only (does NOT inflate N with Pending email invites).
    • Managers see Pending rows inside the scrollable list with Pending badge, role dropdown + Resend invite + Cancel invite (and in-sheet mobile personDetail support without duplicating email (email)). Non-managers never see Pending invites.
  • /invite#dpe_… Email Mismatch PageCard:
    • When signed in with a different email than invited: "This invite was sent to <invitedEmail>, but you're signed in as <currentEmail>."
    • Primary CTA: Switch account (signs out / returns to auth keeping #dpe_ token); Secondary CTA (variant="cancel"): Continue as <currentEmail> (confirmMismatch: true).

Maintainer rulings, 2026-11-23

  • Hybrid rule: instant grant when verified email matches an existing account; Pending dpe_ invite with flexible-claim mismatch disclosure when unregistered.
  • Derive dpe_ HMAC secrets inside hocuspocus-worker at render time (never put raw secrets in BullMQ/DLQ jobs).
  • Keep active header count N strictly to Owner + active grants; hide Pending rows from non-managers.
  • Email mismatch screen uses Switch account as primary CTA and Continue as <email> as secondary.

Acceptance criteria

  • Inviting an existing user email grants immediate access + mirror row; inviting an unregistered email creates a Pending row and delivers a working /invite#dpe_… email (14d TTL).
  • POST /invites/email enforces 20/hr caller cap, 20 emails/batch, 50 pending/doc, 2s MX validation, and Resend extends expiry (1/5m cooldown).
  • Two-stage Add people chip input (Enter/,/Backspace) and Pending row actions (Resend, Cancel, change role) work across Desktop and Mobile BottomSheet; People with access · N excludes Pending rows from N.
  • Opening /invite#dpe_… under another account shows the mismatch warning with Switch account primary and Continue as <current> secondary, redeeming cleanly on choice.
  • Real-Postgres tests + worker template test + webapp typecheck/lint pass.

Blocked by

Agent brief

Type: AFK

Where to start (read from code, not measured, as of 2026-11-23):

  • Server: apps/hocuspocus.server/src/api/email.ts (extract MX helper), src/lib/email/{service,queue}.ts, src/hocuspocus.worker.ts, src/config/env.schema.ts, src/modules/document-sharing/
  • Templates: packages/email-templates/templates/
  • Webapp: Share UI (#827), apps/webapp/src/pages/invite.tsx (#829).

Deploy order: hocuspocus-worker → rest-api → webapp (after Prisma migration)

Verify: Server email invite + mismatch + rate-limit tests, hocuspocus-worker buildEmailMessage test (verifying no token in job JSON), webapp typecheck/lint/build, and end-to-end /invite#dpe_… mismatch & instant-grant check.

Out of scope

Activity

  1. added this to the v2.4.0 milestone on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions